-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathio_alternativa3d_tools.py
9135 lines (7859 loc) · 263 KB
/
io_alternativa3d_tools.py
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
bl_info = {
'name': 'Export: Alternativa3d Tools',
'author': 'David E Jones, http://davidejones.com',
'version': (1, 2, 1),
'blender': (2, 6, 3),
'location': 'File > Import/Export;',
'description': 'Importer and exporter for Alternativa3D engine. Supports A3D and Actionscript"',
'warning': '',
'wiki_url': '',
'tracker_url': 'http://davidejones.com',
'category': 'Import-Export'}
import bpy, os, time, zlib, tempfile, re, shutil
from binascii import hexlify
from struct import unpack, pack, calcsize
from math import atan, atan2
from mathutils import Vector, Matrix, Quaternion
from bpy_extras.io_utils import path_reference,path_reference_copy
from bpy_extras.image_utils import load_image
from bpy.props import *
#==================================
# Common Functions
#==================================
def checkBMesh():
a,b,c = bpy.app.version
return (int(b) >= 63)
def rshift(val, n): return (val % 0x100000000) >> n
def toRgb(RGBint):
Blue = RGBint & 255
Green = (RGBint >> 8) & 255
Red = (RGBint >> 16) & 255
return [Red,Green,Blue]
def fromRgb(Red,Green,Blue):
RGBint = int(Red)
RGBint = (RGBint << 8) + int(Green)
RGBint = (RGBint << 8) + int(Blue)
return RGBint
def rgb2hex(rgb):
#Given a len 3 rgb tuple of 0-1 floats, return the hex string
return '0x%02x%02x%02x' % tuple([round(val*255) for val in rgb])
def rgbtohtmlcolor(rgb):
hexcolor = '#%02x%02x%02x' % rgb
return hexcolor
def cleanupString(input):
output = input
#output = output.replace('.','')
#remove anything that isn't letter number or underscore
reg = re.compile(r'[^A-Za-z0-9_]+')
output = re.sub(reg,"",output)
return output
def ConvertQuadsToTris(obj):
for object in bpy.data.objects:
object.select = False
obj.select = True
bpy.context.scene.objects.active = obj
bpy.ops.object.mode_set(mode="OBJECT", toggle = False)
bpy.ops.object.mode_set(mode="EDIT", toggle = True)
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_all(action='SELECT')
mesh = obj.data
if checkBMesh() == True:
mefdata = mesh.polygons
else:
mefdata = mesh.faces
for f in mefdata:
f.select = True
bpy.ops.mesh.quads_convert_to_tris()
#Return to object mode
bpy.ops.object.mode_set(mode="EDIT", toggle = False)
bpy.ops.object.mode_set(mode="OBJECT", toggle = True)
def copyImages(obj,filepath):
mesh = obj.data
source_dir = bpy.data.filepath
dest_dir = os.path.dirname(filepath)
copy_set = set()
#print("filepath="+str(filepath))
#print("source_dir="+str(source_dir))
#print("dest_dir="+str(dest_dir))
if len(mesh.materials) > 0:
for mat in mesh.materials:
tex = mat.active_texture
if tex is not None:
if "image" in tex:
img = tex.image
rel = path_reference(bpy.path.abspath(img.filepath), source_dir, dest_dir, 'COPY', "", copy_set)
else:
start,end,mts,mats,uvimgs = collectSurfaces(mesh)
#os.path.basename(bpy.path.abspath(uvimgs[x].filepath))
if len(uvimgs) > 0:
for x in range(len(uvimgs)):
if uvimgs[x] != None:
rel = path_reference(bpy.path.abspath(uvimgs[x].filepath), source_dir, dest_dir, 'COPY', "", copy_set)
path_reference_copy(copy_set)
#==================================
# AS EXPORTER
#==================================
class ASExporterSettings:
def __init__(self,A3DVersionSystem=1,CompilerOption=1,ExportMode=1,DocClass=False,CopyImgs=True,ByClass=False,ExportAnim=0,ExportUV=1,ExportNormals=1,ExportTangents=1,ExportUVLayer=2):
self.A3DVersionSystem = int(A3DVersionSystem)
self.CompilerOption = int(CompilerOption)
self.ExportMode = int(ExportMode)
self.DocClass = bool(DocClass)
self.CopyImgs = bool(CopyImgs)
self.ByClass = bool(ByClass)
self.ExportAnim = int(ExportAnim)
self.ExportUV = int(ExportUV)
self.ExportNormals = int(ExportNormals)
self.ExportTangents = int(ExportTangents)
self.ExportUVLayer = int(ExportUVLayer)
class ASExporter(bpy.types.Operator):
bl_idname = "ops.asexporter"
bl_label = "Export to AS (Alternativa)"
bl_description = "Export to AS (Alternativa)"
A3DVersions = []
A3DVersions.append(("1", "5.6.0", ""))
A3DVersions.append(("2", "7.5.0", ""))
A3DVersions.append(("3", "7.5.1", ""))
A3DVersions.append(("4", "7.6.0", ""))
A3DVersions.append(("5", "7.7.0", ""))
A3DVersions.append(("6", "7.8.0", ""))
A3DVersions.append(("7", "8.5.0", ""))
A3DVersions.append(("8", "8.8.0", ""))
A3DVersions.append(("9", "8.12.0", ""))
A3DVersions.append(("10", "8.17.0", ""))
A3DVersions.append(("11", "8.27.0", ""))
A3DVersionSystem = EnumProperty(name="Alternativa3D", description="Select a version of alternativa3D to export to", items=A3DVersions, default="11")
Compilers = []
Compilers.append(("1", "Flex", ""))
Compilers.append(("2", "Flash", ""))
CompilerOption = EnumProperty(name="Use With", description="Select the compiler you will be using", items=Compilers, default="1")
ExportModes = []
ExportModes.append(("1", "Selected Objects", ""))
ExportModes.append(("2", "All Objects", ""))
ExportMode = EnumProperty(name="Export", description="Select which objects to export", items=ExportModes, default="1")
DocClass = BoolProperty(name="Create Document Class", description="Create document class that makes use of exported data", default=False)
CopyImgs = BoolProperty(name="Copy Images", description="Copy images to destination folder of export", default=True)
ByClass = BoolProperty(name="Use ByteArray Data (v8.27+)", description="Exports mesh data to compressed bytearray in as3", default=False)
#ExportAnim = BoolProperty(name="Animation", description="Animation", default=False)
ExportUV = BoolProperty(name="Include UVs", description="Normals", default=True)
ExportNormals = BoolProperty(name="Include Normals", description="Normals", default=True)
ExportTangents = BoolProperty(name="Include Tangents", description="Tangents", default=True)
ExportUVLayers = []
ExportUVLayers.append(("1", "Active UV Layer Only", ""))
ExportUVLayers.append(("2", "All UV Layers", ""))
ExportUVLayer = EnumProperty(name="UV Layers", description="Select which UV Layers to export", items=ExportUVLayers, default="2")
filepath = bpy.props.StringProperty()
def execute(self, context):
filePath = self.properties.filepath
fp = self.properties.filepath
if not filePath.lower().endswith('.as'):
filePath += '.as'
try:
time1 = time.clock()
print('Output file : %s' %filePath)
file = open(filePath, 'w')
Config = ASExporterSettings(A3DVersionSystem=self.A3DVersionSystem,CompilerOption=self.CompilerOption,ExportMode=self.ExportMode, DocClass=self.DocClass,CopyImgs=self.CopyImgs,ByClass=self.ByClass,ExportAnim=False,ExportUV=self.ExportUV,ExportNormals=self.ExportNormals,ExportTangents=self.ExportTangents,ExportUVLayer=self.ExportUVLayer)
ASExport(file,Config,fp)
file.close()
print(".as export time: %.2f" % (time.clock() - time1))
except Exception as e:
print(e)
file.close()
return {'FINISHED'}
def invoke (self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
def ASExport(file,Config,fp):
print('Export to Alternativa3d Class started...\n')
WritePackageHeader(file,Config)
if Config.ExportMode == 1:
#get selected objects that are mesh
objs = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']
print('Export selection only...\n')
else:
#get all objects that are mesh
objs = [obj for obj in bpy.data.objects if obj.type == 'MESH']
print('Export all meshes...\n')
aobjs = []
for obj in objs:
ConvertQuadsToTris(obj)
if "a3dtype" in obj:
aobjs.append(obj)
else:
if (Config.A3DVersionSystem == 7) or (Config.A3DVersionSystem == 8) or (Config.A3DVersionSystem == 9) or (Config.A3DVersionSystem == 10) or (Config.A3DVersionSystem == 11):
# version 8.5.0, 8.8.0, 8.12.0, 8.17.0, 8.27.0
WriteClass8270(file,obj,Config)
elif (Config.A3DVersionSystem == 4) or (Config.A3DVersionSystem == 5) or (Config.A3DVersionSystem == 6):
# version 7.6.0, 7.7.0, 7.8.0
WriteClass78(file,obj,Config)
elif (Config.A3DVersionSystem == 2) or (Config.A3DVersionSystem == 3):
# version 7.5.0, 7.5.1
WriteClass75(file,obj,Config)
elif Config.A3DVersionSystem == 1:
# version 5.6.0
WriteClass5(file,obj,Config)
else:
print("No Alternativa Version\n")
if Config.CopyImgs:
print("copy images...\n")
copyImages(obj,fp)
WritePackageEnd(file)
if Config.DocClass:
WriteDocuClass(file,objs,aobjs,Config,fp)
print('Export Completed...\n')
def WritePackageHeader(file,Config):
file.write("//Alternativa3D Class Export For Blender 2.62 and above\n")
file.write("//Plugin Author: David E Jones, http://davidejones.com\n\n")
file.write("package {\n\n")
if Config.A3DVersionSystem == 1:
# version 5.6.0
file.write("\timport alternativa.engine3d.core.Mesh;\n")
file.write("\timport alternativa.engine3d.materials.FillMaterial;\n")
file.write("\timport alternativa.engine3d.materials.TextureMaterial;\n")
file.write("\timport alternativa.types.Texture;\n")
file.write("\timport alternativa.types.Matrix3D;\n")
file.write("\timport alternativa.types.Point3D;\n")
file.write("\timport flash.display.BlendMode;\n")
file.write("\timport flash.geom.Point;\n")
file.write("\timport flash.display.Bitmap;\n\n")
elif (Config.A3DVersionSystem == 2) or (Config.A3DVersionSystem == 3):
# version 7.5.0, 7.5.1
file.write("\timport alternativa.engine3d.objects.Mesh;\n")
file.write("\timport alternativa.engine3d.materials.FillMaterial;\n")
file.write("\timport alternativa.engine3d.materials.TextureMaterial;\n")
file.write("\timport alternativa.engine3d.core.Vertex;\n")
file.write("\timport alternativa.engine3d.core.Geometry;\n")
file.write("\timport __AS3__.vec.Vector;\n")
file.write("\timport flash.display.Bitmap;\n\n")
elif (Config.A3DVersionSystem == 4) or (Config.A3DVersionSystem == 5) or (Config.A3DVersionSystem == 6):
# version 7.6.0, 7.7.0, 7.8.0
file.write("\timport alternativa.engine3d.objects.Mesh;\n")
file.write("\timport alternativa.engine3d.materials.FillMaterial;\n")
file.write("\timport alternativa.engine3d.materials.TextureMaterial;\n")
file.write("\timport alternativa.engine3d.core.Vertex;\n")
file.write("\timport __AS3__.vec.Vector;\n")
file.write("\timport flash.display.Bitmap;\n\n")
elif (Config.A3DVersionSystem == 7) or (Config.A3DVersionSystem == 8) or (Config.A3DVersionSystem == 9) or (Config.A3DVersionSystem == 10) or (Config.A3DVersionSystem == 11):
# version 8.5.0, 8.8.0, 8.12.0, 8.17.0, 8.27.0
file.write("\timport alternativa.engine3d.core.VertexAttributes;\n")
file.write("\timport alternativa.engine3d.core.BoundBox;\n")
file.write("\timport alternativa.engine3d.materials.FillMaterial;\n")
file.write("\timport alternativa.engine3d.materials.TextureMaterial;\n")
file.write("\timport alternativa.engine3d.resources.BitmapTextureResource;\n")
file.write("\timport alternativa.engine3d.objects.Mesh;\n")
file.write("\timport alternativa.engine3d.resources.Geometry;\n")
file.write("\timport __AS3__.vec.Vector;\n")
file.write("\timport flash.display.Bitmap;\n")
if Config.ByClass == 1:
file.write("\timport flash.utils.ByteArray;\n")
file.write("\timport flash.utils.Endian;\n")
file.write("\n")
else:
print("version not found")
def WriteDocPackageHeader(file,Config):
file.write("//Alternativa3D Class Export For Blender 2.62 and above\n")
file.write("//Plugin Author: David E Jones, http://davidejones.com\n\n")
file.write("package {\n\n")
if Config.A3DVersionSystem == 1:
# version 5.6.0
file.write("\timport alternativa.engine3d.controllers.CameraController;\n")
file.write("\timport alternativa.engine3d.core.Scene3D;\n")
file.write("\timport alternativa.engine3d.core.Object3D;\n")
file.write("\timport alternativa.engine3d.core.Camera3D;\n")
file.write("\timport alternativa.engine3d.display.View;\n")
file.write("\timport alternativa.utils.MathUtils;\n")
file.write("\timport alternativa.utils.FPS;\n")
file.write("\timport alternativa.types.Point3D;\n")
file.write("\timport flash.display.Sprite;\n")
file.write("\timport flash.display.StageAlign;\n")
file.write("\timport flash.display.StageScaleMode;\n")
file.write("\timport flash.events.Event;\n")
elif (Config.A3DVersionSystem == 2) or (Config.A3DVersionSystem == 3) or (Config.A3DVersionSystem == 4) or (Config.A3DVersionSystem == 5) or (Config.A3DVersionSystem == 6):
# version 7.5.0, 7.5.1, 7.6.0, 7.7.0, 7.8.0
file.write("\timport alternativa.engine3d.core.Camera3D;\n")
file.write("\timport alternativa.engine3d.core.Object3DContainer;\n")
file.write("\timport alternativa.engine3d.core.View;\n")
file.write("\timport alternativa.engine3d.controllers.SimpleObjectController;\n")
file.write("\timport flash.display.Sprite;\n")
file.write("\timport flash.display.StageAlign;\n")
file.write("\timport flash.display.StageScaleMode;\n")
file.write("\timport flash.events.Event;\n")
file.write("\timport flash.geom.Vector3D;\n")
elif (Config.A3DVersionSystem == 7) or (Config.A3DVersionSystem == 8) or (Config.A3DVersionSystem == 9) or (Config.A3DVersionSystem == 10) or (Config.A3DVersionSystem == 11):
# version 8.5.0, 8.8.0, 8.12.0, 8.17.0, 8.27.0
file.write("\timport alternativa.engine3d.core.Camera3D;\n")
file.write("\timport alternativa.engine3d.core.Object3D;\n")
file.write("\timport alternativa.engine3d.core.Resource;\n")
file.write("\timport alternativa.engine3d.core.View;\n")
file.write("\timport alternativa.engine3d.materials.FillMaterial;\n")
file.write("\timport alternativa.engine3d.controllers.SimpleObjectController;\n")
file.write("\timport flash.display.Sprite;\n")
file.write("\timport flash.display.Stage3D;\n")
file.write("\timport flash.display.StageAlign;\n")
file.write("\timport flash.display.StageScaleMode;\n")
file.write("\timport flash.events.Event;\n")
file.write("\timport flash.geom.Vector3D;\n")
else:
print("version not found")
file.write('\n\t[SWF(backgroundColor="#000000", frameRate="100", width="800", height="600")]\n\n')
def WritePackageEnd(file):
file.write("}")
def setupMaterials(file,obj,Config):
mesh = obj.data
verts = mesh.vertices
mati = {}
Materials = mesh.materials
if Materials.keys():
MaterialIndexes = {}
if checkBMesh() == True:
for Face in mesh.polygons:
if Materials[Face.material_index] not in MaterialIndexes:
MaterialIndexes[Materials[Face.material_index]] = len(MaterialIndexes)
else:
for Face in mesh.faces:
if Materials[Face.material_index] not in MaterialIndexes:
MaterialIndexes[Materials[Face.material_index]] = len(MaterialIndexes)
Materials = [Item[::-1] for Item in MaterialIndexes.items()]
Materials.sort()
x=0
for Material in Materials:
mati[x] = cleanupString(str(Material[1].name))
WriteMaterial(file,mati[x],Config, Material[1])
x += 1
return mati
def WriteMaterial(file,id,Config,Material=None):
if Material:
nme = cleanupString(str(Material.name))
Texture = GetMaterialTexture(Material)
if Texture:
# if version 5.6.0
if Config.A3DVersionSystem == 1:
#if flex
if Config.CompilerOption == 1:
file.write('\t\t[Embed(source="'+str(Texture)+'")] private static const bmp'+str(nme)+':Class;\n')
file.write('\t\tprivate static const '+str(id)+':TextureMaterial = new TextureMaterial(new Texture(new bmp'+str(nme)+'().bitmapData, "'+str(nme)+'"));\n\n')
else:
file.write("\t\t//"+str(Texture)+"\n")
file.write("\t\tprivate var bmp"+str(nme)+":Bitmap = new Bitmap(new bd"+str(nme)+"(0,0));\n")
file.write('\t\tprivate var '+str(id)+':TextureMaterial = new TextureMaterial(new Texture(new bmp'+str(nme)+'().bitmapData, "'+str(nme)+'"));\n\n')
#if version 7.5.0, 7.5.1, 7.6.0, 7.7.0, 7.8.0
elif (Config.A3DVersionSystem == 2) or (Config.A3DVersionSystem == 3) or (Config.A3DVersionSystem == 4) or (Config.A3DVersionSystem == 5) or (Config.A3DVersionSystem == 6):
#if flex
if Config.CompilerOption == 1:
file.write('\t\t[Embed(source="'+str(Texture)+'")] private static const bmp'+str(nme)+':Class;\n')
file.write('\t\tprivate static const '+str(id)+':TextureMaterial = new TextureMaterial(new bmp'+str(nme)+'().bitmapData, true, true);\n\n')
else:
file.write("\t\t//"+str(Texture)+"\n")
file.write("\t\tprivate var bmp"+str(nme)+":Bitmap = new Bitmap(new bd"+str(nme)+"(0,0));\n")
file.write("\t\tprivate var "+str(id)+":TextureMaterial = new TextureMaterial(bmp"+str(nme)+".bitmapData, true, true);\n\n")
#if version 8.5.0, 8.8.0, 8.12.0, 8.17.0, 8.27.0
elif (Config.A3DVersionSystem == 7) or (Config.A3DVersionSystem == 8) or (Config.A3DVersionSystem == 9) or (Config.A3DVersionSystem == 10) or (Config.A3DVersionSystem == 11):
#if flex
if Config.CompilerOption == 1:
file.write('\t\t[Embed(source="'+str(Texture)+'")] private static const bmp'+str(nme)+':Class;\n')
file.write('\t\tprivate static const '+str(id)+':TextureMaterial = new TextureMaterial(new BitmapTextureResource(new bmp'+str(nme)+'().bitmapData));\n\n')
else:
file.write("\t\t//"+str(Texture)+"\n")
file.write("\t\tprivate var bmp"+str(nme)+":Bitmap = new Bitmap(new bd"+str(nme)+"(0,0));\n")
file.write("\t\tprivate var "+str(id)+":TextureMaterial = new TextureMaterial(new BitmapTextureResource(bmp"+str(nme)+".bitmapData));\n\n")
else:
print("version not found")
else:
#no tex maybe vertex colour?
Diffuse = list(Material.diffuse_color)
Diffuse.append(Material.alpha)
Specularity = Material.specular_intensity
Specular = list(Material.specular_color)
file.write('\t\tprivate var '+id+':FillMaterial = new FillMaterial('+rgb2hex((Diffuse[0], Diffuse[1], Diffuse[2]))+');\n\n')
def GetMaterialTexture(Material):
img_files = []
if Material:
# Create a list of Textures that have type "IMAGE"
ImageTextures = [Material.texture_slots[TextureSlot].texture for TextureSlot in Material.texture_slots.keys() if Material.texture_slots[TextureSlot].texture.type == "IMAGE"]
# Refine a new list with only image textures that have a file source.
for Texture in ImageTextures:
if Texture.image and Texture.image.source == "FILE":
if Texture.image.filepath:
img_files.append(os.path.basename(Texture.image.filepath))
return img_files[0] if len(img_files) > 0 else None
def writeByteArrayValues(file,verts,uvlayers,indices):
file.write("\t\t\tvalues= new <uint>[")
tfile = tempfile.TemporaryFile(mode ='w+b')
#length of verts -short
tfile.write(pack("<H", len(verts)*3))
for v in verts:
tfile.write(pack("<f", v[0]))
tfile.write(pack("<f", v[1]))
tfile.write(pack("<f", v[2]))
#length of uvts -short
for uvname, uvdata in uvlayers.items():
uvt = uvdata[0]
tfile.write(pack("<H", len(uvt)*2))
for uv in uvt:
tfile.write(pack("<f", uv[0]))
tfile.write(pack("<f", uv[1]))
#length of indices -short
tfile.write(pack("<H", len(indices)))
for i in indices:
tfile.write(pack("<I", i))
tfile.seek(0)
indata = tfile.read()
outdata = zlib.compress(indata)
tfile.close()
tfile = tempfile.TemporaryFile(mode ='w+b')
tfile.write(outdata)
tfile.seek(0)
try:
byte = tfile.read(1)
while byte != "":
if len(byte) > 0:
#file.write("%X," % int(byte))
file.write("0x%X," % unpack('B', byte))
byte = tfile.read(1)
else:
break
finally:
tfile.close()
file.write("];\n")
def getCommonData(Config,obj,flipUV=1):
mesh = obj.data
verts = mesh.vertices
Materials = mesh.materials
hasFaceUV = len(mesh.uv_textures) > 0
vs,uvt,ins,nr,tan,bb,trns = [],[],[],[],[],[],[]
vertices_list = []
vertices_co_list = []
vertices_index_list = []
normals_list = []
uv_coord_list = []
new_index = 0
uvtex = mesh.uv_textures.active
uvlayers={}
uvprocess=True
if hasFaceUV:
#update tessface cache or there is no data
mesh.update(calc_edges=True, calc_tessface=True)
#add active layer first?
#uvlayer = mesh.tessface_uv_textures.active
y=0
uc = 0
for uvlayer in mesh.tessface_uv_textures:
if Config.ExportUVLayer != None:
if Config.ExportUVLayer == 1:
uvprocess=uvlayer.active
elif Config.ExportUVLayer == 2:
uvprocess=True
else:
uvprocess=True
if uvprocess == True:
uv_coord_list = []
uvlayername = uvlayer.name
uvlayers[uvlayername] = []
#for face in uvlayer.data:
#for uv_index in range(len(mesh.polygons)):
for uv_index in range(len(mesh.tessfaces)):
#tmplist = [face.uv,face.image]
#uvlayers[uvlayername].append(tmplist)
face = uvlayer.data[uv_index]
#face = mesh.uv_textures.active.data[uv_index]
uvs = face.uv1, face.uv2, face.uv3, face.uv4
#for vertex_index, vertex_itself in enumerate(mesh.polygons[uv_index].vertices):
for vertex_index, vertex_itself in enumerate(mesh.tessfaces[uv_index].vertices):
uv_coord_list.append(uvs[vertex_index])
if flipUV == 1:
uv = [uv_coord_list[-1][0], 1.0 - uv_coord_list[-1][1]]
else:
uv = [uv_coord_list[-1][0], uv_coord_list[-1][1]]
uvt.append(uv)
y=y+1
#tmplist = [uvt,face.image]
uvlayers[uvlayername].append(uvt)
uvt = []
uc=uc+1
uvtex = mesh.uv_layers[0]
uv_layer = mesh.uv_layers[0]
#for uv_index in range(len(mesh.polygons)):
for uv_index in range(len(mesh.tessfaces)):
#for vertex_index, vertex_itself in enumerate(mesh.polygons[uv_index].vertices):
for vertex_index, vertex_itself in enumerate(mesh.tessfaces[uv_index].vertices):
vertex = mesh.vertices[vertex_itself]
vertices_list.append(vertex_itself)
vertices_co_list.append(vertex.co.xyz)
normals_list.append(vertex.normal.xyz)
vertices_index_list.append(new_index)
new_index += 1
vs.append([vertices_co_list[-1][0],vertices_co_list[-1][1],vertices_co_list[-1][2]])
#if mesh.polygons[uv_index].use_smooth:
if mesh.tessfaces[uv_index].use_smooth:
nr.append([normals_list[-1][0],normals_list[-1][1],normals_list[-1][2]])
else:
#nr.append(mesh.polygons[uv_index].normal)
nr.append(mesh.tessfaces[uv_index].normal)
ins.append(vertices_index_list[-1])
else:
# if there are no image textures, output the old way
#for face in mesh.polygons:
for face in mesh.tessfaces:
if len(face.vertices) > 0:
ins.append(face.vertices[0])
ins.append(face.vertices[1])
ins.append(face.vertices[2])
#nr.append([[face.normal[0],face.normal[1],face.normal[2]]])
for v in mesh.vertices:
vs.append([v.co[0],v.co[1],v.co[2]])
nr.append([v.normal[0],v.normal[1],v.normal[2]])
if (len(uvlayers) > 0) and (len(nr) > 0):
tan = calculateTangents(ins,vs,uv_coord_list,nr)
bb = getBoundBox(obj)
trns = getObjTransform(obj)
return vs,uvlayers,ins,nr,tan,bb,trns
def getCommonDataNoBmesh(Config,obj,flipUV=1):
mesh = obj.data
verts = mesh.vertices
Materials = mesh.materials
hasFaceUV = len(mesh.uv_textures) > 0
vs,uvt,ins,nr,tan,bb,trns = [],[],[],[],[],[],[]
vertices_list = []
vertices_co_list = []
vertices_index_list = []
normals_list = []
uv_coord_list = []
new_index = 0
uvtex = mesh.uv_textures.active
uvlayers={}
uvprocess=True
if hasFaceUV:
y=0
uc=0
for uvlayer in mesh.uv_textures:
if Config.ExportUVLayer != None:
if Config.ExportUVLayer == 1:
if uc > 0:
uvprocess=False
elif Config.ExportUVLayer == 2:
uvprocess=True
else:
uvprocess=True
if uvprocess == True:
uv_coord_list = []
uvlayername = uvlayer.name
uvlayers[uvlayername] = []
#for face in uvlayer.data:
for uv_index in range(len(mesh.faces)):
#tmplist = [face.uv,face.image]
#uvlayers[uvlayername].append(tmplist)
face = uvlayer.data[uv_index]
uvs = face.uv1, face.uv2, face.uv3, face.uv4
for vertex_index, vertex_itself in enumerate(mesh.faces[uv_index].vertices):
uv_coord_list.append(uvs[vertex_index])
if flipUV == 1:
uv = [uv_coord_list[-1][0], 1.0 - uv_coord_list[-1][1]]
else:
uv = [uv_coord_list[-1][0], uv_coord_list[-1][1]]
uvt.append(uv)
y=y+1
#tmplist = [uvt,face.image]
uvlayers[uvlayername].append(uvt)
uvt = []
uc=uc+1
for uv_index, uv_itself in enumerate(uvtex.data):
for vertex_index, vertex_itself in enumerate(mesh.faces[uv_index].vertices):
vertex = mesh.vertices[vertex_itself]
vertices_list.append(vertex_itself)
vertices_co_list.append(vertex.co.xyz)
normals_list.append(vertex.normal.xyz)
vertices_index_list.append(new_index)
new_index += 1
vs.append([vertices_co_list[-1][0],vertices_co_list[-1][1],vertices_co_list[-1][2]])
if mesh.faces[uv_index].use_smooth:
nr.append([normals_list[-1][0],normals_list[-1][1],normals_list[-1][2]])
else:
nr.append(mesh.faces[uv_index].normal)
ins.append(vertices_index_list[-1])
else:
# if there are no image textures, output the old way
for face in mesh.faces:
if len(face.vertices) > 0:
ins.append(face.vertices[0])
ins.append(face.vertices[1])
ins.append(face.vertices[2])
#nr.append([[face.normal[0],face.normal[1],face.normal[2]]])
for i in range(len(face.vertices)):
#if face.use_smooth:
# v = mesh.vertices[face.vertices[i]]
# nr.append([v.normal[0],v.normal[1],v.normal[2]])
#else:
# nr.append(face.normal)
hasFaceUV = len(mesh.uv_textures) > 0
if hasFaceUV:
uv = [mesh.uv_textures.active.data[face.index].uv[i][0], mesh.uv_textures.active.data[face.index].uv[i][1]]
uv[1] = 1.0 - uv[1] # should we flip Y? yes, new in Blender 2.5x
uvt.append(uv)
for v in mesh.vertices:
vs.append([v.co[0],v.co[1],v.co[2]])
nr.append([v.normal[0],v.normal[1],v.normal[2]])
#if we have uv's and normals then calculate tangents
if (len(uvlayers) > 0) and (len(nr) > 0):
tan = calculateTangents(ins,vs,uv_coord_list,nr)
#get bound box
bb = getBoundBox(obj)
trns = getObjTransform(obj)
return vs,uvlayers,ins,nr,tan,bb,trns
def getObjTransform(obj):
trns = []
c=0
j=0
for x in obj.matrix_local:
j=0
for y in x:
if j == 3 and c != 3:
trns.append(obj.location[c])
#t = obj.matrix_local.translation()
#trns.append(t[c])
else:
trns.append(y)
j=j+1
c=c+1
return trns
def getObjWorldTransform(obj):
trns = []
c=0
j=0
for x in obj.matrix_world:
j=0
for y in x:
if j == 3 and c != 3:
trns.append(obj.location[c])
else:
trns.append(y)
j=j+1
c=c+1
return trns
def calculateTangents(ins,verts,uvs,nrms):
# based on alternativas code here
# https://github.com/AlternativaPlatform/Alternativa3D/blob/master/src/alternativa/engine3d/resources/Geometry.as
tangents = []
x=0
numIndices = len(ins)
#print("numIndices="+str(numIndices))
#print("verts="+str(len(verts)))
#print("uvs="+str(len(uvs)))
#print("normals="+str(len(nrms)))
for i in range(numIndices):
if i >= numIndices/3:
break
vertIndexA = ins[x]
vertIndexB = ins[x + 1]
vertIndexC = ins[x + 2]
#vertex1
ax = verts[x][0]
ay = verts[x][1]
az = verts[x][2]
#vertex2
bx = verts[x + 1][0]
by = verts[x + 1][1]
bz = verts[x + 1][2]
#vertex3
cx = verts[x + 2][0]
cy = verts[x + 2][1]
cz = verts[x + 2][2]
#uv
au = uvs[x][0]
av = uvs[x][1]
#uv
bu = uvs[x + 1][0]
bv = uvs[x + 1][1]
#uv
cu = uvs[x + 2][0]
cv = uvs[x + 2][1]
#nrm
anx = nrms[x][0]
any = nrms[x][1]
anz = nrms[x][2]
#nrm
bnx = nrms[x + 1][0]
bny = nrms[x + 1][1]
bnz = nrms[x + 1][2]
#nrm
cnx = nrms[x + 2][0]
cny = nrms[x + 2][1]
cnz = nrms[x + 2][2]
# v2-v1
abx = bx - ax
aby = by - ay
abz = bz - az
# v3-v1
acx = cx - ax
acy = cy - ay
acz = cz - az
abu = bu - au
abv = bv - av
acu = cu - au
acv = cv - av
divisor = (abu*acv - acu*abv)
if divisor == 0: divisor = 0.01 #prevent 0 div. error
r = 1.0/divisor
tangentX = r*(acv*abx - acx*abv)
tangentY = r*(acv*aby - abv*acy)
tangentZ = r*(acv*abz - abv*acz)
if vertIndexA in tangents:
#exists
#print("va exists")
tangent = tangents[vertIndexA]
tangent.x += tangentX - anx*(anx*tangentX + any*tangentY + anz*tangentZ)
tangent.y += tangentY - any*(anx*tangentX + any*tangentY + anz*tangentZ)
tangent.z += tangentZ - anz*(anx*tangentX + any*tangentY + anz*tangentZ)
else:
#doesn't exist
#print("va doesn't exist")
#tangents[vertIndexA]
tangents.append(Vector((tangentX - anx*(anx*tangentX + any*tangentY + anz*tangentZ),tangentY - any*(anx*tangentX + any*tangentY + anz*tangentZ),tangentZ - anz*(anx*tangentX + any*tangentY + anz*tangentZ))))
if vertIndexB in tangents:
#exists
#print("vb exists")
tangent = tangents[vertIndexB]
tangent.x += tangentX - bnx*(bnx*tangentX + bny*tangentY + bnz*tangentZ)
tangent.y += tangentY - bny*(bnx*tangentX + bny*tangentY + bnz*tangentZ)
tangent.z += tangentZ - bnz*(bnx*tangentX + bny*tangentY + bnz*tangentZ)
else:
#doesn't exist
#print("vb doesn't exist")
#tangents[vertIndexB]
tangents.append(Vector((tangentX - bnx*(bnx*tangentX + bny*tangentY + bnz*tangentZ),tangentY - bny*(bnx*tangentX + bny*tangentY + bnz*tangentZ),tangentZ - bnz*(bnx*tangentX + bny*tangentY + bnz*tangentZ))))
if vertIndexC in tangents:
#exists
#print("vc exists")
tangent = tangents[vertIndexC]
tangent.x += tangentX - cnx*(cnx*tangentX + cny*tangentY + cnz*tangentZ)
tangent.y += tangentY - cny*(cnx*tangentX + cny*tangentY + cnz*tangentZ)
tangent.z += tangentZ - cnz*(cnx*tangentX + cny*tangentY + cnz*tangentZ)
else:
#doesn't exist
#print("vc doesn't exist")
#tangents[vertIndexC]
tangents.append(Vector((tangentX - cnx*(cnx*tangentX + cny*tangentY + cnz*tangentZ),tangentY - cny*(cnx*tangentX + cny*tangentY + cnz*tangentZ),tangentZ - cnz*(cnx*tangentX + cny*tangentY + cnz*tangentZ))))
#Calculate handedness
x = x + 3
#normalize
for tan in tangents:
tan.normalize()
return tangents
def getBoundBox(obj):
#v = [list(bb) for bb in obj.bound_box]
#bmin = min(v)
#bmax = max(v)
#minx = max(bmin[0] * obj.scale.x, -1e10)
#miny = max(bmin[1] * obj.scale.y, -1e10)
#minz = max(bmin[2] * obj.scale.z, -1e10)
#maxx = min(bmax[0] * obj.scale.x, 1e10)
#maxy = min(bmax[1] * obj.scale.y, 1e10)
#maxz = min(bmax[2] * obj.scale.z, 1e10)
#return [minx,miny,minz,maxx,maxy,maxz]
d = obj.bound_box
#return Vec((d[0])), Vec((d[6]))
return [d[0][0],d[0][1],d[0][2],d[6][0],d[6][1],d[6][2]]
def writeTransform(file,obj,Config):
mesh = obj.data
loc, rot, sca = obj.matrix_local.decompose()
rot1 = rot.to_euler()
mtrx = obj.matrix_local
file.write("\n")
file.write("\t\t\tthis.x = %f;\n" % loc.x)
file.write("\t\t\tthis.y = %f;\n" % loc.y)
file.write("\t\t\tthis.z = %f;\n" % loc.z)
file.write("\t\t\tthis.rotationX = %f;\n" % rot1.x)
file.write("\t\t\tthis.rotationY = %f;\n" % rot1.y)
file.write("\t\t\tthis.rotationZ = %f;\n" % rot1.z)
file.write("\t\t\tthis.scaleX = %f;\n" % sca.x)
file.write("\t\t\tthis.scaleY = %f;\n" % sca.y)
file.write("\t\t\tthis.scaleZ = %f;\n" % sca.z)
def writeBoundBox(file,bb,Config):
file.write("\n")
if Config.A3DVersionSystem == 1:
# version 5.6.0
print("no boundbox for v5")
elif (Config.A3DVersionSystem == 2) or (Config.A3DVersionSystem == 3) or (Config.A3DVersionSystem == 4) or (Config.A3DVersionSystem == 5) or (Config.A3DVersionSystem == 6):
# version 7.5.0, 7.5.1, 7.6.0, 7.7.0, 7.8.0
file.write("\t\t\tthis.boundMaxX = %f;\n" % bb[0])
file.write("\t\t\tthis.boundMaxY = %f;\n" % bb[1])
file.write("\t\t\tthis.boundMaxZ = %f;\n" % bb[2])
file.write("\t\t\tthis.boundMinX = %f;\n" % bb[3])
file.write("\t\t\tthis.boundMinY = %f;\n" % bb[4])
file.write("\t\t\tthis.boundMinZ = %f;\n" % bb[5])
elif (Config.A3DVersionSystem == 7) or (Config.A3DVersionSystem == 8) or (Config.A3DVersionSystem == 9) or (Config.A3DVersionSystem == 10) or (Config.A3DVersionSystem == 11):
# version 8.5.0, 8.8.0, 8.12.0, 8.17.0, 8.27.0
file.write("\t\t\tvar bb:BoundBox = new BoundBox();\n")
file.write("\t\t\tbb.maxX = %f;\n" % bb[0])
file.write("\t\t\tbb.maxY = %f;\n" % bb[1])
file.write("\t\t\tbb.maxZ = %f;\n" % bb[2])
file.write("\t\t\tbb.minX = %f;\n" % bb[3])
file.write("\t\t\tbb.minY = %f;\n" % bb[4])
file.write("\t\t\tbb.minZ = %f;\n" % bb[5])
file.write("\t\t\tthis.boundBox = bb;\n")
else:
print("version not found")
def WriteClass8270(file,obj,Config):
mesh = obj.data
verts = mesh.vertices
Materials = mesh.materials
hasFaceUV = len(mesh.uv_textures) > 0
file.write("\tpublic class "+obj.data.name+" extends Mesh {\n\n")
mati = setupMaterials(file,obj,Config)
if checkBMesh() == True:
vs,uvlayers,ins,nr,tan,bb,trns = getCommonData(Config,obj)
else:
vs,uvlayers,ins,nr,tan,bb,trns = getCommonDataNoBmesh(Config,obj)
#if bytearray
if Config.ByClass == 1:
file.write("\t\tprivate var values:Vector.<uint>;\n")
file.write("\t\tprivate var bytedata:ByteArray = new ByteArray();\n")
file.write("\t\tprivate var attributes:Array;\n\n")
file.write("\t\tpublic function "+obj.data.name+"() {\n\n")
file.write("\t\t\tattributes = [\n")
if len(vs) > 0:
file.write("\t\t\t\tVertexAttributes.POSITION,\n")
file.write("\t\t\t\tVertexAttributes.POSITION,\n")
file.write("\t\t\t\tVertexAttributes.POSITION,\n")
if (len(uvlayers) > 0) and (Config.ExportUV == 1):
j=0
for uvname, uvdata in uvlayers.items():
file.write("\t\t\t\tVertexAttributes.TEXCOORDS["+str(j)+"],\n")
file.write("\t\t\t\tVertexAttributes.TEXCOORDS["+str(j)+"],\n")
j=j+1
if Config.ByClass == 0:
file.write("\t\t\t\tVertexAttributes.NORMAL,\n")
file.write("\t\t\t\tVertexAttributes.NORMAL,\n")
file.write("\t\t\t\tVertexAttributes.NORMAL,\n")
file.write("\t\t\t\tVertexAttributes.TANGENT4,\n")
file.write("\t\t\t\tVertexAttributes.TANGENT4,\n")
file.write("\t\t\t\tVertexAttributes.TANGENT4,\n")
file.write("\t\t\t\tVertexAttributes.TANGENT4,\n")
file.write("\t\t\t];\n")
file.write("\t\t\tvar g:Geometry = new Geometry();\n")
file.write("\t\t\tg.addVertexStream(attributes);\n")
file.write("\t\t\tg.numVertices = "+str(len(vs))+";\n\n")
if Config.ByClass == 0:
if len(vs) > 0:
file.write("\t\t\tvar vertices:Array = [\n")
for v in vs:
file.write("\t\t\t\t%.6g, %.6g, %.6g,\n" % (v[0],v[1],v[2]))
file.write("\t\t\t];\n")
else:
file.write("\t\t\tvar vertices:Array = new Array();\n")
if (len(uvlayers) > 0) and (Config.ExportUV == 1):
j=0
for uvname, uvdata in uvlayers.items():
if j <= 7:
file.write("\t\t\tvar uvlayer"+str(j)+":Array = [\n")
for u in uvdata[0]:
file.write("\t\t\t\t%.4g,%.4g,\n" % (u[0],u[1]))
file.write("\t\t\t];\n")
j=j+1
else:
file.write("\t\t\tvar uvlayer:Array = new Array();\n")
if len(ins) > 0:
file.write("\t\t\tvar ind:Array = [\n")
x=0
for t in ins:
if x == 0:
file.write("\t\t\t\t")
file.write("%i," % (t))
if x >= 2:
file.write("\n")
x=-1
x = x+1
file.write("\t\t\t];\n")
else:
file.write("\t\t\tvar ind:Array = new Array();\n")
if (len(nr) > 0) and (Config.ExportNormals == 1):
file.write("\t\t\tvar normals:Array = [\n")
for n in nr:
file.write("\t\t\t\t%.6g, %.6g, %.6g,\n" % (n[0],n[1],n[2]))
file.write("\t\t\t];\n")
else:
file.write("\t\t\tvar normals:Array = new Array();\n")