Skip to content

Instantly share code, notes, and snippets.

@skipme
Created March 25, 2017 15:09
Show Gist options
  • Save skipme/218b244cfe2c3430c695e2c8a9f0cd4c to your computer and use it in GitHub Desktop.
Save skipme/218b244cfe2c3430c695e2c8a9f0cd4c to your computer and use it in GitHub Desktop.
primitive json exporter
import bpy
import string
import mathutils
from mathutils import *
from math import radians, pi
# https://docs.blender.org/api/blender_python_api_current/bpy.types.MeshVertex.html#bpy.types.MeshVertex
# https://docs.blender.org/api/blender_python_api_current/bpy.types.Mesh.html
# https://docs.blender.org/api/blender_python_api_current/mathutils.html
# https://docs.blender.org/api/blender_python_api_current/bpy.types.Object.html#bpy.types.Object
def write_some_data(context, filepath, use_some_setting):
print("running write_some_data...")
f = open(filepath, 'w', encoding='utf-8')
f.write("[ ")
# f.write("Hello World %s" % use_some_setting)
# if self.Config.SelectedOnly:
# ExportList = list(self.context.selected_objects)
# else:
ExportList = list(context.scene.objects)
first = True
for Object in ExportList:
if first:
f.write("{\n")
first = False
else:
f.write(",\n{\n")
f.write(" \"type_name\": \""+Object.type+"\", \n")
f.write(" \"name\": \""+Object.name+"\", \n")
#f.write(" \"matrix\": ["+print_matrix(Object.matrix_local)+"], \n")
#mat = Object.matrix_world * mathutils.Matrix(Object.matrix_local)
mat = mathutils.Matrix(Object.matrix_local)
#mat = mat * Matrix.Rotation(radians(90), 4, 'X')
if Object.type == 'EMPTY':
vec = mathutils.Vector((0.0, 0.0, 0.0))
vec = mat * vec
#print(vec)
#print(" \"matrix\": ["+print_matrix(mat)+"], \n")
f.write(" \"points\": [ ["+("{:9f}, {:9f}, {:9f}".format(vec[0],vec[1],vec[2]))+"] ], \n")
elif Object.type == 'MESH':
f.write(" \"points\": [ "+print_polygons_verts(mat, Object.data)+" ], \n")
f.write("}")
f.write(" ]")
f.close()
print("well done")
return {'FINISHED'}
def print_polygons_verts(mat, mesh_data):
result = ""
first = True
mat90 = Matrix.Rotation(radians(90), 4, 'X')
for poly in mesh_data.polygons:
#print("Polygon index: %d, length: %d" % (poly.index, poly.loop_total))
for polyli in poly.loop_indices:
coco = mesh_data.vertices[mesh_data.loops[polyli].vertex_index].co
vec = mat * coco
#vec = mat90 * vec
print(vec, coco)
if first:
first = False
result += "[{:9f}, {:9f}, {:9f}]".format(vec[0], vec[1], vec[2])
else:
result += ", [{:9f}, {:9f}, {:9f}]".format(vec[0], vec[1], vec[2])
#print(" Vertex: %d" % mesh_data.loops[polyli].vertex_index)
#print(" Vertex: ", mesh_data.vertices[mesh_data.loops[polyli].vertex_index].co)
#print(result)
return result
# range is used here to show how the polygons reference loops,
# for convenience 'poly.loop_indices' can be used instead.
#for loop_index in range(poly.loop_start, poly.loop_start + poly.loop_total):
# print(" Vertex: %d" % me.loops[loop_index].vertex_index)
# print(" UV: %r" % uv_layer[loop_index].uv)
def print_matrix(m):
result = "{:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}, {:9f}".format(
m[0][0], m[0][1],m[0][2],m[0][3],
m[1][0],m[1][1],m[1][2],m[1][3],
m[2][0],m[2][1],m[2][2],m[2][3],
m[3][0],m[3][1],m[3][2],m[3][3])
return result
# ExportHelper is a helper class, defines filename and
# invoke() function which calls the file selector.
from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator
class ExportSomeData(Operator, ExportHelper):
"""This appears in the tooltip of the operator and in the generated docs"""
bl_idname = "export_scene.test_dataexport" # important since its how bpy.ops.import_test.some_data is constructed
bl_label = "I NEED EXPORT"
# ExportHelper mixin class uses this
filename_ext = ".txt"
filter_glob = StringProperty(
default="*.txt",
options={'HIDDEN'},
)
# List of operator properties, the attributes will be assigned
# to the class instance from the operator settings before calling.
use_setting = BoolProperty(
name="Example Boolean",
description="Example Tooltip",
default=True,
)
type = EnumProperty(
name="Example Enum",
description="Choose between two items",
items=(('OPT_A', "First Option", "Description one"),
('OPT_B', "Second Option", "Description two")),
default='OPT_A',
)
def execute(self, context):
return write_some_data(context, self.filepath, self.use_setting)
# Only needed if you want to add into a dynamic menu
def menu_func_export(self, context):
self.layout.operator(ExportSomeData.bl_idname, text="Text Export Operator")
def register():
bpy.utils.register_class(ExportSomeData)
bpy.types.INFO_MT_file_export.append(menu_func_export)
def unregister():
bpy.utils.unregister_class(ExportSomeData)
bpy.types.INFO_MT_file_export.remove(menu_func_export)
if __name__ == "__main__":
register()
print("in main...")
# test call
bpy.ops.export_scene.test_dataexport('INVOKE_DEFAULT')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment