1 | "use strict"; |
---|
2 | import * as THREE from 'three'; |
---|
3 | |
---|
4 | /** |
---|
5 | * Class helper for creating a THREE.js scene with multiple meshes. |
---|
6 | */ |
---|
7 | class Scene { |
---|
8 | /** |
---|
9 | * Basic constructor setting THREE.js Scene object |
---|
10 | */ |
---|
11 | constructor() { |
---|
12 | this.scene = new THREE.Scene(); |
---|
13 | } |
---|
14 | |
---|
15 | /** |
---|
16 | * Adds new element (or more elements) to THREE.js Scene |
---|
17 | * @param {...Object3D[]} obj list of objects to be added to the Scene |
---|
18 | */ |
---|
19 | add(obj) { |
---|
20 | this.scene.add(obj); |
---|
21 | } |
---|
22 | |
---|
23 | /** |
---|
24 | * Removes object from Scene by reference. If object was geometry or material, |
---|
25 | * then it disposes their data |
---|
26 | * @param {Object3D} obj object to be removed from Scene |
---|
27 | */ |
---|
28 | remove(obj) { |
---|
29 | this.scene.remove(obj); |
---|
30 | if (obj.geometry) { |
---|
31 | obj.geometry.dispose(); |
---|
32 | obj.geometry = null; |
---|
33 | } |
---|
34 | if (obj.material) { |
---|
35 | obj.material.dispose(); |
---|
36 | obj.material = null; |
---|
37 | } |
---|
38 | } |
---|
39 | |
---|
40 | /** |
---|
41 | * Getter for Scene children |
---|
42 | * @returns {Object3D} children of Scene |
---|
43 | */ |
---|
44 | getChildren() { |
---|
45 | return this.scene.children; |
---|
46 | } |
---|
47 | |
---|
48 | /** |
---|
49 | * Getter of meshes of Scene |
---|
50 | * @returns {Mesh} only meshes objects from Scene |
---|
51 | */ |
---|
52 | getMeshes() { |
---|
53 | let meshes = []; |
---|
54 | for (let i = 0; i < this.scene.children.length; i++) { |
---|
55 | let child = this.scene.children[i]; |
---|
56 | if (child instanceof THREE.Mesh) { |
---|
57 | meshes.push(child); |
---|
58 | } |
---|
59 | } |
---|
60 | return meshes; |
---|
61 | } |
---|
62 | |
---|
63 | /** |
---|
64 | * Removes all elements from Scene. |
---|
65 | */ |
---|
66 | clear() { |
---|
67 | let toRemove = []; |
---|
68 | for (let i = 0; i < this.scene.children.length; i++) { |
---|
69 | let obj = this.scene.children[i]; |
---|
70 | if (obj.userData && obj.userData.isBodyElement) { |
---|
71 | toRemove.push(obj); |
---|
72 | } |
---|
73 | } |
---|
74 | for (let i = 0; i < toRemove.length; i++) { |
---|
75 | this.remove(toRemove[i]); |
---|
76 | } |
---|
77 | } |
---|
78 | |
---|
79 | /** |
---|
80 | * Render scene with renderer |
---|
81 | * @param {WebGLRenderer} renderer Renderer for scene |
---|
82 | * @param {PerspectiveCamera} camera Perspective camera for scene |
---|
83 | */ |
---|
84 | render(renderer, camera) { |
---|
85 | renderer.render(this.scene, camera); |
---|
86 | } |
---|
87 | } |
---|
88 | |
---|
89 | export default Scene; |
---|