-
Notifications
You must be signed in to change notification settings - Fork 1
/
rwx2blender.py
1386 lines (1002 loc) · 48.1 KB
/
rwx2blender.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
"""
rwx2blender - Blender add-on to import Active Worlds RenderWare scripts.
Copyright (C) 2017 Julien Bardagi (Blaxar Waldarax <blaxar.waldarax@gmail.com>)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import os
import re
import fileinput
from copy import deepcopy
from math import radians, cos, sin, pi
import mathutils as mu
from hashlib import md5
import zipfile
import tempfile
in_blender = None
try:
import bpy
from bpy.props import *
import bmesh
from bmesh.ops import edgeloop_fill, triangulate, pointmerge
except ModuleNotFoundError as mnf:
in_blender = False
else:
in_blender = True
from traceback import print_exc
from enum import Enum
bl_info = {"name": "rwx2blender",
"author": "Julien Bardagi (Blaxar Waldarax)",
"description": "Add-on to import Active Worlds RenderWare scripts (.rwx)",
"version": (0, 4, 0),
"blender": (4, 1, 0),
"location": "File > Import...",
"category": "Import-Export"}
class LightSampling(Enum):
FACET = 1
VERTEX = 2
class GeometrySampling(Enum):
POINTCOULD = 1
WIREFRAME = 2
SOLID = 3
class TextureMode(Enum):
LIT = 1
FORESHORTEN = 2
FILTER = 3
class MaterialMode(Enum):
NONE = 1
NULL = 2
DOUBLE = 3
def apply_proto_recursive(root, proto, transform = mu.Matrix.Identity(4)):
offset = len(root.vertices)
shapes = deepcopy(proto.shapes)
for shape in shapes:
for i, vid in enumerate(shape.vertices_id):
shape.vertices_id[i] += offset
root.shapes.extend(shapes)
for i, vert in enumerate(proto.vertices):
mat = transform @ mu.Vector([vert.x, vert.y, vert.z, 1])
root.vertices.append(RwxVertex(mat[0], mat[1], mat[2], u=vert.u, v=vert.v))
for sub_proto in proto.clumps:
sub_clump = RwxClump(parent = root, state = proto.state)
apply_proto_recursive(sub_clump, sub_proto, transform)
root.clumps.append(sub_clump)
class RwxState:
def __init__(self):
# Material related properties start here
self.color = (0.0, 0.0, 0.0) # Red, Green, Blue
self.surface = (0.0, 0.0, 0.0) # Ambience, Diffusion, Specularity
self.opacity = 1.0
self.lightsampling = LightSampling.FACET
self.geometrysampling = GeometrySampling.SOLID
self.texturemodes = [TextureMode.LIT,] # There's possibly more than one mode enabled at a time (hence why we use an array)
self.materialmode = MaterialMode.NONE # Neither NULL nor DOUBLE: we only render one side of the polygon
self.texture = None
self.mask = None
# End of material related properties
@property
def mat_signature(self):
h = md5()
sign = [f'{x:.3f}' for x in self.color]
sign.extend([f'{x:.3f}' for x in self.surface])
sign.append(f'{self.opacity:.3f}')
sign.append(self.lightsampling.name)
sign.append(self.geometrysampling.name)
sign.extend([x.name for x in sorted(self.texturemodes)])
sign.append(self.materialmode.name)
h.update(''.join([str(x) for x in sign]).replace('.','').lower().encode('utf-8'))
return '_'.join([str(self.texture), str(self.mask), h.hexdigest()[:10]])
def __str__(self):
return self.mat_signature
def __repr__(self):
return f'<RwxState: {self.mat_signature}>'
class RwxVertex:
def __init__(self, x, y, z, transform = mu.Matrix.Identity(4), u = None, v = None):
mat = transform @ mu.Vector([x, y, z, 1])
self.x = mat[0]
self.y = mat[1]
self.z = mat[2]
self.u = u
self.v = v
def __str__(self):
return f'x:{self.x} y:{self.y} z:{self.z} (u:{self.u}, v:{self.v})'
def __call__(self):
return (self.x, self.y, self.z)
@property
def uv(self):
return (self.u, self.v)
class RwxScope:
def __init__(self, parent, state = RwxState()):
self.state = deepcopy(state)
self.vertices = []
self.shapes = []
self.parent = parent
def __str__(self):
return f'vertices:{os.linesep}' +\
os.linesep.join([ f'-- {(str(v),)}' for v in self.vertices ]) +\
f'{os.linesep}shapes:{os.linesep}' +\
os.linesep.join([ f'-- {(str(s),)}' for s in self.shapes ])
@property
def faces(self):
faces = []
for shape in self.shapes:
if not isinstance(shape, RwxPolygon): faces.extend(shape())
return faces
@property
def polys(self):
polys = []
for shape in self.shapes:
if isinstance(shape, RwxPolygon): polys.append(shape())
return polys
@property
def verts(self):
return [vert() for vert in self.vertices]
@property
def verts_uv(self):
return [[vert.uv[0], 1.0-vert.uv[1] if vert.uv[1] is not None else None] for vert in self.vertices]
@property
def faces_uv(self):
faces = self.faces
verts_uv = self.verts_uv
return [ [verts_uv[face[0]], verts_uv[face[1]], verts_uv[face[2]]] for face in faces ]
@property
def polys_uv(self):
polys = self.polys
verts_uv = self.verts_uv
return [ [ verts_uv[edge[0]] for edge in enumerate(poly) ] for poly in polys ]
@property
def faces_state(self):
states = []
for shape in self.shapes:
for face in shape():
if not isinstance(shape, RwxPolygon): states.append(shape.state)
return states
@property
def polys_state(self):
states = []
for shape in self.shapes:
if isinstance(shape, RwxPolygon): states.append(shape.state)
return states
class RwxClump(RwxScope):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.clumps = []
def __str__(self):
cl = [ str(c).split(os.linesep) for c in self.clumps ]
clumps = []
for clump in cl: clumps.extend(clump)
clumps = [f'----{str(c)}' for c in clumps]
return f'clump:{os.linesep}' +\
super().__str__() + os.linesep+\
f'--clumps:{os.linesep}' +\
os.linesep.join(clumps)
def apply_proto(self, proto, transform = mu.Matrix.Identity(4)):
apply_proto_recursive(self, proto, transform)
class RwxShape:
def __init__(self, state = RwxState()):
self.state = deepcopy(state)
self.vertices_id = None
def __call__(self):
return []
class RwxTriangle(RwxShape):
def __init__(self, v1, v2, v3, **kwargs):
super().__init__(**kwargs)
self.vertices_id = [v1, v2, v3]
def __call__(self):
return [(self.vertices_id[0]-1, self.vertices_id[1]-1, self.vertices_id[2]-1)]
class RwxQuad(RwxShape):
def __init__(self, v1, v2, v3, v4, **kwargs):
super().__init__(**kwargs)
self.vertices_id = [v1, v2, v3, v4]
def __call__(self):
return [(self.vertices_id[0]-1, self.vertices_id[1]-1, self.vertices_id[2]-1),\
(self.vertices_id[0]-1, self.vertices_id[2]-1, self.vertices_id[3]-1)]
class RwxPolygon(RwxShape):
def __init__(self, v_id = [], **kwargs):
super().__init__(**kwargs)
self.vertices_id = v_id
def __call__(self):
edges = []
vertices_id = self.vertices_id
for id in range(0, len(vertices_id)-1):
if vertices_id[id] != vertices_id[id+1]:
edges.append((vertices_id[id]-1, vertices_id[id+1]-1))
if vertices_id[-1] != vertices_id[0]:
edges.append((vertices_id[-1]-1, vertices_id[0]-1))
return edges
class RwxObject:
state = None
def __init__(self, name = None):
self.protos = []
self.clumps = []
self.state = RwxState()
self.name = name
def __str__(self):
cl = [ str(c).split(os.linesep) for c in self.clumps ]
clumps = []
for clump in cl: clumps.extend(clump)
clumps = [f'----{str(c)}' for c in clumps]
return f'object:{os.linesep}' +\
f'--clumps:{os.linesep}' +\
os.linesep.join(clumps)
class RwxParser:
# Begin regex list
_integer_regex = re.compile("([-+]?[0-9]+)")
_float_regex = re.compile("([+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?)")
_non_comment_regex = re.compile("^(.*)#")
_clumpbegin_regex = re.compile("^ *(clumpbegin).*$", re.IGNORECASE)
_clumpend_regex = re.compile("^ *(clumpend).*$", re.IGNORECASE)
_transformbegin_regex = re.compile("^ *(transformbegin).*$", re.IGNORECASE)
_transformend_regex = re.compile("^ *(transformend).*$", re.IGNORECASE)
_protobegin_regex = re.compile("^ *(protobegin) +([A-Za-z0-9_\\-]+).*$", re.IGNORECASE)
_protoinstance_regex = re.compile("^ *(protoinstance) +([A-Za-z0-9_\\-]+).*$", re.IGNORECASE)
_protoend_regex = re.compile("^ *(protoend).*$", re.IGNORECASE)
_vertex_regex = re.compile("^ *(vertex|vertexext)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){3}) *(uv(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){2}))?.*$", re.IGNORECASE)
_polygon_regex = re.compile("^ *(polygon|polygonext)( +[0-9]+)(( +[0-9]+)+) ?.*$", re.IGNORECASE)
_quad_regex = re.compile("^ *(quad|quadext)(( +([0-9]+)){4}).*$", re.IGNORECASE)
_triangle_regex = re.compile("^ *(triangle|triangleext)(( +([0-9]+)){3}).*$", re.IGNORECASE)
_texture_regex = re.compile("^ *(texture) +([A-Za-z0-9_\\-]+) *(mask *([A-Za-z0-9_\\-]+))?.*$", re.IGNORECASE)
_color_regex = re.compile("^ *(color)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){3}).*$", re.IGNORECASE)
_opacity_regex = re.compile("^ *(opacity)( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?).*$", re.IGNORECASE)
_transform_regex = re.compile("^ *(transform)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){16}).*$", re.IGNORECASE)
_translate_regex = re.compile("^ *(translate)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){3}).*$", re.IGNORECASE)
_scale_regex = re.compile("^ *(scale)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){3}).*$", re.IGNORECASE)
_rotate_regex = re.compile("^ *(rotate)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){4})$", re.IGNORECASE)
_surface_regex = re.compile("^ *(surface)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?){3}).*$", re.IGNORECASE)
_ambient_regex = re.compile("^ *(ambient)( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?).*$", re.IGNORECASE)
_diffuse_regex = re.compile("^ *(diffuse)( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?).*$", re.IGNORECASE)
_specular_regex = re.compile("^ *(specular)( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+][0-9]+)?).*$", re.IGNORECASE)
_materialmode_regex = re.compile("^ *((add)?materialmode(s)?) +([A-Za-z0-9_\\-]+).*$", re.IGNORECASE)
_block_regex = re.compile("^ *(block)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?){3}).*$", re.IGNORECASE)
_cone_regex = re.compile("^ *(cone)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?){2}( +[-+]?[0-9]+)).*$", re.IGNORECASE)
_cylinder_regex = re.compile("^ *(cylinder)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?){3}( +[-+]?[0-9]+)).*$", re.IGNORECASE)
_disc_regex = re.compile("^ *(disc)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?){2}( +[-+]?[0-9]+)).*$", re.IGNORECASE)
_hemisphere_regex = re.compile("^ *(hemisphere)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?)( +[-+]?[0-9]+)).*$", re.IGNORECASE)
_sphere_regex = re.compile("^ *(sphere)(( +[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)(e[-+][0-9]+)?)( +[-+]?[0-9]+)).*$", re.IGNORECASE)
_identity_regex = re.compile("^identity$", re.IGNORECASE)
# End regex list
def _begin_clump(self):
self._push_current_transform()
rwx_clump = RwxClump(parent = self._current_scope, state = self._current_scope.state)
self._current_scope.clumps.append(rwx_clump)
self._current_scope = rwx_clump
def _end_clump(self):
self._pop_current_transform()
self._current_scope = self._current_scope.parent
def _add_mesh(self, vertices, uvs, faces):
assert(len(vertices)%3 == 0)
assert(len(uvs)%2 == 0)
assert(len(vertices)/3 == len(uvs)/2)
assert(len(faces)%3 == 0)
self._begin_clump()
# Zip vertex positions (3 by 3) with UVs (2 by 2) to get a new RwxVertex per entry
for (vert, uv) in zip([vertices[i:i+3] for i in range(0, len(vertices), 3)],\
[vertices[i:i+2] for i in range(0, len(uvs), 2)]):
self._current_scope.vertices.append(RwxVertex(vert[0], vert[1], vert[2],\
self._final_transform,\
uv[0], uv[1]))
for f in [faces[i:i+3] for i in range(0, len(faces), 3)]:
self._current_scope.shapes.append(RwxTriangle(f[0]+1, f[1]+1, f[2]+1,\
state=self._current_scope.state))
self._end_clump()
def _make_vertex_circle(self, h, r, n, v = None):
if n < 3:
raise ValueError("Need at least 3 sides to make a vertex circle")
positions = []
uvs = []
vec = mu.Vector([r, 0, 0])
delta_rad = pi * 2 / n
for i in range(0, n):
positions.extend([vec.x, vec.y + h, vec.z])
vec = vec @ mu.Matrix.Rotation(delta_rad, 3, 'Y')
if v is None:
# No reference V value provided for UVs: assuming a circular cutout in the texture
uvs.extend([(cos(delta_rad*i)+1)/2, (sin(delta_rad*i)+1)/2])
else:
# V value provided: picking UVs along U axis with fixed V
uvs.extend([1/n*i, v])
return positions, uvs
def _add_block(self, w, h, d):
positions = [\
-w/2, h/2, -d/2,\
w/2, h/2, -d/2,\
w/2, h/2, d/2,\
-w/2, h/2, d/2,\
-w/2, -h/2, -d/2,\
w/2, -h/2, -d/2,\
w/2, -h/2, d/2,\
-w/2, -h/2, d/2]
uvs = [\
0.0, 0.0,\
1.0, 0.0,\
1.0, 1.0,\
0.0, 1.0,\
1.0, 1.0,\
0.0, 1.0,\
0.0, 0.0,\
1.0, 0.0]
faces = [\
0, 3, 1, 1, 3, 2,\
0, 4, 3, 3, 4, 7,\
3, 6, 2, 3, 7, 6,\
6, 7, 5, 5, 7, 4,\
1, 5, 0, 0, 5, 4,\
2, 5, 1, 6, 5, 2]
self._add_mesh(positions, uvs, faces)
def _add_cone(self, h, r, n):
if n < 3:
#Silently skip if the cone doesn't have enough faces on its base
pass
positions, uvs = self._make_vertex_circle(0, r, n)
positions.extend([0, h, 0])
uvs.extend([0.5, 0.5])
faces = []
for i in range(0, n):
faces.extend([n, (i+1)%n, i])
self._add_mesh(positions, uvs, faces)
def _add_cylinder(self, h, br, tr, n):
if n < 3:
#Silently skip if the cylinder doesn't have enough faces on its base
pass
#Bottom vertex circle
positions, uvs = self._make_vertex_circle(0, br, n, 1.0)
#Top vertex circle
top_pos, top_uvs = self._make_vertex_circle(h, tr, n, 0.0)
positions.extend(top_pos)
uvs.extend(top_uvs)
first_top_id = n
faces = []
#We weave faces across both circles (up and down) to make a cylinder
for i in range(0, n):
faces.extend([first_top_id+i, (i+1)%n, i])
faces.extend([first_top_id+i, first_top_id+((i+1)%n), (i+1)%n])
self._add_mesh(positions, uvs, faces)
def _add_disc(self, h, r, n):
if n < 3:
#Silently skip if the disc doesn't have enough faces on its base
pass
positions, uvs = self._make_vertex_circle(h, r, n)
faces = []
for i in range(0, n):
faces.extend([0, (i+1)%n, i])
self._add_mesh(positions, uvs, faces)
def _add_hemisphere(self, r, n):
if n < 2:
# Silently skip if the hemisphere doesn't have enough density
pass
nb_sides = n * 4
nb_segments = n
delta_rad = pi/(nb_segments*2)
# Bottom vertex circle
positions, uvs = self._make_vertex_circle(0, r, nb_sides, 1.0)
previous_level_id = 0
current_level_id = 0
faces = []
# Now that we have the base of the hemisphere: we build up from there to the top
for h in range(1, nb_segments):
current_level_id = previous_level_id+nb_sides
n_h = sin(delta_rad*h)
pos, uv = self._make_vertex_circle(n_h*r, cos(delta_rad*h)*r, nb_sides, n_h)
positions.extend(pos)
uvs.extend(uv)
#We weave faces across both circles (up and down) to make a cylinder
for i in range(0, nb_sides):
faces.extend([previous_level_id+i, current_level_id+i, previous_level_id+((i+1)%nb_sides),\
previous_level_id+((i+1)%nb_sides), current_level_id+i,\
current_level_id+((i+1)%nb_sides)])
previous_level_id = current_level_id
# We add the pointy top of the hemisphere
positions.extend([0, r, 0])
uvs.extend([0.5, 0.0])
top_id = int(len(positions)/3-1)
# We weave faces across the circle (starting from the pointy top) to make a cone
for i in range(0, nb_sides):
faces.extend([top_id, previous_level_id+((i+1)%nb_sides), previous_level_id+i])
self._add_mesh(positions, uvs, faces)
def _add_sphere(self, r, n):
if n < 2:
# Silently skip if the sphere doesn't have enough density
pass
nb_sides = n*4
nb_segments = n
delta_rad = pi/(nb_segments*2)
# We add the pointy bottom of the sphere
positions = [0, -r, 0]
uvs = [0.5, 0.0]
# Bottom vertex circle (above pointy bottom)
_h = -nb_segments+1
n_h = sin(delta_rad*_h)
pos, uv = self._make_vertex_circle(n_h*r, cos(delta_rad*_h)*r, nb_sides, n_h)
positions.extend(pos)
uvs.extend(uv)
previous_level_id = 0
current_level_id = 1
faces = []
# We weave faces across the circle (starting from the pointy bottom) to make a cone
for i in range(0, nb_sides):
faces.extend([previous_level_id, current_level_id+i, current_level_id+(i+1)%nb_sides])
previous_level_id = current_level_id
# Now that we have the base of the sphere: we build up from there to the top
for h in range(_h+1, nb_segments):
current_level_id = previous_level_id+nb_sides
n_h = sin(delta_rad*h)
pos, uv = self._make_vertex_circle(n_h*r, cos(delta_rad*h)*r, nb_sides, n_h)
positions.extend(pos)
uvs.extend(uv)
# We weave faces across both circles (up and down) to make a cylinder
for i in range(0, nb_sides):
faces.extend([previous_level_id+i, current_level_id+i, previous_level_id+((i+1)%nb_sides),\
previous_level_id+((i+1)%nb_sides), current_level_id+i,\
current_level_id+((i+1)%nb_sides)])
previous_level_id = current_level_id
# We add the pointy top of the sphere
positions.extend([0, r, 0])
uvs.extend([0.5, 0.0])
current_level_id += nb_sides
# We weave faces across the circle (starting from the pointy top) to make a cone
for i in range(0, nb_sides):
faces.extend([previous_level_id+i, current_level_id,\
previous_level_id+((i+1)%nb_sides)])
self._add_mesh(positions, uvs, faces)
def _push_current_transform(self):
self._transform_stack.append(self._current_transform)
self._current_transform = mu.Matrix.Identity(4)
def _pop_current_transform(self):
self._current_transform = self._transform_stack.pop()
def _save_current_transform(self):
self._transform_saves.append(deepcopy(self._current_transform))
def _load_current_transform(self):
if len(self._transform_saves) > 0:
self._current_transform = self._transform_saves.pop()
else:
self._current_transform = mu.Matrix.Identity(4)
@property
def _final_transform(self):
transform = mu.Matrix.Identity(4)
for t in self._transform_stack:
transform = transform @ t
return transform @ self._current_transform
def __init__(self, uri, report, default_surface=(0.0, 0.0, 0.0)):
self._rwx_proto_dict = {}
self._current_scope = None
self._transform_stack = []
self._transform_saves = []
self._current_transform = mu.Matrix.Identity(4)
transform_before_proto = None
# Ready root object group
self._rwx_object = RwxObject(os.path.basename(uri))
self._current_scope = self._rwx_object
self._current_scope.state.surface = default_surface
self._push_current_transform()
rwx_file = open(uri, mode = 'r')
try:
lines = rwx_file.readlines()
except UnicodeDecodeError:
report({'WARNING'}, "Failed to open file using local encoding, trying cp437 (Windows/DOS) instead")
lines = open(uri, mode = 'r', encoding = 'cp437').readlines()
res = None
for line in lines:
if line[0] == '#':
# The whole line is a comment: we can safely ditch it
continue
# Strip comment away
res = self._non_comment_regex.match(line)
if res:
line = res.group(1)
# Replace tabs with spaces
line = line.replace('\t', ' ').strip()
res = self._clumpbegin_regex.match(line)
if res:
self._begin_clump()
continue
res = self._clumpend_regex.match(line)
if res:
self._end_clump()
continue
res = self._transformbegin_regex.match(line)
if res:
self._save_current_transform()
res = self._transformend_regex.match(line)
if res:
self._load_current_transform()
res = self._protobegin_regex.match(line)
if res:
name = res.group(2)
self._rwx_proto_dict[name] = RwxClump(parent = self._current_scope, state = self._current_scope.state)
self._current_scope = self._rwx_proto_dict[name]
transform_before_proto = self._current_transform.copy()
self._current_transform = mu.Matrix.Identity(4)
continue
res = self._protoend_regex.match(line)
if res:
self._current_scope = self._rwx_object
self._current_transform = transform_before_proto
continue
res = self._protoinstance_regex.match(line)
if res:
name = res.group(2)
self._current_scope.apply_proto(self._rwx_proto_dict[name], self._final_transform)
continue
res = self._texture_regex.match(line)
if res:
self._current_scope.state.texture = None if res.group(2).lower() == "null" else res.group(2)
self._current_scope.state.mask = res.group(4)
continue
res = self._triangle_regex.match(line)
if res:
v_id = [ int(x) for x in self._integer_regex.findall(res.group(2)) ]
self._current_scope.shapes.append(RwxTriangle(v_id[0], v_id[1], v_id[2],\
state=self._current_scope.state))
continue
res = self._quad_regex.match(line)
if res:
v_id = [ int(x) for x in self._integer_regex.findall(res.group(2)) ]
self._current_scope.shapes.append(RwxQuad(v_id[0], v_id[1], v_id[2], v_id[3],\
state=self._current_scope.state))
continue
res = self._polygon_regex.match(line)
if res:
v_len = int(self._integer_regex.findall(res.group(2))[0])
v_id = [ int(x) for x in self._integer_regex.findall(res.group(3)) ]
self._current_scope.shapes.append(RwxPolygon(v_id[0:v_len],\
state=self._current_scope.state))
continue
res = self._vertex_regex.match(line)
if res:
vprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if res.group(7):
vprops.extend([ float(x[0]) for x in self._float_regex.findall(res.group(7)) ])
self._current_scope.vertices.append(RwxVertex(vprops[0], vprops[1], vprops[2],
self._final_transform,
u = vprops[3],
v = vprops[4]))
else:
self._current_scope.vertices.append(RwxVertex(vprops[0], vprops[1], vprops[2],
self._final_transform))
continue
res = self._color_regex.match(line)
if res:
cprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if len(cprops) == 3:
self._current_scope.state.color = tuple(cprops)
continue
res = self._opacity_regex.match(line)
if res:
self._current_scope.state.opacity = float(res.group(2))
continue
res = self._transform_regex.match(line)
if res:
tprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if len(tprops) == 16:
# Important Note: it seems the AW client always acts as if this element
# (which is related to the projection plane) was equal to 1 when it was
# set 0, hence why we always override this.
if tprops[15] == 0.0:
tprops[15] = 1
self._current_transform = mu.Matrix(list(zip(*[iter(tprops)]*4))).transposed()
continue
res = self._translate_regex.match(line)
if res:
tprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._current_transform = self._current_transform @ mu.Matrix.Translation(mu.Vector(tprops))
continue
res = self._rotate_regex.match(line)
if res:
rprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if len(rprops) == 4:
if rprops[0]:
self._current_transform =\
self._current_transform @ mu.Matrix.Rotation(radians(rprops[3]*rprops[0]), 4, 'X')
if rprops[1]:
self._current_transform =\
self._current_transform @ mu.Matrix.Rotation(radians(rprops[3]*rprops[1]), 4, 'Y')
if rprops[2]:
self._current_transform =\
self._current_transform @ mu.Matrix.Rotation(radians(rprops[3]*rprops[2]), 4, 'Z')
continue
res = self._scale_regex.match(line)
if res:
sprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if len(sprops) == 3:
self._current_transform = self._current_transform @\
mu.Matrix.Scale(sprops[0], 4, (1.0, 0.0, 0.0)) @\
mu.Matrix.Scale(sprops[1], 4, (0.0, 1.0, 0.0)) @\
mu.Matrix.Scale(sprops[2], 4, (0.0, 0.0, 1.0))
continue
res = self._surface_regex.match(line)
if res:
sprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
if len(sprops) == 3:
self._current_scope.state.surface = tuple(sprops)
continue
res = self._ambient_regex.match(line)
if res:
surf = self._current_scope.state.surface
self._current_scope.state.surface = (float(res.group(2)), surf[1], surf[2])
continue
res = self._diffuse_regex.match(line)
if res:
surf = self._current_scope.state.surface
self._current_scope.state.surface = (surf[0], float(res.group(2)), surf[2])
continue
res = self._specular_regex.match(line)
if res:
surf = self._current_scope.state.surface
self._current_scope.state.surface = (surf[0], surf[1], float(res.group(2)))
continue
res = self._materialmode_regex.match(line)
if res:
mat_mode = res.group(4).lower()
if mat_mode == "none":
self._current_scope.state.materialmode = MaterialMode.NONE
elif mat_mode == "null":
self._current_scope.state.materialmode = MaterialMode.NULL
elif mat_mode == "double":
self._current_scope.state.materialmode = MaterialMode.DOUBLE
continue
res = self._block_regex.match(line)
if res:
bprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_block(bprops[0], bprops[1], bprops[2])
continue
res = self._cone_regex.match(line)
if res:
cprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_cone(cprops[0], cprops[1], int(cprops[2]))
continue
res = self._cylinder_regex.match(line)
if res:
cprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_cylinder(cprops[0], cprops[1], cprops[2], int(cprops[3]))
continue
res = self._disc_regex.match(line)
if res:
dprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_disc(dprops[0], dprops[1], int(dprops[2]))
continue
res = self._hemisphere_regex.match(line)
if res:
hprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_hemisphere(hprops[0], int(hprops[1]))
continue
res = self._sphere_regex.match(line)
if res:
sprops = [ float(x[0]) for x in self._float_regex.findall(res.group(2)) ]
self._add_sphere(sprops[0], int(sprops[1]))
continue
res = self._identity_regex.match(line)
if res:
self._current_transform = mu.Matrix.Identity(4)
continue
def __call__(self):
return self._rwx_object
def gather_attr_recursive(clump, name):
attr = []
attr.extend(getattr(clump, name))
for c in clump.clumps:
attr.extend(gather_attr_recursive(c, name))
return attr
def gather_vertices_recursive(clump):
vertices = []
for v in clump.verts:
vert = mu.Vector([v[0], v[1], v[2], 1])
vertices.append((vert[0], vert[1], vert[2]))
for c in clump.clumps:
vertices.extend(gather_vertices_recursive(c))
return vertices
def gather_faces_recursive(clump, offset=0):
faces = []
polys = []
tmp_faces = clump.faces
tmp_polys = clump.polys
for tmp_face in tmp_faces:
faces.append((tmp_face[0]+offset, tmp_face[1]+offset, tmp_face[2]+offset))
for tmp_poly in tmp_polys:
polys.append([(edge[0]+offset, edge[1]+offset) for edge in tmp_poly])
offset += len(clump.verts)
for c in clump.clumps:
(tmp_faces, tmp_polys, offset) = gather_faces_recursive(c, offset)
faces.extend(tmp_faces)
polys.extend(tmp_polys)
return (faces, polys, offset)
def create_mesh(ob, mesh, verts, faces, polys, faces_state, polys_state, faces_uv, verts_uv):
# Create mesh from given verts, edges, faces. Either edges or
# faces should be [], or you're asking for problems
mesh.from_pydata(verts, [], faces)
bm = bmesh.new()
bm.from_mesh(mesh)
uv_layer = bm.loops.layers.uv.verify()
if uv_layer is None: