Сброшены трансформации в asp_sdf_to_asset.py и унифицированы за счет freecad_to_asset.py

This commit is contained in:
brothermechanic 2023-03-06 12:50:35 +00:00 committed by Igor Brylyov
parent 748fcd1351
commit 1ea7e50ecd
8 changed files with 116 additions and 121 deletions

View file

@ -19,7 +19,6 @@ import sys
import xml.sax
import zipfile
import os
sys.path.append('/home/bm/bin/blender-git/blender_bin') # import blender module
import bpy
from bpy_extras.node_shader_utils import PrincipledBSDFWrapper
from import_fcstd.handler import FreeCAD_xml_handler

View file

@ -25,8 +25,8 @@ def asset_setup(transforms=True, sharpness=True, shading=True):
bpy.context.view_layer.objects.active = ob
if transforms:
# apply rot scale
apply_transforms(ob)
# apply scale
apply_transforms(ob, location=False, rotation=False, scale=True)
# remove doubles
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')

View file

@ -8,6 +8,8 @@
**shininess_to_roughness.py** - преобразование значения материала shiny в значения материала roughness
**sdf_mesh_selector.py** - выбор 3д ассетов из объектов сцены Freecad по описанию SDF
## blender_render_settings

View file

@ -2,6 +2,9 @@
# original idea from https://github.com/machin3io/MACHIN3tools
# Copyright (C) 2023 Ilia Kurochkin <brothermechanic@gmail.com>
#
# -*- coding: utf-8 -*-
# Copyright 2023 by brothermechanic. All Rights Reserved.
# Based on https://github.com/machin3io/MACHIN3tools/blob/master/operators/apply.py
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
@ -11,12 +14,12 @@
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
__version__ = "0.1"
__version__ = "0.2"
from mathutils import Matrix, Vector, Quaternion
def apply_transforms(obj):
def apply_transforms(obj, location=False, rotation=False, scale=False):
""" bake local object transforms """
def get_loc_matrix(location):
return Matrix.Translation(location)
@ -25,21 +28,33 @@ def apply_transforms(obj):
return rotation.to_matrix().to_4x4()
def get_sca_matrix(scale):
scale_mx = Matrix()
scale_martix = Matrix()
for i in range(3):
scale_mx[i][i] = scale[i]
return scale_mx
scale_martix[i][i] = scale[i]
return scale_martix
mx = obj.matrix_world
loc, rot, sca = mx.decompose()
if location and rotation and scale:
loc, rot, sca = obj.matrix_world.decompose()
mesh_martix = get_loc_matrix(loc) @ get_rot_matrix(rot) @ get_sca_matrix(sca)
obj.data.transform(mesh_martix)
apply_matrix = get_loc_matrix(Vector.Fill(3, 0)) @ get_rot_matrix(Quaternion()) @ get_sca_matrix(Vector.Fill(3, 1))
obj.matrix_world = apply_matrix
else:
if location:
raise Exception("Location only applies with all transformations (rotate and scale) together!")
if rotation:
loc, rot, sca = obj.matrix_world.decompose()
mesh_martix = get_rot_matrix(rot)
obj.data.transform(mesh_martix)
apply_matrix = get_loc_matrix(loc) @ get_rot_matrix(Quaternion()) @ get_sca_matrix(sca)
obj.matrix_world = apply_matrix
meshmx = get_rot_matrix(rot) @ get_sca_matrix(sca)
obj.data.transform(meshmx)
applymx = get_loc_matrix(loc) @ get_rot_matrix(Quaternion()) @ get_sca_matrix(Vector.Fill(3, 1))
obj.matrix_world = applymx
if scale:
loc, rot, sca = obj.matrix_world.decompose()
mesh_martix = get_sca_matrix(sca)
obj.data.transform(mesh_martix)
apply_matrix = get_loc_matrix(loc) @ get_rot_matrix(rot) @ get_sca_matrix(Vector.Fill(3, 1))
obj.matrix_world = apply_matrix
obj.rotation_mode = 'XYZ'

View file

