s3m-three 0.3.6 → 0.3.8

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 (92) hide show
  1. package/dist/anim/Animator.d.ts +111 -0
  2. package/dist/anim/Animator.d.ts.map +1 -0
  3. package/dist/anim/Animator.js +382 -0
  4. package/dist/anim/Animator.js.map +1 -0
  5. package/dist/anim/Path.d.ts +30 -0
  6. package/dist/anim/Path.d.ts.map +1 -0
  7. package/dist/anim/Path.js +100 -0
  8. package/dist/anim/Path.js.map +1 -0
  9. package/dist/anim/easing.d.ts +70 -0
  10. package/dist/anim/easing.d.ts.map +1 -0
  11. package/dist/anim/easing.js +170 -0
  12. package/dist/anim/easing.js.map +1 -0
  13. package/dist/anim/index.d.ts +6 -0
  14. package/dist/anim/index.d.ts.map +1 -0
  15. package/dist/anim/index.js +4 -0
  16. package/dist/anim/index.js.map +1 -0
  17. package/dist/browser/assets/{s3mWorker-hZY5KqWF.js → s3mWorker-D7AV6O30.js} +1 -1
  18. package/dist/browser/s3m-three.iife.ext-three.js +60 -22
  19. package/dist/browser/s3m-three.iife.js +60 -22
  20. package/dist/core/TextureDecode.d.ts +22 -1
  21. package/dist/core/TextureDecode.d.ts.map +1 -1
  22. package/dist/core/TextureDecode.js +47 -3
  23. package/dist/core/TextureDecode.js.map +1 -1
  24. package/dist/core/TileGeometry.d.ts +92 -0
  25. package/dist/core/TileGeometry.d.ts.map +1 -0
  26. package/dist/core/TileGeometry.js +607 -0
  27. package/dist/core/TileGeometry.js.map +1 -0
  28. package/dist/core/types.d.ts +16 -0
  29. package/dist/core/types.d.ts.map +1 -1
  30. package/dist/index.d.ts +3 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +1 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/render/EdgeLines.d.ts +62 -14
  35. package/dist/render/EdgeLines.d.ts.map +1 -1
  36. package/dist/render/EdgeLines.js +97 -8
  37. package/dist/render/EdgeLines.js.map +1 -1
  38. package/dist/render/FeatureStyleManager.d.ts +17 -1
  39. package/dist/render/FeatureStyleManager.d.ts.map +1 -1
  40. package/dist/render/FeatureStyleManager.js +14 -4
  41. package/dist/render/FeatureStyleManager.js.map +1 -1
  42. package/dist/render/GeometryBuilder.d.ts +8 -10
  43. package/dist/render/GeometryBuilder.d.ts.map +1 -1
  44. package/dist/render/GeometryBuilder.js +77 -555
  45. package/dist/render/GeometryBuilder.js.map +1 -1
  46. package/dist/render/MergeVertices.d.ts +7 -0
  47. package/dist/render/MergeVertices.d.ts.map +1 -1
  48. package/dist/render/MergeVertices.js +10 -1
  49. package/dist/render/MergeVertices.js.map +1 -1
  50. package/dist/render/S3MViewer.d.ts +218 -9
  51. package/dist/render/S3MViewer.d.ts.map +1 -1
  52. package/dist/render/S3MViewer.js +772 -68
  53. package/dist/render/S3MViewer.js.map +1 -1
  54. package/dist/render/StyleMaterial.d.ts +19 -0
  55. package/dist/render/StyleMaterial.d.ts.map +1 -1
  56. package/dist/render/StyleMaterial.js +37 -0
  57. package/dist/render/StyleMaterial.js.map +1 -1
  58. package/dist/render/TextureFactory.d.ts +2 -1
  59. package/dist/render/TextureFactory.d.ts.map +1 -1
  60. package/dist/render/TextureFactory.js +30 -6
  61. package/dist/render/TextureFactory.js.map +1 -1
  62. package/dist/tileset/S3MTileset.d.ts +6 -2
  63. package/dist/tileset/S3MTileset.d.ts.map +1 -1
  64. package/dist/tileset/S3MTileset.js +17 -7
  65. package/dist/tileset/S3MTileset.js.map +1 -1
  66. package/dist/worker/S3MWorkerClient.d.ts +12 -4
  67. package/dist/worker/S3MWorkerClient.d.ts.map +1 -1
  68. package/dist/worker/S3MWorkerClient.js +12 -8
  69. package/dist/worker/S3MWorkerClient.js.map +1 -1
  70. package/dist/worker/s3mWorker.js +11 -3
  71. package/dist/worker/s3mWorker.js.map +1 -1
  72. package/docs/ANIMATION.md +534 -0
  73. package/docs/API.md +4 -0
  74. package/package.json +1 -1
  75. package/src/anim/Animator.ts +460 -0
  76. package/src/anim/Path.ts +107 -0
  77. package/src/anim/easing.ts +195 -0
  78. package/src/anim/index.ts +10 -0
  79. package/src/core/TextureDecode.ts +69 -3
  80. package/src/core/TileGeometry.ts +745 -0
  81. package/src/core/types.ts +8 -0
  82. package/src/index.ts +10 -0
  83. package/src/render/EdgeLines.ts +131 -15
  84. package/src/render/FeatureStyleManager.ts +12 -4
  85. package/src/render/GeometryBuilder.ts +91 -617
  86. package/src/render/MergeVertices.ts +11 -1
  87. package/src/render/S3MViewer.ts +866 -67
  88. package/src/render/StyleMaterial.ts +54 -1
  89. package/src/render/TextureFactory.ts +42 -8
  90. package/src/tileset/S3MTileset.ts +25 -9
  91. package/src/worker/S3MWorkerClient.ts +18 -9
  92. package/src/worker/s3mWorker.ts +24 -6
@@ -22,12 +22,14 @@
22
22
  */
23
23
  import * as THREE from 'three';
24
24
  import { usableGeoBounds } from '../tileset/S3MTileset.js';
25
- import { setMaxAnisotropy, setTextureOffThreadDecode } from './TextureFactory.js';
25
+ import { setMaxAnisotropy, setCompressedTexturesSupported, setTextureOffThreadDecode } from './TextureFactory.js';
26
26
  import { decodeTextureWithWorker } from '../worker/S3MWorkerClient.js';
27
27
  import { STYLE, STYLE_LABELS, SELECT_MODE, DEFAULT_STYLE, createSharedUniforms, createOutlineMaterial, } from './StyleMaterial.js';
28
28
  import { applyPointCloudStyle, isOwnedPointCloudMaterial } from './PointCloudMaterial.js';
29
29
  import { Picker } from './Picker.js';
30
- import { buildFeatureEdgeSegments, buildThickLineGeometry, createLineSharedUniforms, createThickLineMaterial, } from './EdgeLines.js';
30
+ import { Animator } from '../anim/Animator.js';
31
+ import { Path } from '../anim/Path.js';
32
+ import { buildFeatureEdgeSegments, buildPositionBatchMap, buildThickLineGeometry, createLineSharedUniforms, createThickLineMaterial, positionQuantKey, } from './EdgeLines.js';
31
33
  import { mergeVerticesByPosition } from './MergeVertices.js';
32
34
  import { resolveFeature, measureSegments, buildAttributes, buildInstanceLookup, pickEntryId, } from '../core/FeatureInfo.js';
33
35
  import { AttributeQuery } from '../core/AttributeQuery.js';
@@ -46,6 +48,31 @@ function styledMaterialOf(mesh) {
46
48
  function isPointCloudObject(o) {
47
49
  return o.isPoints === true;
48
50
  }
51
+ /* ------------------------------------------------------------------ 可动画的样式键 */
52
+ /**
53
+ * 能逐帧插值的标量样式键。
54
+ *
55
+ * 判据:写一次只是「改一个 uniform 或一个字段」,不重建几何、不换 program。
56
+ * `mode` / `shading` / `edges` 不在此列——它们是结构变更,只能编排不能插值。
57
+ */
58
+ const STYLE_SCALAR_KEYS = [
59
+ 'opacity',
60
+ 'floorHeight',
61
+ 'selectOpacity',
62
+ 'selectEmissive',
63
+ 'selectElevation',
64
+ 'dimFactor',
65
+ 'texMix',
66
+ 'roofThreshold',
67
+ 'ambientGain',
68
+ 'edgeWidth',
69
+ 'edgeOpacity',
70
+ 'outlineWidth',
71
+ ];
72
+ /** 能逐帧插值的颜色键(在线性空间插值,与 shader 消费端一致) */
73
+ const STYLE_COLOR_KEYS = ['colorA', 'colorB', 'colorC', 'selectColor', 'edgeColor'];
74
+ /** 可动画的单体属性 */
75
+ const FEATURE_PROPS = ['translation', 'elevation', 'opacity', 'color'];
49
76
  /* ------------------------------------------------------------------ 图层 */
50
77
  export class S3MViewer {
51
78
  options;
@@ -63,14 +90,21 @@ export class S3MViewer {
63
90
  camera = null;
64
91
  picker = null;
65
92
  uniforms;
93
+ /** 当前**显示**的样式(动画推进中会逐帧变) */
66
94
  style;
95
+ /** 用户想要的样式(getStyle 返回它,动画目标以它为准) */
96
+ _styleTarget;
67
97
  outlineMaterial;
68
98
  /** 等宽线共享的分辨率 uniform(全局棱线 + 选中棱线共用) */
69
99
  lineShared;
70
- /** 全局棱线材质 */
100
+ /** 全局棱线材质(外观 uniform 的持有者,逐网格棱线材质共享它的对象) */
71
101
  edgeMaterial;
72
- /** 选中棱线材质 */
102
+ /** 选中棱线材质(同上,选中棱线的逐网格材质共享它的对象) */
73
103
  selectionEdgeMaterial;
104
+ /** 全局棱线的外观 uniform:逐网格棱线材质直接复用这些对象 */
105
+ _edgeStyleUniforms;
106
+ /** 选中棱线的外观 uniform */
107
+ _selEdgeStyleUniforms;
74
108
  /** 3D 物理地表面 / 基坑开挖管理器 */
75
109
  groundManager;
76
110
  /** 多数据集生命周期与锚点管理器 */
@@ -105,11 +139,34 @@ export class S3MViewer {
105
139
  _selectionEdges = null;
106
140
  _selectionEdgeMeshes = [];
107
141
  _edgesEnabled = false;
142
+ /** 瓦片淡入通道的自增序号(不用 pickId:pickId 会被回收复用) */
143
+ _tileFadeSeq = 0;
144
+ /** setMode 编排的代次,用来作废被新调用顶掉的旧编排 */
145
+ _modeGen = 0;
146
+ /** 路径运动的规格表:通道 key → 路径 + 偏移 */
147
+ _pathSpecs = new Map();
148
+ /** 路径采样临时对象,避免每帧 new */
149
+ _pathScratch = new Float32Array(3);
108
150
  /** 预制棱线缓存(Crease Cache):从外部 source-creases 载入的全局统一 LineSegments,性能最高、视觉最干净 */
109
151
  _creaseLines = null;
152
+ /** 数据自带的棱线对象(LineSegments),改棱线颜色时只刷这些,不再全场景 traverse */
153
+ _nativeEdgeLines = new Set();
154
+ /** 点云对象集合:透明度动画时只刷它们,避免每帧遍历全部 pickables */
155
+ _pointClouds = new Set();
156
+ /** 当前材质是否处于 transparent 状态,用来避免逐帧重复切换 program */
157
+ _opacityTransparent = false;
158
+ /**
159
+ * 统一动画调度器。
160
+ *
161
+ * 所有「有过渡」的样式 / 单体 / 棱线变更都经由它推进;公开 API 只写目标值,
162
+ * 真正的逐帧写入由注册在这里的通道完成。
163
+ */
164
+ animator = new Animator();
110
165
  /** 业务属性查询(可选,配了 `attributes` 才有) */
111
166
  attributeQuery = null;
112
167
  _enuMatrix = new THREE.Matrix4();
168
+ /** 颜色换算用的临时对象,避免每帧 new */
169
+ _colorScratch = new THREE.Color();
113
170
  _needsRepaint = true;
114
171
  _frame = 0;
115
172
  _fps = { value: 0, last: 0 };
@@ -168,23 +225,37 @@ export class S3MViewer {
168
225
  this._featureStyleManager = new FeatureStyleManager(() => this.style.floorHeight, () => this._requestRepaint(), () => {
169
226
  if (this._selection)
170
227
  this._syncSelectionStyle();
171
- }, () => this.getAllMeshes(), (mesh) => this._applyOverridesToMesh(mesh));
228
+ }, () => this.getAllMeshes(), (mesh) => this._applyOverridesToMesh(mesh),
229
+ // 图层自身是否半透明:全局透明度改走 uOpacity 后,材质 opacity 不再代表它
230
+ () => this._opacityTransparent);
172
231
  this.uniforms = createSharedUniforms();
173
232
  // 纹理解码优先派给共享解析 Worker(崩溃自动回主线程,见 decodeTextureWithWorker)
174
233
  setTextureOffThreadDecode(decodeTextureWithWorker);
175
234
  this.style = { ...DEFAULT_STYLE, ...(options.style ?? {}) };
235
+ this._styleTarget = { ...this.style };
236
+ this._opacityTransparent = (this.style.opacity ?? 1) < 0.999;
237
+ this._applyStyleUniforms();
238
+ this._registerAnimChannels();
239
+ // 动画启动必须把按需驱动的帧循环踢起来:MapLibre 空闲时不渲染,
240
+ // 不踢的话动画「卡住不动」,直到别的什么碰巧触发了重绘
241
+ this.animator.onActive = () => this._requestRepaint();
176
242
  this.outlineMaterial = createOutlineMaterial(this.uniforms);
177
243
  this.lineShared = createLineSharedUniforms();
178
- this.edgeMaterial = createThickLineMaterial(this.lineShared, {
179
- color: this.style.edgeColor,
180
- opacity: this.style.edgeOpacity ?? 0.45,
181
- width: this.style.edgeWidth ?? 1.2,
182
- });
183
- this.selectionEdgeMaterial = createThickLineMaterial(this.lineShared, {
184
- color: this.style.outlineColor ?? this.style.selectColor,
185
- opacity: 1,
186
- width: this.style.outlineWidthPx ?? 3,
187
- });
244
+ // 棱线外观 uniform:全局棱线材质与逐网格棱线材质**共用同一批对象**,
245
+ // _syncEdgeStyle 改一次,所有棱线(含淡入乘子)同时生效,保持 O(1)。
246
+ this._edgeStyleUniforms = {
247
+ uColor: { value: new THREE.Color(this.style.edgeColor) },
248
+ uWidth: { value: Math.max(0.1, this.style.edgeWidth ?? 1.5) },
249
+ uOpacity: { value: 0.6 },
250
+ };
251
+ this.edgeMaterial = createThickLineMaterial(this.lineShared, {}, this._edgeStyleUniforms);
252
+ this._selEdgeStyleUniforms = {
253
+ uColor: { value: new THREE.Color(this.style.outlineColor ?? this.style.selectColor) },
254
+ uWidth: { value: Math.max(0.1, this.style.outlineWidthPx ?? 3) },
255
+ uOpacity: { value: 1 },
256
+ uElevation: { value: this.style.selectElevation ?? 0 },
257
+ };
258
+ this.selectionEdgeMaterial = createThickLineMaterial(this.lineShared, {}, this._selEdgeStyleUniforms);
188
259
  // 关键:style.edges 是个开关,但构造函数从没据此启用过棱线,导致
189
260
  // `style: { edges: true }` 形同虚设、_edgesEnabled 永远是 false。
190
261
  // 这里按 style 实际值调一次 setEdges,让开关真正生效(与 setEdges 后来的手工调用一致)。
@@ -208,15 +279,22 @@ export class S3MViewer {
208
279
  });
209
280
  r.autoClear = false;
210
281
  r.setPixelRatio(1);
211
- // 白模 albedo 接近 1,不做色调映射会过曝成一片纯白、丢失明暗关系
212
- r.toneMapping = THREE.ACESFilmicToneMapping;
213
- r.toneMappingExposure = 1.0;
282
+ // 允许外部传入色调映射模式,默认使用 THREE.NoToneMapping 还原真实材质与底图通透度,避免 ACESFilmic 压暗阴影与偏色
283
+ r.toneMapping = this.options.toneMapping !== undefined ? this.options.toneMapping : THREE.NoToneMapping;
284
+ r.toneMappingExposure = this.options.toneMappingExposure ?? 1.0;
214
285
  return r;
215
286
  }
287
+ /** 按 GL 能力开/关 DXT 压缩直传:两个 s3tc 扩展都要在(srgb 缺了贴图会发白失配) */
288
+ _syncTextureCapabilities(gl) {
289
+ const s3tc = !!gl.getExtension('WEBGL_compressed_texture_s3tc');
290
+ const s3tcSrgb = !!gl.getExtension('WEBGL_compressed_texture_s3tc_srgb');
291
+ setCompressedTexturesSupported(s3tc && s3tcSrgb);
292
+ }
216
293
  mount(canvas, gl) {
217
294
  this.canvas = canvas;
218
295
  this.renderer = this._createRenderer(canvas, gl);
219
296
  setMaxAnisotropy(this.renderer.capabilities.getMaxAnisotropy());
297
+ this._syncTextureCapabilities(gl);
220
298
  this.scene = new THREE.Scene();
221
299
  this.scene.add(this.groundManager.group);
222
300
  this._addLights();
@@ -254,6 +332,7 @@ export class S3MViewer {
254
332
  }
255
333
  this.renderer = this._createRenderer(this.canvas, gl);
256
334
  setMaxAnisotropy(this.renderer.capabilities.getMaxAnisotropy());
335
+ this._syncTextureCapabilities(gl);
257
336
  this.picker?.dispose();
258
337
  this.picker = new Picker(this.renderer);
259
338
  // 共享 uniform / 材质引用不变,three 重新编译着色器时会自然接管;
@@ -279,6 +358,11 @@ export class S3MViewer {
279
358
  this._selectionEdges = null;
280
359
  this._smidMeshes.clear();
281
360
  this._meshHeight.clear();
361
+ // 场景已经清空,还挂着的动画通道(瓦片淡入 / 单体位移)不能再对着死对象写
362
+ this.animator.clear();
363
+ this.animator.unregisterPrefix('tile.');
364
+ this.animator.unregisterPrefix('feature.');
365
+ this._pathSpecs.clear();
282
366
  this._heightMin = Infinity;
283
367
  this._heightMax = -Infinity;
284
368
  this.renderer?.dispose();
@@ -322,7 +406,14 @@ export class S3MViewer {
322
406
  * 动态设置光照配置
323
407
  */
324
408
  setLight(options) {
325
- Object.assign(this._lightOptions, options);
409
+ const normalized = { ...options };
410
+ if (normalized.mainColor !== undefined && normalized.keyLightColor === undefined) {
411
+ normalized.keyLightColor = normalized.mainColor;
412
+ }
413
+ if (normalized.mainIntensity !== undefined && normalized.keyLightIntensity === undefined) {
414
+ normalized.keyLightIntensity = normalized.mainIntensity;
415
+ }
416
+ Object.assign(this._lightOptions, normalized);
326
417
  this._applyLightOptions();
327
418
  this._updateLights();
328
419
  this._needsRepaint = true;
@@ -334,6 +425,28 @@ export class S3MViewer {
334
425
  getLight() {
335
426
  return { ...this._lightOptions };
336
427
  }
428
+ /**
429
+ * 动态设置色调映射模式与曝光度
430
+ */
431
+ setToneMapping(toneMapping, exposure = 1.0) {
432
+ this.options.toneMapping = toneMapping;
433
+ this.options.toneMappingExposure = exposure;
434
+ if (this.renderer) {
435
+ this.renderer.toneMapping = toneMapping;
436
+ this.renderer.toneMappingExposure = exposure;
437
+ this._needsRepaint = true;
438
+ this.triggerRepaint();
439
+ }
440
+ }
441
+ /**
442
+ * 获取当前色调映射模式与曝光度
443
+ */
444
+ getToneMapping() {
445
+ return {
446
+ toneMapping: this.renderer ? this.renderer.toneMapping : (this.options.toneMapping ?? THREE.NoToneMapping),
447
+ toneMappingExposure: this.renderer ? this.renderer.toneMappingExposure : (this.options.toneMappingExposure ?? 1.0),
448
+ };
449
+ }
337
450
  /**
338
451
  * 更新光照位置与方向:
339
452
  * - 'headlamp': 随地图方位角 bearing 旋转,主光始终在镜头上方,受光面面向镜头;
@@ -496,6 +609,242 @@ export class S3MViewer {
496
609
  setFeaturesStyle(smids, style) {
497
610
  this._featureStyleManager.setFeaturesStyle(smids, style, this._meshesOf(smids));
498
611
  }
612
+ /**
613
+ * 把单体平移到新位置(米,场景 ENU 坐标的增量)。
614
+ *
615
+ * 平移写进状态纹理第 2 行,所以拾取、选中描边、棱线都会自动跟随——
616
+ * 但**视锥剔除不会**:three 用的是几何原始包围球,移出包围球后整块瓦片会被剔掉。
617
+ * 所以这里顺手把「有位移」的网格关掉 frustumCulled,归零时再恢复。
618
+ */
619
+ moveFeature(smid, translation, transition) {
620
+ const key = this._ensureFeatureChannel(smid, 'translation');
621
+ this.animator.to(key, translation, transition);
622
+ }
623
+ /** 让单体沿某个轴移动的便捷写法(单位米) */
624
+ moveFeatureBy(smid, delta, transition) {
625
+ const cur = this._featureStyleManager.getFeatureStyle(smid)?.translation ?? [0, 0, 0];
626
+ this.moveFeature(smid, [cur[0] + delta[0], cur[1] + delta[1], cur[2] + delta[2]], transition);
627
+ }
628
+ /**
629
+ * 让单体沿折线运动。
630
+ *
631
+ * 路径先做**弧长参数化**(见 anim/Path.ts):缓动作用在「已走距离」上,而不是
632
+ * 顶点索引上,所以顶点疏密不均也不会忽快忽慢。
633
+ *
634
+ * 实现上没有引入新的 track 类型——把「进度 0→1」当成一条普通补间,通道的 write
635
+ * 把进度映射成弧长再查表得位置。这样打断、循环、缓动、预算全部复用现有调度器。
636
+ *
637
+ * 注意:不要和 `moveFeature` 同时驱动同一个单体,两者都写 `translation`。
638
+ */
639
+ followPath(smid, points, opts = {}) {
640
+ const path = points instanceof Path ? points : new Path(points, { closed: opts.closed });
641
+ if (path.length <= 0)
642
+ return;
643
+ const offset = opts.offset ?? [0, 0, 0];
644
+ const duration = opts.duration ??
645
+ (opts.speed && opts.speed > 0 ? (path.length / opts.speed) * 1000 : 2000);
646
+ const key = `feature.${smid}.path`;
647
+ this._pathSpecs.set(key, { path, offset });
648
+ if (!this.animator.has(key)) {
649
+ this.animator.register(key, {
650
+ dim: 1,
651
+ // 每次都从起点开始:进度通道没有「当前值」的概念,循环时正好重置
652
+ read: (out) => {
653
+ out[0] = 0;
654
+ },
655
+ write: (v) => {
656
+ const spec = this._pathSpecs.get(key);
657
+ if (!spec)
658
+ return;
659
+ spec.path.sampleAt(v[0], this._pathScratch);
660
+ const meshes = this._meshesOf([smid]);
661
+ const cur = this._featureStyleManager.getFeatureStyle(smid) ?? {};
662
+ this._featureStyleManager.setFeatureStyle(smid, {
663
+ ...cur,
664
+ translation: [
665
+ spec.offset[0] + this._pathScratch[0],
666
+ spec.offset[1] + this._pathScratch[1],
667
+ spec.offset[2] + this._pathScratch[2],
668
+ ],
669
+ }, meshes);
670
+ // 轨迹可能跑到原始包围球外,关掉视锥剔除免得整块瓦片被剔掉
671
+ for (const mesh of meshes)
672
+ mesh.frustumCulled = false;
673
+ },
674
+ });
675
+ }
676
+ const run = () => {
677
+ this.animator.to(key, 1, {
678
+ duration,
679
+ easing: opts.easing ?? 'linear',
680
+ onComplete: () => {
681
+ if (opts.loop)
682
+ run();
683
+ else
684
+ opts.onComplete?.();
685
+ },
686
+ });
687
+ };
688
+ run();
689
+ }
690
+ /** 停下路径运动(停在当前位置,不回弹) */
691
+ stopPath(smid) {
692
+ const key = `feature.${smid}.path`;
693
+ this.animator.cancel(key);
694
+ this.animator.unregister(key);
695
+ this._pathSpecs.delete(key);
696
+ }
697
+ /**
698
+ * 单体样式过渡:颜色 / 抬高 / 透明度 / 平移可以任意组合。
699
+ *
700
+ * 各属性各走一条通道,互不覆盖——同一个单体上「一边抬高一边变色」是两条独立的
701
+ * track,写回时都是「读当前 → 改一个字段 → 写回」,不会互相冲掉。
702
+ * `hidden` 不可插值,直接生效。
703
+ */
704
+ animateFeature(smid, style, transition) {
705
+ if (style.translation)
706
+ this.moveFeature(smid, style.translation, transition);
707
+ if (style.elevation != null) {
708
+ this.animator.to(this._ensureFeatureChannel(smid, 'elevation'), style.elevation, transition);
709
+ }
710
+ if (style.opacity != null) {
711
+ this.animator.to(this._ensureFeatureChannel(smid, 'opacity'), style.opacity, transition);
712
+ }
713
+ if (style.color) {
714
+ this._colorScratch.set(style.color);
715
+ this.animator.to(this._ensureFeatureChannel(smid, 'color'), [this._colorScratch.r, this._colorScratch.g, this._colorScratch.b], transition);
716
+ }
717
+ if (style.hidden != null) {
718
+ const cur = this._featureStyleManager.getFeatureStyle(smid) ?? {};
719
+ this.setFeatureStyle(smid, { ...cur, hidden: style.hidden });
720
+ }
721
+ }
722
+ /**
723
+ * 批量单体样式过渡,支持 `stagger` 错峰。
724
+ *
725
+ * 错峰是这类系统性价比最高的选项:一万个单体错峰 8ms,总时长不变,但每帧只推进
726
+ * 一小批,把峰值摊平——比任何「每帧上限」都自然。
727
+ */
728
+ animateFeatures(smids, style, transition) {
729
+ const stagger = transition?.stagger ?? 0;
730
+ if (stagger <= 0) {
731
+ for (const smid of smids)
732
+ this.animateFeature(smid, style, transition);
733
+ return;
734
+ }
735
+ const baseDelay = transition?.delay ?? 0;
736
+ for (let i = 0; i < smids.length; i++) {
737
+ this.animateFeature(smids[i], style, { ...transition, delay: baseDelay + i * stagger });
738
+ }
739
+ }
740
+ /**
741
+ * 切换着色模式,用 fade-through 代替硬切。
742
+ *
743
+ * `uMode` 是 int,插不了值;能做的就是「压暗 → 换 → 亮回来」。
744
+ * 编排走 onComplete 回调而不是 Promise 链,这样换模式发生在同一帧的回调里,
745
+ * 不会多出一帧的空白。返回的 Promise 在整段编排结束后 resolve。
746
+ */
747
+ setMode(mode, opts = {}) {
748
+ const d = Math.max(0, opts.duration ?? 300);
749
+ const dim = Math.min(1, Math.max(0.05, opts.dim ?? 0.35));
750
+ if (this.style.mode === mode)
751
+ return Promise.resolve();
752
+ if (d <= 0) {
753
+ this.setStyle({ mode });
754
+ return Promise.resolve();
755
+ }
756
+ const gen = ++this._modeGen;
757
+ return new Promise((resolve) => {
758
+ this.animator.to('style.fade', dim, {
759
+ duration: d,
760
+ easing: 'easeInOutQuad',
761
+ onComplete: () => {
762
+ // 中途又切了一次:这次编排作废,收尾交给新的那次
763
+ if (gen !== this._modeGen) {
764
+ resolve();
765
+ return;
766
+ }
767
+ this.setStyle({ mode });
768
+ this.animator.to('style.fade', 1, {
769
+ duration: d,
770
+ easing: 'easeInOutQuad',
771
+ onComplete: resolve,
772
+ });
773
+ },
774
+ });
775
+ });
776
+ }
777
+ /**
778
+ * 按需注册「单体属性」通道。
779
+ *
780
+ * 通道按 smid 惰性创建:绝大多数场景只动几十个单体,没必要给全城几万个 smid
781
+ * 预先建通道。`removeFeatureStyle` / `clearFeatureStyles` 会顺手回收。
782
+ *
783
+ * 写回统一走 `setFeatureStyle`:它内部已经按 `_meshesOf([smid])` 收敛脏网格,
784
+ * 所以单个单体动画每帧只重烘「含这个单体」的那一两块,不会全场景重算。
785
+ */
786
+ _ensureFeatureChannel(smid, prop) {
787
+ const key = `feature.${smid}.${prop}`;
788
+ if (this.animator.has(key))
789
+ return key;
790
+ const channel = prop === 'translation' || prop === 'color'
791
+ ? {
792
+ dim: 3,
793
+ read: (out) => {
794
+ if (prop === 'translation') {
795
+ const t = this._featureStyleManager.getFeatureStyle(smid)?.translation;
796
+ out[0] = t?.[0] ?? 0;
797
+ out[1] = t?.[1] ?? 0;
798
+ out[2] = t?.[2] ?? 0;
799
+ }
800
+ else {
801
+ // 没有自定义色时以图层主色为起点,插值才连续
802
+ const hex = this._featureStyleManager.getFeatureStyle(smid)?.color ?? this.style.colorA;
803
+ this._colorScratch.set(hex);
804
+ out[0] = this._colorScratch.r;
805
+ out[1] = this._colorScratch.g;
806
+ out[2] = this._colorScratch.b;
807
+ }
808
+ },
809
+ write: (v) => {
810
+ const meshes = this._meshesOf([smid]);
811
+ const cur = this._featureStyleManager.getFeatureStyle(smid) ?? {};
812
+ if (prop === 'translation') {
813
+ this._featureStyleManager.setFeatureStyle(smid, { ...cur, translation: [v[0], v[1], v[2]] }, meshes);
814
+ // 有位移就关掉视锥剔除,否则移出原始包围球后整块瓦片会凭空消失
815
+ const moving = Math.abs(v[0]) > 1e-6 || Math.abs(v[1]) > 1e-6 || Math.abs(v[2]) > 1e-6;
816
+ for (const mesh of meshes)
817
+ mesh.frustumCulled = !moving;
818
+ }
819
+ else {
820
+ const c = this._colorScratch.setRGB(v[0], v[1], v[2]);
821
+ this._featureStyleManager.setFeatureStyle(smid, { ...cur, color: `#${c.getHexString()}` }, meshes);
822
+ }
823
+ },
824
+ }
825
+ : {
826
+ dim: 1,
827
+ read: (out) => {
828
+ const st = this._featureStyleManager.getFeatureStyle(smid);
829
+ out[0] = (prop === 'elevation' ? st?.elevation : st?.opacity) ?? (prop === 'opacity' ? 1 : 0);
830
+ },
831
+ write: (v) => {
832
+ const cur = this._featureStyleManager.getFeatureStyle(smid) ?? {};
833
+ const next = prop === 'elevation' ? { ...cur, elevation: v[0] } : { ...cur, opacity: v[0] };
834
+ this._featureStyleManager.setFeatureStyle(smid, next, this._meshesOf([smid]));
835
+ },
836
+ };
837
+ this.animator.register(key, channel);
838
+ return key;
839
+ }
840
+ /** 回收某个单体的动画通道(单体被删除 / 样式被清空时调用) */
841
+ _releaseFeatureChannels(smid) {
842
+ for (const prop of FEATURE_PROPS)
843
+ this.animator.unregister(`feature.${smid}.${prop}`);
844
+ const pathKey = `feature.${smid}.path`;
845
+ this.animator.unregister(pathKey);
846
+ this._pathSpecs.delete(pathKey);
847
+ }
499
848
  /** 获取指定单体的自定义样式 */
500
849
  getFeatureStyle(smid) {
501
850
  return this._featureStyleManager.getFeatureStyle(smid);
@@ -506,10 +855,14 @@ export class S3MViewer {
506
855
  }
507
856
  /** 移除指定单体的自定义样式,恢复为图层全局样式 */
508
857
  removeFeatureStyle(smid) {
858
+ this._releaseFeatureChannels(smid);
509
859
  this._featureStyleManager.removeFeatureStyle(smid, this._meshesOf([smid]));
510
860
  }
511
861
  /** 清空所有单体的自定义样式 */
512
862
  clearFeatureStyles() {
863
+ for (const smid of this._featureStyleManager.getFeatureStyles().keys()) {
864
+ this._releaseFeatureChannels(smid);
865
+ }
513
866
  this._featureStyleManager.clearFeatureStyles();
514
867
  }
515
868
  /* ---------------------------------------------------------------- 按业务字段着色 */
@@ -696,6 +1049,7 @@ export class S3MViewer {
696
1049
  // 数据自带的棱线包:只跟着 edges 开关显示,不参与拾取、不参与着色
697
1050
  if (child.isLineSegments && child.userData.isEdgeLines) {
698
1051
  child.visible = this._edgesEnabled;
1052
+ this._nativeEdgeLines.add(child);
699
1053
  this._styleEdgeLine(child);
700
1054
  continue;
701
1055
  }
@@ -704,6 +1058,8 @@ export class S3MViewer {
704
1058
  const mesh = child;
705
1059
  if (!mesh.isMesh && !isPoints)
706
1060
  continue;
1061
+ if (isPoints)
1062
+ this._pointClouds.add(child);
707
1063
  const ud = mesh.userData;
708
1064
  ud.pickId = this._allocPickId();
709
1065
  ud.datasetId = entry.id;
@@ -730,12 +1086,13 @@ export class S3MViewer {
730
1086
  const mat = styledMaterialOf(mesh);
731
1087
  if (mat) {
732
1088
  const o = Math.min(1, Math.max(0.05, this.style.opacity ?? 1));
733
- mat.opacity = o;
1089
+ // 不写 mat.opacity:全局透明度走共享 uOpacity,材质自身 opacity 保留模型自带 alpha
734
1090
  mat.transparent = o < 0.999;
735
1091
  mat.depthWrite = o >= 0.999;
736
1092
  mat.flatShading = this.style.shading !== 'smooth';
737
1093
  mat.needsUpdate = true;
738
1094
  this._featureStyleManager.applyOverridesToMesh(mesh);
1095
+ this._startTileFade(mesh, mat);
739
1096
  }
740
1097
  }
741
1098
  // 选中状态也要跟着继承:LOD 细化 / 瓦片重载会换掉 mesh,
@@ -743,6 +1100,53 @@ export class S3MViewer {
743
1100
  this._replaySelectionOnto(mesh);
744
1101
  }
745
1102
  }
1103
+ /**
1104
+ * 新瓦片淡入。
1105
+ *
1106
+ * 每块网格有自己的材质实例,所以给一个逐材质的 `uTileFade` 就够,不需要动共享
1107
+ * uniform、也不需要重建任何东西。淡入期间该网格进透明队列(混合 + 排序),
1108
+ * 淡完立刻把 `transparent` 还给图层状态,避免长期留在透明通道里。
1109
+ *
1110
+ * 通道 key 用自增序号而不是 pickId:pickId 会被回收复用,用它会串到新瓦片上。
1111
+ */
1112
+ _startTileFade(mesh, mat) {
1113
+ const duration = this.style.fadeIn ?? 0;
1114
+ if (duration <= 0)
1115
+ return;
1116
+ const uFade = mat.userData.uTileFade;
1117
+ if (!uFade)
1118
+ return;
1119
+ uFade.value = 0;
1120
+ mat.transparent = true;
1121
+ // 淡入期间保持深度写入:否则能透过正在淡入的楼看到后面的东西,像在「漏」
1122
+ mat.depthWrite = true;
1123
+ const key = `tile.${this._tileFadeSeq++}.fade`;
1124
+ mesh.userData.tileFadeKey = key;
1125
+ this.animator.register(key, {
1126
+ dim: 1,
1127
+ read: (out) => {
1128
+ out[0] = uFade.value;
1129
+ },
1130
+ write: (v) => {
1131
+ uFade.value = v[0];
1132
+ },
1133
+ });
1134
+ this.animator.to(key, 1, {
1135
+ duration,
1136
+ easing: 'easeOutQuad',
1137
+ onComplete: () => {
1138
+ uFade.value = 1;
1139
+ mesh.userData.tileFadeKey = undefined;
1140
+ this.animator.unregister(key);
1141
+ // 淡入期间强制开了 transparent + depthWrite,结束时不能自己拍板关掉——
1142
+ // 图层可能本来就半透明、单体也可能还有淡化。交给淡化流程重新裁决一次。
1143
+ this._featureStyleManager.applyOverridesToMesh(mesh);
1144
+ if (!mat.transparent)
1145
+ mat.depthWrite = true;
1146
+ this._requestRepaint();
1147
+ },
1148
+ });
1149
+ }
746
1150
  /**
747
1151
  * 把「当前选中」重放到一块新登记的 mesh 上。
748
1152
  *
@@ -811,6 +1215,16 @@ export class S3MViewer {
811
1215
  _unregisterTile(node, entry) {
812
1216
  node.group.traverse((child) => {
813
1217
  const obj = child;
1218
+ if (child.isLineSegments && obj.userData?.isEdgeLines) {
1219
+ this._nativeEdgeLines.delete(child);
1220
+ }
1221
+ if (isPointCloudObject(child))
1222
+ this._pointClouds.delete(child);
1223
+ // 淡入还没结束就被淘汰:把通道收掉,否则会对着已释放的材质继续写
1224
+ if (obj.userData?.tileFadeKey) {
1225
+ this.animator.unregister(obj.userData.tileFadeKey);
1226
+ obj.userData.tileFadeKey = undefined;
1227
+ }
814
1228
  if (obj.userData?.pickId != null) {
815
1229
  this._pickables.delete(obj.userData.pickId);
816
1230
  this._releasePickId(obj.userData.pickId);
@@ -881,12 +1295,160 @@ export class S3MViewer {
881
1295
  }
882
1296
  /* ---------------------------------------------------------------- 样式 */
883
1297
  /** 动态设置图层整体透明度 (0.0 ~ 1.0) */
884
- setOpacity(opacity) {
885
- this.setStyle({ opacity });
1298
+ setOpacity(opacity, transition) {
1299
+ this.setStyle({ opacity }, transition);
886
1300
  }
887
- /** 合并并应用样式。只改 uniform 的项不会触发几何/着色器重建。 */
888
- setStyle(patch = {}) {
889
- this.style = { ...this.style, ...patch };
1301
+ /**
1302
+ * 合并并应用样式。
1303
+ *
1304
+ * 只改 uniform 的项不会触发几何 / 着色器重建。带 `transition` 时,能插值的项
1305
+ * 交给动画调度器逐帧推进;不能插值的项(`mode` / `shading` / `edges`)走各自的
1306
+ * 编排逻辑(`edges` 由 setEdges 做淡入淡出,`mode` 建议配 fade-through)。
1307
+ */
1308
+ setStyle(patch = {}, transition) {
1309
+ Object.assign(this._styleTarget, patch);
1310
+ const duration = transition?.duration ?? 0;
1311
+ const wantAnim = duration > 0 || !!transition?.spring;
1312
+ // 棱线开关是结构变更,不是插值:交给 setEdges 编排
1313
+ let rest = patch;
1314
+ if ('edges' in patch) {
1315
+ const { edges, ...others } = patch;
1316
+ rest = others;
1317
+ this.setEdges(!!edges, wantAnim ? transition : undefined);
1318
+ if (Object.keys(rest).length === 0) {
1319
+ this._requestRepaint();
1320
+ return;
1321
+ }
1322
+ }
1323
+ const animated = [];
1324
+ const immediate = {};
1325
+ for (const key of Object.keys(rest)) {
1326
+ if (wantAnim && this.animator.has(`style.${String(key)}`))
1327
+ animated.push(String(key));
1328
+ else
1329
+ immediate[key] = rest[key];
1330
+ }
1331
+ if (Object.keys(immediate).length > 0) {
1332
+ Object.assign(this.style, immediate);
1333
+ this._applyStyleEffects(immediate);
1334
+ }
1335
+ for (const key of animated) {
1336
+ this.animator.to(`style.${key}`, this._animTargetOf(key, rest), {
1337
+ ...transition,
1338
+ duration,
1339
+ });
1340
+ }
1341
+ this._requestRepaint();
1342
+ }
1343
+ getStyle() {
1344
+ return { ...this._styleTarget, modeLabel: STYLE_LABELS[this._styleTarget.mode] };
1345
+ }
1346
+ /** 把某个样式键的取值转成动画通道能吃的形状(标量 or 线性 RGB 三元组) */
1347
+ _animTargetOf(key, patch) {
1348
+ const value = patch[key];
1349
+ const dim = this._animDimOf(key);
1350
+ if (dim === 1)
1351
+ return Number(value);
1352
+ this._colorScratch.set(String(value));
1353
+ return [this._colorScratch.r, this._colorScratch.g, this._colorScratch.b];
1354
+ }
1355
+ /** 该样式键的动画维度:3 = 颜色,1 = 标量 */
1356
+ _animDimOf(key) {
1357
+ return STYLE_COLOR_KEYS.includes(key) ? 3 : 1;
1358
+ }
1359
+ /**
1360
+ * 注册样式动画通道。
1361
+ *
1362
+ * 每个通道的 write 都是 O(1):只改 `this.style` 的一个字段 + 一次 uniform 赋值。
1363
+ * 这里不注册 `mode` / `shading` / `edges`——它们不可插值,见类文档。
1364
+ */
1365
+ _registerAnimChannels() {
1366
+ for (const key of STYLE_SCALAR_KEYS) {
1367
+ this.animator.register(`style.${key}`, {
1368
+ dim: 1,
1369
+ read: (out) => {
1370
+ out[0] = Number(this.style[key] ?? 0);
1371
+ },
1372
+ write: (v) => {
1373
+ this.style[key] = v[0];
1374
+ this._onStyleChannelWrote(key);
1375
+ },
1376
+ });
1377
+ }
1378
+ for (const key of STYLE_COLOR_KEYS) {
1379
+ this.animator.register(`style.${key}`, {
1380
+ dim: 3,
1381
+ read: (out) => {
1382
+ const c = this._uniformColorOf(key);
1383
+ out[0] = c.r;
1384
+ out[1] = c.g;
1385
+ out[2] = c.b;
1386
+ },
1387
+ write: (v) => {
1388
+ const c = this._uniformColorOf(key);
1389
+ // 直接写线性分量:shader 消费的就是线性值,端点严格吻合
1390
+ c.setRGB(v[0], v[1], v[2]);
1391
+ this.style[key] = `#${c.getHexString()}`;
1392
+ this._onStyleChannelWrote(key);
1393
+ },
1394
+ });
1395
+ }
1396
+ // 棱线淡入淡出乘子:不属于 S3MStyle,单独一条通道
1397
+ this.animator.register('style.edgeFade', {
1398
+ dim: 1,
1399
+ read: (out) => {
1400
+ out[0] = this.uniforms.uEdgeFade?.value ?? 1;
1401
+ },
1402
+ write: (v) => {
1403
+ if (this.uniforms.uEdgeFade)
1404
+ this.uniforms.uEdgeFade.value = v[0];
1405
+ this._syncEdgeStyle();
1406
+ },
1407
+ });
1408
+ // 整体压暗乘子:setMode 的 fade-through 用它,也不是 S3MStyle 字段
1409
+ this.animator.register('style.fade', {
1410
+ dim: 1,
1411
+ read: (out) => {
1412
+ out[0] = this.uniforms.uFade?.value ?? 1;
1413
+ },
1414
+ write: (v) => {
1415
+ if (this.uniforms.uFade)
1416
+ this.uniforms.uFade.value = v[0];
1417
+ this._requestRepaint();
1418
+ },
1419
+ });
1420
+ }
1421
+ /** 通道写完一个样式键后的最小副作用(全部 O(1)) */
1422
+ _onStyleChannelWrote(key) {
1423
+ if (key === 'opacity') {
1424
+ this._applyOpacity();
1425
+ return;
1426
+ }
1427
+ this._applyStyleUniforms();
1428
+ if (key === 'edgeColor' || key === 'edgeWidth' || key === 'edgeOpacity') {
1429
+ this._refreshEdgeLines();
1430
+ }
1431
+ }
1432
+ /** 取某个颜色键对应的共享 uniform Color 对象 */
1433
+ _uniformColorOf(key) {
1434
+ const u = this.uniforms;
1435
+ switch (key) {
1436
+ case 'colorA':
1437
+ return u.uColorA.value;
1438
+ case 'colorB':
1439
+ return u.uColorB.value;
1440
+ case 'colorC':
1441
+ return u.uColorC.value;
1442
+ case 'selectColor':
1443
+ return u.uSelColor.value;
1444
+ case 'edgeColor':
1445
+ return this.edgeMaterial.uniforms.uColor.value;
1446
+ default:
1447
+ return u.uColorA.value;
1448
+ }
1449
+ }
1450
+ /** 应用一批样式键带来的副作用(uniform / 材质 / 棱线 / 选中态) */
1451
+ _applyStyleEffects(patch) {
890
1452
  this._applyStyleUniforms();
891
1453
  if ('opacity' in patch || 'depthWrite' in patch)
892
1454
  this._applyOpacity();
@@ -895,13 +1457,13 @@ export class S3MViewer {
895
1457
  this._applyPointCloudStyles();
896
1458
  if ('shading' in patch)
897
1459
  this._applyShading();
898
- // 临界角变了要重建 CPU 棱线(EdgesGeometry 参数),开/关走 setEdges 整体刷新
1460
+ // 临界角变了要重建 CPU 棱线(EdgesGeometry 的参数),开 / 关走 setEdges 整体刷新。
1461
+ // 必须先 _disposeEdges():setEdges 只挑「还没有棱线」的网格来建,
1462
+ // 不先拆掉的话已经建好的会被全部跳过,临界角改了等于没改。
899
1463
  if ('edgeThreshold' in patch && this._edgesEnabled) {
1464
+ this._disposeEdges();
900
1465
  this.setEdges(true);
901
1466
  }
902
- else if ('edges' in patch) {
903
- this.setEdges(!!this.style.edges);
904
- }
905
1467
  else if ('edgeColor' in patch || 'edgeWidth' in patch || 'opacity' in patch || 'edgeOpacity' in patch) {
906
1468
  this._refreshEdgeLines();
907
1469
  }
@@ -912,10 +1474,6 @@ export class S3MViewer {
912
1474
  else
913
1475
  this._syncSelectionStyle();
914
1476
  }
915
- this._requestRepaint();
916
- }
917
- getStyle() {
918
- return { ...this.style, modeLabel: STYLE_LABELS[this.style.mode] };
919
1477
  }
920
1478
  _applyStyleUniforms() {
921
1479
  const u = this.uniforms;
@@ -951,6 +1509,9 @@ export class S3MViewer {
951
1509
  if (u.uTexMix && s.texMix != null) {
952
1510
  u.uTexMix.value = s.texMix;
953
1511
  }
1512
+ if (u.uAmbientGain && s.ambientGain != null) {
1513
+ u.uAmbientGain.value = s.ambientGain;
1514
+ }
954
1515
  if (this.outlineMaterial) {
955
1516
  if (this.outlineMaterial.uniforms.uElevation && s.selectElevation != null) {
956
1517
  this.outlineMaterial.uniforms.uElevation.value = s.selectElevation;
@@ -965,24 +1526,43 @@ export class S3MViewer {
965
1526
  }
966
1527
  }
967
1528
  }
968
- /** 透明度:只改材质状态,不触发着色器重编译,所以可以跟着滑块实时拖 */
1529
+ /**
1530
+ * 透明度:写共享 uniform,**不再逐 mesh 改材质**。
1531
+ *
1532
+ * 原来的写法每次都要遍历全部 pickables 改 `material.opacity` + `material.transparent`,
1533
+ * 是 O(meshes);而且 `opaque` 参与 three 的 program 缓存键,跨 0.999 会换一次 program。
1534
+ * 拖滑块时一秒钟几十次调用,几十万面的场景就是明显掉帧。
1535
+ *
1536
+ * 现在逐帧只写一个 float(`uOpacity`),混合开关只在**真正跨过阈值**时切一次。
1537
+ */
969
1538
  _applyOpacity() {
970
1539
  const o = Math.min(1, Math.max(0.05, this.style.opacity ?? 1));
1540
+ if (this.uniforms.uOpacity)
1541
+ this.uniforms.uOpacity.value = o;
971
1542
  const transparent = o < 0.999;
972
- // 关键:若 depthWrite 开启(默认开启),即使半透明也保持深度写入,完美遮挡背面棱线,防止背面线条透出
973
- const keepDepth = this.style.depthWrite !== false;
974
- for (const p of this._pickables.values()) {
975
- if (isPointCloudObject(p.mesh)) {
976
- this._applyPointCloudStyle(p.mesh);
977
- continue;
1543
+ if (transparent !== this._opacityTransparent) {
1544
+ this._opacityTransparent = transparent;
1545
+ // 关键:若 depthWrite 开启(默认开启),即使半透明也保持深度写入,完美遮挡背面棱线,防止背面线条透出
1546
+ const keepDepth = this.style.depthWrite !== false;
1547
+ for (const p of this._pickables.values()) {
1548
+ if (isPointCloudObject(p.mesh))
1549
+ continue;
1550
+ const m = styledMaterialOf(p.mesh);
1551
+ if (!m)
1552
+ continue;
1553
+ // 有单体淡化 / 正在淡入的材质,transparent 由各自的流程管,这里不要抢
1554
+ if (m.userData.uBatchTexActive?.value)
1555
+ continue;
1556
+ if ((m.userData.uTileFade?.value ?? 1) < 1)
1557
+ continue;
1558
+ m.transparent = transparent;
1559
+ m.depthWrite = transparent ? keepDepth : true;
978
1560
  }
979
- const m = styledMaterialOf(p.mesh);
980
- if (!m)
981
- continue;
982
- m.opacity = o;
983
- m.transparent = transparent;
984
- m.depthWrite = transparent ? keepDepth : true;
985
1561
  }
1562
+ // 点云不走 StyleMaterial,自己有一套 uOpacity,逐帧刷的只有这几个对象
1563
+ for (const pc of this._pointClouds)
1564
+ this._applyPointCloudStyle(pc);
1565
+ this._syncEdgeStyle();
986
1566
  this._requestRepaint();
987
1567
  }
988
1568
  /** 单个点云对象同步当前样式(着色模式 + 不透明度 + 选中高亮) */
@@ -991,10 +1571,8 @@ export class S3MViewer {
991
1571
  }
992
1572
  /** 全部点云刷新:着色模式切换时用(uniform 是共享引用,改色不用走这里) */
993
1573
  _applyPointCloudStyles() {
994
- for (const p of this._pickables.values()) {
995
- if (isPointCloudObject(p.mesh))
996
- this._applyPointCloudStyle(p.mesh);
997
- }
1574
+ for (const pc of this._pointClouds)
1575
+ this._applyPointCloudStyle(pc);
998
1576
  this._requestRepaint();
999
1577
  }
1000
1578
  /** 平面/平滑着色:FLAT_SHADED 是编译期宏,改它必须重编译 */
@@ -1116,10 +1694,16 @@ export class S3MViewer {
1116
1694
  *
1117
1695
  * 棱线本身用「屏幕空间等宽线」画(见 EdgeLines.ts):WebGL 的 lineWidth 基本无效,
1118
1696
  * 只有摊成面向屏幕的四边形,`edgeWidth` 才能真正调粗。
1697
+ *
1698
+ * 带 `transition` 时做「淡入 / 淡出」,**不对几何做插值**(几何没法插值):
1699
+ * 开:立刻置位 + 开始分片建线,同时 `uEdgeFade` 0→1 —— 建好一块亮一块,视觉上是渐显;
1700
+ * 关:`uEdgeFade` 1→0,淡完才 dispose,避免棱线「啪」一下消失。
1119
1701
  */
1120
- setEdges(enabled) {
1702
+ setEdges(enabled, transition) {
1703
+ const wantAnim = !!transition && ((transition.duration ?? 0) > 0 || !!transition.spring);
1121
1704
  this._edgesEnabled = enabled;
1122
1705
  this.style.edges = enabled;
1706
+ this._styleTarget.edges = enabled;
1123
1707
  // 数据自带的棱线:直接切可见性
1124
1708
  for (const entry of this.datasets.values()) {
1125
1709
  entry.root.traverse((o) => {
@@ -1132,8 +1716,20 @@ export class S3MViewer {
1132
1716
  }
1133
1717
  this._syncEdgeStyle();
1134
1718
  if (!enabled) {
1135
- for (const p of this._pickables.values())
1136
- this._removeEdges(p.mesh);
1719
+ if (wantAnim) {
1720
+ this.animator.to('style.edgeFade', 0, {
1721
+ ...transition,
1722
+ onComplete: () => {
1723
+ this._disposeEdges();
1724
+ this._requestRepaint();
1725
+ transition?.onComplete?.();
1726
+ },
1727
+ });
1728
+ }
1729
+ else {
1730
+ this._setEdgeFade(1);
1731
+ this._disposeEdges();
1732
+ }
1137
1733
  this._requestRepaint();
1138
1734
  return;
1139
1735
  }
@@ -1155,6 +1751,25 @@ export class S3MViewer {
1155
1751
  this._requestRepaint();
1156
1752
  };
1157
1753
  step();
1754
+ if (wantAnim) {
1755
+ // 从 0 起淡入:新建出来的棱线自动继承当前进度,不会半路冒出一条满亮度的线
1756
+ this._setEdgeFade(0);
1757
+ this.animator.to('style.edgeFade', 1, transition);
1758
+ }
1759
+ else {
1760
+ this._setEdgeFade(1);
1761
+ }
1762
+ }
1763
+ /** 直接写棱线淡入乘子(不走动画通道) */
1764
+ _setEdgeFade(v) {
1765
+ if (this.uniforms.uEdgeFade)
1766
+ this.uniforms.uEdgeFade.value = v;
1767
+ this._syncEdgeStyle();
1768
+ }
1769
+ /** 释放所有现算棱线几何 */
1770
+ _disposeEdges() {
1771
+ for (const p of this._pickables.values())
1772
+ this._removeEdges(p.mesh);
1158
1773
  }
1159
1774
  /**
1160
1775
  * 挂载预制棱线缓存(Crease Cache)。
@@ -1201,19 +1816,27 @@ export class S3MViewer {
1201
1816
  this._creaseLines = null;
1202
1817
  this._requestRepaint();
1203
1818
  }
1204
- /** 让全局棱线材质跟上 style.edgeColor / edgeWidth / edgeOpacity */
1819
+ /**
1820
+ * 让全局棱线材质跟上 style.edgeColor / edgeWidth / edgeOpacity。
1821
+ *
1822
+ * 全程 O(1):只有一份共享 edgeMaterial(所有逐 mesh 棱线都用它)+ 一份预制缓存,
1823
+ * 所以棱线淡入淡出只要改一个 uniform,新建瓦片自动继承当前进度。
1824
+ */
1205
1825
  _syncEdgeStyle() {
1206
1826
  const s = this.style;
1827
+ const fade = this.uniforms.uEdgeFade?.value ?? 1;
1828
+ const opacity = Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) *
1829
+ Math.min(1, Math.max(0.05, s.opacity ?? 1)) *
1830
+ fade;
1207
1831
  const u = this.edgeMaterial.uniforms;
1208
1832
  u.uColor.value.set(s.edgeColor);
1209
1833
  u.uWidth.value = Math.max(0.1, s.edgeWidth ?? 1.5);
1210
- u.uOpacity.value =
1211
- Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) * Math.min(1, Math.max(0.05, s.opacity ?? 1));
1834
+ u.uOpacity.value = opacity;
1212
1835
  // 预制棱线缓存(LineBasicMaterial)同步颜色 / 不透明度
1213
1836
  if (this._creaseLines) {
1214
1837
  const m = this._creaseLines.material;
1215
1838
  m.color.set(s.edgeColor);
1216
- m.opacity = Math.min(1, Math.max(0, s.edgeOpacity ?? 0.6)) * Math.min(1, Math.max(0.05, s.opacity ?? 1));
1839
+ m.opacity = opacity;
1217
1840
  }
1218
1841
  }
1219
1842
  /** 让数据自带的棱线跟着 style.edgeColor / opacity 走(这些是 LineBasicMaterial,改不了粗细) */
@@ -1223,20 +1846,28 @@ export class S3MViewer {
1223
1846
  return;
1224
1847
  mat.color.set(this.style.edgeColor);
1225
1848
  const baseOpacity = this.style.edgeOpacity ?? 0.6;
1226
- mat.opacity = baseOpacity * Math.min(1, Math.max(0.05, this.style.opacity ?? 1));
1849
+ mat.opacity =
1850
+ baseOpacity *
1851
+ Math.min(1, Math.max(0.05, this.style.opacity ?? 1)) *
1852
+ (this.uniforms.uEdgeFade?.value ?? 1);
1227
1853
  mat.transparent = true;
1228
1854
  mat.polygonOffset = true;
1229
1855
  mat.polygonOffsetFactor = -1;
1230
1856
  mat.polygonOffsetUnits = -1;
1231
1857
  mat.needsUpdate = true;
1232
1858
  }
1859
+ /**
1860
+ * 刷新所有棱线外观。
1861
+ *
1862
+ * 数据自带的棱线是逐对象的 LineBasicMaterial,改颜色只能一个个写;但原来每次都要
1863
+ * 遍历整个数据集树(几千个节点),颜色动画逐帧跑就是灾难。改成只刷注册时收集好的
1864
+ * 那批 LineSegments,复杂度降到 O(棱线条数)。
1865
+ */
1233
1866
  _refreshEdgeLines() {
1234
1867
  this._syncEdgeStyle();
1235
- for (const entry of this.datasets.values()) {
1236
- entry.root.traverse((o) => {
1237
- if (o.userData.isEdgeLines)
1238
- this._styleEdgeLine(o);
1239
- });
1868
+ for (const lines of this._nativeEdgeLines) {
1869
+ if (lines.parent)
1870
+ this._styleEdgeLine(lines);
1240
1871
  }
1241
1872
  }
1242
1873
  /** 地形 / 绿地 / 道路 / 地面铺装等不参与自动描边(数据自带棱线包另说) */
@@ -1285,7 +1916,22 @@ export class S3MViewer {
1285
1916
  source.dispose();
1286
1917
  if (!segments || segments.length < 6)
1287
1918
  return;
1288
- const lines = new THREE.Mesh(buildThickLineGeometry(segments), this.edgeMaterial);
1919
+ // 3. 回填每段棱线所属的单体 batchId。
1920
+ // EdgesGeometry 只输出坐标不输出顶点号,只能拿端点坐标去查「位置 → batchId」表。
1921
+ // 没有这张表,单体一动棱线就留在原地——这正是「棱线跟随」的关键一环。
1922
+ const TOL = 0.005;
1923
+ const batchMap = buildPositionBatchMap(mesh.geometry, TOL);
1924
+ let batchIds;
1925
+ if (batchMap) {
1926
+ const segCount = segments.length / 6;
1927
+ batchIds = new Float32Array(segCount);
1928
+ for (let i = 0; i < segCount; i++) {
1929
+ const s = i * 6;
1930
+ batchIds[i] =
1931
+ batchMap.get(positionQuantKey(segments[s], segments[s + 1], segments[s + 2], 1 / TOL)) ?? -1;
1932
+ }
1933
+ }
1934
+ const lines = new THREE.Mesh(buildThickLineGeometry(segments, batchIds), this._createEdgeMaterial(mesh));
1289
1935
  lines.renderOrder = 2;
1290
1936
  // 屏幕空间外扩后可能超出原包围球,关掉剔除更稳
1291
1937
  lines.frustumCulled = false;
@@ -1294,6 +1940,37 @@ export class S3MViewer {
1294
1940
  ud.edges = lines;
1295
1941
  mesh.add(lines); // 作为子节点,自动继承 mesh 的世界变换
1296
1942
  }
1943
+ /**
1944
+ * 给一块网格造专属的棱线材质。
1945
+ *
1946
+ * 棱线材质必须逐网格一份,因为它要绑定**这个网格**的单体状态纹理;但外观
1947
+ * (颜色 / 粗细 / 透明度)必须全局统一——所以外观 uniform 直接复用
1948
+ * `_edgeStyleUniforms` 里的对象,`_syncEdgeStyle()` 改一次全部生效,
1949
+ * program 也因为着色器相同而只编译一次。
1950
+ */
1951
+ _createEdgeMaterial(mesh) {
1952
+ const styled = styledMaterialOf(mesh);
1953
+ const batch = styled?.userData?.uBatchTex
1954
+ ? {
1955
+ uBatchTex: styled.userData.uBatchTex,
1956
+ uBatchTexWidth: styled.userData.uBatchTexWidth,
1957
+ uBatchTexActive: styled.userData.uBatchTexActive,
1958
+ }
1959
+ : undefined;
1960
+ return createThickLineMaterial(this.lineShared, {}, this._edgeStyleUniforms, batch);
1961
+ }
1962
+ /** 选中棱线的逐网格材质,道理同上 */
1963
+ _createSelectionEdgeMaterial(mesh) {
1964
+ const styled = styledMaterialOf(mesh);
1965
+ const batch = styled?.userData?.uBatchTex
1966
+ ? {
1967
+ uBatchTex: styled.userData.uBatchTex,
1968
+ uBatchTexWidth: styled.userData.uBatchTexWidth,
1969
+ uBatchTexActive: styled.userData.uBatchTexActive,
1970
+ }
1971
+ : undefined;
1972
+ return createThickLineMaterial(this.lineShared, {}, this._selEdgeStyleUniforms, batch);
1973
+ }
1297
1974
  _removeEdges(mesh) {
1298
1975
  const ud = mesh.userData;
1299
1976
  const lines = ud.edges;
@@ -1301,6 +1978,14 @@ export class S3MViewer {
1301
1978
  return;
1302
1979
  mesh.remove(lines);
1303
1980
  lines.geometry?.dispose();
1981
+ // 棱线材质现在是逐网格一份(要绑各自的 batch 纹理),得跟着释放
1982
+ const mat = lines.material;
1983
+ if (Array.isArray(mat)) {
1984
+ mat.forEach((m) => m?.dispose?.());
1985
+ }
1986
+ else {
1987
+ mat?.dispose?.();
1988
+ }
1304
1989
  ud.edges = null;
1305
1990
  }
1306
1991
  /* ---------------------------------------------------------------- 拾取 */
@@ -1822,24 +2507,34 @@ export class S3MViewer {
1822
2507
  const ud = mesh.userData;
1823
2508
  const geoRef = ud.geoRef;
1824
2509
  let segments = [];
2510
+ // 这块网格上的棱线全部属于选中的那个单体,整批填同一个 batchId,
2511
+ // 顶点着色器才能从状态纹理里取到平移 / 拔高——选中跟随移动靠它。
2512
+ let batchId = -1;
1825
2513
  if (mesh === result.mesh && result.instanceIndex != null) {
1826
2514
  // 实例化几何没有逐单体的顶点区间,整个 base mesh 就是这一栋的外形
1827
2515
  segments = [{ vertexOffset: 0, vertexCount: mesh.geometry.getAttribute('position')?.count ?? 0 }];
2516
+ const pickInfo = geoRef?.pickInfo;
2517
+ const entry = pickInfo?.[result.smid ?? ''] ??
2518
+ pickInfo?.[String(result.smid)];
2519
+ batchId = entry ? pickEntryId(entry) : -1;
1828
2520
  }
1829
2521
  else if (result.smid != null) {
1830
2522
  const pickInfo = geoRef?.pickInfo;
1831
2523
  const entry = pickInfo?.[result.smid] ??
1832
2524
  pickInfo?.[String(result.smid)];
1833
2525
  const bId = entry ? pickEntryId(entry) : -1;
2526
+ batchId = bId;
1834
2527
  segments = entry?.segments ?? (bId >= 0 ? resolveFeature(geoRef, bId).segments : []);
1835
2528
  }
1836
2529
  else if (mesh === result.mesh) {
1837
2530
  const localGeo = ud.geoByBatchId?.get(result.batchId) ?? geoRef;
1838
2531
  segments = resolveFeature(localGeo, result.batchId).segments;
2532
+ batchId = result.batchId;
1839
2533
  }
1840
2534
  const pairs = buildFeatureEdgeSegments(mesh.geometry, segments);
1841
2535
  if (pairs && pairs.length > 0) {
1842
- const lines = new THREE.Mesh(buildThickLineGeometry(pairs), this.selectionEdgeMaterial);
2536
+ const batchIds = batchId >= 0 ? new Float32Array(pairs.length / 6).fill(batchId) : undefined;
2537
+ const lines = new THREE.Mesh(buildThickLineGeometry(pairs, batchIds), this._createSelectionEdgeMaterial(mesh));
1843
2538
  lines.renderOrder = 4;
1844
2539
  // 屏幕空间外扩后可能超出原包围球,关掉剔除更稳
1845
2540
  lines.frustumCulled = false;
@@ -1904,7 +2599,10 @@ export class S3MViewer {
1904
2599
  u.uColor.value.set(s.outlineColor ?? s.selectColor);
1905
2600
  u.uWidth.value = Math.max(0.1, s.outlineWidthPx ?? 3);
1906
2601
  u.uOpacity.value = Math.min(1, Math.max(0.05, s.opacity ?? 1));
1907
- u.uElevation.value = this._selection ? this._selectionElevation(this._selection) : 0;
2602
+ // 只加全局 selectElevation:单体自己的拔高已经写在状态纹理第 2 行 z 里,
2603
+ // 顶点着色器采样时带出来了,这里再加一次就会双重拔高
2604
+ if (u.uElevation)
2605
+ u.uElevation.value = s.selectElevation ?? 0;
1908
2606
  // 外扩描边是另一个材质实例,单体状态纹理的开关是建的时候抄过去的。
1909
2607
  // 先选中、再抬高(或反过来)时模板会停留在旧值,这里补一次同步。
1910
2608
  for (const outline of this._outlineMeshes) {
@@ -1990,6 +2688,8 @@ export class S3MViewer {
1990
2688
  const gl = this.renderer.getContext();
1991
2689
  if (gl && typeof gl.isContextLost === 'function' && gl.isContextLost())
1992
2690
  return false;
2691
+ // 先推进动画,再刷脏标记,最后渲染 —— 保证本帧画出来的是最新值
2692
+ const animating = this.animator.tick();
1993
2693
  // 脏标记正常由微任务刷掉;这里再兜一次底,保证「本帧画出来的」一定是最新样式
1994
2694
  this.flushOverrides();
1995
2695
  const canvas = this.canvas;
@@ -2041,8 +2741,12 @@ export class S3MViewer {
2041
2741
  this._frame = 0;
2042
2742
  this._fps.last = now;
2043
2743
  }
2044
- // 动态着色 / 瓦片加载中 / 瓦片层级或可见性改变,都需要宿主继续驱动下一帧
2045
- return this.style.mode === STYLE.DYNAMIC || this.stats.loading > 0 || tilesetChanged;
2744
+ // 动态着色 / 动画进行中 / 瓦片加载中 / 瓦片层级或可见性改变,都需要宿主继续驱动下一帧。
2745
+ // 动画结束那一帧必须精确回到 false,否则 MapLibre 会永远重绘(耗电、发热)。
2746
+ return (animating ||
2747
+ this.style.mode === STYLE.DYNAMIC ||
2748
+ this.stats.loading > 0 ||
2749
+ tilesetChanged);
2046
2750
  }
2047
2751
  /* ---------------------------------------------------------------- 只读属性 */
2048
2752
  get fps() {