@margoengine/loaders 0.0.0-stage → 1.0.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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
@@ -0,0 +1,461 @@
1
+ // COLLADA 1.5 kinematics, clean room from the Khronos COLLADA 1.5.0 specification and schema (Khronos Group, 2008,
2
+ // https://www.khronos.org/files/collada_schema_1_5): joints, kinematics models, articulated systems and kinematics
3
+ // scenes, whose `bind_joint_axis` ties a joint axis to one transform of a visual scene node. Parameters and SID
4
+ // paths are resolved through the instance tree, so two instances of one model keep their own joints.
5
+ import { LoaderError } from './types.js';
6
+ import { daeRoot, readDAE } from './dae.js';
7
+ import { AXES, converter, F, IDENTITY, kid, kids, multiply, ref, stackMatrix } from './dae-common.js';
8
+ /** Instantiated kinematics elements per file. */
9
+ const MAX_SCOPES = 100_000;
10
+ const MAX_DEPTH = 64;
11
+ /** Elements and nodes visited while resolving SID paths, so a hostile file cannot cost the square of its size. */
12
+ const MAX_VISITS = 20_000_000;
13
+ // `link` trees hold no joint of their own and nest two levels per joint, so a long chain is not walked.
14
+ const SKIPPED = new Set(['asset', 'extra', 'technique', 'link', 'formula', 'instance_formula']);
15
+ const INSTANCES = new Set([
16
+ 'instance_kinematics_scene',
17
+ 'instance_articulated_system',
18
+ 'instance_kinematics_model',
19
+ 'instance_joint',
20
+ ]);
21
+ const PRIMITIVES = new Set(['revolute', 'prismatic']);
22
+ const textOf = (e) => e.attributes.ref ?? e.text.trim();
23
+ /** An address without a trailing member selector (".ANGLE", "(2)"), which names part of a value, not an element. */
24
+ const withoutMember = (sid) => sid.replace(/(\.\w+|\(\d+\))+$/, '');
25
+ class Resolver {
26
+ constructor(ids, warn) {
27
+ this.ids = ids;
28
+ this.warn = warn;
29
+ this.scopes = 0;
30
+ this.visits = 0;
31
+ /** `setparam` replacements, by the `newparam` they replace. */
32
+ this.overrides = new Map();
33
+ }
34
+ expand(element, parent, depth) {
35
+ if (++this.scopes > MAX_SCOPES || depth > MAX_DEPTH)
36
+ throw new LoaderError(F, 'limit', `the kinematics instances expand past ${MAX_SCOPES} elements or ${MAX_DEPTH} levels (an instance cycle?)`);
37
+ const scope = { element, children: [] };
38
+ if (parent)
39
+ scope.parent = parent;
40
+ const add = (from) => {
41
+ for (const child of from.children)
42
+ if (SKIPPED.has(child.name)) {
43
+ if (child.name.endsWith('formula'))
44
+ this.warn('kinematics formulas (coupled joints) are not evaluated: pose the dependent axes yourself');
45
+ }
46
+ else
47
+ scope.children.push(this.expand(child, scope, depth + 1));
48
+ };
49
+ add(element);
50
+ if (INSTANCES.has(element.name)) {
51
+ const url = element.attributes.url ?? '', target = url.startsWith('#') ? this.ids.get(ref(url)) : undefined;
52
+ if (target && target.name === element.name.slice('instance_'.length)) {
53
+ scope.target = target;
54
+ add(target);
55
+ }
56
+ else
57
+ this.warn(`${element.name} "${url}" names nothing in this file, so its joints are not imported`);
58
+ }
59
+ return scope;
60
+ }
61
+ /** Counts one element or node looked at. */
62
+ visit() {
63
+ if (++this.visits > MAX_VISITS)
64
+ throw new LoaderError(F, 'limit', 'resolving the kinematics SID paths visits too many elements');
65
+ }
66
+ /** The `newparam` of SID `sid` nearest below `owner`. */
67
+ parameter(owner, sid) {
68
+ const queue = [owner];
69
+ for (let i = 0; i < queue.length; i++) {
70
+ this.visit();
71
+ const scope = queue[i];
72
+ if (scope.element.name === 'newparam' && scope.element.attributes.sid === sid)
73
+ return scope;
74
+ for (const child of scope.children)
75
+ queue.push(child);
76
+ }
77
+ return undefined;
78
+ }
79
+ /** Breadth-first from `start`, as SID addresses are searched. */
80
+ search(start, token, seen) {
81
+ const queue = [start];
82
+ for (let i = 0; i < queue.length; i++) {
83
+ const scope = queue[i];
84
+ this.visit();
85
+ const { sid, id } = scope.element.attributes;
86
+ if ((sid === token || id === token || scope.target?.attributes.id === token) && !seen.has(scope))
87
+ return scope;
88
+ for (const child of scope.children)
89
+ queue.push(child);
90
+ }
91
+ return undefined;
92
+ }
93
+ /** A `newparam` holding a SIDREF stands for what the SIDREF names. */
94
+ follow(scope, seen) {
95
+ if (scope.element.name !== 'newparam')
96
+ return scope;
97
+ const value = (this.overrides.get(scope) ?? scope).children[0];
98
+ if (value?.element.name !== 'SIDREF')
99
+ return scope;
100
+ if (seen.size >= MAX_DEPTH)
101
+ return undefined;
102
+ return this.resolve(textOf(value.element), value, new Set(seen).add(scope));
103
+ }
104
+ /**
105
+ * The element a SID path or parameter name addresses, seen from `from`: the first segment is an id or SID searched
106
+ * in the nearest enclosing scope outward (`.` is `from` itself), each later one a SID below the last.
107
+ */
108
+ resolve(path, from, seen = new Set()) {
109
+ this.visit();
110
+ const [first, ...rest] = path.split('/');
111
+ let hit = first === '.' ? from : undefined;
112
+ for (let scope = from; scope && !hit; scope = scope.parent)
113
+ hit = this.search(scope, first, seen);
114
+ for (let i = 0; hit; i++) {
115
+ hit = this.follow(hit, seen);
116
+ if (!hit || i === rest.length)
117
+ break;
118
+ const token = rest[i], found = this.below(hit, token, seen);
119
+ hit = found ?? (i === rest.length - 1 ? this.below(hit, withoutMember(token), seen) : undefined);
120
+ }
121
+ return hit;
122
+ }
123
+ below(scope, token, seen) {
124
+ for (const child of scope.children) {
125
+ this.visit();
126
+ if (child.element.attributes.sid === token && !seen.has(child))
127
+ return child;
128
+ }
129
+ for (const child of scope.children) {
130
+ const found = this.search(child, token, seen);
131
+ if (found)
132
+ return found;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** The text of a value written plainly, as a typed child, or through a parameter. */
137
+ value(holder) {
138
+ const typed = holder.children.find((c) => /^(float|int|bool|param|SIDREF)$/.test(c.element.name));
139
+ if (!typed)
140
+ return holder.element.text.trim() || undefined;
141
+ if (typed.element.name !== 'param' && typed.element.name !== 'SIDREF')
142
+ return typed.element.text.trim();
143
+ const target = this.resolve(textOf(typed.element), holder);
144
+ const held = target && (this.overrides.get(target) ?? target);
145
+ return held && held !== holder ? held.children[0]?.element.text.trim() : undefined;
146
+ }
147
+ /** The `<revolute>` or `<prismatic>` an address leads to. */
148
+ axis(found, seen = 0) {
149
+ if (!found || seen > MAX_DEPTH)
150
+ return undefined;
151
+ const name = found.element.name;
152
+ if (PRIMITIVES.has(name))
153
+ return found;
154
+ if (name === 'axis' && found.parent && PRIMITIVES.has(found.parent.element.name))
155
+ return found.parent;
156
+ if (name === 'axis_info') {
157
+ const next = this.resolve(found.element.attributes.axis ?? '', found, new Set([found]));
158
+ return this.axis(next, seen + 1);
159
+ }
160
+ if (name === 'joint' || name === 'instance_joint') {
161
+ const primitives = found.children.filter((c) => PRIMITIVES.has(c.element.name));
162
+ if (primitives.length === 1)
163
+ return primitives[0];
164
+ }
165
+ return undefined;
166
+ }
167
+ }
168
+ const walk = (scope, visit) => {
169
+ visit(scope);
170
+ for (const child of scope.children)
171
+ walk(child, visit);
172
+ };
173
+ const part = (scope, name) => scope?.children.find((c) => c.element.name === name);
174
+ /** The transform of SID `sid` in `start` or nearest below it. */
175
+ function transformBelow(start, sid, resolver) {
176
+ const queue = [start];
177
+ for (let i = 0; i < queue.length; i++) {
178
+ resolver.visit();
179
+ const node = queue[i], transform = node.transforms.findIndex((t) => t.sid === sid);
180
+ if (transform >= 0)
181
+ return { node, transform };
182
+ for (const child of node.children)
183
+ queue.push(child);
184
+ }
185
+ return undefined;
186
+ }
187
+ /** The node of SID `sid` nearest below `start`. */
188
+ function nodeBelow(start, sid, resolver) {
189
+ const queue = [...start.children];
190
+ for (let i = 0; i < queue.length; i++) {
191
+ resolver.visit();
192
+ if (queue[i].sid === sid)
193
+ return queue[i];
194
+ for (const child of queue[i].children)
195
+ queue.push(child);
196
+ }
197
+ return undefined;
198
+ }
199
+ /** The node transforms `target` ("nodeId/sid/.../transformSid") names, one per copy of the node. */
200
+ function boundTransforms(byId, target, resolver) {
201
+ const [id, ...sids] = target.split('/'), last = sids.pop();
202
+ if (last === undefined)
203
+ return [];
204
+ const out = [];
205
+ for (const node of byId.get(id) ?? []) {
206
+ let from = node;
207
+ for (const step of sids)
208
+ from = from && nodeBelow(from, step, resolver);
209
+ if (!from)
210
+ continue;
211
+ // A trailing member selector (".ANGLE", "(2)") names one value of the transform.
212
+ const found = transformBelow(from, last, resolver) ?? transformBelow(from, withoutMember(last), resolver);
213
+ if (found)
214
+ out.push(found);
215
+ }
216
+ return out;
217
+ }
218
+ function readJoints(root, dae, warn) {
219
+ const ids = new Map();
220
+ const index = (e) => {
221
+ if (e.attributes.id)
222
+ ids.set(e.attributes.id, e);
223
+ for (const child of e.children)
224
+ index(child);
225
+ };
226
+ index(root);
227
+ let elements = kids(kid(root, 'scene'), 'instance_kinematics_scene');
228
+ if (!elements.length) {
229
+ elements = kids(root, 'library_kinematics_scenes').flatMap((l) => kids(l, 'kinematics_scene'));
230
+ if (!elements.length) {
231
+ if (kid(root, 'library_joints') || kid(root, 'library_kinematics_models'))
232
+ warn('the file has joints but no kinematics scene, so no joint is imported');
233
+ return [];
234
+ }
235
+ warn('<scene> instances no kinematics scene, so the joints drive no node');
236
+ }
237
+ const resolver = new Resolver(ids, warn), roots = elements.map((e) => resolver.expand(e, undefined, 0));
238
+ // setparam: inner instances first, so that an outer one has the last word.
239
+ const setters = [];
240
+ for (const scope of roots)
241
+ walk(scope, (s) => s.element.name === 'setparam' && setters.push(s));
242
+ for (const setter of setters.reverse()) {
243
+ const name = setter.element.attributes.ref ?? '', from = setter.parent;
244
+ // The reference names the parameter itself, so it is found without following what the parameter holds.
245
+ const split = name.lastIndexOf('/'), owner = split < 0 ? from : resolver.resolve(name.slice(0, split), from), last = name.slice(split + 1);
246
+ const found = owner && resolver.parameter(owner, last);
247
+ if (found)
248
+ resolver.overrides.set(found, setter);
249
+ else
250
+ warn(`setparam "${name}" names no parameter`);
251
+ }
252
+ const upAxis = AXES[dae.upAxis], axes = new Map(),
253
+ /** How many axes already have each path. */
254
+ taken = new Map(), tokens = [];
255
+ const number = (holder, scale, what) => {
256
+ if (!holder)
257
+ return undefined;
258
+ const text = resolver.value(holder), value = text === undefined ? Number.NaN : Number(text);
259
+ if (Number.isFinite(value))
260
+ return value * scale;
261
+ warn(`${what} has no finite value`);
262
+ return undefined;
263
+ };
264
+ const unit = (axis) => (axis.type === 'prismatic' ? dae.meter : 1);
265
+ const limit = (axis, limits) => {
266
+ for (const end of ['min', 'max']) {
267
+ const value = number(part(limits, end), unit(axis), `axis "${axis.path}" <${end}>`);
268
+ if (value !== undefined)
269
+ axis[end] = value;
270
+ }
271
+ };
272
+ const collect = (scope, path, joint) => {
273
+ const { name, attributes } = scope.element;
274
+ if (name === 'joint' || name === 'instance_joint')
275
+ joint = scope;
276
+ if (PRIMITIVES.has(name)) {
277
+ const text = part(scope, 'axis')?.element.text.trim() ?? '', v = text.split(/\s+/).map(Number), length = Math.hypot(...v);
278
+ if (v.length !== 3 || !(length > 0 && Number.isFinite(length)))
279
+ throw new LoaderError(F, 'syntax', `<${name}> needs an <axis> of three finite numbers, not all zero`);
280
+ const owner = joint?.element, definition = joint?.target ?? owner, token = owner?.attributes.sid ?? definition?.attributes.sid ?? definition?.attributes.id ?? 'joint', sid = attributes.sid ?? name;
281
+ const written = [...path, sid].join('/'), copy = (taken.get(written) ?? 0) + 1, full = copy > 1 ? `${written}#${copy}` : written;
282
+ taken.set(written, copy);
283
+ const axis = {
284
+ name: full,
285
+ path: full,
286
+ joint: definition?.attributes.name ?? token,
287
+ type: name,
288
+ axis: [0, 1, 2].map((r) => (upAxis[r * 3] * v[0] + upAxis[r * 3 + 1] * v[1] + upAxis[r * 3 + 2] * v[2]) / length),
289
+ value: 0,
290
+ active: true,
291
+ locked: false,
292
+ targets: [],
293
+ };
294
+ limit(axis, part(scope, 'limits'));
295
+ axes.set(scope, axis);
296
+ tokens.push({ joint: token, axis: sid });
297
+ return;
298
+ }
299
+ // technique_common and library containers have no SID, so they leave no step in the path.
300
+ const next = attributes.sid === undefined ? path : [...path, attributes.sid];
301
+ for (const child of scope.children)
302
+ collect(child, next, joint);
303
+ };
304
+ for (const scope of roots)
305
+ collect(scope, [], undefined);
306
+ const infos = [];
307
+ for (const scope of roots)
308
+ walk(scope, (s) => s.element.name === 'axis_info' && infos.push(s));
309
+ // A motion system's technique follows the system it instances, so document order applies inner bounds first.
310
+ for (const info of infos) {
311
+ const scope = resolver.axis(info), axis = scope && axes.get(scope);
312
+ if (!axis) {
313
+ warn(`axis_info "${info.element.attributes.axis ?? ''}" names no joint axis`);
314
+ continue;
315
+ }
316
+ limit(axis, part(info, 'limits'));
317
+ for (const flag of ['active', 'locked']) {
318
+ const holder = part(info, flag), text = holder && resolver.value(holder);
319
+ if (text !== undefined)
320
+ axis[flag] = text === 'true' || text === '1';
321
+ }
322
+ const order = number(part(info, 'index'), 1, `axis "${axis.path}" <index>`);
323
+ if (order !== undefined)
324
+ axis.index = order;
325
+ for (const bound of ['speed', 'acceleration', 'deceleration', 'jerk']) {
326
+ const value = number(part(info, bound), unit(axis), `axis "${axis.path}" <${bound}>`);
327
+ if (value !== undefined)
328
+ axis[bound] = value;
329
+ }
330
+ }
331
+ for (const axis of axes.values())
332
+ if (axis.min !== undefined && axis.max !== undefined && axis.min > axis.max) {
333
+ warn(`axis "${axis.path}" has its lower limit above its upper one, so it has no limits`);
334
+ delete axis.min;
335
+ delete axis.max;
336
+ }
337
+ const byId = new Map();
338
+ const register = (node) => {
339
+ if (node.id !== undefined) {
340
+ const list = byId.get(node.id);
341
+ if (list)
342
+ list.push(node);
343
+ else
344
+ byId.set(node.id, [node]);
345
+ }
346
+ for (const child of node.children)
347
+ register(child);
348
+ };
349
+ for (const node of dae.nodes)
350
+ register(node);
351
+ const initial = new Set();
352
+ for (const scope of roots)
353
+ for (const bind of scope.children) {
354
+ if (bind.element.name !== 'bind_joint_axis')
355
+ continue;
356
+ const target = bind.element.attributes.target ?? '', holder = part(bind, 'axis'), written = holder?.children[0], found = written
357
+ ? resolver.resolve(textOf(written.element), written)
358
+ : holder && resolver.resolve(holder.element.text.trim(), holder), primitive = resolver.axis(found), axis = primitive && axes.get(primitive);
359
+ if (!axis) {
360
+ warn(`bind_joint_axis "${target}" names no joint axis`);
361
+ continue;
362
+ }
363
+ const value = number(part(bind, 'value'), unit(axis), `bind_joint_axis "${target}" <value>`);
364
+ if (value !== undefined) {
365
+ axis.value = value;
366
+ initial.add(axis);
367
+ }
368
+ if (!target)
369
+ continue;
370
+ const wanted = axis.type === 'revolute' ? 'rotate' : 'translate', targets = boundTransforms(byId, target, resolver);
371
+ if (!targets.length)
372
+ warn(`bind_joint_axis target "${target}" names no node transform`);
373
+ for (const t of targets)
374
+ if (t.node.transforms[t.transform].type !== wanted)
375
+ warn(`bind_joint_axis target "${target}" is not a <${wanted}>, which a ${axis.type} axis needs`);
376
+ else
377
+ axis.targets.push(t);
378
+ }
379
+ // Without a bound value, an axis starts where its first target stands.
380
+ for (const axis of axes.values()) {
381
+ const first = axis.targets[0];
382
+ if (initial.has(axis) || !first)
383
+ continue;
384
+ const v = first.node.transforms[first.transform].values, along = fileAxis(upAxis, axis.axis), dot = along[0] * v[0] + along[1] * v[1] + along[2] * v[2];
385
+ axis.value = axis.type === 'revolute' ? v[3] * Math.sign(dot) : dot * dae.meter;
386
+ }
387
+ const list = [...axes.values()], candidates = tokens.map((t, i) => [t.joint, `${t.joint}/${t.axis}`, list[i].path]);
388
+ for (let level = 0; level < 2; level++) {
389
+ const count = new Map();
390
+ for (const c of candidates)
391
+ count.set(c[level], (count.get(c[level]) ?? 0) + 1);
392
+ list.forEach((axis, i) => {
393
+ if (axis.name === axis.path && count.get(candidates[i][level]) === 1)
394
+ axis.name = candidates[i][level];
395
+ });
396
+ }
397
+ return list;
398
+ }
399
+ /** The inverse of the up-axis rotation: a Y-up direction back in the file's axes. */
400
+ const fileAxis = (upAxis, v) => [0, 1, 2].map((c) => upAxis[c] * v[0] + upAxis[3 + c] * v[1] + upAxis[6 + c] * v[2]);
401
+ /**
402
+ * `parseDAE` plus the document's COLLADA 1.5 kinematics: `joints` lists every revolute and prismatic axis of the
403
+ * instanced kinematics scenes with its limits, its `axis_info` data and the node transforms it drives. What cannot be
404
+ * resolved is reported in `warnings`. Formulas, closed-loop attachments and tool frames are not evaluated.
405
+ */
406
+ export function parseDAEKinematics(input, options = {}) {
407
+ const root = daeRoot(input, options), dae = readDAE(root, options), warnings = new Set(dae.warnings), joints = readJoints(root, dae, (message) => void warnings.add(message));
408
+ return { ...dae, warnings: [...warnings], joints };
409
+ }
410
+ /**
411
+ * The scene with its joints at the given values (degrees for revolute axes, meters for prismatic ones), for
412
+ * `flattenDAE` or your own meshes: `world` holds every node's matrix. An axis left out stands at its `value`. Each
413
+ * bound transform becomes the axis' motion: a rotation about `axis`, or a translation along it. Values are held
414
+ * inside the limits unless `clamp` is false.
415
+ */
416
+ export function poseDAEJoints(dae, values = {}, options = {}) {
417
+ const byName = new Map(dae.joints.map((j) => [j.name, j]));
418
+ for (const name of Object.keys(values))
419
+ if (!byName.has(name))
420
+ throw new RangeError(`DAE joint "${name}" does not exist; pass one of ${[...byName.keys()].slice(0, 32).join(', ') || '(none)'}`);
421
+ const upAxis = AXES[dae.upAxis], changed = new Map();
422
+ for (const axis of dae.joints) {
423
+ let value = axis.value;
424
+ if (Object.hasOwn(values, axis.name)) {
425
+ value = values[axis.name];
426
+ if (typeof value !== 'number' || !Number.isFinite(value))
427
+ throw new RangeError(`DAE joint "${axis.name}" value ${value} is invalid; pass a finite number`);
428
+ if (axis.locked && value !== axis.value)
429
+ throw new RangeError(`DAE joint "${axis.name}" is locked at ${axis.value}; leave it out`);
430
+ if (options.clamp !== false)
431
+ value = Math.min(axis.max ?? Infinity, Math.max(axis.min ?? -Infinity, value));
432
+ }
433
+ const along = fileAxis(upAxis, axis.axis);
434
+ for (const { node, transform } of axis.targets) {
435
+ let list = changed.get(node);
436
+ if (!list)
437
+ changed.set(node, (list = node.transforms.slice()));
438
+ const moved = axis.type === 'revolute'
439
+ ? { type: 'rotate', values: [...along, value] }
440
+ : {
441
+ type: 'translate',
442
+ values: along.map((a) => (a * value) / dae.meter),
443
+ };
444
+ const sid = list[transform].sid;
445
+ if (sid !== undefined)
446
+ moved.sid = sid;
447
+ list[transform] = moved;
448
+ }
449
+ }
450
+ const convert = converter(dae.upAxis, dae.meter), local = new Map(), world = new Map();
451
+ const place = (node, parent) => {
452
+ const list = changed.get(node), matrix = list ? convert(stackMatrix(list)) : node.matrix, w = multiply(parent, matrix);
453
+ local.set(node, matrix);
454
+ world.set(node, w);
455
+ for (const child of node.children)
456
+ place(child, w);
457
+ };
458
+ for (const node of dae.nodes)
459
+ place(node, IDENTITY);
460
+ return { local, world, weights: dae.morphs.map((m) => [...m.weights]) };
461
+ }
@@ -0,0 +1,131 @@
1
+ import type { MutableVec3 } from '@margoengine/math';
2
+ import { type Matrix } from './dae-common.js';
3
+ import type { DAEGeometry, DAEGroup, DAEInstance, DAENode, LoadedDAE } from './dae.js';
4
+ /** A parsed COLLADA scene posed at one time by {@link poseDAE}. */
5
+ export interface DAEPose {
6
+ /** Local matrix of every node (column-major, Y-up meters): animated where channels address it, else `node.matrix`. */
7
+ local: Map<DAENode, number[]>;
8
+ /** World matrix of every node. */
9
+ world: Map<DAENode, number[]>;
10
+ /** Weights of every morph, by index into `LoadedDAE.morphs`: animated where channels address them, else defaults. */
11
+ weights: number[][];
12
+ }
13
+ /** Options of {@link poseDAE} and {@link daeKeyframeClip}. */
14
+ export interface DAEPoseOptions {
15
+ /** Play only this `LoadedDAE.clips` entry, with time 0 at its start (held at its end). Default: every animation. */
16
+ clip?: number;
17
+ }
18
+ /**
19
+ * A mesh with normals, ready for a materials `createMesh` or `mesh.setGeometry`. Its groups number the primitives
20
+ * (`materialIndex` 0, 1, ...) for a material array; a single material ignores them.
21
+ */
22
+ export type DAEMeshGeometry = Omit<DAEGeometry, 'groups'> & {
23
+ normals: Float32Array;
24
+ groups: (DAEGroup & {
25
+ materialIndex: number;
26
+ })[];
27
+ };
28
+ /**
29
+ * Every node's local and world matrix and every morph's weights at `time` seconds, from the document's animation
30
+ * channels (or one clip's). Channels replace values of the node's transform stack as written, which is then converted
31
+ * to Y-up meters like `node.matrix`.
32
+ */
33
+ export declare function poseDAE(dae: LoadedDAE, time: number, options?: DAEPoseOptions): DAEPose;
34
+ /** The scene at rest: `node.matrix` everywhere and the morphs' default weights. */
35
+ export declare function restPose(dae: LoadedDAE): DAEPose;
36
+ /**
37
+ * A copy of a morph's base mesh with its targets blended at `weights` (default: the morph's own weights), position
38
+ * by position: `NORMALIZED` (1 - sum w) base + sum w target, `RELATIVE` base + sum w target. Normals blend the same
39
+ * way and are renormalised (computed when the base has none). Vertex order is the base mesh's, so the result can
40
+ * replace a mesh's geometry every frame.
41
+ */
42
+ export declare function morphDAE(dae: LoadedDAE, morph: number, weights?: ArrayLike<number>): DAEMeshGeometry;
43
+ /**
44
+ * @internal An instance's mesh in world space at a pose: morphed by the pose's weights, then skinned by its joints'
45
+ * world matrices (sum w joint * inverseBind * bindShape) or moved by `world`. `flip` is set when the transform
46
+ * mirrors, so the caller can keep outward winding.
47
+ */
48
+ export declare function deformInstance(dae: LoadedDAE, instance: DAEInstance, world: Matrix, pose: DAEPose): {
49
+ positions: Float32Array;
50
+ normals?: Float32Array;
51
+ flip: boolean;
52
+ };
53
+ /**
54
+ * A unique name for every node, depth first: its id, else its name, else `node`, with `#2`, `#3`... added to repeats
55
+ * (copies made by `instance_node`). Bones of {@link bindDAESkin} and tracks of {@link daeKeyframeClip} use these.
56
+ */
57
+ export declare function daeNodeNames(dae: LoadedDAE): Map<DAENode, string>;
58
+ /** One bone for the animation package's `Skeleton`: a node's local transform split into TRS. */
59
+ export interface DAEBone {
60
+ /** The node's name from {@link daeNodeNames}, which keyframe tracks target. */
61
+ name: string;
62
+ /** Index of the parent bone, -1 for the root. */
63
+ parent: number;
64
+ translation: MutableVec3;
65
+ rotation: [number, number, number, number];
66
+ scale: MutableVec3;
67
+ }
68
+ /**
69
+ * A skinned instance ready for the animation package: `new Skeleton(bones, inverseBindMatrices)` and
70
+ * `Skin.attach(mesh, skeleton, joints, weights)` on a mesh made from `geometry`. Bones live in scene (world) space,
71
+ * so put the mesh at the scene root with an identity transform.
72
+ */
73
+ export interface DAESkinBinding {
74
+ /** The node holding the `<instance_controller>`. */
75
+ node: DAENode;
76
+ instance: DAEInstance;
77
+ /** The mesh in its bind shape (`bind_shape_matrix` applied, morphs at the given weights), in Y-up meters. */
78
+ geometry: DAEMeshGeometry;
79
+ /** Every joint node and its ancestors in scene order; an identity root bone is added when needed. */
80
+ bones: DAEBone[];
81
+ /** 16 column-major numbers per bone: the skin's for joints, the inverse rest world matrix for other bones. */
82
+ inverseBindMatrices: Float64Array;
83
+ /** Four bone indices per vertex of `geometry`. */
84
+ joints: Uint32Array;
85
+ /** Four weights per vertex, summing to 1 (all zero follows the root bone). */
86
+ weights: Float32Array;
87
+ }
88
+ /** Options of {@link bindDAESkin}. */
89
+ export interface DAESkinBindingOptions {
90
+ /** Weights for a skin over a morph (default: the morph's own). */
91
+ weights?: ArrayLike<number>;
92
+ }
93
+ /**
94
+ * Skeleton and skin data of a skinned instance (default: the first one in the scene) for the animation package's
95
+ * `Skeleton` and `Skin`. Throws a `LoaderError` (`unsupported`) when the document has no skinned instance.
96
+ */
97
+ export declare function bindDAESkin(dae: LoadedDAE, instance?: DAEInstance, options?: DAESkinBindingOptions): DAESkinBinding;
98
+ /** One key of a {@link DAEKeyframeTrack}: the shape of the animation package's `Keyframe`. */
99
+ export interface DAEKeyframe {
100
+ /** Seconds from the clip's start. */
101
+ time: number;
102
+ /** [x, y, z] translation or scale, an [x, y, z, w] quaternion, or one weight per morph target. */
103
+ value: number[];
104
+ interpolation: 'linear' | 'discrete';
105
+ }
106
+ /** Keys for one property of one node: the shape of the animation package's `KeyframeTrackData`. */
107
+ export interface DAEKeyframeTrack {
108
+ /** The node's name from {@link daeNodeNames} (a bone name of {@link bindDAESkin}). */
109
+ target: string;
110
+ path: 'translation' | 'rotation' | 'scale' | 'weights';
111
+ keys: DAEKeyframe[];
112
+ }
113
+ /** A clip in the shape of the animation package's `KeyframeClipData`, for `createKeyframeClip`. */
114
+ export interface DAEKeyframeClip {
115
+ name: string;
116
+ tracks: DAEKeyframeTrack[];
117
+ }
118
+ /** Options of {@link daeKeyframeClip}. */
119
+ export interface DAEKeyframeClipOptions extends DAEPoseOptions {
120
+ /** Samples per second between keys. Default 30. */
121
+ fps?: number;
122
+ /** Clip name. Default: the clip's name or id, else `''`. */
123
+ name?: string;
124
+ }
125
+ /**
126
+ * The document's animation (or one clip) as keyframe tracks: translation, rotation and scale for every animated node
127
+ * and weights for every node whose morph is animated. COLLADA channels address single transform elements, so each
128
+ * node is sampled at every key time of its channels and every `1 / fps` second between them, then split into TRS
129
+ * (exact at those times, linear between); a node whose channels all STEP keeps only its keys, held (`discrete`).
130
+ */
131
+ export declare function daeKeyframeClip(dae: LoadedDAE, options?: DAEKeyframeClipOptions): DAEKeyframeClip;