1
0
mirror of https://github.com/troisjs/trois.git synced 2024-11-24 12:22:03 +08:00
trois/src/geometries/Geometry.ts

88 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-04-19 04:25:24 +08:00
import { BufferGeometry } from 'three'
import { defineComponent, inject, watch } from 'vue'
2021-04-24 05:29:56 +08:00
import { MeshInterface } from '../meshes/Mesh'
2021-04-19 04:25:24 +08:00
2021-04-24 05:29:56 +08:00
export interface GeometryInterface {
2021-04-19 04:25:24 +08:00
geometry?: BufferGeometry
mesh?: MeshInterface
watchProps: string[]
}
function defaultSetup(): GeometryInterface {
const mesh = inject('mesh') as MeshInterface
const watchProps: string[] = []
return { mesh, watchProps }
}
2021-04-16 10:13:00 +08:00
const Geometry = defineComponent({
props: {
rotateX: Number,
rotateY: Number,
rotateZ: Number,
},
2021-04-19 04:25:24 +08:00
setup() {
return defaultSetup()
},
2021-04-16 10:13:00 +08:00
created() {
if (!this.mesh) {
console.error('Missing parent Mesh')
2021-04-19 04:25:24 +08:00
return
2021-04-16 10:13:00 +08:00
}
Object.entries(this.$props).forEach(e => this.watchProps.push(e[0]))
this.createGeometry()
this.rotateGeometry()
2021-04-19 04:25:24 +08:00
if (this.geometry) this.mesh.setGeometry(this.geometry)
2021-04-16 10:13:00 +08:00
this.addWatchers()
},
unmounted() {
2021-04-19 04:25:24 +08:00
this.geometry?.dispose()
2021-04-16 10:13:00 +08:00
},
methods: {
2021-04-19 04:25:24 +08:00
createGeometry() {},
2021-04-16 10:13:00 +08:00
addWatchers() {
this.watchProps.forEach(prop => {
2021-04-19 04:25:24 +08:00
// @ts-ignore
2021-04-16 10:13:00 +08:00
watch(() => this[prop], () => {
this.refreshGeometry()
})
})
},
rotateGeometry() {
2021-04-19 04:25:24 +08:00
if (this.rotateX) this.geometry?.rotateX(this.rotateX)
if (this.rotateY) this.geometry?.rotateY(this.rotateY)
if (this.rotateZ) this.geometry?.rotateZ(this.rotateZ)
2021-04-16 10:13:00 +08:00
},
refreshGeometry() {
const oldGeo = this.geometry
this.createGeometry()
this.rotateGeometry()
2021-04-19 04:25:24 +08:00
if (this.geometry) this.mesh?.setGeometry(this.geometry)
oldGeo?.dispose()
2021-04-16 10:13:00 +08:00
},
},
2021-04-21 22:08:10 +08:00
render() { return [] },
2021-04-16 10:13:00 +08:00
})
export default Geometry
2021-04-22 03:05:02 +08:00
// @ts-ignore
2021-04-16 10:13:00 +08:00
export function geometryComponent(name, props, createGeometry) {
return defineComponent({
name,
extends: Geometry,
props,
2021-04-19 04:25:24 +08:00
setup() {
return defaultSetup()
},
2021-04-16 10:13:00 +08:00
methods: {
createGeometry() {
this.geometry = createGeometry(this)
},
},
2021-04-19 04:25:24 +08:00
// __hmrId: name,
2021-04-16 10:13:00 +08:00
})
}