-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgx3d.py
1748 lines (1523 loc) · 60.1 KB
/
gx3d.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
"""
GX3D file exporter main module
"""
import mathutils
import bpy_extras
import bpy
import tempfile
import sys
import subprocess
import os
import math
import io
import gc
import enum
import ctypes
import collections
itemsbl_info = {
'name': 'Gearoenix 3D Blender',
'author': 'Hossein Noroozpour',
'version': (3, 0),
'blender': (2, 7, 5),
'api': 1,
'location': 'File > Export',
'description': 'Export several scene into a Gearoenix 3D file format.',
'warning': '',
'wiki_url': '',
'tracker_url': '',
'category': 'Import-Export',
}
class Gearoenix:
"""Main class and a pseudo-namespace of the GX3D exporter"""
TYPE_BOOLEAN = ctypes.c_uint8
TYPE_BYTE = ctypes.c_uint8
TYPE_FLOAT = ctypes.c_float
TYPE_DOUBLE = ctypes.c_double
TYPE_U64 = ctypes.c_uint64
TYPE_U32 = ctypes.c_uint32
TYPE_U16 = ctypes.c_uint16
TYPE_U8 = ctypes.c_uint8
DEBUG_MODE = True
EPSILON = 0.0001
ENGINE_GEAROENIX = 0
ENGINE_VULKUST = 1
EXPORT_GEAROENIX = False
EXPORT_VULKUST = False
EXPORT_FILE_PATH = ''
GX3D_FILE = None
CPP_FILE = None
RUST_FILE = None
BAKED_SKYBOX_CUBE_RES = '1024'
IRRADIANCE_RES = '128'
RADIANCE_RES = '512'
IBL_BAKER_ENVIRONMENT_NAME = 'GEAROENIX_IBL_BAKER'
last_id = None
@staticmethod
def terminate(*msgs):
"""Terminates the plugin process"""
final_msg = ''
for msg in msgs:
final_msg += str(msg) + ' '
print('Fatal error: ' + final_msg)
raise Exception(final_msg)
@staticmethod
def initialize():
"""Initializes the class propeties that will be used in other functions"""
Gearoenix.last_id = 1024
Gearoenix.GX3D_FILE = open(Gearoenix.EXPORT_FILE_PATH, mode='wb')
dirstr = os.path.dirname(Gearoenix.EXPORT_FILE_PATH)
filename = Gearoenix.EXPORT_FILE_PATH[len(dirstr) + 1:]
p_dir_str = os.path.dirname(dirstr)
if Gearoenix.EXPORT_VULKUST:
rs_file = filename.replace('.', '_') + '.rs'
Gearoenix.RUST_FILE = open(p_dir_str + '/src/' + rs_file, mode='w')
elif Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE = open(
Gearoenix.EXPORT_FILE_PATH + '.hpp', mode='w')
else:
Gearoenix.terminate('Unexpected engine selection')
@staticmethod
def log_info(*msgs):
"""Logs in debug mode"""
if Gearoenix.DEBUG_MODE:
print('Info:', *msgs)
@staticmethod
def write_float(f):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_FLOAT(f))
@staticmethod
def write_double(f):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_DOUBLE(f))
@staticmethod
def write_u64(n):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_U64(n))
@staticmethod
def write_u32(n):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_U32(n))
@staticmethod
def write_u16(n):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_U16(n))
@staticmethod
def write_u8(n):
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_U8(n))
@staticmethod
def write_type_id(n):
Gearoenix.write_u8(n)
@staticmethod
def write_instances_ids(instances):
Gearoenix.write_u64(len(instances))
for ins in instances:
Gearoenix.write_id(ins.instance_id)
@staticmethod
def write_id(obj_id):
Gearoenix.write_u64(obj_id)
@staticmethod
def write_vector(v, element_count=3):
for i in range(element_count):
Gearoenix.write_float(v[i])
@staticmethod
def write_matrix(matrix):
for i in range(0, 4):
for j in range(0, 4):
Gearoenix.write_float(matrix[j][i])
@staticmethod
def write_u32_array(arr):
Gearoenix.write_u64(len(arr))
for i in arr:
Gearoenix.write_u32(i)
@staticmethod
def write_u64_array(arr):
Gearoenix.write_u64(len(arr))
for i in arr:
Gearoenix.write_u64(i)
@staticmethod
def write_bool(b):
data = 0
if b:
data = 1
Gearoenix.GX3D_FILE.write(Gearoenix.TYPE_BOOLEAN(data))
@staticmethod
def write_file_content(name):
Gearoenix.GX3D_FILE.write(open(name, 'rb').read())
@staticmethod
def file_tell():
return Gearoenix.GX3D_FILE.tell()
@staticmethod
def limit_check(val, maxval=1.0, minval=0.0, obj=None):
if val > maxval or val < minval:
msg = 'Out of range value'
if obj is not None:
msg += ', in object: ' + obj.name
Gearoenix.terminate(msg)
@staticmethod
def uint_check(s):
try:
if int(s) >= 0:
return True
except ValueError:
Gearoenix.terminate('Type error')
Gearoenix.terminate('Type error')
@staticmethod
def get_origin_name(blender_object):
origin_name = blender_object.name.strip().split('.')
num_dot = len(origin_name)
if num_dot > 2 or num_dot < 1:
Gearoenix.terminate('Wrong name in:', blender_object.name)
elif num_dot == 1:
return None
try:
int(origin_name[1])
except ValueError:
Gearoenix.terminate('Wrong name in:', blender_object.name)
return origin_name[0]
@staticmethod
def is_zero(f):
return -Gearoenix.EPSILON < f < Gearoenix.EPSILON
@staticmethod
def has_transformation(blender_object):
m = blender_object.matrix_world
if blender_object.parent is not None:
m = blender_object.parent.matrix_world.inverted() @ m
for i in range(4):
for j in range(4):
if i == j:
if not Gearoenix.is_zero(m[i][j] - 1.0):
return True
elif not Gearoenix.is_zero(m[i][j]):
return True
return False
@staticmethod
def write_string(s):
bs = bytes(s, 'utf-8')
Gearoenix.write_u64(len(bs))
for b in bs:
Gearoenix.write_u8(b)
@staticmethod
def const_string(s):
ss = s.replace('-', '_')
ss = ss.replace('/', '_')
ss = ss.replace('.', '_')
ss = ss.replace('C:\\', '_')
ss = ss.replace('c:\\', '_')
ss = ss.replace('\\', '_')
ss = ss.upper()
return ss
@staticmethod
def read_file(f):
return open(f, 'rb').read()
@staticmethod
def write_file(f):
Gearoenix.write_u64(len(f))
Gearoenix.GX3D_FILE.write(f)
@staticmethod
def enum_max_check(e):
if e == e.MAX:
Gearoenix.terminate('UNEXPECTED')
@staticmethod
def write_start_module(c):
mod_name = c.__name__
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.write('#[allow(dead_code)]\n')
Gearoenix.RUST_FILE.write(
'#[cfg_attr(debug_assertions, derive(Debug))]\n')
Gearoenix.RUST_FILE.write('#[repr(u64)]\n')
Gearoenix.RUST_FILE.write('pub enum ' + mod_name + ' {\n')
Gearoenix.RUST_FILE.write(' Unexpected = 0,\n')
elif Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.write('namespace ' + mod_name + '\n{\n')
@staticmethod
def make_camel_underlined(name):
camel = ""
must_up = True
for c in name:
if c == '_':
must_up = True
elif must_up:
camel += c.upper()
must_up = False
else:
camel += c.lower()
return camel
@staticmethod
def write_name_id(name, item_id):
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.write(
' ' + Gearoenix.make_camel_underlined(name) + ' = ' + str(int(item_id)) + ',\n')
elif Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.write(
' const gearoenix::core::Id ' + name + ' = ' + str(item_id) + ';\n')
@staticmethod
def write_end_module():
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.write('}\n\n')
elif Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.write('}\n')
@staticmethod
def find_common_starting(s1, s2):
s = ''
l = min(len(s1), len(s2))
for i in range(l):
if s1[i] == s2[i]:
s += s1[i]
else:
break
return s
@staticmethod
def find_tools():
Gearoenix.IBL_BAKER_PATH = os.environ[Gearoenix.IBL_BAKER_ENVIRONMENT_NAME]
class GxTmpFile:
"""A better temporary file"""
def __init__(self):
tmpfile = tempfile.NamedTemporaryFile(delete=False)
self.filename = tmpfile.name
tmpfile.close()
def __del__(self):
os.remove(self.filename)
def read(self):
f = open(self.filename, 'rb')
d = f.read()
f.close()
return d
@staticmethod
def create_sky_resources(file: str):
baked_cube = Gearoenix.GxTmpFile()
irradiance = Gearoenix.GxTmpFile()
radiance = Gearoenix.GxTmpFile()
subprocess.run(args=[
Gearoenix.IBL_BAKER_PATH,
'--environment-file',
file,
'--baked-cube-file',
baked_cube.filename,
'--baked-cube-resolution',
Gearoenix.BAKED_SKYBOX_CUBE_RES,
'--irradiance-file',
irradiance.filename,
'--irradiance-resolution',
Gearoenix.IRRADIANCE_RES,
'--radiance-file',
radiance.filename,
'--radiance-resolution',
Gearoenix.RADIANCE_RES,
], check=True)
return (baked_cube, irradiance, radiance)
@staticmethod
def menu_func_export(obj, _):
obj.layout.operator(
Gearoenix.Exporter.bl_idname, text='Gearoenix 3D Exporter (.gx3d)')
@staticmethod
def register_plugin():
bpy.utils.register_class(Gearoenix.Exporter)
try:
bpy.types.TOPBAR_MT_file_export.append(Gearoenix.menu_func_export)
except AttributeError:
return
@staticmethod
def write_tables():
Gearoenix.Camera.write_table()
Gearoenix.Audio.write_table()
Gearoenix.Light.write_table()
Gearoenix.Texture.write_table()
Gearoenix.Font.write_table()
Gearoenix.Mesh.write_table()
Gearoenix.Model.write_table()
Gearoenix.Reflection.write_table()
Gearoenix.Skybox.write_table()
Gearoenix.Constraint.write_table()
Gearoenix.Scene.write_table()
@staticmethod
def export_files():
Gearoenix.initialize()
Gearoenix.Audio.init()
Gearoenix.Light.init()
Gearoenix.Camera.init()
Gearoenix.Texture.init()
Gearoenix.Font.init()
Gearoenix.Mesh.init()
Gearoenix.Model.init()
Gearoenix.Skybox.init()
Gearoenix.Constraint.init()
Gearoenix.Reflection.init()
Gearoenix.Scene.init()
Gearoenix.Scene.read_all()
Gearoenix.write_bool(sys.byteorder == 'little')
Gearoenix.write_id(Gearoenix.last_id)
Gearoenix.tables_offset = Gearoenix.file_tell()
Gearoenix.write_tables()
Gearoenix.Camera.write_all()
Gearoenix.Audio.write_all()
Gearoenix.Light.write_all()
Gearoenix.Texture.write_all()
Gearoenix.Font.write_all()
Gearoenix.Mesh.write_all()
Gearoenix.Model.write_all()
Gearoenix.Reflection.write_all()
Gearoenix.Skybox.write_all()
Gearoenix.Constraint.write_all()
Gearoenix.Scene.write_all()
Gearoenix.GX3D_FILE.flush()
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.flush()
if Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.flush()
Gearoenix.GX3D_FILE.seek(Gearoenix.tables_offset)
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.seek(0)
if Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.seek(0)
Gearoenix.write_tables()
Gearoenix.GX3D_FILE.flush()
Gearoenix.GX3D_FILE.close()
if Gearoenix.EXPORT_VULKUST:
Gearoenix.RUST_FILE.flush()
Gearoenix.RUST_FILE.close()
if Gearoenix.EXPORT_GEAROENIX:
Gearoenix.CPP_FILE.flush()
Gearoenix.CPP_FILE.close()
gc.collect()
class Asset:
"""
Parent class for all assets.
...
Attributes
----------
instances : dict
instances of that subclass all together
name : str
name of the instance
instance_id : int
id of instance
offset : int
offset of object in the gx3d file
blender_object: bpy_types.Objec
corresponding blender object
instance_type : int
each instance of subclass of this class must define and initialize it."""
def __init__(self, blender_object):
self.instance_type = None
self.offset = 0
self.blender_object = blender_object
self.instance_id = Gearoenix.last_id
Gearoenix.last_id += 1
self.name = self.__class__.get_name_from_blender_object(
blender_object)
if not blender_object.name.startswith(self.__class__.get_prefix()):
Gearoenix.terminate(
'Unexpected name in ',
self.__class__.__name__)
if self.name in self.__class__.instances:
Gearoenix.terminate(self.name, 'is already in instances.')
self.__class__.instances[self.name] = self
@classmethod
def get_prefix(cls):
return cls.__name__.lower() + '-'
def write(self):
Gearoenix.write_type_id(self.instance_type)
@classmethod
def write_all(cls):
instances = sorted(
cls.instances.items(),
key=lambda kv: kv[1].instance_id)
for (_, item) in instances:
item.offset = Gearoenix.file_tell()
item.write()
def get_reference_name(self):
"""The name that will be used in table as a reference."""
name = self.name[len(self.__class__.get_prefix()):]
return name[name.find('-') + 1:]
@classmethod
def find_common_starting(cls) -> str:
common_starting = ''
if len(cls.instances) < 2:
return common_starting
for k in cls.instances:
common_starting = Gearoenix.const_string(k)
break
for k in cls.instances:
common_starting = Gearoenix.find_common_starting(
common_starting, Gearoenix.const_string(k))
return common_starting
@classmethod
def check_names(cls):
"""Checks the names that required and their uniqueness"""
if not Gearoenix.DEBUG_MODE:
return
names = set()
const_names = set()
for k, item in cls.instances.items():
const_name = Gearoenix.const_string(k)
name = item.get_reference_name()
if const_name in const_names or name in names:
Gearoenix.terminate(
"Duplicated name in module", str(item.__class__),
"name:", item.blender_object.name)
names.add(name)
const_names.add(const_name)
@classmethod
def write_table(cls):
cls.check_names()
Gearoenix.write_start_module(cls)
instances = sorted(
cls.instances.items(),
key=lambda kv: kv[1].instance_id)
common_starting = cls.find_common_starting()
Gearoenix.write_u64(len(instances))
Gearoenix.log_info('Number of', cls.__name__, len(instances))
for _, item in instances:
Gearoenix.write_id(item.instance_id)
Gearoenix.write_u64(item.offset)
Gearoenix.write_string(item.get_reference_name())
Gearoenix.log_info(
'instance_id:', item.instance_id,
'offset:', item.offset,
'name:', item.get_reference_name())
name = Gearoenix.const_string(item.name)[len(common_starting):]
Gearoenix.write_name_id(name, item.instance_id)
Gearoenix.write_end_module()
@staticmethod
def get_name_from_blender_object(blender_object):
return blender_object.name
@classmethod
def read(cls, blender_object):
name = cls.get_name_from_blender_object(blender_object)
if not blender_object.name.startswith(cls.get_prefix()):
return None
if name in cls.instances:
return None
return cls(blender_object)
@classmethod
def init(cls):
cls.instances = dict()
def get_offset(self):
return self.offset
Gearoenix.Asset = Asset
class UniqueAsset(Gearoenix.Asset):
"""
This class is parent of those classes having instances with
an origin that shares most of the data (e.g. Mesh) is and
must be kept unique in all other instances to prevent data redundancy
...
Attributes
----------
origin_instance: Object
"""
def __init__(self, blender_object):
self.origin_instance = None
origin_name = Gearoenix.get_origin_name(blender_object)
if origin_name is None:
super().__init__(blender_object)
else:
self.origin_instance = self.__class__.instances[origin_name]
self.name = blender_object.name
self.instance_id = self.origin_instance.instance_id
self.instance_type = self.origin_instance.instance_type
self.blender_object = blender_object
def write(self):
if self.origin_instance is not None:
Gearoenix.terminate(
'This object must not written like this. in', self.name)
super().write()
@classmethod
def read(cls, blender_object):
if not blender_object.name.startswith(cls.get_prefix()):
return None
origin_name = Gearoenix.get_origin_name(blender_object)
if origin_name is None:
return super().read(blender_object)
super().read(bpy.data.objects[origin_name])
return cls(blender_object)
Gearoenix.UniqueAsset = UniqueAsset
class ReferencingAsset(Gearoenix.Asset):
"""
This class is parent of those classes having instances that
reference same data (e.g. Texture)
...
Attributes
----------
origin_instance: Object
"""
def __init__(self, blender_object):
self.origin_instance = None
self.name = self.__class__.get_name_from_blender_object(blender_object)
if self.name not in self.__class__.instances:
super().__init__(blender_object)
else:
self.origin_instance = self.__class__.instances[self.name]
self.instance_id = self.origin_instance.instance_id
self.instance_type = self.origin_instance.instance_type
self.blender_object = blender_object
@classmethod
def read(cls, blender_object):
if not blender_object.name.startswith(cls.get_prefix()):
return None
name = cls.get_name_from_blender_object(blender_object)
if name not in cls.instances:
return super().read(blender_object)
return cls(blender_object)
def write(self):
if self.origin_instance is not None:
Gearoenix.terminate(
'This object must not written like this. in', self.name)
super().write()
def get_offset(self):
if self.origin_instance is None:
return self.offset
return self.origin_instance.offset
Gearoenix.ReferencingAsset = ReferencingAsset
class Aabb():
def __init__(self):
m = sys.float_info.max
self.upper = mathutils.Vector((-m, -m, -m))
self.lower = mathutils.Vector((m, m, m))
def put(self, v):
if self.upper.x < v.x:
self.upper.x = v.x
if self.upper.y < v.y:
self.upper.y = v.y
if self.upper.z < v.z:
self.upper.z = v.z
if self.lower.x > v.x:
self.lower.x = v.x
if self.lower.y > v.y:
self.lower.y = v.y
if self.lower.z > v.z:
self.lower.z = v.z
def write(self):
Gearoenix.write_vector(self.upper)
Gearoenix.write_vector(self.lower)
Gearoenix.Aabb = Aabb
class Audio(Gearoenix.ReferencingAsset):
TYPE_MUSIC = 1
TYPE_OBJECT = 2
@classmethod
def init(cls):
super().init()
cls.MUSIC_PREFIX = cls.get_prefix() + 'music-'
cls.OBJECT_PREFIX = cls.get_prefix() + 'object-'
def __init__(self, blender_object):
super().__init__(blender_object)
if blender_object.startswith(self.MUSIC_PREFIX):
self.instance_type = self.TYPE_MUSIC
elif blender_object.startswith(self.OBJECT_PREFIX):
self.instance_type = self.TYPE_OBJECT
else:
Gearoenix.terminate('Unspecified type in:', blender_object.name)
self.file = Gearoenix.read_file(self.name)
def write(self):
super().write()
Gearoenix.write_file(self.file)
@staticmethod
def get_name_from_blender_object(blender_object):
if blender_object.type != 'SPEAKER':
Gearoenix.terminate('Audio must be speaker: ', blender_object.name)
aud = blender_object.data
if aud is None:
Gearoenix.terminate(
'Audio is not set in speaker: ', blender_object.name)
aud = aud.sound
if aud is None:
Gearoenix.terminate(
'Sound is not set in speaker: ', blender_object.name)
filepath = aud.filepath.strip()
if filepath is None or len(filepath) == 0:
Gearoenix.terminate(
'Audio is not specified yet in speaker: ', blender_object.name)
if not filepath.endswith('.ogg'):
Gearoenix.terminate('Use OGG instead of ', filepath)
return filepath
Gearoenix.Audio = Audio
class Light(Gearoenix.Asset):
TYPE_CONE = 1
TYPE_DIRECTIONAL = 2
TYPE_POINT = 3
@classmethod
def init(cls):
super().init()
cls.DIRECTIONAL_PREFIX = cls.get_prefix() + 'directional-'
cls.POINT_PREFIX = cls.get_prefix() + 'point-'
cls.CONE_PREFIX = cls.get_prefix() + 'cone-'
def __init__(self, blender_object):
super().__init__(blender_object)
if self.blender_object.type != 'LIGHT':
Gearoenix.terminate('Light type is incorrect:',
blender_object.name)
if blender_object.name.startswith(self.DIRECTIONAL_PREFIX):
if blender_object.data.type != 'SUN':
Gearoenix.terminate(blender_object.name,
"should be a sun light")
self.instance_type = self.TYPE_DIRECTIONAL
elif blender_object.name.startswith(self.POINT_PREFIX):
if blender_object.data.type != 'POINT':
Gearoenix.terminate(blender_object.name,
"should be a point light")
self.instance_type = self.TYPE_POINT
else:
Gearoenix.terminate('Unspecified type in:', blender_object.name)
def write(self):
super().write()
color = self.blender_object.data.color
strength = self.blender_object.data.energy
Gearoenix.write_float(color[0] * strength)
Gearoenix.write_float(color[1] * strength)
Gearoenix.write_float(color[2] * strength)
Gearoenix.write_bool(self.blender_object.data.use_shadow)
if self.instance_type == self.TYPE_POINT:
Gearoenix.write_vector(self.blender_object.location)
elif self.instance_type == self.TYPE_DIRECTIONAL:
v = self.blender_object.matrix_world @ mathutils.Vector(
(0.0, 0.0, -1.0, 0.0))
v.normalize()
Gearoenix.write_vector(v)
Gearoenix.Light = Light
class Camera(Gearoenix.Asset):
TYPE_PERSPECTIVE = 1
TYPE_ORTHOGRAPHIC = 2
@classmethod
def init(cls):
super().init()
cls.PERSPECTIVE_PREFIX = cls.get_prefix() + 'perspective-'
cls.ORTHOGRAPHIC_PREFIX = cls.get_prefix() + 'orthographic-'
def __init__(self, blender_object):
super().__init__(blender_object)
if self.blender_object.type != 'CAMERA':
Gearoenix.terminate('Camera type is incorrect:',
blender_object.name)
if blender_object.name.startswith(self.PERSPECTIVE_PREFIX):
self.instance_type = self.TYPE_PERSPECTIVE
if blender_object.data.type != 'PERSP':
Gearoenix.terminate(
'Camera type is incorrect:', blender_object.name)
elif blender_object.name.startswith(self.ORTHOGRAPHIC_PREFIX):
self.instance_type = self.TYPE_ORTHOGRAPHIC
if blender_object.data.type != 'ORTHO':
Gearoenix.terminate(
'Camera type is incorrect:', blender_object.name)
else:
Gearoenix.terminate('Unspecified type in:', blender_object.name)
def write(self):
super().write()
cam = self.blender_object.data
Gearoenix.write_vector(self.blender_object.location)
Gearoenix.log_info(
"Camera location is:",
str(self.blender_object.location))
Gearoenix.write_vector(
self.blender_object.matrix_world.to_quaternion(), 4)
Gearoenix.log_info("Camera quaternion is:",
str(self.blender_object.matrix_world.to_quaternion()))
Gearoenix.write_float(cam.clip_start)
Gearoenix.write_float(cam.clip_end)
if self.instance_type == self.TYPE_PERSPECTIVE:
Gearoenix.write_float(cam.angle_x)
elif self.instance_type == self.TYPE_ORTHOGRAPHIC:
Gearoenix.write_float(cam.ortho_scale)
else:
Gearoenix.terminate('Unspecified type in:',
self.blender_object.name)
Gearoenix.Camera = Camera
class Constraint(Gearoenix.Asset):
TYPE_PLACER = 1
TYPE_TRACKER = 2
TYPE_SPRING = 3
TYPE_SPRING_JOINT = 4
@classmethod
def init(cls):
super().init()
cls.PLACER_PREFIX = cls.get_prefix() + 'placer-'
def __init__(self, blender_object):
super().__init__(blender_object)
if blender_object.name.startswith(self.PLACER_PREFIX):
self.instance_type = self.TYPE_PLACER
self.init_placer()
else:
Gearoenix.terminate('Unspecified type in:', blender_object.name)
def write(self):
super().write()
if self.instance_type == self.TYPE_PLACER:
self.write_placer()
else:
Gearoenix.terminate('Unspecified type in:',
self.blender_object.name)
def init_placer(self):
B_TYPE = 'EMPTY'
DESC = 'Placer constraint'
ATT_X_MIDDLE = 'x-middle' # 0
ATT_Y_MIDDLE = 'y-middle' # 1
ATT_X_RIGHT = 'x-right' # 2
ATT_X_LEFT = 'x-left' # 3
ATT_Y_UP = 'y-up' # 4
ATT_Y_DOWN = 'y-down' # 5
ATT_RATIO = 'ratio'
if self.blender_object.type != B_TYPE:
Gearoenix.terminate(DESC, 'type must be', B_TYPE,
'in object:', self.blender_object.name)
if len(self.blender_object.children) < 1:
Gearoenix.terminate(
DESC, 'must have more than 0 children, in object:', self.blender_object.name)
self.model_children = []
for c in self.blender_object.children:
ins = Gearoenix.Model.read(c)
if ins is None:
Gearoenix.terminate(
DESC, 'can only have model as its child, in object:', self.blender_object.name)
self.model_children.append(ins)
self.attrs = [None for i in range(6)]
if ATT_X_MIDDLE in self.blender_object:
self.check_trans()
self.attrs[0] = self.blender_object[ATT_X_MIDDLE]
if ATT_Y_MIDDLE in self.blender_object:
self.check_trans()
self.attrs[1] = self.blender_object[ATT_Y_MIDDLE]
if ATT_X_LEFT in self.blender_object:
self.attrs[2] = self.blender_object[ATT_X_LEFT]
if ATT_X_RIGHT in self.blender_object:
self.attrs[3] = self.blender_object[ATT_X_RIGHT]
if ATT_Y_UP in self.blender_object:
self.attrs[4] = self.blender_object[ATT_Y_UP]
if ATT_Y_DOWN in self.blender_object:
self.attrs[5] = self.blender_object[ATT_Y_DOWN]
if ATT_RATIO in self.blender_object:
self.ratio = self.blender_object[ATT_RATIO]
else:
self.ratio = None
self.placer_type = 0
for i in range(len(self.attrs)):
if self.attrs[i] is not None:
self.placer_type |= (1 << i)
if self.placer_type not in {4, 8, 33}:
Gearoenix.terminate(
DESC, 'must have meaningful combination, in object:', self.blender_object.name)
def write_placer(self):
Gearoenix.write_u64(self.placer_type)
if self.ratio is not None:
Gearoenix.write_float(self.ratio)
if self.placer_type == 4:
Gearoenix.write_float(self.attrs[2])
elif self.placer_type == 8:
Gearoenix.write_float(self.attrs[3])
elif self.placer_type == 33:
Gearoenix.write_float(self.attrs[0])
Gearoenix.write_float(self.attrs[5])
else:
Gearoenix.terminate(
'It is not implemented, in object:', self.blender_object.name)
childrenids = []
for c in self.model_children:
childrenids.append(c.instance_id)
childrenids.sort()
Gearoenix.write_u64_array(childrenids)
def check_trans(self):
if Gearoenix.has_transformation(self.blender_object):
Gearoenix.terminate(
'This object should not have any transformation, in:', self.blender_object.name)
Gearoenix.Constraint = Constraint
class Collider:
GHOST = 1
MESH = 2
PREFIX = 'collider-'
CHILDREN = []
def __init__(self, blender_object=None):
if blender_object is None:
if self.MY_TYPE == self.GHOST:
return
else:
Gearoenix.terminate('Unexpected blender_object is None')
if not blender_object.name.startswith(self.PREFIX):
Gearoenix.terminate(
'Collider object name is wrong. In:', blender_object.name)
self.blender_object = blender_object
def write(self):
Gearoenix.write_type_id(self.MY_TYPE)
@classmethod
def read(cls, pb_obj):
collider_object = None
for blender_object in pb_obj.children:
for c in cls.CHILDREN:
if blender_object.name.startswith(c.PREFIX):
if collider_object is not None:
Gearoenix.terminate(
'Only one collider is acceptable. In model:', pb_obj.name)
collider_object = c(blender_object)
if collider_object is None:
return Gearoenix.GhostCollider()
return collider_object
Gearoenix.Collider = Collider
class GhostCollider(Gearoenix.Collider):
MY_TYPE = Gearoenix.Collider.GHOST
PREFIX = Gearoenix.Collider.PREFIX + 'ghost-'
Gearoenix.GhostCollider = GhostCollider
Gearoenix.Collider.CHILDREN.append(Gearoenix.GhostCollider)
class MeshCollider(Gearoenix.Collider):
MY_TYPE = Gearoenix.Collider.MESH
PREFIX = Gearoenix.Collider.PREFIX + 'mesh-'
def __init__(self, blender_object):
super().__init__(blender_object)
self.blender_object = blender_object
if blender_object.type != 'MESH':
Gearoenix.terminate(
'Mesh collider must have mesh object type, In model:', blender_object.name)
if has_transformation(blender_object):
Gearoenix.terminate(
'Mesh collider can not have any transformation, in:', blender_object.name)