usd-gltf 0.0.0-stage → 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +56 -2
- package/bin/usd-gltf.js +53 -0
- package/package.json +47 -4
- package/src/convert/gltf-to-usd.js +1807 -0
- package/src/convert/usd-material.js +1039 -0
- package/src/convert/usd-mesh.js +329 -0
- package/src/convert/usd-shapes.js +202 -0
- package/src/convert/usd-to-gltf.js +1325 -0
- package/src/detect.js +28 -0
- package/src/gltf/document.js +353 -0
- package/src/gltf/glb.js +105 -0
- package/src/gltf/meshopt.js +537 -0
- package/src/image/deflate.js +705 -0
- package/src/image/index.js +96 -0
- package/src/image/inflate.js +520 -0
- package/src/image/jpeg.js +1025 -0
- package/src/image/png.js +560 -0
- package/src/image/webp-tables.js +119 -0
- package/src/image/webp.js +1634 -0
- package/src/index.js +67 -0
- package/src/usd/model.js +237 -0
- package/src/usd/stage.js +880 -0
- package/src/usd/usda/reader.js +853 -0
- package/src/usd/usda/writer.js +375 -0
- package/src/usd/usdc/intcompression.js +220 -0
- package/src/usd/usdc/lz4.js +295 -0
- package/src/usd/usdc/reader.js +1079 -0
- package/src/usd/usdc/types.js +162 -0
- package/src/usd/usdc/writer.js +1108 -0
- package/src/usd/usdz.js +141 -0
- package/src/usd/xform.js +99 -0
- package/src/util/crc32.js +18 -0
- package/src/util/math.js +235 -0
|
@@ -0,0 +1,1807 @@
|
|
|
1
|
+
// glTF -> USD layer (plus the image files a usdz package needs).
|
|
2
|
+
//
|
|
3
|
+
// Mapping:
|
|
4
|
+
// nodes Xform prims with translate / orient / scale ops (time sampled when animated)
|
|
5
|
+
// mesh primitives Mesh prims (Points / BasisCurves for point and line modes) under the node
|
|
6
|
+
// materials UsdPreviewSurface networks; glTF data UsdPreviewSurface can't express is kept
|
|
7
|
+
// as JSON in the material's customData so converting back is lossless
|
|
8
|
+
// skins a SkelRoot per skin with Skeleton, SkelAnimation and the skinned meshes
|
|
9
|
+
// morph targets BlendShapes driven by a SkelAnimation
|
|
10
|
+
// animations time samples; several animations become variants of an "animation" variant set
|
|
11
|
+
// materials variants a "materialVariant" variant set switching material bindings
|
|
12
|
+
// cameras, KHR_lights_punctual, KHR_node_visibility, EXT_mesh_gpu_instancing (PointInstancer)
|
|
13
|
+
|
|
14
|
+
import { AssetPath, Layer, ListOp, PrimSpec, PropertySpec } from '../usd/model.js';
|
|
15
|
+
import { compose, decompose, identity, invert, multiply } from '../util/math.js';
|
|
16
|
+
import { decodeImageAsync, encodePNG, imageMimeType } from '../image/index.js';
|
|
17
|
+
|
|
18
|
+
const MODES = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6 };
|
|
19
|
+
const WRAP = { 10497: 'repeat', 33648: 'mirror', 33071: 'clamp' };
|
|
20
|
+
const TIME_CODES_PER_SECOND = 60;
|
|
21
|
+
|
|
22
|
+
// Extensions whose data is fully expressed in USD; anything else on a material is stashed.
|
|
23
|
+
const MAPPED_MATERIAL_EXTENSIONS = new Set( [ 'KHR_materials_emissive_strength', 'KHR_materials_ior', 'KHR_materials_clearcoat' ] );
|
|
24
|
+
|
|
25
|
+
function sanitize( name, fallback ) {
|
|
26
|
+
|
|
27
|
+
let s = String( name ?? '' ).normalize( 'NFKD' ).replace( /[^A-Za-z0-9_]/g, '_' );
|
|
28
|
+
if ( ! s || ! /[A-Za-z0-9]/.test( s ) ) s = fallback;
|
|
29
|
+
if ( /^[0-9]/.test( s ) ) s = '_' + s;
|
|
30
|
+
return s;
|
|
31
|
+
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
class Builder {
|
|
35
|
+
|
|
36
|
+
constructor() {
|
|
37
|
+
|
|
38
|
+
this.layer = new Layer( 'root.usda' );
|
|
39
|
+
this.paths = new Map(); // PrimSpec -> path
|
|
40
|
+
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
uniqueName( parent, name ) {
|
|
44
|
+
|
|
45
|
+
let n = name, i = 1;
|
|
46
|
+
while ( parent.children.has( n ) || parent.properties.has( n ) ) n = `${ name }_${ i ++ }`;
|
|
47
|
+
return n;
|
|
48
|
+
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
def( parent, name, typeName = '', specifier = 'def' ) {
|
|
52
|
+
|
|
53
|
+
const spec = parent.addChild( new PrimSpec( this.uniqueName( parent, name ), specifier, typeName ) );
|
|
54
|
+
const parentPath = this.paths.get( parent ) ?? '';
|
|
55
|
+
this.paths.set( spec, ( parentPath === '/' ? '' : parentPath ) + '/' + spec.name );
|
|
56
|
+
return spec;
|
|
57
|
+
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
path( spec ) {
|
|
61
|
+
|
|
62
|
+
return this.paths.get( spec );
|
|
63
|
+
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
attr( prim, name, typeName, value, { interpolation, uniform = false, metadata = {}, timeSamples = null, custom = false } = {} ) {
|
|
67
|
+
|
|
68
|
+
const p = prim.addProperty( new PropertySpec( name, 'attribute' ) );
|
|
69
|
+
p.typeName = typeName;
|
|
70
|
+
if ( value !== undefined ) p.default = value;
|
|
71
|
+
if ( timeSamples ) p.timeSamples = timeSamples;
|
|
72
|
+
if ( uniform ) p.variability = 'uniform';
|
|
73
|
+
if ( custom ) p.custom = true;
|
|
74
|
+
if ( interpolation ) p.metadata.interpolation = interpolation;
|
|
75
|
+
Object.assign( p.metadata, metadata );
|
|
76
|
+
return p;
|
|
77
|
+
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
connect( prim, name, typeName, target ) {
|
|
81
|
+
|
|
82
|
+
const p = prim.addProperty( new PropertySpec( name, 'attribute' ) );
|
|
83
|
+
p.typeName = typeName;
|
|
84
|
+
p.connections = ListOp.explicit( [ target ] );
|
|
85
|
+
return p;
|
|
86
|
+
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
rel( prim, name, targets, metadata = {} ) {
|
|
90
|
+
|
|
91
|
+
const p = prim.addProperty( new PropertySpec( name, 'relationship' ) );
|
|
92
|
+
p.targets = ListOp.explicit( targets );
|
|
93
|
+
Object.assign( p.metadata, metadata );
|
|
94
|
+
return p;
|
|
95
|
+
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
apiSchema( prim, name ) {
|
|
99
|
+
|
|
100
|
+
const op = prim.metadata.apiSchemas ||= new ListOp();
|
|
101
|
+
if ( ! op.prepended.includes( name ) ) op.prepended.push( name );
|
|
102
|
+
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class GLTFToUSD {
|
|
108
|
+
|
|
109
|
+
constructor( doc, { log = () => {}, textureDir = 'textures', debug = false, imageDecoder = null, bakeNormalScale = true } = {} ) {
|
|
110
|
+
|
|
111
|
+
this.doc = doc;
|
|
112
|
+
this.json = doc.json;
|
|
113
|
+
this.log = log;
|
|
114
|
+
this.textureDir = textureDir;
|
|
115
|
+
this.imageDecoder = imageDecoder;
|
|
116
|
+
this.bakeNormalScale = bakeNormalScale;
|
|
117
|
+
this.debug = debug; // returns the node/primitive -> prim path mapping, for verification
|
|
118
|
+
this.b = new Builder();
|
|
119
|
+
this.files = []; // { name, data } for the package
|
|
120
|
+
this.imageFiles = new Map(); // image index -> path | null
|
|
121
|
+
this.materialPaths = new Map(); // material index (or 'default') -> path
|
|
122
|
+
this.nodePrims = new Map(); // node index -> prim spec
|
|
123
|
+
this.meshPrims = new Map(); // `${node}/${primitive}` -> prim spec
|
|
124
|
+
this.jointNodes = new Set();
|
|
125
|
+
this.timeCodes = new Set();
|
|
126
|
+
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async convert() {
|
|
130
|
+
|
|
131
|
+
const json = this.json;
|
|
132
|
+
const layer = this.b.layer;
|
|
133
|
+
const sceneIndex = json.scene ?? 0;
|
|
134
|
+
const scene = json.scenes?.[ sceneIndex ] ?? { nodes: ( json.nodes || [] ).map( ( _, i ) => i ).filter( ( i ) => ! ( json.nodes || [] ).some( ( n ) => n.children?.includes( i ) ) ) };
|
|
135
|
+
|
|
136
|
+
const needsSkel = ( json.skins || [] ).length > 0 || ( json.meshes || [] ).some( ( m ) => m.primitives.some( ( p ) => p.targets?.length ) );
|
|
137
|
+
this.root = this.b.def( layer.root, sanitize( scene.name, 'root' ), needsSkel ? 'SkelRoot' : 'Xform' );
|
|
138
|
+
this.root.metadata.kind = 'component';
|
|
139
|
+
layer.metadata.defaultPrim = this.root.name;
|
|
140
|
+
layer.metadata.upAxis = 'Y';
|
|
141
|
+
layer.metadata.metersPerUnit = 1;
|
|
142
|
+
layer.metadata.timeCodesPerSecond = TIME_CODES_PER_SECOND;
|
|
143
|
+
layer.metadata.doc = `Converted from glTF by usd-gltf${ json.asset?.generator ? ` (source generator: ${ json.asset.generator })` : '' }`;
|
|
144
|
+
|
|
145
|
+
const stash = {};
|
|
146
|
+
if ( json.asset ) stash.asset = json.asset;
|
|
147
|
+
if ( json.extras !== undefined ) stash.extras = json.extras;
|
|
148
|
+
if ( json.extensions?.KHR_xmp_json_ld ) stash.KHR_xmp_json_ld = json.extensions.KHR_xmp_json_ld;
|
|
149
|
+
if ( json.extensions?.KHR_xmp ) stash.KHR_xmp = json.extensions.KHR_xmp;
|
|
150
|
+
layer.metadata.customLayerData = { gltf: { json: JSON.stringify( stash ) } };
|
|
151
|
+
|
|
152
|
+
for ( const skin of json.skins || [] ) for ( const j of skin.joints ) this.jointNodes.add( j );
|
|
153
|
+
|
|
154
|
+
await this.convertMaterials();
|
|
155
|
+
|
|
156
|
+
this.materialScope = this.materialScope ?? null;
|
|
157
|
+
for ( const index of scene.nodes || [] ) this.convertNode( index, this.root );
|
|
158
|
+
|
|
159
|
+
this.convertSkins();
|
|
160
|
+
this.convertAnimations();
|
|
161
|
+
this.convertMaterialVariants();
|
|
162
|
+
|
|
163
|
+
if ( this.unmappedPointers ) {
|
|
164
|
+
|
|
165
|
+
const data = layer.metadata.customLayerData.gltf;
|
|
166
|
+
data.json = JSON.stringify( { ...JSON.parse( data.json ), pointers: this.unmappedPointers } );
|
|
167
|
+
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if ( this.timeCodes.size ) {
|
|
171
|
+
|
|
172
|
+
const times = [ ...this.timeCodes ];
|
|
173
|
+
layer.metadata.startTimeCode = Math.min( 0, ...times );
|
|
174
|
+
layer.metadata.endTimeCode = Math.max( ...times );
|
|
175
|
+
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const mapping = this.debug ? Object.fromEntries( [ ...this.meshPrims ].map( ( [ key, prim ] ) => [ key, this.b.path( prim ) ] ) ) : null;
|
|
179
|
+
return { layer, files: this.files, mapping };
|
|
180
|
+
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// --- materials and textures ---
|
|
184
|
+
|
|
185
|
+
async imagePath( index ) {
|
|
186
|
+
|
|
187
|
+
if ( this.imageFiles.has( index ) ) return this.imageFiles.get( index );
|
|
188
|
+
|
|
189
|
+
const image = this.doc.images[ index ];
|
|
190
|
+
let path = null;
|
|
191
|
+
|
|
192
|
+
if ( image?.bytes ) {
|
|
193
|
+
|
|
194
|
+
let bytes = image.bytes;
|
|
195
|
+
let mime = imageMimeType( bytes ) || image.mimeType;
|
|
196
|
+
|
|
197
|
+
if ( mime !== 'image/png' && mime !== 'image/jpeg' ) {
|
|
198
|
+
|
|
199
|
+
// usdz packages may only hold png and jpeg images
|
|
200
|
+
try {
|
|
201
|
+
|
|
202
|
+
bytes = encodePNG( await decodeImageAsync( bytes, mime, this.imageDecoder ) );
|
|
203
|
+
mime = 'image/png';
|
|
204
|
+
|
|
205
|
+
} catch ( e ) {
|
|
206
|
+
|
|
207
|
+
this.log( `image ${ index }: ${ e.message }` );
|
|
208
|
+
bytes = null;
|
|
209
|
+
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if ( bytes ) {
|
|
215
|
+
|
|
216
|
+
const base = sanitize( image.name || image.uri?.split( '/' ).pop()?.replace( /\.[^.]*$/, '' ), 'image' ) + '_' + index;
|
|
217
|
+
path = `${ this.textureDir }/${ base }.${ mime === 'image/png' ? 'png' : 'jpg' }`;
|
|
218
|
+
this.files.push( { name: path, data: bytes } );
|
|
219
|
+
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
this.imageFiles.set( index, path );
|
|
225
|
+
return path;
|
|
226
|
+
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// A normal map with glTF's normal scale applied: n = normalize( ( tex * 2 - 1 ) * ( s, s, 1 ) ).
|
|
230
|
+
async bakedNormal( source, s ) {
|
|
231
|
+
|
|
232
|
+
const key = source + '/' + s;
|
|
233
|
+
this.bakedNormals ??= new Map();
|
|
234
|
+
if ( this.bakedNormals.has( key ) ) return this.bakedNormals.get( key );
|
|
235
|
+
|
|
236
|
+
let path = null;
|
|
237
|
+
const image = this.doc.images[ source ];
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
|
|
241
|
+
const img = await decodeImageAsync( image.bytes, image.mimeType, this.imageDecoder );
|
|
242
|
+
const max = img.bitDepth === 16 ? 65535 : 255;
|
|
243
|
+
const out = new Uint8Array( img.width * img.height * 3 );
|
|
244
|
+
|
|
245
|
+
for ( let i = 0, n = img.width * img.height; i < n; i ++ ) {
|
|
246
|
+
|
|
247
|
+
const c = img.channels;
|
|
248
|
+
const x = ( img.data[ i * c ] / max * 2 - 1 ) * s;
|
|
249
|
+
const y = ( img.data[ i * c + ( c > 2 ? 1 : 0 ) ] / max * 2 - 1 ) * s;
|
|
250
|
+
const z = c > 2 ? img.data[ i * c + 2 ] / max * 2 - 1 : 1;
|
|
251
|
+
const l = Math.hypot( x, y, z ) || 1;
|
|
252
|
+
out[ i * 3 ] = Math.round( ( x / l + 1 ) * 127.5 );
|
|
253
|
+
out[ i * 3 + 1 ] = Math.round( ( y / l + 1 ) * 127.5 );
|
|
254
|
+
out[ i * 3 + 2 ] = Math.round( ( z / l + 1 ) * 127.5 );
|
|
255
|
+
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const base = sanitize( image.name || image.uri?.split( '/' ).pop()?.replace( /\.[^.]*$/, '' ), 'normal' ) + '_' + source;
|
|
259
|
+
path = `${ this.textureDir }/${ base }_scale${ String( s ).replace( /[^0-9]/g, '_' ) }.png`;
|
|
260
|
+
this.files.push( { name: path, data: encodePNG( { width: img.width, height: img.height, channels: 3, data: out } ) } );
|
|
261
|
+
|
|
262
|
+
} catch ( e ) {
|
|
263
|
+
|
|
264
|
+
this.log( `normal map ${ source }: ${ e.message }` );
|
|
265
|
+
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
this.bakedNormals.set( key, path );
|
|
269
|
+
return path;
|
|
270
|
+
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
textureSource( textureIndex ) {
|
|
274
|
+
|
|
275
|
+
const texture = this.json.textures?.[ textureIndex ];
|
|
276
|
+
if ( ! texture ) return undefined;
|
|
277
|
+
const ext = texture.extensions || {};
|
|
278
|
+
return ext.KHR_texture_basisu?.source ?? ext.EXT_texture_webp?.source ?? ext.EXT_texture_avif?.source ?? texture.source;
|
|
279
|
+
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async convertMaterials() {
|
|
283
|
+
|
|
284
|
+
const materials = this.json.materials || [];
|
|
285
|
+
if ( ! materials.length && ! this.needsDefaultMaterial() ) return;
|
|
286
|
+
|
|
287
|
+
this.materialScope = this.b.def( this.root, 'Materials', 'Scope' );
|
|
288
|
+
|
|
289
|
+
for ( let i = 0; i < materials.length; i ++ ) {
|
|
290
|
+
|
|
291
|
+
this.materialPaths.set( i, await this.convertMaterial( materials[ i ], i ) );
|
|
292
|
+
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
needsDefaultMaterial() {
|
|
298
|
+
|
|
299
|
+
return ( this.json.meshes || [] ).some( ( m ) => m.primitives.some( ( p ) => p.material === undefined ) );
|
|
300
|
+
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
defaultMaterialPath() {
|
|
304
|
+
|
|
305
|
+
if ( ! this.materialPaths.has( 'default' ) ) {
|
|
306
|
+
|
|
307
|
+
this.materialScope ??= this.b.def( this.root, 'Materials', 'Scope' );
|
|
308
|
+
const m = this.b.def( this.materialScope, 'default', 'Material' );
|
|
309
|
+
const shader = this.b.def( m, 'PreviewSurface', 'Shader' );
|
|
310
|
+
this.b.attr( shader, 'info:id', 'token', 'UsdPreviewSurface', { uniform: true } );
|
|
311
|
+
this.b.attr( shader, 'inputs:diffuseColor', 'color3f', [ 1, 1, 1 ] );
|
|
312
|
+
this.b.attr( shader, 'inputs:metallic', 'float', 1 );
|
|
313
|
+
this.b.attr( shader, 'inputs:roughness', 'float', 1 );
|
|
314
|
+
this.b.attr( shader, 'outputs:surface', 'token' );
|
|
315
|
+
this.b.connect( m, 'outputs:surface', 'token', this.b.path( shader ) + '.outputs:surface' );
|
|
316
|
+
this.materialPaths.set( 'default', this.b.path( m ) );
|
|
317
|
+
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return this.materialPaths.get( 'default' );
|
|
321
|
+
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async convertMaterial( material, index ) {
|
|
325
|
+
|
|
326
|
+
const b = this.b;
|
|
327
|
+
const m = b.def( this.materialScope, sanitize( material.name, 'material' ), 'Material' );
|
|
328
|
+
const mPath = b.path( m );
|
|
329
|
+
const shader = b.def( m, 'PreviewSurface', 'Shader' );
|
|
330
|
+
const sPath = b.path( shader );
|
|
331
|
+
b.attr( shader, 'info:id', 'token', 'UsdPreviewSurface', { uniform: true } );
|
|
332
|
+
b.attr( shader, 'outputs:surface', 'token' );
|
|
333
|
+
b.connect( m, 'outputs:surface', 'token', sPath + '.outputs:surface' );
|
|
334
|
+
|
|
335
|
+
const ext = material.extensions || {};
|
|
336
|
+
const pbr = material.pbrMetallicRoughness || {};
|
|
337
|
+
const readers = new Map(); // uv set -> reader path
|
|
338
|
+
const textures = new Map();
|
|
339
|
+
this.shaderInputs = this.shaderInputs || new Map();
|
|
340
|
+
const inputs = {};
|
|
341
|
+
this.shaderInputs.set( index, inputs );
|
|
342
|
+
|
|
343
|
+
const uvReader = ( texCoord ) => {
|
|
344
|
+
|
|
345
|
+
if ( ! readers.has( texCoord ) ) {
|
|
346
|
+
|
|
347
|
+
const r = b.def( m, texCoord ? `uvReader_st${ texCoord }` : 'uvReader_st', 'Shader' );
|
|
348
|
+
b.attr( r, 'info:id', 'token', 'UsdPrimvarReader_float2', { uniform: true } );
|
|
349
|
+
b.attr( r, 'inputs:varname', 'string', texCoord ? `st${ texCoord }` : 'st' );
|
|
350
|
+
b.attr( r, 'outputs:result', 'float2' );
|
|
351
|
+
readers.set( texCoord, b.path( r ) + '.outputs:result' );
|
|
352
|
+
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return readers.get( texCoord );
|
|
356
|
+
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
// A UsdUVTexture for a glTF textureInfo with per channel scale and bias.
|
|
360
|
+
const texture = async ( info, name, { scale = [ 1, 1, 1, 1 ], bias = [ 0, 0, 0, 0 ], colorSpace = 'raw', file = null } = {} ) => {
|
|
361
|
+
|
|
362
|
+
const source = this.textureSource( info.index );
|
|
363
|
+
file ??= source !== undefined ? await this.imagePath( source ) : null;
|
|
364
|
+
if ( ! file ) return null;
|
|
365
|
+
|
|
366
|
+
const transform = info.extensions?.KHR_texture_transform;
|
|
367
|
+
const texCoord = transform?.texCoord ?? info.texCoord ?? 0;
|
|
368
|
+
const key = JSON.stringify( [ file, texCoord, transform, scale, bias, colorSpace, this.json.textures[ info.index ].sampler ] );
|
|
369
|
+
if ( textures.has( key ) ) return textures.get( key );
|
|
370
|
+
|
|
371
|
+
const t = b.def( m, name, 'Shader' );
|
|
372
|
+
const tPath = b.path( t );
|
|
373
|
+
b.attr( t, 'info:id', 'token', 'UsdUVTexture', { uniform: true } );
|
|
374
|
+
b.attr( t, 'inputs:file', 'asset', new AssetPath( './' + file ) );
|
|
375
|
+
b.attr( t, 'inputs:sourceColorSpace', 'token', colorSpace );
|
|
376
|
+
|
|
377
|
+
let st = uvReader( texCoord );
|
|
378
|
+
|
|
379
|
+
if ( transform ) {
|
|
380
|
+
|
|
381
|
+
const tr = b.def( m, name + '_transform', 'Shader' );
|
|
382
|
+
const u = usdTextureTransform( transform );
|
|
383
|
+
b.attr( tr, 'info:id', 'token', 'UsdTransform2d', { uniform: true } );
|
|
384
|
+
b.connect( tr, 'inputs:in', 'float2', st );
|
|
385
|
+
b.attr( tr, 'inputs:rotation', 'float', u.rotation );
|
|
386
|
+
b.attr( tr, 'inputs:scale', 'float2', u.scale );
|
|
387
|
+
b.attr( tr, 'inputs:translation', 'float2', u.translation );
|
|
388
|
+
b.attr( tr, 'outputs:result', 'float2' );
|
|
389
|
+
st = b.path( tr ) + '.outputs:result';
|
|
390
|
+
inputs[ `texture:${ info.index }:transform` ] = b.path( tr );
|
|
391
|
+
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
b.connect( t, 'inputs:st', 'float2', st );
|
|
395
|
+
|
|
396
|
+
const sampler = this.json.samplers?.[ this.json.textures[ info.index ].sampler ] || {};
|
|
397
|
+
b.attr( t, 'inputs:wrapS', 'token', WRAP[ sampler.wrapS ?? 10497 ] );
|
|
398
|
+
b.attr( t, 'inputs:wrapT', 'token', WRAP[ sampler.wrapT ?? 10497 ] );
|
|
399
|
+
if ( scale.some( ( v ) => v !== 1 ) ) b.attr( t, 'inputs:scale', 'float4', scale );
|
|
400
|
+
if ( bias.some( ( v ) => v !== 0 ) ) b.attr( t, 'inputs:bias', 'float4', bias );
|
|
401
|
+
for ( const out of [ 'rgb', 'r', 'g', 'b', 'a' ] ) b.attr( t, 'outputs:' + out, out === 'rgb' ? 'float3' : 'float' );
|
|
402
|
+
|
|
403
|
+
textures.set( key, tPath );
|
|
404
|
+
return tPath;
|
|
405
|
+
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const set = ( name, type, value ) => {
|
|
409
|
+
|
|
410
|
+
b.attr( shader, 'inputs:' + name, type, value );
|
|
411
|
+
inputs[ name ] = sPath + '.inputs:' + name;
|
|
412
|
+
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const link = ( name, type, texPath, output ) => b.connect( shader, 'inputs:' + name, type, `${ texPath }.outputs:${ output }` );
|
|
416
|
+
|
|
417
|
+
// base color and opacity
|
|
418
|
+
const specGloss = ext.KHR_materials_pbrSpecularGlossiness;
|
|
419
|
+
const baseFactor = specGloss ? specGloss.diffuseFactor ?? [ 1, 1, 1, 1 ] : pbr.baseColorFactor ?? [ 1, 1, 1, 1 ];
|
|
420
|
+
const baseInfo = specGloss ? specGloss.diffuseTexture : pbr.baseColorTexture;
|
|
421
|
+
const alphaMode = material.alphaMode || 'OPAQUE';
|
|
422
|
+
const unlit = !! ext.KHR_materials_unlit;
|
|
423
|
+
const baseTex = baseInfo && await texture( baseInfo, 'baseColorTexture', { scale: baseFactor, colorSpace: 'sRGB' } );
|
|
424
|
+
|
|
425
|
+
const colorInput = unlit ? 'emissiveColor' : 'diffuseColor';
|
|
426
|
+
if ( baseTex ) link( colorInput, 'color3f', baseTex, 'rgb' );
|
|
427
|
+
else set( colorInput, 'color3f', baseFactor.slice( 0, 3 ) );
|
|
428
|
+
if ( unlit ) set( 'diffuseColor', 'color3f', [ 0, 0, 0 ] );
|
|
429
|
+
inputs.baseColorTexture = baseTex;
|
|
430
|
+
|
|
431
|
+
if ( alphaMode !== 'OPAQUE' ) {
|
|
432
|
+
|
|
433
|
+
if ( baseTex ) link( 'opacity', 'float', baseTex, 'a' );
|
|
434
|
+
else set( 'opacity', 'float', baseFactor[ 3 ] );
|
|
435
|
+
if ( alphaMode === 'MASK' ) set( 'opacityThreshold', 'float', material.alphaCutoff ?? 0.5 );
|
|
436
|
+
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if ( specGloss ) {
|
|
440
|
+
|
|
441
|
+
// specular workflow: UsdPreviewSurface supports it directly
|
|
442
|
+
set( 'useSpecularWorkflow', 'int', 1 );
|
|
443
|
+
const sf = specGloss.specularFactor ?? [ 1, 1, 1 ];
|
|
444
|
+
const g = specGloss.glossinessFactor ?? 1;
|
|
445
|
+
const sgTex = specGloss.specularGlossinessTexture && await texture( specGloss.specularGlossinessTexture, 'specularGlossinessTexture', { scale: [ ...sf, - g ], bias: [ 0, 0, 0, 1 ], colorSpace: 'sRGB' } );
|
|
446
|
+
if ( sgTex ) { link( 'specularColor', 'color3f', sgTex, 'rgb' ); link( 'roughness', 'float', sgTex, 'a' ); }
|
|
447
|
+
else { set( 'specularColor', 'color3f', sf ); set( 'roughness', 'float', 1 - g ); }
|
|
448
|
+
|
|
449
|
+
} else {
|
|
450
|
+
|
|
451
|
+
const metallic = pbr.metallicFactor ?? 1;
|
|
452
|
+
const roughness = pbr.roughnessFactor ?? 1;
|
|
453
|
+
const mrTex = pbr.metallicRoughnessTexture && await texture( pbr.metallicRoughnessTexture, 'metallicRoughnessTexture', { scale: [ 1, roughness, metallic, 1 ] } );
|
|
454
|
+
if ( mrTex ) { link( 'roughness', 'float', mrTex, 'g' ); link( 'metallic', 'float', mrTex, 'b' ); }
|
|
455
|
+
else { set( 'roughness', 'float', roughness ); set( 'metallic', 'float', metallic ); }
|
|
456
|
+
inputs.metallicRoughnessTexture = mrTex;
|
|
457
|
+
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
if ( ! unlit ) {
|
|
461
|
+
|
|
462
|
+
// emissive
|
|
463
|
+
const strength = ext.KHR_materials_emissive_strength?.emissiveStrength ?? 1;
|
|
464
|
+
const ef = ( material.emissiveFactor ?? [ 0, 0, 0 ] ).map( ( v ) => v * strength );
|
|
465
|
+
const emTex = material.emissiveTexture && ef.some( ( v ) => v > 0 ) && await texture( material.emissiveTexture, 'emissiveTexture', { scale: [ ...ef, 1 ], colorSpace: 'sRGB' } );
|
|
466
|
+
if ( emTex ) link( 'emissiveColor', 'color3f', emTex, 'rgb' );
|
|
467
|
+
else if ( ef.some( ( v ) => v > 0 ) ) set( 'emissiveColor', 'color3f', ef );
|
|
468
|
+
inputs.emissiveTexture = emTex;
|
|
469
|
+
|
|
470
|
+
// normal: n = ( tex * 2 - 1 ) * ( s, s, 1 )
|
|
471
|
+
if ( material.normalTexture ) {
|
|
472
|
+
|
|
473
|
+
const s = material.normalTexture.scale ?? 1;
|
|
474
|
+
// UsdPreviewSurface requires 8 bit normal maps to use scale 2 and bias -1, so a glTF
|
|
475
|
+
// normal scale is baked into a new texture; the original is kept for the way back
|
|
476
|
+
const baked = s !== 1 && this.bakeNormalScale ? await this.bakedNormal( this.textureSource( material.normalTexture.index ), s ) : null;
|
|
477
|
+
const nTex = baked
|
|
478
|
+
? await texture( material.normalTexture, 'normalTexture', { scale: [ 2, 2, 2, 1 ], bias: [ - 1, - 1, - 1, 0 ], file: baked } )
|
|
479
|
+
: await texture( material.normalTexture, 'normalTexture', { scale: [ 2 * s, 2 * s, 2, 1 ], bias: [ - s, - s, - 1, 0 ] } );
|
|
480
|
+
if ( nTex ) link( 'normal', 'normal3f', nTex, 'rgb' );
|
|
481
|
+
if ( baked ) inputs.originalNormal = ( await this.stashTextures( { normalTexture: material.normalTexture } ) ).normalTexture;
|
|
482
|
+
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// occlusion: lerp( 1, tex, strength )
|
|
486
|
+
if ( material.occlusionTexture ) {
|
|
487
|
+
|
|
488
|
+
const s = material.occlusionTexture.strength ?? 1;
|
|
489
|
+
const oTex = await texture( material.occlusionTexture, 'occlusionTexture', { scale: [ s, s, s, 1 ], bias: [ 1 - s, 1 - s, 1 - s, 0 ] } );
|
|
490
|
+
if ( oTex ) link( 'occlusion', 'float', oTex, 'r' );
|
|
491
|
+
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const cc = ext.KHR_materials_clearcoat;
|
|
495
|
+
|
|
496
|
+
if ( cc && ( cc.clearcoatFactor ?? 0 ) > 0 ) {
|
|
497
|
+
|
|
498
|
+
const f = cc.clearcoatFactor ?? 0;
|
|
499
|
+
const ccTex = cc.clearcoatTexture && await texture( cc.clearcoatTexture, 'clearcoatTexture', { scale: [ f, f, f, 1 ] } );
|
|
500
|
+
if ( ccTex ) link( 'clearcoat', 'float', ccTex, 'r' );
|
|
501
|
+
else set( 'clearcoat', 'float', f );
|
|
502
|
+
|
|
503
|
+
const r = cc.clearcoatRoughnessFactor ?? 0;
|
|
504
|
+
const ccrTex = cc.clearcoatRoughnessTexture && await texture( cc.clearcoatRoughnessTexture, 'clearcoatRoughnessTexture', { scale: [ r, r, r, 1 ] } );
|
|
505
|
+
if ( ccrTex ) link( 'clearcoatRoughness', 'float', ccrTex, 'g' );
|
|
506
|
+
else set( 'clearcoatRoughness', 'float', r );
|
|
507
|
+
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
if ( ext.KHR_materials_ior && ext.KHR_materials_ior.ior !== undefined ) set( 'ior', 'float', ext.KHR_materials_ior.ior );
|
|
511
|
+
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// keep whatever UsdPreviewSurface can't express, with textures as package paths
|
|
515
|
+
const stash = {};
|
|
516
|
+
for ( const [ key, value ] of Object.entries( ext ) ) if ( ! MAPPED_MATERIAL_EXTENSIONS.has( key ) ) stash[ key ] = await this.stashTextures( value );
|
|
517
|
+
if ( ext.KHR_materials_ior ) stash.KHR_materials_ior = ext.KHR_materials_ior;
|
|
518
|
+
if ( material.extras !== undefined ) stash.extras = material.extras;
|
|
519
|
+
if ( inputs.originalNormal ) stash.normalTexture = inputs.originalNormal;
|
|
520
|
+
if ( material.doubleSided ) stash.doubleSided = true;
|
|
521
|
+
// blending can't be inferred from an opaque opacity
|
|
522
|
+
if ( alphaMode !== 'OPAQUE' ) { stash.alphaMode = alphaMode; if ( alphaMode === 'MASK' ) stash.alphaCutoff = material.alphaCutoff ?? 0.5; }
|
|
523
|
+
if ( Object.keys( stash ).length ) {
|
|
524
|
+
|
|
525
|
+
stash.name = material.name;
|
|
526
|
+
m.metadata.customData = { gltf: { json: JSON.stringify( stash ) } };
|
|
527
|
+
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
return mPath;
|
|
531
|
+
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
async stashTextures( value ) {
|
|
535
|
+
|
|
536
|
+
if ( Array.isArray( value ) ) return Promise.all( value.map( ( v ) => this.stashTextures( v ) ) );
|
|
537
|
+
if ( ! value || typeof value !== 'object' ) return value;
|
|
538
|
+
|
|
539
|
+
const out = {};
|
|
540
|
+
|
|
541
|
+
for ( const [ k, v ] of Object.entries( value ) ) {
|
|
542
|
+
|
|
543
|
+
if ( /Texture$/.test( k ) && v && typeof v.index === 'number' ) {
|
|
544
|
+
|
|
545
|
+
const source = this.textureSource( v.index );
|
|
546
|
+
const path = source !== undefined ? await this.imagePath( source ) : null;
|
|
547
|
+
const sampler = this.json.samplers?.[ this.json.textures[ v.index ].sampler ];
|
|
548
|
+
out[ k ] = { ...v, index: undefined, uri: path, sampler };
|
|
549
|
+
|
|
550
|
+
} else {
|
|
551
|
+
|
|
552
|
+
out[ k ] = await this.stashTextures( v );
|
|
553
|
+
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
return out;
|
|
559
|
+
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// --- nodes ---
|
|
563
|
+
|
|
564
|
+
// Joints are written as Skeleton joints; their Xform is only needed when content hangs below them.
|
|
565
|
+
hasContent( index ) {
|
|
566
|
+
|
|
567
|
+
const node = this.json.nodes[ index ];
|
|
568
|
+
if ( node.mesh !== undefined || node.camera !== undefined || node.extensions?.KHR_lights_punctual ) return true;
|
|
569
|
+
return ( node.children || [] ).some( ( c ) => this.hasContent( c ) );
|
|
570
|
+
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
convertNode( index, parent ) {
|
|
574
|
+
|
|
575
|
+
const node = this.json.nodes[ index ];
|
|
576
|
+
const b = this.b;
|
|
577
|
+
if ( this.jointNodes.has( index ) && ! this.hasContent( index ) ) return null;
|
|
578
|
+
const prim = b.def( parent, sanitize( node.name, `node_${ index }` ), 'Xform' );
|
|
579
|
+
this.nodePrims.set( index, prim );
|
|
580
|
+
this.writeTransform( prim, node );
|
|
581
|
+
|
|
582
|
+
if ( node.extensions?.KHR_node_visibility?.visible === false ) b.attr( prim, 'visibility', 'token', 'invisible' );
|
|
583
|
+
if ( node.extras !== undefined ) prim.metadata.customData = { gltf: { extras: JSON.stringify( node.extras ) } };
|
|
584
|
+
|
|
585
|
+
if ( node.mesh !== undefined ) this.convertMeshInstance( index, prim );
|
|
586
|
+
if ( node.camera !== undefined ) this.convertCamera( node.camera, prim );
|
|
587
|
+
|
|
588
|
+
const light = node.extensions?.KHR_lights_punctual?.light;
|
|
589
|
+
if ( light !== undefined ) this.convertLight( light, prim );
|
|
590
|
+
|
|
591
|
+
for ( const child of node.children || [] ) this.convertNode( child, prim );
|
|
592
|
+
|
|
593
|
+
return prim;
|
|
594
|
+
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
writeTransform( prim, node ) {
|
|
598
|
+
|
|
599
|
+
const b = this.b;
|
|
600
|
+
let t = node.translation, r = node.rotation, s = node.scale;
|
|
601
|
+
|
|
602
|
+
if ( node.matrix ) {
|
|
603
|
+
|
|
604
|
+
const d = decompose( node.matrix );
|
|
605
|
+
const back = compose( d.t, d.r, d.s );
|
|
606
|
+
const exact = back.every( ( v, i ) => Math.abs( v - node.matrix[ i ] ) <= 1e-6 * ( 1 + Math.abs( node.matrix[ i ] ) ) );
|
|
607
|
+
|
|
608
|
+
if ( ! exact ) {
|
|
609
|
+
|
|
610
|
+
b.attr( prim, 'xformOp:transform', 'matrix4d', Array.from( node.matrix ) );
|
|
611
|
+
b.attr( prim, 'xformOpOrder', 'token[]', [ 'xformOp:transform' ], { uniform: true } );
|
|
612
|
+
return;
|
|
613
|
+
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
t = d.t; r = d.r; s = d.s;
|
|
617
|
+
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const order = [];
|
|
621
|
+
if ( t && t.some( ( v ) => v !== 0 ) ) { b.attr( prim, 'xformOp:translate', 'double3', Array.from( t ) ); order.push( 'xformOp:translate' ); }
|
|
622
|
+
if ( r && ( r[ 0 ] || r[ 1 ] || r[ 2 ] || r[ 3 ] !== 1 ) ) { b.attr( prim, 'xformOp:orient', 'quatf', Array.from( r ) ); order.push( 'xformOp:orient' ); }
|
|
623
|
+
if ( s && s.some( ( v ) => v !== 1 ) ) { b.attr( prim, 'xformOp:scale', 'float3', Array.from( s ) ); order.push( 'xformOp:scale' ); }
|
|
624
|
+
if ( order.length ) b.attr( prim, 'xformOpOrder', 'token[]', order, { uniform: true } );
|
|
625
|
+
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// Ensures a node prim has a given op (for animation), keeping translate, orient, scale order.
|
|
629
|
+
ensureOp( prim, path ) {
|
|
630
|
+
|
|
631
|
+
const op = { translation: 'xformOp:translate', rotation: 'xformOp:orient', scale: 'xformOp:scale' }[ path ];
|
|
632
|
+
const order = prim.properties.get( 'xformOpOrder' );
|
|
633
|
+
|
|
634
|
+
if ( order && order.default.includes( 'xformOp:transform' ) ) {
|
|
635
|
+
|
|
636
|
+
// a sheared matrix node that is also animated: fall back to TRS
|
|
637
|
+
const m = prim.properties.get( 'xformOp:transform' ).default;
|
|
638
|
+
prim.properties.delete( 'xformOp:transform' );
|
|
639
|
+
prim.properties.delete( 'xformOpOrder' );
|
|
640
|
+
const d = decompose( m );
|
|
641
|
+
this.writeTransform( prim, { translation: d.t, rotation: d.r, scale: d.s } );
|
|
642
|
+
return this.ensureOp( prim, path );
|
|
643
|
+
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
if ( ! prim.properties.has( op ) ) {
|
|
647
|
+
|
|
648
|
+
const fallback = { translation: [ 0, 0, 0 ], rotation: [ 0, 0, 0, 1 ], scale: [ 1, 1, 1 ] }[ path ];
|
|
649
|
+
this.b.attr( prim, op, { translation: 'double3', rotation: 'quatf', scale: 'float3' }[ path ], fallback );
|
|
650
|
+
const ops = [ 'xformOp:translate', 'xformOp:orient', 'xformOp:scale' ].filter( ( o ) => prim.properties.has( o ) );
|
|
651
|
+
prim.properties.delete( 'xformOpOrder' );
|
|
652
|
+
this.b.attr( prim, 'xformOpOrder', 'token[]', ops, { uniform: true } );
|
|
653
|
+
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
return prim.properties.get( op );
|
|
657
|
+
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// --- meshes ---
|
|
661
|
+
|
|
662
|
+
convertMeshInstance( nodeIndex, prim ) {
|
|
663
|
+
|
|
664
|
+
const node = this.json.nodes[ nodeIndex ];
|
|
665
|
+
const mesh = this.json.meshes[ node.mesh ];
|
|
666
|
+
const skinned = node.skin !== undefined;
|
|
667
|
+
const instancing = node.extensions?.EXT_mesh_gpu_instancing;
|
|
668
|
+
|
|
669
|
+
mesh.primitives.forEach( ( primitive, p ) => {
|
|
670
|
+
|
|
671
|
+
const name = sanitize( mesh.primitives.length > 1 ? `${ mesh.name || 'mesh' }_${ p }` : mesh.name, `mesh_${ node.mesh }` );
|
|
672
|
+
|
|
673
|
+
if ( instancing && ! skinned ) {
|
|
674
|
+
|
|
675
|
+
this.convertInstancer( prim, name, primitive, instancing, nodeIndex, p );
|
|
676
|
+
return;
|
|
677
|
+
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const meshPrim = this.convertPrimitive( prim, name, primitive, { nodeIndex, joints: skinned } );
|
|
681
|
+
if ( ! meshPrim ) return;
|
|
682
|
+
this.meshPrims.set( `${ nodeIndex }/${ p }`, meshPrim );
|
|
683
|
+
|
|
684
|
+
// skins are bound once skeletons exist; morph only meshes get a rigid one joint skeleton
|
|
685
|
+
if ( skinned ) ( this.pendingSkinned ||= [] ).push( { nodeIndex, primitive, p, meshPrim } );
|
|
686
|
+
else if ( primitive.targets?.length ) this.addMorphSkeleton( prim, meshPrim, nodeIndex, primitive );
|
|
687
|
+
|
|
688
|
+
} );
|
|
689
|
+
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* Writes one glTF primitive as a Mesh, Points or BasisCurves prim.
|
|
694
|
+
*/
|
|
695
|
+
convertPrimitive( parent, name, primitive, { nodeIndex, joints = null } = {} ) {
|
|
696
|
+
|
|
697
|
+
const doc = this.doc;
|
|
698
|
+
const b = this.b;
|
|
699
|
+
const attrs = primitive.attributes;
|
|
700
|
+
if ( attrs.POSITION === undefined ) return null;
|
|
701
|
+
|
|
702
|
+
const mode = primitive.mode ?? MODES.TRIANGLES;
|
|
703
|
+
const positions = doc.getFloats( attrs.POSITION ).array;
|
|
704
|
+
const count = positions.length / 3;
|
|
705
|
+
let indices = primitive.indices !== undefined ? doc.getAccessor( primitive.indices ).array : null;
|
|
706
|
+
if ( ! indices ) indices = Uint32Array.from( { length: count }, ( _, i ) => i );
|
|
707
|
+
|
|
708
|
+
if ( mode === MODES.POINTS ) {
|
|
709
|
+
|
|
710
|
+
const prim = b.def( parent, name, 'Points' );
|
|
711
|
+
const used = primitive.indices !== undefined ? Float32Array.from( Array.from( indices ).flatMap( ( i ) => [ positions[ i * 3 ], positions[ i * 3 + 1 ], positions[ i * 3 + 2 ] ] ) ) : positions;
|
|
712
|
+
b.attr( prim, 'points', 'point3f[]', used );
|
|
713
|
+
b.attr( prim, 'widths', 'float[]', Float32Array.of( 0.01 ), { interpolation: 'constant' } );
|
|
714
|
+
b.attr( prim, 'extent', 'float3[]', extent( used ) );
|
|
715
|
+
this.writeColors( prim, attrs, primitive.indices !== undefined ? indices : null, 'vertex' );
|
|
716
|
+
this.bindMaterial( prim, primitive.material );
|
|
717
|
+
return prim;
|
|
718
|
+
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if ( mode === MODES.LINES || mode === MODES.LINE_STRIP || mode === MODES.LINE_LOOP ) {
|
|
722
|
+
|
|
723
|
+
const prim = b.def( parent, name, 'BasisCurves' );
|
|
724
|
+
b.attr( prim, 'type', 'token', 'linear', { uniform: true } );
|
|
725
|
+
let verts;
|
|
726
|
+
let counts;
|
|
727
|
+
|
|
728
|
+
if ( mode === MODES.LINES ) {
|
|
729
|
+
|
|
730
|
+
verts = Array.from( indices );
|
|
731
|
+
counts = new Int32Array( indices.length / 2 ).fill( 2 );
|
|
732
|
+
|
|
733
|
+
} else {
|
|
734
|
+
|
|
735
|
+
verts = Array.from( indices );
|
|
736
|
+
if ( mode === MODES.LINE_LOOP ) verts.push( indices[ 0 ] );
|
|
737
|
+
counts = Int32Array.of( verts.length );
|
|
738
|
+
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const pts = Float32Array.from( verts.flatMap( ( i ) => [ positions[ i * 3 ], positions[ i * 3 + 1 ], positions[ i * 3 + 2 ] ] ) );
|
|
742
|
+
b.attr( prim, 'points', 'point3f[]', pts );
|
|
743
|
+
b.attr( prim, 'curveVertexCounts', 'int[]', counts );
|
|
744
|
+
b.attr( prim, 'widths', 'float[]', Float32Array.of( 0.01 ), { interpolation: 'constant' } );
|
|
745
|
+
b.attr( prim, 'extent', 'float3[]', extent( pts ) );
|
|
746
|
+
this.writeColors( prim, attrs, Uint32Array.from( verts ), 'vertex' );
|
|
747
|
+
this.bindMaterial( prim, primitive.material );
|
|
748
|
+
return prim;
|
|
749
|
+
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// triangles; strips and fans are expanded
|
|
753
|
+
let tris = indices;
|
|
754
|
+
|
|
755
|
+
if ( mode === MODES.TRIANGLE_STRIP ) {
|
|
756
|
+
|
|
757
|
+
const out = [];
|
|
758
|
+
for ( let i = 0; i + 2 < indices.length; i ++ ) {
|
|
759
|
+
|
|
760
|
+
if ( i % 2 === 0 ) out.push( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
|
|
761
|
+
else out.push( indices[ i + 1 ], indices[ i ], indices[ i + 2 ] );
|
|
762
|
+
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
tris = Uint32Array.from( out );
|
|
766
|
+
|
|
767
|
+
} else if ( mode === MODES.TRIANGLE_FAN ) {
|
|
768
|
+
|
|
769
|
+
const out = [];
|
|
770
|
+
for ( let i = 1; i + 1 < indices.length; i ++ ) out.push( indices[ 0 ], indices[ i ], indices[ i + 1 ] );
|
|
771
|
+
tris = Uint32Array.from( out );
|
|
772
|
+
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
tris = tris.subarray( 0, tris.length - ( tris.length % 3 ) );
|
|
776
|
+
const prim = b.def( parent, name, 'Mesh' );
|
|
777
|
+
b.attr( prim, 'points', 'point3f[]', positions );
|
|
778
|
+
b.attr( prim, 'faceVertexCounts', 'int[]', new Int32Array( tris.length / 3 ).fill( 3 ) );
|
|
779
|
+
b.attr( prim, 'faceVertexIndices', 'int[]', Int32Array.from( tris ) );
|
|
780
|
+
b.attr( prim, 'extent', 'float3[]', extent( positions ) );
|
|
781
|
+
b.attr( prim, 'subdivisionScheme', 'token', 'none', { uniform: true } );
|
|
782
|
+
|
|
783
|
+
if ( attrs.NORMAL !== undefined ) b.attr( prim, 'normals', 'normal3f[]', doc.getFloats( attrs.NORMAL ).array, { interpolation: 'vertex' } );
|
|
784
|
+
|
|
785
|
+
for ( let i = 0; attrs[ 'TEXCOORD_' + i ] !== undefined; i ++ ) {
|
|
786
|
+
|
|
787
|
+
const uv = doc.getFloats( attrs[ 'TEXCOORD_' + i ] ).array;
|
|
788
|
+
const st = new Float32Array( uv.length );
|
|
789
|
+
for ( let k = 0; k < uv.length; k += 2 ) { st[ k ] = uv[ k ]; st[ k + 1 ] = 1 - uv[ k + 1 ]; }
|
|
790
|
+
b.attr( prim, i ? `primvars:st${ i }` : 'primvars:st', 'texCoord2f[]', st, { interpolation: 'vertex' } );
|
|
791
|
+
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if ( attrs.TANGENT !== undefined ) b.attr( prim, 'primvars:tangents', 'float4[]', doc.getFloats( attrs.TANGENT ).array, { interpolation: 'vertex' } );
|
|
795
|
+
|
|
796
|
+
this.writeColors( prim, attrs, null, 'vertex' );
|
|
797
|
+
if ( attrs.COLOR_0 !== undefined ) gltfData( prim ).color0 = true;
|
|
798
|
+
|
|
799
|
+
const material = primitive.material !== undefined ? this.json.materials[ primitive.material ] : null;
|
|
800
|
+
if ( material?.doubleSided ) b.attr( prim, 'doubleSided', 'bool', true, { uniform: true } );
|
|
801
|
+
this.bindMaterial( prim, primitive.material );
|
|
802
|
+
|
|
803
|
+
if ( joints ) this.writeSkinWeights( prim, attrs, joints );
|
|
804
|
+
|
|
805
|
+
void nodeIndex;
|
|
806
|
+
return prim;
|
|
807
|
+
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
writeColors( prim, attrs, indices, interpolation ) {
|
|
811
|
+
|
|
812
|
+
if ( attrs.COLOR_0 === undefined ) return;
|
|
813
|
+
const c = this.doc.getFloats( attrs.COLOR_0 );
|
|
814
|
+
const n = indices ? indices.length : c.count;
|
|
815
|
+
const rgb = new Float32Array( n * 3 );
|
|
816
|
+
const alpha = c.itemSize === 4 ? new Float32Array( n ) : null;
|
|
817
|
+
|
|
818
|
+
for ( let i = 0; i < n; i ++ ) {
|
|
819
|
+
|
|
820
|
+
const v = indices ? indices[ i ] : i;
|
|
821
|
+
rgb[ i * 3 ] = c.array[ v * c.itemSize ];
|
|
822
|
+
rgb[ i * 3 + 1 ] = c.array[ v * c.itemSize + 1 ];
|
|
823
|
+
rgb[ i * 3 + 2 ] = c.array[ v * c.itemSize + 2 ];
|
|
824
|
+
if ( alpha ) alpha[ i ] = c.array[ v * 4 + 3 ];
|
|
825
|
+
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// glTF vertex colors are linear and multiply base color; UsdPreviewSurface reads displayColor through a primvar reader
|
|
829
|
+
this.b.attr( prim, 'primvars:displayColor', 'color3f[]', rgb, { interpolation } );
|
|
830
|
+
if ( alpha && alpha.some( ( a ) => a !== 1 ) ) this.b.attr( prim, 'primvars:displayOpacity', 'float[]', alpha, { interpolation } );
|
|
831
|
+
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
bindMaterial( prim, materialIndex ) {
|
|
835
|
+
|
|
836
|
+
const path = materialIndex !== undefined ? this.materialPaths.get( materialIndex ) : this.defaultMaterialPath();
|
|
837
|
+
if ( ! path ) return;
|
|
838
|
+
this.b.apiSchema( prim, 'MaterialBindingAPI' );
|
|
839
|
+
this.b.rel( prim, 'material:binding', [ path ] );
|
|
840
|
+
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
convertInstancer( parent, name, primitive, instancing, nodeIndex, p ) {
|
|
844
|
+
|
|
845
|
+
const b = this.b;
|
|
846
|
+
const inst = b.def( parent, name + '_instances', 'PointInstancer' );
|
|
847
|
+
const protos = b.def( inst, 'Prototypes', 'Scope' );
|
|
848
|
+
const proto = this.convertPrimitive( protos, name, primitive, { nodeIndex } );
|
|
849
|
+
if ( ! proto ) return;
|
|
850
|
+
this.meshPrims.set( `${ nodeIndex }/${ p }`, proto );
|
|
851
|
+
|
|
852
|
+
const a = instancing.attributes || {};
|
|
853
|
+
const t = a.TRANSLATION !== undefined ? this.doc.getFloats( a.TRANSLATION ) : null;
|
|
854
|
+
const r = a.ROTATION !== undefined ? this.doc.getFloats( a.ROTATION ) : null;
|
|
855
|
+
const s = a.SCALE !== undefined ? this.doc.getFloats( a.SCALE ) : null;
|
|
856
|
+
const n = ( t || r || s ).count;
|
|
857
|
+
|
|
858
|
+
b.rel( inst, 'prototypes', [ b.path( proto ) ] );
|
|
859
|
+
b.attr( inst, 'protoIndices', 'int[]', new Int32Array( n ) );
|
|
860
|
+
b.attr( inst, 'positions', 'point3f[]', t ? t.array : new Float32Array( n * 3 ) );
|
|
861
|
+
if ( r ) b.attr( inst, 'orientations', 'quath[]', Float32Array.from( r.array ) );
|
|
862
|
+
if ( s ) b.attr( inst, 'scales', 'float3[]', s.array );
|
|
863
|
+
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// --- skins and morph targets ---
|
|
867
|
+
|
|
868
|
+
writeSkinWeights( prim, attrs, joints ) {
|
|
869
|
+
|
|
870
|
+
const sets = [];
|
|
871
|
+
for ( let s = 0; attrs[ 'JOINTS_' + s ] !== undefined; s ++ ) sets.push( [ this.doc.getAccessor( attrs[ 'JOINTS_' + s ], { normalize: false } ).array, this.doc.getFloats( attrs[ 'WEIGHTS_' + s ] ).array ] );
|
|
872
|
+
if ( ! sets.length ) return;
|
|
873
|
+
|
|
874
|
+
const n = sets[ 0 ][ 0 ].length / 4;
|
|
875
|
+
const es = sets.length * 4;
|
|
876
|
+
const idx = new Int32Array( n * es );
|
|
877
|
+
const w = new Float32Array( n * es );
|
|
878
|
+
|
|
879
|
+
for ( let v = 0; v < n; v ++ ) {
|
|
880
|
+
|
|
881
|
+
let sum = 0;
|
|
882
|
+
sets.forEach( ( [ , ws ] ) => { for ( let k = 0; k < 4; k ++ ) sum += ws[ v * 4 + k ]; } );
|
|
883
|
+
|
|
884
|
+
sets.forEach( ( [ js, ws ], s ) => {
|
|
885
|
+
|
|
886
|
+
for ( let k = 0; k < 4; k ++ ) {
|
|
887
|
+
|
|
888
|
+
idx[ v * es + s * 4 + k ] = js[ v * 4 + k ];
|
|
889
|
+
w[ v * es + s * 4 + k ] = sum > 0 ? ws[ v * 4 + k ] / sum : 0;
|
|
890
|
+
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
} );
|
|
894
|
+
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
this.b.apiSchema( prim, 'SkelBindingAPI' );
|
|
898
|
+
this.b.attr( prim, 'primvars:skel:jointIndices', 'int[]', idx, { interpolation: 'vertex', metadata: { elementSize: es } } );
|
|
899
|
+
this.b.attr( prim, 'primvars:skel:jointWeights', 'float[]', w, { interpolation: 'vertex', metadata: { elementSize: es } } );
|
|
900
|
+
this.b.attr( prim, 'primvars:skel:geomBindTransform', 'matrix4d', identity() );
|
|
901
|
+
void joints;
|
|
902
|
+
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
writeBlendShapes( meshPrim, primitive, names ) {
|
|
906
|
+
|
|
907
|
+
const b = this.b;
|
|
908
|
+
const targets = [];
|
|
909
|
+
const shapeNames = [];
|
|
910
|
+
|
|
911
|
+
primitive.targets.forEach( ( target, i ) => {
|
|
912
|
+
|
|
913
|
+
const name = sanitize( names?.[ i ], `target_${ i }` );
|
|
914
|
+
const shape = b.def( meshPrim, name, 'BlendShape' );
|
|
915
|
+
const count = this.doc.json.accessors[ primitive.attributes.POSITION ].count;
|
|
916
|
+
b.attr( shape, 'offsets', 'vector3f[]', target.POSITION !== undefined ? this.doc.getFloats( target.POSITION ).array : new Float32Array( count * 3 ), { uniform: true } );
|
|
917
|
+
if ( target.NORMAL !== undefined ) b.attr( shape, 'normalOffsets', 'vector3f[]', this.doc.getFloats( target.NORMAL ).array, { uniform: true } );
|
|
918
|
+
targets.push( b.path( shape ) );
|
|
919
|
+
shapeNames.push( shape.name );
|
|
920
|
+
|
|
921
|
+
} );
|
|
922
|
+
|
|
923
|
+
b.apiSchema( meshPrim, 'SkelBindingAPI' );
|
|
924
|
+
b.attr( meshPrim, 'skel:blendShapes', 'token[]', shapeNames, { uniform: true } );
|
|
925
|
+
b.rel( meshPrim, 'skel:blendShapeTargets', targets );
|
|
926
|
+
return shapeNames;
|
|
927
|
+
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// UsdSkel only applies blend shapes through a skeleton binding, so a non-skinned mesh with morph
|
|
931
|
+
// targets gets a one joint skeleton beside it that binds it rigidly in place.
|
|
932
|
+
addMorphSkeleton( parent, meshPrim, nodeIndex, primitive ) {
|
|
933
|
+
|
|
934
|
+
const b = this.b;
|
|
935
|
+
const mesh = this.json.meshes[ this.json.nodes[ nodeIndex ].mesh ];
|
|
936
|
+
const names = this.writeBlendShapes( meshPrim, primitive, mesh.extras?.targetNames );
|
|
937
|
+
const skel = b.def( parent, meshPrim.name + '_skeleton', 'Skeleton' );
|
|
938
|
+
skel.metadata.customData = { gltf: { morphOnly: true } };
|
|
939
|
+
b.attr( skel, 'joints', 'token[]', [ 'root' ], { uniform: true } );
|
|
940
|
+
b.attr( skel, 'bindTransforms', 'matrix4d[]', Float64Array.from( identity() ), { uniform: true } );
|
|
941
|
+
b.attr( skel, 'restTransforms', 'matrix4d[]', Float64Array.from( identity() ), { uniform: true } );
|
|
942
|
+
b.attr( meshPrim, 'primvars:skel:jointIndices', 'int[]', Int32Array.of( 0 ), { interpolation: 'constant', metadata: { elementSize: 1 } } );
|
|
943
|
+
b.attr( meshPrim, 'primvars:skel:jointWeights', 'float[]', Float32Array.of( 1 ), { interpolation: 'constant', metadata: { elementSize: 1 } } );
|
|
944
|
+
b.attr( meshPrim, 'primvars:skel:geomBindTransform', 'matrix4d', identity() );
|
|
945
|
+
const anim = b.def( skel, 'Animation', 'SkelAnimation' );
|
|
946
|
+
b.attr( anim, 'blendShapes', 'token[]', names, { uniform: true } );
|
|
947
|
+
const weights = this.json.nodes[ nodeIndex ].weights ?? mesh.weights ?? new Array( names.length ).fill( 0 );
|
|
948
|
+
b.attr( anim, 'blendShapeWeights', 'float[]', Float32Array.from( names, ( _, i ) => weights[ i ] ?? 0 ) );
|
|
949
|
+
b.apiSchema( skel, 'SkelBindingAPI' );
|
|
950
|
+
b.rel( skel, 'skel:animationSource', [ b.path( anim ) ] );
|
|
951
|
+
b.apiSchema( meshPrim, 'SkelBindingAPI' );
|
|
952
|
+
b.rel( meshPrim, 'skel:skeleton', [ b.path( skel ) ] );
|
|
953
|
+
( this.morphAnimations ||= new Map() ).set( nodeIndex, ( this.morphAnimations.get( nodeIndex ) || [] ).concat( [ anim ] ) );
|
|
954
|
+
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
convertSkins() {
|
|
958
|
+
|
|
959
|
+
const json = this.json;
|
|
960
|
+
const b = this.b;
|
|
961
|
+
this.skinInfo = [];
|
|
962
|
+
|
|
963
|
+
( json.skins || [] ).forEach( ( skin, s ) => {
|
|
964
|
+
|
|
965
|
+
const pending = ( this.pendingSkinned || [] ).filter( ( e ) => json.nodes[ e.nodeIndex ].skin === s );
|
|
966
|
+
if ( ! pending.length && ! skin.joints.length ) return;
|
|
967
|
+
|
|
968
|
+
const jointSet = new Set( skin.joints );
|
|
969
|
+
const parents = new Map();
|
|
970
|
+
json.nodes.forEach( ( n, i ) => ( n.children || [] ).forEach( ( c ) => parents.set( c, i ) ) );
|
|
971
|
+
|
|
972
|
+
// the skeleton sits under the nearest written node above all root joints, so joint
|
|
973
|
+
// transforms stay plain node transforms (root joints fold in any skipped nodes between)
|
|
974
|
+
const roots = skin.joints.filter( ( j ) => jointParent( j, parents, jointSet ) === null );
|
|
975
|
+
const ancestors = ( j ) => { const a = []; for ( let p = parents.get( j ); p !== undefined; p = parents.get( p ) ) a.push( p ); return a; };
|
|
976
|
+
let base = null;
|
|
977
|
+
for ( const candidate of ancestors( roots[ 0 ] ) ) {
|
|
978
|
+
|
|
979
|
+
if ( this.nodePrims.has( candidate ) && roots.every( ( r ) => ancestors( r ).includes( candidate ) ) ) { base = candidate; break; }
|
|
980
|
+
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
const skel = b.def( base !== null ? this.nodePrims.get( base ) : this.root, sanitize( skin.name, `skeleton_${ s }` ), 'Skeleton' );
|
|
984
|
+
|
|
985
|
+
// joint paths: names along joint ancestry, unique among siblings
|
|
986
|
+
const tokens = [];
|
|
987
|
+
const used = new Set();
|
|
988
|
+
const tokenOf = new Map();
|
|
989
|
+
const order = orderJoints( skin.joints, parents, jointSet );
|
|
990
|
+
|
|
991
|
+
for ( const j of order ) {
|
|
992
|
+
|
|
993
|
+
const parent = jointParent( j, parents, jointSet );
|
|
994
|
+
const prefix = parent !== null ? tokenOf.get( parent ) + '/' : '';
|
|
995
|
+
let name = sanitize( json.nodes[ j ].name, `joint_${ j }` );
|
|
996
|
+
let token = prefix + name;
|
|
997
|
+
for ( let k = 1; used.has( token ); k ++ ) token = prefix + name + '_' + k;
|
|
998
|
+
used.add( token );
|
|
999
|
+
tokenOf.set( j, token );
|
|
1000
|
+
tokens.push( token );
|
|
1001
|
+
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// joint index in the skin -> index in the ordered skeleton
|
|
1005
|
+
const remap = skin.joints.map( ( j ) => order.indexOf( j ) );
|
|
1006
|
+
const ibm = skin.inverseBindMatrices !== undefined ? this.doc.getFloats( skin.inverseBindMatrices ).array : null;
|
|
1007
|
+
const bind = new Float64Array( order.length * 16 );
|
|
1008
|
+
skin.joints.forEach( ( j, k ) => bind.set( ibm ? invert( Array.from( ibm.subarray( k * 16, k * 16 + 16 ) ) ) : identity(), remap[ k ] * 16 ) );
|
|
1009
|
+
|
|
1010
|
+
const info = { skin: s, order, parents, jointSet, base, blendNames: [] };
|
|
1011
|
+
const rest = new Float64Array( order.length * 16 );
|
|
1012
|
+
order.forEach( ( j, k ) => rest.set( this.jointLocal( j, info, 0, null ), k * 16 ) );
|
|
1013
|
+
|
|
1014
|
+
b.attr( skel, 'joints', 'token[]', tokens, { uniform: true } );
|
|
1015
|
+
b.attr( skel, 'bindTransforms', 'matrix4d[]', bind, { uniform: true } );
|
|
1016
|
+
b.attr( skel, 'restTransforms', 'matrix4d[]', rest, { uniform: true } );
|
|
1017
|
+
|
|
1018
|
+
const anim = b.def( skel, 'Animation', 'SkelAnimation' );
|
|
1019
|
+
b.attr( anim, 'joints', 'token[]', tokens, { uniform: true } );
|
|
1020
|
+
b.apiSchema( skel, 'SkelBindingAPI' );
|
|
1021
|
+
b.rel( skel, 'skel:animationSource', [ b.path( anim ) ] );
|
|
1022
|
+
|
|
1023
|
+
const blendNames = info.blendNames;
|
|
1024
|
+
info.anim = anim;
|
|
1025
|
+
|
|
1026
|
+
for ( const { meshPrim, nodeIndex, primitive } of pending ) {
|
|
1027
|
+
|
|
1028
|
+
// remap joint indices into skeleton order
|
|
1029
|
+
const ji = meshPrim.properties.get( 'primvars:skel:jointIndices' );
|
|
1030
|
+
if ( ji ) for ( let i = 0; i < ji.default.length; i ++ ) ji.default[ i ] = remap[ ji.default[ i ] ] ?? 0;
|
|
1031
|
+
b.rel( meshPrim, 'skel:skeleton', [ b.path( skel ) ] );
|
|
1032
|
+
|
|
1033
|
+
if ( primitive.targets?.length ) {
|
|
1034
|
+
|
|
1035
|
+
const mesh = json.meshes[ json.nodes[ nodeIndex ].mesh ];
|
|
1036
|
+
const names = this.writeBlendShapes( meshPrim, primitive, mesh.extras?.targetNames );
|
|
1037
|
+
for ( const n of names ) if ( ! blendNames.includes( n ) ) blendNames.push( n );
|
|
1038
|
+
( this.skinnedMorphs ||= [] ).push( { nodeIndex, names, anim } );
|
|
1039
|
+
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
if ( blendNames.length ) {
|
|
1045
|
+
|
|
1046
|
+
b.attr( anim, 'blendShapes', 'token[]', blendNames, { uniform: true } );
|
|
1047
|
+
const weights = new Float32Array( blendNames.length );
|
|
1048
|
+
for ( const m of this.skinnedMorphs.filter( ( x ) => x.anim === anim ) ) {
|
|
1049
|
+
|
|
1050
|
+
const node = json.nodes[ m.nodeIndex ];
|
|
1051
|
+
const w = node.weights ?? json.meshes[ node.mesh ].weights ?? [];
|
|
1052
|
+
m.names.forEach( ( n, i ) => { weights[ blendNames.indexOf( n ) ] = w[ i ] ?? 0; } );
|
|
1053
|
+
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
b.attr( anim, 'blendShapeWeights', 'float[]', weights );
|
|
1057
|
+
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
this.skinInfo.push( info );
|
|
1061
|
+
|
|
1062
|
+
} );
|
|
1063
|
+
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// Local transform of a node at a time in an animation (null = rest pose).
|
|
1067
|
+
nodeLocal( index, time, animation ) {
|
|
1068
|
+
|
|
1069
|
+
const node = this.json.nodes[ index ];
|
|
1070
|
+
let t = node.translation || [ 0, 0, 0 ], r = node.rotation || [ 0, 0, 0, 1 ], s = node.scale || [ 1, 1, 1 ];
|
|
1071
|
+
|
|
1072
|
+
if ( node.matrix ) {
|
|
1073
|
+
|
|
1074
|
+
const d = decompose( node.matrix );
|
|
1075
|
+
t = d.t; r = d.r; s = d.s;
|
|
1076
|
+
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
if ( animation ) {
|
|
1080
|
+
|
|
1081
|
+
for ( const c of animation.channels ) {
|
|
1082
|
+
|
|
1083
|
+
if ( c.node !== index ) continue;
|
|
1084
|
+
const v = sampleTrack( c, time );
|
|
1085
|
+
if ( c.path === 'translation' ) t = v;
|
|
1086
|
+
else if ( c.path === 'rotation' ) r = v;
|
|
1087
|
+
else if ( c.path === 'scale' ) s = v;
|
|
1088
|
+
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
if ( node.matrix && ! animation?.channels.some( ( c ) => c.node === index ) ) return Array.from( node.matrix );
|
|
1094
|
+
return compose( t, r, s );
|
|
1095
|
+
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// Joint transform relative to its parent joint, or to the skeleton's node for root joints.
|
|
1099
|
+
// Nodes in between that aren't written (joints without content) are folded in.
|
|
1100
|
+
jointLocal( j, info, time, animation ) {
|
|
1101
|
+
|
|
1102
|
+
const parent = jointParent( j, info.parents, info.jointSet );
|
|
1103
|
+
const stop = parent !== null ? parent : info.base;
|
|
1104
|
+
let m = this.nodeLocal( j, time, animation );
|
|
1105
|
+
for ( let p = info.parents.get( j ); p !== undefined && p !== stop; p = info.parents.get( p ) ) m = multiply( this.nodeLocal( p, time, animation ), m );
|
|
1106
|
+
return m;
|
|
1107
|
+
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// --- cameras and lights ---
|
|
1111
|
+
|
|
1112
|
+
convertCamera( index, parent ) {
|
|
1113
|
+
|
|
1114
|
+
const camera = this.json.cameras[ index ];
|
|
1115
|
+
const b = this.b;
|
|
1116
|
+
const prim = b.def( parent, sanitize( camera.name, `camera_${ index }` ), 'Camera' );
|
|
1117
|
+
|
|
1118
|
+
if ( camera.type === 'orthographic' ) {
|
|
1119
|
+
|
|
1120
|
+
const o = camera.orthographic;
|
|
1121
|
+
b.attr( prim, 'projection', 'token', 'orthographic' );
|
|
1122
|
+
b.attr( prim, 'horizontalAperture', 'float', o.xmag * 20 );
|
|
1123
|
+
b.attr( prim, 'verticalAperture', 'float', o.ymag * 20 );
|
|
1124
|
+
b.attr( prim, 'clippingRange', 'float2', [ o.znear, o.zfar ] );
|
|
1125
|
+
|
|
1126
|
+
} else {
|
|
1127
|
+
|
|
1128
|
+
const p = camera.perspective;
|
|
1129
|
+
const focal = 50;
|
|
1130
|
+
const v = 2 * focal * Math.tan( p.yfov / 2 );
|
|
1131
|
+
b.attr( prim, 'projection', 'token', 'perspective' );
|
|
1132
|
+
b.attr( prim, 'focalLength', 'float', focal );
|
|
1133
|
+
b.attr( prim, 'verticalAperture', 'float', v );
|
|
1134
|
+
b.attr( prim, 'horizontalAperture', 'float', v * ( p.aspectRatio ?? 1 ) );
|
|
1135
|
+
b.attr( prim, 'clippingRange', 'float2', [ p.znear, p.zfar ?? 1e6 ] );
|
|
1136
|
+
if ( p.aspectRatio === undefined ) prim.metadata.customData = { gltf: { json: JSON.stringify( { aspectRatio: null } ) } };
|
|
1137
|
+
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
convertLight( index, parent ) {
|
|
1143
|
+
|
|
1144
|
+
const light = this.json.extensions.KHR_lights_punctual.lights[ index ];
|
|
1145
|
+
const b = this.b;
|
|
1146
|
+
const type = light.type === 'directional' ? 'DistantLight' : 'SphereLight';
|
|
1147
|
+
const prim = b.def( parent, sanitize( light.name, `light_${ index }` ), type );
|
|
1148
|
+
b.attr( prim, 'inputs:intensity', 'float', light.intensity ?? 1 );
|
|
1149
|
+
b.attr( prim, 'inputs:color', 'color3f', light.color ?? [ 1, 1, 1 ] );
|
|
1150
|
+
|
|
1151
|
+
if ( type === 'SphereLight' ) {
|
|
1152
|
+
|
|
1153
|
+
b.attr( prim, 'inputs:radius', 'float', 0 );
|
|
1154
|
+
b.attr( prim, 'treatAsPoint', 'bool', true );
|
|
1155
|
+
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
if ( light.type === 'spot' ) {
|
|
1159
|
+
|
|
1160
|
+
const outer = light.spot?.outerConeAngle ?? Math.PI / 4;
|
|
1161
|
+
const inner = light.spot?.innerConeAngle ?? 0;
|
|
1162
|
+
b.apiSchema( prim, 'ShapingAPI' );
|
|
1163
|
+
b.attr( prim, 'inputs:shaping:cone:angle', 'float', outer * 180 / Math.PI );
|
|
1164
|
+
b.attr( prim, 'inputs:shaping:cone:softness', 'float', outer > 0 ? 1 - inner / outer : 0 );
|
|
1165
|
+
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
if ( light.range !== undefined ) prim.metadata.customData = { gltf: { json: JSON.stringify( { range: light.range } ) } };
|
|
1169
|
+
( this.lightPrims ||= new Map() ).set( index, prim );
|
|
1170
|
+
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// --- animation ---
|
|
1174
|
+
|
|
1175
|
+
tracks( animation ) {
|
|
1176
|
+
|
|
1177
|
+
const doc = this.doc;
|
|
1178
|
+
return animation.channels.map( ( channel ) => {
|
|
1179
|
+
|
|
1180
|
+
const sampler = animation.samplers[ channel.sampler ];
|
|
1181
|
+
let target = channel.target;
|
|
1182
|
+
let pointer = target.extensions?.KHR_animation_pointer?.pointer;
|
|
1183
|
+
|
|
1184
|
+
if ( pointer ) {
|
|
1185
|
+
|
|
1186
|
+
const m = /^\/nodes\/(\d+)\/(translation|rotation|scale|weights)$/.exec( pointer );
|
|
1187
|
+
if ( m ) { target = { node: + m[ 1 ], path: m[ 2 ] }; pointer = null; }
|
|
1188
|
+
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const input = doc.getAccessor( sampler.input ).array;
|
|
1192
|
+
const output = doc.getFloats( sampler.output );
|
|
1193
|
+
const interpolation = sampler.interpolation || 'LINEAR';
|
|
1194
|
+
// weights are scalar accessors holding one value per morph target per key
|
|
1195
|
+
const width = target.path === 'weights' ? output.array.length / input.length / ( interpolation === 'CUBICSPLINE' ? 3 : 1 ) : output.itemSize;
|
|
1196
|
+
return { node: target.node, path: pointer ? 'pointer' : target.path, pointer, input, output: output.array, width, interpolation };
|
|
1197
|
+
|
|
1198
|
+
} ).filter( ( c ) => c.input.length );
|
|
1199
|
+
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
convertAnimations() {
|
|
1203
|
+
|
|
1204
|
+
const animations = this.json.animations || [];
|
|
1205
|
+
if ( ! animations.length ) return;
|
|
1206
|
+
|
|
1207
|
+
const b = this.b;
|
|
1208
|
+
this.animTracks = animations.map( ( a ) => ( { channels: this.tracks( a ) } ) );
|
|
1209
|
+
const multiple = animations.length > 1;
|
|
1210
|
+
let variantSet = null;
|
|
1211
|
+
|
|
1212
|
+
if ( multiple ) {
|
|
1213
|
+
|
|
1214
|
+
variantSet = new Map();
|
|
1215
|
+
this.root.variantSets.set( 'animation', variantSet );
|
|
1216
|
+
this.root.metadata.variantSetNames = new ListOp( { prepended: [ 'animation' ] } );
|
|
1217
|
+
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
const names = [];
|
|
1221
|
+
|
|
1222
|
+
animations.forEach( ( animation, a ) => {
|
|
1223
|
+
|
|
1224
|
+
let name = sanitize( animation.name, `animation_${ a }` );
|
|
1225
|
+
while ( names.includes( name ) ) name += '_';
|
|
1226
|
+
names.push( name );
|
|
1227
|
+
|
|
1228
|
+
// with several animations, each writes its samples into overs inside its variant
|
|
1229
|
+
const target = multiple ? new PrimSpec( name, 'over', '' ) : null;
|
|
1230
|
+
if ( target ) variantSet.set( name, target );
|
|
1231
|
+
const specFor = ( prim ) => target ? this.overFor( target, prim ) : prim;
|
|
1232
|
+
|
|
1233
|
+
this.writeAnimation( this.animTracks[ a ], specFor, multiple ? name : null );
|
|
1234
|
+
|
|
1235
|
+
} );
|
|
1236
|
+
|
|
1237
|
+
if ( multiple ) {
|
|
1238
|
+
|
|
1239
|
+
this.root.metadata.variants = { ...this.root.metadata.variants, animation: names[ 0 ] };
|
|
1240
|
+
this.moveDefaultsIntoVariants( variantSet );
|
|
1241
|
+
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
void b;
|
|
1245
|
+
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
// Local opinions are stronger than variant opinions, so a value authored on the prim itself would
|
|
1249
|
+
// hide the time samples inside the variants. Defaults of anything a variant animates move into
|
|
1250
|
+
// every variant instead.
|
|
1251
|
+
moveDefaultsIntoVariants( variantSet ) {
|
|
1252
|
+
|
|
1253
|
+
const animated = new Map(); // path below the root -> Set of property names
|
|
1254
|
+
|
|
1255
|
+
const collect = ( spec, path ) => {
|
|
1256
|
+
|
|
1257
|
+
for ( const prop of spec.properties.values() ) if ( prop.timeSamples || prop.targets ) ( animated.get( path ) || animated.set( path, new Set() ).get( path ) ).add( prop.name );
|
|
1258
|
+
for ( const child of spec.children.values() ) collect( child, path + '/' + child.name );
|
|
1259
|
+
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
for ( const variant of variantSet.values() ) collect( variant, '' );
|
|
1263
|
+
|
|
1264
|
+
for ( const [ path, names ] of animated ) {
|
|
1265
|
+
|
|
1266
|
+
const local = this.findSpec( this.b.path( this.root ) + path );
|
|
1267
|
+
if ( ! local ) continue;
|
|
1268
|
+
|
|
1269
|
+
for ( const name of names ) {
|
|
1270
|
+
|
|
1271
|
+
const prop = local.properties.get( name );
|
|
1272
|
+
if ( ! prop ) continue;
|
|
1273
|
+
const value = prop.type === 'relationship' ? prop.targets : prop.default;
|
|
1274
|
+
if ( value === undefined || value === null ) continue;
|
|
1275
|
+
|
|
1276
|
+
for ( const variant of variantSet.values() ) {
|
|
1277
|
+
|
|
1278
|
+
let spec = variant;
|
|
1279
|
+
for ( const part of path.split( '/' ).filter( Boolean ) ) spec = spec.children.get( part ) ?? spec.addChild( new PrimSpec( part, 'over', '' ) );
|
|
1280
|
+
let own = spec.properties.get( name );
|
|
1281
|
+
if ( ! own ) {
|
|
1282
|
+
|
|
1283
|
+
own = spec.addProperty( new PropertySpec( name, prop.type ) );
|
|
1284
|
+
own.typeName = prop.typeName;
|
|
1285
|
+
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
if ( prop.type === 'relationship' ) { if ( ! own.targets ) own.targets = value; }
|
|
1289
|
+
else if ( ! own.timeSamples && own.default === undefined ) own.default = value;
|
|
1290
|
+
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
if ( prop.type === 'relationship' ) local.properties.delete( name );
|
|
1294
|
+
else prop.default = undefined;
|
|
1295
|
+
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
// The over inside a variant mirroring a prim's path below the root.
|
|
1303
|
+
overFor( variant, prim ) {
|
|
1304
|
+
|
|
1305
|
+
const path = this.b.path( prim );
|
|
1306
|
+
const rootPath = this.b.path( this.root );
|
|
1307
|
+
const parts = path.slice( rootPath.length + 1 ).split( '/' ).filter( Boolean );
|
|
1308
|
+
let spec = variant;
|
|
1309
|
+
for ( const part of parts ) spec = spec.children.get( part ) ?? spec.addChild( new PrimSpec( part, 'over', '' ) );
|
|
1310
|
+
return spec;
|
|
1311
|
+
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
writeAnimation( anim, specFor, animationName ) {
|
|
1315
|
+
|
|
1316
|
+
const b = this.b;
|
|
1317
|
+
const json = this.json;
|
|
1318
|
+
|
|
1319
|
+
// node transforms
|
|
1320
|
+
for ( const track of anim.channels ) {
|
|
1321
|
+
|
|
1322
|
+
if ( track.path === 'pointer' ) {
|
|
1323
|
+
|
|
1324
|
+
this.writePointerTrack( track, specFor, animationName );
|
|
1325
|
+
continue;
|
|
1326
|
+
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
if ( track.path === 'weights' ) continue;
|
|
1330
|
+
const prim = this.nodePrims.get( track.node );
|
|
1331
|
+
if ( ! prim || this.jointNodes.has( track.node ) && ! this.nodePrims.has( track.node ) ) continue;
|
|
1332
|
+
|
|
1333
|
+
const op = this.ensureOp( prim, track.path );
|
|
1334
|
+
const spec = specFor( prim );
|
|
1335
|
+
const prop = spec === prim ? op : spec.properties.get( op.name ) ?? spec.addProperty( Object.assign( new PropertySpec( op.name ), { typeName: op.typeName } ) );
|
|
1336
|
+
prop.timeSamples = this.sampleTrack( track );
|
|
1337
|
+
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// skeletons: joints relative to their parent joint (root joints relative to the scene)
|
|
1341
|
+
for ( const info of this.skinInfo || [] ) {
|
|
1342
|
+
|
|
1343
|
+
const affected = anim.channels.some( ( c ) => c.node !== undefined && ( info.jointSet.has( c.node ) || this.isAncestorOfJoint( c.node, info ) ) );
|
|
1344
|
+
const morphs = ( this.skinnedMorphs || [] ).filter( ( m ) => m.anim === info.anim );
|
|
1345
|
+
const weightTracks = anim.channels.filter( ( c ) => c.path === 'weights' && morphs.some( ( m ) => m.nodeIndex === c.node ) );
|
|
1346
|
+
if ( ! affected && ! weightTracks.length ) continue;
|
|
1347
|
+
|
|
1348
|
+
const spec = specFor( info.anim );
|
|
1349
|
+
|
|
1350
|
+
if ( affected ) {
|
|
1351
|
+
|
|
1352
|
+
const times = this.trackTimes( anim.channels.filter( ( c ) => c.node !== undefined && c.path !== 'weights' ) );
|
|
1353
|
+
const translations = new Map(), rotations = new Map(), scales = new Map();
|
|
1354
|
+
const prev = new Map();
|
|
1355
|
+
|
|
1356
|
+
for ( const t of times ) {
|
|
1357
|
+
|
|
1358
|
+
const tr = new Float32Array( info.order.length * 3 ), ro = new Float32Array( info.order.length * 4 ), sc = new Float32Array( info.order.length * 3 );
|
|
1359
|
+
|
|
1360
|
+
info.order.forEach( ( j, k ) => {
|
|
1361
|
+
|
|
1362
|
+
const d = decompose( this.jointLocal( j, info, t, anim ) );
|
|
1363
|
+
const p = prev.get( k );
|
|
1364
|
+
if ( p && p[ 0 ] * d.r[ 0 ] + p[ 1 ] * d.r[ 1 ] + p[ 2 ] * d.r[ 2 ] + p[ 3 ] * d.r[ 3 ] < 0 ) d.r = d.r.map( ( v ) => - v );
|
|
1365
|
+
prev.set( k, d.r );
|
|
1366
|
+
tr.set( d.t, k * 3 ); ro.set( d.r, k * 4 ); sc.set( d.s, k * 3 );
|
|
1367
|
+
|
|
1368
|
+
} );
|
|
1369
|
+
|
|
1370
|
+
const code = t * TIME_CODES_PER_SECOND;
|
|
1371
|
+
this.timeCodes.add( code );
|
|
1372
|
+
translations.set( code, tr ); rotations.set( code, ro ); scales.set( code, sc );
|
|
1373
|
+
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
setSamples( spec, 'translations', 'float3[]', translations );
|
|
1377
|
+
setSamples( spec, 'rotations', 'quatf[]', rotations );
|
|
1378
|
+
setSamples( spec, 'scales', 'half3[]', scales );
|
|
1379
|
+
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
if ( weightTracks.length ) {
|
|
1383
|
+
|
|
1384
|
+
const times = this.trackTimes( weightTracks );
|
|
1385
|
+
const samples = new Map();
|
|
1386
|
+
|
|
1387
|
+
for ( const t of times ) {
|
|
1388
|
+
|
|
1389
|
+
const w = new Float32Array( info.blendNames.length );
|
|
1390
|
+
for ( const m of morphs ) {
|
|
1391
|
+
|
|
1392
|
+
const track = weightTracks.find( ( c ) => c.node === m.nodeIndex );
|
|
1393
|
+
const node = json.nodes[ m.nodeIndex ];
|
|
1394
|
+
const values = track ? sampleTrack( track, t ) : node.weights ?? json.meshes[ node.mesh ].weights ?? [];
|
|
1395
|
+
m.names.forEach( ( n, i ) => { w[ info.blendNames.indexOf( n ) ] = values[ i ] ?? 0; } );
|
|
1396
|
+
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
samples.set( t * TIME_CODES_PER_SECOND, w );
|
|
1400
|
+
this.timeCodes.add( t * TIME_CODES_PER_SECOND );
|
|
1401
|
+
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
setSamples( spec, 'blendShapeWeights', 'float[]', samples );
|
|
1405
|
+
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// morph weights of non skinned meshes
|
|
1411
|
+
for ( const track of anim.channels.filter( ( c ) => c.path === 'weights' ) ) {
|
|
1412
|
+
|
|
1413
|
+
for ( const animPrim of this.morphAnimations?.get( track.node ) || [] ) {
|
|
1414
|
+
|
|
1415
|
+
const samples = new Map();
|
|
1416
|
+
for ( const t of this.trackTimes( [ track ] ) ) {
|
|
1417
|
+
|
|
1418
|
+
samples.set( t * TIME_CODES_PER_SECOND, Float32Array.from( sampleTrack( track, t ) ) );
|
|
1419
|
+
this.timeCodes.add( t * TIME_CODES_PER_SECOND );
|
|
1420
|
+
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
setSamples( specFor( animPrim ), 'blendShapeWeights', 'float[]', samples );
|
|
1424
|
+
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
void b;
|
|
1430
|
+
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
isAncestorOfJoint( node, info ) {
|
|
1434
|
+
|
|
1435
|
+
for ( const j of info.order ) for ( let p = info.parents.get( j ); p !== undefined; p = info.parents.get( p ) ) if ( p === node ) return true;
|
|
1436
|
+
return false;
|
|
1437
|
+
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// Key times for a set of tracks, densified for cubic and step interpolation.
|
|
1441
|
+
trackTimes( tracks ) {
|
|
1442
|
+
|
|
1443
|
+
const times = new Set();
|
|
1444
|
+
|
|
1445
|
+
for ( const track of tracks ) {
|
|
1446
|
+
|
|
1447
|
+
const input = track.input;
|
|
1448
|
+
for ( let i = 0; i < input.length; i ++ ) {
|
|
1449
|
+
|
|
1450
|
+
times.add( input[ i ] );
|
|
1451
|
+
if ( track.interpolation === 'STEP' && i + 1 < input.length ) times.add( Math.max( input[ i ], input[ i + 1 ] - 1e-4 ) );
|
|
1452
|
+
if ( track.interpolation === 'CUBICSPLINE' && i + 1 < input.length ) for ( let k = 1; k < 4; k ++ ) times.add( input[ i ] + ( input[ i + 1 ] - input[ i ] ) * k / 4 );
|
|
1453
|
+
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
return [ ...times ].sort( ( a, b ) => a - b );
|
|
1459
|
+
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
sampleTrack( track ) {
|
|
1463
|
+
|
|
1464
|
+
const samples = new Map();
|
|
1465
|
+
const isRotation = track.path === 'rotation';
|
|
1466
|
+
let prev = null;
|
|
1467
|
+
|
|
1468
|
+
for ( const t of this.trackTimes( [ track ] ) ) {
|
|
1469
|
+
|
|
1470
|
+
let v = sampleTrack( track, t );
|
|
1471
|
+
if ( isRotation ) {
|
|
1472
|
+
|
|
1473
|
+
if ( prev && prev[ 0 ] * v[ 0 ] + prev[ 1 ] * v[ 1 ] + prev[ 2 ] * v[ 2 ] + prev[ 3 ] * v[ 3 ] < 0 ) v = v.map( ( x ) => - x );
|
|
1474
|
+
prev = v;
|
|
1475
|
+
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
const code = t * TIME_CODES_PER_SECOND;
|
|
1479
|
+
this.timeCodes.add( code );
|
|
1480
|
+
samples.set( code, v );
|
|
1481
|
+
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
return samples;
|
|
1485
|
+
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
writePointerTrack( track, specFor, animationName ) {
|
|
1489
|
+
|
|
1490
|
+
const pointer = track.pointer;
|
|
1491
|
+
let m;
|
|
1492
|
+
|
|
1493
|
+
if ( ( m = /^\/nodes\/(\d+)\/extensions\/KHR_node_visibility\/visible$/.exec( pointer ) ) ) {
|
|
1494
|
+
|
|
1495
|
+
const prim = this.nodePrims.get( + m[ 1 ] );
|
|
1496
|
+
if ( ! prim ) return;
|
|
1497
|
+
const samples = new Map();
|
|
1498
|
+
for ( let i = 0; i < track.input.length; i ++ ) {
|
|
1499
|
+
|
|
1500
|
+
const code = track.input[ i ] * TIME_CODES_PER_SECOND;
|
|
1501
|
+
this.timeCodes.add( code );
|
|
1502
|
+
samples.set( code, track.output[ i * track.width ] ? 'inherited' : 'invisible' );
|
|
1503
|
+
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
setSamples( specFor( prim ), 'visibility', 'token', samples );
|
|
1507
|
+
return;
|
|
1508
|
+
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
if ( ( m = /^\/extensions\/KHR_lights_punctual\/lights\/(\d+)\/(intensity|color)$/.exec( pointer ) ) ) {
|
|
1512
|
+
|
|
1513
|
+
const prim = this.lightPrims?.get( + m[ 1 ] );
|
|
1514
|
+
if ( ! prim ) return;
|
|
1515
|
+
const samples = this.sampleTrack( track );
|
|
1516
|
+
setSamples( specFor( prim ), 'inputs:' + m[ 2 ], m[ 2 ] === 'color' ? 'color3f' : 'float', samples );
|
|
1517
|
+
return;
|
|
1518
|
+
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
if ( ( m = /^\/materials\/(\d+)\/(.*)$/.exec( pointer ) ) ) {
|
|
1522
|
+
|
|
1523
|
+
if ( this.writeMaterialTrack( + m[ 1 ], m[ 2 ], track, specFor ) ) return;
|
|
1524
|
+
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// anything else (extension textures, cameras...) is kept as data for the way back, with
|
|
1528
|
+
// glTF indices replaced by prim paths so it survives renumbering
|
|
1529
|
+
const target = { path: pointer };
|
|
1530
|
+
if ( ( m = /^\/materials\/(\d+)(\/.*)$/.exec( pointer ) ) && this.materialPaths.has( + m[ 1 ] ) ) Object.assign( target, { material: this.materialPaths.get( + m[ 1 ] ), path: m[ 2 ] } );
|
|
1531
|
+
else if ( ( m = /^\/nodes\/(\d+)(\/.*)$/.exec( pointer ) ) && this.nodePrims.has( + m[ 1 ] ) ) Object.assign( target, { node: this.b.path( this.nodePrims.get( + m[ 1 ] ) ), path: m[ 2 ] } );
|
|
1532
|
+
for ( const t of track.input ) this.timeCodes.add( t * TIME_CODES_PER_SECOND );
|
|
1533
|
+
( this.unmappedPointers ||= [] ).push( { ...target, animation: animationName, interpolation: track.interpolation, width: track.width, input: Array.from( track.input ), output: Array.from( track.output ) } );
|
|
1534
|
+
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
writeMaterialTrack( index, path, track, specFor ) {
|
|
1538
|
+
|
|
1539
|
+
const inputs = this.shaderInputs?.get( index );
|
|
1540
|
+
const material = this.json.materials?.[ index ];
|
|
1541
|
+
if ( ! inputs || ! material ) return false;
|
|
1542
|
+
const samples = this.sampleTrack( track );
|
|
1543
|
+
const at = ( attrPath ) => {
|
|
1544
|
+
|
|
1545
|
+
const [ primPath, name ] = [ attrPath.slice( 0, attrPath.lastIndexOf( '.' ) ), attrPath.slice( attrPath.lastIndexOf( '.' ) + 1 ) ];
|
|
1546
|
+
const prim = this.findSpec( primPath );
|
|
1547
|
+
return prim ? { prim, name } : null;
|
|
1548
|
+
|
|
1549
|
+
};
|
|
1550
|
+
|
|
1551
|
+
if ( path === 'pbrMetallicRoughness/baseColorFactor' ) {
|
|
1552
|
+
|
|
1553
|
+
if ( inputs.baseColorTexture ) {
|
|
1554
|
+
|
|
1555
|
+
const t = at( inputs.baseColorTexture + '.inputs:scale' );
|
|
1556
|
+
if ( t ) setSamples( specFor( t.prim ), 'inputs:scale', 'float4', samples );
|
|
1557
|
+
|
|
1558
|
+
} else if ( inputs.diffuseColor ) {
|
|
1559
|
+
|
|
1560
|
+
const t = at( inputs.diffuseColor );
|
|
1561
|
+
const rgb = new Map( [ ...samples ].map( ( [ k, v ] ) => [ k, v.slice( 0, 3 ) ] ) );
|
|
1562
|
+
if ( t ) setSamples( specFor( t.prim ), t.name, 'color3f', rgb );
|
|
1563
|
+
if ( inputs.opacity ) {
|
|
1564
|
+
|
|
1565
|
+
const o = at( inputs.opacity );
|
|
1566
|
+
if ( o ) setSamples( specFor( o.prim ), o.name, 'float', new Map( [ ...samples ].map( ( [ k, v ] ) => [ k, v[ 3 ] ] ) ) );
|
|
1567
|
+
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
return true;
|
|
1573
|
+
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
if ( path === 'emissiveFactor' ) {
|
|
1577
|
+
|
|
1578
|
+
const strength = material.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1;
|
|
1579
|
+
const scaled = new Map( [ ...samples ].map( ( [ k, v ] ) => [ k, v.map( ( x ) => x * strength ) ] ) );
|
|
1580
|
+
|
|
1581
|
+
if ( inputs.emissiveTexture ) {
|
|
1582
|
+
|
|
1583
|
+
const t = at( inputs.emissiveTexture + '.inputs:scale' );
|
|
1584
|
+
if ( t ) setSamples( specFor( t.prim ), 'inputs:scale', 'float4', new Map( [ ...scaled ].map( ( [ k, v ] ) => [ k, [ ...v, 1 ] ] ) ) );
|
|
1585
|
+
|
|
1586
|
+
} else {
|
|
1587
|
+
|
|
1588
|
+
const prim = this.findSpec( this.materialPaths.get( index ) + '/PreviewSurface' );
|
|
1589
|
+
if ( prim ) setSamples( specFor( prim ), 'inputs:emissiveColor', 'color3f', scaled );
|
|
1590
|
+
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
return true;
|
|
1594
|
+
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
const tt = /^(.*)\/extensions\/KHR_texture_transform\/(offset|rotation|scale)$/.exec( path );
|
|
1598
|
+
|
|
1599
|
+
if ( tt ) {
|
|
1600
|
+
|
|
1601
|
+
// find the texture info at that path to locate its transform node
|
|
1602
|
+
const info = tt[ 1 ].split( '/' ).reduce( ( o, k ) => o?.[ k ], material );
|
|
1603
|
+
const node = info && inputs[ `texture:${ info.index }:transform` ];
|
|
1604
|
+
if ( ! node ) return false;
|
|
1605
|
+
const prim = this.findSpec( node );
|
|
1606
|
+
const transform = info.extensions.KHR_texture_transform;
|
|
1607
|
+
const out = new Map();
|
|
1608
|
+
|
|
1609
|
+
for ( const [ k, v ] of samples ) {
|
|
1610
|
+
|
|
1611
|
+
const u = usdTextureTransform( { ...transform, [ tt[ 2 ] ]: tt[ 2 ] === 'rotation' ? v[ 0 ] : v } );
|
|
1612
|
+
out.set( k, u );
|
|
1613
|
+
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
setSamples( specFor( prim ), 'inputs:translation', 'float2', new Map( [ ...out ].map( ( [ k, u ] ) => [ k, u.translation ] ) ) );
|
|
1617
|
+
setSamples( specFor( prim ), 'inputs:rotation', 'float', new Map( [ ...out ].map( ( [ k, u ] ) => [ k, u.rotation ] ) ) );
|
|
1618
|
+
setSamples( specFor( prim ), 'inputs:scale', 'float2', new Map( [ ...out ].map( ( [ k, u ] ) => [ k, u.scale ] ) ) );
|
|
1619
|
+
return true;
|
|
1620
|
+
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
return false;
|
|
1624
|
+
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
findSpec( path ) {
|
|
1628
|
+
|
|
1629
|
+
return this.b.layer.getPrimAtPath( path );
|
|
1630
|
+
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// --- material variants ---
|
|
1634
|
+
|
|
1635
|
+
convertMaterialVariants() {
|
|
1636
|
+
|
|
1637
|
+
const variants = this.json.extensions?.KHR_materials_variants?.variants;
|
|
1638
|
+
if ( ! variants?.length ) return;
|
|
1639
|
+
|
|
1640
|
+
const set = new Map();
|
|
1641
|
+
const names = [];
|
|
1642
|
+
|
|
1643
|
+
variants.forEach( ( v, i ) => {
|
|
1644
|
+
|
|
1645
|
+
let name = sanitize( v.name, `variant_${ i }` );
|
|
1646
|
+
while ( names.includes( name ) ) name += '_';
|
|
1647
|
+
names.push( name );
|
|
1648
|
+
const variant = new PrimSpec( name, 'over', '' );
|
|
1649
|
+
set.set( name, variant );
|
|
1650
|
+
|
|
1651
|
+
for ( const [ key, prim ] of this.meshPrims ) {
|
|
1652
|
+
|
|
1653
|
+
const [ nodeIndex, p ] = key.split( '/' ).map( Number );
|
|
1654
|
+
const primitive = this.json.meshes[ this.json.nodes[ nodeIndex ].mesh ].primitives[ p ];
|
|
1655
|
+
const mapping = primitive.extensions?.KHR_materials_variants?.mappings?.find( ( m ) => m.variants.includes( i ) );
|
|
1656
|
+
const material = mapping ? mapping.material : primitive.material;
|
|
1657
|
+
const path = material !== undefined ? this.materialPaths.get( material ) : this.defaultMaterialPath();
|
|
1658
|
+
if ( ! path ) continue;
|
|
1659
|
+
// the binding without a variant selected, which glTF has and USD doesn't
|
|
1660
|
+
if ( i === 0 && primitive.material !== undefined ) gltfData( prim ).material = this.materialPaths.get( primitive.material );
|
|
1661
|
+
const over = this.overFor( variant, prim );
|
|
1662
|
+
const rel = over.addProperty( new PropertySpec( 'material:binding', 'relationship' ) );
|
|
1663
|
+
rel.targets = ListOp.explicit( [ path ] );
|
|
1664
|
+
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
} );
|
|
1668
|
+
|
|
1669
|
+
this.root.variantSets.set( 'materialVariant', set );
|
|
1670
|
+
const op = this.root.metadata.variantSetNames || new ListOp();
|
|
1671
|
+
op.prepended.push( 'materialVariant' );
|
|
1672
|
+
this.root.metadata.variantSetNames = op;
|
|
1673
|
+
this.root.metadata.variants = { ...this.root.metadata.variants, materialVariant: names[ 0 ] };
|
|
1674
|
+
this.moveDefaultsIntoVariants( set );
|
|
1675
|
+
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// The customData.gltf dictionary of a prim spec, where glTF only data is kept.
|
|
1681
|
+
function gltfData( spec ) {
|
|
1682
|
+
|
|
1683
|
+
const customData = spec.metadata.customData ||= {};
|
|
1684
|
+
return customData.gltf ||= {};
|
|
1685
|
+
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
function setSamples( spec, name, typeName, samples ) {
|
|
1689
|
+
|
|
1690
|
+
let prop = spec.properties.get( name );
|
|
1691
|
+
|
|
1692
|
+
if ( ! prop ) {
|
|
1693
|
+
|
|
1694
|
+
prop = spec.addProperty( new PropertySpec( name, 'attribute' ) );
|
|
1695
|
+
prop.typeName = typeName;
|
|
1696
|
+
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
prop.timeSamples = samples;
|
|
1700
|
+
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
function jointParent( j, parents, jointSet ) {
|
|
1704
|
+
|
|
1705
|
+
for ( let p = parents.get( j ); p !== undefined; p = parents.get( p ) ) if ( jointSet.has( p ) ) return p;
|
|
1706
|
+
return null;
|
|
1707
|
+
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// Orders joints so parents come before children.
|
|
1711
|
+
function orderJoints( joints, parents, jointSet ) {
|
|
1712
|
+
|
|
1713
|
+
const depth = ( j ) => {
|
|
1714
|
+
|
|
1715
|
+
let d = 0;
|
|
1716
|
+
for ( let p = jointParent( j, parents, jointSet ); p !== null; p = jointParent( p, parents, jointSet ) ) d ++;
|
|
1717
|
+
return d;
|
|
1718
|
+
|
|
1719
|
+
};
|
|
1720
|
+
|
|
1721
|
+
return joints.map( ( j, i ) => ( { j, i, d: depth( j ) } ) ).sort( ( a, b ) => a.d - b.d || a.i - b.i ).map( ( x ) => x.j );
|
|
1722
|
+
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
export function sampleTrack( track, time ) {
|
|
1726
|
+
|
|
1727
|
+
const { input, output, width, interpolation } = track;
|
|
1728
|
+
const n = input.length;
|
|
1729
|
+
const cubic = interpolation === 'CUBICSPLINE';
|
|
1730
|
+
const get = ( k ) => Array.from( output.subarray( cubic ? ( k * 3 + 1 ) * width : k * width, ( cubic ? ( k * 3 + 1 ) * width : k * width ) + width ) );
|
|
1731
|
+
|
|
1732
|
+
if ( time <= input[ 0 ] ) return get( 0 );
|
|
1733
|
+
if ( time >= input[ n - 1 ] ) return get( n - 1 );
|
|
1734
|
+
|
|
1735
|
+
let k = 0;
|
|
1736
|
+
let lo = 0, hi = n - 1;
|
|
1737
|
+
while ( lo <= hi ) { const mid = ( lo + hi ) >> 1; if ( input[ mid ] <= time ) { k = mid; lo = mid + 1; } else hi = mid - 1; }
|
|
1738
|
+
k = Math.min( k, n - 2 );
|
|
1739
|
+
|
|
1740
|
+
const t0 = input[ k ], t1 = input[ k + 1 ];
|
|
1741
|
+
const u = t1 > t0 ? ( time - t0 ) / ( t1 - t0 ) : 0;
|
|
1742
|
+
if ( interpolation === 'STEP' ) return get( k );
|
|
1743
|
+
|
|
1744
|
+
if ( cubic ) {
|
|
1745
|
+
|
|
1746
|
+
const dt = t1 - t0;
|
|
1747
|
+
const p0 = get( k ), p1 = get( k + 1 );
|
|
1748
|
+
const m0 = Array.from( output.subarray( ( k * 3 + 2 ) * width, ( k * 3 + 3 ) * width ) );
|
|
1749
|
+
const m1 = Array.from( output.subarray( ( k + 1 ) * 3 * width, ( ( k + 1 ) * 3 + 1 ) * width ) );
|
|
1750
|
+
const u2 = u * u, u3 = u2 * u;
|
|
1751
|
+
const r = p0.map( ( _, i ) => ( 2 * u3 - 3 * u2 + 1 ) * p0[ i ] + ( u3 - 2 * u2 + u ) * dt * m0[ i ] + ( - 2 * u3 + 3 * u2 ) * p1[ i ] + ( u3 - u2 ) * dt * m1[ i ] );
|
|
1752
|
+
if ( track.path === 'rotation' ) { const l = Math.hypot( ...r ) || 1; return r.map( ( v ) => v / l ); }
|
|
1753
|
+
return r;
|
|
1754
|
+
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
const a = get( k ), b = get( k + 1 );
|
|
1758
|
+
|
|
1759
|
+
if ( track.path === 'rotation' ) {
|
|
1760
|
+
|
|
1761
|
+
let dot = a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ] + a[ 3 ] * b[ 3 ];
|
|
1762
|
+
const bb = dot < 0 ? b.map( ( v ) => - v ) : b;
|
|
1763
|
+
dot = Math.abs( dot );
|
|
1764
|
+
if ( dot > 0.9995 ) { const r = a.map( ( v, i ) => v + ( bb[ i ] - v ) * u ); const l = Math.hypot( ...r ); return r.map( ( v ) => v / l ); }
|
|
1765
|
+
const th = Math.acos( dot ), s = Math.sin( th );
|
|
1766
|
+
return a.map( ( v, i ) => v * Math.sin( ( 1 - u ) * th ) / s + bb[ i ] * Math.sin( u * th ) / s );
|
|
1767
|
+
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
return a.map( ( v, i ) => v + ( b[ i ] - v ) * u );
|
|
1771
|
+
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
function extent( positions ) {
|
|
1775
|
+
|
|
1776
|
+
const min = [ Infinity, Infinity, Infinity ], max = [ - Infinity, - Infinity, - Infinity ];
|
|
1777
|
+
for ( let i = 0; i < positions.length; i += 3 ) for ( let k = 0; k < 3; k ++ ) {
|
|
1778
|
+
|
|
1779
|
+
const v = positions[ i + k ];
|
|
1780
|
+
if ( v < min[ k ] ) min[ k ] = v;
|
|
1781
|
+
if ( v > max[ k ] ) max[ k ] = v;
|
|
1782
|
+
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
if ( min[ 0 ] === Infinity ) return Float32Array.of( 0, 0, 0, 0, 0, 0 );
|
|
1786
|
+
return Float32Array.of( ...min, ...max );
|
|
1787
|
+
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
// glTF KHR_texture_transform (v down) -> UsdTransform2d parameters (v up).
|
|
1791
|
+
export function usdTextureTransform( t ) {
|
|
1792
|
+
|
|
1793
|
+
const [ ox, oy ] = t.offset || [ 0, 0 ];
|
|
1794
|
+
const r = t.rotation || 0;
|
|
1795
|
+
const [ sx, sy ] = t.scale || [ 1, 1 ];
|
|
1796
|
+
const c = Math.cos( r ), s = Math.sin( r );
|
|
1797
|
+
// glTF matrix = T * R * S with R = [ c s; -s c ] in column major [ c, -s, s, c ]
|
|
1798
|
+
const g = [ c * sx, - s * sx, 0, 0, s * sy, c * sy, 0, 0, 0, 0, 1, 0, ox, oy, 0, 1 ];
|
|
1799
|
+
const flip = [ 1, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 ];
|
|
1800
|
+
const m = multiply( flip, multiply( g, flip ) );
|
|
1801
|
+
const usx = Math.hypot( m[ 0 ], m[ 1 ] );
|
|
1802
|
+
const det = m[ 0 ] * m[ 5 ] - m[ 1 ] * m[ 4 ];
|
|
1803
|
+
const usy = Math.hypot( m[ 4 ], m[ 5 ] ) * Math.sign( det || 1 );
|
|
1804
|
+
return { rotation: Math.atan2( m[ 1 ], m[ 0 ] ) * 180 / Math.PI, scale: [ usx, usy ], translation: [ m[ 12 ], m[ 13 ] ] };
|
|
1805
|
+
|
|
1806
|
+
}
|
|
1807
|
+
|