-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmesh.py
1629 lines (1506 loc) · 81.8 KB
/
mesh.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
import bpy
import bmesh
import itertools
import math
import mathutils
import os, os.path
import random
import struct
import sys
import zlib
from bpy.props import EnumProperty, IntProperty, PointerProperty, StringProperty
from bpy.types import Object, Operator, Panel, PropertyGroup
from mathutils import Vector
from typing import Sequence
from .binstruct import *
from .lgtypes import *
#---------------------------------------------------------------------------#
# Import
def create_color_table(size):
rand = random.Random(0)
def random_color(alpha=1.0):
r = rand.uniform(0.0, 1.0)
g = rand.uniform(0.0, 1.0)
b = rand.uniform(0.0, 1.0)
return (r, g, b, alpha)
return [random_color() for i in range(size)]
ID_COLOR_TABLE = create_color_table(1024)
def id_color(id):
return ID_COLOR_TABLE[abs(id)%len(ID_COLOR_TABLE)]
def create_empty(name, location, context=None, link=True):
o = bpy.data.objects.new(name, None)
o.location = location
o.empty_display_size = 0.125
o.empty_display_type = 'PLAIN_AXES'
if context and link:
coll = context.view_layer.active_layer_collection.collection
coll.objects.link(o)
return o
def create_object(name, mesh, location, context=None, link=True):
o = bpy.data.objects.new(name, mesh)
o.location = location
if context and link:
coll = context.view_layer.active_layer_collection.collection
coll.objects.link(o)
return o
def create_armature(name, location, context=None, link=True, display_type='OCTAHEDRAL'):
arm = bpy.data.armatures.new(name)
arm.display_type = display_type
o = bpy.data.objects.new(name, arm)
o.location = location
o.show_in_front = True
if context and link:
coll = context.view_layer.active_layer_collection.collection
coll.objects.link(o)
return o
MAX_JOINT_COUNT = 40
class DarkSkeleton:
# Stores the skeleton as a sequence of tuples:
# [ (joint_id, name, parent, connected, head_pos, tail_pos, limb_end), ... ]
# int str int bool Vector Vector bool
def __init__(self, name, joint_info):
self.name = name
self.joint_info = [
( int(j), str(name), int(pj), bool(conn),
Vector(head), Vector(tail), bool(limb_end) )
for (j, name, pj, conn, head, tail, limb_end) in joint_info]
def __len__(self):
return len(self.joint_info)
def __iter__(self):
return iter(self.joint_info)
def topology(self):
"""Return a value used only for comparing topology with other skeletons."""
return tuple(sorted((t[2], t[0]) for t in self.joint_info))
@classmethod
def from_cal(cls, filename, report_fn=None):
cal = LGCALFile(filename)
joint_ids = set()
head_pos = [Vector((0,0,0)) for _ in range(MAX_JOINT_COUNT)] # armature-local space
tail_pos = [Vector((1,0,0)) for _ in range(MAX_JOINT_COUNT)] # armature-local space
parent_joint_id = [-1]*MAX_JOINT_COUNT
is_connected = [False]*MAX_JOINT_COUNT
is_limb_end = [False]*MAX_JOINT_COUNT
for torso_id, torso in enumerate(cal.p_torsos):
if torso.parent == -1:
j = torso.joint
# Some skeletons (burrick, spider, ...) have multiple root
# torsos defined with the same joint id (presumably from before
# they increased the torso's fixed-point maximum to 16). We just
# ignore that; the rest of the skeleton will continue to
# import correctly.
if j not in joint_ids:
head_pos[j] = Vector((0,0,0))
tail_pos[j] = Vector((1,0,0))
parent_joint_id[j] = -1
else:
j = torso.joint
pj = cal.p_torsos[torso.parent].joint
assert pj in joint_ids, f"parent joint {pj} (from torso {torso_id}) has not been loaded"
# head_pos will have already been loaded from the parent torso's fixed points
tail_pos[j] = head_pos[j] + Vector((1,0,0))
parent_joint_id[j] = pj
joint_ids.add(j)
is_connected[j] = False
is_limb_end[j] = False
root = head_pos[j]
k = torso.fixed_points
parts = list(zip(
torso.joint_id[:k],
torso.pts[:k]))
# Calculate an average of the torso's fixed points, and put its tail
# there instead.
if parts and torso.parent!=-1:
avg = Vector((0,0,0))
for _, pt in parts:
avg += Vector(pt)
avg = (avg/len(parts))
if avg.length>=0.25:
tail_pos[j] = root+avg
for j2, pt in parts:
assert j2 not in joint_ids, f"joint {j2} (from torso {torso_id} fixed point) already loaded"
# Each fixed point could be:
# a) another torso (e.g. Humanoid Abdomen)
# b) a limb-root (e.g. Humanoid LHip, LShldr)
# c) never mentioned again (e.g. Burrick Tail, Apparition Toe)
# So we need to ensure a full definition exists for its joint,
# even though in (a) and (b) we will overwrite half of this.
joint_ids.add(j2)
parent_joint_id[j2] = j
head_pos[j2] = root+Vector(pt)
tail_pos[j2] = head_pos[j2]+Vector((1,0,0))
is_connected[j2] = False
is_limb_end[j2] = True
for limb_id, limb in enumerate(cal.p_limbs):
j = limb.joint_id[0]
assert j in joint_ids, f"joint {j} (from limb {limb_id}) not loaded"
is_connected[j] = False
is_limb_end[j] = False
head = head_pos[j]
k = limb.segments
parts = zip(
limb.joint_id[:k+1],
limb.seg[:k] + [limb.seg[k-1]], # finger etc. bones, tail gets wrist vector
limb.seg_len[:k] + [0.25]) # finger etc. bones, get fixed length
pj = j
for i, (j, seg, seg_len) in enumerate(parts):
first = (i==0)
last = (i==limb.segments)
head_pos[j] = head
tail = head+(seg_len*Vector(seg))
tail_pos[j] = tail
head = tail
if not first:
assert j not in joint_ids, f"joint {j} (from limb {limb_id} segment {i}) already loaded"
joint_ids.add(j)
parent_joint_id[j] = pj
is_connected[j] = True
is_limb_end[j] = last
pj = j
# Build a dummy skeleton first, to get its topology value; then look
# for a matching topology in the predefined list.
dummy_sk = DarkSkeleton("Dummy", [
( j, "Dummy", parent_joint_id[j], is_connected[j],
head_pos[j], tail_pos[j], is_limb_end[j] )
for j in joint_ids])
topo = dummy_sk.topology()
matching_sk = None
for sk in SKELETONS.values():
if topo==sk.topology():
matching_sk = sk
break
joint_name = [str(i) for i in range(MAX_JOINT_COUNT)]
if matching_sk:
skeleton_name = sk.name
for (j, name, pj, conn, head, tail, limb_end) in sk:
joint_name[j] = name
else:
# Import the skeleton anyway, but warn about it.
if report_fn:
report_fn({'WARNING'}, 'Did not recognise skeleton topology')
skeleton_name = "UnrecognisedSkeleton"
# Build the skeleton again, now with the right name and joint names.
joint_info = [
( j, joint_name[j], parent_joint_id[j], is_connected[j],
head_pos[j], tail_pos[j], is_limb_end[j] )
for j in joint_ids]
return DarkSkeleton(skeleton_name, joint_info)
def do_import_cal(context, cal_filename):
sk = DarkSkeleton.from_cal(cal_filename)
arm_obj = create_armature_from_skeleton(sk, context)
return arm_obj
def do_import_mesh(context, bin_filename):
cal_filename = os.path.splitext(bin_filename)[0]+'.cal'
with open(bin_filename, 'rb') as f:
bin_data = f.read()
dump_filename = os.path.splitext(bin_filename)[0]+'.dump'
dumpf = open(dump_filename, 'w')
# Parse the .bin file
bin_view = memoryview(bin_data)
header = LGMMHeader.read(bin_view)
if header.magic != b'LGMM':
raise ValueError("File is not a .bin mesh (LGMM)")
if header.version not in (1, 2):
raise ValueError("Only version 1 and 2 .bin files are supported")
if header.layout!=0:
raise ValueError("Only material-layout (layout=0) meshes are supported")
print(f"magic: {header.magic}", file=dumpf)
print(f"version: {header.version}", file=dumpf)
print(f"radius: {header.radius:f}", file=dumpf)
print(f"flags: {header.flags:04x}", file=dumpf)
print(f"app_data: {header.app_data:04x}", file=dumpf)
print(f"layout: {header.layout}", file=dumpf)
print(f"segs: {header.segs}", file=dumpf)
print(f"smatrs: {header.smatrs}", file=dumpf)
print(f"smatsegs: {header.smatsegs}", file=dumpf)
print(f"pgons: {header.pgons}", file=dumpf)
print(f"verts: {header.verts}", file=dumpf)
print(f"weights: {header.weights}", file=dumpf)
print(f"map_off: {header.map_off:08x}", file=dumpf)
print(f"seg_off: {header.seg_off:08x}", file=dumpf)
print(f"smatr_off: {header.smatr_off:08x}", file=dumpf)
print(f"smatseg_off: {header.smatseg_off:08x}", file=dumpf)
print(f"pgon_off: {header.pgon_off:08x}", file=dumpf)
print(f"norm_off: {header.norm_off:08x}", file=dumpf)
print(f"vert_vec_off: {header.vert_vec_off:08x}", file=dumpf)
print(f"vert_uvn_off: {header.vert_uvn_off:08x}", file=dumpf)
print(f"weight_off: {header.weight_off:08x}", file=dumpf)
print(file=dumpf)
# TODO: does this match number of segs? smatrs? anything?
map_count = header.seg_off-header.map_off
print(f"maps: {map_count}", file=dumpf)
p_maps = StructView(bin_view, uint8, offset=header.map_off, count=map_count)
p_segs = StructView(bin_view, LGMMSegment, offset=header.seg_off, count=header.segs)
p_smatrs = StructView(bin_view, (LGMMSMatrV2 if header.version==2 else LGMMSMatrV1),
offset=header.smatr_off, count=header.smatrs)
p_smatsegs = StructView(bin_view, LGMMSmatSeg, offset=header.smatseg_off, count=header.smatsegs)
p_pgons = StructView(bin_view, LGMMPolygon, offset=header.pgon_off, count=header.pgons)
p_norms = StructView(bin_view, LGVector, offset=header.norm_off, count=header.pgons) # TODO: is count correct??
p_verts = StructView(bin_view, LGVector, offset=header.vert_vec_off, count=header.verts)
p_uvnorms = StructView(bin_view, LGMMUVNorm, offset=header.vert_uvn_off, count=header.verts)
p_weights = StructView(bin_view, float32, offset=header.weight_off, count=header.weights)
print("BIN:", file=dumpf)
print("Segments", file=dumpf)
for i, seg in enumerate(p_segs):
print(f" Seg {i}:", file=dumpf)
print(f" bbox: {seg.bbox}", file=dumpf)
print(f" joint_id: {seg.joint_id}", file=dumpf)
print(f" smatsegs: {seg.smatsegs}", file=dumpf)
print(f" map_start: {seg.map_start}", file=dumpf)
print(f" flags: {seg.flags}", file=dumpf)
print(f" pgons: {seg.pgons}", file=dumpf)
print(f" pgon_start: {seg.pgon_start}", file=dumpf)
print(f" verts: {seg.verts}", file=dumpf)
print(f" vert_start: {seg.vert_start}", file=dumpf)
print(f" weight_start: {seg.weight_start}", file=dumpf)
print("Smatrs", file=dumpf)
for i, smatr in enumerate(p_smatrs):
print(f" Smatr {i}:", file=dumpf)
print(f" name: {smatr.name}", file=dumpf)
print(f" caps: {smatr.caps}", file=dumpf)
print(f" alpha: {smatr.alpha}", file=dumpf)
print(f" self_illum: {smatr.self_illum}", file=dumpf)
print(f" for_rent: {smatr.for_rent}", file=dumpf)
print(f" handle: {smatr.handle}", file=dumpf)
print(f" uv: {smatr.uv}", file=dumpf)
print(f" mat_type: {smatr.mat_type}", file=dumpf)
print(f" smatsegs: {smatr.smatsegs}", file=dumpf)
print(f" map_start: {smatr.map_start}", file=dumpf)
print(f" flags: {smatr.flags}", file=dumpf)
print(f" pgons: {smatr.pgons}", file=dumpf)
print(f" pgon_start: {smatr.pgon_start}", file=dumpf)
print(f" verts: {smatr.verts}", file=dumpf)
print(f" vert_start: {smatr.vert_start}", file=dumpf)
print(f" weight_start: {smatr.weight_start}", file=dumpf)
print(f" pad: {smatr.pad}", file=dumpf)
print("SmatSegs", file=dumpf)
for i, smatseg in enumerate(p_smatsegs):
print(f" Smatseg {i}:", file=dumpf)
print(f" pgons: {smatseg.pgons}", file=dumpf)
print(f" pgon_start: {smatseg.pgon_start}", file=dumpf)
print(f" verts: {smatseg.verts}", file=dumpf)
print(f" vert_start: {smatseg.vert_start}", file=dumpf)
print(f" weight_start: {smatseg.weight_start}", file=dumpf)
print(f" pad: {smatseg.pad}", file=dumpf)
print(f" smatr_id: {smatseg.smatr_id}", file=dumpf)
print(f" seg_id: {smatseg.seg_id}", file=dumpf)
print(file=dumpf)
print("Maps:", file=dumpf)
for i, m in enumerate(p_maps):
print(f" {i}: {m}", file=dumpf)
print("Pgons:", file=dumpf)
for i, p in enumerate(p_pgons):
print(f" {i}: verts {p.vert[0]},{p.vert[1]},{p.vert[2]}; smatr {p.smatr_id}; norm: {p.norm}, d: {p.d}", file=dumpf)
print("Verts:", file=dumpf)
for i, v in enumerate(p_verts):
print(f" {i}: {v.x},{v.y},{v.z}", file=dumpf)
print("Norms:", file=dumpf)
for i, n in enumerate(p_norms):
print(f" {i}: {n.x},{n.y},{n.z}", file=dumpf)
print("UVNorms:", file=dumpf)
for i, n in enumerate(p_uvnorms):
print(f" {i}: {n.u},{n.v}; norm {n.norm}", file=dumpf)
print("Weights:", file=dumpf)
for i, w in enumerate(p_weights):
print(f" {i}: {w}", file=dumpf)
# TODO: we are still dumping the .cal here for convenience, but get rid
# of this later
cal = LGCALFile(cal_filename)
cal.dump(dumpf)
dumpf.close()
# Read the skeleton from the .cal
sk = DarkSkeleton.from_cal(cal_filename)
# test: check that only stretchy segments have pgons in their smatsegs:
# UNTRUE! segment 9 (head) is non-stretchy, but has 30 pgons!
# however, i still dont think it matters, for hardware rendering?
for seg_id, seg in enumerate(p_segs):
is_stretchy = bool(seg.flags & 1)
map_start = seg.map_start
map_end = map_start+seg.smatsegs
for smatseg_id in p_maps[map_start:map_end]:
smatseg = p_smatsegs[smatseg_id]
if is_stretchy:
print(f"stretchy seg {seg_id}, smatseg {smatseg_id} has {smatseg.pgons} pgons")
else:
print(f"non-stretchy seg {seg_id} smatseg {smatseg_id} has {smatseg.pgons} pgons")
# Build segment/material/joint tables for later lookup
segment_by_vert_id = {}
smatseg_by_vert_id = {}
material_by_vert_id = {}
joint_by_vert_id = {}
for mi, smatr in enumerate(p_smatrs):
print(f"smatr {mi}: {smatr.name!r}, {smatr.pgons} pgons, {smatr.verts} verts")
map_start = smatr.map_start
map_end = map_start+smatr.smatsegs
for smatseg_id in p_maps[map_start:map_end]:
smatseg = p_smatsegs[smatseg_id]
seg = p_segs[smatseg.seg_id]
vert_start = smatseg.vert_start
vert_end = vert_start+smatseg.verts
for vi in range(vert_start, vert_end):
assert vi not in segment_by_vert_id
segment_by_vert_id[vi] = smatseg.seg_id
assert vi not in smatseg_by_vert_id
smatseg_by_vert_id[vi] = smatseg_id
assert vi not in material_by_vert_id
material_by_vert_id[vi] = smatseg.smatr_id
assert vi not in joint_by_vert_id
joint_by_vert_id[vi] = seg.joint_id
# Build the bare mesh
vertices = [Vector(v) for v in p_verts]
# Offset each vert by the joint its attached to
joint_pos = {j: head
for (j, name, pj, conn, head, tail, limb_end) in sk}
assert len(joint_by_vert_id)==len(p_verts)
for i in range(len(vertices)):
v = vertices[i]
j = joint_by_vert_id[i]
head = joint_pos[j]
vertices[i] = head+v
faces = [tuple(p.vert) for p in p_pgons]
name = f"TEST"
mesh = bpy.data.meshes.new(f"{name} mesh")
mesh.from_pydata(vertices, [], faces)
mesh.validate(verbose=True)
print(f"mesh vertices: {len(mesh.vertices)}, loops: {len(mesh.loops)}, polygons: {len(mesh.polygons)}")
# BUG: if we use the collection returned from .new(), then we sometimes get
# a RuntimeError: "bpy_prop_collection[index]: internal error, valid index
# X given in Y sized collection, but value not found" -- so we create the
# collections first, then look them up to use them.
mesh.vertex_colors.new(name="SmatSegCol", do_init=False)
mesh.vertex_colors.new(name="SegCol", do_init=False)
mesh.vertex_colors.new(name="MatCol", do_init=False)
mesh.vertex_colors.new(name="JointCol", do_init=False)
mesh.vertex_colors.new(name="StretchyCol", do_init=False)
mesh.vertex_colors.new(name="WeightCol", do_init=False)
mesh.vertex_colors.new(name="UVCol", do_init=False)
smatseg_colors = mesh.vertex_colors["SmatSegCol"]
seg_colors = mesh.vertex_colors["SegCol"]
mat_colors = mesh.vertex_colors["MatCol"]
joint_colors = mesh.vertex_colors["JointCol"]
stretchy_colors = mesh.vertex_colors["StretchyCol"]
weight_colors = mesh.vertex_colors["WeightCol"]
uv_colors = mesh.vertex_colors["UVCol"]
for li, loop in enumerate(mesh.loops):
vi = loop.vertex_index
smatseg_colors.data[li].color = id_color( smatseg_by_vert_id[vi] )
seg_colors.data[li].color = id_color( segment_by_vert_id[vi] )
mat_colors.data[li].color = id_color( material_by_vert_id[vi] )
joint_colors.data[li].color = id_color( joint_by_vert_id[vi] )
seg = p_segs[ segment_by_vert_id[vi] ]
is_stretchy = bool(seg.flags & 1)
stretchy_colors.data[li].color = id_color(0) if is_stretchy else id_color(1)
uvn = p_uvnorms[vi]
uv_colors.data[li].color = (float(uvn.u),float(uvn.v),0.0,1.0)
# Create the object
mesh_obj = create_object(name, mesh, Vector((0,0,0)), context=context)
# Create vertex groups for each joint, with matching name
print("Vertex groups:")
joint_name = [str(i) for i in range(MAX_JOINT_COUNT)]
for (j, name, pj, conn, head, tail, limb_end) in sk:
joint_name[j] = name
weight_by_vert_id = {}
for seg_id, seg in enumerate(p_segs):
print(f" seg {seg_id} flags {seg.flags} smatsegs {seg.smatsegs}")
j = seg.joint_id
is_stretchy = bool(seg.flags & 1)
group_name = joint_name[j]
try:
group = mesh_obj.vertex_groups[group_name]
except KeyError:
group = mesh_obj.vertex_groups.new(name=group_name)
# TODO: do we need to do this same collection dance?
#group = mesh_obj.vertex_groups[group_name]
map_start = seg.map_start
map_end = map_start+seg.smatsegs
print(f" map_start: {map_start}, map_end: {map_end}")
for smatseg_id in p_maps[map_start:map_end]:
print(f" smatseg {smatseg_id}")
smatseg = p_smatsegs[smatseg_id]
for i in range(smatseg.verts):
vi = smatseg.vert_start+i
print(f" vert {vi}")
# OKAY, so this is wrong. but why?
# by definition a 'stretchy' area should have
# weights for _two_ different bones, right? but not
# in this format! each smatseg belongs to _one_ segment,
# i.e. one joint. so what delimits this?
# from the code it looks like the parent bone transform
# gets applied, then the child bone transform gets applied
# _with weighting_. in blender weight terms, i am not sure
# if this should be interpreted as vertex weights:
# parent bone: 1.0
# child bone: weight
# or as vertex weights:
# parent bone: 1.0-weight
# child bone: weight
# TODO: compare extreme poses in game and in blender to
# compare how each strategy places the stretchy vertices.
if is_stretchy:
wi = smatseg.weight_start+i
print(f" weight {wi}")
weight = p_weights[wi]
weight_by_vert_id[vi] = weight # TODO just for weight debugging
else:
weight = 1.0
group.add([vi], weight, 'REPLACE')
for li, loop in enumerate(mesh.loops):
vi = loop.vertex_index
if vi in weight_by_vert_id:
w = weight_by_vert_id[vi]
weight_colors.data[li].color = (w,w,w,1.0)
else:
weight_colors.data[li].color = (1.0,0.0,0.0,1.0)
# Smatr vertex groups
print("Smatr Vertex groups:")
for smatr_id, smatr in enumerate(p_smatrs):
group_name = f"Smatr{smatr_id}"
try:
group = mesh_obj.vertex_groups[group_name]
except KeyError:
group = mesh_obj.vertex_groups.new(name=group_name)
for i in range(smatr.verts):
vi = smatr.vert_start+i
group.add([vi], 1.0, 'REPLACE')
# Seg vertex groups
print("Seg Vertex groups:")
for seg_id, seg in enumerate(p_segs):
group_name = f"Seg{seg_id}"
try:
group = mesh_obj.vertex_groups[group_name]
except KeyError:
group = mesh_obj.vertex_groups.new(name=group_name)
map_start = seg.map_start
map_end = map_start+seg.smatsegs
print(f" map_start: {map_start}, map_end: {map_end}")
for smatseg_id in p_maps[map_start:map_end]:
smatseg = p_smatsegs[smatseg_id]
for i in range(smatseg.verts):
vi = smatseg.vert_start+i
group.add([vi], 1.0, 'REPLACE')
# SmatSmeg vertex groups
print("SmatSmeg Vertex groups:")
for smatseg_id, smatseg in enumerate(p_smatsegs):
group_name = f"SmatSmeg{smatseg_id}"
try:
group = mesh_obj.vertex_groups[group_name]
except KeyError:
group = mesh_obj.vertex_groups.new(name=group_name)
for i in range(smatseg.verts):
vi = smatseg.vert_start+i
group.add([vi], 1.0, 'REPLACE')
# Create the armature
arm_obj = create_armature_from_skeleton(sk, context)
# Add an armature modifier
arm_mod = mesh_obj.modifiers.new(name='Armature', type='ARMATURE')
arm_mod.object = arm_obj
arm_mod.use_vertex_groups = True
context.view_layer.objects.active = mesh_obj
return mesh_obj
#---------------------------------------------------------------------------#
# Export
def do_export_mesh(context, mesh_obj, bin_filename):
cal_filename = os.path.splitext(bin_filename)[0]+'.cal'
dump_filename = os.path.splitext(bin_filename)[0]+'.export_dump'
dumpf = open(dump_filename, 'w')
# TODO: note that if we import the spider this way, the 'sac' thats in the
# .e and in the .map will just be part of the 'base' vertex group. and
# that is exactly how it should be! not relevant here ofc, just noting why
# it is not listed.
SPIDER_JOINTS = [
'base', # 0
'lmand', # 1
'lmelbow', # 2
'rmand', # 3
'rmelbow', # 4
'r1shldr', # 5
'r1elbow', # 6
'r1wrist', # 7
'r2shldr', # 8
'r2elbow', # 9
'r2wrist', # 10
'r3shldr', # 11
'r3elbow', # 12
'r3wrist', # 13
'r4shldr', # 14
'r4elbow', # 15
'r4wrist', # 16
'l1shldr', # 17
'l1elbow', # 18
'l1wrist', # 19
'l2shldr', # 20
'l2elbow', # 21
'l2wrist', # 22
'l3shldr', # 23
'l3elbow', # 24
'l3wrist', # 25
'l4shldr', # 26
'l4elbow', # 27
'l4wrist', # 28
'r1finger', # 29
'r2finger', # 30
'r3finger', # 31
'r4finger', # 32
'l1finger', # 33
'l2finger', # 34
'l3finger', # 35
'l4finger', # 36
'ltip', # 37
'rtip', # 38
]
SPIDER_JOINT_INDICES = {name: j
for j, name in enumerate(SPIDER_JOINTS)}
arm_mod = [mod for mod in mesh_obj.modifiers if mod.type == 'ARMATURE'][0]
arm_obj = arm_mod.object
arm = arm_obj.data.copy()
arm.pose_position = 'REST'
mesh = mesh_obj.data.copy()
mesh.calc_loop_triangles()
# TODO: smoothing amount?
mesh.calc_normals_split()
# TODO: verify that the armature matches the hardcoded skeleton!
# (optionally omitting trailing chains of bones)
bone_head_pos = [(0.0,0.0,0.0) for j in SPIDER_JOINTS]
bone_directions = [(1.0,0.0,0.0) for j in SPIDER_JOINTS]
bone_lengths = [(1.0,0.0,0.0) for j in SPIDER_JOINTS]
for b in arm.bones:
ji = SPIDER_JOINTS.index(b.name)
bone_head_pos[ji] = tuple(Vector(arm_obj.location)+Vector(b.head_local))
d = (Vector(b.tail_local)-Vector(b.head_local)).normalized()
bone_directions[ji] = tuple(d)
bone_lengths[ji] = b.length
vertex_group_joint_ids = [
SPIDER_JOINT_INDICES.get(g.name.lower(), 0)
for g in mesh_obj.vertex_groups]
# TODO: ensure one uv layer
# Vectors are all kinds of weird (only sometimes hashable), so
# just keep everything as tuples unless we are doing maths on it!
# TODO: actually get actual material info from the object!
material_temp = []
material_temp.append("fake")
# Vertex attributes, one entry per split vertex. For now these are not in
# final sorted order, so we call these indices u[nsorted]v[ertex]i[index].
vertex_pos = []
vertex_normal = []
vertex_uv = []
vertex_material_id = []
vertex_joint_id = []
vertex_weight = []
# Polygon attributes, one entry per triangle.
poly_vertex_ids = []
poly_material_id = []
poly_normal = []
poly_distance = []
# Lookup table for keeping track of split vertices.
vertex_tuples = {}
# Cache some attribute lookups.
mesh_vertices = mesh.vertices
mesh_uvloops = mesh.uv_layers[0].data
for tri in mesh.loop_triangles:
tri_vertex_ids = []
for i in range(3):
# Gather vertex attributes.
vertex_index = tri.vertices[i]
mesh_vert = mesh_vertices[vertex_index]
world_pos = tuple(mesh_vert.co)
normal = tuple(tri.split_normals[i])
uv = tuple(mesh_uvloops[ tri.loops[i] ].uv)
material_id = tri.material_index # TODO: handle materials!
# Split a vertex if it has multiple materials, uvs or split normals.
tup = (vertex_index, uv, material_id, normal)
uvi = vertex_tuples.get(tup, -1)
if uvi==-1:
uvi = len(vertex_pos)
# Determine the joint for this vertex from its vertex groups.
group_count = len(mesh_vert.groups)
if group_count == 0:
joint_id = 0
weight = 1.0
elif group_count == 1:
g = mesh_vert.groups[0]
joint_id = vertex_group_joint_ids[g.group]
weight = g.weight # TODO: double-check if this is correct weight handling!
elif group_count == 2:
g0 = mesh_vert.groups[0]
g1 = mesh_vert.groups[1]
# TODO: only allow this if one group is the parent (with weight 1.0)
# and the other is the child (with whatever weight); then this
# will be a stretchy vertex!
raise NotImplementedError("Stretchy vertices not yet implemented")
else:
raise ValueError(f"Vertex {vertex_index} is in more than 2 vertex groups")
# vertex positions must be relative to the bone they belong to.
# (TODO: confirm they are in local-world-space, not bone-space)
pos = Vector(world_pos)-Vector(bone_head_pos[ji])
vertex_pos.append(pos)
vertex_normal.append(normal)
vertex_uv.append(uv)
vertex_material_id.append(material_id) # TODO: handle materials!
vertex_joint_id.append(joint_id)
vertex_weight.append(weight)
vertex_tuples[tup] = uvi
# Add this vertex to the polygon
tri_vertex_ids.append(uvi)
# Gather polygon attributes.
material_id = tri.material_index # TODO: handle materials!
normal = tuple(tri.normal)
distance = tri.center.length
poly_vertex_ids.append(tuple(tri_vertex_ids))
poly_material_id.append(material_id)
poly_normal.append(normal)
poly_distance.append(distance)
del vertex_tuples
del mesh_vertices
del mesh_uvloops
# From here on out, we are working with our arrays of data, and don't use
# any more Blender objects (except for Vectors that we construct).
print(file=dumpf)
print("MATERIALS:", file=dumpf)
for mi, (name) \
in enumerate(material_temp):
print(f" {mi}: name {name}", file=dumpf)
print("VERTICES:", file=dumpf)
for vi, (pos, normal, uv, material_id, joint_id, weight) \
in enumerate(zip(vertex_pos, vertex_normal, vertex_uv, vertex_material_id, vertex_joint_id, vertex_weight)):
print(f" {vi}: mat {material_id}; joint_id {joint_id}", file=dumpf)
#print(f" {vi}: pos {pos}; normal {normal}; uv {uv}; joint_id {joint_id}; weight {weight}", file=dumpf)
print("TRIANGLES:", file=dumpf)
for pi, (vertex_ids, material_id, normal, distance) \
in enumerate(zip(poly_vertex_ids, poly_material_id, poly_normal, poly_distance)):
print(f" {pi}: vertex_ids {vertex_ids}; material_id {material_id}; normal {normal}; distance {distance}", file=dumpf)
print(file=dumpf)
print(f"{len(material_temp)} materials", file=dumpf)
print(f"{len(vertex_pos)} vertices", file=dumpf)
print(f"{len(poly_vertex_ids)} triangles", file=dumpf)
print(file=dumpf)
dumpf.flush()
# Vertices need to be sorted by material, then joint id, so that all the
# verts in a smatr and in a smatseg are contiguous.
#
# TODO: this is not taking into account stretchy vertices, which need their
# own sort flag!
#
# Sort all the vertex attributes together.
unsorted_vertex_ids = list(range(len(vertex_pos)))
temp = sorted(zip(vertex_material_id, vertex_joint_id, unsorted_vertex_ids,
vertex_pos, vertex_normal, vertex_uv, vertex_weight))
(vertex_material_id, vertex_joint_id, unsorted_vertex_ids,
vertex_pos, vertex_normal, vertex_uv, vertex_weight) = zip(*temp)
# Rewrite the polygon vertex ids with the sorted ids.
vi_from_uvi = [-1]*len(unsorted_vertex_ids)
for vi, uvi in enumerate(unsorted_vertex_ids):
vi_from_uvi[uvi] = vi
for pi in range(len(poly_vertex_ids)):
poly_vertex_ids[pi] = tuple(vi_from_uvi[uvi] for uvi in poly_vertex_ids[pi])
# Polygons need to be sorted by material, so that all pgons in a smatr are
# also contiguous.
# TODO: stretchy smatsegs also need to reference their pgons in a contiguous
# group! this implies: no poly can be part of two stretchy smatsegs;
# (although a stretchy joint can have multiple smatsegs; see mecsub03.bin
# for an example where the neck and breathing tube are different materials
# but both part of the stretchy neck segment). note however that you
# _could_ allow polys to be in multiple stretchy smatsegs if you kept
# subdividing them into more smatsegs until the polys were contiguous...
unsorted_poly_ids = list(range(len(poly_vertex_ids)))
temp = sorted(zip(poly_material_id, unsorted_poly_ids,
poly_vertex_ids, poly_normal, poly_distance))
(poly_material_id, unsorted_poly_ids,
poly_vertex_ids, poly_normal, poly_distance) = zip(*temp)
# TODO: more figuring out what needs to be done to properly output stretchy
# smatsegs!
# TODO: could compact the normals table here, to eliminate duplicates.
# probably only a tiny space savings though.
# TEMP: test the grouping looks okay?
vi = 0; vi_end = len(vertex_pos)
pi = 0; pi_end = len(poly_vertex_ids)
smatseg_id = 0
mi = 0
ji = 0
while True:
print(f"smatsmeg {smatseg_id}:", file=dumpf)
print(f" start at vi {vi}, pi {pi}", file=dumpf)
# Advance to the next change in vertex material/joint:
while (vi<vi_end
and vertex_material_id[vi]==mi
and vertex_joint_id[vi]==ji):
vi += 1
# Advance to the next change in polygon material/joint:
# TODO: need to sort polys by material (and joint??) first!
# while (pi<pi_end
# and poly_material_id[vi]==mi
# and poly_joint_id[vi]==ji):
# vi += 1
# TODO: rather than this weird awkward doublestep, maybe we
# could store poly indices with the verts? that way the polys would
# get the right sorting order too?? unsure.
print(f" end at vi {vi}, pi {pi}", file=dumpf)
if vi==vi_end: break
# Next smatseg begins with the next material/joint
mi = vertex_material_id[vi]
ji = vertex_joint_id[vi]
smatseg_id += 1
if smatseg_id>10000: raise RuntimeError("Whoa boy, you screwed up!")
print(file=dumpf)
dumpf.flush()
# From here we build up the file-specific data formats.
vert_count = len(vertex_pos)
pgon_count = len(poly_vertex_ids)
verts = [
LGVector(vertex_pos[vi])
for vi in range(vert_count)
]
uvnorms = [
LGMMUVNorm(values=(
vertex_uv[vi][0],
vertex_uv[vi][1],
pack_normal(vertex_normal[vi])))
for vi in range(vert_count)
]
pgons = [
LGMMPolygon(values=(
poly_vertex_ids[pi],
poly_material_id[pi],
poly_distance[pi],
pi,
0))
for pi in range(pgon_count)
]
norms = [
LGVector(poly_normal[pi])
for pi in range(pgon_count)
]
print("VERTS:", file=dumpf)
for i, v in enumerate(verts):
print(f" {i}: {v.x},{v.y},{v.z}", file=dumpf)
print("UVNORMS:", file=dumpf)
for i, uvn in enumerate(uvnorms):
print(f" {i}: {uvn.u},{uvn.v},{uvn.norm:08x}", file=dumpf)
print("NORMS:", file=dumpf)
for i, n in enumerate(norms):
print(f" {i}: {n.x},{n.y},{n.z}", file=dumpf)
print("PGONS:", file=dumpf)
for i, p in enumerate(pgons):
print(f" {i}:", file=dumpf)
print(f" vert0: {p.vert[0]}", file=dumpf)
print(f" vert1: {p.vert[1]}", file=dumpf)
print(f" vert2: {p.vert[2]}", file=dumpf)
print(f" smatr_id: {p.smatr_id}", file=dumpf)
print(f" d: {p.d}", file=dumpf)
print(f" norm: {p.norm}", file=dumpf)
raise NotImplementedError("rewrite in progress up to here")
# HERE: ...
# TEMP: test the grouping looks okay?
smatsegs = []
grouped_vis = itertools.groupby(range(vert_count),
key=lambda vi: (vertex_material_id[vi], vertex_joint_id[vi]))
for (mi, ji), group in grouped_vis:
smatseg_id = len(smatsegs)
smatseg = LGMMSmatSeg()
smatseg.pgons = uint16(0)
smatseg.pgon_start = uint16(0)
smatseg.verts = uint16(len(smatseg_source_verts))
smatseg.vert_start = uint16(smatseg_source_verts[0].vert_id)
smatseg.weight_start = uint16(0) # TODO: smatsegs of stretchy segs need weights
smatseg.smatr_id = uint16(0) # TODO: do materials
smatseg.seg_id = uint16(smatseg_id) # TODO: if there are multiple materials, or
mi = 0
ji = 0
while True:
print(f"smatsmeg {smatseg_id}:", file=dumpf)
print(f" start at vi {vi}, pi {pi}", file=dumpf)
# Advance to the next change in vertex material/joint:
while (vi<vi_end
and vertex_material_id[vi]==mi
and vertex_joint_id[vi]==ji):
vi += 1
# Advance to the next change in polygon material/joint:
# TODO: need to sort polys by material (and joint??) first!
# while (pi<pi_end
# and poly_material_id[vi]==mi
# and poly_joint_id[vi]==ji):
# vi += 1
# TODO: rather than this weird awkward doublestep, maybe we
# could store poly indices with the verts? that way the polys would
# get the right sorting order too?? unsure.
print(f" end at vi {vi}, pi {pi}", file=dumpf)
if vi==vi_end: break
# Next smatseg begins with the next material/joint
mi = vertex_material_id[vi]
ji = vertex_joint_id[vi]
smatseg_id += 1
if smatseg_id>10000: raise RuntimeError("Whoa boy, you screwed up!")
print(file=dumpf)
dumpf.flush()
smatsegs = []
for smatseg_id, (sort_key, smatseg_source_verts) \
in enumerate(itertools.groupby(source_verts, key=SourceVert.sort_key)):
temp_mat_id = sort_key[0]
group_id = sort_key[1]
group_name = mesh_obj.vertex_groups[group_id].name
bone_head = bone_head_pos[group_name]
smatseg_source_verts = list(smatseg_source_verts)
print(f"Smatseg {smatseg_id}: material {temp_mat_id}, vertex group {group_id}", file=dumpf)
smatseg = LGMMSmatSeg()
smatseg.pgons = uint16(0)
smatseg.pgon_start = uint16(0)
smatseg.verts = uint16(len(smatseg_source_verts))
smatseg.vert_start = uint16(smatseg_source_verts[0].vert_id)
smatseg.weight_start = uint16(0) # TODO: smatsegs of stretchy segs need weights
smatseg.smatr_id = uint16(0) # TODO: do materials
smatseg.seg_id = uint16(smatseg_id) # TODO: if there are multiple materials, or
# stretchy segs, then this cannot be 1:1
smatsegs.append(smatseg)
for source_vert in smatseg_source_verts:
vi = source_vert.vert_id
pos = Vector((verts[vi].x,verts[vi].y,verts[vi].z))
local_pos = pos - bone_head
verts[vi] = LGVector(values=local_pos)
# TODO: do we want to use undeformed_co? or do we want to ensure that
# the armature is in rest pose for the export? (cause there might
# reasonably be other modifiers that we _do_ want to have affecting
# the mesh!
pos = source_vert.mesh_vert.co
print(f" {vi}: mesh_vert_id {source_vert.mesh_vert_id} at {pos[0]},{pos[1]},{pos[2]}", file=dumpf)
# TODO: if there are multiple materials, or
# stretchy segs, then this cannot be 1:1
segs = []
for seg_id, (sort_key, seg_source_verts) \
in enumerate(itertools.groupby(source_verts, key=SourceVert.sort_key)):
temp_mat_id = sort_key[0]
group_id = sort_key[1]
group_name = mesh_obj.vertex_groups[group_id].name
smatseg_source_verts = list(smatseg_source_verts)
joint_id = SPIDER_JOINTS.index(group_name)
seg = LGMMSegment()
seg.joint_id = uint8(joint_id)
seg.smatsegs = uint8(1) # TODO: fix this when we do materials and stretchies
seg.map_start = uint8(seg_id) # TODO: fix this when we do materials and stretchies
seg.flags = uint8(0) # TODO: fix this for stretchies
seg.pgons = uint16(0) # no stretchies and only hardware rendering, so we ignore this
seg.pgon_start = uint16(0) # ditto
seg.verts = uint16(0) # No verts for material-first layout
seg.vert_start = uint16(0)
seg.weight_start = uint16(0) # TODO: support weights for stretchies
segs.append(seg)
smatrs = []
# TODO: dont hardcode 1 material!
smatr = LGMMSMatrV2()
smatr.name = bytes16(b'face.png\x00\x00\x00\x00\x00\x00\x00\x00')
smatr.caps = uint32(0)
smatr.alpha = float32(1.0) # TODO: i think this is 1.0 for opaque?
smatr.self_illum = float32(0.0)
smatr.for_rent = uint32(0.0)
smatr.handle = uint32(0)
smatr.uv = float32(1.0) # TODO: i think this is uv scale?
smatr.mat_type = uint8(0)
smatr.smatsegs = uint8(len(smatsegs))
smatr.map_start = uint8(0) # maps for materials are just smatseg indices in order
smatr.flags = uint8(0) # TODO: what are these flags?
smatr.pgons = uint16(len(pgons))
smatr.pgon_start = uint16(0)
smatr.verts = uint16(len(verts))
smatr.vert_start = uint16(0)
smatr.weight_start = uint16(0)
smatrs.append(smatr)
maps = [uint8(i) for i in range(len(smatsegs))]
print("Segments", file=dumpf)
for i, seg in enumerate(segs):
print(f" Seg {i}:", file=dumpf)
print(f" bbox: {seg.bbox}", file=dumpf)
print(f" joint_id: {seg.joint_id}", file=dumpf)
print(f" smatsegs: {seg.smatsegs}", file=dumpf)
print(f" map_start: {seg.map_start}", file=dumpf)
print(f" flags: {seg.flags}", file=dumpf)
print(f" pgons: {seg.pgons}", file=dumpf)
print(f" pgon_start: {seg.pgon_start}", file=dumpf)
print(f" verts: {seg.verts}", file=dumpf)
print(f" vert_start: {seg.vert_start}", file=dumpf)
print(f" weight_start: {seg.weight_start}", file=dumpf)
print("Smatrs", file=dumpf)