@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/build/deformation-runtime.js +2143 -0
  4. package/build/deformation-runtime.js.map +7 -0
  5. package/build/impostor-runtime-needle-engine.js +42 -0
  6. package/build/impostor-runtime-needle-engine.js.map +7 -0
  7. package/build/impostor-runtime.js +1333 -0
  8. package/build/impostor-runtime.js.map +7 -0
  9. package/build/internal/deformation/cloth-surface.js +288 -0
  10. package/build/internal/deformation/cloth-surface.js.map +7 -0
  11. package/build/internal/deformation/fur-surface.js +130 -0
  12. package/build/internal/deformation/fur-surface.js.map +7 -0
  13. package/build/internal/deformation/ik-constraints.js +44 -0
  14. package/build/internal/deformation/ik-constraints.js.map +7 -0
  15. package/build/internal/deformation/joints-json.js +197 -0
  16. package/build/internal/deformation/joints-json.js.map +7 -0
  17. package/build/internal/deformation/limits.js +16 -0
  18. package/build/internal/deformation/limits.js.map +7 -0
  19. package/build/internal/deformation/motion-settings.js +12 -0
  20. package/build/internal/deformation/motion-settings.js.map +7 -0
  21. package/build/internal/deformation/pin-cloth.js +196 -0
  22. package/build/internal/deformation/pin-cloth.js.map +7 -0
  23. package/build/internal/deformation/pin-ik.js +650 -0
  24. package/build/internal/deformation/pin-ik.js.map +7 -0
  25. package/build/internal/deformation/pin-types.js +12 -0
  26. package/build/internal/deformation/pin-types.js.map +7 -0
  27. package/build/internal/deformation/pin-wiggle.js +249 -0
  28. package/build/internal/deformation/pin-wiggle.js.map +7 -0
  29. package/build/internal/deformation/pose-slots.js +84 -0
  30. package/build/internal/deformation/pose-slots.js.map +7 -0
  31. package/build/internal/deformation/pose-timeline.js +210 -0
  32. package/build/internal/deformation/pose-timeline.js.map +7 -0
  33. package/build/internal/deformation/rig-drivers.js +48 -0
  34. package/build/internal/deformation/rig-drivers.js.map +7 -0
  35. package/build/internal/deformation/rig-extension.js +334 -0
  36. package/build/internal/deformation/rig-extension.js.map +7 -0
  37. package/build/internal/deformation/rig-runtime.js +2141 -0
  38. package/build/internal/deformation/rig-runtime.js.map +7 -0
  39. package/build/internal/deformation/wind.js +34 -0
  40. package/build/internal/deformation/wind.js.map +7 -0
  41. package/build/internal/impostor/impostor-metadata.js +77 -0
  42. package/build/internal/impostor/impostor-metadata.js.map +7 -0
  43. package/build/internal/impostor/impostor-node-material.js +1331 -0
  44. package/build/internal/impostor/impostor-node-material.js.map +7 -0
  45. package/build/internal/impostor/impostor-runtime-support.js +162 -0
  46. package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
  47. package/build/internal/impostor/octahedral.js +232 -0
  48. package/build/internal/impostor/octahedral.js.map +7 -0
  49. package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
  50. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
  51. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
  52. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
  53. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
  54. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
  55. package/build/internal/rendering/skin-projection.js +4630 -0
  56. package/build/internal/rendering/skin-projection.js.map +7 -0
  57. package/build/internal/rendering/surface-query.js +4519 -0
  58. package/build/internal/rendering/surface-query.js.map +7 -0
  59. package/build/internal/rendering/wireframe.js +112 -0
  60. package/build/internal/rendering/wireframe.js.map +7 -0
  61. package/build/internal/rendering/wrap-preview-settings.js +126 -0
  62. package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
  63. package/build/internal/rendering/wrap-preview.js +5610 -0
  64. package/build/internal/rendering/wrap-preview.js.map +7 -0
  65. package/build/internal/rendering/wrap-skin.js +4746 -0
  66. package/build/internal/rendering/wrap-skin.js.map +7 -0
  67. package/build/pixel-impostor-runtime.js +876 -0
  68. package/build/pixel-impostor-runtime.js.map +7 -0
  69. package/build/types/deformation/cloth-surface.d.ts +39 -0
  70. package/build/types/deformation/cloth-surface.js +1 -0
  71. package/build/types/deformation/fur-surface.d.ts +27 -0
  72. package/build/types/deformation/fur-surface.js +1 -0
  73. package/build/types/deformation/ik-constraints.d.ts +18 -0
  74. package/build/types/deformation/ik-constraints.js +1 -0
  75. package/build/types/deformation/joints-json.d.ts +17 -0
  76. package/build/types/deformation/joints-json.js +1 -0
  77. package/build/types/deformation/limits.d.ts +23 -0
  78. package/build/types/deformation/limits.js +1 -0
  79. package/build/types/deformation/motion-settings.d.ts +9 -0
  80. package/build/types/deformation/motion-settings.js +1 -0
  81. package/build/types/deformation/pin-cloth.d.ts +28 -0
  82. package/build/types/deformation/pin-cloth.js +1 -0
  83. package/build/types/deformation/pin-ik.d.ts +37 -0
  84. package/build/types/deformation/pin-ik.js +1 -0
  85. package/build/types/deformation/pin-types.d.ts +53 -0
  86. package/build/types/deformation/pin-types.js +1 -0
  87. package/build/types/deformation/pin-wiggle.d.ts +16 -0
  88. package/build/types/deformation/pin-wiggle.js +1 -0
  89. package/build/types/deformation/pose-slots.d.ts +41 -0
  90. package/build/types/deformation/pose-slots.js +1 -0
  91. package/build/types/deformation/pose-timeline.d.ts +65 -0
  92. package/build/types/deformation/pose-timeline.js +1 -0
  93. package/build/types/deformation/rig-drivers.d.ts +19 -0
  94. package/build/types/deformation/rig-drivers.js +1 -0
  95. package/build/types/deformation/rig-extension.d.ts +33 -0
  96. package/build/types/deformation/rig-extension.js +1 -0
  97. package/build/types/deformation/rig-runtime.d.ts +95 -0
  98. package/build/types/deformation/rig-runtime.js +1 -0
  99. package/build/types/deformation/wind.d.ts +16 -0
  100. package/build/types/deformation/wind.js +1 -0
  101. package/build/types/impostor/impostor-metadata.d.ts +61 -0
  102. package/build/types/impostor/impostor-metadata.js +1 -0
  103. package/build/types/impostor/impostor-node-material.d.ts +140 -0
  104. package/build/types/impostor/impostor-node-material.js +1 -0
  105. package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
  106. package/build/types/impostor/impostor-runtime-support.js +1 -0
  107. package/build/types/impostor/octahedral.d.ts +84 -0
  108. package/build/types/impostor/octahedral.js +1 -0
  109. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
  110. package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
  111. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
  112. package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
  113. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
  114. package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
  115. package/build/types/public/deformation-runtime.d.ts +3 -0
  116. package/build/types/public/deformation-runtime.js +1 -0
  117. package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
  118. package/build/types/public/impostor-runtime-needle-engine.js +1 -0
  119. package/build/types/public/impostor-runtime.d.ts +6 -0
  120. package/build/types/public/impostor-runtime.js +1 -0
  121. package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
  122. package/build/types/public/pixel-impostor-runtime.js +1 -0
  123. package/build/types/public/wrap-effects.d.ts +4 -0
  124. package/build/types/public/wrap-effects.js +1 -0
  125. package/build/types/rendering/skin-projection.d.ts +44 -0
  126. package/build/types/rendering/skin-projection.js +1 -0
  127. package/build/types/rendering/surface-query.d.ts +66 -0
  128. package/build/types/rendering/surface-query.js +1 -0
  129. package/build/types/rendering/wireframe.d.ts +25 -0
  130. package/build/types/rendering/wireframe.js +1 -0
  131. package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
  132. package/build/types/rendering/wrap-preview-settings.js +1 -0
  133. package/build/types/rendering/wrap-preview.d.ts +39 -0
  134. package/build/types/rendering/wrap-preview.js +1 -0
  135. package/build/types/rendering/wrap-skin.d.ts +14 -0
  136. package/build/types/rendering/wrap-skin.js +1 -0
  137. package/build/wrap-effects.js +5640 -0
  138. package/build/wrap-effects.js.map +7 -0
  139. package/package.json +105 -4
  140. package/src/deformation/cloth-surface.ts +223 -0
  141. package/src/deformation/fur-surface.ts +129 -0
  142. package/src/deformation/ik-constraints.ts +37 -0
  143. package/src/deformation/joints-json.ts +94 -0
  144. package/src/deformation/limits.ts +25 -0
  145. package/src/deformation/motion-settings.ts +9 -0
  146. package/src/deformation/pin-cloth.ts +149 -0
  147. package/src/deformation/pin-ik.ts +582 -0
  148. package/src/deformation/pin-types.ts +22 -0
  149. package/src/deformation/pin-wiggle.ts +119 -0
  150. package/src/deformation/pose-slots.ts +106 -0
  151. package/src/deformation/pose-timeline.ts +242 -0
  152. package/src/deformation/rig-drivers.ts +32 -0
  153. package/src/deformation/rig-extension.ts +87 -0
  154. package/src/deformation/rig-runtime.ts +416 -0
  155. package/src/deformation/wind.ts +36 -0
  156. package/src/impostor/impostor-metadata.js +137 -0
  157. package/src/impostor/impostor-node-material.js +1581 -0
  158. package/src/impostor/impostor-runtime-support.js +139 -0
  159. package/src/impostor/octahedral.js +280 -0
  160. package/src/pixel-impostor/pixel-impostor-display.js +794 -0
  161. package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
  162. package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
  163. package/src/public/deformation-runtime.ts +3 -0
  164. package/src/public/impostor-runtime-needle-engine.js +56 -0
  165. package/src/public/impostor-runtime.js +21 -0
  166. package/src/public/pixel-impostor-runtime.js +5 -0
  167. package/src/public/wrap-effects.js +21 -0
  168. package/src/rendering/skin-projection.js +113 -0
  169. package/src/rendering/surface-query.js +88 -0
  170. package/src/rendering/wireframe.js +115 -0
  171. package/src/rendering/wrap-preview-settings.js +123 -0
  172. package/src/rendering/wrap-preview.js +645 -0
  173. package/src/rendering/wrap-skin.js +109 -0
@@ -0,0 +1,74 @@
1
+ // @ts-check
2
+
3
+ export const NEEDLE_PIXEL_IMPOSTOR = 'NEEDLE_pixel_impostor';
4
+
5
+ /**
6
+ * @typedef {object} PixelImpostorDescriptor
7
+ * @property {1 | 2 | 3} version
8
+ * @property {[number, number, number]} dimensions
9
+ * @property {number} atlasColumns
10
+ * @property {number} atlasRows
11
+ * @property {[number, number, number]} volumeMin
12
+ * @property {[number, number, number]} volumeSize
13
+ * @property {[number, number, number]} occupiedMin
14
+ * @property {[number, number, number]} occupiedSize
15
+ * @property {number} alphaCutoff
16
+ * @property {'dense' | 'sparse'} storage
17
+ * @property {number=} surfaceCount
18
+ * @property {[number, number]=} surfaceAtlasSize
19
+ * @property {[number, number]=} indexAtlasSize
20
+ */
21
+
22
+ /** @param {unknown} value @returns {PixelImpostorDescriptor | null} */
23
+ export function parsePixelImpostorDescriptor(value) {
24
+ if (!value || typeof value !== 'object') return null;
25
+ const raw = /** @type {Record<string, unknown>} */ (value);
26
+ if ((raw.version !== 1 && raw.version !== 2 && raw.version !== 3) || !triplet(raw.dimensions) || !triplet(raw.volumeMin)
27
+ || !triplet(raw.volumeSize)) return null;
28
+ const dimensions = /** @type {number[]} */ (raw.dimensions);
29
+ const volumeSize = /** @type {number[]} */ (raw.volumeSize);
30
+ const occupiedMin = triplet(raw.occupiedMin)
31
+ ? /** @type {number[]} */ (raw.occupiedMin)
32
+ : /** @type {number[]} */ (raw.volumeMin);
33
+ const occupiedSize = triplet(raw.occupiedSize)
34
+ ? /** @type {number[]} */ (raw.occupiedSize)
35
+ : volumeSize;
36
+ if (!dimensions.every((item) => Number.isInteger(item) && item > 0)
37
+ || !volumeSize.every((item) => Number.isFinite(item) && item > 0)
38
+ || !occupiedSize.every((item) => Number.isFinite(item) && item > 0)
39
+ || (raw.version !== 3 && (!Number.isInteger(raw.atlasColumns) || Number(raw.atlasColumns) < 1
40
+ || !Number.isInteger(raw.atlasRows) || Number(raw.atlasRows) < 1))) return null;
41
+ const sparse = raw.version === 3 && raw.storage === 'sparse';
42
+ if (raw.version === 3 && (!sparse
43
+ || !Number.isInteger(raw.surfaceCount) || Number(raw.surfaceCount) < 1
44
+ || !pair(raw.surfaceAtlasSize) || !pair(raw.indexAtlasSize))) return null;
45
+ return /** @type {PixelImpostorDescriptor} */ ({
46
+ version: /** @type {1 | 2 | 3} */ (raw.version),
47
+ dimensions: [...dimensions],
48
+ atlasColumns: sparse ? 0 : Number(raw.atlasColumns),
49
+ atlasRows: sparse ? 0 : Number(raw.atlasRows),
50
+ volumeMin: [.../** @type {number[]} */ (raw.volumeMin)],
51
+ volumeSize: [...volumeSize],
52
+ occupiedMin: [...occupiedMin],
53
+ occupiedSize: [...occupiedSize],
54
+ alphaCutoff: Number.isFinite(raw.alphaCutoff) ? Number(raw.alphaCutoff) : 0.5,
55
+ storage: sparse ? 'sparse' : 'dense',
56
+ ...(sparse ? {
57
+ surfaceCount: Number(raw.surfaceCount),
58
+ surfaceAtlasSize: [.../** @type {number[]} */ (raw.surfaceAtlasSize)],
59
+ indexAtlasSize: [.../** @type {number[]} */ (raw.indexAtlasSize)],
60
+ } : {}),
61
+ });
62
+ }
63
+
64
+ /** @param {unknown} value */
65
+ function triplet(value) {
66
+ return Array.isArray(value) && value.length === 3
67
+ && value.every((item) => Number.isFinite(item));
68
+ }
69
+
70
+ /** @param {unknown} value */
71
+ function pair(value) {
72
+ return Array.isArray(value) && value.length === 2
73
+ && value.every((item) => Number.isInteger(item) && item > 0);
74
+ }
@@ -0,0 +1,78 @@
1
+ // @ts-check
2
+
3
+ import { ClampToEdgeWrapping, NearestFilter, NoColorSpace, SRGBColorSpace } from 'three';
4
+ import { NEEDLE_PIXEL_IMPOSTOR, parsePixelImpostorDescriptor } from './pixel-impostor-metadata.js';
5
+
6
+ /**
7
+ * Three.js GLTFLoader plugin for versioned pixel impostor atlas bindings.
8
+ * It leaves the portable voxel shell intact. Use `createPixelImpostorDisplay`
9
+ * after loading to select the workbench's TSL display modes.
10
+ */
11
+ export class NeedlePixelImpostorLoaderPlugin {
12
+ /** @param {unknown} parser */
13
+ constructor(parser) { this.name = NEEDLE_PIXEL_IMPOSTOR; this.parser = parser; }
14
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
15
+ async afterRoot(result) {
16
+ const parser = /** @type {{json:{meshes?:Array<{primitives:Array<{extensions?:Record<string,unknown>}>}>},associations:Map<import('three').Object3D,{meshes?:number,primitives?:number}>,getDependency(type:'texture',index:number):Promise<import('three').Texture>,getDependency(type:'accessor',index:number):Promise<import('three').BufferAttribute>}} */ (this.parser);
17
+ const pending = /** @type {Promise<void>[]} */ ([]);
18
+ // Scene-less glTFs are legal (e.g. material libraries). Leave validation
19
+ // to the consuming app instead of crashing during loader postprocessing.
20
+ result.scene?.traverse((object) => {
21
+ if (!('isMesh' in object) || object.isMesh !== true) return;
22
+ const association = parser.associations.get(object);
23
+ if (association?.meshes === undefined || association.primitives === undefined) return;
24
+ const raw = parser.json.meshes?.[association.meshes]
25
+ ?.primitives[association.primitives]?.extensions?.[NEEDLE_PIXEL_IMPOSTOR];
26
+ const descriptor = parsePixelImpostorDescriptor(raw);
27
+ if (!descriptor || !raw || typeof raw !== 'object') return;
28
+ const record = /** @type {Record<string, unknown>} */ (raw);
29
+ const atlasInfo = record.atlas;
30
+ const atlasIndex = atlasInfo && typeof atlasInfo === 'object' ? Reflect.get(atlasInfo, 'index') : undefined;
31
+ if (!Number.isInteger(atlasIndex)) throw new Error('NEEDLE_pixel_impostor has no atlas binding.');
32
+ /** @param {string} role @param {string} colorSpace @param {boolean} [required] */
33
+ const loadTexture = async (role, colorSpace, required = false) => {
34
+ const info = record[role];
35
+ const index = info && typeof info === 'object' ? Reflect.get(info, 'index') : undefined;
36
+ if (!Number.isInteger(index)) {
37
+ if (required) throw new Error(`NEEDLE_pixel_impostor has no ${role} binding.`);
38
+ return null;
39
+ }
40
+ const texture = await parser.getDependency('texture', Number(index));
41
+ texture.colorSpace = colorSpace;
42
+ texture.magFilter = NearestFilter;
43
+ texture.minFilter = NearestFilter;
44
+ texture.wrapS = ClampToEdgeWrapping;
45
+ texture.wrapT = ClampToEdgeWrapping;
46
+ texture.generateMipmaps = false;
47
+ texture.needsUpdate = true;
48
+ return texture;
49
+ };
50
+ const surfacePointsIndex = record.surfacePoints;
51
+ const surfacePointsPromise = Number.isInteger(surfacePointsIndex)
52
+ ? parser.getDependency('accessor', Number(surfacePointsIndex))
53
+ : Promise.resolve(null);
54
+ pending.push(Promise.all([
55
+ loadTexture('atlas', SRGBColorSpace, true),
56
+ loadTexture('normalAtlas', NoColorSpace),
57
+ loadTexture('ormAtlas', NoColorSpace),
58
+ loadTexture('indexAtlas', NoColorSpace, descriptor.version === 3),
59
+ surfacePointsPromise,
60
+ ]).then(([atlas, normalAtlas, ormAtlas, indexAtlas, surfacePoints]) => {
61
+ if (!atlas) throw new Error('NEEDLE_pixel_impostor atlas is unavailable.');
62
+ object.userData.pixelImpostor = {
63
+ descriptor, atlas, normalAtlas, ormAtlas, indexAtlas, surfacePoints,
64
+ };
65
+ }));
66
+ });
67
+ await Promise.all(pending);
68
+ }
69
+ }
70
+
71
+ /** Register pixel atlas loading before calling `loadAsync`; returns the same loader.
72
+ * @template {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} T
73
+ * @param {T} loader @returns {T}
74
+ */
75
+ export function registerNeedlePixelImpostorLoader(loader) {
76
+ loader.register((parser) => new NeedlePixelImpostorLoaderPlugin(parser));
77
+ return loader;
78
+ }
@@ -0,0 +1,3 @@
1
+ export { DeformationRigRuntime, NeedleDeformationRigLoaderPlugin, registerNeedleDeformationRigLoader, getDeformationRig } from '../deformation/rig-runtime.js';
2
+ export { NEEDLE_DEFORMATION_RIG, parseRigDescriptor, type RigDescriptor } from '../deformation/rig-extension.js';
3
+ export type { PinRecord, PinPose, Point, Rotation, IKTarget } from '../deformation/pin-types.js';
@@ -0,0 +1,56 @@
1
+ // @ts-check
2
+
3
+ import {
4
+ addCustomExtensionPlugin,
5
+ removeCustomImportExtensionType,
6
+ } from '@needle-tools/engine';
7
+ import { registerNeedleImpostorLoader } from '@needle-tools/three-mesh-effects/impostor-runtime';
8
+
9
+ /** @typedef {import('@needle-tools/engine').INeedleGLTFExtensionPlugin} INeedleGLTFExtensionPlugin */
10
+
11
+ /**
12
+ * Needle Engine adapter that installs the impostor Three.js loader plugin on
13
+ * every GLTFLoader created by the engine.
14
+ *
15
+ * @implements {INeedleGLTFExtensionPlugin}
16
+ */
17
+ export class NeedleEngineImpostorLoaderPlugin {
18
+ name = 'NeedleEngineImpostorLoaderPlugin';
19
+
20
+ /** @type {Parameters<typeof registerNeedleImpostorLoader>[1]} */
21
+ options;
22
+
23
+ /** @param {Parameters<typeof registerNeedleImpostorLoader>[1]=} options */
24
+ constructor(options = {}) {
25
+ this.options = options;
26
+ }
27
+
28
+ /**
29
+ * @param {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} loader
30
+ * @param {string} _url
31
+ * @param {import('@needle-tools/engine').Context} context
32
+ */
33
+ onImport = (loader, _url, context) => {
34
+ registerNeedleImpostorLoader(loader, {
35
+ ...this.options,
36
+ renderer: context.renderer,
37
+ });
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Registers impostor loading for all subsequent Needle Engine glTF imports.
43
+ * Keep the returned plugin if it needs to be unregistered later.
44
+ *
45
+ * @param {ConstructorParameters<typeof NeedleEngineImpostorLoaderPlugin>[0]=} options
46
+ */
47
+ export function registerNeedleEngineImpostorLoader(options = {}) {
48
+ const plugin = new NeedleEngineImpostorLoaderPlugin(options);
49
+ addCustomExtensionPlugin(plugin);
50
+ return plugin;
51
+ }
52
+
53
+ /** @param {NeedleEngineImpostorLoaderPlugin} plugin */
54
+ export function unregisterNeedleEngineImpostorLoader(plugin) {
55
+ removeCustomImportExtensionType(plugin);
56
+ }
@@ -0,0 +1,21 @@
1
+ // @ts-check
2
+
3
+ export {
4
+ DEFAULT_IMPOSTOR_RUNTIME_FEATURES,
5
+ IMPOSTOR_RUNTIME_SAMPLE_LIMITS,
6
+ NeedleImpostorLoaderPlugin,
7
+ createPbrImpostorNodeMaterial,
8
+ registerNeedleImpostorLoader,
9
+ rendererSupportsImpostorNodeMaterials,
10
+ resolveImpostorRuntimeFeatures,
11
+ upgradeImpostorScene,
12
+ } from '../impostor/impostor-node-material.js';
13
+ export {
14
+ NEEDLE_MESH_IMPOSTOR,
15
+ parseImpostorDescriptor,
16
+ } from '../impostor/impostor-metadata.js';
17
+
18
+ /** @typedef {import('../impostor/impostor-metadata.js').ImpostorDescriptor} ImpostorDescriptor */
19
+ /** @typedef {import('../impostor/impostor-node-material.js').ImpostorRuntimeFeatures} ImpostorRuntimeFeatures */
20
+ /** @typedef {import('../impostor/impostor-node-material.js').ResolvedImpostorRuntimeFeatures} ResolvedImpostorRuntimeFeatures */
21
+ /** @typedef {import('../impostor/impostor-node-material.js').ImpostorRenderer} ImpostorRenderer */
@@ -0,0 +1,5 @@
1
+ // @ts-check
2
+
3
+ export { NeedlePixelImpostorLoaderPlugin, registerNeedlePixelImpostorLoader } from '../pixel-impostor/pixel-impostor-runtime.js';
4
+ export { NEEDLE_PIXEL_IMPOSTOR, parsePixelImpostorDescriptor } from '../pixel-impostor/pixel-impostor-metadata.js';
5
+ export { createPixelImpostorDisplay, createPixelImpostorRaycastPreview } from '../pixel-impostor/pixel-impostor-display.js';
@@ -0,0 +1,21 @@
1
+ // @ts-check
2
+
3
+ export {
4
+ createWrapPreview,
5
+ prepareIceNormalAttributes,
6
+ prepareAuraGeometry,
7
+ prepareRayGeometry,
8
+ } from '../rendering/wrap-preview.js';
9
+ export {
10
+ WRAP_PREVIEW_MODES,
11
+ WRAP_PREVIEW_CONTROLS,
12
+ createWrapPreviewValues,
13
+ isWrapTopology,
14
+ } from '../rendering/wrap-preview-settings.js';
15
+ export { captureWrapSkinPose } from '../rendering/wrap-skin.js';
16
+ export {
17
+ createBarycentricWireframeGeometry,
18
+ createPreviewWireframeMaterial,
19
+ applyPreviewWireframeBlendMode,
20
+ parseWireframeBlendMode,
21
+ } from '../rendering/wireframe.js';
@@ -0,0 +1,113 @@
1
+ // @ts-check
2
+ import { Triangle, Vector3 } from 'three';
3
+ import { createSurfaceQuery } from './surface-query.js';
4
+ /** @typedef {{size: number, data: Float32Array}} SkinAttribute */
5
+ /** @typedef {{positions: Float32Array, indices: Uint32Array, attributes: Map<string, SkinAttribute>}} SkinGeometry */
6
+
7
+ /** @param {SkinGeometry[]} meshes @returns {SkinGeometry} */
8
+ export function mergeSkinGeometry(meshes) {
9
+ const semantics = new Set(meshes.flatMap(m => [...m.attributes.keys()]));
10
+ const count = meshes.reduce((s, m) => s + m.positions.length / 3, 0);
11
+ const attributes = new Map();
12
+ for (const semantic of semantics) {
13
+ const size = /** @type {SkinAttribute} */ (meshes.find(m => m.attributes.has(semantic))?.attributes.get(semantic)).size;
14
+ const data = new Float32Array(count * size);
15
+ if (semantic.startsWith('COLOR_')) data.fill(1);
16
+ let offset = 0;
17
+ for (const mesh of meshes) {
18
+ const attribute = mesh.attributes.get(semantic);
19
+ if (attribute) data.set(attribute.data, offset * size);
20
+ offset += mesh.positions.length / 3;
21
+ }
22
+ attributes.set(semantic, { size, data });
23
+ }
24
+ const indices = new Uint32Array(meshes.reduce((s, m) => s + m.indices.length, 0));
25
+ let vertexOffset = 0, indexOffset = 0;
26
+ for (const mesh of meshes) {
27
+ indices.set(mesh.indices.map(i => i + vertexOffset), indexOffset);
28
+ indexOffset += mesh.indices.length; vertexOffset += mesh.positions.length / 3;
29
+ }
30
+ return { positions: attributes.get('POSITION').data, indices, attributes };
31
+ }
32
+
33
+ /** Reusable triangle barycentrics for both weight transfer and pose validation.
34
+ * @param {SkinGeometry} surface
35
+ * @param {{fastBuild?: boolean}} [options] A fast build suits a query made for a few thousand lookups.
36
+ */
37
+ export function skinSurface(surface, options = {}) {
38
+ const query = createSurfaceQuery(surface, { fastBuild: options.fastBuild, geometryOnly: true });
39
+ const a = new Vector3(), b = new Vector3(), c = new Vector3(), p = new Vector3(), bary = new Vector3();
40
+ return {
41
+ dispose: () => query.dispose(),
42
+ /** @param {ArrayLike<number>} position */
43
+ closest(position) {
44
+ const hit = query.closestPoint(position);
45
+ if (!hit) throw new Error('Cannot project onto an empty surface.');
46
+ const vertices = Array.from(surface.indices.subarray(hit.faceIndex * 3, hit.faceIndex * 3 + 3));
47
+ a.fromArray(surface.positions, vertices[0] * 3); b.fromArray(surface.positions, vertices[1] * 3); c.fromArray(surface.positions, vertices[2] * 3);
48
+ if (!Triangle.getBarycoord(p.fromArray(hit.point), a, b, c, bary)) {
49
+ // Degenerate source triangles occur in collapsed supports and thin
50
+ // authored details. Use the closest segment, never stale barycentrics.
51
+ const corners = [a, b, c];
52
+ let distance = Infinity;
53
+ for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) {
54
+ const delta = corners[j].clone().sub(corners[i]);
55
+ const t = Math.max(0, Math.min(1, p.clone().sub(corners[i]).dot(delta) / (delta.lengthSq() || 1)));
56
+ const squared = corners[i].clone().addScaledVector(delta, t).distanceToSquared(p);
57
+ if (squared < distance) { distance = squared; bary.set(0, 0, 0).setComponent(i, 1 - t).setComponent(j, t); }
58
+ }
59
+ }
60
+ return { vertices, bary: bary.toArray(), point: hit.point, face: hit.faceIndex };
61
+ },
62
+ };
63
+ }
64
+
65
+ /** Transfer the closest source triangle's attributes. Joint IDs are categorical:
66
+ * accumulate contributions per ID, keep the strongest four, then normalize.
67
+ * Snapping is useful for point wraps, but reconstructed topology must retain
68
+ * its positions: independently snapping its vertices can invert or collapse
69
+ * triangles even though every individual vertex lands on the source.
70
+ * @param {SkinGeometry} source @param {{positions: Float32Array, indices: Uint32Array}} target
71
+ * @param {{snapPositions?: boolean}} [options]
72
+ * @returns {SkinGeometry}
73
+ */
74
+ export function projectSkinGeometry(source, target, options = {}) {
75
+ const query = skinSurface(source), count = target.positions.length / 3;
76
+ const attributes = new Map([...source.attributes].map(([s, a]) => [s, { size: a.size, data: new Float32Array(count * a.size) }]));
77
+ const positions = /** @type {SkinAttribute} */ (attributes.get('POSITION')).data;
78
+ try {
79
+ for (let i = 0; i < count; i++) {
80
+ const hit = query.closest(target.positions.subarray(i * 3, i * 3 + 3));
81
+ for (const [semantic, dest] of attributes) {
82
+ if (semantic === 'JOINTS_0' || semantic === 'WEIGHTS_0') continue;
83
+ const original = /** @type {SkinAttribute} */ (source.attributes.get(semantic));
84
+ for (let k = 0; k < dest.size; k++) dest.data[i * dest.size + k] = hit.vertices.reduce((sum, v, j) => sum + hit.bary[j] * original.data[v * dest.size + k], 0);
85
+ if (semantic === 'NORMAL' || semantic === 'TANGENT') {
86
+ const normal = new Vector3().fromArray(dest.data, i * dest.size).normalize();
87
+ normal.toArray(dest.data, i * dest.size);
88
+ if (semantic === 'TANGENT') dest.data[i * 4 + 3] = dest.data[i * 4 + 3] < 0 ? -1 : 1;
89
+ }
90
+ }
91
+ positions.set(options.snapPositions === false
92
+ ? target.positions.subarray(i * 3, i * 3 + 3)
93
+ : hit.point, i * 3);
94
+ const joints = source.attributes.get('JOINTS_0'), weights = source.attributes.get('WEIGHTS_0');
95
+ if (joints && weights) {
96
+ /** @type {Map<number, number>} */
97
+ const contributions = new Map();
98
+ hit.vertices.forEach((v, j) => { for (let k = 0; k < 4; k++) {
99
+ const id = joints.data[v * 4 + k], w = Math.max(0, hit.bary[j]) * weights.data[v * 4 + k];
100
+ if (w > 0) contributions.set(id, (contributions.get(id) ?? 0) + w);
101
+ } });
102
+ const strongest = [...contributions].sort((a, b) => b[1] - a[1]).slice(0, 4);
103
+ const total = strongest.reduce((s, [, w]) => s + w, 0);
104
+ if (!(total > 0)) throw new Error('Weight projection produced no joint influence.');
105
+ strongest.forEach(([id, w], k) => {
106
+ /** @type {SkinAttribute} */ (attributes.get('JOINTS_0')).data[i * 4 + k] = id;
107
+ /** @type {SkinAttribute} */ (attributes.get('WEIGHTS_0')).data[i * 4 + k] = w / total;
108
+ });
109
+ }
110
+ }
111
+ } finally { query.dispose(); }
112
+ return { positions, indices: target.indices, attributes };
113
+ }
@@ -0,0 +1,88 @@
1
+ // @ts-check
2
+ import { BackSide, BufferAttribute, BufferGeometry, FrontSide, Ray, Vector3 } from 'three';
3
+ import { MeshBVH, SAH, AVERAGE } from 'three-mesh-bvh';
4
+
5
+ /** @typedef {{positions: Float32Array, indices: Uint32Array, normals?: Float32Array, uvs?: Float32Array}} QueryMesh */
6
+ /** @param {QueryMesh} mesh */
7
+ function assertQueryMesh(mesh) {
8
+ if (!(mesh.positions instanceof Float32Array) || mesh.positions.length % 3) throw new TypeError('Invalid mesh positions.');
9
+ if (!(mesh.indices instanceof Uint32Array) || mesh.indices.length % 3) throw new TypeError('Invalid mesh indices.');
10
+ const count = mesh.positions.length / 3;
11
+ for (const index of mesh.indices) if (index >= count) throw new RangeError('Mesh index exceeds vertex count.');
12
+ }
13
+
14
+ /**
15
+ * @param {QueryMesh} mesh
16
+ * @param {{fastBuild?:boolean, geometryOnly?:boolean}=} options Fast builds use centroid-average splits; geometry-only queries omit UV/normal interpolation in ray hits.
17
+ */
18
+ export function createSurfaceQuery(mesh, options = {}) {
19
+ assertQueryMesh(mesh);
20
+ const geometry = new BufferGeometry();
21
+ geometry.setAttribute('position', new BufferAttribute(mesh.positions, 3));
22
+ if (mesh.normals && !options.geometryOnly) geometry.setAttribute('normal', new BufferAttribute(mesh.normals, 3));
23
+ if (mesh.uvs && !options.geometryOnly) geometry.setAttribute('uv', new BufferAttribute(mesh.uvs, 2));
24
+ geometry.setIndex(new BufferAttribute(mesh.indices, 1));
25
+ const bvh = new MeshBVH(geometry, {
26
+ strategy: options.fastBuild ? AVERAGE : SAH,
27
+ indirect: true,
28
+ verbose: false,
29
+ });
30
+
31
+ return createSurfaceQueryFromBvh(geometry, bvh);
32
+ }
33
+
34
+ /**
35
+ * Wraps a prebuilt BVH with the allocation-reusing query API used by the wrap skin preview and baker. The geometry and BVH must use indirect indexing so face IDs stay
36
+ * aligned with the source triangle arrays.
37
+ *
38
+ * @param {BufferGeometry} geometry
39
+ * @param {MeshBVH} bvh
40
+ */
41
+ export function createSurfaceQueryFromBvh(geometry, bvh) {
42
+
43
+ const point = new Vector3();
44
+ const direction = new Vector3();
45
+ const ray = new Ray(point, direction);
46
+ const closestTarget = {
47
+ point: new Vector3(),
48
+ distance: Infinity,
49
+ faceIndex: -1,
50
+ };
51
+
52
+ return {
53
+ geometry,
54
+ bvh,
55
+
56
+ /**
57
+ * @param {ArrayLike<number>} value
58
+ * @param {number=} maxDistance
59
+ */
60
+ closestPoint(value, maxDistance = Infinity) {
61
+ point.set(value[0], value[1], value[2]);
62
+ const hit = bvh.closestPointToPoint(point, closestTarget, 0, maxDistance);
63
+ if (!hit || hit.distance === undefined || hit.faceIndex === undefined || !hit.point) return null;
64
+ return {
65
+ point: [hit.point.x, hit.point.y, hit.point.z],
66
+ distance: hit.distance,
67
+ faceIndex: hit.faceIndex,
68
+ };
69
+ },
70
+
71
+ /**
72
+ * @param {ArrayLike<number>} origin
73
+ * @param {ArrayLike<number>} rayDirection
74
+ * @param {number} near
75
+ * @param {number} far
76
+ * @param {'front' | 'back'} side
77
+ */
78
+ raycastFirst(origin, rayDirection, near, far, side = 'front') {
79
+ point.set(origin[0], origin[1], origin[2]);
80
+ direction.set(rayDirection[0], rayDirection[1], rayDirection[2]).normalize();
81
+ return bvh.raycastFirst(ray, side === 'front' ? FrontSide : BackSide, near, far);
82
+ },
83
+
84
+ dispose() {
85
+ geometry.dispose();
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,115 @@
1
+ // @ts-check
2
+ import * as THREE from 'three';
3
+ import { MeshBasicNodeMaterial } from 'three/webgpu';
4
+ import { attribute, fwidth, min, vec3, uniform, float } from 'three/tsl';
5
+ /** @typedef {'black' | 'white' | 'invert'} WireframeBlendMode */
6
+
7
+ /**
8
+ * Produces a triangle overlay with a screen-space barycentric edge mask. Unlike
9
+ * hardware line primitives this supports stable, adjustable pixel thickness.
10
+ * @param {THREE.Material} sourceMaterial
11
+ * @param {boolean} isImpostor
12
+ * @param {number} thickness
13
+ * @param {WireframeBlendMode} blendMode
14
+ */
15
+ export function createPreviewWireframeMaterial(sourceMaterial, isImpostor, thickness, blendMode) {
16
+ const thicknessNode = uniform(thickness);
17
+ const barycentric = attribute('previewBarycentric', /** @type {'vec3'} */ ('vec3'));
18
+ const edgeMask = attribute('previewWireframeEdgeMask', /** @type {'vec3'} */ ('vec3'));
19
+ const derivative = fwidth(barycentric).max(vec3(1e-4));
20
+ const edgeDistanceVector = barycentric.div(derivative)
21
+ .add(vec3(1).sub(edgeMask).mul(1e4));
22
+ const edgeDistance = min(
23
+ edgeDistanceVector.x,
24
+ edgeDistanceVector.y,
25
+ edgeDistanceVector.z,
26
+ );
27
+ const halfWidth = thicknessNode.mul(0.5);
28
+ // Exact overlap of the requested line interval with a one-pixel box filter.
29
+ // The difference of the two ramps preserves integrated line energy for
30
+ // subpixel widths instead of quantizing or over-attenuating thin lines.
31
+ const coverage = halfWidth.add(0.5).sub(edgeDistance).clamp(0, 1).sub(
32
+ float(0.5).sub(halfWidth).sub(edgeDistance).clamp(0, 1),
33
+ );
34
+ const material = new MeshBasicNodeMaterial({
35
+ name: isImpostor ? 'Black impostor quad overlay' : 'Black mesh wireframe overlay',
36
+ color: 0x000000,
37
+ side: isImpostor ? THREE.DoubleSide : sourceMaterial.side,
38
+ depthTest: !isImpostor,
39
+ depthWrite: false,
40
+ polygonOffset: !isImpostor,
41
+ polygonOffsetFactor: -1,
42
+ polygonOffsetUnits: -1,
43
+ toneMapped: false,
44
+ });
45
+ material.transparent = true;
46
+ material.premultipliedAlpha = true;
47
+ material.opacityNode = coverage;
48
+ material.maskNode = coverage.greaterThan(1 / 1024);
49
+ if ('positionNode' in sourceMaterial) {
50
+ const sourceNodeMaterial = /** @type {import('three/webgpu').NodeMaterial} */ (sourceMaterial);
51
+ material.positionNode = sourceNodeMaterial.positionNode ?? null;
52
+ }
53
+ material.userData.previewWireframeThickness = thicknessNode;
54
+ applyPreviewWireframeBlendMode(material, blendMode);
55
+ return material;
56
+ }
57
+
58
+ /** @param {string} value @returns {WireframeBlendMode} */
59
+ export function parseWireframeBlendMode(value) {
60
+ return value === 'white' || value === 'invert' ? value : 'black';
61
+ }
62
+
63
+ /**
64
+ * @param {THREE.Material} material
65
+ * @param {WireframeBlendMode} mode
66
+ */
67
+ export function applyPreviewWireframeBlendMode(material, mode) {
68
+ const basic = /** @type {import('three/webgpu').MeshBasicNodeMaterial} */ (material);
69
+ basic.color.set(mode === 'black' ? 0x000000 : 0xffffff);
70
+ if (mode === 'invert') {
71
+ basic.blending = THREE.CustomBlending;
72
+ basic.blendEquation = THREE.AddEquation;
73
+ basic.blendSrc = THREE.OneMinusDstColorFactor;
74
+ basic.blendDst = THREE.OneMinusSrcColorFactor;
75
+ basic.blendEquationAlpha = THREE.AddEquation;
76
+ basic.blendSrcAlpha = THREE.OneFactor;
77
+ basic.blendDstAlpha = THREE.OneMinusSrcAlphaFactor;
78
+ } else {
79
+ basic.blending = THREE.NormalBlending;
80
+ }
81
+ basic.userData.previewWireframeBlendMode = mode;
82
+ basic.needsUpdate = true;
83
+ }
84
+
85
+ /**
86
+ * @param {THREE.BufferGeometry} source
87
+ * @returns {THREE.BufferGeometry}
88
+ */
89
+ export function createBarycentricWireframeGeometry(source) {
90
+ const geometry = source.index ? source.toNonIndexed() : source.clone();
91
+ const vertexCount = geometry.getAttribute('position')?.count ?? 0;
92
+ const barycentric = new Float32Array(vertexCount * 3);
93
+ const edgeMask = new Float32Array(vertexCount * 3);
94
+ const triangleMasks = source.userData.previewWireframeEdgeMasks;
95
+ for (let vertex = 0; vertex + 2 < vertexCount; vertex += 3) {
96
+ barycentric[(vertex + 0) * 3 + 0] = 1;
97
+ barycentric[(vertex + 1) * 3 + 1] = 1;
98
+ barycentric[(vertex + 2) * 3 + 2] = 1;
99
+ const triangle = vertex / 3;
100
+ const x = triangleMasks?.[triangle * 3] ?? 1;
101
+ const y = triangleMasks?.[triangle * 3 + 1] ?? 1;
102
+ const z = triangleMasks?.[triangle * 3 + 2] ?? 1;
103
+ for (let corner = 0; corner < 3; corner++) {
104
+ edgeMask[(vertex + corner) * 3] = x;
105
+ edgeMask[(vertex + corner) * 3 + 1] = y;
106
+ edgeMask[(vertex + corner) * 3 + 2] = z;
107
+ }
108
+ }
109
+ geometry.setAttribute('previewBarycentric', new THREE.BufferAttribute(barycentric, 3));
110
+ geometry.setAttribute(
111
+ 'previewWireframeEdgeMask',
112
+ new THREE.BufferAttribute(edgeMask, 3),
113
+ );
114
+ return geometry;
115
+ }