Files
test2/source/blender/io/collada/ControllerExporter.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

629 lines
18 KiB
C++
Raw Normal View History

/* SPDX-FileCopyrightText: 2010-2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup collada
*/
#include "COLLADASWBaseInputElement.h"
#include "COLLADASWInstanceController.h"
#include "COLLADASWPrimitves.h"
#include "COLLADASWSource.h"
#include "DNA_action_types.h"
#include "DNA_meshdata_types.h"
#include "BKE_action.hh"
#include "BKE_armature.hh"
2024-01-29 18:57:16 -05:00
#include "BKE_deform.hh"
#include "BKE_key.hh"
2024-01-15 12:44:04 -05:00
#include "BKE_lib_id.hh"
#include "BKE_mesh.hh"
#include "ED_armature.hh"
#include "BLI_listbase.h"
#include "BLI_math_matrix.h"
#include "ControllerExporter.h"
#include "GeometryExporter.h"
#include "collada_utils.h"
bool ControllerExporter::is_skinned_mesh(Object *ob)
{
return bc_get_assigned_armature(ob) != nullptr;
}
void ControllerExporter::write_bone_URLs(COLLADASW::InstanceController &ins,
Object *ob_arm,
Bone *bone)
{
if (bc_is_root_bone(bone, this->export_settings.get_deform_bones_only())) {
Partial rewrite of the Collada Module for Blender 2.8 Most important changes are in the Animation exporter and Animation Importer. There is still some cleaning up to be done. But the Exporter/Importer basically work within Blender 2.8 Some details: User Interface: The interface has been reorganized to look more like the FBX interface. New options in user interface: * keep_keyframes: When sampling the distance between 2 keyframes is defined by the sampling rate. Furthermore the keyframes defined in the FCurves are not exported. However when this option is enabled then also the defined keyframes will be added to the exported fcurves * keep_smooth_curves: When sampling we do not use FCurves. So we also have no Curve handles for smooth exporting. However when this option is enabled, Blender does its best to recreate the handles for export. This is a very experimental feature and it is know to break when: - the exported animated objects have parent inverse matrices different from the unit matrix - The exported objects have negative scaling There may be many other situations when this feature breaks. This needs to be further tested. It may be removed later or replaced by something less wonky. BlenderContext: is a new class that contains the bridge to Blender. It contains pointers to the current export/import context plus derived values of Depsgraph, Scene, Main Reporting: I reorganized the output on the Blender Console to become more informative and more readable Preservation of Item names: name attributes are now encoded with XML entities. This makes sure that i can export/import names exactly defined in the tool. This affects material names, bone names and object names. Hierarchy export: * Object and Bone Hierarchies are now exported correctly by taking the Blender parent/child hierarchy into account * Export also not selected intermediate objects Problem: When we export an Object Hierarchy, then we must export all elements of the hierarchy to maintain the transforms. This is especially important when exporting animated objects, because the animation curves are exported as relative curves based on the parent-child hierarchy. If an intermediate animated object is missing then the exported animation breaks. Solution: If the "Selected" Optioon is enabled, then take care to also export all objects which are not selected and hidden, but which are parents of selected objects. Node Based Material Importer (wip): Added basic support for Materials with diffuse color and diffuse textures. More properties (opacity, emission) need changes in the used shader. Note: Materials are all constructed by using the principled BSDF shader. Animation Exporter: * Massive optimization of the Animation Bake tool (Animation Sampler). Instead of sampling each fcurve separately, i now sample all exported fcurves simultaneously. So i avoid many (many!) scene updates during animation export. * Add support for Continuous Acceleration (Fcurve handles) This allows us to create smoother FCurves during importing Collada Animation curves. Possibly this should become an option ionstead of a fixed import feature. * Add support for sampling curves (to bake animations) * The animation sampler now can be used for any animation curve. Before the sampler only looked at curves which are supported by Standard Collada 1.4. However the Collada exporter currently ignores all animation curves which are not covered by the 1.4.1 Collada Standards. There is still some room for improvements here (work in progres) Known issues: * Some exports do currently not work reliably, among those are the camera animations, material animations and light animations those animations will be added back next (work in progres) * Exporting animation curves with keyframes (and tangents) sometimes results in odd curves (when parent inverse matrix is involved) This needs to be checked in more depth (probably it can not be solved). * Export of "all animations in scene" is disabled because the Collada Importer can not handle this reliably at the moment (work in progres). * Support for Animation Clip export Added one extra level to the exported animations such that now all scene animations are enclosed: <Animation name="id_name(ob)_Action"> <Animation>...</Animation> ... </Animation> Animation Importer: * Import of animations for objects with multiple materials When importing multiple materials for one object, the imported material animation curves have all been assigned to the first material in the object. Error handling (wip): The Importer was a bit confused as it sometimes ignored fatal parsing errors and continued to import. I did my best to unconfuse it, but i believe that this needs to be tested more. Refactoring: update : move generation of effect id names into own function update : adjust importer/exporter for no longer supported HEMI lights cleanup: Removed no lopnger existing attribute from the exporter presets cleanup: Removed not needed Context attribute from DocumentExporter fix : Avoid duplicate deletion of temporary items cleanup: fixed indentation and white space issues update : Make BCAnimation class more self contained cleanup: Renamed classes, updated comments for better reading cleanup: Moved static class functions to collada_utils cleanup: Moved typedefs to more intuitive locations cleanup: indentation and class method declarations cleanup: Removed no longer needed methods update : Moved Classes into separate files cleanup: Added comments cleanup: take care of name conventions ... : many more small changes, not helpful to list them all
2018-11-23 15:57:45 +01:00
std::string node_id = translate_id(id_name(ob_arm) + "_" + bone->name);
ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, node_id));
}
else {
LISTBASE_FOREACH (Bone *, child, &bone->childbase) {
write_bone_URLs(ins, ob_arm, child);
}
}
}
bool ControllerExporter::add_instance_controller(Object *ob)
{
Object *ob_arm = bc_get_assigned_armature(ob);
bArmature *arm = (bArmature *)ob_arm->data;
const std::string &controller_id = get_controller_id(ob_arm, ob);
COLLADASW::InstanceController ins(mSW);
ins.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, controller_id));
Mesh *mesh = (Mesh *)ob->data;
if (mesh->deform_verts().is_empty()) {
return false;
}
/* write root bone URLs */
LISTBASE_FOREACH (Bone *, bone, &arm->bonebase) {
write_bone_URLs(ins, ob_arm, bone);
}
2013-02-04 00:18:09 +00:00
InstanceWriter::add_material_bindings(
ins.getBindMaterial(), ob, this->export_settings.get_active_uv_only());
ins.add();
return true;
}
Partial rewrite of the Collada Module for Blender 2.8 Most important changes are in the Animation exporter and Animation Importer. There is still some cleaning up to be done. But the Exporter/Importer basically work within Blender 2.8 Some details: User Interface: The interface has been reorganized to look more like the FBX interface. New options in user interface: * keep_keyframes: When sampling the distance between 2 keyframes is defined by the sampling rate. Furthermore the keyframes defined in the FCurves are not exported. However when this option is enabled then also the defined keyframes will be added to the exported fcurves * keep_smooth_curves: When sampling we do not use FCurves. So we also have no Curve handles for smooth exporting. However when this option is enabled, Blender does its best to recreate the handles for export. This is a very experimental feature and it is know to break when: - the exported animated objects have parent inverse matrices different from the unit matrix - The exported objects have negative scaling There may be many other situations when this feature breaks. This needs to be further tested. It may be removed later or replaced by something less wonky. BlenderContext: is a new class that contains the bridge to Blender. It contains pointers to the current export/import context plus derived values of Depsgraph, Scene, Main Reporting: I reorganized the output on the Blender Console to become more informative and more readable Preservation of Item names: name attributes are now encoded with XML entities. This makes sure that i can export/import names exactly defined in the tool. This affects material names, bone names and object names. Hierarchy export: * Object and Bone Hierarchies are now exported correctly by taking the Blender parent/child hierarchy into account * Export also not selected intermediate objects Problem: When we export an Object Hierarchy, then we must export all elements of the hierarchy to maintain the transforms. This is especially important when exporting animated objects, because the animation curves are exported as relative curves based on the parent-child hierarchy. If an intermediate animated object is missing then the exported animation breaks. Solution: If the "Selected" Optioon is enabled, then take care to also export all objects which are not selected and hidden, but which are parents of selected objects. Node Based Material Importer (wip): Added basic support for Materials with diffuse color and diffuse textures. More properties (opacity, emission) need changes in the used shader. Note: Materials are all constructed by using the principled BSDF shader. Animation Exporter: * Massive optimization of the Animation Bake tool (Animation Sampler). Instead of sampling each fcurve separately, i now sample all exported fcurves simultaneously. So i avoid many (many!) scene updates during animation export. * Add support for Continuous Acceleration (Fcurve handles) This allows us to create smoother FCurves during importing Collada Animation curves. Possibly this should become an option ionstead of a fixed import feature. * Add support for sampling curves (to bake animations) * The animation sampler now can be used for any animation curve. Before the sampler only looked at curves which are supported by Standard Collada 1.4. However the Collada exporter currently ignores all animation curves which are not covered by the 1.4.1 Collada Standards. There is still some room for improvements here (work in progres) Known issues: * Some exports do currently not work reliably, among those are the camera animations, material animations and light animations those animations will be added back next (work in progres) * Exporting animation curves with keyframes (and tangents) sometimes results in odd curves (when parent inverse matrix is involved) This needs to be checked in more depth (probably it can not be solved). * Export of "all animations in scene" is disabled because the Collada Importer can not handle this reliably at the moment (work in progres). * Support for Animation Clip export Added one extra level to the exported animations such that now all scene animations are enclosed: <Animation name="id_name(ob)_Action"> <Animation>...</Animation> ... </Animation> Animation Importer: * Import of animations for objects with multiple materials When importing multiple materials for one object, the imported material animation curves have all been assigned to the first material in the object. Error handling (wip): The Importer was a bit confused as it sometimes ignored fatal parsing errors and continued to import. I did my best to unconfuse it, but i believe that this needs to be tested more. Refactoring: update : move generation of effect id names into own function update : adjust importer/exporter for no longer supported HEMI lights cleanup: Removed no lopnger existing attribute from the exporter presets cleanup: Removed not needed Context attribute from DocumentExporter fix : Avoid duplicate deletion of temporary items cleanup: fixed indentation and white space issues update : Make BCAnimation class more self contained cleanup: Renamed classes, updated comments for better reading cleanup: Moved static class functions to collada_utils cleanup: Moved typedefs to more intuitive locations cleanup: indentation and class method declarations cleanup: Removed no longer needed methods update : Moved Classes into separate files cleanup: Added comments cleanup: take care of name conventions ... : many more small changes, not helpful to list them all
2018-11-23 15:57:45 +01:00
void ControllerExporter::export_controllers()
{
Partial rewrite of the Collada Module for Blender 2.8 Most important changes are in the Animation exporter and Animation Importer. There is still some cleaning up to be done. But the Exporter/Importer basically work within Blender 2.8 Some details: User Interface: The interface has been reorganized to look more like the FBX interface. New options in user interface: * keep_keyframes: When sampling the distance between 2 keyframes is defined by the sampling rate. Furthermore the keyframes defined in the FCurves are not exported. However when this option is enabled then also the defined keyframes will be added to the exported fcurves * keep_smooth_curves: When sampling we do not use FCurves. So we also have no Curve handles for smooth exporting. However when this option is enabled, Blender does its best to recreate the handles for export. This is a very experimental feature and it is know to break when: - the exported animated objects have parent inverse matrices different from the unit matrix - The exported objects have negative scaling There may be many other situations when this feature breaks. This needs to be further tested. It may be removed later or replaced by something less wonky. BlenderContext: is a new class that contains the bridge to Blender. It contains pointers to the current export/import context plus derived values of Depsgraph, Scene, Main Reporting: I reorganized the output on the Blender Console to become more informative and more readable Preservation of Item names: name attributes are now encoded with XML entities. This makes sure that i can export/import names exactly defined in the tool. This affects material names, bone names and object names. Hierarchy export: * Object and Bone Hierarchies are now exported correctly by taking the Blender parent/child hierarchy into account * Export also not selected intermediate objects Problem: When we export an Object Hierarchy, then we must export all elements of the hierarchy to maintain the transforms. This is especially important when exporting animated objects, because the animation curves are exported as relative curves based on the parent-child hierarchy. If an intermediate animated object is missing then the exported animation breaks. Solution: If the "Selected" Optioon is enabled, then take care to also export all objects which are not selected and hidden, but which are parents of selected objects. Node Based Material Importer (wip): Added basic support for Materials with diffuse color and diffuse textures. More properties (opacity, emission) need changes in the used shader. Note: Materials are all constructed by using the principled BSDF shader. Animation Exporter: * Massive optimization of the Animation Bake tool (Animation Sampler). Instead of sampling each fcurve separately, i now sample all exported fcurves simultaneously. So i avoid many (many!) scene updates during animation export. * Add support for Continuous Acceleration (Fcurve handles) This allows us to create smoother FCurves during importing Collada Animation curves. Possibly this should become an option ionstead of a fixed import feature. * Add support for sampling curves (to bake animations) * The animation sampler now can be used for any animation curve. Before the sampler only looked at curves which are supported by Standard Collada 1.4. However the Collada exporter currently ignores all animation curves which are not covered by the 1.4.1 Collada Standards. There is still some room for improvements here (work in progres) Known issues: * Some exports do currently not work reliably, among those are the camera animations, material animations and light animations those animations will be added back next (work in progres) * Exporting animation curves with keyframes (and tangents) sometimes results in odd curves (when parent inverse matrix is involved) This needs to be checked in more depth (probably it can not be solved). * Export of "all animations in scene" is disabled because the Collada Importer can not handle this reliably at the moment (work in progres). * Support for Animation Clip export Added one extra level to the exported animations such that now all scene animations are enclosed: <Animation name="id_name(ob)_Action"> <Animation>...</Animation> ... </Animation> Animation Importer: * Import of animations for objects with multiple materials When importing multiple materials for one object, the imported material animation curves have all been assigned to the first material in the object. Error handling (wip): The Importer was a bit confused as it sometimes ignored fatal parsing errors and continued to import. I did my best to unconfuse it, but i believe that this needs to be tested more. Refactoring: update : move generation of effect id names into own function update : adjust importer/exporter for no longer supported HEMI lights cleanup: Removed no lopnger existing attribute from the exporter presets cleanup: Removed not needed Context attribute from DocumentExporter fix : Avoid duplicate deletion of temporary items cleanup: fixed indentation and white space issues update : Make BCAnimation class more self contained cleanup: Renamed classes, updated comments for better reading cleanup: Moved static class functions to collada_utils cleanup: Moved typedefs to more intuitive locations cleanup: indentation and class method declarations cleanup: Removed no longer needed methods update : Moved Classes into separate files cleanup: Added comments cleanup: take care of name conventions ... : many more small changes, not helpful to list them all
2018-11-23 15:57:45 +01:00
Scene *sce = blender_context.get_scene();
openLibrary();
GeometryFunctor gf;
gf.forEachMeshObjectInExportSet<ControllerExporter>(
sce, *this, this->export_settings.get_export_set());
closeLibrary();
}
void ControllerExporter::operator()(Object *ob)
{
Object *ob_arm = bc_get_assigned_armature(ob);
Key *key = BKE_key_from_object(ob);
2013-02-10 17:06:05 +00:00
if (ob_arm) {
export_skin_controller(ob, ob_arm);
2013-02-10 17:06:05 +00:00
}
if (key && this->export_settings.get_include_shapekeys()) {
export_morph_controller(ob, key);
}
}
#if 0
bool ArmatureExporter::already_written(Object *ob_arm)
{
return std::find(written_armatures.begin(), written_armatures.end(), ob_arm) !=
written_armatures.end();
}
void ArmatureExporter::wrote(Object *ob_arm)
{
written_armatures.push_back(ob_arm);
}
void ArmatureExporter::find_objects_using_armature(Object *ob_arm,
std::vector<Object *> &objects,
Scene *sce)
{
objects.clear();
Base *base = (Base *)sce->base.first;
while (base) {
Object *ob = base->object;
if (ob->type == OB_MESH && get_assigned_armature(ob) == ob_arm) {
objects.push_back(ob);
}
base = base->next;
}
}
#endif
std::string ControllerExporter::get_controller_id(Object *ob_arm, Object *ob)
{
return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) +
SKIN_CONTROLLER_ID_SUFFIX;
}
std::string ControllerExporter::get_controller_id(Key *key, Object *ob)
{
return translate_id(id_name(ob)) + MORPH_CONTROLLER_ID_SUFFIX;
}
void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm)
{
/* joint names
* joint inverse bind matrices
* vertex weights */
/* input:
* joint names: ob -> vertex group names
* vertex group weights: mesh->dvert -> groups -> index, weight */
bool use_instantiation = this->export_settings.get_use_object_instantiation();
Mesh *mesh;
if (((Mesh *)ob->data)->deform_verts().is_empty()) {
return;
}
mesh = bc_get_mesh_copy(blender_context,
ob,
this->export_settings.get_export_mesh_type(),
this->export_settings.get_apply_modifiers(),
this->export_settings.get_triangulate());
std::string controller_name = id_name(ob_arm);
std::string controller_id = get_controller_id(ob_arm, ob);
openSkin(controller_id,
controller_name,
COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
add_bind_shape_mat(ob);
const ListBase *defbase = BKE_object_defgroup_list(ob);
std::string joints_source_id = add_joints_source(ob_arm, defbase, controller_id);
std::string inv_bind_mat_source_id = add_inv_bind_mats_source(ob_arm, defbase, controller_id);
std::list<int> vcounts;
std::list<int> joints;
std::list<float> weights;
{
int i, j;
/* def group index -> joint index */
std::vector<int> joint_index_by_def_index;
const bDeformGroup *def;
for (def = (const bDeformGroup *)defbase->first, i = 0, j = 0; def; def = def->next, i++) {
if (is_bone_defgroup(ob_arm, def)) {
joint_index_by_def_index.push_back(j++);
}
else {
joint_index_by_def_index.push_back(-1);
}
}
const MDeformVert *dvert = mesh->deform_verts().data();
int oob_counter = 0;
for (i = 0; i < mesh->verts_num; i++) {
Mesh: Remove redundant custom data pointers For copy-on-write, we want to share attribute arrays between meshes where possible. Mutable pointers like `Mesh.mvert` make that difficult by making ownership vague. They also make code more complex by adding redundancy. The simplest solution is just removing them and retrieving layers from `CustomData` as needed. Similar changes have already been applied to curves and point clouds (e9f82d3dc7ee, 410a6efb747f). Removing use of the pointers generally makes code more obvious and more reusable. Mesh data is now accessed with a C++ API (`Mesh::edges()` or `Mesh::edges_for_write()`), and a C API (`BKE_mesh_edges(mesh)`). The CoW changes this commit makes possible are described in T95845 and T95842, and started in D14139 and D14140. The change also simplifies the ongoing mesh struct-of-array refactors from T95965. **RNA/Python Access Performance** Theoretically, accessing mesh elements with the RNA API may become slower, since the layer needs to be found on every random access. However, overhead is already high enough that this doesn't make a noticible differenc, and performance is actually improved in some cases. Random access can be up to 10% faster, but other situations might be a bit slower. Generally using `foreach_get/set` are the best way to improve performance. See the differential revision for more discussion about Python performance. Cycles has been updated to use raw pointers and the internal Blender mesh types, mostly because there is no sense in having this overhead when it's already compiled with Blender. In my tests this roughly halves the Cycles mesh creation time (0.19s to 0.10s for a 1 million face grid). Differential Revision: https://developer.blender.org/D15488
2022-09-05 11:56:34 -05:00
const MDeformVert *vert = &dvert[i];
std::map<int, float> jw;
/* We're normalizing the weights later */
float sumw = 0.0f;
for (j = 0; j < vert->totweight; j++) {
uint idx = vert->dw[j].def_nr;
if (idx >= joint_index_by_def_index.size()) {
/* XXX: Maybe better find out where and
* why the Out Of Bound indexes get created? */
oob_counter += 1;
}
else {
int joint_index = joint_index_by_def_index[idx];
if (joint_index != -1 && vert->dw[j].weight > 0.0f) {
jw[joint_index] += vert->dw[j].weight;
sumw += vert->dw[j].weight;
2013-02-08 12:31:47 +00:00
}
}
}
if (sumw > 0.0f) {
float invsumw = 1.0f / sumw;
vcounts.push_back(jw.size());
for (auto &index_and_weight : jw) {
joints.push_back(index_and_weight.first);
weights.push_back(invsumw * index_and_weight.second);
}
}
else {
vcounts.push_back(0);
#if 0
vcounts.push_back(1);
joints.push_back(-1);
weights.push_back(1.0f);
#endif
}
}
if (oob_counter > 0) {
fprintf(stderr,
"Ignored %d Vertex weights which use index to non existing VGroup %zu.\n",
oob_counter,
joint_index_by_def_index.size());
}
}
std::string weights_source_id = add_weights_source(mesh, controller_id, weights);
add_joints_element(defbase, joints_source_id, inv_bind_mat_source_id);
add_vertex_weights_element(weights_source_id, joints_source_id, vcounts, joints);
BKE_id_free(nullptr, mesh);
closeSkin();
closeController();
}
void ControllerExporter::export_morph_controller(Object *ob, Key *key)
{
bool use_instantiation = this->export_settings.get_use_object_instantiation();
Mesh *mesh;
mesh = bc_get_mesh_copy(blender_context,
ob,
this->export_settings.get_export_mesh_type(),
this->export_settings.get_apply_modifiers(),
this->export_settings.get_triangulate());
std::string controller_name = id_name(ob) + "-morph";
std::string controller_id = get_controller_id(key, ob);
openMorph(
controller_id,
controller_name,
COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, use_instantiation)));
2013-02-04 00:18:09 +00:00
std::string targets_id = add_morph_targets(key, ob);
std::string morph_weights_id = add_morph_weights(key, ob);
COLLADASW::TargetsElement targets(mSW);
COLLADASW::InputList &input = targets.getInputList();
input.push_back(COLLADASW::Input(
COLLADASW::InputSemantic::MORPH_TARGET, /* constant declared in COLLADASWInputList.h */
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, targets_id)));
input.push_back(
COLLADASW::Input(COLLADASW::InputSemantic::MORPH_WEIGHT,
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, morph_weights_id)));
targets.add();
BKE_id_free(nullptr, mesh);
2013-02-04 00:18:09 +00:00
/* support for animations
* can also try the base element and param alternative */
add_weight_extras(key);
closeMorph();
closeController();
}
std::string ControllerExporter::add_morph_targets(Key *key, Object *ob)
{
std::string source_id = translate_id(id_name(ob)) + TARGETS_SOURCE_ID_SUFFIX;
2013-02-04 00:18:09 +00:00
COLLADASW::IdRefSource source(mSW);
source.setId(source_id);
source.setArrayId(source_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(key->totkey - 1);
source.setAccessorStride(1);
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.emplace_back("IDREF");
source.prepareToAppendValues();
2013-03-18 11:44:56 +00:00
KeyBlock *kb = (KeyBlock *)key->block.first;
/* skip the basis */
kb = kb->next;
for (; kb; kb = kb->next) {
std::string geom_id = get_geometry_id(ob, false) + "_morph_" + translate_id(kb->name);
source.appendValues(geom_id);
}
source.finish();
return source_id;
}
std::string ControllerExporter::add_morph_weights(Key *key, Object *ob)
{
std::string source_id = translate_id(id_name(ob)) + WEIGHTS_SOURCE_ID_SUFFIX;
COLLADASW::FloatSourceF source(mSW);
source.setId(source_id);
source.setArrayId(source_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(key->totkey - 1);
source.setAccessorStride(1);
2013-02-04 00:18:09 +00:00
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.emplace_back("MORPH_WEIGHT");
source.prepareToAppendValues();
2013-03-18 11:44:56 +00:00
KeyBlock *kb = (KeyBlock *)key->block.first;
/* skip the basis */
kb = kb->next;
for (; kb; kb = kb->next) {
float weight = kb->curval;
source.appendValues(weight);
}
source.finish();
return source_id;
}
2013-02-10 17:06:05 +00:00
void ControllerExporter::add_weight_extras(Key *key)
{
/* can also try the base element and param alternative */
COLLADASW::BaseExtraTechnique extra;
2018-10-11 08:49:28 +11:00
KeyBlock *kb = (KeyBlock *)key->block.first;
/* skip the basis */
kb = kb->next;
for (; kb; kb = kb->next) {
/* XXX why is the weight not used here and set to 0.0?
* float weight = kb->curval; */
extra.addExtraTechniqueParameter("KHR", "morph_weights", 0.000, "MORPH_WEIGHT_TO_TARGET");
}
}
void ControllerExporter::add_joints_element(const ListBase *defbase,
const std::string &joints_source_id,
const std::string &inv_bind_mat_source_id)
{
COLLADASW::JointsElement joints(mSW);
COLLADASW::InputList &input = joints.getInputList();
input.push_back(COLLADASW::Input(
COLLADASW::InputSemantic::JOINT, /* constant declared in COLLADASWInputList.h */
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id)));
input.push_back(
COLLADASW::Input(COLLADASW::InputSemantic::BINDMATRIX,
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, inv_bind_mat_source_id)));
joints.add();
}
void ControllerExporter::add_bind_shape_mat(Object *ob)
{
double bind_mat[4][4];
float f_obmat[4][4];
BKE_object_matrix_local_get(ob, f_obmat);
if (export_settings.get_apply_global_orientation()) {
/* do nothing, rotation is going to be applied to the Data */
}
else {
bc_add_global_transform(f_obmat, export_settings.get_global_transform());
}
// UnitConverter::mat4_to_dae_double(bind_mat, ob->object_to_world().ptr());
UnitConverter::mat4_to_dae_double(bind_mat, f_obmat);
if (this->export_settings.get_limit_precision()) {
2019-06-04 10:51:48 +10:00
BCMatrix::sanitize(bind_mat, LIMITTED_PRECISION);
}
addBindShapeTransform(bind_mat);
}
std::string ControllerExporter::add_joints_source(Object *ob_arm,
const ListBase *defbase,
const std::string &controller_id)
{
std::string source_id = controller_id + JOINTS_SOURCE_ID_SUFFIX;
int totjoint = 0;
LISTBASE_FOREACH (bDeformGroup *, def, defbase) {
if (is_bone_defgroup(ob_arm, def)) {
totjoint++;
}
}
COLLADASW::NameSource source(mSW);
source.setId(source_id);
source.setArrayId(source_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(totjoint);
source.setAccessorStride(1);
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.emplace_back("JOINT");
source.prepareToAppendValues();
LISTBASE_FOREACH (bDeformGroup *, def, defbase) {
Bone *bone = get_bone_from_defgroup(ob_arm, def);
if (bone) {
source.appendValues(get_joint_sid(bone));
}
}
source.finish();
return source_id;
}
std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm,
const ListBase *defbase,
const std::string &controller_id)
{
std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX;
int totjoint = 0;
LISTBASE_FOREACH (bDeformGroup *, def, defbase) {
if (is_bone_defgroup(ob_arm, def)) {
totjoint++;
}
}
COLLADASW::FloatSourceF source(mSW);
source.setId(source_id);
source.setArrayId(source_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(totjoint); // BLI_listbase_count(defbase));
source.setAccessorStride(16);
source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4);
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.emplace_back("TRANSFORM");
source.prepareToAppendValues();
bPose *pose = ob_arm->pose;
bArmature *arm = (bArmature *)ob_arm->data;
int flag = arm->flag;
/* put armature in rest position */
if (!(arm->flag & ARM_RESTPOS)) {
Partial rewrite of the Collada Module for Blender 2.8 Most important changes are in the Animation exporter and Animation Importer. There is still some cleaning up to be done. But the Exporter/Importer basically work within Blender 2.8 Some details: User Interface: The interface has been reorganized to look more like the FBX interface. New options in user interface: * keep_keyframes: When sampling the distance between 2 keyframes is defined by the sampling rate. Furthermore the keyframes defined in the FCurves are not exported. However when this option is enabled then also the defined keyframes will be added to the exported fcurves * keep_smooth_curves: When sampling we do not use FCurves. So we also have no Curve handles for smooth exporting. However when this option is enabled, Blender does its best to recreate the handles for export. This is a very experimental feature and it is know to break when: - the exported animated objects have parent inverse matrices different from the unit matrix - The exported objects have negative scaling There may be many other situations when this feature breaks. This needs to be further tested. It may be removed later or replaced by something less wonky. BlenderContext: is a new class that contains the bridge to Blender. It contains pointers to the current export/import context plus derived values of Depsgraph, Scene, Main Reporting: I reorganized the output on the Blender Console to become more informative and more readable Preservation of Item names: name attributes are now encoded with XML entities. This makes sure that i can export/import names exactly defined in the tool. This affects material names, bone names and object names. Hierarchy export: * Object and Bone Hierarchies are now exported correctly by taking the Blender parent/child hierarchy into account * Export also not selected intermediate objects Problem: When we export an Object Hierarchy, then we must export all elements of the hierarchy to maintain the transforms. This is especially important when exporting animated objects, because the animation curves are exported as relative curves based on the parent-child hierarchy. If an intermediate animated object is missing then the exported animation breaks. Solution: If the "Selected" Optioon is enabled, then take care to also export all objects which are not selected and hidden, but which are parents of selected objects. Node Based Material Importer (wip): Added basic support for Materials with diffuse color and diffuse textures. More properties (opacity, emission) need changes in the used shader. Note: Materials are all constructed by using the principled BSDF shader. Animation Exporter: * Massive optimization of the Animation Bake tool (Animation Sampler). Instead of sampling each fcurve separately, i now sample all exported fcurves simultaneously. So i avoid many (many!) scene updates during animation export. * Add support for Continuous Acceleration (Fcurve handles) This allows us to create smoother FCurves during importing Collada Animation curves. Possibly this should become an option ionstead of a fixed import feature. * Add support for sampling curves (to bake animations) * The animation sampler now can be used for any animation curve. Before the sampler only looked at curves which are supported by Standard Collada 1.4. However the Collada exporter currently ignores all animation curves which are not covered by the 1.4.1 Collada Standards. There is still some room for improvements here (work in progres) Known issues: * Some exports do currently not work reliably, among those are the camera animations, material animations and light animations those animations will be added back next (work in progres) * Exporting animation curves with keyframes (and tangents) sometimes results in odd curves (when parent inverse matrix is involved) This needs to be checked in more depth (probably it can not be solved). * Export of "all animations in scene" is disabled because the Collada Importer can not handle this reliably at the moment (work in progres). * Support for Animation Clip export Added one extra level to the exported animations such that now all scene animations are enclosed: <Animation name="id_name(ob)_Action"> <Animation>...</Animation> ... </Animation> Animation Importer: * Import of animations for objects with multiple materials When importing multiple materials for one object, the imported material animation curves have all been assigned to the first material in the object. Error handling (wip): The Importer was a bit confused as it sometimes ignored fatal parsing errors and continued to import. I did my best to unconfuse it, but i believe that this needs to be tested more. Refactoring: update : move generation of effect id names into own function update : adjust importer/exporter for no longer supported HEMI lights cleanup: Removed no lopnger existing attribute from the exporter presets cleanup: Removed not needed Context attribute from DocumentExporter fix : Avoid duplicate deletion of temporary items cleanup: fixed indentation and white space issues update : Make BCAnimation class more self contained cleanup: Renamed classes, updated comments for better reading cleanup: Moved static class functions to collada_utils cleanup: Moved typedefs to more intuitive locations cleanup: indentation and class method declarations cleanup: Removed no longer needed methods update : Moved Classes into separate files cleanup: Added comments cleanup: take care of name conventions ... : many more small changes, not helpful to list them all
2018-11-23 15:57:45 +01:00
Depsgraph *depsgraph = blender_context.get_depsgraph();
Scene *scene = blender_context.get_scene();
arm->flag |= ARM_RESTPOS;
BKE_pose_where_is(depsgraph, scene, ob_arm);
}
LISTBASE_FOREACH (bDeformGroup *, def, defbase) {
if (is_bone_defgroup(ob_arm, def)) {
bPoseChannel *pchan = BKE_pose_channel_find_name(pose, def->name);
float mat[4][4];
float world[4][4];
float inv_bind_mat[4][4];
float bind_mat[4][4]; /* derived from bone->arm_mat */
bool has_bindmat = bc_get_property_matrix(pchan->bone, "bind_mat", bind_mat);
if (!has_bindmat) {
/* Have no bind matrix stored, try old style <= Blender 2.78 */
bc_create_restpose_mat(
this->export_settings, pchan->bone, bind_mat, pchan->bone->arm_mat, true);
/* SL/OPEN_SIM COMPATIBILITY */
if (export_settings.get_open_sim()) {
float loc[3];
float rot[3] = {0, 0, 0};
float scale[3];
bc_decompose(bind_mat, loc, nullptr, nullptr, scale);
/* Only translations, no rotation vs armature */
loc_eulO_size_to_mat4(bind_mat, loc, rot, scale, 6);
}
}
/* make world-space matrix (bind_mat is armature-space) */
mul_m4_m4m4(world, ob_arm->object_to_world().ptr(), bind_mat);
if (!has_bindmat) {
if (export_settings.get_apply_global_orientation()) {
bc_apply_global_transform(world, export_settings.get_global_transform());
}
}
invert_m4_m4(mat, world);
UnitConverter::mat4_to_dae(inv_bind_mat, mat);
if (this->export_settings.get_limit_precision()) {
BCMatrix::sanitize(inv_bind_mat, LIMITTED_PRECISION);
}
source.appendValues(inv_bind_mat);
}
}
/* back from rest position */
if (!(flag & ARM_RESTPOS)) {
Partial rewrite of the Collada Module for Blender 2.8 Most important changes are in the Animation exporter and Animation Importer. There is still some cleaning up to be done. But the Exporter/Importer basically work within Blender 2.8 Some details: User Interface: The interface has been reorganized to look more like the FBX interface. New options in user interface: * keep_keyframes: When sampling the distance between 2 keyframes is defined by the sampling rate. Furthermore the keyframes defined in the FCurves are not exported. However when this option is enabled then also the defined keyframes will be added to the exported fcurves * keep_smooth_curves: When sampling we do not use FCurves. So we also have no Curve handles for smooth exporting. However when this option is enabled, Blender does its best to recreate the handles for export. This is a very experimental feature and it is know to break when: - the exported animated objects have parent inverse matrices different from the unit matrix - The exported objects have negative scaling There may be many other situations when this feature breaks. This needs to be further tested. It may be removed later or replaced by something less wonky. BlenderContext: is a new class that contains the bridge to Blender. It contains pointers to the current export/import context plus derived values of Depsgraph, Scene, Main Reporting: I reorganized the output on the Blender Console to become more informative and more readable Preservation of Item names: name attributes are now encoded with XML entities. This makes sure that i can export/import names exactly defined in the tool. This affects material names, bone names and object names. Hierarchy export: * Object and Bone Hierarchies are now exported correctly by taking the Blender parent/child hierarchy into account * Export also not selected intermediate objects Problem: When we export an Object Hierarchy, then we must export all elements of the hierarchy to maintain the transforms. This is especially important when exporting animated objects, because the animation curves are exported as relative curves based on the parent-child hierarchy. If an intermediate animated object is missing then the exported animation breaks. Solution: If the "Selected" Optioon is enabled, then take care to also export all objects which are not selected and hidden, but which are parents of selected objects. Node Based Material Importer (wip): Added basic support for Materials with diffuse color and diffuse textures. More properties (opacity, emission) need changes in the used shader. Note: Materials are all constructed by using the principled BSDF shader. Animation Exporter: * Massive optimization of the Animation Bake tool (Animation Sampler). Instead of sampling each fcurve separately, i now sample all exported fcurves simultaneously. So i avoid many (many!) scene updates during animation export. * Add support for Continuous Acceleration (Fcurve handles) This allows us to create smoother FCurves during importing Collada Animation curves. Possibly this should become an option ionstead of a fixed import feature. * Add support for sampling curves (to bake animations) * The animation sampler now can be used for any animation curve. Before the sampler only looked at curves which are supported by Standard Collada 1.4. However the Collada exporter currently ignores all animation curves which are not covered by the 1.4.1 Collada Standards. There is still some room for improvements here (work in progres) Known issues: * Some exports do currently not work reliably, among those are the camera animations, material animations and light animations those animations will be added back next (work in progres) * Exporting animation curves with keyframes (and tangents) sometimes results in odd curves (when parent inverse matrix is involved) This needs to be checked in more depth (probably it can not be solved). * Export of "all animations in scene" is disabled because the Collada Importer can not handle this reliably at the moment (work in progres). * Support for Animation Clip export Added one extra level to the exported animations such that now all scene animations are enclosed: <Animation name="id_name(ob)_Action"> <Animation>...</Animation> ... </Animation> Animation Importer: * Import of animations for objects with multiple materials When importing multiple materials for one object, the imported material animation curves have all been assigned to the first material in the object. Error handling (wip): The Importer was a bit confused as it sometimes ignored fatal parsing errors and continued to import. I did my best to unconfuse it, but i believe that this needs to be tested more. Refactoring: update : move generation of effect id names into own function update : adjust importer/exporter for no longer supported HEMI lights cleanup: Removed no lopnger existing attribute from the exporter presets cleanup: Removed not needed Context attribute from DocumentExporter fix : Avoid duplicate deletion of temporary items cleanup: fixed indentation and white space issues update : Make BCAnimation class more self contained cleanup: Renamed classes, updated comments for better reading cleanup: Moved static class functions to collada_utils cleanup: Moved typedefs to more intuitive locations cleanup: indentation and class method declarations cleanup: Removed no longer needed methods update : Moved Classes into separate files cleanup: Added comments cleanup: take care of name conventions ... : many more small changes, not helpful to list them all
2018-11-23 15:57:45 +01:00
Depsgraph *depsgraph = blender_context.get_depsgraph();
Scene *scene = blender_context.get_scene();
arm->flag = flag;
BKE_pose_where_is(depsgraph, scene, ob_arm);
}
source.finish();
return source_id;
}
Bone *ControllerExporter::get_bone_from_defgroup(Object *ob_arm, const bDeformGroup *def)
{
bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, def->name);
return pchan ? pchan->bone : nullptr;
}
bool ControllerExporter::is_bone_defgroup(Object *ob_arm, const bDeformGroup *def)
{
return get_bone_from_defgroup(ob_arm, def) != nullptr;
}
std::string ControllerExporter::add_weights_source(Mesh *mesh,
const std::string &controller_id,
const std::list<float> &weights)
{
std::string source_id = controller_id + WEIGHTS_SOURCE_ID_SUFFIX;
COLLADASW::FloatSourceF source(mSW);
source.setId(source_id);
source.setArrayId(source_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(weights.size());
source.setAccessorStride(1);
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.emplace_back("WEIGHT");
source.prepareToAppendValues();
for (float weight : weights) {
source.appendValues(weight);
}
source.finish();
return source_id;
}
void ControllerExporter::add_vertex_weights_element(const std::string &weights_source_id,
const std::string &joints_source_id,
const std::list<int> &vcounts,
const std::list<int> &joints)
{
COLLADASW::VertexWeightsElement weightselem(mSW);
COLLADASW::InputList &input = weightselem.getInputList();
int offset = 0;
input.push_back(COLLADASW::Input(
COLLADASW::InputSemantic::JOINT, /* constant declared in COLLADASWInputList.h */
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, joints_source_id),
offset++));
input.push_back(
COLLADASW::Input(COLLADASW::InputSemantic::WEIGHT,
COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, weights_source_id),
offset++));
weightselem.setCount(vcounts.size());
/* write number of deformers per vertex */
COLLADASW::PrimitivesBase::VCountList vcountlist;
vcountlist.resize(vcounts.size());
std::copy(vcounts.begin(), vcounts.end(), vcountlist.begin());
weightselem.prepareToAppendVCountValues();
weightselem.appendVertexCount(vcountlist);
weightselem.CloseVCountAndOpenVElement();
/* write deformer index - weight index pairs */
int weight_index = 0;
for (int joint_index : joints) {
weightselem.appendValues(joint_index, weight_index++);
}
weightselem.finish();
}