-
Notifications
You must be signed in to change notification settings - Fork 0
/
modexport.py
286 lines (218 loc) · 10.2 KB
/
modexport.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
bl_info = {
"name": "JGE Model Export",
"description": "Exports to proprietary .MOD format",
"author": "Jason H",
"version": (1, 0),
"blender": (2, 65, 0),
"location": "File > Import-Export",
"warning": "", # used for warning icon and text in addons panel
"doc_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
"Scripts/My_Script",
"tracker_url": "https://developer.blender.org/maniphest/task/edit/form/2/",
"support": "COMMUNITY",
"category": "Import-Export",
}
import bpy
import array
from bpy.props import (
BoolProperty,
FloatProperty,
StringProperty,
EnumProperty,
)
from bpy_extras.io_utils import (
ImportHelper,
ExportHelper,
orientation_helper_factory,
path_reference_mode,
axis_conversion,
)
IOOBJOrientationHelper = orientation_helper_factory("IOOBJOrientationHelper", axis_forward='-Z', axis_up='Y')
class ExportMOD(bpy.types.Operator, ExportHelper, IOOBJOrientationHelper):
bl_idname = "export_scene_normals.mod"
bl_label = 'Export MOD'
bl_options = {'PRESET'}
filename_ext = ".mod"
filter_glob = StringProperty(
default = "*.mod",
options = {'HIDDEN'},
)
def execute(self, context):
# Force into object mode
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
weightsUnsorted = [] # \ The weights and respective bones, in the same order as mesh.vertices
boneIdsUnsorted = [] # /
objects = []
vertices = [] # \
texCoords = [] # |
normals = [] # | .. Raw mesh data
weights = [] # |
boneIds = [] # |
indices = [] # /
translation = [] # In case the mesh is translated in blender
maxInfluence = 3 # Max number of bones allows to influence a single vertex
i = 0
for object in bpy.data.objects:
if object.type == "MESH":
x = object.matrix_local[0].w
y = object.matrix_local[1].w
z = object.matrix_local[2].w
translation.append([x, y, z])
break
i += 1
print("Beginning .MOD export...")
for mesh in bpy.data.meshes:
#set vertices
for vertex in mesh.vertices:
# Get a list of the non-zero group weightings for the vertex
nonZero = []
for g in vertex.groups:
g.weight = round(g.weight, 4)
if g.weight < .0001:
continue
nonZero.append(g)
# Sort them by weight decending
byWeight = sorted(nonZero, key=lambda group: group.weight)
byWeight.reverse()
# As long as there are more than 'maxInfluence' bones, take the lowest influence bone
# and distribute the weight to the other bones.
while len(byWeight) > maxInfluence:
print("Distributing weight for vertex %d" % (vertex.index))
# Pop the lowest influence off and compute how much should go to the other bones.
minInfluence = byWeight.pop()
distributeWeight = minInfluence.weight / len(byWeight)
minInfluence.weight = 0
# Add this amount to the other bones
for influence in byWeight:
influence.weight = influence.weight + distributeWeight
# Round off the remaining values.
for influence in byWeight:
influence.weight = round(influence.weight, 4)
for influence in byWeight:
weightsUnsorted.append( influence.weight )
boneIdsUnsorted.append( influence.group )
for x in range(len(byWeight) - 1, maxInfluence):
weightsUnsorted.append( 0 )
boneIdsUnsorted.append( 0 )
# Since when parsing .MOD files, vertices have a 1:1 relationship with texture coords, normals, weights, and bone IDs,
# we must reorganize this data, as in blender texture coords exists w.r.t. faces
newVertexArray = []
newTexCoordArray = []
curIndexId = -1
for polygon in mesh.polygons:
for j in range(0,3):
exists = False
curIndexId += 1
for k in range(0, len(newVertexArray)):
if newVertexArray[k] == polygon.vertices[j] and curIndexId == newTexCoordArray[k]:
indices.append(k)
exists = True
break
if not exists:
newVertexArray.append(polygon.vertices[j])
newTexCoordArray.append(curIndexId)
indices.append(len(newVertexArray) - 1)
"""
SET OBJECT DATA
"""
objects.append( 0 ) # materialId (placeholder)
objects.append( len( mesh.vertices ) ) # numVertices
objects.append( len( mesh.polygons ) * 3 ) # numFaces
print(str(len( mesh.vertices )) + " vertices")
print(str(len( mesh.polygons )) + " faces")
"""
SET MESH DATA
"""
for ww in range(len(newVertexArray)):
vertId = newVertexArray[ww]
texCoordId = newTexCoordArray[ww]
vertex = mesh.vertices[vertId]
x = vertex.co.x
y = vertex.co.y
z = vertex.co.z
vertices.extend([y + translation[0][1], z + translation[0][2], x + translation[0][0]])
if mesh.uv_layers is None:
texCoords.extend([0, 0])
else:
texCoords.extend( mesh.uv_layers.active.data[texCoordId].uv )
normals.extend(vertex.normal)
weights.append(weightsUnsorted[vertId])
boneIds.append(boneIdsUnsorted[vertId])
"""
SET ARMATURE DATA
"""
boneNames = []
boneNameOffests = []
boneMatrices = []
boneParents = []
offset = 0
# TODO: Find better way to do this
rig = None # bpy.data.objects['Armature']
for armature in [ob for ob in bpy.data.objects if ob.type == 'ARMATURE']:
rig = armature
break
if rig is not None:
boneNameOffests.append(len( rig.data.bones )) # number of bones
for x, b in enumerate(rig.data.bones):
tempString = b.name
tempList = [ord(c) for c in tempString]
boneNames.extend( tempList )
boneNameOffests.append( offset )
offset += len( tempList )
boneNameOffests.append( len( tempList ) )
for j in range(3):
for i in range(3):
boneMatrices.append( b.matrix[i][j] )
parentid = -1
if b.parent is not None:
parentid = rig.data.bones.find( b.parent.name )
boneParents.append( parentid )
"""
WRITE EVERYTHING TO FILE
"""
print("Exporting to: " + self.filepath)
f = open(self.filepath, "wb")
magicNumber = array.array('b', 'MOD4'.encode())
objectsArray = array.array('i', objects)
verticesArray = array.array('f', vertices)
texCoordArray = array.array('f', texCoords)
normalsArray = array.array('f', normals)
weightsArray = array.array('f', weights)
boneIdsArray = array.array('b', boneIds)
indexArray = array.array('i', indices)
boneNamesArray = array.array('b', boneNames)
boneNameOffestsArray = array.array('i', boneNameOffests)
boneParentsArray = array.array('b', boneParents)
boneMatricesArray = array.array('f', boneMatrices)
magicNumber.tofile(f)
objectsArray.tofile(f)
verticesArray.tofile(f)
texCoordArray.tofile(f)
normalsArray.tofile(f)
weightsArray.tofile(f)
boneIdsArray.tofile(f)
indexArray.tofile(f)
if rig is None:
array.array('b', [0]).tofile(f)
print("No armature found, skipping")
else:
array.array('b', [1]).tofile(f)
boneNameOffestsArray.tofile(f)
boneNamesArray.tofile(f)
boneParentsArray.tofile(f)
boneMatricesArray.tofile(f)
f.close()
print("Finished")
break
return {'FINISHED'}
def menu_func_export(self, context):
self.layout.operator(ExportMOD.bl_idname, text="Model (.mod)")
def register():
bpy.utils.register_module(__name__)
bpy.types.INFO_MT_file_export.append(menu_func_export)
def unregister():
bpy.utils.unregister_module(__name__)
bpy.types.INFO_MT_file_export.remove(menu_func_export)
if __name__ == "__main__":
register()