-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
/
USDZLoader.js
870 lines (485 loc) · 18.3 KB
/
USDZLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
import {
BufferAttribute,
BufferGeometry,
ClampToEdgeWrapping,
FileLoader,
Group,
NoColorSpace,
Loader,
Mesh,
MeshPhysicalMaterial,
MirroredRepeatWrapping,
RepeatWrapping,
SRGBColorSpace,
TextureLoader,
Object3D,
Vector2
} from 'three';
import * as fflate from '../libs/fflate.module.js';
class USDAParser {
parse( text ) {
const data = {};
const lines = text.split( '\n' );
let string = null;
let target = data;
const stack = [ data ];
// debugger;
for ( const line of lines ) {
// console.log( line );
if ( line.includes( '=' ) ) {
const assignment = line.split( '=' );
const lhs = assignment[ 0 ].trim();
const rhs = assignment[ 1 ].trim();
if ( rhs.endsWith( '{' ) ) {
const group = {};
stack.push( group );
target[ lhs ] = group;
target = group;
} else if ( rhs.endsWith( '(' ) ) {
// see #28631
const values = rhs.slice( 0, - 1 );
target[ lhs ] = values;
const meta = {};
stack.push( meta );
target = meta;
} else {
target[ lhs ] = rhs;
}
} else if ( line.endsWith( '{' ) ) {
const group = target[ string ] || {};
stack.push( group );
target[ string ] = group;
target = group;
} else if ( line.endsWith( '}' ) ) {
stack.pop();
if ( stack.length === 0 ) continue;
target = stack[ stack.length - 1 ];
} else if ( line.endsWith( '(' ) ) {
const meta = {};
stack.push( meta );
string = line.split( '(' )[ 0 ].trim() || string;
target[ string ] = meta;
target = meta;
} else if ( line.endsWith( ')' ) ) {
stack.pop();
target = stack[ stack.length - 1 ];
} else {
string = line.trim();
}
}
return data;
}
}
class USDZLoader extends Loader {
constructor( manager ) {
super( manager );
}
load( url, onLoad, onProgress, onError ) {
const scope = this;
const loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.setResponseType( 'arraybuffer' );
loader.setRequestHeader( scope.requestHeader );
loader.setWithCredentials( scope.withCredentials );
loader.load( url, function ( text ) {
try {
onLoad( scope.parse( text ) );
} catch ( e ) {
if ( onError ) {
onError( e );
} else {
console.error( e );
}
scope.manager.itemError( url );
}
}, onProgress, onError );
}
parse( buffer ) {
const parser = new USDAParser();
function parseAssets( zip ) {
const data = {};
const loader = new FileLoader();
loader.setResponseType( 'arraybuffer' );
for ( const filename in zip ) {
if ( filename.endsWith( 'png' ) ) {
const blob = new Blob( [ zip[ filename ] ], { type: { type: 'image/png' } } );
data[ filename ] = URL.createObjectURL( blob );
}
if ( filename.endsWith( 'usd' ) || filename.endsWith( 'usda' ) ) {
if ( isCrateFile( zip[ filename ] ) ) {
throw Error( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
}
const text = fflate.strFromU8( zip[ filename ] );
data[ filename ] = parser.parse( text );
}
}
return data;
}
function isCrateFile( buffer ) {
// Check if this a crate file. First 7 bytes of a crate file are "PXR-USDC".
const fileHeader = buffer.slice( 0, 7 );
const crateHeader = new Uint8Array( [ 0x50, 0x58, 0x52, 0x2D, 0x55, 0x53, 0x44, 0x43 ] );
// If this is not a crate file, we assume it is a plain USDA file.
return fileHeader.every( ( value, index ) => value === crateHeader[ index ] );
}
function findUSD( zip ) {
if ( zip.length < 1 ) return undefined;
const firstFileName = Object.keys( zip )[ 0 ];
let isCrate = false;
// As per the USD specification, the first entry in the zip archive is used as the main file ("UsdStage").
// ASCII files can end in either .usda or .usd.
// See https://openusd.org/release/spec_usdz.html#layout
if ( firstFileName.endsWith( 'usda' ) ) return zip[ firstFileName ];
if ( firstFileName.endsWith( 'usdc' ) ) {
isCrate = true;
} else if ( firstFileName.endsWith( 'usd' ) ) {
// If this is not a crate file, we assume it is a plain USDA file.
if ( ! isCrateFile( zip[ firstFileName ] ) ) {
return zip[ firstFileName ];
} else {
isCrate = true;
}
}
if ( isCrate ) {
throw Error( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
}
}
const zip = fflate.unzipSync( new Uint8Array( buffer ) );
// console.log( zip );
const assets = parseAssets( zip );
// console.log( assets )
const file = findUSD( zip );
// Parse file
const text = fflate.strFromU8( file );
const root = parser.parse( text );
// Build scene
function findMeshGeometry( data ) {
if ( ! data ) return undefined;
if ( 'prepend references' in data ) {
const reference = data[ 'prepend references' ];
const parts = reference.split( '@' );
const path = parts[ 1 ].replace( /^.\//, '' );
const id = parts[ 2 ].replace( /^<\//, '' ).replace( />$/, '' );
return findGeometry( assets[ path ], id );
}
return findGeometry( data );
}
function findGeometry( data, id ) {
if ( ! data ) return undefined;
if ( id !== undefined ) {
const def = `def Mesh "${id}"`;
if ( def in data ) {
return data[ def ];
}
}
for ( const name in data ) {
const object = data[ name ];
if ( name.startsWith( 'def Mesh' ) ) {
return object;
}
if ( typeof object === 'object' ) {
const geometry = findGeometry( object );
if ( geometry ) return geometry;
}
}
}
function buildGeometry( data ) {
if ( ! data ) return undefined;
const geometry = new BufferGeometry();
let indices = null;
let counts = null;
let uvs = null;
let positionsLength = - 1;
// index
if ( 'int[] faceVertexIndices' in data ) {
indices = JSON.parse( data[ 'int[] faceVertexIndices' ] );
}
// face count
if ( 'int[] faceVertexCounts' in data ) {
counts = JSON.parse( data[ 'int[] faceVertexCounts' ] );
indices = toTriangleIndices( indices, counts );
}
// position
if ( 'point3f[] points' in data ) {
const positions = JSON.parse( data[ 'point3f[] points' ].replace( /[()]*/g, '' ) );
positionsLength = positions.length;
let attribute = new BufferAttribute( new Float32Array( positions ), 3 );
if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
geometry.setAttribute( 'position', attribute );
}
// uv
if ( 'float2[] primvars:st' in data ) {
data[ 'texCoord2f[] primvars:st' ] = data[ 'float2[] primvars:st' ];
}
if ( 'texCoord2f[] primvars:st' in data ) {
uvs = JSON.parse( data[ 'texCoord2f[] primvars:st' ].replace( /[()]*/g, '' ) );
let attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
geometry.setAttribute( 'uv', attribute );
}
if ( 'int[] primvars:st:indices' in data && uvs !== null ) {
// custom uv index, overwrite uvs with new data
const attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
let indices = JSON.parse( data[ 'int[] primvars:st:indices' ] );
indices = toTriangleIndices( indices, counts );
geometry.setAttribute( 'uv', toFlatBufferAttribute( attribute, indices ) );
}
// normal
if ( 'normal3f[] normals' in data ) {
const normals = JSON.parse( data[ 'normal3f[] normals' ].replace( /[()]*/g, '' ) );
let attribute = new BufferAttribute( new Float32Array( normals ), 3 );
// normals require a special treatment in USD
if ( normals.length === positionsLength ) {
// raw normal and position data have equal length (like produced by USDZExporter)
if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
} else {
// unequal length, normals are independent of faceVertexIndices
let indices = Array.from( Array( normals.length / 3 ).keys() ); // [ 0, 1, 2, 3 ... ]
indices = toTriangleIndices( indices, counts );
attribute = toFlatBufferAttribute( attribute, indices );
}
geometry.setAttribute( 'normal', attribute );
} else {
// compute flat vertex normals
geometry.computeVertexNormals();
}
return geometry;
}
function toTriangleIndices( rawIndices, counts ) {
const indices = [];
for ( let i = 0; i < counts.length; i ++ ) {
const count = counts[ i ];
const stride = i * count;
if ( count === 3 ) {
const a = rawIndices[ stride + 0 ];
const b = rawIndices[ stride + 1 ];
const c = rawIndices[ stride + 2 ];
indices.push( a, b, c );
} else if ( count === 4 ) {
const a = rawIndices[ stride + 0 ];
const b = rawIndices[ stride + 1 ];
const c = rawIndices[ stride + 2 ];
const d = rawIndices[ stride + 3 ];
indices.push( a, b, c );
indices.push( a, c, d );
} else {
console.warn( 'THREE.USDZLoader: Face vertex count of %s unsupported.', count );
}
}
return indices;
}
function toFlatBufferAttribute( attribute, indices ) {
const array = attribute.array;
const itemSize = attribute.itemSize;
const array2 = new array.constructor( indices.length * itemSize );
let index = 0, index2 = 0;
for ( let i = 0, l = indices.length; i < l; i ++ ) {
index = indices[ i ] * itemSize;
for ( let j = 0; j < itemSize; j ++ ) {
array2[ index2 ++ ] = array[ index ++ ];
}
}
return new BufferAttribute( array2, itemSize );
}
function findMeshMaterial( data ) {
if ( ! data ) return undefined;
if ( 'rel material:binding' in data ) {
const reference = data[ 'rel material:binding' ];
const id = reference.replace( /^<\//, '' ).replace( />$/, '' );
const parts = id.split( '/' );
return findMaterial( root, ` "${ parts[ 1 ] }"` );
}
return findMaterial( data );
}
function findMaterial( data, id = '' ) {
for ( const name in data ) {
const object = data[ name ];
if ( name.startsWith( 'def Material' + id ) ) {
return object;
}
if ( typeof object === 'object' ) {
const material = findMaterial( object, id );
if ( material ) return material;
}
}
}
function setTextureParams( map, data_value ) {
// rotation, scale and translation
if ( data_value[ 'float inputs:rotation' ] ) {
map.rotation = parseFloat( data_value[ 'float inputs:rotation' ] );
}
if ( data_value[ 'float2 inputs:scale' ] ) {
map.repeat = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:scale' ].replace( /[()]*/g, '' ) + ']' ) );
}
if ( data_value[ 'float2 inputs:translation' ] ) {
map.offset = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:translation' ].replace( /[()]*/g, '' ) + ']' ) );
}
}
function buildMaterial( data ) {
const material = new MeshPhysicalMaterial();
if ( data !== undefined ) {
const surfaceConnection = data[ 'token outputs:surface.connect' ];
const surfaceName = /(\w+).output/.exec( surfaceConnection )[ 1 ];
const surface = data[ `def Shader "${surfaceName}"` ];
if ( surface !== undefined ) {
if ( 'color3f inputs:diffuseColor.connect' in surface ) {
const path = surface[ 'color3f inputs:diffuseColor.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.map = buildTexture( sampler );
material.map.colorSpace = SRGBColorSpace;
if ( 'def Shader "Transform2d_diffuse"' in data ) {
setTextureParams( material.map, data[ 'def Shader "Transform2d_diffuse"' ] );
}
} else if ( 'color3f inputs:diffuseColor' in surface ) {
const color = surface[ 'color3f inputs:diffuseColor' ].replace( /[()]*/g, '' );
material.color.fromArray( JSON.parse( '[' + color + ']' ) );
}
if ( 'color3f inputs:emissiveColor.connect' in surface ) {
const path = surface[ 'color3f inputs:emissiveColor.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.emissiveMap = buildTexture( sampler );
material.emissiveMap.colorSpace = SRGBColorSpace;
material.emissive.set( 0xffffff );
if ( 'def Shader "Transform2d_emissive"' in data ) {
setTextureParams( material.emissiveMap, data[ 'def Shader "Transform2d_emissive"' ] );
}
} else if ( 'color3f inputs:emissiveColor' in surface ) {
const color = surface[ 'color3f inputs:emissiveColor' ].replace( /[()]*/g, '' );
material.emissive.fromArray( JSON.parse( '[' + color + ']' ) );
}
if ( 'normal3f inputs:normal.connect' in surface ) {
const path = surface[ 'normal3f inputs:normal.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.normalMap = buildTexture( sampler );
material.normalMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_normal"' in data ) {
setTextureParams( material.normalMap, data[ 'def Shader "Transform2d_normal"' ] );
}
}
if ( 'float inputs:roughness.connect' in surface ) {
const path = surface[ 'float inputs:roughness.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.roughness = 1.0;
material.roughnessMap = buildTexture( sampler );
material.roughnessMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_roughness"' in data ) {
setTextureParams( material.roughnessMap, data[ 'def Shader "Transform2d_roughness"' ] );
}
} else if ( 'float inputs:roughness' in surface ) {
material.roughness = parseFloat( surface[ 'float inputs:roughness' ] );
}
if ( 'float inputs:metallic.connect' in surface ) {
const path = surface[ 'float inputs:metallic.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.metalness = 1.0;
material.metalnessMap = buildTexture( sampler );
material.metalnessMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_metallic"' in data ) {
setTextureParams( material.metalnessMap, data[ 'def Shader "Transform2d_metallic"' ] );
}
} else if ( 'float inputs:metallic' in surface ) {
material.metalness = parseFloat( surface[ 'float inputs:metallic' ] );
}
if ( 'float inputs:clearcoat.connect' in surface ) {
const path = surface[ 'float inputs:clearcoat.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.clearcoat = 1.0;
material.clearcoatMap = buildTexture( sampler );
material.clearcoatMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_clearcoat"' in data ) {
setTextureParams( material.clearcoatMap, data[ 'def Shader "Transform2d_clearcoat"' ] );
}
} else if ( 'float inputs:clearcoat' in surface ) {
material.clearcoat = parseFloat( surface[ 'float inputs:clearcoat' ] );
}
if ( 'float inputs:clearcoatRoughness.connect' in surface ) {
const path = surface[ 'float inputs:clearcoatRoughness.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.clearcoatRoughness = 1.0;
material.clearcoatRoughnessMap = buildTexture( sampler );
material.clearcoatRoughnessMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_clearcoatRoughness"' in data ) {
setTextureParams( material.clearcoatRoughnessMap, data[ 'def Shader "Transform2d_clearcoatRoughness"' ] );
}
} else if ( 'float inputs:clearcoatRoughness' in surface ) {
material.clearcoatRoughness = parseFloat( surface[ 'float inputs:clearcoatRoughness' ] );
}
if ( 'float inputs:ior' in surface ) {
material.ior = parseFloat( surface[ 'float inputs:ior' ] );
}
if ( 'float inputs:occlusion.connect' in surface ) {
const path = surface[ 'float inputs:occlusion.connect' ];
const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
material.aoMap = buildTexture( sampler );
material.aoMap.colorSpace = NoColorSpace;
if ( 'def Shader "Transform2d_occlusion"' in data ) {
setTextureParams( material.aoMap, data[ 'def Shader "Transform2d_occlusion"' ] );
}
}
}
}
return material;
}
function findTexture( data, id ) {
for ( const name in data ) {
const object = data[ name ];
if ( name.startsWith( `def Shader "${ id }"` ) ) {
return object;
}
if ( typeof object === 'object' ) {
const texture = findTexture( object, id );
if ( texture ) return texture;
}
}
}
function buildTexture( data ) {
if ( 'asset inputs:file' in data ) {
const path = data[ 'asset inputs:file' ].replace( /@*/g, '' ).trim();
const loader = new TextureLoader();
const texture = loader.load( assets[ path ] );
const map = {
'"clamp"': ClampToEdgeWrapping,
'"mirror"': MirroredRepeatWrapping,
'"repeat"': RepeatWrapping
};
if ( 'token inputs:wrapS' in data ) {
texture.wrapS = map[ data[ 'token inputs:wrapS' ] ];
}
if ( 'token inputs:wrapT' in data ) {
texture.wrapT = map[ data[ 'token inputs:wrapT' ] ];
}
return texture;
}
return null;
}
function buildObject( data ) {
const geometry = buildGeometry( findMeshGeometry( data ) );
const material = buildMaterial( findMeshMaterial( data ) );
const mesh = geometry ? new Mesh( geometry, material ) : new Object3D();
if ( 'matrix4d xformOp:transform' in data ) {
const array = JSON.parse( '[' + data[ 'matrix4d xformOp:transform' ].replace( /[()]*/g, '' ) + ']' );
mesh.matrix.fromArray( array );
mesh.matrix.decompose( mesh.position, mesh.quaternion, mesh.scale );
}
return mesh;
}
function buildHierarchy( data, group ) {
for ( const name in data ) {
if ( name.startsWith( 'def Scope' ) ) {
buildHierarchy( data[ name ], group );
} else if ( name.startsWith( 'def Xform' ) ) {
const mesh = buildObject( data[ name ] );
if ( /def Xform "(\w+)"/.test( name ) ) {
mesh.name = /def Xform "(\w+)"/.exec( name )[ 1 ];
}
group.add( mesh );
buildHierarchy( data[ name ], mesh );
}
}
}
const group = new Group();
buildHierarchy( root, group );
return group;
}
}
export { USDZLoader };