|
| 1 | +import { BufferGeometry, BufferAttribute, Mesh } from 'three' |
| 2 | + |
| 3 | +class ChunkManager { |
| 4 | + constructor (game) { |
| 5 | + this.game = game |
| 6 | + this.chunks = new Map() |
| 7 | + this.cellMesh = new Map() |
| 8 | + } |
| 9 | + |
| 10 | + addChunk (cellId, vert) { |
| 11 | + this.chunks.set(cellId, vert) |
| 12 | + |
| 13 | + const geometry = new BufferGeometry() |
| 14 | + geometry.setAttribute('position', new BufferAttribute(new Float32Array(vert.positions), 3)) |
| 15 | + geometry.setAttribute('normal', new BufferAttribute(new Float32Array(vert.normals), 3)) |
| 16 | + geometry.setAttribute('uv', new BufferAttribute(new Float32Array(vert.uvs), 2)) |
| 17 | + geometry.setAttribute('color', new BufferAttribute(new Float32Array(vert.colors), 3)) |
| 18 | + geometry.matrixAutoUpdate = false |
| 19 | + |
| 20 | + const mesh = this.cellMesh.get(cellId) |
| 21 | + if (mesh === undefined) { |
| 22 | + const newMesh = new Mesh(geometry, this.game.world.material) |
| 23 | + newMesh.matrixAutoUpdate = false |
| 24 | + newMesh.frustumCulled = false |
| 25 | + newMesh.onAfterRender = () => { |
| 26 | + newMesh.frustumCulled = true |
| 27 | + newMesh.onAfterRender = function () {} |
| 28 | + } |
| 29 | + this.cellMesh.set(cellId, newMesh) |
| 30 | + this.game.scene.add(newMesh) |
| 31 | + if (this.game.world.lastPlayerChunk !== null) { |
| 32 | + this.game.world.updateRenderOrder(JSON.parse(this.game.world.lastPlayerChunk)) |
| 33 | + } |
| 34 | + } else { |
| 35 | + this.cellMesh.get(cellId).geometry = geometry |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + removeChunk (cellId) { |
| 40 | + if (this.chunks.get(cellId) !== undefined) { |
| 41 | + this.cellMesh.get(cellId).geometry.dispose() |
| 42 | + this.game.scene.remove(this.cellMesh.get(cellId)) |
| 43 | + this.cellMesh.delete(cellId) |
| 44 | + this.game.renderer.renderLists.dispose() |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + reset () { |
| 49 | + for (const i of this.cellMesh) { |
| 50 | + if (i[1].geometry !== undefined) { |
| 51 | + i[1].geometry.dispose() |
| 52 | + this.game.scene.remove(i[1]) |
| 53 | + } |
| 54 | + } |
| 55 | + this.cellMesh.clear() |
| 56 | + this.chunks.clear() |
| 57 | + } |
| 58 | +} |
| 59 | +export { ChunkManager } |
0 commit comments