@inweb/viewer-three 25.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +63 -0
  3. package/dist/viewer-three.js +42841 -0
  4. package/dist/viewer-three.js.map +1 -0
  5. package/dist/viewer-three.min.js +6 -0
  6. package/dist/viewer-three.module.js +1102 -0
  7. package/dist/viewer-three.module.js.map +1 -0
  8. package/lib/ThreejsViewer/IComponent.d.ts +3 -0
  9. package/lib/ThreejsViewer/ThreejsViewer.d.ts +54 -0
  10. package/lib/ThreejsViewer/components/BackgroundComponent.d.ts +10 -0
  11. package/lib/ThreejsViewer/components/DefaultCameraPositionComponent.d.ts +9 -0
  12. package/lib/ThreejsViewer/components/LightComponent.d.ts +10 -0
  13. package/lib/ThreejsViewer/components/ObjectSelectionComponent.d.ts +16 -0
  14. package/lib/ThreejsViewer/components/RenderLoopComponent.d.ts +9 -0
  15. package/lib/ThreejsViewer/components/ResizeCanvasComponent.d.ts +9 -0
  16. package/lib/ThreejsViewer/draggers/ClippingPlaneDragger.d.ts +17 -0
  17. package/lib/ThreejsViewer/draggers/OrbitDragger.d.ts +10 -0
  18. package/lib/ThreejsViewer/draggers/PanDragger.d.ts +5 -0
  19. package/lib/ThreejsViewer/draggers/WalkDragger.d.ts +39 -0
  20. package/lib/ThreejsViewer/draggers/ZoomDragger.d.ts +5 -0
  21. package/lib/ThreejsViewer/loaders/GLTFLoadingManager.d.ts +11 -0
  22. package/lib/index.d.ts +2 -0
  23. package/package.json +42 -0
  24. package/src/ThreejsViewer/IComponent.ts +3 -0
  25. package/src/ThreejsViewer/ThreejsViewer.ts +369 -0
  26. package/src/ThreejsViewer/components/BackgroundComponent.ts +57 -0
  27. package/src/ThreejsViewer/components/DefaultCameraPositionComponent.ts +66 -0
  28. package/src/ThreejsViewer/components/LightComponent.ts +48 -0
  29. package/src/ThreejsViewer/components/ObjectSelectionComponent.ts +105 -0
  30. package/src/ThreejsViewer/components/RenderLoopComponent.ts +44 -0
  31. package/src/ThreejsViewer/components/ResizeCanvasComponent.ts +53 -0
  32. package/src/ThreejsViewer/draggers/ClippingPlaneDragger.ts +120 -0
  33. package/src/ThreejsViewer/draggers/OrbitDragger.ts +61 -0
  34. package/src/ThreejsViewer/draggers/PanDragger.ts +34 -0
  35. package/src/ThreejsViewer/draggers/WalkDragger.ts +260 -0
  36. package/src/ThreejsViewer/draggers/ZoomDragger.ts +34 -0
  37. package/src/ThreejsViewer/loaders/GLTFLoadingManager.ts +69 -0
  38. package/src/index.ts +25 -0
@@ -0,0 +1,369 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2023, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2021 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ import { EventEmitter2 } from "@inweb/eventemitter2";
25
+ import { Assembly, Client, File, Model } from "@inweb/client";
26
+ import {
27
+ CANVAS_EVENTS,
28
+ commands,
29
+ IViewpoint,
30
+ IViewer,
31
+ Options,
32
+ OptionsData,
33
+ OptionsEventMap,
34
+ ViewerEventMap,
35
+ } from "@inweb/viewer-core";
36
+ import * as THREE from "three";
37
+ import { GLTF, GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
38
+ import { GLTFLoadingManager } from "./loaders/GLTFLoadingManager";
39
+
40
+ import { PanDragger } from "./draggers/PanDragger";
41
+ import { OrbitDragger } from "./draggers/OrbitDragger";
42
+ import { ZoomDragger } from "./draggers/ZoomDragger";
43
+ import { WalkDragger } from "./draggers/WalkDragger";
44
+ import { ClippingPlaneDragger } from "./draggers/ClippingPlaneDragger";
45
+
46
+ import { IComponent } from "./IComponent";
47
+ import { LightComponent } from "./components/LightComponent";
48
+ import { BackgroundComponent } from "./components/BackgroundComponent";
49
+ import { DefaultCameraPositionComponent } from "./components/DefaultCameraPositionComponent";
50
+ import { ResizeCanvasComponent } from "./components/ResizeCanvasComponent";
51
+ import { RenderLoopComponent } from "./components/RenderLoopComponent";
52
+ // import { ObjectSelectionComponent } from "./components/ObjectSelectionComponent";
53
+
54
+ export class ThreejsViewer extends EventEmitter2<ViewerEventMap & OptionsEventMap> implements IViewer {
55
+ public client: Client | undefined;
56
+ private _options: Options;
57
+
58
+ private canvaseventlistener: (event: any) => void;
59
+
60
+ public canvas: HTMLCanvasElement | undefined;
61
+ public canvasEvents: string[];
62
+
63
+ public scene: THREE.Scene | undefined;
64
+ public camera: THREE.PerspectiveCamera | undefined;
65
+ public renderer: THREE.WebGLRenderer | undefined;
66
+ public models: Array<GLTF>;
67
+ public selectedObjects: Array<any>;
68
+
69
+ private draggerFactory: Record<string, any>;
70
+ private _activeDragger: any;
71
+
72
+ private components: Array<IComponent>;
73
+
74
+ private renderNeeded: boolean;
75
+ private renderTime: DOMHighResTimeStamp;
76
+
77
+ constructor(client?: Client) {
78
+ super();
79
+ this._options = new Options(this);
80
+
81
+ this.client = client;
82
+
83
+ this.canvasEvents = CANVAS_EVENTS;
84
+ this.canvaseventlistener = (event: Event) => this.emit(event);
85
+
86
+ this.draggerFactory = {
87
+ Pan: PanDragger,
88
+ Zoom: ZoomDragger,
89
+ Orbit: OrbitDragger,
90
+ Walk: WalkDragger,
91
+ Clipping: ClippingPlaneDragger,
92
+ };
93
+ this._activeDragger = null;
94
+
95
+ this.models = [];
96
+ this.components = [];
97
+ this.selectedObjects = [];
98
+
99
+ this.renderTime = 0;
100
+
101
+ this.render = this.render.bind(this);
102
+ this.update = this.update.bind(this);
103
+ }
104
+
105
+ get options(): Options {
106
+ return this._options;
107
+ }
108
+
109
+ get draggers(): string[] {
110
+ return Object.keys(this.draggerFactory);
111
+ }
112
+
113
+ initialize(canvas: HTMLCanvasElement, onProgress?: (event: ProgressEvent<EventTarget>) => void): Promise<this> {
114
+ this.addEventListener("optionschange", (event) => this.syncOptions(event.data));
115
+
116
+ this.scene = new THREE.Scene();
117
+
118
+ const rect = canvas.parentElement.getBoundingClientRect();
119
+ const width = rect.width || 1;
120
+ const height = rect.height || 1;
121
+ this.camera = new THREE.PerspectiveCamera(45, width / height, 0.01, 1000);
122
+ this.camera.up.set(0, 0, 1);
123
+
124
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
125
+ this.renderer.setPixelRatio(window.devicePixelRatio);
126
+ this.renderer.setSize(width, height);
127
+ this.renderer.toneMapping = THREE.LinearToneMapping;
128
+
129
+ this.canvas = canvas;
130
+ this.canvasEvents.forEach((x) => canvas.addEventListener(x, this.canvaseventlistener));
131
+
132
+ this.components.push(new LightComponent(this));
133
+ this.components.push(new BackgroundComponent(this));
134
+ this.components.push(new DefaultCameraPositionComponent(this));
135
+ this.components.push(new ResizeCanvasComponent(this));
136
+ this.components.push(new RenderLoopComponent(this as any));
137
+ // this.components.push(new ObjectSelectionComponent(this as any));
138
+
139
+ this.options.notifierChangeEvent();
140
+
141
+ this.renderTime = performance.now();
142
+ this.render(this.renderTime);
143
+
144
+ if (typeof onProgress === "function")
145
+ onProgress(new ProgressEvent("progress", { lengthComputable: true, loaded: 1, total: 1 }));
146
+
147
+ return Promise.resolve(this);
148
+ }
149
+
150
+ dispose(): this {
151
+ this.cancel();
152
+ this.emitEvent({ type: "dispose" });
153
+
154
+ this.components.forEach((component: IComponent) => component.dispose());
155
+ this.components = [];
156
+
157
+ this.setActiveDragger("");
158
+ this.removeAllListeners();
159
+
160
+ if (this.canvas) {
161
+ this.canvasEvents.forEach((x) => this.canvas.removeEventListener(x, this.canvaseventlistener));
162
+ this.canvas = undefined;
163
+ }
164
+
165
+ if (this.renderer) this.renderer.dispose();
166
+
167
+ this.renderer = undefined;
168
+ this.camera = undefined;
169
+ this.scene = undefined;
170
+
171
+ return this;
172
+ }
173
+
174
+ isInitialized(): boolean {
175
+ return !!this.renderer;
176
+ }
177
+
178
+ public render(time: DOMHighResTimeStamp): void {
179
+ if (!this.renderNeeded) return;
180
+ if (!this.renderer) return;
181
+
182
+ this.renderer.render(this.scene, this.camera);
183
+ this.renderNeeded = false;
184
+
185
+ const deltaTime = (time - this.renderTime) / 1000;
186
+ this.renderTime = time;
187
+ this.emitEvent({ type: "render", time, deltaTime });
188
+ }
189
+
190
+ public update(force = false): void {
191
+ this.renderNeeded = true;
192
+ if (force) this.render(performance.now());
193
+ this.emitEvent({ type: "update", data: force });
194
+ }
195
+
196
+ public syncOptions(options: OptionsData = this.options.data): void {
197
+ // this.update();
198
+ }
199
+
200
+ loadReferences(model: Model | File | Assembly): Promise<this> {
201
+ // todo: load reference as text fonts
202
+ return Promise.resolve(this);
203
+ }
204
+
205
+ async open(file: File | Assembly | Model): Promise<this> {
206
+ if (!this.renderer) return this;
207
+
208
+ this.cancel();
209
+ this.clear();
210
+
211
+ this.emitEvent({ type: "open", file, model: file });
212
+
213
+ let model: Model;
214
+
215
+ if (file) {
216
+ const models = (await file.getModels()) || [];
217
+ model = models.find((model: Model) => model.default) || models[0];
218
+ }
219
+ if (!model) throw new Error("No default model found");
220
+
221
+ const geometryType = model.database.split(".").pop();
222
+ if (geometryType !== "gltf") throw new Error(`Unknown geometry type: ${geometryType}`);
223
+
224
+ const url = `${model.httpClient.serverUrl}${model.path}/${model.database}`;
225
+ const params = { requestHeader: model.httpClient.headers };
226
+
227
+ await this.loadReferences(model);
228
+ await this.loadGltfFile(url, undefined, params);
229
+
230
+ return this;
231
+ }
232
+
233
+ cancel(): this {
234
+ this.emitEvent({ type: "cancel" });
235
+ return this;
236
+ }
237
+
238
+ openGltfFile(
239
+ file: string | ArrayBuffer | Blob,
240
+ externalData: Map<string, string | ArrayBuffer | Blob> = new Map(),
241
+ params: {
242
+ path?: string;
243
+ requestHeader?: HeadersInit;
244
+ crossOrigin?: string;
245
+ withCredentials?: boolean;
246
+ } = {}
247
+ ): Promise<this> {
248
+ if (!this.renderer) return Promise.resolve(this);
249
+
250
+ this.cancel();
251
+ this.clear();
252
+
253
+ this.emitEvent({ type: "open" });
254
+
255
+ return this.loadGltfFile(file, externalData, params);
256
+ }
257
+
258
+ async loadGltfFile(
259
+ file: string | ArrayBuffer | Blob,
260
+ externalData: Map<string, string | ArrayBuffer | Blob> = new Map(),
261
+ params: {
262
+ path?: string;
263
+ requestHeader?: HeadersInit;
264
+ crossOrigin?: string;
265
+ withCredentials?: boolean;
266
+ } = {}
267
+ ): Promise<this> {
268
+ const manager = new GLTFLoadingManager(file, externalData, params);
269
+ try {
270
+ this.emitEvent({ type: "geometrystart" });
271
+
272
+ const loader = new GLTFLoader(manager);
273
+ loader.setPath(manager.path);
274
+ loader.setRequestHeader(params.requestHeader as any);
275
+ loader.setCrossOrigin(params.crossOrigin || loader.crossOrigin);
276
+ loader.setWithCredentials(params.withCredentials || loader.withCredentials);
277
+
278
+ const gltf = await loader.loadAsync(manager.fileURL, (event: ProgressEvent) => {
279
+ const { lengthComputable, loaded, total } = event;
280
+ const progress = lengthComputable ? loaded / total : 1;
281
+ this.emitEvent({ type: "geometryprogress", data: progress });
282
+ });
283
+
284
+ if (!this.scene) return this;
285
+ if (!gltf.scene) throw new Error("No glTF scene found");
286
+
287
+ this.models.push(gltf);
288
+ this.scene.add(gltf.scene);
289
+ this.update();
290
+
291
+ this.emitEvent({ type: "databasechunk" });
292
+ this.emitEvent({ type: "geometryend", data: gltf.scene });
293
+ } catch (error) {
294
+ this.emitEvent({ type: "geometryerror", data: error });
295
+ throw error;
296
+ } finally {
297
+ manager.dispose();
298
+ }
299
+
300
+ return this;
301
+ }
302
+
303
+ clear(): this {
304
+ function disposeMaterial(material: any) {
305
+ const materials = Array.isArray(material) ? material : [material];
306
+ materials.forEach((material: any) => {
307
+ // Object.keys(material).forEach((key) => material[key]?.dispose?.());
308
+ material.dispose();
309
+ });
310
+ }
311
+
312
+ function disposeObject(object: any) {
313
+ if (object.geometry) object.geometry.dispose();
314
+ if (object.material) disposeMaterial(object.material);
315
+ }
316
+
317
+ this.selectedObjects = [];
318
+
319
+ this.models.forEach((gltf) => gltf.scene.traverse(disposeObject));
320
+ this.models.forEach((gltf) => gltf.scene.removeFromParent());
321
+ this.models = [];
322
+
323
+ this.update();
324
+ this.emitEvent({ type: "clear" });
325
+
326
+ return this;
327
+ }
328
+
329
+ activeDragger(): any | null {
330
+ return this._activeDragger;
331
+ }
332
+
333
+ setActiveDragger(name: string): any {
334
+ if (!this._activeDragger || this._activeDragger.name !== name) {
335
+ if (this._activeDragger) {
336
+ this._activeDragger.dispose();
337
+ this._activeDragger = null;
338
+ }
339
+ const Constructor = this.draggerFactory[name];
340
+ if (Constructor) {
341
+ this._activeDragger = new Constructor(this);
342
+ this._activeDragger.name = name;
343
+ }
344
+ }
345
+ return this._activeDragger;
346
+ }
347
+
348
+ resetActiveDragger(): void {
349
+ const dragger = this._activeDragger;
350
+ if (dragger) {
351
+ this.setActiveDragger("");
352
+ this.setActiveDragger(dragger.name);
353
+ }
354
+ }
355
+
356
+ is3D(): boolean {
357
+ return false;
358
+ }
359
+
360
+ executeCommand(id: string, ...args: any[]): any {
361
+ return commands("ThreeJS").executeCommand(id, this, ...args);
362
+ }
363
+
364
+ drawViewpoint(viewpoint: IViewpoint): void {}
365
+
366
+ createViewpoint(): IViewpoint {
367
+ return {};
368
+ }
369
+ }
@@ -0,0 +1,57 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2023, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2021 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ import * as THREE from "three";
25
+ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
26
+ import { IComponent } from "../IComponent";
27
+ import type { ThreejsViewer } from "../ThreejsViewer";
28
+
29
+ export class BackgroundComponent implements IComponent {
30
+ protected viewer: ThreejsViewer;
31
+ protected backgroundColor: THREE.Color;
32
+
33
+ constructor(viewer: ThreejsViewer) {
34
+ this.viewer = viewer;
35
+
36
+ this.backgroundColor = new THREE.Color(0xffffff);
37
+
38
+ const environment = new RoomEnvironment();
39
+ const pmremGenerator = new THREE.PMREMGenerator(this.viewer.renderer);
40
+
41
+ this.viewer.scene.background = this.backgroundColor;
42
+ this.viewer.scene.environment = pmremGenerator.fromScene(environment).texture;
43
+ this.viewer.addEventListener("optionschange", this.syncOptions);
44
+
45
+ environment.dispose();
46
+ }
47
+
48
+ dispose() {
49
+ this.viewer.removeEventListener("optionschange", this.syncOptions);
50
+ this.viewer.scene.environment = undefined;
51
+ this.viewer.scene.background = undefined;
52
+ }
53
+
54
+ syncOptions = () => {
55
+ this.backgroundColor.setHex(0xffffff);
56
+ };
57
+ }
@@ -0,0 +1,66 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2023, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2021 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ import { GeometryEndEvent } from "@inweb/viewer-core";
25
+ import * as THREE from "three";
26
+ import { IComponent } from "../IComponent";
27
+ import type { ThreejsViewer } from "../ThreejsViewer";
28
+
29
+ export class DefaultCameraPositionComponent implements IComponent {
30
+ protected viewer: ThreejsViewer;
31
+
32
+ constructor(viewer: ThreejsViewer) {
33
+ this.viewer = viewer;
34
+ this.viewer.addEventListener("geometryend", this.geometryEnd);
35
+ }
36
+
37
+ dispose() {
38
+ this.viewer.removeEventListener("geometryend", this.geometryEnd);
39
+ }
40
+
41
+ geometryEnd = (event: GeometryEndEvent) => {
42
+ const { data: scene } = event;
43
+
44
+ scene.updateMatrixWorld();
45
+
46
+ const box = new THREE.Box3().setFromObject(scene);
47
+ const size = box.getSize(new THREE.Vector3()).length();
48
+ const center = box.getCenter(new THREE.Vector3());
49
+
50
+ scene.position.x += scene.position.x - center.x;
51
+ scene.position.y += scene.position.y - center.y;
52
+ scene.position.z += scene.position.z - center.z;
53
+
54
+ this.viewer.camera.near = size / 100;
55
+ this.viewer.camera.far = size * 100;
56
+
57
+ this.viewer.camera.position.copy(center);
58
+ this.viewer.camera.position.x += size / 2.0;
59
+ this.viewer.camera.position.y += size / 5.0;
60
+ this.viewer.camera.position.z += size / 2.0;
61
+
62
+ this.viewer.camera.updateMatrixWorld();
63
+ this.viewer.camera.updateProjectionMatrix();
64
+ this.viewer.camera.lookAt(center);
65
+ };
66
+ }
@@ -0,0 +1,48 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2023, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2021 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ import * as THREE from "three";
25
+ import { IComponent } from "../IComponent";
26
+ import type { ThreejsViewer } from "../ThreejsViewer";
27
+
28
+ export class LightComponent implements IComponent {
29
+ protected viewer: ThreejsViewer;
30
+ protected ambientLight: THREE.AmbientLight;
31
+ protected directLight: THREE.DirectionalLight;
32
+
33
+ constructor(viewer: ThreejsViewer) {
34
+ this.viewer = viewer;
35
+
36
+ this.ambientLight = new THREE.AmbientLight(0xffffff, 0);
37
+ this.viewer.camera.add(this.ambientLight);
38
+
39
+ this.directLight = new THREE.DirectionalLight(0xffffff, 1);
40
+ this.directLight.position.set(0.5, 0, 0.866); // ~60º
41
+ this.viewer.camera.add(this.directLight);
42
+ }
43
+
44
+ dispose() {
45
+ this.ambientLight.removeFromParent();
46
+ this.directLight.removeFromParent();
47
+ }
48
+ }
@@ -0,0 +1,105 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2023, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2021 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ import * as THREE from "three";
25
+ import { IComponent } from "../IComponent";
26
+ import type { ThreejsViewer } from "../ThreejsViewer";
27
+
28
+ export class ObjectSelectionComponent implements IComponent {
29
+ protected viewer: ThreejsViewer;
30
+ protected raycaster: THREE.Raycaster;
31
+ protected mouse: THREE.Vector2;
32
+ protected selectionMaterial: THREE.MeshBasicMaterial;
33
+
34
+ constructor(viewer: ThreejsViewer) {
35
+ this.viewer = viewer;
36
+ this.raycaster = new THREE.Raycaster();
37
+ this.mouse = new THREE.Vector2();
38
+ this.selectionMaterial = new THREE.MeshBasicMaterial({ color: "red" });
39
+
40
+ this.viewer.addEventListener("pointerdown", this.onPointerDown);
41
+ this.viewer.addEventListener("pointerup", this.onPointerUp);
42
+ }
43
+
44
+ dispose() {
45
+ this.viewer.removeEventListener("pointerdown", this.onPointerDown);
46
+ this.viewer.removeEventListener("pointerup", this.onPointerUp);
47
+ }
48
+
49
+ onPointerUp = (event: PointerEvent) => {
50
+ const x = (event.offsetX / this.viewer.canvas.clientWidth) * 2 - 1;
51
+ const y = -(event.offsetY / this.viewer.canvas.clientHeight) * 2 + 1;
52
+
53
+ if (this.mouse.x === x && this.mouse.y === y) {
54
+ this.raycaster.setFromCamera(this.mouse, this.viewer.camera);
55
+ const intersects = this.raycaster.intersectObjects(this.viewer.scene.children, true);
56
+ this.clearSelection();
57
+ if (intersects.length > 0) {
58
+ const object = intersects[0].object as THREE.Mesh;
59
+ this.setSelectObject(object, true);
60
+ }
61
+ }
62
+ };
63
+
64
+ onPointerDown = (event: PointerEvent) => {
65
+ this.mouse.x = (event.offsetX / this.viewer.canvas.clientWidth) * 2 - 1;
66
+ this.mouse.y = -(event.offsetY / this.viewer.canvas.clientHeight) * 2 + 1;
67
+ };
68
+
69
+ clearSelection() {
70
+ this.viewer.selectedObjects.forEach((object) => this.setSelectObject(object, false));
71
+ this.viewer.selectedObjects.length = 0;
72
+ }
73
+
74
+ setSelectObject(object, selected) {
75
+ if (selected) {
76
+ const index = this.viewer.selectedObjects.findIndex((o) => o === object);
77
+ if (index === -1) {
78
+ this.viewer.selectedObjects.push(object);
79
+ this.highlightObject(object, true);
80
+ this.viewer.emit("selectobject", object);
81
+ }
82
+ } else {
83
+ const index = this.viewer.selectedObjects.findIndex((o) => o === object);
84
+ if (index !== -1) {
85
+ this.viewer.selectedObjects.splice(index, 1);
86
+ this.highlightObject(object, false);
87
+ this.viewer.emit("deselectobject", object);
88
+ }
89
+ }
90
+ }
91
+
92
+ highlightObject(object, enable) {
93
+ if (enable) {
94
+ if (!object.originalMaterial) {
95
+ object.originalMaterial = object.material;
96
+ object.material = this.selectionMaterial;
97
+ }
98
+ } else {
99
+ if (object.originalMaterial) {
100
+ object.material = object.originalMaterial;
101
+ delete object.originalMaterial;
102
+ }
103
+ }
104
+ }
105
+ }