Newer
Older
EPQ-3D-renderer / blenderJSON.py
@cory cory on 8 Feb 2023 2 KB Fix #21
import bpy
import json

def separateCollection(collection):
    result = {
    "name":collection.name,
    "subCollections":[separateCollection(subCollection) for subCollection in collection.children],
    "objects":[separateObject(object) for object in collection.objects]
    }
    return result

def separateObject(object):
    materialNameList = [material.name for material in object.material_slots]
    
    result = {
    "name":object.name,
    "position":vec3ToList(object.delta_location),
    "rotation":vec3ToList(object.delta_rotation_euler),
    "scale":vec3ToList(object.delta_scale),
    "points":[vec3ToList(vertex.co) for vertex in object.to_mesh().vertices],
    "faceList":[[vertex for vertex in polygon.vertices] for polygon in object.to_mesh().polygons],
    "uvPointsList":[vec2ToList(item.uv) for item in object.to_mesh().uv_layers[0].data],
    "textureList":[materialNameList[polygon.material_index] for polygon in object.to_mesh().polygons]
    }
    return result

def vec3ToList(vec):
    return[vec[0], vec[1], vec[2]]
def vec2ToList(vec):
    return[vec[0], vec[1]]
jsonCollections = {
"collections":{},
}
jsonTextures = {
"textures":{},
}

MainCollection = 0
collections = bpy.data.collections
for collection in collections:
    if collection.name == "MainCollection":
        MainCollection = collection
        break
jsonCollections["collections"] = [separateCollection(MainCollection)]
jsonTextures["textures"] = [{
"name":material.name,
"type":"solid",
"color":
    f'{(int)(255*material.diffuse_color[0]):02x}'+
    f'{(int)(255*material.diffuse_color[1]):02x}'+
    f'{(int)(255*material.diffuse_color[2]):02x}', #[material.diffuse_color[0], material.diffuse_color[1], material.diffuse_color[2], material.diffuse_color[3]],
"imgPath":"/"
}
 for material in bpy.data.materials]
file = open("/home/cory/IdeaProjects/testing/jsonCollections.json", "w")
file.write(json.dumps(jsonCollections))
file.close()
file = open("/home/cory/IdeaProjects/testing/jsonTextures.json", "w")
file.write(json.dumps(jsonTextures))
file.close()