@sequent-org/ifc-viewer 1.2.4-ci.53.0 → 1.2.4-ci.55.0

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.
@@ -1,839 +1,7 @@
1
- import * as THREE from "three";
2
-
3
- class CardMarker {
4
- /**
5
- * @param {object} deps
6
- * @param {number|string} deps.id
7
- * @param {THREE.Vector3} deps.localPoint
8
- * @param {HTMLElement} deps.el
9
- * @param {object|null} deps.sceneState
10
- */
11
- constructor(deps) {
12
- this.id = deps.id;
13
- this.localPoint = deps.localPoint;
14
- this.el = deps.el;
15
- this.sceneState = deps.sceneState || null;
16
- }
17
- }
1
+ import { LabelPlacementController } from "./LabelPlacementController.js";
18
2
 
19
3
  /**
20
- * UI-контроллер: "+ Добавить карточку" → призрак у курсора → установка метки кликом по модели.
21
- *
22
- * Важно:
23
- * - метка хранит координату в ЛОКАЛЬНЫХ координатах activeModel, чтобы "ехать" вместе с моделью при её перемещении.
24
- * - во время режима постановки блокируем обработку LMB у OrbitControls/других контроллеров (capture-phase).
4
+ * @deprecated используйте LabelPlacementController
25
5
  */
26
- export class CardPlacementController {
27
- /**
28
- * @param {object} deps
29
- * @param {import('../viewer/Viewer.js').Viewer} deps.viewer
30
- * @param {HTMLElement} deps.container Контейнер viewer (обычно #app)
31
- * @param {object} [deps.logger]
32
- */
33
- constructor(deps) {
34
- this.viewer = deps.viewer;
35
- this.container = deps.container;
36
- this.logger = deps.logger || null;
37
-
38
- this._placing = false;
39
- this._nextId = 1;
40
- /** @type {CardMarker[]} */
41
- this._markers = [];
42
-
43
- this._raycaster = new THREE.Raycaster();
44
- this._ndc = new THREE.Vector2();
45
- this._tmpV = new THREE.Vector3();
46
- this._tmpLocal = new THREE.Vector3();
47
-
48
- this._lastPointer = { x: 0, y: 0 };
49
- this._ghostPos = { x: 0, y: 0 };
50
- this._raf = 0;
51
-
52
- this._controlsWasEnabled = null;
53
-
54
- this._containerOffset = { left: 0, top: 0 };
55
- this._containerOffsetValid = false;
56
-
57
- this._fly = {
58
- raf: 0,
59
- active: false,
60
- prevControlsEnabled: null,
61
- startTs: 0,
62
- durationMs: 550,
63
- // start/end snapshots
64
- from: null,
65
- to: null,
66
- // tmp vectors
67
- v0: new THREE.Vector3(),
68
- v1: new THREE.Vector3(),
69
- v2: new THREE.Vector3(),
70
- };
71
-
72
- this._ui = this.#createUi();
73
- this.#attachUi();
74
- this.#bindEvents();
75
- this.#startRaf();
76
- }
77
-
78
- dispose() {
79
- try { this.cancelPlacement(); } catch (_) {}
80
- try { this.#cancelFly(); } catch (_) {}
81
-
82
- const dom = this.viewer?.renderer?.domElement;
83
- try { dom?.removeEventListener("pointermove", this._onPointerMove); } catch (_) {}
84
- try { dom?.removeEventListener("pointerrawupdate", this._onPointerRawUpdate); } catch (_) {}
85
- try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture, { capture: true }); } catch (_) {
86
- try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture); } catch (_) {}
87
- }
88
- try { window.removeEventListener("keydown", this._onKeyDown); } catch (_) {}
89
- try { window.removeEventListener("resize", this._onWindowResize); } catch (_) {}
90
- try { window.removeEventListener("scroll", this._onWindowScroll, true); } catch (_) {}
91
- try { this._ui?.btn?.removeEventListener("click", this._onBtnClick); } catch (_) {}
92
-
93
- if (this._raf) cancelAnimationFrame(this._raf);
94
- this._raf = 0;
95
-
96
- try { this._markers.forEach((m) => m?.el?.remove?.()); } catch (_) {}
97
- this._markers.length = 0;
98
-
99
- try { this._ui?.ghost?.remove?.(); } catch (_) {}
100
- try { this._ui?.btn?.remove?.(); } catch (_) {}
101
- }
102
-
103
- startPlacement() {
104
- if (this._placing) return;
105
- this._placing = true;
106
-
107
- const controls = this.viewer?.controls;
108
- if (controls) {
109
- // Запоминаем и временно выключаем OrbitControls целиком
110
- this._controlsWasEnabled = !!controls.enabled;
111
- controls.enabled = false;
112
- }
113
-
114
- this.#refreshContainerOffset();
115
- this.#syncGhost();
116
- this.#setGhostVisible(true);
117
- this.#log("startPlacement", { nextId: this._nextId });
118
- }
119
-
120
- cancelPlacement() {
121
- if (!this._placing) return;
122
- this._placing = false;
123
- this.#setGhostVisible(false);
124
-
125
- const controls = this.viewer?.controls;
126
- if (controls && this._controlsWasEnabled != null) {
127
- controls.enabled = !!this._controlsWasEnabled;
128
- this._controlsWasEnabled = null;
129
- }
130
-
131
- this.#log("cancelPlacement", {});
132
- }
133
-
134
- #log(event, payload) {
135
- try {
136
- this.logger?.log?.("[CardPlacement]", event, payload);
137
- } catch (_) {}
138
- }
139
-
140
- #dispatchCardEvent(name, detail) {
141
- try {
142
- const ev = new CustomEvent(name, { detail, bubbles: true });
143
- this.container?.dispatchEvent?.(ev);
144
- } catch (_) {}
145
- }
146
-
147
- #easeOutCubic(t) {
148
- const x = Math.min(1, Math.max(0, Number(t) || 0));
149
- const inv = 1 - x;
150
- return 1 - inv * inv * inv; // быстрый старт, плавный конец
151
- }
152
-
153
- #cancelFly() {
154
- if (this._fly.raf) cancelAnimationFrame(this._fly.raf);
155
- this._fly.raf = 0;
156
- this._fly.active = false;
157
- this._fly.startTs = 0;
158
- this._fly.from = null;
159
- this._fly.to = null;
160
-
161
- // Вернём OrbitControls, если отключали
162
- try {
163
- const controls = this.viewer?.controls;
164
- if (controls && this._fly.prevControlsEnabled != null) controls.enabled = this._fly.prevControlsEnabled;
165
- } catch (_) {}
166
- this._fly.prevControlsEnabled = null;
167
- }
168
-
169
- #getCurrentCameraSnapshot() {
170
- const viewer = this.viewer;
171
- if (!viewer) return null;
172
- const camera = viewer.camera;
173
- const controls = viewer.controls;
174
- if (!camera || !controls) return null;
175
-
176
- const snap = {
177
- projectionMode: (typeof viewer.getProjectionMode === "function")
178
- ? viewer.getProjectionMode()
179
- : (camera.isOrthographicCamera ? "ortho" : "perspective"),
180
- camPos: camera.position.clone(),
181
- target: controls.target.clone(),
182
- fov: camera.isPerspectiveCamera ? Number(camera.fov) : null,
183
- zoom: camera.isOrthographicCamera ? Number(camera.zoom || 1) : null,
184
- viewOffset: (camera.view && camera.view.enabled)
185
- ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
186
- : { enabled: false, offsetX: 0, offsetY: 0 },
187
- };
188
- return snap;
189
- }
190
-
191
- #captureSceneState() {
192
- const viewer = this.viewer;
193
- if (!viewer) return null;
194
-
195
- const camera = viewer.camera;
196
- const controls = viewer.controls;
197
- const model = viewer.activeModel;
198
-
199
- const projectionMode = (typeof viewer.getProjectionMode === "function")
200
- ? viewer.getProjectionMode()
201
- : (camera?.isOrthographicCamera ? "ortho" : "perspective");
202
-
203
- const camPos = camera?.position ? { x: camera.position.x, y: camera.position.y, z: camera.position.z } : null;
204
- const target = controls?.target ? { x: controls.target.x, y: controls.target.y, z: controls.target.z } : null;
205
-
206
- const cam = {
207
- projectionMode,
208
- position: camPos,
209
- target,
210
- fov: (camera && camera.isPerspectiveCamera) ? Number(camera.fov) : null,
211
- zoom: (camera && camera.isOrthographicCamera) ? Number(camera.zoom || 1) : null,
212
- // MMB-pan (camera.viewOffset) — сохраняем как есть, в пикселях
213
- viewOffset: (camera && camera.view && camera.view.enabled)
214
- ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
215
- : { enabled: false, offsetX: 0, offsetY: 0 },
216
- };
217
-
218
- const modelTransform = model ? {
219
- position: { x: model.position.x, y: model.position.y, z: model.position.z },
220
- quaternion: { x: model.quaternion.x, y: model.quaternion.y, z: model.quaternion.z, w: model.quaternion.w },
221
- scale: { x: model.scale.x, y: model.scale.y, z: model.scale.z },
222
- } : null;
223
-
224
- const planes = viewer.clipping?.planes || [];
225
- const clipConstants = [
226
- planes?.[0]?.constant,
227
- planes?.[1]?.constant,
228
- planes?.[2]?.constant,
229
- ];
230
-
231
- return {
232
- camera: cam,
233
- modelTransform,
234
- clipping: { constants: clipConstants },
235
- };
236
- }
237
-
238
- #restoreSceneState(sceneState) {
239
- const viewer = this.viewer;
240
- if (!viewer || !sceneState) return;
241
-
242
- // 1) Проекция (может заменить ссылку viewer.camera)
243
- try {
244
- const pm = sceneState?.camera?.projectionMode;
245
- if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
246
- } catch (_) {}
247
-
248
- const camera = viewer.camera;
249
- const controls = viewer.controls;
250
- const model = viewer.activeModel;
251
-
252
- // 2) Камера + target + zoom/fov
253
- try {
254
- const t = sceneState?.camera?.target;
255
- if (controls && t) controls.target.set(Number(t.x) || 0, Number(t.y) || 0, Number(t.z) || 0);
256
- } catch (_) {}
257
- try {
258
- const p = sceneState?.camera?.position;
259
- if (camera && p) camera.position.set(Number(p.x) || 0, Number(p.y) || 0, Number(p.z) || 0);
260
- } catch (_) {}
261
- try {
262
- if (camera?.isPerspectiveCamera && sceneState?.camera?.fov != null) {
263
- const fov = Number(sceneState.camera.fov);
264
- if (Number.isFinite(fov) && fov > 1e-3 && fov < 179) camera.fov = fov;
265
- }
266
- } catch (_) {}
267
- try {
268
- if (camera?.isOrthographicCamera && sceneState?.camera?.zoom != null) {
269
- const z = Number(sceneState.camera.zoom);
270
- if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
271
- }
272
- } catch (_) {}
273
-
274
- // 3) Трансформ модели (позиция/поворот/масштаб)
275
- try {
276
- const mt = sceneState?.modelTransform;
277
- if (model && mt?.position && mt?.quaternion && mt?.scale) {
278
- model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
279
- model.quaternion.set(
280
- Number(mt.quaternion.x) || 0,
281
- Number(mt.quaternion.y) || 0,
282
- Number(mt.quaternion.z) || 0,
283
- Number(mt.quaternion.w) || 1
284
- );
285
- model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
286
- model.updateMatrixWorld?.(true);
287
- }
288
- } catch (_) {}
289
-
290
- // 4) ViewOffset (MMB-pan) — применяем после смены камеры/проекции
291
- try {
292
- const vo = sceneState?.camera?.viewOffset;
293
- if (camera && vo && typeof camera.setViewOffset === "function") {
294
- const dom = viewer?.renderer?.domElement;
295
- const rect = dom?.getBoundingClientRect?.();
296
- const w = Math.max(1, Math.floor(rect?.width || 1));
297
- const h = Math.max(1, Math.floor(rect?.height || 1));
298
- if (vo.enabled) {
299
- camera.setViewOffset(w, h, Math.round(Number(vo.offsetX) || 0), Math.round(Number(vo.offsetY) || 0), w, h);
300
- } else if (typeof camera.clearViewOffset === "function") {
301
- camera.clearViewOffset();
302
- } else {
303
- camera.setViewOffset(w, h, 0, 0, w, h);
304
- }
305
- }
306
- } catch (_) {}
307
-
308
- // 5) Клиппинг (как Home: сначала восстановили камеру+модель, затем planes)
309
- try {
310
- const constants = sceneState?.clipping?.constants || [];
311
- if (typeof viewer.setSection === "function") {
312
- ["x", "y", "z"].forEach((axis, i) => {
313
- const c = constants[i];
314
- const enabled = Number.isFinite(c);
315
- const dist = -Number(c);
316
- viewer.setSection(axis, enabled, enabled ? dist : 0);
317
- });
318
- }
319
- } catch (_) {}
320
-
321
- try { camera?.updateProjectionMatrix?.(); } catch (_) {}
322
- try { controls?.update?.(); } catch (_) {}
323
- }
324
-
325
- #applyModelTransformFromState(sceneState) {
326
- const viewer = this.viewer;
327
- if (!viewer || !sceneState) return;
328
- const model = viewer.activeModel;
329
- if (!model) return;
330
- const mt = sceneState?.modelTransform;
331
- if (!mt?.position || !mt?.quaternion || !mt?.scale) return;
332
- try {
333
- model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
334
- model.quaternion.set(
335
- Number(mt.quaternion.x) || 0,
336
- Number(mt.quaternion.y) || 0,
337
- Number(mt.quaternion.z) || 0,
338
- Number(mt.quaternion.w) || 1
339
- );
340
- model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
341
- model.updateMatrixWorld?.(true);
342
- } catch (_) {}
343
- }
344
-
345
- #applyClippingFromState(sceneState) {
346
- const viewer = this.viewer;
347
- if (!viewer || !sceneState) return;
348
- try {
349
- const constants = sceneState?.clipping?.constants || [];
350
- if (typeof viewer.setSection === "function") {
351
- ["x", "y", "z"].forEach((axis, i) => {
352
- const c = constants[i];
353
- const enabled = Number.isFinite(c);
354
- const dist = -Number(c);
355
- viewer.setSection(axis, enabled, enabled ? dist : 0);
356
- });
357
- }
358
- } catch (_) {}
359
- }
360
-
361
- #applyViewOffset(camera, viewOffset) {
362
- if (!camera || !viewOffset) return;
363
- try {
364
- const viewer = this.viewer;
365
- const dom = viewer?.renderer?.domElement;
366
- const rect = dom?.getBoundingClientRect?.();
367
- const w = Math.max(1, Math.floor(rect?.width || 1));
368
- const h = Math.max(1, Math.floor(rect?.height || 1));
369
-
370
- if (viewOffset.enabled) {
371
- camera.setViewOffset(w, h, Math.round(Number(viewOffset.offsetX) || 0), Math.round(Number(viewOffset.offsetY) || 0), w, h);
372
- } else if (typeof camera.clearViewOffset === "function") {
373
- camera.clearViewOffset();
374
- } else {
375
- camera.setViewOffset(w, h, 0, 0, w, h);
376
- }
377
- } catch (_) {}
378
- }
379
-
380
- #animateToSceneState(sceneState, durationMs = 550) {
381
- const viewer = this.viewer;
382
- if (!viewer || !sceneState) return;
383
-
384
- // Если уже летим — отменим предыдущую анимацию
385
- this.#cancelFly();
386
-
387
- // 1) Сразу применяем проекцию (может сменить viewer.camera)
388
- try {
389
- const pm = sceneState?.camera?.projectionMode;
390
- if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
391
- } catch (_) {}
392
-
393
- // 2) Сразу применяем трансформ модели (если нужен) — камера полетит уже к нужной сцене
394
- this.#applyModelTransformFromState(sceneState);
395
-
396
- const camera = viewer.camera;
397
- const controls = viewer.controls;
398
- if (!camera || !controls) return;
399
-
400
- const from = this.#getCurrentCameraSnapshot();
401
- if (!from) return;
402
-
403
- // Целевые значения (камера/target/zoom/fov/offset)
404
- const to = {
405
- projectionMode: sceneState?.camera?.projectionMode || from.projectionMode,
406
- camPos: sceneState?.camera?.position
407
- ? new THREE.Vector3(Number(sceneState.camera.position.x) || 0, Number(sceneState.camera.position.y) || 0, Number(sceneState.camera.position.z) || 0)
408
- : from.camPos.clone(),
409
- target: sceneState?.camera?.target
410
- ? new THREE.Vector3(Number(sceneState.camera.target.x) || 0, Number(sceneState.camera.target.y) || 0, Number(sceneState.camera.target.z) || 0)
411
- : from.target.clone(),
412
- fov: (camera.isPerspectiveCamera && sceneState?.camera?.fov != null) ? Number(sceneState.camera.fov) : from.fov,
413
- zoom: (camera.isOrthographicCamera && sceneState?.camera?.zoom != null) ? Number(sceneState.camera.zoom) : from.zoom,
414
- viewOffset: sceneState?.camera?.viewOffset || from.viewOffset,
415
- };
416
-
417
- // На время "долеталки" отключаем controls
418
- try {
419
- this._fly.prevControlsEnabled = !!controls.enabled;
420
- controls.enabled = false;
421
- } catch (_) {
422
- this._fly.prevControlsEnabled = null;
423
- }
424
-
425
- this._fly.active = true;
426
- this._fly.startTs = performance.now();
427
- this._fly.durationMs = Math.max(50, Number(durationMs) || 550);
428
- this._fly.from = from;
429
- this._fly.to = to;
430
-
431
- const tick = () => {
432
- if (!this._fly.active) return;
433
- const now = performance.now();
434
- const t = (now - this._fly.startTs) / this._fly.durationMs;
435
- const k = this.#easeOutCubic(t);
436
-
437
- // position lerp
438
- this._fly.v0.copy(from.camPos).lerp(to.camPos, k);
439
- camera.position.copy(this._fly.v0);
440
-
441
- // target lerp
442
- this._fly.v1.copy(from.target).lerp(to.target, k);
443
- controls.target.copy(this._fly.v1);
444
-
445
- // fov/zoom
446
- try {
447
- if (camera.isPerspectiveCamera && to.fov != null && from.fov != null) {
448
- const f = Number(from.fov) + (Number(to.fov) - Number(from.fov)) * k;
449
- if (Number.isFinite(f) && f > 1e-3 && f < 179) camera.fov = f;
450
- }
451
- } catch (_) {}
452
- try {
453
- if (camera.isOrthographicCamera && to.zoom != null && from.zoom != null) {
454
- const z = Number(from.zoom) + (Number(to.zoom) - Number(from.zoom)) * k;
455
- if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
456
- }
457
- } catch (_) {}
458
-
459
- // viewOffset lerp
460
- try {
461
- const vo0 = from.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
462
- const vo1 = to.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
463
- const enabled = !!(vo0.enabled || vo1.enabled);
464
- const ox = Number(vo0.offsetX) + (Number(vo1.offsetX) - Number(vo0.offsetX)) * k;
465
- const oy = Number(vo0.offsetY) + (Number(vo1.offsetY) - Number(vo0.offsetY)) * k;
466
- this.#applyViewOffset(camera, { enabled, offsetX: ox, offsetY: oy });
467
- } catch (_) {}
468
-
469
- try { camera.updateProjectionMatrix?.(); } catch (_) {}
470
- try { controls.update?.(); } catch (_) {}
471
-
472
- if (t >= 1) {
473
- // Финал: зафиксируем точные значения
474
- try { camera.position.copy(to.camPos); } catch (_) {}
475
- try { controls.target.copy(to.target); } catch (_) {}
476
- try {
477
- if (camera.isPerspectiveCamera && to.fov != null) camera.fov = to.fov;
478
- if (camera.isOrthographicCamera && to.zoom != null) camera.zoom = to.zoom;
479
- } catch (_) {}
480
- try { this.#applyViewOffset(camera, to.viewOffset); } catch (_) {}
481
-
482
- // В конце применяем clipping (чтобы ориентация плоскостей считалась по финальной камере)
483
- this.#applyClippingFromState(sceneState);
484
-
485
- try { camera.updateProjectionMatrix?.(); } catch (_) {}
486
- try { controls.update?.(); } catch (_) {}
487
-
488
- this.#cancelFly();
489
- return;
490
- }
491
-
492
- this._fly.raf = requestAnimationFrame(tick);
493
- };
494
-
495
- this._fly.raf = requestAnimationFrame(tick);
496
- }
497
-
498
- #createUi() {
499
- const btn = document.createElement("button");
500
- btn.type = "button";
501
- btn.className = "ifc-card-add-btn";
502
- btn.textContent = "+ Добавить карточку";
503
-
504
- const ghost = document.createElement("div");
505
- ghost.className = "ifc-card-ghost";
506
- ghost.setAttribute("aria-hidden", "true");
507
- ghost.style.display = "none";
508
- // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
509
- ghost.style.left = "0px";
510
- ghost.style.top = "0px";
511
-
512
- const dot = document.createElement("div");
513
- dot.className = "ifc-card-dot";
514
- const num = document.createElement("div");
515
- num.className = "ifc-card-num";
516
-
517
- ghost.appendChild(dot);
518
- ghost.appendChild(num);
519
-
520
- return { btn, ghost, dot, num };
521
- }
522
-
523
- #attachUi() {
524
- // Важно: container должен быть position:relative (в index.html уже так).
525
- this.container.appendChild(this._ui.btn);
526
- this.container.appendChild(this._ui.ghost);
527
- }
528
-
529
- #bindEvents() {
530
- this._onBtnClick = (e) => {
531
- // Не даём событию уйти в canvas/OrbitControls и не ставим метку "тем же кликом".
532
- try { e.preventDefault(); } catch (_) {}
533
- try { e.stopPropagation(); } catch (_) {}
534
- try { e.stopImmediatePropagation?.(); } catch (_) {}
535
- this.startPlacement();
536
- };
537
- this._ui.btn.addEventListener("click", this._onBtnClick, { passive: false });
538
-
539
- this._onKeyDown = (e) => {
540
- if (!this._placing) return;
541
- if (e.key === "Escape") this.cancelPlacement();
542
- };
543
- window.addEventListener("keydown", this._onKeyDown);
544
-
545
- // Смещение контейнера (#app) относительно viewport может меняться при resize/scroll.
546
- // Обновляем кэш, чтобы призрак/метки не "плыли".
547
- this._onWindowResize = () => {
548
- this.#refreshContainerOffset();
549
- if (this._placing) this.#syncGhost();
550
- };
551
- this._onWindowScroll = () => {
552
- this.#refreshContainerOffset();
553
- if (this._placing) this.#syncGhost();
554
- };
555
- window.addEventListener("resize", this._onWindowResize, { passive: true });
556
- // scroll слушаем в capture, чтобы ловить скролл вложенных контейнеров
557
- window.addEventListener("scroll", this._onWindowScroll, true);
558
-
559
- const dom = this.viewer?.renderer?.domElement;
560
- if (!dom) return;
561
-
562
- this._onPointerMove = (e) => {
563
- if (!this._placing) return;
564
- this.#updateGhostFromClient(e.clientX, e.clientY);
565
- };
566
- dom.addEventListener("pointermove", this._onPointerMove, { passive: true });
567
-
568
- // Best-effort: более частые координаты, чем pointermove (Chrome).
569
- this._onPointerRawUpdate = (e) => {
570
- if (!this._placing) return;
571
- this.#updateGhostFromClient(e.clientX, e.clientY);
572
- };
573
- try { dom.addEventListener("pointerrawupdate", this._onPointerRawUpdate, { passive: true }); } catch (_) {}
574
-
575
- this._onPointerDownCapture = (e) => {
576
- if (!this._placing) return;
577
- // Только ЛКМ ставит метку. Остальные кнопки не блокируем (например, колесо/ПКМ).
578
- if (e.button !== 0) return;
579
-
580
- // Блокируем другие контроллеры (OrbitControls/MMB/RMB) на время постановки.
581
- try { e.preventDefault(); } catch (_) {}
582
- try { e.stopPropagation(); } catch (_) {}
583
- try { e.stopImmediatePropagation?.(); } catch (_) {}
584
-
585
- const hit = this.#pickModelPoint(e.clientX, e.clientY);
586
- if (!hit) {
587
- this.#log("placeAttempt:no-hit", {});
588
- return; // остаёмся в режиме, пользователь может кликнуть ещё раз
589
- }
590
- this.#createMarkerAtHit(hit);
591
- this.cancelPlacement(); // по ТЗ: “вторым кликом устанавливаем”
592
- };
593
- dom.addEventListener("pointerdown", this._onPointerDownCapture, { capture: true, passive: false });
594
- }
595
-
596
- #setGhostVisible(visible) {
597
- if (!this._ui?.ghost) return;
598
- this._ui.ghost.style.display = visible ? "block" : "none";
599
- }
600
-
601
- #refreshContainerOffset() {
602
- const cr = this.container?.getBoundingClientRect?.();
603
- if (!cr) {
604
- this._containerOffset.left = 0;
605
- this._containerOffset.top = 0;
606
- this._containerOffsetValid = false;
607
- return;
608
- }
609
- this._containerOffset.left = cr.left || 0;
610
- this._containerOffset.top = cr.top || 0;
611
- this._containerOffsetValid = true;
612
- }
613
-
614
- #applyGhostTransform() {
615
- const g = this._ui?.ghost;
616
- if (!g) return;
617
- g.style.transform = `translate3d(${this._ghostPos.x}px, ${this._ghostPos.y}px, 0) translate(-50%, -50%)`;
618
- }
619
-
620
- #updateGhostFromClient(clientX, clientY) {
621
- this._lastPointer = { x: clientX, y: clientY };
622
- if (!this._containerOffsetValid) this.#refreshContainerOffset();
623
- const x = (clientX - this._containerOffset.left);
624
- const y = (clientY - this._containerOffset.top);
625
- this._ghostPos.x = x;
626
- this._ghostPos.y = y;
627
- // Обновляем transform сразу в обработчике — без ожидания RAF.
628
- this.#applyGhostTransform();
629
- }
630
-
631
- #syncGhost() {
632
- const g = this._ui?.ghost;
633
- if (!g) return;
634
- this._ui.num.textContent = String(this._nextId);
635
- // Число может меняться (id), позиция — из последних координат курсора.
636
- this.#updateGhostFromClient(this._lastPointer.x, this._lastPointer.y);
637
- }
638
-
639
- #pickModelPoint(clientX, clientY) {
640
- const model = this.viewer?.activeModel;
641
- const camera = this.viewer?.camera;
642
- const dom = this.viewer?.renderer?.domElement;
643
- if (!model || !camera || !dom) return null;
644
-
645
- const rect = dom.getBoundingClientRect?.();
646
- if (!rect || rect.width <= 0 || rect.height <= 0) return null;
647
-
648
- const x = ((clientX - rect.left) / rect.width) * 2 - 1;
649
- const y = -(((clientY - rect.top) / rect.height) * 2 - 1);
650
- this._ndc.set(x, y);
651
-
652
- this._raycaster.setFromCamera(this._ndc, camera);
653
- const hits = this._raycaster.intersectObject(model, true);
654
- if (!hits || hits.length <= 0) return null;
655
-
656
- // ВАЖНО: у модели могут быть контурные линии/оверлеи (LineSegments),
657
- // которые перехватывают hit раньше "реального" Mesh фасада.
658
- // Для постановки метки выбираем первый hit именно по Mesh.
659
- let best = null;
660
- for (const h of hits) {
661
- if (!h || !h.point) continue;
662
- const obj = h.object;
663
- if (obj && obj.isMesh) { best = h; break; }
664
- }
665
- // fallback: если Mesh не найден (редко), берём первый валидный hit
666
- if (!best) {
667
- for (const h of hits) {
668
- if (h && h.point) { best = h; break; }
669
- }
670
- }
671
-
672
- if (!best || !best.point) return null;
673
- return best;
674
- }
675
-
676
- #createMarkerAtHit(hit) {
677
- const model = this.viewer?.activeModel;
678
- if (!model) return;
679
-
680
- const id = this._nextId++;
681
-
682
- // Храним локальную координату модели, чтобы метка оставалась “приклеенной” к модели
683
- this._tmpLocal.copy(hit.point);
684
- model.worldToLocal(this._tmpLocal);
685
-
686
- const sceneState = this.#captureSceneState();
687
- const marker = this.#createMarkerFromData({
688
- id,
689
- localPoint: { x: this._tmpLocal.x, y: this._tmpLocal.y, z: this._tmpLocal.z },
690
- sceneState,
691
- }, true);
692
-
693
- this.#log("placed", {
694
- id,
695
- local: { x: +marker.localPoint.x.toFixed(4), y: +marker.localPoint.y.toFixed(4), z: +marker.localPoint.z.toFixed(4) },
696
- sceneState: sceneState ? { hasCamera: !!sceneState.camera, hasModel: !!sceneState.modelTransform, hasClip: !!sceneState.clipping } : null,
697
- });
698
- }
699
-
700
- #createMarkerElement(id) {
701
- const el = document.createElement("div");
702
- el.className = "ifc-card-marker";
703
- el.setAttribute("data-id", String(id));
704
- el.innerHTML = `<div class="ifc-card-dot"></div><div class="ifc-card-num">${id}</div>`;
705
- // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
706
- el.style.left = "0px";
707
- el.style.top = "0px";
708
- this.container.appendChild(el);
709
- return el;
710
- }
711
-
712
- #createMarkerFromData(data, emitPlacedEvent) {
713
- if (!data) return null;
714
- const localPoint = data.localPoint || {};
715
- const marker = new CardMarker({
716
- id: data.id,
717
- localPoint: new THREE.Vector3(
718
- Number(localPoint.x) || 0,
719
- Number(localPoint.y) || 0,
720
- Number(localPoint.z) || 0
721
- ),
722
- el: this.#createMarkerElement(data.id),
723
- sceneState: data.sceneState || null,
724
- });
725
- this._markers.push(marker);
726
-
727
- const onMarkerPointerDown = (e) => {
728
- // Важно: не даём клику попасть в canvas/OrbitControls
729
- try { e.preventDefault(); } catch (_) {}
730
- try { e.stopPropagation(); } catch (_) {}
731
- try { e.stopImmediatePropagation?.(); } catch (_) {}
732
- // если были в режиме постановки — выходим
733
- try { this.cancelPlacement(); } catch (_) {}
734
-
735
- this.#dispatchCardEvent("ifcviewer:card-click", {
736
- id: marker.id,
737
- sceneState: marker.sceneState || null,
738
- });
739
- // "Долеталка" камеры: быстрый старт + мягкий конец
740
- this.#animateToSceneState(marker.sceneState, 550);
741
- };
742
- // capture-phase, чтобы обогнать любые handlers на canvas
743
- try { marker.el.addEventListener("pointerdown", onMarkerPointerDown, { capture: true, passive: false }); } catch (_) {
744
- try { marker.el.addEventListener("pointerdown", onMarkerPointerDown); } catch (_) {}
745
- }
746
-
747
- if (emitPlacedEvent) {
748
- this.#dispatchCardEvent("ifcviewer:card-placed", {
749
- id: marker.id,
750
- localPoint: { x: marker.localPoint.x, y: marker.localPoint.y, z: marker.localPoint.z },
751
- sceneState: marker.sceneState || null,
752
- });
753
- }
754
-
755
- return marker;
756
- }
757
-
758
- #clearMarkers() {
759
- try { this._markers.forEach((m) => m?.el?.remove?.()); } catch (_) {}
760
- this._markers.length = 0;
761
- }
762
-
763
- setCardMarkers(items) {
764
- if (!Array.isArray(items)) return;
765
- this.#clearMarkers();
766
-
767
- let maxNumericId = null;
768
- for (const item of items) {
769
- const marker = this.#createMarkerFromData(item, false);
770
- if (marker && typeof marker.id === "number" && Number.isFinite(marker.id)) {
771
- maxNumericId = (maxNumericId == null) ? marker.id : Math.max(maxNumericId, marker.id);
772
- }
773
- }
774
- if (maxNumericId != null) this._nextId = Math.max(1, Math.floor(maxNumericId) + 1);
775
- }
776
-
777
- getCardMarkers() {
778
- return this._markers.map((m) => ({
779
- id: m.id,
780
- localPoint: { x: m.localPoint.x, y: m.localPoint.y, z: m.localPoint.z },
781
- sceneState: m.sceneState || null,
782
- }));
783
- }
784
-
785
- #startRaf() {
786
- const tick = () => {
787
- this._raf = requestAnimationFrame(tick);
788
- this.#updateMarkerScreenspace();
789
- };
790
- this._raf = requestAnimationFrame(tick);
791
- }
792
-
793
- #updateMarkerScreenspace() {
794
- const model = this.viewer?.activeModel;
795
- const camera = this.viewer?.camera;
796
- const dom = this.viewer?.renderer?.domElement;
797
- if (!camera || !dom) return;
798
-
799
- const rect = dom.getBoundingClientRect?.();
800
- if (!rect || rect.width <= 0 || rect.height <= 0) return;
801
-
802
- const w = rect.width;
803
- const h = rect.height;
804
-
805
- for (const m of this._markers) {
806
- if (!m || !m.el) continue;
807
-
808
- if (!model) {
809
- m.el.style.display = "none";
810
- continue;
811
- }
812
-
813
- // local -> world (учитывает позицию/поворот/scale модели)
814
- this._tmpV.copy(m.localPoint);
815
- model.localToWorld(this._tmpV);
816
-
817
- const ndc = this._tmpV.project(camera);
818
-
819
- // Если точка за камерой или далеко за пределами — скрываем
820
- const inFront = Number.isFinite(ndc.z) && ndc.z >= -1 && ndc.z <= 1;
821
- if (!inFront) {
822
- m.el.style.display = "none";
823
- continue;
824
- }
825
-
826
- const x = (ndc.x * 0.5 + 0.5) * w;
827
- const y = (-ndc.y * 0.5 + 0.5) * h;
828
-
829
- if (!Number.isFinite(x) || !Number.isFinite(y)) {
830
- m.el.style.display = "none";
831
- continue;
832
- }
833
-
834
- m.el.style.display = "block";
835
- m.el.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
836
- }
837
- }
838
- }
6
+ export class CardPlacementController extends LabelPlacementController {}
839
7