@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
Subassembly models setup from SDFormat file.
Script selected subassembly models.
Support Blender compiled as a Python Module only!
"""
__version__ = "0.1"
import logging
import sys
import xml.etree.ElementTree as ET
import os
sys.path.append('../')
from import_fcstd.importer import importer
from mathutils import Matrix
from utils.remove_collections import remove_collections
from utils.cleanup_orphan_data import cleanup_orphan_data
from remesh import asset_setup
from export.stl import export_stl
import bpy
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def sdf_mesh_selector(sdf_path):
""" Setup scene by SDFormat file description """
mytree = ET.parse(sdf_path)
myroot = mytree.getroot()
models_transforms = {}
for models in myroot.iter('model'):
for models_childs in models:
if models_childs.find('pose') is not None:
pose = models_childs.find('pose').text
logger.debug(models.attrib['name'], pose)
pose_vectors = [float(x) * 0.001 for x in pose.split()]
models_transforms[models.attrib['name']] = pose_vectors
# TODO More cleanup and optimise
# TODO add models <==> objects compare validation
for obj in bpy.context.scene.objects:
if obj.name in models_transforms:
obj.matrix_world = Matrix()
else:
bpy.data.objects.remove(bpy.data.objects[obj.name], do_unlink=True)
logger.info(obj.name, '- is not in assemly objects. Deleted!')

View file

@ -12,21 +12,3 @@
- обработку mesh объектов для использования в качестве ассетов
- импорт FEM материалов и назначение их для mesh объектов
- экспорт mesh объектов в требуемые форматы
### asp_sdf_to_asset.py
Пакетное производство 3д ассетов из объектов сцены Freecad по описанию Генератора подсборок ASP
Поддерживается работа поверх Blender в качестве модуля!
Сценарий производит:
- импорт solid объектов в Blender сцену
- имена solid объектов в mesh объекты
- тесселяцию solid объектов с заданным уровнем
- выбор состава подсборки из SDF файла описания
- позиция деталей подсборки из SDF файла описания
- ретопологию mesh объектов с заданным уровнем
- обработку mesh объектов для использования в качестве ассетов
- импорт FEM материалов и назначение их для mesh объектов
- экспорт mesh объектов в STL mesh
- экспорт ассета подсборки BLEND

View file

@ -1,77 +0,0 @@
# -*- coding: utf-8 -*-
"""
DESCRIPTION.
Subassembly models setup from SDFormat file.
Script selected, transform, exported subassembly models.
Support Blender compiled as a Python Module only!
"""
__version__ = "0.1"
import logging
import sys
import xml.etree.ElementTree as ET
import os
sys.path.append('../blender/')
from import_fcstd.importer import importer
from utils.remove_collections import remove_collections
from utils.cleanup_orphan_data import cleanup_orphan_data
from remesh import asset_setup
from export.stl import export_stl
sys.path.append('/home/bm/bin/blender-git/blender_bin') # import blender module
import bpy
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def sdf_to_subassembly(assembly_path):
""" Setup scene by SDFormat file description """
assembly_sdf = os.path.join(assembly_path, 'assembly.sdf').replace('\\', '/')
mytree = ET.parse(assembly_sdf)
myroot = mytree.getroot()
models_transforms = {}
for models in myroot.iter('model'):
for models_childs in models:
# if hasattr(models_childs.find('pose'), 'text'): is this better?
if models_childs.find('pose') is not None:
pose = models_childs.find('pose').text
logger.debug(models.attrib['name'], pose)
pose_vectors = [float(x) * 0.001 for x in pose.split()]
models_transforms[models.attrib['name']] = pose_vectors
# TODO add models <==> objects compare validation
for obj in bpy.context.scene.objects:
if obj.name in models_transforms:
obj_transforms = models_transforms[obj.name]
obj.location = obj_transforms[:3]
obj.rotation_mode = 'XYZ'
obj.rotation_euler = obj_transforms[3:] # may be TODO
else:
bpy.data.objects.remove(bpy.data.objects[obj.name], do_unlink=True)
logger.info(obj.name, '- is not in assemly objects. Deleted!')
def asp_asset_pipeline(fcstd_path, export_path, assembly_path, tessellation=20):
""" Setup FreeCAD scene to CG asset """
remove_collections()
cleanup_orphan_data()
importer(fcstd_path, tessellation)
sdf_to_subassembly(assembly_path)
asset_setup()
bpy.ops.wm.save_as_mainfile(filepath=blend_path)
export_stl(export_path)
if __name__ == '__main__':
fcstd_path = '/media/disk/robossembler/project/pipeline/asp/1.FCStd'
blend_path = '/media/disk/robossembler/project/pipeline/asp/1.blend'
assembly_path = '/media/disk/robossembler/project/pipeline/asp/asp-generation'
assembly_meshes_path = os.path.join(assembly_path, 'meshes').replace('\\', '/')
export_path = assembly_meshes_path
asp_asset_pipeline(fcstd_path, export_path, assembly_path, tessellation=20)
logger.info("Assets setup finished without errors")

View file

@ -12,30 +12,55 @@ sys.path.append('../blender/')
from import_fcstd.importer import importer
from utils.remove_collections import remove_collections
from utils.cleanup_orphan_data import cleanup_orphan_data
from utils.sdf_mesh_selector import sdf_mesh_selector
from remesh import asset_setup
from export.dae import export_dae
from export.collision import export_col_stl
sys.path.append('/home/bm/bin/blender-git/blender_bin') # import blender module
import bpy
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def freecad_asset_pipeline(fcstd_path, export_path, tessellation=20):
def freecad_asset_pipeline(fcstd_path,
mesh_export_path,
tessellation=10,
blend_path=None,
sdf_path=None):
""" Setup FreeCAD scene to CG asset """
remove_collections()
cleanup_orphan_data()
importer(fcstd_path, tessellation)
if sdf_path is not None:
sdf_mesh_selector(sdf_path)
asset_setup()
bpy.ops.wm.save_as_mainfile(filepath="/home/bm/test.blend")
export_dae(export_path)
export_col_stl(export_path)
if blend_path is not None:
bpy.ops.wm.save_as_mainfile(filepath=blend_path)
export_dae(mesh_export_path)
export_col_stl(mesh_export_path)
if __name__ == '__main__':
fcstd_path = '/media/disk/robossembler/io-import-fcstd/test/solids.FCStd'
export_path = 'asset_generator/'
freecad_asset_pipeline(fcstd_path, export_path, tessellation=20)
import argparse
parser = argparse.ArgumentParser(
description='Convert and setup FreeCAD solid objects to 3d assets mesh files.')
parser.add_argument(
'--fcstd_path', type=str, help='Path to source FreeCAD scene', required=True)
parser.add_argument(
'--mesh_export_path', type=str, help='Path for export meshes', required=True)
parser.add_argument(
'--tessellation', type=int, help='Tessellation number', default=10, required=False)
parser.add_argument(
'--blend_path', type=str, help='Path for export blend assembly file', required=False)
parser.add_argument(
'--sdf_path', type=str, help='Path to source SDF assembly file', required=False)
args = parser.parse_args()
freecad_asset_pipeline(args.fcstd_path,
args.mesh_export_path,
args.tessellation,
args.blend_path,
args.sdf_path)
logger.info("Assets setup finished without errors")