-
Notifications
You must be signed in to change notification settings - Fork 33
/
AWD2Parser.hx
2436 lines (2215 loc) · 91.5 KB
/
AWD2Parser.hx
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package away3d.loaders.parsers;
import away3d.*;
import away3d.animators.*;
import away3d.animators.data.*;
import away3d.animators.nodes.*;
import away3d.cameras.*;
import away3d.cameras.lenses.*;
import away3d.containers.*;
import away3d.core.base.*;
import away3d.entities.*;
import away3d.library.assets.*;
import away3d.lights.*;
import away3d.lights.shadowmaps.*;
import away3d.loaders.misc.*;
import away3d.loaders.parsers.utils.*;
import away3d.materials.*;
import away3d.materials.lightpickers.*;
import away3d.materials.methods.*;
import away3d.materials.utils.*;
import away3d.primitives.*;
import away3d.textures.*;
import away3d.tools.utils.*;
import openfl.display.BitmapData;
import openfl.display.BlendMode;
import openfl.display.Sprite;
import openfl.geom.ColorTransform;
import openfl.geom.Matrix;
import openfl.geom.Matrix3D;
import openfl.geom.Vector3D;
import openfl.net.URLRequest;
import openfl.utils.ByteArray;
import openfl.utils.CompressionAlgorithm;
import openfl.utils.Endian;
import openfl.Lib;
import openfl.Vector;
using Reflect;
/**
* AWDParser provides a parser for the AWD data type.
*/
class AWD2Parser extends ParserBase
{
//set to "true" to have some traces in the Console
private var _debug:Bool = false;
private var _byteData:ByteArray;
private var _cur_block_id:UInt;
private var _blocks:Vector<AWDBlock>;
private var _newBlockBytes:ByteArray;
private var _version:Array<Int>;
private var _compression:UInt;
private var _accuracyOnBlocks:Bool;
private var _accuracyMatrix:Bool;
private var _accuracyGeo:Bool;
private var _accuracyProps:Bool;
private var _matrixNrType:UInt;
private var _geoNrType:UInt;
private var _propsNrType:UInt;
private var _streaming:Bool;
private var _texture_users:Map<String, Array<Int>>;
private var _body:ByteArray;
private var _defaultTexture:BitmapTexture;
private var _defaultCubeTexture:BitmapCubeTexture;
private var _defaultBitmapMaterial:TextureMaterial;
private var _cubeTextures:Array<BitmapData>;
public static inline var COMPRESSIONMODE_LZMA:String = "lzma";
public static inline var UNCOMPRESSED:UInt = 0;
public static inline var DEFLATE:UInt = 1;
public static inline var LZMA:UInt = 2;
public static inline var INT8:UInt = 1;
public static inline var INT16:UInt = 2;
public static inline var INT32:UInt = 3;
public static inline var UINT8:UInt = 4;
public static inline var UINT16:UInt = 5;
public static inline var UINT32:UInt = 6;
public static inline var FLOAT32:UInt = 7;
public static inline var FLOAT64:UInt = 8;
public static inline var BOOL:UInt = 21;
public static inline var COLOR:UInt = 22;
public static inline var BADDR:UInt = 23;
public static inline var AWDSTRING:UInt = 31;
public static inline var AWDBYTEARRAY:UInt = 32;
public static inline var VECTOR2x1:UInt = 41;
public static inline var VECTOR3x1:UInt = 42;
public static inline var VECTOR4x1:UInt = 43;
public static inline var MTX3x2:UInt = 44;
public static inline var MTX3x3:UInt = 45;
public static inline var MTX4x3:UInt = 46;
public static inline var MTX4x4:UInt = 47;
private var blendModeDic:Vector<BlendMode>;
private var _depthSizeDic:Vector<UInt>;
/**
* Creates a new AWDParser object.
* @param uri The url or id of the data or file to be parsed.
* @param extra The holder for extra contextual data that the parser might need.
*/
public function new()
{
super(ParserDataFormat.BINARY);
blendModeDic = new Vector<BlendMode>(); // used to translate ints to blendMode-strings
blendModeDic.push(BlendMode.NORMAL);
blendModeDic.push(BlendMode.ADD);
blendModeDic.push(BlendMode.ALPHA);
blendModeDic.push(BlendMode.DARKEN);
blendModeDic.push(BlendMode.DIFFERENCE);
blendModeDic.push(BlendMode.ERASE);
blendModeDic.push(BlendMode.HARDLIGHT);
blendModeDic.push(BlendMode.INVERT);
blendModeDic.push(BlendMode.LAYER);
blendModeDic.push(BlendMode.LIGHTEN);
blendModeDic.push(BlendMode.MULTIPLY);
blendModeDic.push(BlendMode.OVERLAY);
blendModeDic.push(BlendMode.SCREEN);
//blendModeDic.push(BlendMode.SHADER);
_depthSizeDic = new Vector<UInt>(); // used to translate ints to depthSize-values
_depthSizeDic.push(256);
_depthSizeDic.push(512);
_depthSizeDic.push(2048);
_depthSizeDic.push(1024);
}
/**
* Indicates whether or not a given file extension is supported by the parser.
* @param extension The file extension of a potential file to be parsed.
* @return Whether or not the given file type is supported.
*/
public static function supportsType(extension:String):Bool
{
extension = extension.toLowerCase();
return extension == "awd";
}
/**
* Tests whether a data block can be parsed by the parser.
* @param data The data block to potentially be parsed.
* @return Whether or not the given data is supported.
*/
public static function supportsData(data:Dynamic):Bool
{
return (ParserUtil.toString(data, 3) == 'AWD');
}
/**
* @inheritDoc
*/
override private function resolveDependency(resourceDependency:ResourceDependency):Void
{
// this function will be called when Dependency has finished loading.
// the Assets waiting for this Bitmap, can be Texture or CubeTexture.
// if the Bitmap is awaited by a CubeTexture, we need to check if its the last Bitmap of the CubeTexture,
// so we know if we have to finalize the Asset (CubeTexture) or not.
if (resourceDependency.assets.length == 1) {
var isCubeTextureArray:Array<String> = resourceDependency.id.split("#");
var ressourceID:String = isCubeTextureArray[0];
var asset:TextureProxyBase;
var thisBitmapTexture:Texture2DBase;
var block:AWDBlock;
if (isCubeTextureArray.length == 1) {
asset = #if (haxe_ver >= 4.2) Std.isOfType #else Std.is #end(resourceDependency.assets[0], Texture2DBase) ? cast resourceDependency.assets[0] : null;
if (asset != null) {
var mat:TextureMaterial;
//var users:Array;
block = _blocks[Std.parseInt(resourceDependency.id)];
block.data = asset; // Store finished asset
// Reset name of texture to the one defined in the AWD file,
// as opposed to whatever the image parser came up with.
asset.resetAssetPath(block.name, null, true);
block.name = asset.name;
// Finalize texture asset to dispatch texture event, which was
// previously suppressed while the dependency was loaded.
finalizeAsset(asset);
if (_debug) {
trace("Successfully loadet Bitmap for texture");
trace("Parsed CubeTexture: Name = " + block.name);
}
}
}
if (isCubeTextureArray.length > 1) {
thisBitmapTexture = cast(resourceDependency.assets[0], BitmapTexture);
_cubeTextures[Std.parseInt(isCubeTextureArray[1])] = cast(thisBitmapTexture, BitmapTexture).bitmapData;
_texture_users[ressourceID].push(1);
if (_debug)
trace("Successfully loadet Bitmap " + _texture_users[ressourceID].length + " / 6 for Cubetexture");
if (_texture_users[ressourceID].length == _cubeTextures.length) {
asset = new BitmapCubeTexture(_cubeTextures[0], _cubeTextures[1], _cubeTextures[2], _cubeTextures[3], _cubeTextures[4], _cubeTextures[5]);
block = _blocks[Std.parseInt(ressourceID)];
block.data = asset; // Store finished asset
// Reset name of texture to the one defined in the AWD file,
// as opposed to whatever the image parser came up with.
asset.resetAssetPath(block.name, null, true);
block.name = asset.name;
// Finalize texture asset to dispatch texture event, which was
// previously suppressed while the dependency was loaded.
finalizeAsset(asset);
if (_debug)
trace("Parsed CubeTexture: Name = " + block.name);
}
}
}
}
/**
* @inheritDoc
*/
override private function resolveDependencyFailure(resourceDependency:ResourceDependency):Void
{
//not used - if a dependcy fails, the awaiting Texture or CubeTexture will never be finalized, and the default-bitmaps will be used.
// this means, that if one Bitmap of a CubeTexture fails, the CubeTexture will have the DefaultTexture applied for all six Bitmaps.
}
/**
* Resolve a dependency name
*
* @param resourceDependency The dependency to be resolved.
*/
override private function resolveDependencyName(resourceDependency:ResourceDependency, asset:IAsset):String
{
var oldName:String = asset.name;
if (asset != null) {
var block:AWDBlock = _blocks[Std.parseInt(resourceDependency.id)];
// Reset name of texture to the one defined in the AWD file,
// as opposed to whatever the image parser came up with.
asset.resetAssetPath(block.name, null, true);
}
var newName:String = asset.name;
asset.name = oldName;
return newName;
}
/**
* @inheritDoc
*/
private override function startParsing(frameLimit:Float):Void
{
super.startParsing(frameLimit);
_texture_users = new Map<String, Array<Int>> ();
_byteData = getByteData();
_blocks = new Vector<AWDBlock>();
_blocks[0] = new AWDBlock();
_blocks[0].data = null; // Zero address means null in AWD
_version = []; // will contain 2 int (major-version, minor-version) for awd-version-check
//parse header
_byteData.endian = Endian.LITTLE_ENDIAN;
// Parse header and decompress body if needed
parseHeader();
switch (_compression) {
case DEFLATE:
_body = new ByteArray();
_byteData.readBytes(_body, 0, _byteData.bytesAvailable);
_body.uncompress();
case LZMA:
_body = new ByteArray();
_byteData.readBytes(_body, 0, _byteData.bytesAvailable);
_body.uncompress(COMPRESSIONMODE_LZMA);
case UNCOMPRESSED:
_body = _byteData;
}
_body.endian = Endian.LITTLE_ENDIAN;
}
/**
* @inheritDoc
*/
override private function proceedParsing():Bool
{
while (_body.bytesAvailable > 0 && !parsingPaused && hasTime())
parseNextBlock();
// Return complete status
if (_body.bytesAvailable == 0)
return ParserBase.PARSING_DONE;
else
return ParserBase.MORE_TO_PARSE;
}
private function parseHeader():Void
{
var flags:UInt;
var body_len:Float;
_byteData.position = 3; // Skip magic string and parse version
_version[0] = _byteData.readUnsignedByte();
_version[1] = _byteData.readUnsignedByte();
flags = _byteData.readUnsignedShort(); // Parse bit flags
_streaming = BitFlags.test(flags, BitFlags.FLAG1);
if ((_version[0] == 2) && (_version[1] == 1)) {
_accuracyMatrix = BitFlags.test(flags, BitFlags.FLAG2);
_accuracyGeo = BitFlags.test(flags, BitFlags.FLAG3);
_accuracyProps = BitFlags.test(flags, BitFlags.FLAG4);
}
// if we set _accuracyOnBlocks, the precision-values are read from each block-header.
// set storagePrecision types
_geoNrType = FLOAT32;
if (_accuracyGeo)
_geoNrType = FLOAT64;
_matrixNrType = FLOAT32;
if (_accuracyMatrix)
_matrixNrType = FLOAT64;
_propsNrType = FLOAT32;
if (_accuracyProps)
_propsNrType = FLOAT64;
_compression = _byteData.readUnsignedByte(); // compression
if (_debug) {
trace("Import AWDFile of version = " + _version[0] + " - " + _version[1]);
trace("Global Settings = Compression = " + _compression + " | Streaming = " + _streaming + " | Matrix-Precision = " + _accuracyMatrix + " | Geometry-Precision = " + _accuracyGeo + " | Properties-Precision = " + _accuracyProps);
}
// Check file integrity
body_len = _byteData.readUnsignedInt();
if (!_streaming && body_len != _byteData.bytesAvailable)
dieWithError('AWD2 body length does not match header integrity field');
}
private function parseNextBlock():Void
{
var block:AWDBlock = null;
var assetData:IAsset = null;
var isParsed:Bool = false;
var ns:UInt, type:UInt, flags:UInt, len:UInt;
_cur_block_id = _body.readUnsignedInt();
ns = _body.readUnsignedByte();
type = _body.readUnsignedByte();
flags = _body.readUnsignedByte();
len = _body.readUnsignedInt();
var blockCompression:Bool = BitFlags.test(flags, BitFlags.FLAG4);
var blockCompressionLZMA:Bool = BitFlags.test(flags, BitFlags.FLAG5);
if (_accuracyOnBlocks) {
_accuracyMatrix = BitFlags.test(flags, BitFlags.FLAG1);
_accuracyGeo = BitFlags.test(flags, BitFlags.FLAG2);
_accuracyProps = BitFlags.test(flags, BitFlags.FLAG3);
_geoNrType = FLOAT32;
if (_accuracyGeo)
_geoNrType = FLOAT64;
_matrixNrType = FLOAT32;
if (_accuracyMatrix)
_matrixNrType = FLOAT64;
_propsNrType = FLOAT32;
if (_accuracyProps)
_propsNrType = FLOAT64;
}
var blockEndAll:UInt = _body.position + len;
if (Std.int(len) > Std.int(_body.bytesAvailable)) {
dieWithError('AWD2 block length is bigger than the bytes that are available!');
_body.position += _body.bytesAvailable;
return;
}
_newBlockBytes = new ByteArray();
_body.readBytes(_newBlockBytes, 0, len);
if (blockCompression) {
if (blockCompressionLZMA)
_newBlockBytes.uncompress(CompressionAlgorithm.LZMA);
else
_newBlockBytes.uncompress();
}
_newBlockBytes.endian = Endian.LITTLE_ENDIAN;
_newBlockBytes.position = 0;
block = new AWDBlock();
block.len = _newBlockBytes.position + len;
block.id = _cur_block_id;
var blockEndBlock:UInt = _newBlockBytes.position + len;
if (blockCompression) {
blockEndBlock = _newBlockBytes.position + _newBlockBytes.length;
block.len = blockEndBlock;
}
if (_debug)
trace("AWDBlock: ID = " + _cur_block_id + " | TypeID = " + type + " | Compression = " + blockCompression + " | Matrix-Precision = " + _accuracyMatrix + " | Geometry-Precision = " + _accuracyGeo + " | Properties-Precision = " + _accuracyProps);
_blocks[_cur_block_id] = block;
if ((_version[0] == 2) && (_version[1] == 1)) {
switch (type) {
case 11:
parsePrimitves(_cur_block_id);
isParsed = true;
case 31:
parseSkyBoxInstance(_cur_block_id);
isParsed = true;
case 41:
parseLight(_cur_block_id);
isParsed = true;
case 42:
parseCamera(_cur_block_id);
isParsed = true;
case 43:
parseTextureProjector(_cur_block_id);
isParsed = true;
case 51:
parseLightPicker(_cur_block_id);
isParsed = true;
case 81:
parseMaterial_v1(_cur_block_id);
isParsed = true;
case 83:
parseCubeTexture(_cur_block_id);
isParsed = true;
case 91:
parseSharedMethodBlock(_cur_block_id);
isParsed = true;
case 92:
parseShadowMethodBlock(_cur_block_id);
isParsed = true;
case 111:
parseMeshPoseAnimation(_cur_block_id, true);
isParsed = true;
case 112:
parseMeshPoseAnimation(_cur_block_id);
isParsed = true;
case 113:
parseVertexAnimationSet(_cur_block_id);
isParsed = true;
case 122:
parseAnimatorSet(_cur_block_id);
isParsed = true;
case 253:
parseCommand(_cur_block_id);
isParsed = true;
}
}
if (isParsed == false) {
switch (type) {
case 1:
parseTriangleGeometrieBlock(_cur_block_id);
case 22:
parseContainer(_cur_block_id);
case 23:
parseMeshInstance(_cur_block_id);
case 81:
parseMaterial(_cur_block_id);
case 82:
parseTexture(_cur_block_id);
case 101:
parseSkeleton(_cur_block_id);
case 102:
parseSkeletonPose(_cur_block_id);
case 103:
parseSkeletonAnimation(_cur_block_id);
case 121:
parseUVAnimation(_cur_block_id);
case 254:
parseNameSpace(_cur_block_id);
case 255:
parseMetaData(_cur_block_id);
default:
if (_debug)
trace("AWDBlock: Unknown BlockType (BlockID = " + _cur_block_id + ") - Skip " + len + " bytes");
_newBlockBytes.position += len;
}
}
var msgCnt:Int = 0;
if (_newBlockBytes.position == blockEndBlock) {
if (_debug) {
if (block.errorMessages != null) {
while (msgCnt < block.errorMessages.length) {
trace(" (!) Error: " + block.errorMessages[msgCnt] + " (!)");
msgCnt++;
}
}
}
if (_debug)
trace("\n");
} else {
if (_debug) {
trace(" (!)(!)(!) Error while reading AWDBlock ID " + _cur_block_id + " = skip to next block");
if (block.errorMessages != null) {
while (msgCnt < block.errorMessages.length) {
trace(" (!) Error: " + block.errorMessages[msgCnt] + " (!)");
msgCnt++;
}
}
}
}
_body.position = blockEndAll;
_newBlockBytes = null;
}
//Block ID = 1
private function parseTriangleGeometrieBlock(blockID:UInt):Void
{
var geom:Geometry = new Geometry();
// Read name and sub count
var name:String = parseVarStr();
var num_subs:Int = _newBlockBytes.readUnsignedShort();
// Read optional properties
var props:AWDProperties = parseProperties({"1":_geoNrType, "2":_geoNrType});
var geoScaleU:Float = props.get(1, 1);
var geoScaleV:Float = props.get(2, 1);
var sub_geoms:Vector<ISubGeometry> = new Vector<ISubGeometry>();
// Loop through sub meshes
var subs_parsed:Int = 0;
while (subs_parsed < num_subs) {
var i:UInt;
var sm_len:UInt, sm_end:UInt;
var w_indices:Vector<Float> = null;
var weights:Vector<Float> = null;
sm_len = _newBlockBytes.readUnsignedInt();
sm_end = _newBlockBytes.position + sm_len;
// Ignore for now
var subProps:AWDProperties = parseProperties({ "1":_geoNrType, "2":_geoNrType });
var verts:Vector<Float> = null;
var indices:Vector<UInt> = null;
var uvs:Vector<Float> = null;
var normals:Vector<Float> = null;
// Loop through data streams
while (_newBlockBytes.position < sm_end) {
var idx:UInt = 0;
var str_ftype:UInt, str_type:UInt, str_len:UInt, str_end:UInt;
// Type, field type, length
str_type = _newBlockBytes.readUnsignedByte();
str_ftype = _newBlockBytes.readUnsignedByte();
str_len = _newBlockBytes.readUnsignedInt();
str_end = _newBlockBytes.position + str_len;
var x:Float, y:Float, z:Float;
if (str_type == 1) {
verts = new Vector<Float>();
while (_newBlockBytes.position < str_end) {
// TODO: Respect stream field type
x = readNumber(_accuracyGeo);
y = readNumber(_accuracyGeo);
z = readNumber(_accuracyGeo);
verts[idx++] = x;
verts[idx++] = y;
verts[idx++] = z;
}
} else if (str_type == 2) {
indices = new Vector<UInt>();
while (_newBlockBytes.position < str_end) {
// TODO: Respect stream field type
indices[idx++] = _newBlockBytes.readUnsignedShort();
}
} else if (str_type == 3) {
uvs = new Vector<Float>();
while (_newBlockBytes.position < str_end)
uvs[idx++] = readNumber(_accuracyGeo);
} else if (str_type == 4) {
normals = new Vector<Float>();
while (_newBlockBytes.position < str_end)
normals[idx++] = readNumber(_accuracyGeo);
} else if (str_type == 6) {
w_indices = new Vector<Float>();
while (_newBlockBytes.position < str_end)
w_indices[idx++] = _newBlockBytes.readUnsignedShort()*3; // TODO: Respect stream field type
} else if (str_type == 7) {
weights = new Vector<Float>();
while (_newBlockBytes.position < str_end)
weights[idx++] = readNumber(_accuracyGeo);
} else
_newBlockBytes.position = str_end;
}
parseUserAttributes(); // Ignore sub-mesh attributes for now
sub_geoms = GeomUtil.fromVectors(verts, indices, uvs, normals, null, weights, w_indices);
var scaleU:Float = subProps.get(1, 1);
var scaleV:Float = subProps.get(2, 1);
var setSubUVs:Bool = false; //this should remain false atm, because in AwayBuilder the uv is only scaled by the geometry
if ((geoScaleU != scaleU) || (geoScaleV != scaleV)) {
trace("set sub uvs");
setSubUVs = true;
scaleU = geoScaleU/scaleU;
scaleV = geoScaleV/scaleV;
}
for (i in 0...sub_geoms.length) {
if (setSubUVs)
sub_geoms[i].scaleUV(scaleU, scaleV);
geom.addSubGeometry(sub_geoms[i]);
// TODO: Somehow map in-sub to out-sub indices to enable look-up
// when creating meshes (and their material assignments.)
}
subs_parsed++;
}
if ((geoScaleU != 1) || (geoScaleV != 1))
geom.scaleUV(geoScaleU, geoScaleV);
parseUserAttributes();
finalizeAsset(geom, name);
_blocks[blockID].data = geom;
if (_debug)
trace("Parsed a TriangleGeometry: Name = " + name + "| SubGeometries = " + sub_geoms.length);
}
//Block ID = 11
private function parsePrimitves(blockID:Int):Void
{
var name:String;
var geom:Geometry;
var primType:Int;
var subs_parsed:Int;
var props:AWDProperties;
var bsm:Matrix3D;
// Read name and sub count
name = parseVarStr();
primType = _newBlockBytes.readUnsignedByte();
props = parseProperties({ "101": _geoNrType, "102": _geoNrType, "103": _geoNrType, "110": _geoNrType, "111": _geoNrType, "301": UINT16, "302": UINT16, "303": UINT16, "701": BOOL, "702": BOOL, "703": BOOL, "704": BOOL});
var primitveTypes:Array<String> = ["Unsupported Type-ID", "PlaneGeometry", "CubeGeometry", "SphereGeometry", "CylinderGeometry", "ConeGeometry", "CapsuleGeometry", "TorusGeometry"];
switch (primType) {
// to do, not all properties are set on all primitives
case 1:
geom = new PlaneGeometry(props.get(101, 100), props.get(102, 100), props.get(301, 1), props.get(302, 1), props.get(701, true), props.get(702, false));
case 2:
geom = new CubeGeometry(props.get(101, 100), props.get(102, 100), props.get(103, 100), props.get(301, 1), props.get(302, 1), props.get(303, 1), props.get(701, true));
case 3:
geom = new SphereGeometry(props.get(101, 50), props.get(301, 16), props.get(302, 12), props.get(701, true));
case 4:
geom = new CylinderGeometry(props.get(101, 50), props.get(102, 50), props.get(103, 100), props.get(301, 16), props.get(302, 1), true, true, true); // bool701, bool702, bool703, bool704);
if (!props.get(701, true))
cast(geom, CylinderGeometry).topClosed = false;
if (!props.get(702, true))
cast(geom, CylinderGeometry).bottomClosed = false;
if (!props.get(703, true))
cast(geom, CylinderGeometry).yUp = false;
case 5:
geom = new ConeGeometry(props.get(101, 50), props.get(102, 100), props.get(301, 16), props.get(302, 1), props.get(701, true), props.get(702, true));
case 6:
geom = new CapsuleGeometry(props.get(101, 50), props.get(102, 100), props.get(301, 16), props.get(302, 15), props.get(701, true));
case 7:
geom = new TorusGeometry(props.get(101, 50), props.get(102, 50), props.get(301, 16), props.get(302, 8), props.get(701, true));
default:
geom = new Geometry();
trace("ERROR: UNSUPPORTED PRIMITIVE_TYPE");
}
if ((props.get(110, 1) != 1) || (props.get(111, 1) != 1)) {
geom.subGeometries;
geom.scaleUV(props.get(110, 1), props.get(111, 1));
}
parseUserAttributes();
geom.name = name;
finalizeAsset(geom, name);
_blocks[blockID].data = geom;
if (_debug) {
if ((primType < 0) || (primType > 7))
primType = 0;
trace("Parsed a Primivite: Name = " + name + "| type = " + primitveTypes[primType]);
}
}
// Block ID = 22
private function parseContainer(blockID:Int):Void
{
var name:String;
var par_id:Int;
var mtx:Matrix3D;
var ctr:ObjectContainer3D;
var parent:ObjectContainer3D;
par_id = _newBlockBytes.readUnsignedInt();
mtx = parseMatrix3D();
name = parseVarStr();
var parentName:String = "Root (TopLevel)";
ctr = new ObjectContainer3D();
ctr.transform = mtx;
var assetVO:AssetVO = getAssetByID(par_id, [Asset3DType.CONTAINER, Asset3DType.LIGHT, Asset3DType.MESH, Asset3DType.ENTITY, Asset3DType.SEGMENT_SET]);
if (assetVO.enable) {
cast(assetVO.data, ObjectContainer3D).addChild(ctr);
parentName = cast(assetVO.data, ObjectContainer3D).name;
} else if (par_id > 0)
_blocks[blockID].addError("Could not find a parent for this ObjectContainer3D");
// in AWD version 2.1 we read the Container properties
if ((_version[0] == 2) && (_version[1] == 1)) {
var props:Dynamic = parseProperties({"1" : _matrixNrType, "2": _matrixNrType, "3": _matrixNrType, "4": UINT8});
ctr.pivotPoint = new Vector3D(props.get(1, 0), props.get(2, 0), props.get(3, 0));
}
// in other versions we do not read the Container properties
else
parseProperties(null);
// the extraProperties should only be set for AWD2.1-Files, but is read for both versions
ctr.extra = parseUserAttributes();
finalizeAsset(ctr, name);
_blocks[blockID].data = ctr;
if (_debug)
trace("Parsed a Container: Name = '" + name + "' | Parent-Name = " + parentName);
}
// Block ID = 23
private function parseMeshInstance(blockID:Int):Void
{
var num_materials:Int;
var materials_parsed:Int;
var parent:ObjectContainer3D;
var par_id:Int = _newBlockBytes.readUnsignedInt();
var mtx:Matrix3D = parseMatrix3D();
var name:String = parseVarStr();
var parentName:String = "Root (TopLevel)";
var data_id:Int = _newBlockBytes.readUnsignedInt();
var geom:Geometry;
var geometryAssetVO:AssetVO = getAssetByID(data_id, [Asset3DType.GEOMETRY]);
if (geometryAssetVO.enable)
geom = cast(geometryAssetVO.data, Geometry);
else {
_blocks[blockID].addError("Could not find a Geometry for this Mesh. A empty Geometry is created!");
geom = new Geometry();
}
_blocks[blockID].geoID = data_id;
var materials:Vector<MaterialBase> = new Vector<MaterialBase>();
num_materials = _newBlockBytes.readUnsignedShort();
var materialNames:Array<String> = new Array<String>();
materials_parsed = 0;
var materialAssetVO:AssetVO;
while (materials_parsed < num_materials) {
var mat_id:Int;
mat_id = _newBlockBytes.readUnsignedInt();
materialAssetVO = getAssetByID(mat_id, [Asset3DType.MATERIAL]);
if (!materialAssetVO.enable && (mat_id > 0))
_blocks[blockID].addError("Could not find Material Nr " + materials_parsed + " (ID = " + mat_id + " ) for this Mesh");
materials.push(cast(materialAssetVO.data, MaterialBase));
materialNames.push(cast(materialAssetVO.data, MaterialBase).name);
materials_parsed++;
}
var mesh:Mesh = new Mesh(geom, null);
mesh.transform = mtx;
var parentAssetVO:AssetVO = getAssetByID(par_id, [Asset3DType.CONTAINER, Asset3DType.LIGHT, Asset3DType.MESH, Asset3DType.ENTITY, Asset3DType.SEGMENT_SET]);
if (parentAssetVO.enable) {
cast(parentAssetVO.data, ObjectContainer3D).addChild(mesh);
parentName = cast(parentAssetVO.data, ObjectContainer3D).name;
} else if (par_id > 0)
_blocks[blockID].addError("Could not find a parent for this Mesh");
if (materials.length >= 1 && mesh.subMeshes.length == 1)
mesh.material = materials[0];
else if (materials.length > 1) {
var i:UInt;
// Assign each sub-mesh in the mesh a material from the list. If more sub-meshes
// than materials, repeat the last material for all remaining sub-meshes.
for (i in 0...mesh.subMeshes.length)
mesh.subMeshes[i].material = materials[Std.int(Math.min(materials.length - 1, i))];
}
if ((_version[0] == 2) && (_version[1] == 1)) {
var props:Dynamic = parseProperties({"1" : _matrixNrType, "2": _matrixNrType, "3": _matrixNrType, "4": UINT8, "5": BOOL});
mesh.pivotPoint = new Vector3D(props.get(1, 0), props.get(2, 0), props.get(3, 0));
mesh.castsShadows = props.get(5, true);
} else
parseProperties(null);
mesh.extra = parseUserAttributes();
finalizeAsset(mesh, name);
_blocks[blockID].data = mesh;
if (_debug)
trace("Parsed a Mesh: Name = '" + name + "' | Parent-Name = " + parentName + "| Geometry-Name = " + geom.name + " | SubMeshes = " + mesh.subMeshes.length + " | Mat-Names = " + materialNames.toString());
}
//Block ID 31
private function parseSkyBoxInstance(blockID:UInt):Void
{
var name:String = parseVarStr();
var cubeTexAddr:UInt = _newBlockBytes.readUnsignedInt();
var cubeTexAssetVO:AssetVO = getAssetByID(cubeTexAddr, [Asset3DType.TEXTURE], "CubeTexture");
if (!cubeTexAssetVO.enable && (cubeTexAddr != 0))
_blocks[blockID].addError("Could not find the Cubetexture (ID = " + cubeTexAddr + " ) for this SkyBox");
var asset:SkyBox = new SkyBox(cast(cubeTexAssetVO.data, BitmapCubeTexture));
parseProperties(null);
asset.extra = parseUserAttributes();
finalizeAsset(asset, name);
_blocks[blockID].data = asset;
if (_debug)
trace("Parsed a SkyBox: Name = '" + name + "' | CubeTexture-Name = " + cast(cubeTexAssetVO.data, BitmapCubeTexture).name);
}
//Block ID = 41
private function parseLight(blockID:UInt):Void
{
var light:LightBase = null;
var newShadowMapper:ShadowMapperBase = null;
var par_id:UInt = _newBlockBytes.readUnsignedInt();
var mtx:Matrix3D = parseMatrix3D();
var name:String = parseVarStr();
var lightType:UInt = _newBlockBytes.readUnsignedByte();
var props:AWDProperties = parseProperties({"1" : _propsNrType, "2": _propsNrType, "3": COLOR, "4": _propsNrType, "5": _propsNrType, "6": BOOL, "7": COLOR, "8": _propsNrType, "9": UINT8, "10": UINT8, "11": _propsNrType, "12": UINT16, "21": _matrixNrType, "22": _matrixNrType, "23": _matrixNrType});
var shadowMapperType:UInt = props.get(9, 0);
var parentName:String = "Root (TopLevel)";
var lightTypes:Array<String> = ["Unsupported LightType", "PointLight", "DirectionalLight"];
var shadowMapperTypes:Array<String> = ["No ShadowMapper", "DirectionalShadowMapper", "NearDirectionalShadowMapper", "CascadeShadowMapper", "CubeMapShadowMapper"];
if (lightType == 1) {
light = new PointLight();
cast(light, PointLight).radius = props.get(1, 90000);
cast(light, PointLight).fallOff = props.get(2, 100000);
if (shadowMapperType > 0) {
if (shadowMapperType == 4)
newShadowMapper = new CubeMapShadowMapper();
}
light.transform = mtx;
}
if (lightType == 2) {
light = new DirectionalLight(props.get(21, 0), props.get(22, -1), props.get(23, 1));
if (shadowMapperType > 0) {
if (shadowMapperType == 1)
newShadowMapper = new DirectionalShadowMapper();
if (shadowMapperType == 2)
newShadowMapper = new NearDirectionalShadowMapper(props.get(11, 0.5));
if (shadowMapperType == 3)
newShadowMapper = new CascadeShadowMapper(props.get(12, 3));
}
}
if ((lightType != 2) && (lightType != 1)){
_blocks[blockID].addError("Unsuported lighttype = "+lightType);
return;
}
light.color = props.get(3, 0xffffff);
light.specular = props.get(4, 1.0);
light.diffuse = props.get(5, 1.0);
light.ambientColor = props.get(7, 0xffffff);
light.ambient = props.get(8, 0.0);
// if a shadowMapper has been created, adjust the depthMapSize if needed, assign to light and set castShadows to true
if (newShadowMapper != null) {
if (#if (haxe_ver >= 4.2) Std.isOfType #else Std.is #end(newShadowMapper, CubeMapShadowMapper)) {
if (props.get(10, 1) != 1)
newShadowMapper.depthMapSize = _depthSizeDic[props.get(10, 1)];
} else {
if (props.get(10, 2) != 2)
newShadowMapper.depthMapSize = _depthSizeDic[props.get(10, 2)];
}
light.shadowMapper = newShadowMapper;
light.castsShadows = true;
}
if (par_id != 0) {
var parentAssetVO:AssetVO = getAssetByID(par_id, [Asset3DType.CONTAINER, Asset3DType.LIGHT, Asset3DType.MESH, Asset3DType.ENTITY, Asset3DType.SEGMENT_SET]);
if (parentAssetVO.enable) {
cast(parentAssetVO.data, ObjectContainer3D).addChild(light);
parentName = cast(parentAssetVO.data, ObjectContainer3D).name;
} else
_blocks[blockID].addError("Could not find a parent for this Light");
}
parseUserAttributes();
finalizeAsset(light, name);
_blocks[blockID].data = light;
if (_debug)
trace("Parsed a Light: Name = '" + name + "' | Type = " + lightTypes[lightType] + " | Parent-Name = " + parentName + " | ShadowMapper-Type = " + shadowMapperTypes[shadowMapperType]);
}
//Block ID = 43
private function parseCamera(blockID:UInt):Void
{
var par_id:UInt = _newBlockBytes.readUnsignedInt();
var mtx:Matrix3D = parseMatrix3D();
var name:String = parseVarStr();
var parentName:String = "Root (TopLevel)";
var lens:LensBase;
_newBlockBytes.readUnsignedByte(); //set as active camera
_newBlockBytes.readShort(); //lengthof lenses - not used yet
var lenstype:UInt = _newBlockBytes.readShort();
var props:AWDProperties = parseProperties({"101": _propsNrType, "102": _propsNrType, "103": _propsNrType, "104": _propsNrType});
switch (lenstype) {
case 5001:
lens = new PerspectiveLens(props.get(101, 60));
case 5002:
lens = new OrthographicLens(props.get(101, 500));
case 5003:
lens = new OrthographicOffCenterLens(props.get(101, -400), props.get(102, 400), props.get(103, -300), props.get(104, 300));
default:
trace("unsupportedLenstype");
return;
}
var camera:Camera3D = new Camera3D(lens);
camera.transform = mtx;
var parentAssetVO:AssetVO = getAssetByID(par_id, [Asset3DType.CONTAINER, Asset3DType.LIGHT, Asset3DType.MESH, Asset3DType.ENTITY, Asset3DType.SEGMENT_SET]);
if (parentAssetVO.enable) {
cast(parentAssetVO.data, ObjectContainer3D).addChild(camera);
parentName = cast(parentAssetVO.data, ObjectContainer3D).name;
} else if (par_id > 0)
_blocks[blockID].addError("Could not find a parent for this Camera");
camera.name = name;
props = parseProperties({"1": _matrixNrType, "2": _matrixNrType, "3": _matrixNrType, "4": UINT8, "101":_propsNrType, "102":_propsNrType});
camera.pivotPoint = new Vector3D(props.get(1, 0), props.get(2, 0), props.get(3, 0));
camera.lens.near = props.get(101, 20);
camera.lens.far = props.get(102, 3000);
camera.extra = parseUserAttributes();
finalizeAsset(camera, name);
_blocks[blockID].data = camera;
if (_debug)
trace("Parsed a Camera: Name = '" + name + "' | Lenstype = " + lens + " | Parent-Name = " + parentName);
}
//Block ID = 43
private function parseTextureProjector(blockID:UInt):Void
{
var par_id:UInt = _newBlockBytes.readUnsignedInt();
var mtx:Matrix3D = parseMatrix3D();
var name:String = parseVarStr();
var parentName:String = "Root (TopLevel)";
var tex_id:UInt = _newBlockBytes.readUnsignedInt();
var geometryAssetVO:AssetVO = getAssetByID(tex_id, [Asset3DType.TEXTURE]);
if (!geometryAssetVO.enable && (tex_id != 0))
_blocks[blockID].addError("Could not find the Texture (ID = " + tex_id + " ( for this TextureProjector!");
var textureProjector:TextureProjector = new TextureProjector(geometryAssetVO.data);
textureProjector.name = name;
textureProjector.aspectRatio = _newBlockBytes.readFloat();
textureProjector.fieldOfView = _newBlockBytes.readFloat();
textureProjector.transform = mtx;
var props:AWDProperties = parseProperties({"1": _matrixNrType, "2": _matrixNrType, "3": _matrixNrType, "4": UINT8});
textureProjector.pivotPoint = new Vector3D(props.get(1, 0), props.get(2, 0), props.get(3, 0));
textureProjector.extra = parseUserAttributes();
finalizeAsset(textureProjector, name);
_blocks[blockID].data = textureProjector;
if (_debug)
trace("Parsed a TextureProjector: Name = '" + name + "' | Texture-Name = " + cast(geometryAssetVO.data, Texture2DBase).name + " | Parent-Name = " + parentName);
}
//Block ID = 51
private function parseLightPicker(blockID:UInt):Void
{
var name:String = parseVarStr();
var numLights:UInt = _newBlockBytes.readUnsignedShort();
var lightsArray:Array<LightBase> = new Array();
var k:Int = 0;
var lightID:Int = 0;
var lightAssetVO:AssetVO;
var lightsArrayNames:Array<String> = new Array();
for (k in 0...numLights) {
lightID = _newBlockBytes.readUnsignedInt();
lightAssetVO = getAssetByID(lightID, [Asset3DType.LIGHT]);
if (lightAssetVO.enable) {
lightsArray.push(cast(lightAssetVO.data, LightBase));
lightsArrayNames.push(cast(lightAssetVO.data, LightBase).name);
} else
_blocks[blockID].addError("Could not find a Light Nr " + k + " (ID = " + lightID + " ) for this LightPicker");
}
if (lightsArray.length == 0) {
_blocks[blockID].addError("Could not create this LightPicker, cause no Light was found.");
parseUserAttributes();
return; //return without any more parsing for this block
}
var lightPick:LightPickerBase = new StaticLightPicker(lightsArray);
lightPick.name = name;
parseUserAttributes();
finalizeAsset(lightPick, name);
_blocks[blockID].data = lightPick;
if (_debug)
trace("Parsed a StaticLightPicker: Name = '" + name + "' | Texture-Name = " + lightsArrayNames.toString());
}