forked from reattiva/Urho3D-Blender
-
Notifications
You must be signed in to change notification settings - Fork 4
/
export_urho.py
1297 lines (1121 loc) · 50 KB
/
export_urho.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
#
# This script is licensed as public domain.
# Based on the Ogre Importer from the Urho3D project
#
from .utils import FloatToString, WriteXmlFile, BinaryFileWriter
from mathutils import Vector, Matrix, Quaternion
from math import cos, pi
from xml.etree import ElementTree as ET
from collections import defaultdict
import operator
import os
import random
import logging
log = logging.getLogger("ExportLogger")
#--------------------
# Urho enums
#--------------------
ELEMENT_POSITION = 0x0001
ELEMENT_NORMAL = 0x0002
ELEMENT_COLOR = 0x0004
ELEMENT_UV1 = 0x0008
ELEMENT_UV2 = 0x0010
ELEMENT_CUBE_UV1 = 0x0020
ELEMENT_CUBE_UV2 = 0x0040
ELEMENT_TANGENT = 0x0080
ELEMENT_BWEIGHTS = 0x0100
ELEMENT_BINDICES = 0x0200
ELEMENT_BLEND = 0x0300
MORPH_ELEMENTS = ELEMENT_POSITION | ELEMENT_NORMAL | ELEMENT_TANGENT
BONE_BOUNDING_SPHERE = 0x0001
BONE_BOUNDING_BOX = 0x0002
TRACK_POSITION = 0x0001
TRACK_ROTATION = 0x0002
TRACK_SCALE = 0x0004
TRIANGLE_LIST = 0
LINE_LIST = 1
# Max number of bones supported by HW skinning
MAX_SKIN_MATRICES = 64
BONES_PER_VERTEX = 4
#--------------------
# Float comparison
#--------------------
# Max difference between floats to be equal
EPSILON = 1e-6
# Max difference between floats to be equal
INFINITY = float("+inf")
# Returns True is v1 and v2 are both None or their corresponding elements are almost equal
def FloatListAlmostEqual(v1, v2):
if v1 is None:
return v2 is None
if v2 is None:
return False
for e1, e2 in zip(v1, v2):
if abs(e1 - e2) > EPSILON:
return False
return True
def RelativeAbs(e1, e2):
if e1 == 0 and e2 == 0:
return 0
diff = abs(e1-e2)
if diff < EPSILON:
return 0
return d / max(abs(e1),abs(e2))
def FloatListEqualError(v1, v2):
if v1 is None:
if v2 is None:
return 0
else:
return INFINITY
if v2 is None:
return INFINITY
#return sum(RelativeAbs(e1, e2) for e1, e2 in zip(v1, v2))
return sum(abs(e1 - e2) for e1, e2 in zip(v1, v2))
def VectorDotProduct(v1, v2):
if v1 is None:
if v2 is None:
return 1
else:
return -1
if v2 is None:
return -1
return v1.dot(v2)
#--------------------
# Classes
#--------------------
# Bounding box axes aligned
class BoundingBox:
def __init__(self):
self.min = None # Vector((0.0, 0.0, 0.0))
self.max = None # Vector((0.0, 0.0, 0.0))
def merge(self, point):
if self.min is None:
self.min = point.copy()
self.max = point.copy()
return
if point.x < self.min.x:
self.min.x = point.x
if point.y < self.min.y:
self.min.y = point.y
if point.z < self.min.z:
self.min.z = point.z
if point.x > self.max.x:
self.max.x = point.x
if point.y > self.max.y:
self.max.y = point.y
if point.z > self.max.z:
self.max.z = point.z
# Exception for a vertex with more or less elements than its vertex buffer
class VertexMaskError(Exception):
def __init__(self, oldMask, disruptMask):
self.oldMask = oldMask
self.disruptMask = disruptMask
self.elements = { ELEMENT_POSITION: "Position",
ELEMENT_NORMAL: "Normal",
ELEMENT_COLOR: "Color",
ELEMENT_UV1: "UV1",
ELEMENT_UV2: "UV2",
ELEMENT_CUBE_UV1: "Cube UV1",
ELEMENT_CUBE_UV2: "Cube UV2",
ELEMENT_TANGENT: "Tangent",
ELEMENT_BWEIGHTS: "Blend weights",
ELEMENT_BINDICES: "Blend indices" }
def __str__(self):
diff = self.oldMask ^ self.disruptMask
names = [name for mask,name in self.elements.items() if (mask & diff)]
txt = "{:04X} vs {:04X}".format(self.oldMask, self.disruptMask)
txt += "\n differences: {:s}".format(", ".join(names))
return txt
# Exception for a keyframe with more or less elements than its track
class FrameMaskError(Exception):
def __init__(self, oldMask, disruptMask, newMask):
self.oldMask = oldMask
self.disruptMask = disruptMask
self.newMask = newMask
self.elements = { TRACK_POSITION: "Position",
TRACK_ROTATION: "Rotation",
TRACK_SCALE: "Scale" }
def __str__(self):
diff = self.oldMask ^ self.disruptMask
names = [name for mask,name in self.elements.items() if (mask & diff)]
txt = "{:04X} AND {:04X} = {:04X}".format(self.oldMask, self.disruptMask, self.newMask)
txt += "\n differences: {:s}".format(", ".join(names))
return txt
# --- Model classes ---
class UrhoVertex:
def __init__(self, tVertex):
# Bit mask of elements present
self.mask = 0
# Only used by morphs, original vertex index in the not morphed vertex buffer
self.index = None
# Vertex position: Vector((0.0, 0.0, 0.0)) of floats
self.pos = tVertex.pos
if tVertex.pos:
self.mask |= ELEMENT_POSITION
# Vertex normal: Vector((0.0, 0.0, 0.0)) of floats
self.normal = tVertex.normal
if tVertex.normal:
self.mask |= ELEMENT_NORMAL
# Vertex color: (0, 0, 0, 0) of unsigned bytes
self.color = tVertex.color
if tVertex.color:
self.mask |= ELEMENT_COLOR
# Vertex UV texture coordinate: (0.0, 0.0) of floats
self.uv = tVertex.uv
if tVertex.uv:
self.mask |= ELEMENT_UV1
# Vertex UV2 texture coordinate: (0.0, 0.0) of floats
self.uv2 = tVertex.uv2
if tVertex.uv2:
self.mask |= ELEMENT_UV2
# Vertex tangent: Vector((0.0, 0.0, 0.0, 0.0)) of floats
self.tangent = tVertex.tangent
if tVertex.tangent:
self.mask |= ELEMENT_TANGENT
# List of tuples: blend weight (float), bone index (unsigned byte), mapped bone index (None if the bone is not mapped)
self.weights = [(0.0, 0, None)] * BONES_PER_VERTEX
if tVertex.weights is not None:
# Sort tuples (index, weight) by decreasing weight
sortedList = sorted(tVertex.weights, key = operator.itemgetter(1), reverse = True)
sortedList = sortedList[:BONES_PER_VERTEX]
# Normalize weights and add to the list
totalWeight = sum([t[1] for t in sortedList])
for i, t in enumerate(sortedList):
self.weights[i] = (t[1] / totalWeight, t[0], None)
self.mask |= ELEMENT_BLEND
# used by the function index() of lists
def __eq__(self, other):
return (self.pos == other.pos and self.normal == other.normal and
self.color == other.color and self.uv == other.uv)
# compare position, normal, color, UV, UV2 with another vertex, returns True is the error is insignificant
def AlmostEqual(self, other):
if not FloatListAlmostEqual(self.pos, other.pos):
return False
if not FloatListAlmostEqual(self.normal, other.normal):
return False
if self.color != other.color:
return False
if not FloatListAlmostEqual(self.uv, other.uv):
return False
if not FloatListAlmostEqual(self.uv2, other.uv2):
return False
return True
# compare position, normal, UV with another vertex, returns the error
def LodError(self, other):
# If the position is not equal, return max error
if not FloatListAlmostEqual(self.pos, other.pos):
return INFINITY
# If the angle between normals is above 30°, return max error (TODO: document this)
ncos = VectorDotProduct(self.normal, other.normal)
if ncos < cos(30 / 180 * pi):
return INFINITY
# UV are 0..1 x2, normals -1..1 x1, so this absolute error should be good
return (FloatListEqualError(self.uv, other.uv) + 1-ncos)
# not unique id of this vertex based on its position
def __hash__(self):
hashValue = 0
if self.pos:
hashValue ^= hash(self.pos.x) ^ hash(self.pos.y) ^ hash(self.pos.z)
return hashValue
# used by morph vertex calculations (see AnimatedModel::ApplyMorph)
def subtract(self, other, mask):
if mask & ELEMENT_POSITION:
self.pos -= other.pos
if mask & ELEMENT_NORMAL:
self.normal -= other.normal
if mask & ELEMENT_TANGENT:
self.tangent -= other.tangent
# tangent.w it is not modified by morphs (remember, there we
# have saved bitangent direction)
self.tangent.w = 0
class UrhoVertexBuffer:
def __init__(self):
# Flags of the elements contained in every vertex of this buffer
self.elementMask = None
# Morph min index and max index in the list vertices TODO: check
self.morphMinIndex = None
self.morphMaxIndex = None
# List of UrhoVertex
self.vertices = []
# Check if a vertex is compatible with this buffer or has different elements
def updateMask(self, vertexMask):
# Update buffer mask
if self.elementMask is None:
self.elementMask = vertexMask
elif self.elementMask != vertexMask:
oldMask = self.elementMask
# Update vertex buffer mask only if mask has the same and more bits
if (self.elementMask & vertexMask) == self.elementMask:
self.elementMask = vertexMask
raise VertexMaskError(oldMask, vertexMask)
class UrhoIndexBuffer:
def __init__(self):
# Size of each index: 2 for 16 bits, 4 for 32 bits
self.indexSize = 0
# List of triples of indices (in the vertex buffer) to draw triangles
self.indexes = []
class UrhoLodLevel:
def __init__(self):
# Distance above which we draw this LOD
self.distance = 0.0
# How to draw triangles: TRIANGLE_LIST, LINE_LIST
self.primitiveType = 0
# Index of the vertex buffer used by this LOD in the model list
self.vertexBuffer = 0
# Index of the index buffer used by this LOD in the model list
self.indexBuffer = 0
# Pointer in the index buffer where starts this LOD
self.startIndex = 0
# Length in the index buffer to complete draw this LOD
self.countIndex = 0
class UrhoGeometry:
def __init__(self):
# If the bones in the skeleton are too many for the hardware skinning, we
# search for only the bones used by this geometry, then create a map from
# the new bone index to the old bone index (in the skeleton)
self.boneMap = []
# List of UrhoLodLevel
self.lodLevels = []
# Geometry center based on the position of each triangle of the first LOD
self.center = Vector((0.0, 0.0, 0.0))
# Name of the material used (only for materials list)
self.uMaterialName = None
class UrhoVertexMorph:
def __init__(self):
# Morph name
self.name = None
# Maps from 'vertex buffer index' to 'list of vertex', these are only the
# vertices modified by the morph, not all the vertices in the buffer (each
# morphed vertex has an index to the original vertex)
self.vertexBufferMap = {}
class UrhoBone:
def __init__(self):
# Bone name
self.name = None
# Index of the parent bone in the model bones list
self.parentIndex = None
# Bone position in parent space
self.position = None
# Bone rotation in parent space
self.rotation = None
# Bone scale
self.scale = Vector((1.0, 1.0, 1.0))
# Bone transformation in skeleton space
self.matrix = None
# Inverse of the above
self.inverseMatrix = None
# Position in skeleton space
self.derivedPosition = None
# Collision sphere and/or box
self.collisionMask = 0
self.radius = None
self.boundingBox = BoundingBox()
self.length = 0
class UrhoModel:
def __init__(self):
# Model name
self.name = None
# List of UrhoVertexBuffer
self.vertexBuffers = []
# List of UrhoIndexBuffer
self.indexBuffers = []
# List of UrhoGeometry
self.geometries = []
# List of UrhoVertexMorph
self.morphs = []
# List of UrhoBone
self.bones = []
# Bounding box, contains each LOD of each geometry
self.boundingBox = BoundingBox()
# --- Animation classes ---
class UrhoKeyframe:
def __init__(self, tKeyframe):
# Bit mask of elements present
self.mask = 0
# Time position in seconds: float
self.time = tKeyframe.time
# Position: Vector((0.0, 0.0, 0.0))
self.position = tKeyframe.position
if tKeyframe.position:
self.mask |= TRACK_POSITION
# Rotation: Quaternion()
self.rotation = tKeyframe.rotation
if tKeyframe.rotation:
self.mask |= TRACK_ROTATION
# Scale: Vector((0.0, 0.0, 0.0))
self.scale = tKeyframe.scale
if tKeyframe.scale:
self.mask |= TRACK_SCALE
class UrhoTrack:
def __init__(self):
# Track name (practically same as the bone name that should be driven)
self.name = ""
# Mask of included animation data
self.elementMask = None
# Keyframes
self.keyframes = []
# Check if a vertex is compatible with this buffer or has different elements
def updateMask(self, keyframeMask):
# Update track mask
if self.elementMask is None:
self.elementMask = keyframeMask
elif self.elementMask != keyframeMask:
oldMask = self.elementMask
# Update the track mask, keep the common denominator
self.elementMask &= keyframeMask
raise FrameMaskError(oldMask, keyframeMask, self.elementMask)
class UrhoTrigger:
def __init__(self):
# Trigger name
self.name = ""
# Time in seconds: float
self.time = None
# Time as ratio: float
self.ratio = None
# Event data (variant, see typeNames[] in Variant.cpp)
self.data = None
class UrhoAnimation:
def __init__(self):
# Animation name
self.name = ""
# Length in seconds: float
self.length = 0.0
# Tracks
self.tracks = []
# Animation triggers
self.triggers = []
class UrhoMaterial:
def __init__(self):
# Material name
self.name = None
# Technique name
self.techniqueName = None
# Material diffuse color (0.0, 0.0, 0.0, 0.0) (r,g,b,a)
self.diffuseColor = None
# Material specular color (0.0, 0.0, 0.0, 0.0) (r,g,b,power)
self.specularColor = None
# Material emissive color (0.0, 0.0, 0.0) (r,g,b)
self.emissiveColor = None
# Material is two sided
self.twoSided = False
# Material is shadeless
self.shadeless = False
# Shader PS defines
self.psdefines = ""
# Shader VS defines
self.vsdefines = ""
# Textures names (no path, unique names)
# keys: diffuse, specular, normal, emissive(\ao\lightmap)
self.texturesNames = {}
def getTextures(self):
return list(self.texturesNames.values())
# --- Export options classes ---
class UrhoExportData:
def __init__(self):
# List of UrhoModel
self.models = []
# List of UrhoAnimation
self.animations = []
# List of UrhoMaterial
self.materials = []
class UrhoExportOptions:
def __init__(self):
self.splitSubMeshes = False
self.useStrictLods = True
#--------------------
# Writers
#--------------------
def UrhoWriteModel(model, filename):
if not model.vertexBuffers or not model.indexBuffers or not model.geometries:
log.error("No model data to export in {:s}".format(filename))
return
fw = BinaryFileWriter()
try:
fw.open(filename)
except Exception as e:
log.error("Cannot open file {:s} {:s}".format(filename, e))
return
# File Identifier
fw.writeAsciiStr("UMDL")
# Number of vertex buffers
fw.writeUInt(len(model.vertexBuffers))
# For each vertex buffer
for buffer in model.vertexBuffers:
# Vertex count
fw.writeUInt(len(buffer.vertices))
# Vertex element mask (determines vertex size)
mask = buffer.elementMask
fw.writeUInt(mask)
# Morphable vertex range start index
fw.writeUInt(buffer.morphMinIndex)
# Morphable vertex count
if buffer.morphMaxIndex != 0:
fw.writeUInt(buffer.morphMaxIndex - buffer.morphMinIndex + 1)
else:
fw.writeUInt(0)
# Vertex data (vertex count * vertex size)
for vertex in buffer.vertices:
if mask & ELEMENT_POSITION:
fw.writeVector3(vertex.pos)
if mask & ELEMENT_NORMAL:
fw.writeVector3(vertex.normal)
if mask & ELEMENT_COLOR:
for i in range(4):
fw.writeUByte(vertex.color[i])
if mask & ELEMENT_UV1:
for i in range(2):
fw.writeFloat(vertex.uv[i])
if mask & ELEMENT_UV2:
for i in range(2):
fw.writeFloat(vertex.uv2[i])
if mask & ELEMENT_TANGENT:
fw.writeVector3(vertex.tangent)
fw.writeFloat(vertex.tangent.w)
if mask & ELEMENT_BWEIGHTS:
for i in range(BONES_PER_VERTEX):
fw.writeFloat(vertex.weights[i][0])
if mask & ELEMENT_BINDICES:
for i in range(BONES_PER_VERTEX):
boneIndex = vertex.weights[i][1]
remappedBoneIndex = vertex.weights[i][2]
if remappedBoneIndex is not None:
boneIndex = remappedBoneIndex
fw.writeUByte(boneIndex)
# Number of index buffers
fw.writeUInt(len(model.indexBuffers))
# For each index buffer
for buffer in model.indexBuffers:
# Index count
fw.writeUInt(len(buffer.indexes))
# Index size (2 for 16-bit indices, 4 for 32-bit indices)
fw.writeUInt(buffer.indexSize)
# Index data (index count * index size)
for i in buffer.indexes:
if buffer.indexSize == 2:
fw.writeUShort(i)
else:
fw.writeUInt(i)
# Number of geometries
fw.writeUInt(len(model.geometries))
# For each geometry
for geometry in model.geometries:
# Number of bone mapping entries
fw.writeUInt(len(geometry.boneMap))
# For each bone
for bone in geometry.boneMap:
fw.writeUInt(bone)
# Number of LOD levels
fw.writeUInt(len(geometry.lodLevels))
# For each LOD level
for lod in geometry.lodLevels:
# LOD distance
fw.writeFloat(lod.distance)
# Primitive type (0 = triangle list, 1 = line list)
fw.writeUInt(lod.primitiveType)
# Vertex buffer index, starting from 0
fw.writeUInt(lod.vertexBuffer)
# Index buffer index, starting from 0
fw.writeUInt(lod.indexBuffer)
# Draw range: index start
fw.writeUInt(lod.startIndex)
# Draw range: index count
fw.writeUInt(lod.countIndex)
# Number of morphs
fw.writeUInt(len(model.morphs))
# For each morph
for morph in model.morphs:
# Name of morph
fw.writeAsciiStr(morph.name)
fw.writeUByte(0)
# Number of affected vertex buffers
fw.writeUInt(len(morph.vertexBufferMap))
# For each affected vertex buffers
for morphBufferIndex, morphBuffer in sorted(morph.vertexBufferMap.items()):
# Vertex buffer index, starting from 0
fw.writeUInt(morphBufferIndex)
# Vertex element mask for morph data
mask = (morphBuffer.elementMask & MORPH_ELEMENTS)
fw.writeUInt(mask)
# Vertex count
fw.writeUInt(len(morphBuffer.vertices))
# For each vertex:
for vertex in morphBuffer.vertices:
# Moprh vertex index
fw.writeUInt(vertex.index)
# Moprh vertex Position
if mask & ELEMENT_POSITION:
fw.writeVector3(vertex.pos)
# Moprh vertex Normal
if mask & ELEMENT_NORMAL:
fw.writeVector3(vertex.normal)
# Moprh vertex Tangent
if mask & ELEMENT_TANGENT:
fw.writeVector3(vertex.tangent)
# Number of bones (may be 0)
fw.writeUInt(len(model.bones))
# For each bone
for bone in model.bones:
# Bone name
fw.writeAsciiStr(bone.name)
fw.writeUByte(0)
# Parent bone index starting from 0
fw.writeUInt(bone.parentIndex)
# Initial position
fw.writeVector3(bone.position)
# Initial rotation
fw.writeQuaternion(bone.rotation)
# Initial scale
fw.writeVector3(bone.scale)
# 4x3 offset matrix for skinning
for row in bone.inverseMatrix[:3]:
for v in row:
fw.writeFloat(v)
# Bone collision info bitmask
fw.writeUByte(bone.collisionMask)
# Bone radius
if bone.collisionMask & BONE_BOUNDING_SPHERE:
fw.writeFloat(bone.radius)
# Bone bounding box minimum and maximum
if bone.collisionMask & BONE_BOUNDING_BOX:
fw.writeVector3(bone.boundingBox.min)
fw.writeVector3(bone.boundingBox.max)
# Model bounding box minimum
fw.writeVector3(model.boundingBox.min)
# Model bounding box maximum
fw.writeVector3(model.boundingBox.max)
# For each geometry
for geometry in model.geometries:
# Geometry center
fw.writeVector3(geometry.center)
fw.close()
def UrhoWriteAnimation(animation, filename):
if not animation.tracks:
log.error("No animation data to export in {:s}".format(filename))
return
fw = BinaryFileWriter()
try:
fw.open(filename)
except Exception as e:
log.error("Cannot open file {:s} {:s}".format(filename, e))
return
# File Identifier
fw.writeAsciiStr("UANI")
# Animation name
fw.writeAsciiStr(animation.name)
fw.writeUByte(0)
# Length in seconds
fw.writeFloat(animation.length)
# Number of tracks
fw.writeUInt(len(animation.tracks))
# For each track
for track in animation.tracks:
# Track name (practically same as the bone name that should be driven)
fw.writeAsciiStr(track.name)
fw.writeUByte(0)
# Mask of included animation data
mask = track.elementMask
fw.writeUByte(track.elementMask)
# Number of tracks
fw.writeUInt(len(track.keyframes))
# For each keyframe
for keyframe in track.keyframes:
# Time position in seconds: float
fw.writeFloat(keyframe.time)
# Keyframe position
if mask & TRACK_POSITION:
fw.writeVector3(keyframe.position)
# Keyframe rotation
if mask & TRACK_ROTATION:
fw.writeQuaternion(keyframe.rotation)
# Keyframe scale
if mask & TRACK_SCALE:
fw.writeVector3(keyframe.scale)
fw.close()
# As described in Animation::Load, Animation::Save
def UrhoWriteTriggers(triggersList, filename, fOptions):
triggersElem = ET.Element('animation')
for trigger in triggersList:
triggerElem = ET.SubElement(triggersElem, "trigger")
if trigger.time is not None:
triggerElem.set("time", FloatToString(trigger.time))
if trigger.ratio is not None:
triggerElem.set("normalizedtime", FloatToString(trigger.ratio))
# We use a string variant, for other types See typeNames[] in Variant.cpp
# and XMLElement::GetVariant()
triggerElem.set("type", "String")
triggerElem.set("value", str(trigger.data))
WriteXmlFile(triggersElem, filename, fOptions)
#--------------------
# Utils
#--------------------
# Search for the most complete element mask
def GetMaxElementMask(indices, vertices):
maxElementMask = 0
maxElementMaskCount = 0
for vertexIndex in indices:
tVertex = vertices[vertexIndex]
uVertex = UrhoVertex(tVertex)
count = bin(uVertex.mask).count("1")
if maxElementMaskCount < count:
maxElementMaskCount = count
maxElementMask = uVertex.mask
if maxElementMask:
return maxElementMask
return None
#---------------------------------------
# NOTE: only different geometries use different buffers
# NOTE: LODs must use the same vertex buffer, and so the same vertices. This means
# normals and tangents are a bit off, but they are good infact they are approximations
# of the first LOD which uses those vertices.
# Creating a LOD we search for the similar vertex.
# NOTE: vertex buffers can have different mask (ex. skeleton weights)
# NOTE: morph must have what geometry they refer to, or the vertex buffer or better
# the index buffer as vertex buffer is in common.
# NOTE: a morph can affect more than one vertex buffer
# NOTE: if a vertex buffer has blendweights then all its vertices must have it
# NOTE: if we use index() we must have __EQ__ in the class.
# NOTE: don't use index(), it's slow.
#--------------------
# Urho exporter
#--------------------
def UrhoExport(tData, uExportOptions, uExportData, errorsMem):
global MAX_SKIN_MATRICES
global BONES_PER_VERTEX
if uExportOptions.bonesPerGeometry:
MAX_SKIN_MATRICES = uExportOptions.bonesPerGeometry
if uExportOptions.bonesPerVertex:
BONES_PER_VERTEX = uExportOptions.bonesPerVertex
uModel = UrhoModel()
uModel.name = tData.objectName
uExportData.models.append(uModel)
# For each bone
for boneName, bone in tData.bonesMap.items():
uBoneIndex = len(uModel.bones)
# Sanity check for the OrderedDict
assert bone.index == uBoneIndex
uBone = UrhoBone()
uModel.bones.append(uBone)
uBone.name = boneName
if bone.parentName:
# Child bone
uBone.parentIndex = tData.bonesMap[bone.parentName].index
else:
# Root bone
uBone.parentIndex = uBoneIndex
uBone.position = bone.bindPosition
uBone.rotation = bone.bindRotation
uBone.scale = bone.bindScale
uBone.matrix = bone.worldTransform
uBone.inverseMatrix = uBone.matrix.inverted()
uBone.derivedPosition = uBone.matrix.to_translation()
uBone.length = bone.length
totalVertices = len(tData.verticesList)
# Search in geometries for the maximum number of vertices
maxLodVertices = 0
for tGeometry in tData.geometriesList:
for tLodLevel in tGeometry.lodLevels:
vertexCount = len(tLodLevel.indexSet)
if vertexCount > maxLodVertices:
maxLodVertices = vertexCount
# If one big buffer needs a 32 bits index but each geometry needs only a 16 bits
# index then try to use a different buffer for each geometry
useOneBuffer = True
if uExportOptions.splitSubMeshes or (totalVertices > 65535 and maxLodVertices <= 65535):
useOneBuffer = False
# Urho lod vertex buffer
vertexBuffer = None
# Urho lod index buffer
indexBuffer = None
# Maps old vertex index to Urho vertex buffer index and Urho vertex index
modelIndexMap = {}
# For each geometry
for tGeometry in tData.geometriesList:
uGeometry = UrhoGeometry()
uModel.geometries.append(uGeometry)
geomIndex = len(uModel.geometries) - 1
# Material name (can be None)
uGeometry.uMaterialName = tGeometry.materialName
# Start value for geometry center (one for each geometry)
center = Vector((0.0, 0.0, 0.0))
# Set of remapped vertices
remappedVertices = set()
# For each LOD level
for lodIndex, tLodLevel in enumerate(tGeometry.lodLevels):
uLodLevel = UrhoLodLevel()
uGeometry.lodLevels.append(uLodLevel)
if lodIndex == 0 and tLodLevel.distance != 0.0:
# Note: if we miss a LOD, its range will be covered by the following LOD (which is this one),
# this can cause overlapping between LODs of different geometries
log.error("First LOD of object {:s} Geometry{:d} must have 0.0 distance (found {:.3f})"
.format(uModel.name, geomIndex, tLodLevel.distance))
uLodLevel.distance = tLodLevel.distance
uLodLevel.primitiveType = TRIANGLE_LIST
# If needed add a new vertex buffer (only for first LOD of a geometry)
# For remapping to work a geometry and its LODs must use only one buffer
if vertexBuffer is None or (lodIndex == 0 and not useOneBuffer):
vertexBuffer = UrhoVertexBuffer()
uModel.vertexBuffers.append(vertexBuffer)
uVerticesMap = {}
# If needed add a new index buffer (only for first LOD of a geometry)
if indexBuffer is None or (lodIndex == 0 and not useOneBuffer):
indexBuffer = UrhoIndexBuffer()
uModel.indexBuffers.append(indexBuffer)
uLodLevel.startIndex = 0
else:
uLodLevel.startIndex = len(indexBuffer.indexes)
# Set how many indices the LOD level will use
uLodLevel.countIndex = len(tLodLevel.triangleList) * 3
# Set lod vertex and index buffers
uLodLevel.vertexBuffer = len(uModel.vertexBuffers) - 1
uLodLevel.indexBuffer = len(uModel.indexBuffers) - 1
##print("Geometry{:d} LOD{:d} using: vertex buffer {:d} ({:d}), index buffer {:d} ({:d})"
## .format(geomIndex, lodIndex, uLodLevel.vertexBuffer, len(tLodLevel.indexSet),
## uLodLevel.indexBuffer, uLodLevel.countIndex))
# Maps old vertex index to new vertex index in the new Urho buffer
indexMap = {}
# Errors helpers
warningNewVertices = False
# Try to guess the most complete element mask
randomIndices = random.sample(tLodLevel.indexSet, min(30, len(tLodLevel.indexSet)) )
guessedElementMask = GetMaxElementMask(randomIndices, tData.verticesList)
if vertexBuffer.elementMask is None and guessedElementMask:
vertexBuffer.elementMask = guessedElementMask
# Add vertices to the vertex buffer
for tVertexIndex in tLodLevel.indexSet:
tVertex = tData.verticesList[tVertexIndex]
# Create a Urho vertex
uVertex = UrhoVertex(tVertex)
try:
vertexBuffer.updateMask(uVertex.mask)
except VertexMaskError as e:
if not tVertex.blenderIndex is None:
errorsIndices = errorsMem.Get("element mask " + str(e), set() )
errorsIndices.add(tVertex.blenderIndex)
log.warning("Incompatible vertex elements in object {:s}, {!s}".format(uModel.name, e))
# All that this code do is "uVertexIndex = vertexBuffer.vertices.index(uVertex)", but we use
# a map to speed things up.
# Get an hash of the vertex (more vertices can have the same hash)
uVertexHash = hash(uVertex)
try:
# Get the list of vertices indices with the same hash
uVerticesMapList = uVerticesMap[uVertexHash]
except KeyError:
# If the hash is not mapped, create a new list (we could use a set but a list is faster)
uVerticesMapList = []
uVerticesMap[uVertexHash] = uVerticesMapList
uVertexIndex = None
if lodIndex == 0 or uExportOptions.useStrictLods:
# For each index in the list, get the corresponding vertex and test if it is equal to tVertex.
# If Position, Normal and UV are the same, it must be the same vertex, get its index.
for ivl in uVerticesMapList:
if vertexBuffer.vertices[ivl].AlmostEqual(uVertex):
uVertexIndex = ivl
break
else:
# For successive LODs, we are more permissive, the vertex position must be the same, but for
# the normal and UV we will search the best match in the vertices available.
bestLodError = INFINITY
for ivl in uVerticesMapList:
lodError = vertexBuffer.vertices[ivl].LodError(uVertex)
if lodError < bestLodError:
bestLodError = lodError
uVertexIndex = ivl
# If we cannot find it, the vertex is new, add it to the list, and its index to the map list
if uVertexIndex is None:
uVertexIndex = len(vertexBuffer.vertices)
vertexBuffer.vertices.append(uVertex)
uVerticesMapList.append(uVertexIndex)
if lodIndex != 0:
warningNewVertices = True
# Populate the 'old tVertex index' to 'new uVertex index' map
if not tVertexIndex in indexMap:
indexMap[tVertexIndex] = uVertexIndex
elif indexMap[tVertexIndex] != uVertexIndex:
log.error("Conflict in vertex index map of object {:s}".format(uModel.name))
# Update the model bounding box (common to all geometries)
if vertexBuffer.elementMask & ELEMENT_POSITION:
uModel.boundingBox.merge(uVertex.pos)
if warningNewVertices:
log.warning("LOD {:d} of object {:s} Geometry{:d} has new vertices."
.format(lodIndex, uModel.name, geomIndex))
# Add the local vertex map to the global map
for oldIndex, newIndex in indexMap.items():
# We create a map: Map[old index] = Set( Tuple(new buffer index, new vertex index) )
# Search if this vertex index was already mapped, get its Set or add a new one.
# We need a Set because a vertex can be copied in more than one vertex buffer.
try:
vbviSet = modelIndexMap[oldIndex]
except KeyError:
vbviSet = set()
modelIndexMap[oldIndex] = vbviSet
# Add a tuple to the Set: new buffer index, new vertex index
vbvi = (uLodLevel.vertexBuffer, newIndex)
vbviSet.add(vbvi)
# Add indices to the index buffer
centerCount = 0
for triangle in tLodLevel.triangleList:
for tVertexIndex in triangle:
uVertexIndex = indexMap[tVertexIndex]
indexBuffer.indexes.append(uVertexIndex)
# Update geometry center (only for the first LOD)
if (lodIndex == 0) and (vertexBuffer.elementMask & ELEMENT_POSITION):
centerCount += 1
center += vertexBuffer.vertices[uVertexIndex].pos;
# Update geometry center (only for the first LOD)
if lodIndex == 0 and centerCount:
uGeometry.center = center / centerCount;