Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
PoseBones = Object.pose.bones
for Bone in RootBonesList:
if Config.Verbose:
print(" Writing Root Bone: {}...".format(Bone.name))
PoseBone = PoseBones[Bone.name]
WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, skelFile, True)
if Config.Verbose:
print(" Done")
WriteArmatureChildBones(Config, Object, Bone.children, skelFile)
def WriteArmatureChildBones(Config, Object, BonesList, skelFile):
PoseBones = Object.pose.bones
for Bone in BonesList:
if Config.Verbose:
print(" Writing Child Bone: {}...".format(Bone.name))
PoseBone = PoseBones[Bone.name]
WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, skelFile, True)
if Config.Verbose:
print(" Done")
WriteArmatureChildBones(Config, Object, Bone.children, skelFile)
def WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, File, isRestPoseNotAnimPose):
# Compute armature scale :
# Many others exporter require sthe user to do Apply Scale in Object Mode to have 1,1,1 scale and so that anim data are correctly scaled
# Here we retreive the Scale of the Armture Object.matrix_world.to_scale() and we use it to scale the bones :-)
# So new Blender user should not complain about bad animation export if they forgot to apply the Scale to 1,1,1
armScale = Object.matrix_world.to_scale()
armRot = Object.matrix_world.to_quaternion()
if isRestPoseNotAnimPose:
#skel file, bone header
File.write("\tCIwAnimBone\n")
File.write("\t{\n")
File.write("\t\tname \"%s\"\n" % StripBoneName(Bone.name))
#get bone local matrix for rest pose
if Bone.parent:
File.write("\t\tparent \"%s\"\n" % StripBoneName(Bone.parent.name))
localmat = Bone.parent.matrix_local.inverted() * Bone.matrix_local
else:
localmat = Bone.matrix_local
else:
#anim file, bone header
File.write("\t\t\n")
File.write("\t\tbone \"%s\" \n" % StripBoneName(Bone.name))
localmat = PoseBone.matrix
#get bone local matrix for current anim pose
if Bone.parent:
ParentPoseBone = PoseBones[Bone.parent.name]
localmat = ParentPoseBone.matrix.inverted() * PoseBone.matrix
else:
localmat = PoseBone.matrix
if not Bone.parent:
#Flip Y Z axes (only on root bone, other bones are local to root bones, so no need to rotate)
X_ROT = mathutils.Matrix.Rotation(-math.pi / 2, 4, 'X')
if Config.MergeModes > 0:
# Merge mode is in world coordinates and not in model coordinates: so apply the world coordinate on the rootbone
localmat = X_ROT * Object.matrix_world * localmat
armScale.x = armScale.y = armScale.z = 1
else:
localmat= X_ROT * armRot.to_matrix().to_4x4() * localmat #apply the armature rotation on the root bone
loc = localmat.to_translation()
quat = localmat.to_quaternion()
#Scale the bone
loc.x *= (armScale.x * Config.Scale)
loc.y *= (armScale.y * Config.Scale)
loc.z *= (armScale.z * Config.Scale)
File.write("\t\tpos { %.9f, %.9f, %.9f }\n" % (loc[0], loc[1], loc[2]))
File.write("\t\trot { %.9f, %.9f, %.9f, %.9f }\n" % (quat.w, quat.x, quat.y, quat.z))
if isRestPoseNotAnimPose:
File.write("\t}\n")
def WriteKeyedAnimationSet(Config, Scene):
for Object in [Object for Object in Config.ObjectList if Object.animation_data]:
if Config.Verbose:
print(" Writing Animation Data for Object: {}".format(Object.name))
actions = []
if Config.ExportAnimationActions == 0 and Object.animation_data.action:
actions.append(Object.animation_data.action)
else:
actions = bpy.data.actions[:]
DefaultAction = Object.animation_data.action
for Action in actions:
if Config.ExportAnimationActions == 0:
animFileName = StripName(Object.name)
else:
Object.animation_data.action = Action
animFileName = "%s_%s" % (StripName(Object.name),StripName(Action.name))
#Object animated (aka single bone object)
#build key frame time list
if Config.ExportAnimationFrames == 1:
# Exports only key frames
for FCurve in Action.fcurves:
for Keyframe in FCurve.keyframe_points:
if Keyframe.co[0] < Scene.frame_start:
keyframeTimes.add(Scene.frame_start)
elif Keyframe.co[0] > Scene.frame_end:
keyframeTimes.add(Scene.frame_end)
else:
keyframeTimes.add(int(Keyframe.co[0]))
else:
# Exports all frames
Benoit Muller
committed
keyframeTimes.update(range(Scene.frame_start, Scene.frame_end + 1, 1))
keyframeTimes = list(keyframeTimes)
keyframeTimes.sort()
if len(keyframeTimes):
#Create the anim file for offset animation (or single bone animation
animfullname = os.path.dirname(Config.FilePath) + os.sep + "anims" + os.sep + "%s_offset.anim" % animFileName
## ensure_dir(animfullname)
## if Config.Verbose:
## print(" Creating anim file (single bone animation) %s" % (animfullname))
## animFile = open(animfullname, "w")
## animFile.write('// anim file exported from : %r\n' % os.path.basename(bpy.data.filepath))
## animFile.write("CIwAnim\n")
## animFile.write("{\n")
## animFile.write("\tent \"%s\"\n" % (StripName(Object.name)))
## animFile.write("\tskeleton \"SingleBone\"\n")
## animFile.write("\t\t\n")
##
## Config.File.write("\t\".\\anims\\%s_offset.anim\"\n" % animFileName))
##
## for KeyframeTime in keyframeTimes:
## #Scene.frame_set(KeyframeTime)
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
## animFile.write("\tCIwAnimKeyFrame\n")
## animFile.write("\t{\n")
## animFile.write("\t\ttime %.2f // frame num %d \n" % (KeyframeTime/Config.AnimFPS, KeyframeTime))
## animFile.write("\t\t\n")
## animFile.write("\t\tbone \"SingleBone\" \n")
## #postion
## posx = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "location" and FCurve.array_index == 0: posx = FCurve.evaluate(KeyframeTime)
## posy = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "location" and FCurve.array_index == 1: posy = FCurve.evaluate(KeyframeTime)
## posz = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "location" and FCurve.array_index == 2: posz = FCurve.evaluate(KeyframeTime)
## animFile.write("\t\tpos {%.9f,%.9f,%.9f}\n" % (posx, posy, posz))
## #rotation
## rot = Euler()
## rot[0] = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "rotation_euler" and FCurve.array_index == 1: rot[0] = FCurve.evaluate(KeyframeTime)
## rot[1] = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "rotation_euler" and FCurve.array_index == 2: rot[1] = FCurve.evaluate(KeyframeTime)
## rot[2] = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "rotation_euler" and FCurve.array_index == 3: rot[2] = FCurve.evaluate(KeyframeTime)
## rot = rot.to_quaternion()
## animFile.write("\t\trot {%.9f,%.9f,%.9f,%.9f}\n" % (rot[0], rot[1], rot[2], rot[3]))
## #scale
## scalex = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "scale" and FCurve.array_index == 0: scalex = FCurve.evaluate(KeyframeTime)
## scaley = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "scale" and FCurve.array_index == 1: scaley = FCurve.evaluate(KeyframeTime)
## scalez = 0
## for FCurve in Action.fcurves:
## if FCurve.data_path == "scale" and FCurve.array_index == 2: scalez = FCurve.evaluate(KeyframeTime)
## animFile.write("\t\t//scale {%.9f,%.9f,%.9f}\n" % (scalex, scaley, scalez))
## #keyframe done
## animFile.write("\t}\n")
## animFile.write("}\n")
## animFile.close()
else:
if Config.Verbose:
print(" Object %s has no useable animation data." % (StripName(Object.name)))
if Config.ExportArmatures and Object.type == "ARMATURE":
if Config.Verbose:
print(" Writing Armature Bone Animation Data...\n")
PoseBones = Object.pose.bones
Bones = Object.data.bones
#riged bones animated
#build key frame time list
keyframeTimes = set()
if Config.ExportAnimationFrames == 1:
# Exports only key frames
for FCurve in Action.fcurves:
for Keyframe in FCurve.keyframe_points:
if Keyframe.co[0] < Scene.frame_start:
keyframeTimes.add(Scene.frame_start)
elif Keyframe.co[0] > Scene.frame_end:
keyframeTimes.add(Scene.frame_end)
else:
keyframeTimes.add(int(Keyframe.co[0]))
else:
# Exports all frame
Benoit Muller
committed
keyframeTimes.update(range(Scene.frame_start, Scene.frame_end + 1, 1))
keyframeTimes = list(keyframeTimes)
keyframeTimes.sort()
Benoit Muller
committed
if Config.Verbose:
print("Exporting frames: ")
print(keyframeTimes)
if (Scene.frame_preview_end > Scene.frame_end):
print(" WARNING: END Frame of animation in UI preview is Higher than the Scene Frame end:\n Scene.frame_end %d versus Scene.frame_preview_end %d.\n"
% (Scene.frame_end, Scene.frame_preview_end))
print(" => You might need to change the Scene End Frame, to match the current UI preview frame end...\n=> if you don't want to miss end of animation.\n")
if len(keyframeTimes):
#Create the anim file
animfullname = os.path.dirname(Config.FilePath) + os.sep + "anims" + os.sep + "%s.anim" % animFileName
ensure_dir(animfullname)
if Config.Verbose:
print(" Creating anim file (bones animation) %s\n" % (animfullname))
print(" Frame count %d \n" % (len(keyframeTimes)))
animFile = open(animfullname, "w")
animFile.write('// anim file exported from : %r\n' % os.path.basename(bpy.data.filepath))
animFile.write("CIwAnim\n")
animFile.write("{\n")
animFile.write("\tskeleton \"%s\"\n" % (StripName(Object.name)))
animFile.write("\t\t\n")
Config.File.write("\t\".\\anims\\%s.anim\"\n" % animFileName)
for KeyframeTime in keyframeTimes:
if Config.Verbose:
print(" Writing Frame %d:" % KeyframeTime)
animFile.write("\tCIwAnimKeyFrame\n")
animFile.write("\t{\n")
animFile.write("\t\ttime %.2f // frame num %d \n" % (KeyframeTime / Config.AnimFPS, KeyframeTime))
#for every frame write bones positions
Scene.frame_set(KeyframeTime)
for PoseBone in PoseBones:
if Config.Verbose:
print(" Writing Bone: {}...".format(PoseBone.name))
animFile.write("\t\t\n")
Bone = Bones[PoseBone.name]
WriteBonePosition(Config, Object, Bone, PoseBones, PoseBone, animFile, False)
#keyframe done
animFile.write("\t}\n")
animFile.write("}\n")
animFile.close()
else:
if Config.Verbose:
print(" Object %s has no useable animation data." % (StripName(Object.name)))
if Config.ExportAnimationActions == 1:
#set back the original default animation
Object.animation_data.action = DefaultAction
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
if Config.Verbose:
print(" Done") #Done with Object
################## Utilities
def StripBoneName(name):
return name.replace(" ", "")
def StripName(Name):
def ReplaceSet(String, OldSet, NewChar):
for OldChar in OldSet:
String = String.replace(OldChar, NewChar)
return String
import string
NewName = ReplaceSet(Name, string.punctuation + " ", "_")
return NewName
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
def CloseFile(Config):
if Config.Verbose:
print("Closing File...")
Config.File.close()
if Config.Verbose:
print("Done")
CoordinateSystems = (
("1", "Left-Handed", ""),
("2", "Right-Handed", ""),
)
AnimationFrameModes = (
("0", "None", ""),
("1", "Keyframes Only", ""),
("2", "Full Animation", ""),
)
AnimationActions = (
("0", "Default Animation", ""),
("1", "All Animations", ""),
)
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
ExportModes = (
("1", "All Objects", ""),
("2", "Selected Objects", ""),
)
MergeModes = (
("0", "None", ""),
("1", "Merge in one big Mesh", ""),
("2", "Merge in unique Geo File containing several meshes", ""),
)
from bpy.props import StringProperty, EnumProperty, BoolProperty, IntProperty
class MarmaladeExporter(bpy.types.Operator):
"""Export to the Marmalade model format (.group)"""
bl_idname = "export.marmalade"
bl_label = "Export Marmalade"
filepath = StringProperty(subtype='FILE_PATH')
#Export Mode
ExportMode = EnumProperty(
name="Export",
description="Select which objects to export. Only Mesh, Empty, " \
"and Armature objects will be exported",
items=ExportModes,
default="1")
MergeModes = EnumProperty(
name="Merge",
description="Select if objects should be merged in one Geo File (it can be usefull if a scene is done by several cube/forms)." \
"Do not merge rigged character that have an armature.",
items=MergeModes,
default="0")
#General Options
Scale = IntProperty(
name="Scale Percent",
description="Scale percentage applied for export",
default=100, min=1, max=1000)
FlipNormals = BoolProperty(
name="Flip Normals",
description="",
default=False)
ApplyModifiers = BoolProperty(
name="Apply Modifiers",
description="Apply object modifiers before export",
default=False)
ExportVertexColors = BoolProperty(
name="Export Vertices Colors",
description="Export colors set on vertices, if any",
default=True)
ExportMaterialColors = BoolProperty(
name="Export Material Colors",
description="Ambient color is exported on the Material",
default=True)
ExportTextures = BoolProperty(
name="Export Textures and UVs",
description="Exports UVs and Reference external image files to be used by the model",
default=True)
CopyTextureFiles = BoolProperty(
name="Copy Textures Files",
description="Copy referenced Textures files in the models\\textures directory",
default=True)
ExportArmatures = BoolProperty(
name="Export Armatures",
description="Export the bones of any armatures to deform meshes",
default=True)
ExportAnimationFrames = EnumProperty(
name="Animations Frames",
description="Select the type of animations to export. Only object " \
"and armature bone animations can be exported. Keyframes exports only the keyed frames" \
"Full Animation exports every frames, None disables animationq export. ",
items=AnimationFrameModes,
ExportAnimationActions = EnumProperty(
name="Animations Actions",
description="By default only the Default Animation Action assoiated to an armature is exported." \
"However if you have defined several animations on the same armature,"\
"you can select to export all animations. You can see the list of animation actions in the DopeSheet window.",
items=AnimationActions,
default="0")
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
if bpy.context.scene:
defFPS = bpy.context.scene.render.fps
else:
defFPS = 30
AnimFPS = IntProperty(
name="Animation FPS",
description="Frame rate used to export animation in seconds (can be used to artficially slow down the exported animation, or to speed up it",
default=defFPS, min=1, max=300)
#Advance Options
CoordinateSystem = EnumProperty(
name="System",
description="Select a coordinate system to export to",
items=CoordinateSystems,
default="1")
Verbose = BoolProperty(
name="Verbose",
description="Run the exporter in debug mode. Check the console for output",
default=True)
def execute(self, context):
#Append .group
FilePath = bpy.path.ensure_ext(self.filepath, ".group")
Config = MarmaladeExporterSettings(context,
FilePath,
CoordinateSystem=self.CoordinateSystem,
FlipNormals=self.FlipNormals,
ApplyModifiers=self.ApplyModifiers,
Scale=self.Scale,
AnimFPS=self.AnimFPS,
ExportVertexColors=self.ExportVertexColors,
ExportMaterialColors=self.ExportMaterialColors,
ExportTextures=self.ExportTextures,
CopyTextureFiles=self.CopyTextureFiles,
ExportArmatures=self.ExportArmatures,
ExportAnimationFrames=self.ExportAnimationFrames,
ExportAnimationActions=self.ExportAnimationActions,
ExportMode=self.ExportMode,
MergeModes=self.MergeModes,
Verbose=self.Verbose)
# Exit edit mode before exporting, so current object states are exported properly.
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
ExportMadeWithMarmaladeGroup(Config)
Sebastian Nell
committed
return {'FINISHED'}
def invoke(self, context, event):
if not self.filepath:
self.filepath = bpy.path.ensure_ext(bpy.data.filepath, ".group")
WindowManager = context.window_manager
WindowManager.fileselect_add(self)
Sebastian Nell
committed
return {'RUNNING_MODAL'}
def menu_func(self, context):
self.layout.operator(MarmaladeExporter.bl_idname, text="Marmalade cross-platform Apps (.group)")
def register():
bpy.utils.register_module(__name__)
bpy.types.INFO_MT_file_export.append(menu_func)
def unregister():
bpy.utils.unregister_module(__name__)
bpy.types.INFO_MT_file_export.remove(menu_func)
if __name__ == "__main__":
register()