forked from alexeyd/blender2cal3d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blender2cal3d.py
1782 lines (1491 loc) · 53.2 KB
/
blender2cal3d.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
#!BPY
#fingers 2 each, knees 2.5, feet 2.5
"""
Name: 'Cal3D Exporter'
Blender: 249
Group: 'Export'
Tip: 'Export armature/bone data to the Cal3D library.'
"""
__author__ = ["Jean-Baptiste Lamy (Jiba)", "Chris Montijin", "Damien McGinnes", "David Young", "Alexey Dorokhov"]
__url__ = ("blender", "elysiun", "Cal3D, http://cal3d.sf.net")
__version__ = "1.0"
__bpydoc__ = """\
This script exports armature / bone data to the well known open source Cal3D
library.
Usage:
Simply run the script to export available armatures.
Supported:<br>
Cal3D format versions 0.7 -> 0.9.
Known issues:<br>
Animation export requires an open 3d graphics window.
When you finish an animation and run the script you can get an error
(something with KeyError). Just save your work and reload the model. This is
usually caused by deleted items hanging around;<br>
Cloth export only works reliably on a planar mesh (like a cape, or a
ribbon), not on a connected mesh (like a ball);
Notes:<br>
Objects/bones/actions whose names start by "_" are not exported so call IK
and null bones _LegIK, for example;<br>
Actions that start with '@' will be exported as actions, others will be
exported as cycles;<br>
Meshes whose names are prefixed with Cloth_ or cloth_ will have a spring
system created. Vertex group _cloth_weight is used to define the parts of
the mesh that act as anchors - give the 0 weight in this group. Otherwise 0.01
is a good weight. For now all springs have a coeff of 1000<br>
(The weights in _cloth_weight are stored as each included vertex's <PHYSIQUE> value.
Whatever that does);<br>
Faces with more than 3 sides are automatically split into triangles when they're
exported;<br>
"""
# $Id: blender2cal3d.py,v 1.4 2010/07/16 00:00:00 elefth Exp $
#
# Copyright (C) 2003 Jean-Baptiste LAMY -- jiba@tuxfamily.org
# Copyright (C) 2004 Chris Montijin
# Copyright (C) 2004 Damien McGinnes
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# This script is a Blender 2.49 => Cal3D 0.7/0.8/0.9/0.11 converter.
# (See http://blender.org and http://cal3d.sourceforge.net)
#
# This script was written by Jiba, modified by Chris and later modified by Damien
# and even later it was modified Alexey
# Changes:
# 1.4 Alexey Dorokhov <alexey.dorokhov at gmail.com>
# Updated to work with 2.49a
# Replaced internal linear math routines
# with the ones provided by blender Matutils API
# Replaced "Export to Soya" option with more general
# model transformations
# 1.1 David Young <dcyoung at pobox dot com>
# Updated to work with the Blender 2.41 python API
# Animations are exported from the pose matrix rather
# than ipos; this works around the broken animation
# baking in 2.41
# Fixed bug which caused some bones to be exported several
# times
#
#(Also small changes to 2.24a - note that mesh and armature need to have same position - bookeater)"
#
# 1.0 Damien McGinnes <mcginnes at netspeed.com.au>
# Forked from blender2cal3d because we have had 2
# independant efforts working on the same script
# Fixed springs so now you can have uv discontinuities
# or multiple textures on a cloth mesh - this
# requires a patch to cal3d to work properly
#
# 0.8 Damien McGinnes <mcginnes at netspeed.com.au>
# Added Cloth export
# Fixed bone child translation bug
# Added material colors
#
# 0.7 Damien McGinnes <mcginnes at netspeed com au>
# Added NLA functionality for IPOs - this simplifies
# the animation export and speeds it up significantly
# it also removes the constraints on channel names -
# they no longer have to match the bone or action and
# .L .R etc are supported
# bones starting with _ are not exported
# textures no longer flipped vertically
# fixed a filename bug for .csf and .cfg
# actions that are prefixed with '@' go into the cfg file
# as actions rather than cycles
# works with baked IK actions, unbaked ones wont work well
# because you wont have the constraints evaluated
# added an FPS slider into the gui
# added registry saving for gui state.
#
# 0.6 Chris Montjin
# Updated for Blender 2.32, 2.33
# added basic GUI
# generally improved flexibility
#
# 0.5 Jiba <jiba@tuxfamily.org>
# Initial Release for Blender 2.28
# HOW TO USE :
# 1 - load the script in Blender's text editor
# 2 - type M-P (meta/alt + P) and wait until script execution is finished
# or install it in .scripts and access from the export menu
# ADVICE
# - Objects/bones/actions whose names start by "_" are not exported
# so call IK and null bones _LegIK for example
# - Actions that start with '@' will be exported as actions, others will be
# exported as cycles
# BUGS / TODO :
# - Armature can not be scaled (i.e. you can scale bones in edit mode,
# but if you try to scale armature in object mode script will fail
# to export your animations correctly)
# REMARKS
# 1. When you finished an animation and run the script
# you can get an error (something with KeyError). Just save your work,
# and reload the model. This is usualy caused by deleted items hanging around
# 2. If a vertex is assigned to one or more bones, but is has a for each
# bone a weight of zero, there was a subdivision by zero somewhere
# Made a workaround (if sum is 0.0 then sum becomes 1.0).
# Generally vertices with no weight simply dont deform at all - regardless
# of what you do with the skeleton - it is generally undesirable for this to
# happen
# 3. You can place armature anywhere on the scene and you can place root bone
# anywhere within bonespace, but in the exported model root bone will always
# be at point (0,0,0). All other objects (bones and meshes) will be moved
# accordingly, so the exported model will look right. All rotations (of armature,
# bones, meshes) will be preserved. Mesh scale transformations will also be
# preserved, armature scale transformaions will make you animations a mess (=
# Parameters :
# The directory where the data are saved.
SAVE_TO_DIR = ""
# Delete all existing Cal3D files in directory?
DELETE_ALL_FILES = 1
# Should the script translate root bone origin to (0,0,0)?
ROOT_TO_ZERO = 1
EXPORT_SKELETON = 1
EXPORT_ANIMATION = 1
EXPORT_MESH = 1
EXPORT_MATERIAL = 0
#custom
FILE_SKELETONNAME = "skel"
# Prefix for all created files
FILE_PREFIX = "model_"
# Remove path from imagelocation
REMOVE_PATH_FROM_IMAGE = 0
# prefix or subdir for imagepathname (if you place your textures in a
# subdir or just need a prefix or something). Only used when
# REMOVE_PATH_FROM_IMAGE = 1. Set to "" if none.
IMAGE_PREFIX = "textures/"
# Export to new (>= 900) Cal3D XML-format
EXPORT_TO_XML = 1
# frames per second - used to convert blender frames to times
FPS = 25
RENAME_ANIMATIONS = {
# "OldName" : "NewName",
}
# These define initial model transformation (a generalisation of
# 'export for Soya' functionality). The order of rotation is the following:
# 1) rotate model around X axis for ROT_X degrees
# 2) rotate model around Y axis for ROT_Y degress
# 3) rotate model around Z axis for ROT_Z degress
ROT_X = 0.0
ROT_Y = 0.0
ROT_Z = 0.0
SCALE = 1.0
CHANGE_ROT_X_EVENT_ID = 100
CHANGE_ROT_Y_EVENT_ID = 101
CHANGE_ROT_Z_EVENT_ID = 102
CHANGE_SCALE_EVENT_ID = 103
CHANGE_RTZ_EVENT_ID = 104
# Enables LODs computation. LODs computation is quite slow, and the algo is
# surely not optimal :-(
LODS = 0
#remove the word '.BAKED' from exported baked animations
REMOVE_BAKED = 1
EXPORT_ALL_SCENES = 0
################################################################################
# Code starts here.
#
import sys, os, os.path, struct, math, string
import Blender
from Blender.BGL import *
from Blender.Draw import *
from Blender.Armature import *
from Blender.Registry import *
from Blender.Mathutils import Matrix
# HACK -- it seems that some Blender versions don't define sys.argv,
# which may crash Python if a warning occurs.
if not hasattr(sys, "argv"): sys.argv = ["???"]
# Cal3D data structures
CAL3D_VERSION = 700
CAL3D_XML_VERSION = 900
# Define globals
BONES = {}
MATERIALS = {}
ANIMATIONS = {}
NEXT_MATERIAL_ID = 0
class Material:
def __init__(self, name):
self.ambient_r = 255
self.ambient_g = 255
self.ambient_b = 255
self.ambient_a = 255
self.diffuse_r = 255
self.diffuse_g = 255
self.diffuse_b = 255
self.diffuse_a = 255
self.specular_r = 255
self.specular_g = 255
self.specular_b = 255
self.specular_a = 255
self.shininess = 1.0
self.maps_filenames = []
MATERIALS[name] = self
self.name = name
global NEXT_MATERIAL_ID
self.id = NEXT_MATERIAL_ID
NEXT_MATERIAL_ID += 1
def to_cal3d(self):
s = "CRF\0" + struct.pack("iBBBBBBBBBBBBfi", CAL3D_VERSION,
self.ambient_r, self.ambient_g, self.ambient_b, self.ambient_a,
self.diffuse_r, self.diffuse_g, self.diffuse_b, self.diffuse_a,
self.specular_r, self.specular_g, self.specular_b, self.specular_a,
self.shininess, len(self.maps_filenames))
for map_filename in self.maps_filenames:
s += struct.pack("i", len(map_filename) + 1)
s += map_filename + "\0"
return s
def to_cal3d_xml(self):
s = "<HEADER MAGIC=\"XRF\" VERSION=\"%i\"/>\n" % CAL3D_XML_VERSION
s += " <MATERIAL NUMMAPS=\"%i\">\n" % len(self.maps_filenames)
s += " <AMBIENT>%i %i %i %i</AMBIENT>\n" % \
(self.ambient_r, self.ambient_g, self.ambient_b, self.ambient_a)
s += " <DIFFUSE>%i %i %i %i</DIFFUSE>\n" % \
(self.diffuse_r, self.diffuse_g, self.diffuse_b, self.diffuse_a)
s += " <SPECULAR>%i %i %i %i</SPECULAR>\n" % \
(self.specular_r, self.specular_g, self.specular_b, self.specular_a)
s += " <SHININESS>%f</SHININESS>\n" % self.shininess
for map_filename in self.maps_filenames:
s += " <MAP>%s</MAP>\n" % map_filename
s += "</MATERIAL>\n"
return s
class Mesh:
def __init__(self, name):
self.name = name
self.submeshes = []
self.next_submesh_id = 0
def to_cal3d(self):
s = "CMF\0" + struct.pack("ii", CAL3D_VERSION, len(self.submeshes))
s += "".join(map(SubMesh.to_cal3d, self.submeshes))
return s
def to_cal3d_xml(self):
s = "<HEADER MAGIC=\"XMF\" VERSION=\"%i\"/>\n" % CAL3D_XML_VERSION
s += "<MESH NUMSUBMESH=\"%i\">\n" % len(self.submeshes)
s += "".join(map(SubMesh.to_cal3d_xml, self.submeshes))
s += "</MESH>\n"
return s
class SubMesh:
def __init__(self, mesh, material_id):
self.material_id = material_id
self.vertices = []
self.faces = []
self.nb_lodsteps = 0
self.springs = []
self.next_vertex_id = 0
self.mesh = mesh
self.id = mesh.next_submesh_id
mesh.next_submesh_id += 1
mesh.submeshes.append(self)
def compute_lods(self):
"""Computes LODs info for Cal3D (there's no Blender related stuff here)."""
print "Start LODs computation..."
vertex2faces = {}
for face in self.faces:
for vertex in (face.vertex1, face.vertex2, face.vertex3):
l = vertex2faces.get(vertex)
if not l:
vertex2faces[vertex] = [face]
else:
l.append(face)
couple_treated = {}
couple_collapse_factor = []
nn = 0
for face in self.faces:
for a, b in ((face.vertex1, face.vertex2), (face.vertex1, face.vertex3),
(face.vertex2, face.vertex3)):
a = a.cloned_from or a
b = b.cloned_from or b
if a.id > b.id:
a, b = b, a
if not couple_treated.has_key((a, b)):
# The collapse factor is simply the distance between the 2 points :-(
# This should be improved !!
if a.normal.dot(b.normal) < 0.1:
continue
dist_vec = b.loc - a.loc
couple_collapse_factor.append((dist_vec.length, a, b))
couple_treated[a, b] = 1
#else:
# nn+=1
# print nn
#
couple_collapse_factor.sort()
collapsed = {}
new_vertices = []
new_faces = []
for factor, v1, v2 in couple_collapse_factor:
# Determines if v1 collapses to v2 or v2 to v1.
# We choose to keep the vertex which is on the
# smaller number of faces, since
# this one has more chance of being in an extrimity of the body.
# Though heuristic, this rule yields very good results in practice.
if len(vertex2faces[v1]) < len(vertex2faces[v2]):
v2, v1 = v1, v2
elif len(vertex2faces[v1]) == len(vertex2faces[v2]):
if collapsed.get(v1, 0): v2, v1 = v1, v2 # v1 already collapsed, try v2
if (not collapsed.get(v1, 0)) and (not collapsed.get(v2, 0)):
collapsed[v1] = 1
#collapsed[v2] = 1
# Check if v2 is already collapsed
while v2.collapse_to:
v2 = v2.collapse_to
common_faces = filter(vertex2faces[v1].__contains__, vertex2faces[v2])
v1.collapse_to = v2
v1.face_collapse_count = len(common_faces)
for clone in v1.clones:
# Find the clone of v2 that correspond to this clone of v1
possibles = []
for face in vertex2faces[clone]:
possibles.append(face.vertex1)
possibles.append(face.vertex2)
possibles.append(face.vertex3)
clone.collapse_to = v2
for vertex in v2.clones:
if vertex in possibles:
clone.collapse_to = vertex
break
clone.face_collapse_count = 0
new_vertices.append(clone)
# HACK -- all faces get collapsed with v1
# (and no faces are collapsed with v1's
# clones). This is why we add v1 in new_vertices after v1's clones.
# This hack has no other incidence that consuming
# a little few memory for the
# extra faces if some v1's clone are collapsed but v1 is not.
new_vertices.append(v1)
self.nb_lodsteps += 1 + len(v1.clones)
new_faces.extend(common_faces)
for face in common_faces:
face.can_collapse = 1
# Updates vertex2faces
if vertex2faces[face.vertex1].count(face):
vertex2faces[face.vertex1].remove(face)
if vertex2faces[face.vertex2].count(face):
vertex2faces[face.vertex2].remove(face)
if vertex2faces[face.vertex3].count(face):
vertex2faces[face.vertex3].remove(face)
vertex2faces[v2].extend(vertex2faces[v1])
#end loop
new_vertices.extend(filter(lambda vertex: not vertex.collapse_to,
self.vertices))
new_vertices.reverse() # Cal3D want LODed vertices at the end
for i in range(len(new_vertices)): new_vertices[i].id = i
self.vertices = new_vertices
new_faces.extend(filter(lambda face: not face.can_collapse, self.faces))
new_faces.reverse() # Cal3D want LODed faces at the end
self.faces = new_faces
print "LODs computed : %s vertices can be removed (from a total of %s)." % \
(self.nb_lodsteps, len(self.vertices))
def rename_vertices(self, new_vertices):
"""Rename (change ID) of all vertices, such as self.vertices ==
new_vertices.
"""
for i in range(len(new_vertices)):
new_vertices[i].id = i
self.vertices = new_vertices
def to_cal3d(self):
texcoords_num = 0
if self.vertices and len(self.vertices) > 0:
texcoords_num = len(self.vertices[0].maps)
s = struct.pack("iiiiii", self.material_id, len(self.vertices),
len(self.faces), self.nb_lodsteps, len(self.springs), texcoords_num)
s += "".join(map(Vertex.to_cal3d, self.vertices))
s += "".join(map(Spring.to_cal3d, self.springs))
s += "".join(map(Face.to_cal3d, self.faces))
return s
def to_cal3d_xml(self):
texcoords_num = 0
if self.vertices and len(self.vertices) > 0:
texcoords_num = len(self.vertices[0].maps)
s = " <SUBMESH NUMVERTICES=\"%i\" NUMFACES=\"%i\" MATERIAL=\"%i\" " % \
(len(self.vertices), len(self.faces), self.material_id)
s += "NUMLODSTEPS=\"%i\" NUMSPRINGS=\"%i\" NUMTEXCOORDS=\"%i\">\n" % \
(self.nb_lodsteps, len(self.springs), texcoords_num)
s += "".join(map(Vertex.to_cal3d_xml, self.vertices))
s += "".join(map(Spring.to_cal3d_xml, self.springs))
s += "".join(map(Face.to_cal3d_xml, self.faces))
s += " </SUBMESH>\n"
return s
class Vertex:
def __init__(self, submesh, loc, normal):
self.loc = loc.copy()
self.normal = normal.copy()
self.collapse_to = None
self.face_collapse_count = 0
self.maps = []
self.influences = []
self.weight = 0.0
self.hasweight = 0
self.cloned_from = None
self.clones = []
self.submesh = submesh
self.id = submesh.next_vertex_id
submesh.next_vertex_id += 1
submesh.vertices.append(self)
def to_cal3d(self):
if self.collapse_to:
collapse_id = self.collapse_to.id
else:
collapse_id = -1
s = struct.pack("ffffffii", self.loc[0], self.loc[1], self.loc[2],
self.normal[0], self.normal[1], self.normal[2], collapse_id,
self.face_collapse_count)
s += "".join(map(Map.to_cal3d, self.maps))
s += struct.pack("i", len(self.influences))
s += "".join(map(Influence.to_cal3d, self.influences))
if self.hasweight:
s += struct.pack("f", self.weight)
return s
def to_cal3d_xml(self):
if self.collapse_to:
collapse_id = self.collapse_to.id
else:
collapse_id = -1
s = " <VERTEX ID=\"%i\" NUMINFLUENCES=\"%i\">\n" % \
(self.id, len(self.influences))
s += " <POS>%f %f %f</POS>\n" % (self.loc[0], self.loc[1], self.loc[2])
s += " <NORM>%f %f %f</NORM>\n" % \
(self.normal[0], self.normal[1], self.normal[2])
if collapse_id != -1:
s += " <COLLAPSEID>%i</COLLAPSEID>\n" % collapse_id
s += " <COLLAPSECOUNT>%i</COLLAPSECOUNT>\n" % \
self.face_collapse_count
s += "".join(map(Map.to_cal3d_xml, self.maps))
s += "".join(map(Influence.to_cal3d_xml, self.influences))
if self.hasweight:
s += " <PHYSIQUE>%f</PHYSIQUE>\n" % self.weight
s += " </VERTEX>\n"
return s
class Map:
def __init__(self, u, v):
self.u = u
self.v = v
def to_cal3d(self):
return struct.pack("ff", self.u, self.v)
def to_cal3d_xml(self):
return " <TEXCOORD>%f %f</TEXCOORD>\n" % (self.u, self.v)
class Influence:
def __init__(self, bone, weight):
self.bone = bone
self.weight = weight
def to_cal3d(self):
return struct.pack("if", self.bone.id, self.weight)
def to_cal3d_xml(self):
return " <INFLUENCE ID=\"%i\">%f</INFLUENCE>\n" % \
(self.bone.id, self.weight)
class Spring:
def __init__(self, vertex1, vertex2):
self.vertex1 = vertex1
self.vertex2 = vertex2
self.spring_coefficient = 0.0
self.idlelength = 0.0
def to_cal3d(self):
return struct.pack("iiff", self.vertex1.id, self.vertex2.id,
self.spring_coefficient, self.idlelength)
def to_cal3d_xml(self):
return " <SPRING VERTEXID=\"%i %i\" COEF=\"%f\" LENGTH=\"%f\"/>\n" % \
(self.vertex1.id, self.vertex2.id, self.spring_coefficient,
self.idlelength)
class Face:
def __init__(self, submesh, vertex1, vertex2, vertex3):
self.vertex1 = vertex1
self.vertex2 = vertex2
self.vertex3 = vertex3
self.can_collapse = 0
self.submesh = submesh
submesh.faces.append(self)
def to_cal3d(self):
return struct.pack("iii", self.vertex1.id, self.vertex2.id, self.vertex3.id)
def to_cal3d_xml(self):
return " <FACE VERTEXID=\"%i %i %i\"/>\n" % \
(self.vertex1.id, self.vertex2.id, self.vertex3.id)
class Skeleton:
def __init__(self):
self.bones = []
self.next_bone_id = 0
def to_cal3d(self):
s = "CSF\0" + struct.pack("ii", CAL3D_VERSION, len(self.bones))
s += "".join(map(Bone.to_cal3d, self.bones))
return s
def to_cal3d_xml(self):
s = "<HEADER MAGIC=\"XSF\" VERSION=\"%i\"/>\n" % CAL3D_XML_VERSION
s += "<SKELETON NUMBONES=\"%i\">\n" % len(self.bones)
s += "".join(map(Bone.to_cal3d_xml, self.bones))
s += "</SKELETON>\n"
return s
BONES = {}
class Bone:
def __init__(self, skeleton, parent, name, loc, quat):
self.parent = parent
self.name = name
self.loc = loc.copy()
self.quat = quat.copy()
self.children = []
# calculate absolute rotation matrix
matrix = quat.toMatrix()
if parent:
self.matrix = parent.matrix * matrix
parent.children.append(self)
else:
self.matrix = matrix.copy()
#calculate absolute translaton vector
if parent:
self.abs_trans = parent.abs_trans + parent.matrix * self.loc
else:
self.abs_trans = self.loc
# lloc and lquat are the model => bone space transformation
m = self.matrix.copy()
m.invert()
self.lquat = m.toQuat()
self.lloc = m * (-self.abs_trans)
self.skeleton = skeleton
self.id = skeleton.next_bone_id
skeleton.next_bone_id += 1
skeleton.bones.append(self)
BONES[self.name] = self
def to_cal3d(self):
s = struct.pack("i", len(self.name) + 1) + self.name + "\0"
s += struct.pack("ffffffffffffff", self.loc[0], self.loc[1], self.loc[2],
self.quat.x, self.quat.y, self.quat.z, self.quat.w,
self.lloc[0], self.lloc[1], self.lloc[2],
self.lquat.x, self.lquat.y, self.lquat.z, self.lquat.w)
if self.parent:
s += struct.pack("i", self.parent.id)
else:
s += struct.pack("i", -1)
s += struct.pack("i", len(self.children))
s += "".join(map(lambda bone: struct.pack("i", bone.id), self.children))
return s
def to_cal3d_xml(self):
s = " <BONE ID=\"%i\" NAME=\"%s\" NUMCHILDS=\"%i\">\n" % \
(self.id, self.name, len(self.children))
s += " <TRANSLATION>%f %f %f</TRANSLATION>\n" % \
(self.loc[0], self.loc[1], self.loc[2])
s += " <ROTATION>%f %f %f %f</ROTATION>\n" % \
(self.quat.x, self.quat.y, self.quat.z, self.quat.w)
s += " <LOCALTRANSLATION>%f %f %f</LOCALTRANSLATION>\n" % \
(self.lloc[0], self.lloc[1], self.lloc[2])
s += " <LOCALROTATION>%f %f %f %f</LOCALROTATION>\n" % \
(self.lquat.x, self.lquat.y, self.lquat.z, self.lquat.w)
if self.parent:
s += " <PARENTID>%i</PARENTID>\n" % self.parent.id
else:
s += " <PARENTID>%i</PARENTID>\n" % -1
s += "".join(map(lambda bone: " <CHILDID>%i</CHILDID>\n" % bone.id,
self.children))
s += " </BONE>\n"
return s
class Animation:
def __init__(self, name, action, duration = 0.0):
self.name = name
self.action = action
self.duration = duration
self.tracks = {} # Map bone names to tracks
def to_cal3d(self):
s = "CAF\0" + struct.pack("ifi",
CAL3D_VERSION, self.duration, len(self.tracks))
s += "".join(map(Track.to_cal3d, self.tracks.values()))
return s
def to_cal3d_xml(self):
s = "<HEADER MAGIC=\"XAF\" VERSION=\"%i\"/>\n" % CAL3D_XML_VERSION
s += "<ANIMATION DURATION=\"%f\" NUMTRACKS=\"%i\">\n" % \
(self.duration, len(self.tracks))
s += "".join(map(Track.to_cal3d_xml, self.tracks.values()))
s += "</ANIMATION>\n"
return s
class Track:
def __init__(self, animation, bone):
self.bone = bone
self.keyframes = []
self.animation = animation
animation.tracks[bone.name] = self
def to_cal3d(self):
s = struct.pack("ii", self.bone.id, len(self.keyframes))
s += "".join(map(KeyFrame.to_cal3d, self.keyframes))
return s
def to_cal3d_xml(self):
s = " <TRACK BONEID=\"%i\" NUMKEYFRAMES=\"%i\">\n" % \
(self.bone.id, len(self.keyframes))
s += "".join(map(KeyFrame.to_cal3d_xml, self.keyframes))
s += " </TRACK>\n"
return s
class KeyFrame:
def __init__(self, track, time, loc, quat):
self.time = time
self.loc = loc.copy()
self.quat = quat.copy()
self.track = track
track.keyframes.append(self)
def to_cal3d(self):
return struct.pack("ffffffff", self.time, self.loc[0], self.loc[1],
self.loc[2], self.quat.x, self.quat.y, self.quat.z, self.quat.w)
def to_cal3d_xml(self):
s = " <KEYFRAME TIME=\"%f\">\n" % self.time
s += " <TRANSLATION>%f %f %f</TRANSLATION>\n" % \
(self.loc[0], self.loc[1], self.loc[2])
s += " <ROTATION>%f %f %f %f</ROTATION>\n" % \
(self.quat.x, self.quat.y, self.quat.z, self.quat.w)
s += " </KEYFRAME>\n"
return s
def calculate_base_translation(scene):
base_translation = Blender.Mathutils.Vector([0,0,0])
armature_translation = Blender.Mathutils.Vector([0,0,0])
root_bone_translation = Blender.Mathutils.Vector([0,0,0])
for obj in scene.objects:
data = obj.getData()
if type(data) is Blender.Types.ArmatureType:
armature_translation = obj.getMatrix().translationPart()
for b in data.bones.values():
if not b.hasParent():
root_bone_translation = b.head['BONESPACE'].copy()
rotation = obj.getMatrix().rotationPart()
rotation.invert()
root_bone_translation = rotation * \
root_bone_translation
break
base_translation = armature_translation + root_bone_translation
base_translation.negate()
return base_translation.copy()
def get_armature_translation(scene):
armature_translation = Blender.Mathutils.Vector([0,0,0])
for obj in scene.objects:
data = obj.getData()
if type(data) is Blender.Types.ArmatureType:
armature_translation = obj.getMatrix().translationPart()
return armature_translation.copy()
def treat_bone(b, base_matrix, arm_matrix, parent, skeleton, scene):
global SCALE
global ROOT_TO_ZERO
# skip bones that start with _
# also skips children of that bone so be careful
if len(b.name) == 0: return
if b.name[0] == '_' : return
name = b.name
bone_head = b.head['BONESPACE'].copy()
bone_tail = b.tail['BONESPACE'].copy()
if not ROOT_TO_ZERO and not parent:
bone_tail = bone_tail - bone_head
bone_head = bone_head + \
arm_matrix.rotationPart()*get_armature_translation(scene)
bone_tail = bone_tail + bone_head
if bone_head.length != 0:
if not ROOT_TO_ZERO and not parent:
if base_matrix and arm_matrix:
dummy_arm_matrix = arm_matrix.copy()
dummy_arm_matrix.invert()
dummy_base_matrix = base_matrix.copy()
dummy_base_matrix.invert()
result_matrix = dummy_base_matrix * dummy_arm_matrix
tmp_quat = result_matrix.toQuat()
else:
tmp_quat = Blender.Mathutils.Quaternion()
tmp_loc = Blender.Mathutils.Vector([0.0,0.0,0.0])
parent = Bone(skeleton, None, "service_root",
tmp_loc.copy(), tmp_quat.copy())
parent.child_loc = Blender.Mathutils.Vector([0.0,0.0,0.0])
# in this case create a service
# bone between child and parent
if parent:
interm_loc = parent.child_loc.copy()
interm_loc *= SCALE
interm_quat = Blender.Mathutils.Quaternion()
interm_bone = Bone(skeleton, parent, name+"_interm",
interm_loc, interm_quat)
interm_bone.child_loc = bone_head
parent = interm_bone
else:
bone_tail -= bone_head
bone_head -= bone_head
local_rot_mat = b.matrix['BONESPACE'].rotationPart()
# convert to cal3d rotation
local_rot_mat.invert()
if base_matrix and arm_matrix and not parent:
dummy_arm_matrix = arm_matrix.copy()
dummy_arm_matrix.invert()
dummy_base_matrix = base_matrix.copy()
dummy_base_matrix.invert()
cal3d_base_matrix = dummy_base_matrix * dummy_arm_matrix
local_rot_mat = cal3d_base_matrix.rotationPart() * local_rot_mat
if parent:
loc = parent.child_loc.copy()
else:
loc = Blender.Mathutils.Vector([0.0,0.0,0.0])
loc *= SCALE
quat = local_rot_mat.toQuat()
bone = Bone(skeleton, parent, name, loc, quat)
# if I got it right, root bone
# shouldn't have translation =>
# moving all translations one
# bone forward
bone.child_loc = bone_tail - bone_head
bone_matrix = b.matrix['BONESPACE'].rotationPart()
bone.child_loc = bone_matrix * bone.child_loc
has_children = False
if b.hasChildren():
for child in b.children:
if len(child.name):
if child.name[0] != '_':
has_children = True
break
if has_children:
for child in b.children:
treat_bone(child, base_matrix.copy(), arm_matrix.copy(),
bone, skeleton, scene)
else:
# service bone for skeletons to look the
# same both in Blender and cal3d
ender_loc = bone.child_loc.copy()
ender_loc *= SCALE
ender_quat = Blender.Mathutils.Quaternion()
Bone(skeleton, bone, name+"_ender", ender_loc, ender_quat)
def create_actions_dict():
global BONES
legal_curve_types = ("LocX", "LocY", "LocZ",
"QuatX", "QuatY", "QuatZ", "QuatW")
arm_actions_dict = {}
blender_actions = Blender.Armature.NLA.GetActions()
for name, action in blender_actions.items():
if len(name) == 0:
continue
# skip actions that are named _something
if name[0] == "_":
print "skipping animation ", name
continue
# check if this action has channels for
# our armature bones
belongs_to_armature = False
for channel_name in action.getChannelNames():
if channel_name in BONES.keys():
belongs_to_armature = True
break
if not belongs_to_armature:
continue
arm_tracks_dict = {}
ok_to_add = True
for channel_name in action.getChannelNames():
if not channel_name in BONES.keys():
continue
# get rotation and translation keyframes
keyframes = []
ipo = action.getChannelIpo(channel_name)
for curve in ipo.curves:
if curve.name in legal_curve_types:
for point in curve.bezierPoints:
keyframes.append(point.vec[1][0])
else:
ok_to_add = False
# remove double keyframes
keyframes_set = set(keyframes)
keyframes = []
for keyframe in keyframes_set:
keyframes.append(keyframe)
keyframes.sort()
arm_tracks_dict[channel_name] = keyframes
if ok_to_add:
arm_actions_dict[name] = arm_tracks_dict
else:
print "skipping animation", name,": incorrect keyframe types"
return arm_actions_dict
def popup_block(header, body):
global STATUS
block = []
block.append(header)
Blender.Draw.PupBlock("Export message", block)
STATUS = body
Draw()
def scene_is_ok(scene):
armatures_num = 0
for obj in scene.objects:
data = obj.getData()
if type(data) is Blender.Types.ArmatureType:
armatures_num += 1
if armatures_num != 1:
popup_block("Export error",
"only 1 armature allowed, found %d armatrues"
% (armatures_num))
return False
for obj in scene.objects:
data = obj.getData()
root_bones_names = []
if type(data) is Blender.Types.ArmatureType:
arm_scale = obj.getMatrix().scalePart()
if (abs(arm_scale.x - 1.0) > 0.001 or
abs(arm_scale.y - 1.0) > 0.001 or
abs(arm_scale.z - 1.0) > 0.001):
popup_block("Skeleton export error",
"Armature is scaled (%f, %f, %f)" %
(arm_scale.x, arm_scale.y, arm_scale.z))
return False
root_bones_num = 0
for b in data.bones.values():
if not b.hasParent() and b.name[0] != "_":
root_bones_names.append(b.name)
root_bones_num += 1
if root_bones_num != 1:
error_string = "only 1 root bone allowed, found %d root bones: "\
% (root_bones_num)