forked from Befzz/blender3d_import_psk_psa
-
Notifications
You must be signed in to change notification settings - Fork 1
/
io_import_scene_unreal_psa_psk_400.py
2360 lines (1769 loc) · 82.3 KB
/
io_import_scene_unreal_psa_psk_400.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
bl_info = {
"name": "Import Unreal Skeleton Mesh (.psk)/Animation Set (.psa) (280)",
"author": "Darknet, flufy3d, camg188, befzz",
"version": (2, 8, 2),
"blender": (4, 0, 0),
"location": "File > Import > Skeleton Mesh (.psk)/Animation Set (.psa) OR View3D > Tool Shelf (key T) > Misc. tab",
"description": "Import Skeleton Mesh / Animation Data",
"warning": "",
"wiki_url": "https://github.com/Befzz/blender3d_import_psk_psa",
"category": "Import-Export",
"tracker_url": "https://github.com/Befzz/blender3d_import_psk_psa/issues"
}
"""
Version': '2.0' ported by Darknet
Unreal Tournament PSK file to Blender mesh converter V1.0
Author: D.M. Sturgeon (camg188 at the elYsium forum), ported by Darknet
Imports a *psk file to a new mesh
-No UV Texutre
-No Weight
-No Armature Bones
-No Material ID
-Export Text Log From Current Location File (Bool )
"""
"""
Version': '2.7.*' edited by befzz
Github: https://github.com/Befzz/blender3d_import_psk_psa
- Pskx support
- Animation import updated (bone orientation now works)
- Skeleton import: auto-size, auto-orient bones
- UVmap, mesh, weights, etc. import revised
- Extra UVs import
- No Scale support. (no test material)
- No smoothing groups (not exported by umodel)
"""
"""
Version': '2.8.0' edited by floxay
- Vertex normals import (VTXNORMS chunk)
(requires custom UEViewer build /at the moment/)
"""
"""
Version': '2.8.1' edited by Half
- Morph targets import (MRPHINFO and MRPHDATA chunks)
"""
"""
Version': '2.8.2' edited by Ka1serM
- Blender 4.1 smoothing
"""
# https://github.com/gildor2/UModel/blob/master/Exporters/Psk.h
import bpy
import re
from mathutils import Vector, Matrix, Quaternion
from bpy.props import (FloatProperty,
StringProperty,
BoolProperty,
EnumProperty,
PointerProperty )
from struct import unpack, unpack_from, Struct
import time
#DEV
# from mathutils import *
# from math import *
def util_obj_link(context, obj):
# return bpy.context.scene_collection.objects.link(obj)
# bpy.context.view_layer.collections[0].collection.objects.link(obj)
# return bpy.context.collection.objects.link(obj)
# bpy.data.scenes[0].collection.objects.link(obj)
context.collection.objects.link(obj)
def util_obj_select(context, obj, action = 'SELECT'):
# if obj.name in bpy.data.scenes[0].view_layers[0].objects:
if obj.name in context.view_layer.objects:
return obj.select_set(action == 'SELECT')
else:
print('Warning: util_obj_select: Object not in "context.view_layer.objects"')
def util_obj_set_active(context, obj):
# bpy.context.view_layer.objects.active = obj
# bpy.data.scenes[0].view_layers[0].objects.active = obj
context.view_layer.objects.active = obj
def util_get_scene(context):
return context.scene
def get_uv_layers(mesh_obj):
return mesh_obj.uv_layers
def obj_select_get(obj):
return obj.select_get()
def utils_set_mode(mode):
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode = mode, toggle = False)
# else:
# bpy.ops.object.mode_set(mode = mode, toggle = False)
#dev
# since names have type ANSICHAR(signed char) - using cp1251(or 'ASCII'?)
def util_bytes_to_str(in_bytes):
return in_bytes.rstrip(b'\x00').decode(encoding = 'cp1252', errors = 'replace')
class class_psk_bone:
name = ""
parent = None
bone_index = 0
parent_index = 0
# scale = []
mat_world = None
mat_world_rot = None
orig_quat = None
orig_loc = None
children = None
have_weight_data = False
# TODO simplify?
def util_select_all(select):
if select:
actionString = 'SELECT'
else:
actionString = 'DESELECT'
if bpy.ops.object.select_all.poll():
bpy.ops.object.select_all(action = actionString)
if bpy.ops.mesh.select_all.poll():
bpy.ops.mesh.select_all(action = actionString)
if bpy.ops.pose.select_all.poll():
bpy.ops.pose.select_all(action = actionString)
def util_ui_show_msg(msg):
bpy.ops.pskpsa.message('INVOKE_DEFAULT', message = msg)
PSKPSA_FILE_HEADER = {
'psk':b'ACTRHEAD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
'psa':b'ANIMHEAD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
}
def util_is_header_valid(filename, file_ext, chunk_id, error_callback):
'''Return True if chunk_id is a valid psk/psa (file_ext) 'magick number'.'''
if chunk_id != PSKPSA_FILE_HEADER[file_ext]:
error_callback(
"File %s is not a %s file. (header mismach)\nExpected: %s \nPresent %s" % (
filename, file_ext,
PSKPSA_FILE_HEADER[file_ext], chunk_id)
)
return False
return True
def util_gen_name_part(filepath):
'''Return file name without extension'''
return re.match(r'.*[/\\]([^/\\]+?)(\..{2,5})?$', filepath).group(1)
def vec_to_axis_vec(vec_in, vec_out):
'''Make **vec_out** to be an axis-aligned unit vector that is closest to vec_in. (basis?)'''
x, y, z = vec_in
if abs(x) > abs(y):
if abs(x) > abs(z):
vec_out.x = 1 if x >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1
else:
if abs(y) > abs(z):
vec_out.y = 1 if y >= 0 else -1
else:
vec_out.z = 1 if z >= 0 else -1
def calc_bone_rotation(psk_bone, bone_len, bDirectly, avg_bone_len):
children = psk_bone.children
vecy = Vector((0.0, 1.0, 0.0))
quat = Quaternion((1.0, 0.0, 0.0, 0.0))
axis_vec = Vector()
# bone with 0 children (orphan bone)
if len(children) == 0:
# Single bone. ALONE.
if psk_bone.parent == None:
return (bone_len, quat)
elif bDirectly:
# @
# axis_vec = psk_bone.orig_quat * psk_bone.orig_loc
axis_vec = psk_bone.orig_loc.copy()
axis_vec.rotate( psk_bone.orig_quat )
else:
# bone Head near parent Head?
if psk_bone.orig_loc.length < 0.1 * avg_bone_len:
# @
# vec_to_axis_vec(psk_bone.orig_quat.conjugated() * psk_bone.parent.axis_vec, axis_vec)
v = psk_bone.parent.axis_vec.copy()
v.rotate( psk_bone.orig_quat.conjugated() )
vec_to_axis_vec(v, axis_vec)
# reorient bone to other axis bychanging our base Y vec...
# this is not tested well
vecy = Vector((1.0, 0.0, 0.0))
else:
# @
# vec_to_axis_vec(psk_bone.orig_quat.conjugated() * psk_bone.parent.axis_vec, axis_vec)
v = psk_bone.parent.axis_vec.copy()
v.rotate( psk_bone.orig_quat.conjugated() )
vec_to_axis_vec(v, axis_vec)
return (bone_len, vecy.rotation_difference(axis_vec))
# bone with > 0 children BUT only 1 non orphan bone ( reorient to it! )
if bDirectly and len(children) > 1:
childs_with_childs = 0
for child in filter(lambda c: len(c.children), children):
childs_with_childs += 1
if childs_with_childs > 1:
break
candidate = child
if childs_with_childs == 1:
# print('candidate',psk_bone.name,candidate.name)
return (len(candidate.orig_loc), vecy.rotation_difference(candidate.orig_loc))
# bone with > 0 children
sumvec = Vector()
sumlen = 0
for child in children:
sumvec += (child.orig_loc)
sumlen += child.orig_loc.length
sumlen /= len(children)
sumlen = max(sumlen, 0.01)
if bDirectly:
return (sumlen, vecy.rotation_difference(sumvec))
vec_to_axis_vec(sumvec, axis_vec)
psk_bone.axis_vec = axis_vec
return (sumlen, vecy.rotation_difference(axis_vec))
def __pass(*args,**kwargs):
pass
def util_check_file_header(file, ftype):
header_bytes = file.read(32)
if len(header_bytes) < 32:
return False
if not header_bytes.startswith( PSKPSA_FILE_HEADER[ftype] ):
return False
return True
def color_linear_to_srgb(c):
"""
Convert from linear to sRGB color space.
Source: Cycles addon implementation, node_color.h.
"""
if c < 0.0031308:
return 0.0 if c < 0.0 else c * 12.92
else:
return 1.055 * pow(c, 1.0 / 2.4) - 0.055
def pskimport(filepath,
context = None,
bImportmesh = True,
bImportbone = True,
bSpltiUVdata = False,
fBonesize = 5.0,
fBonesizeRatio = 0.6,
bDontInvertRoot = True,
bReorientBones = False,
bReorientDirectly = False,
bScaleDown = True,
bToSRGB = True,
error_callback = None):
'''
Import mesh and skeleton from .psk/.pskx files
Args:
bReorientBones:
Axis based bone orientation to children
error_callback:
Called when importing is failed.
error_callback = lambda msg: print('reason:', msg)
'''
if not hasattr( error_callback, '__call__'):
# error_callback = __pass
error_callback = print
# ref_time = time.process_time()
if not bImportbone and not bImportmesh:
error_callback("Nothing to do.\nSet something for import.")
return False
print ("-----------------------------------------------")
print ("---------EXECUTING PSK PYTHON IMPORTER---------")
print ("-----------------------------------------------")
#file may not exist
try:
file = open(filepath,'rb')
except IOError:
error_callback('Error while opening file for reading:\n "'+filepath+'"')
return False
if not util_check_file_header(file, 'psk'):
error_callback('Not psk file:\n "'+filepath+'"')
return False
Vertices = None
Wedges = None
Faces = None
UV_by_face = None
Materials = None
Bones = None
Weights = None
VertexColors = None
Extrauvs = []
Normals = None
WedgeIdx_by_faceIdx = None
MorphInfos = None
MorphDeltas = None
if not context:
context = bpy.context
#==================================================================================================
# Materials MaterialNameRaw | TextureIndex | PolyFlags | AuxMaterial | AuxFlags | LodBias | LodStyle
# Only Name is usable.
def read_materials():
nonlocal Materials
Materials = []
for counter in range(chunk_datacount):
(MaterialNameRaw,) = unpack_from('64s24x', chunk_data, chunk_datasize * counter)
Materials.append( util_bytes_to_str( MaterialNameRaw ) )
#==================================================================================================
# Faces WdgIdx1 | WdgIdx2 | WdgIdx3 | MatIdx | AuxMatIdx | SmthGrp
def read_faces():
if not bImportmesh:
return True
nonlocal Faces, UV_by_face, WedgeIdx_by_faceIdx
UV_by_face = [None] * chunk_datacount
Faces = [None] * chunk_datacount
WedgeIdx_by_faceIdx = [None] * chunk_datacount
if len(Wedges) > 65536:
unpack_format = '=IIIBBI'
else:
unpack_format = '=HHHBBI'
unpack_data = Struct(unpack_format).unpack_from
for counter in range(chunk_datacount):
(WdgIdx1, WdgIdx2, WdgIdx3,
MatIndex,
AuxMatIndex, #unused
SmoothingGroup # Umodel is not exporting SmoothingGroups
) = unpack_data(chunk_data, counter * chunk_datasize)
# looks ugly
# Wedges is (point_index, u, v, MatIdx)
((vertid0, u0, v0, matid0), (vertid1, u1, v1, matid1), (vertid2, u2, v2, matid2)) = Wedges[WdgIdx1], Wedges[WdgIdx2], Wedges[WdgIdx3]
# note order: C,B,A
# Faces[counter] = (vertid2, vertid1, vertid0)
Faces[counter] = (vertid1, vertid0, vertid2)
# Faces[counter] = (vertid1, vertid2, vertid0)
# Faces[counter] = (vertid0, vertid1, vertid2)
# uv = ( ( u2, 1.0 - v2 ), ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ) )
uv = ( ( u1, 1.0 - v1 ), ( u0, 1.0 - v0 ), ( u2, 1.0 - v2 ) )
# Mapping: FaceIndex <=> UV data <=> FaceMatIndex
UV_by_face[counter] = (uv, MatIndex, (matid2, matid1, matid0))
# We need this for EXTRA UVs
WedgeIdx_by_faceIdx[counter] = (WdgIdx3, WdgIdx2, WdgIdx1)
#==================================================================================================
# Vertices X | Y | Z
def read_vertices():
if not bImportmesh:
return True
nonlocal Vertices
Vertices = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
if bScaleDown:
for counter in range( chunk_datacount ):
(vec_x, vec_y, vec_z) = unpack_data(chunk_data, counter * chunk_datasize)
Vertices[counter] = (vec_x*0.01, vec_y*0.01, vec_z*0.01)
# equal to gltf
# Vertices[counter] = (vec_x*0.01, vec_z*0.01, -vec_y*0.01)
else:
for counter in range( chunk_datacount ):
Vertices[counter] = unpack_data(chunk_data, counter * chunk_datasize)
#==================================================================================================
# Wedges (UV) VertexId | U | V | MatIdx
def read_wedges():
if not bImportmesh:
return True
nonlocal Wedges
Wedges = [None] * chunk_datacount
unpack_data = Struct('=IffBxxx').unpack_from
for counter in range( chunk_datacount ):
(vertex_id,
u, v,
material_index) = unpack_data( chunk_data, counter * chunk_datasize )
# print(vertex_id, u, v, material_index)
# Wedges[counter] = (vertex_id, u, v, material_index)
Wedges[counter] = [vertex_id, u, v, material_index]
#==================================================================================================
# Bones (VBone .. VJointPos ) Name|Flgs|NumChld|PrntIdx|Qw|Qx|Qy|Qz|LocX|LocY|LocZ|Lngth|XSize|YSize|ZSize
def read_bones():
nonlocal Bones, bImportbone
if chunk_datacount == 0:
bImportbone = False
if bImportbone:
# unpack_data = Struct('64s3i11f').unpack_from
unpack_data = Struct('64s3i7f16x').unpack_from
else:
unpack_data = Struct('64s56x').unpack_from
Bones = [None] * chunk_datacount
for counter in range( chunk_datacount ):
Bones[counter] = unpack_data( chunk_data, chunk_datasize * counter)
#==================================================================================================
# Influences (Bone Weight) (VRawBoneInfluence) ( Weight | PntIdx | BoneIdx)
def read_weights():
nonlocal Weights
if not bImportmesh:
return True
Weights = [None] * chunk_datacount
unpack_data = Struct('fii').unpack_from
for counter in range(chunk_datacount):
Weights[counter] = unpack_data(chunk_data, chunk_datasize * counter)
#==================================================================================================
# Vertex colors. R G B A bytes. NOTE: it is Wedge color.(uses Wedges index)
def read_vertex_colors():
nonlocal VertexColors
unpack_data = Struct("=4B").unpack_from
VertexColors = [None] * chunk_datacount
for counter in range( chunk_datacount ):
VertexColors[counter] = unpack_data(chunk_data, chunk_datasize * counter)
#==================================================================================================
# Extra UV. U | V
def read_extrauvs():
unpack_data = Struct("=2f").unpack_from
uvdata = [None] * chunk_datacount
for counter in range( chunk_datacount ):
uvdata[counter] = unpack_data(chunk_data, chunk_datasize * counter)
Extrauvs.append(uvdata)
#==================================================================================================
# Vertex Normals NX | NY | NZ
def read_normals():
if not bImportmesh:
return True
nonlocal Normals
Normals = [None] * chunk_datacount
unpack_data = Struct('3f').unpack_from
for counter in range(chunk_datacount):
Normals[counter] = unpack_data(chunk_data, counter * chunk_datasize)
# ==================================================================================================
# Morph Info MorphName | VertexCount
def read_morph_info():
if not bImportmesh:
return True
nonlocal MorphInfos
MorphInfos = [None] * chunk_datacount
unpack_data = Struct('=64si').unpack_from
for counter in range(chunk_datacount):
MorphInfos[counter] = unpack_data(chunk_data, counter * chunk_datasize)
# ==================================================================================================
# Morph Data PosX | PosY | PosZ | NormX | NormY | NormZ | Point Index
def read_morph_data():
if not bImportmesh:
return True
nonlocal MorphDeltas
MorphDeltas = [None] * chunk_datacount
unpack_data = Struct('6fi').unpack_from
for counter in range(chunk_datacount):
MorphDeltas[counter] = unpack_data(chunk_data, counter * chunk_datasize)
CHUNKS_HANDLERS = {
'PNTS0000': read_vertices,
'VTXW0000': read_wedges,
'VTXW3200': read_wedges,#?
'FACE0000': read_faces,
'FACE3200': read_faces,
'MATT0000': read_materials,
'REFSKELT': read_bones,
'REFSKEL0': read_bones, #?
'RAWW0000': read_weights,
'RAWWEIGH': read_weights,
'VERTEXCO': read_vertex_colors, # VERTEXCOLOR
'EXTRAUVS': read_extrauvs,
'VTXNORMS': read_normals,
'MRPHINFO': read_morph_info,
'MRPHDATA': read_morph_data
}
#===================================================================================================
# File. Read all needed data.
# VChunkHeader Struct
# ChunkID|TypeFlag|DataSize|DataCount
# 0 |1 |2 |3
while True:
header_bytes = file.read(32)
if len(header_bytes) < 32:
if len(header_bytes) != 0:
error_callback("Unexpected end of file.(%s/32 bytes)" % len(header_bytes))
break
(chunk_id, chunk_type, chunk_datasize, chunk_datacount) = unpack('20s3i', header_bytes)
chunk_id_str = util_bytes_to_str(chunk_id)
chunk_id_str = chunk_id_str[:8]
if chunk_id_str in CHUNKS_HANDLERS:
chunk_data = file.read( chunk_datasize * chunk_datacount)
if len(chunk_data) < chunk_datasize * chunk_datacount:
error_callback('Psk chunk %s is broken.' % chunk_id_str)
return False
CHUNKS_HANDLERS[chunk_id_str]()
else:
print('Unknown chunk: ', chunk_id_str)
file.seek(chunk_datasize * chunk_datacount, 1)
# print(chunk_id_str, chunk_datacount)
file.close()
print(" Importing file:", filepath)
if not bImportmesh and (Bones is None or len(Bones) == 0):
error_callback("Psk: no skeleton data.")
return False
MAX_UVS = 8
NAME_UV_PREFIX = "UV"
# file name w/out extension
gen_name_part = util_gen_name_part(filepath)
gen_names = {
'armature_object': gen_name_part + '.ao',
'armature_data': gen_name_part + '.ad',
'mesh_object': gen_name_part + '.mo',
'mesh_data': gen_name_part + '.md'
}
if bImportmesh:
mesh_data = bpy.data.meshes.new(gen_names['mesh_data'])
mesh_obj = bpy.data.objects.new(gen_names['mesh_object'], mesh_data)
#==================================================================================================
# UV. Prepare
if bImportmesh:
if bSpltiUVdata:
# store how much each "matrial index" have vertices
uv_mat_ids = {}
for (_, _, _, material_index) in Wedges:
if not (material_index in uv_mat_ids):
uv_mat_ids[material_index] = 1
else:
uv_mat_ids[material_index] += 1
# if we have more UV material indexes than blender UV maps, then...
if bSpltiUVdata and len(uv_mat_ids) > MAX_UVS :
uv_mat_ids_len = len(uv_mat_ids)
print('UVs: %s out of %s is combined in a first UV map(%s0)' % (uv_mat_ids_len - 8, uv_mat_ids_len, NAME_UV_PREFIX))
mat_idx_proxy = [0] * len(uv_mat_ids)
counts_sorted = sorted(uv_mat_ids.values(), reverse = True)
new_mat_index = MAX_UVS - 1
for c in counts_sorted:
for mat_idx, counts in uv_mat_ids.items():
if c == counts:
mat_idx_proxy[mat_idx] = new_mat_index
if new_mat_index > 0:
new_mat_index -= 1
# print('MatIdx remap: %s > %s' % (mat_idx,new_mat_index))
for i in range(len(Wedges)):
Wedges[i][3] = mat_idx_proxy[Wedges[i][3]]
# print('Wedges:', chunk_datacount)
# print('uv_mat_ids', uv_mat_ids)
# print('uv_mat_ids', uv_mat_ids)
# for w in Wedges:
if bImportmesh:
# print("-- Materials -- (index, name, faces)")
blen_materials = []
for materialname in Materials:
matdata = bpy.data.materials.get(materialname)
if matdata is None:
matdata = bpy.data.materials.new( materialname )
# matdata = bpy.data.materials.new( materialname )
blen_materials.append( matdata )
mesh_data.materials.append( matdata )
# print(counter,materialname,TextureIndex)
# if mat_groups.get(counter) is not None:
# print("%i: %s" % (counter, materialname), len(mat_groups[counter]))
#==================================================================================================
# Prepare bone data
def init_psk_bone(i, psk_bones, name_raw):
psk_bone = class_psk_bone()
psk_bone.children = []
psk_bone.name = util_bytes_to_str(name_raw)
psk_bones[i] = psk_bone
return psk_bone
psk_bone_name_toolong = False
# indexed by bone index. array of psk_bone
psk_bones = [None] * len(Bones)
if not bImportbone: #data needed for mesh-only import
for counter,(name_raw,) in enumerate(Bones):
init_psk_bone(counter, psk_bones, name_raw)
if bImportbone: #else?
# average bone length
sum_bone_pos = 0
for counter, (name_raw, flags, NumChildren, ParentIndex, #0 1 2 3
quat_x, quat_y, quat_z, quat_w, #4 5 6 7
vec_x, vec_y, vec_z
# , #8 9 10
# joint_length, #11
# scale_x, scale_y, scale_z
) in enumerate(Bones):
psk_bone = init_psk_bone(counter, psk_bones, name_raw)
psk_bone.bone_index = counter
psk_bone.parent_index = ParentIndex
# Tested. 64 is getting cut to 63
if len(psk_bone.name) > 63:
psk_bone_name_toolong = True
# print('Warning. Bone name is too long:', psk_bone.name)
# make sure we have valid parent_index
if psk_bone.parent_index < 0:
psk_bone.parent_index = 0
# psk_bone.scale = (scale_x, scale_y, scale_z)
# print("%s: %03f %03f | %f" % (psk_bone.name, scale_x, scale_y, joint_length),scale_x)
# print("%s:" % (psk_bone.name), vec_x, quat_x)
# store bind pose to make it available for psa-import via CustomProperty of the Blender bone
psk_bone.orig_quat = Quaternion((quat_w, quat_x, quat_y, quat_z))
if bScaleDown:
psk_bone.orig_loc = Vector((vec_x * 0.01, vec_y * 0.01, vec_z * 0.01))
else:
psk_bone.orig_loc = Vector((vec_x, vec_y, vec_z))
# root bone must have parent_index = 0 and selfindex = 0
if psk_bone.parent_index == 0 and psk_bone.bone_index == psk_bone.parent_index:
if bDontInvertRoot:
psk_bone.mat_world_rot = psk_bone.orig_quat.to_matrix()
else:
psk_bone.mat_world_rot = psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world = Matrix.Translation(psk_bone.orig_loc)
sum_bone_pos += psk_bone.orig_loc.length
#==================================================================================================
# Bones. Calc World-space matrix
# TODO optimize math.
for psk_bone in psk_bones:
if psk_bone.parent_index == 0:
if psk_bone.bone_index == 0:
psk_bone.parent = None
continue
parent = psk_bones[psk_bone.parent_index]
psk_bone.parent = parent
parent.children.append(psk_bone)
# mat_world - world space bone matrix WITHOUT own rotation
# mat_world_rot - world space bone rotation WITH own rotation
# psk_bone.mat_world = parent.mat_world_rot.to_4x4()
# psk_bone.mat_world.translation = parent.mat_world.translation + parent.mat_world_rot * psk_bone.orig_loc
# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world = parent.mat_world_rot.to_4x4()
v = psk_bone.orig_loc.copy()
v.rotate( parent.mat_world_rot )
psk_bone.mat_world.translation = parent.mat_world.translation + v
psk_bone.mat_world_rot = psk_bone.orig_quat.conjugated().to_matrix()
psk_bone.mat_world_rot.rotate( parent.mat_world_rot )
# psk_bone.mat_world = ( parent.mat_world_rot.to_4x4() * psk_bone.trans)
# psk_bone.mat_world.translation += parent.mat_world.translation
# psk_bone.mat_world_rot = parent.mat_world_rot * psk_bone.orig_quat.conjugated().to_matrix()
#==================================================================================================
# Skeleton. Prepare.
armature_data = bpy.data.armatures.new(gen_names['armature_data'])
armature_obj = bpy.data.objects.new(gen_names['armature_object'], armature_data)
# TODO: options for axes and x_ray?
armature_data.show_axes = False
armature_data.display_type = 'STICK'
armature_obj.show_in_front = True
util_obj_link(context, armature_obj)
util_select_all(False)
util_obj_select(context, armature_obj)
util_obj_set_active(context, armature_obj)
utils_set_mode('EDIT')
sum_bone_pos /= len(Bones) # average
sum_bone_pos *= fBonesizeRatio # corrected
# bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))))
bone_size_choosen = max(0.01, round((min(sum_bone_pos, fBonesize))*100)/100)
# bone_size_choosen = max(0.01, min(sum_bone_pos, fBonesize))
# print("Bonesize %f | old: %f round: %f" % (bone_size_choosen, max(0.01, min(sum_bone_pos, fBonesize)),max(0.01, round((min(sum_bone_pos, fBonesize))*100)/100)))
if not bReorientBones:
new_bone_size = bone_size_choosen
#==================================================================================================
# Skeleton. Build.
if psk_bone_name_toolong:
print('Warning. Some bones will be renamed(names are too long). Animation import may be broken.')
for psk_bone in psk_bones:
# TODO too long name cutting options?
orig_long_name = psk_bone.name
# Blender will cut the name here (>63 chars)
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
edit_bone["orig_long_name"] = orig_long_name
# if orig_long_name != edit_bone.name:
# print('--')
# print(len(orig_long_name),orig_long_name)
# print(len(edit_bone.name),edit_bone.name)
# Use the bone name made by blender (.001 , .002 etc.)
psk_bone.name = edit_bone.name
else:
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones.new(psk_bone.name)
psk_bone.name = edit_bone.name
for psk_bone in psk_bones:
edit_bone = armature_obj.data.edit_bones[psk_bone.name]
armature_obj.data.edit_bones.active = edit_bone
if psk_bone.parent is not None:
edit_bone.parent = armature_obj.data.edit_bones[psk_bone.parent.name]
else:
if bDontInvertRoot:
psk_bone.orig_quat.conjugate()
if bReorientBones:
(new_bone_size, quat_orient_diff) = calc_bone_rotation(psk_bone, bone_size_choosen, bReorientDirectly, sum_bone_pos)
# @
# post_quat = psk_bone.orig_quat.conjugated() * quat_orient_diff
post_quat = quat_orient_diff
post_quat.rotate( psk_bone.orig_quat.conjugated() )
else:
post_quat = psk_bone.orig_quat.conjugated()
# only length of this vector is matter?
edit_bone.tail = Vector(( 0.0, new_bone_size, 0.0))
# @
# edit_bone.matrix = psk_bone.mat_world * post_quat.to_matrix().to_4x4()
m = post_quat.copy()
m.rotate( psk_bone.mat_world )
m = m.to_matrix().to_4x4()
m.translation = psk_bone.mat_world.translation
edit_bone.matrix = m
# some dev code...
#### FINAL
# post_quat = psk_bone.orig_quat.conjugated() * quat_diff
# edit_bone.matrix = psk_bone.mat_world * test_quat.to_matrix().to_4x4()
# edit_bone["post_quat"] = test_quat
####
# edit_bone["post_quat"] = Quaternion((1,0,0,0))
# edit_bone.matrix = psk_bone.mat_world* psk_bone.rot
# if edit_bone.parent:
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (psk_bone.orig_quat.conjugated().to_matrix().to_4x4())
# edit_bone.matrix = edit_bone.parent.matrix * psk_bone.trans * (test_quat.to_matrix().to_4x4())
# else:
# edit_bone.matrix = psk_bone.orig_quat.to_matrix().to_4x4()
# save bindPose information for .psa import
# dev
edit_bone["orig_quat"] = psk_bone.orig_quat
edit_bone["orig_loc"] = psk_bone.orig_loc
edit_bone["post_quat"] = post_quat
'''
bone = edit_bone
if psk_bone.parent is not None:
orig_loc = bone.matrix.translation - bone.parent.matrix.translation
orig_loc.rotate( bone.parent.matrix.to_quaternion().conjugated() )
orig_quat = bone.matrix.to_quaternion()
orig_quat.rotate( bone.parent.matrix.to_quaternion().conjugated() )
orig_quat.conjugate()
if orig_quat.dot( psk_bone.orig_quat ) < 0.95:
print(bone.name, psk_bone.orig_quat, orig_quat, orig_quat.dot( psk_bone.orig_quat ))
print('parent:', bone.parent.matrix.to_quaternion(), bone.parent.matrix.to_quaternion().rotation_difference(bone.matrix.to_quaternion()) )
if (psk_bone.orig_loc - orig_loc).length > 0.02:
print(bone.name, psk_bone.orig_loc, orig_loc, (psk_bone.orig_loc - orig_loc).length)
'''
utils_set_mode('OBJECT')
#==================================================================================================
# Weights
if bImportmesh:
vertices_total = len(Vertices)
for ( _, PointIndex, BoneIndex ) in Weights:
if PointIndex < vertices_total: # can it be not?
psk_bones[BoneIndex].have_weight_data = True
# else:
# print(psk_bones[BoneIndex].name, 'for other mesh',PointIndex ,vertices_total)