three-cad-viewer 4.1.2 → 4.2.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.
Files changed (58) hide show
  1. package/Readme.md +12 -5
  2. package/dist/camera/camera.d.ts +14 -2
  3. package/dist/core/studio-manager.d.ts +91 -0
  4. package/dist/core/types.d.ts +260 -9
  5. package/dist/core/viewer-state.d.ts +28 -2
  6. package/dist/core/viewer.d.ts +200 -6
  7. package/dist/index.d.ts +7 -2
  8. package/dist/rendering/environment.d.ts +239 -0
  9. package/dist/rendering/light-detection.d.ts +44 -0
  10. package/dist/rendering/material-factory.d.ts +77 -2
  11. package/dist/rendering/material-presets.d.ts +32 -0
  12. package/dist/rendering/room-environment.d.ts +13 -0
  13. package/dist/rendering/studio-composer.d.ts +130 -0
  14. package/dist/rendering/studio-floor.d.ts +53 -0
  15. package/dist/rendering/texture-cache.d.ts +142 -0
  16. package/dist/rendering/triplanar.d.ts +37 -0
  17. package/dist/scene/animation.d.ts +1 -1
  18. package/dist/scene/clipping.d.ts +31 -0
  19. package/dist/scene/nestedgroup.d.ts +64 -27
  20. package/dist/scene/objectgroup.d.ts +47 -0
  21. package/dist/three-cad-viewer.css +339 -29
  22. package/dist/three-cad-viewer.esm.js +27567 -11874
  23. package/dist/three-cad-viewer.esm.js.map +1 -1
  24. package/dist/three-cad-viewer.esm.min.js +10 -4
  25. package/dist/three-cad-viewer.js +27486 -11787
  26. package/dist/three-cad-viewer.min.js +10 -4
  27. package/dist/ui/display.d.ts +147 -0
  28. package/dist/utils/decode-instances.d.ts +60 -0
  29. package/dist/utils/utils.d.ts +10 -0
  30. package/package.json +4 -2
  31. package/src/_version.ts +1 -1
  32. package/src/camera/camera.ts +27 -10
  33. package/src/core/studio-manager.ts +682 -0
  34. package/src/core/types.ts +328 -9
  35. package/src/core/viewer-state.ts +84 -4
  36. package/src/core/viewer.ts +453 -22
  37. package/src/index.ts +25 -1
  38. package/src/rendering/environment.ts +840 -0
  39. package/src/rendering/light-detection.ts +327 -0
  40. package/src/rendering/material-factory.ts +456 -2
  41. package/src/rendering/material-presets.ts +303 -0
  42. package/src/rendering/raycast.ts +2 -2
  43. package/src/rendering/room-environment.ts +192 -0
  44. package/src/rendering/studio-composer.ts +577 -0
  45. package/src/rendering/studio-floor.ts +108 -0
  46. package/src/rendering/texture-cache.ts +1020 -0
  47. package/src/rendering/triplanar.ts +329 -0
  48. package/src/scene/animation.ts +3 -2
  49. package/src/scene/clipping.ts +59 -0
  50. package/src/scene/nestedgroup.ts +399 -0
  51. package/src/scene/objectgroup.ts +186 -11
  52. package/src/scene/orientation.ts +12 -0
  53. package/src/scene/render-shape.ts +55 -21
  54. package/src/types/n8ao.d.ts +28 -0
  55. package/src/ui/display.ts +1032 -27
  56. package/src/ui/index.html +181 -44
  57. package/src/utils/decode-instances.ts +233 -0
  58. package/src/utils/utils.ts +33 -20
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Triplanar texture mapping for MeshPhysicalMaterial.
3
+ *
4
+ * Replaces standard UV-based texture sampling with model-space triplanar
5
+ * projection via `material.onBeforeCompile`. Eliminates seams on curved
6
+ * surfaces (cylinders, cones, etc.) and maintains uniform texture scale
7
+ * regardless of object proportions.
8
+ *
9
+ * All coordinates are in **model space** to match the geometry's bounding box.
10
+ * `transformed` (model-space position) and `objectNormal` (model-space normal)
11
+ * are used — NOT the view-space `transformedNormal`.
12
+ *
13
+ * NOTE: `onBeforeCompile` receives shaders BEFORE `#include` resolution.
14
+ * Therefore we replace `#include <chunk_name>` directives with inline GLSL
15
+ * that uses triplanar sampling, rather than replacing expanded texture2D calls.
16
+ *
17
+ * Handles: map, normalMap, roughnessMap, metalnessMap, emissiveMap, aoMap,
18
+ * clearcoatNormalMap, alphaMap.
19
+ */
20
+
21
+ import * as THREE from "three";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // GLSL: Varyings (shared between vertex & fragment)
25
+ // ---------------------------------------------------------------------------
26
+
27
+ const TRIPLANAR_VARYINGS = /* glsl */ `
28
+ varying vec3 vTriplanarPos;
29
+ varying vec3 vTriplanarNormal;
30
+ `;
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // GLSL: Fragment header (uniforms + helper functions)
34
+ // ---------------------------------------------------------------------------
35
+
36
+ const TRIPLANAR_FRAGMENT_HEADER = /* glsl */ `
37
+ varying vec3 vTriplanarPos;
38
+ varying vec3 vTriplanarNormal;
39
+ uniform vec3 triplanarOffset;
40
+ uniform float triplanarScale;
41
+ uniform vec2 triplanarRepeat;
42
+
43
+ // normalMatrix is only declared in the fragment shader for object-space
44
+ // normal maps. We need it for triplanar tangent-space normal mapping too.
45
+ #ifndef USE_NORMALMAP_OBJECTSPACE
46
+ uniform mat3 normalMatrix;
47
+ #endif
48
+
49
+ // --- Global triplanar state (computed once, reused by all samples) ---
50
+ vec2 tri_uvX, tri_uvY, tri_uvZ;
51
+ vec3 tri_blend;
52
+
53
+ // Initialize global triplanar UVs and blend weights from varyings.
54
+ // Must be called before any texture sampling.
55
+ void initTriplanarUVs() {
56
+ tri_blend = abs(vTriplanarNormal);
57
+ tri_blend = pow(tri_blend, vec3(3.0));
58
+ tri_blend /= (tri_blend.x + tri_blend.y + tri_blend.z);
59
+ vec3 p = (vTriplanarPos - triplanarOffset) * triplanarScale;
60
+ vec2 r = triplanarRepeat;
61
+ tri_uvX = p.yz * r;
62
+ tri_uvY = p.xz * r;
63
+ tri_uvZ = p.xy * r;
64
+ }
65
+
66
+ // Sample a texture using the global triplanar UVs and blend weights.
67
+ vec4 triplanarSample(sampler2D tex) {
68
+ return texture2D(tex, tri_uvX) * tri_blend.x
69
+ + texture2D(tex, tri_uvY) * tri_blend.y
70
+ + texture2D(tex, tri_uvZ) * tri_blend.z;
71
+ }
72
+
73
+ // Surface-gradient triplanar normal mapping.
74
+ // Instead of constructing full 3D normals per axis (which creates faceted
75
+ // shading at axis boundaries), we extract the tangent-space perturbation (xy)
76
+ // from each axis sample, project it into model space as a gradient, blend
77
+ // the gradients, and add to the geometric normal. Gradients blend smoothly.
78
+ // Ref: Morten Mikkelsen, "Surface Gradient Based Bump Mapping Framework"
79
+ //
80
+ // normalScale is declared in normalmap_pars_fragment (after this header),
81
+ // so we accept it as a parameter to avoid forward-reference errors.
82
+ vec3 triplanarNormal(sampler2D normalTex, vec2 nScale) {
83
+ vec3 N = vTriplanarNormal;
84
+
85
+ // Sample tangent-space normals for each projection axis
86
+ vec3 tnX = texture2D(normalTex, tri_uvX).xyz * 2.0 - 1.0;
87
+ vec3 tnY = texture2D(normalTex, tri_uvY).xyz * 2.0 - 1.0;
88
+ vec3 tnZ = texture2D(normalTex, tri_uvZ).xyz * 2.0 - 1.0;
89
+
90
+ // Apply normal scale to perturbation components
91
+ tnX.xy *= nScale;
92
+ tnY.xy *= nScale;
93
+ tnZ.xy *= nScale;
94
+
95
+ // Project each tangent-space perturbation (xy) into model space.
96
+ // X proj: UV=(y,z) -> tangent=(0,1,0), bitangent=(0,0,1) -> grad=(0, tx, ty)
97
+ // Y proj: UV=(x,z) -> tangent=(1,0,0), bitangent=(0,0,1) -> grad=(tx, 0, ty)
98
+ // Z proj: UV=(x,y) -> tangent=(1,0,0), bitangent=(0,1,0) -> grad=(tx, ty, 0)
99
+ vec3 surfGrad =
100
+ vec3(0.0, tnX.x, tnX.y) * tri_blend.x +
101
+ vec3(tnY.x, 0.0, tnY.y) * tri_blend.y +
102
+ vec3(tnZ.x, tnZ.y, 0.0) * tri_blend.z;
103
+
104
+ return normalize(N + surfGrad);
105
+ }
106
+ `;
107
+
108
+ // ---------------------------------------------------------------------------
109
+ // GLSL: UV initialization injection
110
+ // ---------------------------------------------------------------------------
111
+
112
+ /**
113
+ * Injected after #include <logdepthbuf_fragment>.
114
+ * This is the earliest reliable point in the fragment shader before any
115
+ * texture sampling. Initializes global triplanar UVs.
116
+ */
117
+ const UV_INIT = /* glsl */ `
118
+ #include <logdepthbuf_fragment>
119
+ initTriplanarUVs();
120
+ `;
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // GLSL: Replacement chunks (inline GLSL replacing #include directives)
124
+ // ---------------------------------------------------------------------------
125
+
126
+ /** Replaces #include <map_fragment> */
127
+ const MAP_FRAGMENT = /* glsl */ `
128
+ #ifdef USE_MAP
129
+ vec4 sampledDiffuseColor = triplanarSample( map );
130
+ #ifdef DECODE_VIDEO_TEXTURE
131
+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
132
+ #endif
133
+ diffuseColor *= sampledDiffuseColor;
134
+ #endif
135
+ `;
136
+
137
+ /** Replaces #include <roughnessmap_fragment> */
138
+ const ROUGHNESSMAP_FRAGMENT = /* glsl */ `
139
+ float roughnessFactor = roughness;
140
+ #ifdef USE_ROUGHNESSMAP
141
+ vec4 texelRoughness = triplanarSample( roughnessMap );
142
+ roughnessFactor *= texelRoughness.g;
143
+ #endif
144
+ `;
145
+
146
+ /** Replaces #include <metalnessmap_fragment> */
147
+ const METALNESSMAP_FRAGMENT = /* glsl */ `
148
+ float metalnessFactor = metalness;
149
+ #ifdef USE_METALNESSMAP
150
+ vec4 texelMetalness = triplanarSample( metalnessMap );
151
+ metalnessFactor *= texelMetalness.b;
152
+ #endif
153
+ `;
154
+
155
+ /** Replaces #include <emissivemap_fragment> */
156
+ const EMISSIVEMAP_FRAGMENT = /* glsl */ `
157
+ #ifdef USE_EMISSIVEMAP
158
+ vec4 emissiveColor = triplanarSample( emissiveMap );
159
+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
160
+ emissiveColor = sRGBTransferEOTF( emissiveColor );
161
+ #endif
162
+ totalEmissiveRadiance *= emissiveColor.rgb;
163
+ #endif
164
+ `;
165
+
166
+ /** Replaces #include <aomap_fragment> */
167
+ const AOMAP_FRAGMENT = /* glsl */ `
168
+ #ifdef USE_AOMAP
169
+ float ambientOcclusion = ( triplanarSample( aoMap ).r - 1.0 ) * aoMapIntensity + 1.0;
170
+ reflectedLight.indirectDiffuse *= ambientOcclusion;
171
+ #if defined( USE_CLEARCOAT )
172
+ clearcoatSpecularIndirect *= ambientOcclusion;
173
+ #endif
174
+ #if defined( USE_SHEEN )
175
+ sheenSpecularIndirect *= ambientOcclusion;
176
+ #endif
177
+ #if defined( USE_ENVMAP ) && defined( STANDARD )
178
+ float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
179
+ reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
180
+ #endif
181
+ #endif
182
+ `;
183
+
184
+ /**
185
+ * Replaces #include <normal_fragment_maps>.
186
+ * Object-space and bumpmap paths kept as-is.
187
+ * Tangent-space path: triplanar normal mapping samples the normal map 3x
188
+ * (one per projection axis), swizzles each to model space, blends, and
189
+ * transforms to view space via normalMatrix.
190
+ */
191
+ const NORMAL_FRAGMENT_MAPS = /* glsl */ `
192
+ #ifdef USE_NORMALMAP_OBJECTSPACE
193
+ normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
194
+ #ifdef FLIP_SIDED
195
+ normal = - normal;
196
+ #endif
197
+ #ifdef DOUBLE_SIDED
198
+ normal = normal * faceDirection;
199
+ #endif
200
+ normal = normalize( normalMatrix * normal );
201
+
202
+ #elif defined( USE_NORMALMAP_TANGENTSPACE )
203
+ // Triplanar normal mapping: sample normal map 3x (one per projection axis),
204
+ // swizzle each to model space, blend, and transform to view space.
205
+ normal = normalize(normalMatrix * triplanarNormal(normalMap, normalScale));
206
+
207
+ #elif defined( USE_BUMPMAP )
208
+ normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
209
+
210
+ #endif
211
+ `;
212
+
213
+ /**
214
+ * Replaces #include <clearcoat_normal_fragment_maps>.
215
+ * Triplanar clearcoat normal mapping using surface gradient blending.
216
+ */
217
+ const CLEARCOAT_NORMAL_FRAGMENT_MAPS = /* glsl */ `
218
+ #ifdef USE_CLEARCOAT_NORMALMAP
219
+ // Reuse triplanarNormal with clearcoat normal map and scale
220
+ vec3 clearcoatModelNormal = triplanarNormal(clearcoatNormalMap, clearcoatNormalScale);
221
+ clearcoatNormal = normalize(normalMatrix * clearcoatModelNormal);
222
+ #endif
223
+ `;
224
+
225
+ /** Replaces #include <alphamap_fragment> */
226
+ const ALPHAMAP_FRAGMENT = /* glsl */ `
227
+ #ifdef USE_ALPHAMAP
228
+ diffuseColor.a *= triplanarSample( alphaMap ).g;
229
+ #endif
230
+ `;
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Chunk replacement table
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /** Fragment shader chunk replacements */
237
+ const FRAGMENT_CHUNK_REPLACEMENTS: [string, string][] = [
238
+ ["#include <logdepthbuf_fragment>", UV_INIT],
239
+ ["#include <map_fragment>", MAP_FRAGMENT],
240
+ ["#include <roughnessmap_fragment>", ROUGHNESSMAP_FRAGMENT],
241
+ ["#include <metalnessmap_fragment>", METALNESSMAP_FRAGMENT],
242
+ ["#include <emissivemap_fragment>", EMISSIVEMAP_FRAGMENT],
243
+ ["#include <aomap_fragment>", AOMAP_FRAGMENT],
244
+ ["#include <normal_fragment_maps>", NORMAL_FRAGMENT_MAPS],
245
+ ["#include <clearcoat_normal_fragment_maps>", CLEARCOAT_NORMAL_FRAGMENT_MAPS],
246
+ ["#include <alphamap_fragment>", ALPHAMAP_FRAGMENT],
247
+ ];
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Public API
251
+ // ---------------------------------------------------------------------------
252
+
253
+ /**
254
+ * Apply triplanar texture mapping to a MeshPhysicalMaterial.
255
+ *
256
+ * Modifies the material's shader via `onBeforeCompile` so that all texture
257
+ * lookups use model-space triplanar projection instead of UV coordinates.
258
+ * The material should be a **clone** (not shared) because `onBeforeCompile`
259
+ * and `customProgramCacheKey` are set on it.
260
+ *
261
+ * Bounding box of the geometry determines coordinate normalization: the
262
+ * texture tiles once across the largest dimension with uniform scale,
263
+ * preserving aspect ratio. `textureRepeat` on the material's textures
264
+ * (if set) is respected via the triplanarRepeat uniform.
265
+ *
266
+ * @param material - Material clone to modify
267
+ * @param geometry - Geometry for bounding box computation
268
+ */
269
+ export function applyTriplanarMapping(
270
+ material: THREE.MeshPhysicalMaterial,
271
+ geometry: THREE.BufferGeometry,
272
+ ): void {
273
+ // Compute bounding box for coordinate normalization (model space)
274
+ geometry.computeBoundingBox();
275
+ const bb = geometry.boundingBox!;
276
+ const size = new THREE.Vector3();
277
+ bb.getSize(size);
278
+ const maxDim = Math.max(size.x, size.y, size.z, 1e-6);
279
+
280
+ // Uniform values (captured by closure, per-object)
281
+ const offset = bb.min.clone();
282
+ const scale = 1.0 / maxDim;
283
+
284
+ // Read texture repeat from the material's map (all textures share same repeat)
285
+ const repeat = material.map?.repeat?.clone() ?? new THREE.Vector2(1, 1);
286
+
287
+ material.onBeforeCompile = (shader) => {
288
+ // Custom uniforms
289
+ shader.uniforms.triplanarOffset = { value: offset };
290
+ shader.uniforms.triplanarScale = { value: scale };
291
+ shader.uniforms.triplanarRepeat = { value: repeat };
292
+
293
+ // --- Vertex shader ---
294
+ // Declare varyings
295
+ shader.vertexShader = shader.vertexShader.replace(
296
+ "#include <common>",
297
+ `#include <common>\n${TRIPLANAR_VARYINGS}`,
298
+ );
299
+
300
+ // Pass model-space position and normal to fragment shader.
301
+ // `transformed` = model-space position (after morphing, before view transform)
302
+ // `objectNormal` = model-space normal (before normalMatrix)
303
+ // Both match the geometry's bounding box coordinate space.
304
+ shader.vertexShader = shader.vertexShader.replace(
305
+ "#include <worldpos_vertex>",
306
+ `#include <worldpos_vertex>
307
+ vTriplanarPos = transformed;
308
+ vTriplanarNormal = normalize(objectNormal);`,
309
+ );
310
+
311
+ // --- Fragment shader ---
312
+ // Inject varyings, uniforms, and the triplanarSample helper
313
+ shader.fragmentShader = shader.fragmentShader.replace(
314
+ "#include <common>",
315
+ `#include <common>\n${TRIPLANAR_FRAGMENT_HEADER}`,
316
+ );
317
+
318
+ // Replace texture-sampling #include chunks with triplanar versions
319
+ for (const [from, to] of FRAGMENT_CHUNK_REPLACEMENTS) {
320
+ shader.fragmentShader = shader.fragmentShader.replace(from, to);
321
+ }
322
+ };
323
+
324
+ // All triplanar materials share the same compiled WebGL program
325
+ // (uniform values differ per instance). Appended to Three.js's standard
326
+ // program cache key, so materials with different maps/flags still get
327
+ // separate programs.
328
+ material.customProgramCacheKey = () => "triplanar";
329
+ }
@@ -30,7 +30,7 @@ class Animation {
30
30
  mixer: THREE.AnimationMixer | null;
31
31
  clip: THREE.AnimationClip | null;
32
32
  clipAction: THREE.AnimationAction | null;
33
- clock: THREE.Clock;
33
+ clock: THREE.Timer;
34
34
  duration: number | null;
35
35
  speed: number | null;
36
36
  repeat: boolean | null;
@@ -47,7 +47,7 @@ class Animation {
47
47
  this.mixer = null;
48
48
  this.clip = null;
49
49
  this.clipAction = null;
50
- this.clock = new THREE.Clock();
50
+ this.clock = new THREE.Timer();
51
51
  this.duration = null;
52
52
  this._backup = null;
53
53
  this.root = null;
@@ -334,6 +334,7 @@ class Animation {
334
334
  */
335
335
  update(): void {
336
336
  if (this.mixer) {
337
+ this.clock.update();
337
338
  this.mixer.update(this.clock.getDelta());
338
339
  }
339
340
  }
@@ -272,6 +272,20 @@ interface ClippingOptions {
272
272
  onNormalChange?: (index: ClipIndex, normalArray: Vector3Tuple) => void;
273
273
  }
274
274
 
275
+ /**
276
+ * Saved clipping state for mode transitions (e.g., entering/leaving Studio mode).
277
+ * Captures only Clipping-internal state; renderer flags and ViewerState keys
278
+ * are managed by the caller.
279
+ */
280
+ interface ClippingState {
281
+ /** Centered constant (position) for each of the 3 clip planes */
282
+ planeConstants: [number, number, number];
283
+ /** Whether the plane helper meshes (translucent colored rectangles) are visible */
284
+ helperVisible: boolean;
285
+ /** Whether the stencil plane meshes (solid colored caps) are visible */
286
+ planesVisible: boolean;
287
+ }
288
+
275
289
  /**
276
290
  * Manages clipping planes, stencil rendering, and plane visualization.
277
291
  */
@@ -566,6 +580,50 @@ class Clipping extends THREE.Group {
566
580
  }
567
581
  };
568
582
 
583
+ /**
584
+ * Save the current clipping state for later restoration.
585
+ * Captures plane positions, helper visibility, and stencil plane visibility.
586
+ * Used by Studio mode to snapshot clipping state before disabling clipping.
587
+ *
588
+ * Note: `renderer.localClippingEnabled` and `clipPlaneHelpers` ViewerState
589
+ * are managed by the caller (Display/Viewer layer), not captured here.
590
+ */
591
+ saveState(): ClippingState {
592
+ return {
593
+ planeConstants: [
594
+ this.clipPlanes[0].centeredConstant,
595
+ this.clipPlanes[1].centeredConstant,
596
+ this.clipPlanes[2].centeredConstant,
597
+ ],
598
+ helperVisible: this.planeHelpers?.visible ?? false,
599
+ planesVisible: this._planeMeshGroup?.children.length
600
+ ? this._planeMeshGroup.children[0].material.visible
601
+ : false,
602
+ };
603
+ }
604
+
605
+ /**
606
+ * Restore a previously saved clipping state.
607
+ * Re-applies plane positions, helper visibility, and stencil plane visibility.
608
+ * Used by Studio mode when leaving to restore the clipping configuration.
609
+ *
610
+ * @param state - The state previously captured by `saveState()`.
611
+ */
612
+ restoreState(state: ClippingState): void {
613
+ // Restore plane positions
614
+ for (const i of CLIP_INDICES) {
615
+ this.setConstant(i, state.planeConstants[i]);
616
+ }
617
+
618
+ // Restore plane helper visibility
619
+ if (this.planeHelpers) {
620
+ this.planeHelpers.visible = state.helperVisible;
621
+ }
622
+
623
+ // Restore stencil plane mesh visibility
624
+ this.setVisible(state.planesVisible);
625
+ }
626
+
569
627
  /**
570
628
  * Clean up resources.
571
629
  * Note: We don't null out arrays/references as GC handles cleanup when the Clipping object is collected.
@@ -579,3 +637,4 @@ class Clipping extends THREE.Group {
579
637
  }
580
638
 
581
639
  export { Clipping };
640
+ export type { ClippingState };