Compare commits

11 Commits
Author SHA1 Message Date
ActualHorse a359da1762 - SliceableRigidBody3D is now implemented.
- Skinned vertex generation is now its own interruptible slicing step.
- Hurtbox queue is implemented in a more performant manner.
- Print macros now use class names instead of special tags.
2026-10-16 13:48:15 -04:00
ActualHorse 00332be60c Reorganised code files and moved functions to DamageableNode3D parent class. 2026-10-04 21:40:52 -04:00
ActualHorse 1a38b7bf19 Hitboxes now send multiple hitboxes per frame instead of just one. 2026-10-02 00:27:32 -04:00
ActualHorse 4e0b756000 Slice performance improved by setting time limits on loops. 2026-10-02 00:26:44 -04:00
ActualHorse 4fd24f03a1 Slicing function now has multiple deferred stages. 2026-10-01 11:42:21 -04:00
ActualHorse 223eaf2f32 Reworked slicing code in various ways:
- slice_mesh takes an input struct, and returns all data in an output struct.
- Separated loops to ease the possibility of making them deferred functions.
2026-09-29 04:19:39 -04:00
ActualHorse 6e508ccde2 - slice_mesh now supports interpolating custom Float32 data arrays.
- get_skinned_vertex_positions now uses Ref<ArrayMesh> instead of a pointer.
2026-09-27 17:36:49 -04:00
ActualHorse e35adc23b2 Removed fix_polygon_winding's ability to delete edges, since it caused problems
with polygons that have only three vertices and also that isn't really its job
to do anyway.
2026-09-26 14:04:32 -04:00
ActualHorse b5fe9f7c8d HurtboxBase now sends hit updates on a timer instead of on a new frame. 2026-09-26 01:42:38 -04:00
ActualHorse 64421d8ff7 Added a macro to easily call functions on a timer. 2026-09-26 01:34:33 -04:00
ActualHorse b6315f3076 Sliced mesh caps now generate proper normals, thanks to SurfaceTool. 2026-09-26 01:34:01 -04:00
26 changed files with 2060 additions and 1350 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ env.Append(CPPPATH="liborng/")
env.Append(CPPPATH="liborng/data_assets")
env.Append(CPPPATH="liborng/nodes/interfaces")
env.Append(CPPPATH="liborng/nodes")
env.Append(CPPPATH="liborng/nodes/character_nodes")
env.Append(CPPPATH="liborng/nodes/damageables")
env.Append(CPPPATH="liborng/resources")
env.Append(CPPPATH="liborng/singletons")
env.Append(CPPPATH="liborng/singletons/vendor_service")
-8
View File
@@ -1,8 +0,0 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "i_damageable.h"
-15
View File
@@ -1,15 +0,0 @@
/*
* ©2023 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
class IDamageable
{
public:
virtual void take_damage(const struct HurtboxDamage &hit_data) = 0;
};
@@ -1,163 +0,0 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "character_3d.h"
#include "orng_macros.h"
#include "nodes/debug_draw3d.h"
#include "nodes/mesh_editing_library.h"
#include "nodes/hurtbox/hurtbox_base.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/physical_bone3d.hpp>
#include <godot_cpp/classes/physical_bone_simulator3d.hpp>
#include <godot_cpp/classes/random_number_generator.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
#include <godot_cpp/classes/scene_tree_timer.hpp>
#include <godot_cpp/classes/skin.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void Character3D::_ready()
{
if (this->character_skeleton)
{
this->_rebuild_mesh_instances();
}
}
void Character3D::set_meshes(TypedArray<ArrayMesh> m)
{
this->meshes = m;
this->_full_aabb = AABB();
this->_rebuild_mesh_instances();
}
void Character3D::set_character_skeleton(CharacterSkeleton3D *cs)
{
this->character_skeleton = cs;
this->_rebuild_mesh_instances();
}
void Character3D::take_damage(const HurtboxDamage &hit_data)
{
if (this->_hurtbox_queue.empty())
CALL_NEXT_FRAME(callable_mp(this, &Character3D::_next_hurtbox_in_queue));
this->_hurtbox_queue.emplace_back(hit_data);
}
void Character3D::_next_hurtbox_in_queue()
{
HurtboxDamage &hit_data = this->_hurtbox_queue.front();
if (!hit_data.bones.empty())
{
CharacterSkeleton3D *character_skeleton = hit_data.bones.begin()->first;
const std::vector<int32_t> &bone_hits = hit_data.bones.begin()->second;
hit_data.bones.erase(this->_hurtbox_queue.begin()->bones.begin());
Skeleton3D *skeleton = character_skeleton->get_skeleton();
const Plane &local_slice_plane = skeleton->get_global_transform().inverse().xform(Plane(hit_data.global_hit_transform.get_basis().get_column(1), hit_data.global_hit_transform.origin));
std::vector<MeshInstance3D*> sliced_mesh_instances = character_skeleton->get_mesh_instances();
const uint32_t num_mesh_instances = sliced_mesh_instances.size();
TypedArray<ArrayMesh> first_half_meshes_to_add;
TypedArray<ArrayMesh> other_half_meshes_to_add;
for (uint32_t i = 0; i < num_mesh_instances; i++)
{
MeshInstance3D *original_mesh_instance = sliced_mesh_instances[i];
Ref<ArrayMesh> first_half; first_half.instantiate();
Ref<ArrayMesh> other_half; other_half.instantiate();
PackedVector3Array &impact_points = MeshEditingLibrary::slice_mesh(original_mesh_instance, skeleton, this->_full_aabb, local_slice_plane, first_half, other_half, MeshEditingLibrary::CAP_UV_FILL_MESH_BOUNDS, this->inner_materials);
if (first_half->get_surface_count() <= 0 && other_half->get_surface_count() > 0)
{
Ref<ArrayMesh> temp = first_half;
first_half = other_half;
other_half = temp;
}
if (first_half->get_surface_count() > 0)
{
first_half_meshes_to_add.append(first_half);
}
if (other_half->get_surface_count() > 0)
{
other_half_meshes_to_add.append(other_half);
}
}
character_skeleton->set_meshes(first_half_meshes_to_add);
if (other_half_meshes_to_add.size() > 0)
{
RandomNumberGenerator *rng = memnew(RandomNumberGenerator);
const float random_x = rng->randf_range(-0.05f, 0.05f);
const float random_z = rng->randf_range(-0.05f, 0.05f);
CharacterSkeleton3D *new_character_skeleton = cast_to<CharacterSkeleton3D>(this->character_skeleton->duplicate());
this->character_skeleton->add_sibling(new_character_skeleton);
new_character_skeleton->set_position(Vector3(random_x, 0.0f, random_z));
PRINT_LOG(CHARACTER3D_TAG, "Adding new meshes:");
for (uint16_t i = 0; i < other_half_meshes_to_add.size(); i++)
{
const Ref<ArrayMesh> &new_array_mesh = other_half_meshes_to_add[i];
PRINT_LOG(CHARACTER3D_TAG, " Mesh ", i+1, " size: ", new_array_mesh->get_surface_count());
}
new_character_skeleton->set_meshes(other_half_meshes_to_add);
}
}
else
{
this->_hurtbox_queue.erase(this->_hurtbox_queue.begin());
}
if (!this->_hurtbox_queue.empty())
CALL_NEXT_FRAME(callable_mp(this, &Character3D::_next_hurtbox_in_queue));
}
void Character3D::_on_fell_out_of_world()
{
this->emit_signal("fell_out_of_world");
}
void Character3D::_rebuild_mesh_instances()
{
if (!this->character_skeleton || !this->is_node_ready())
return;
std::vector<MeshInstance3D*> mesh_instances = this->character_skeleton->set_meshes(this->meshes);
const uint32_t num_meshes = mesh_instances.size();
this->_full_aabb = AABB();
for (const MeshInstance3D *mesh_instance : mesh_instances)
{
const Vector3 &full_aabb_position = this->_full_aabb.get_position();
const Vector3 &full_aabb_size = this->_full_aabb.get_size();
const AABB &aabb = mesh_instance->get_aabb();
const Vector3 &aabb_position = aabb.get_position();
const Vector3 &aabb_size = aabb.get_size();
this->_full_aabb.set_position(Vector3(
UtilityFunctions::minf(full_aabb_position.x, aabb_position.x),
UtilityFunctions::minf(full_aabb_position.y, aabb_position.y),
UtilityFunctions::minf(full_aabb_position.z, aabb_position.z)
));
this->_full_aabb.set_size(Vector3(
UtilityFunctions::maxf(full_aabb_position.x, aabb_size.x),
UtilityFunctions::maxf(full_aabb_position.y, aabb_size.y),
UtilityFunctions::maxf(full_aabb_position.z, aabb_size.z)
));
}
}
@@ -1,72 +0,0 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "interfaces/i_damageable.h"
#include "nodes/character_nodes/character_skeleton3d.h"
#include <map>
#include <godot_cpp/classes/character_body3d.hpp>
#include <godot_cpp/classes/material.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/packed_scene.hpp>
#include <godot_cpp/variant/dictionary.hpp>
using namespace godot;
#define CHARACTER3D_TAG "Character3D"
class Character3D : public CharacterBody3D, public IDamageable
{
GDCLASS(Character3D, CharacterBody3D);
public:
virtual void _ready() override;
virtual void take_damage(const HurtboxDamage &hit_data) override;
TypedArray<ArrayMesh> get_meshes() const { return this->meshes; }
CharacterSkeleton3D *get_character_skeleton() const { return this->character_skeleton; }
TypedArray<Material> get_inner_materials() const { return this->inner_materials; }
virtual void _on_fell_out_of_world();
protected:
void set_meshes(TypedArray<ArrayMesh> m);
void set_character_skeleton(CharacterSkeleton3D *cs);
void set_inner_materials(TypedArray<Material> materials) { this->inner_materials = materials; }
private:
void _rebuild_mesh_instances();
void _next_hurtbox_in_queue();
TypedArray<ArrayMesh> meshes;
CharacterSkeleton3D *character_skeleton = nullptr;
AABB _full_aabb;
TypedArray<Material> inner_materials;
std::vector<HurtboxDamage> _hurtbox_queue;
// Godot boilerplate below
protected:
static void _bind_methods()
{
BIND_METHOD(Character3D, _on_fell_out_of_world);
ADD_SIGNAL(MethodInfo("fell_out_of_world"));
ADD_GETTER_SETTER_HINTED(Character3D, meshes, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, "ArrayMesh");
ADD_GETTER_SETTER_HINTED(Character3D, character_skeleton, Variant::OBJECT, PROPERTY_HINT_NODE_TYPE, "CharacterSkeleton3D");
ADD_GETTER_SETTER_HINTED(Character3D, inner_materials, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, "Material");
}
};
@@ -0,0 +1,146 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "character_3d.h"
#include "orng_macros.h"
#include "nodes/damageables/sliceable_rigid_body3d.h"
#include "nodes/hurtbox/hurtbox_base.h"
#include "singletons/mesh_editing_library.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/physical_bone3d.hpp>
#include <godot_cpp/classes/physical_bone_simulator3d.hpp>
#include <godot_cpp/classes/random_number_generator.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
#include <godot_cpp/classes/scene_tree_timer.hpp>
#include <godot_cpp/classes/skin.hpp>
#include <godot_cpp/variant/utility_functions.hpp>
using namespace godot;
void Character3D::set_character_skeleton(CharacterSkeleton3D *cs)
{
if (cs)
{
if (this->character_skeleton)
{
this->_skeleton_set.erase(this->character_skeleton);
this->character_skeleton->queue_free();
}
this->character_skeleton = cs;
this->_skeleton_set.emplace(this->character_skeleton);
this->_rebuild_mesh_instance();
}
}
void Character3D::take_damage(const HurtboxDamage &hit_data)
{
if (this->_hurtbox_queue.empty())
callable_mp(this, &Character3D::_next_hurtbox_in_queue).call_deferred();
this->_hurtbox_queue.emplace_back(hit_data);
}
void Character3D::_next_hurtbox_in_queue()
{
HurtboxDamage &hit_data = this->_hurtbox_queue.front();
if (!hit_data.bones.empty())
{
CharacterSkeleton3D *character_skeleton = hit_data.bones.begin()->first;
const std::vector<int32_t> &bone_hits = hit_data.bones.begin()->second;
hit_data.bones.erase(this->_hurtbox_queue.begin()->bones.begin());
Skeleton3D *skeleton = character_skeleton->get_skeleton();
const Plane &local_slice_plane = skeleton->get_global_transform().inverse().xform(Plane(hit_data.global_hit_transform.get_basis().get_column(1), hit_data.global_hit_transform.origin));
Ref<MeshEditSliceInput> input; input.instantiate();
input->mesh_instance = character_skeleton->get_mesh_instance();
input->skeleton = skeleton;
input->full_aabb = this->aabb;
input->local_plane = local_slice_plane;
input->cap_option = MeshEditingLibrary::CAP_UV_FILL_MESH_BOUNDS;
input->cap_materials = this->inner_materials;
this->_slice_meshes(input);
}
else
{
this->_hurtbox_queue.erase(this->_hurtbox_queue.begin());
}
if (!this->_hurtbox_queue.empty())
CALL_NEXT_FRAME(callable_mp(this, &Character3D::_next_hurtbox_in_queue));
}
void Character3D::_slice_complete(Ref<MeshEditSliceOutput> data)
{
if (data->original_skeleton)
{
for (CharacterSkeleton3D *skeleton : this->_skeleton_set)
{
if (skeleton->get_skeleton() == data->original_skeleton)
{
MeshInstance3D *new_mesh_instance = memnew(MeshInstance3D);
new_mesh_instance->set_mesh(data->main_half);
skeleton->set_mesh(new_mesh_instance);
break;
}
}
if (data->secondary_half.is_valid())
{
if (this->_skeleton_set.size() < 4)
{
RandomNumberGenerator *rng = memnew(RandomNumberGenerator);
const float random_x = rng->randf_range(-0.05f, 0.05f);
const float random_z = rng->randf_range(-0.05f, 0.05f);
CharacterSkeleton3D *new_character_skeleton = cast_to<CharacterSkeleton3D>(this->character_skeleton->duplicate());
this->character_skeleton->add_sibling(new_character_skeleton);
new_character_skeleton->set_position(Vector3(random_x, 0.0f, random_z));
MeshInstance3D *new_mesh_instance = memnew(MeshInstance3D);
new_mesh_instance->set_mesh(data->secondary_half);
new_character_skeleton->set_mesh(new_mesh_instance);
this->_skeleton_set.emplace(new_character_skeleton);
PRINT_LOG(Character3D, "Number of skeletons is now ", this->_skeleton_set.size());
}
else
{
SliceableRigidBody3D *new_rigid_body = memnew(SliceableRigidBody3D);
this->add_sibling(new_rigid_body);
new_rigid_body->set_mesh(data->secondary_half);
new_rigid_body->set_global_transform(this->get_global_transform());
new_rigid_body->set_collision_layer(this->loose_object_collision_layer);
new_rigid_body->set_collision_mask(this->loose_object_collision_mask);
new_rigid_body->set_inner_materials(this->inner_materials);
PRINT_LOG(Character3D, "Not creating skeletons any more. >:c");
}
}
}
}
void Character3D::_on_fell_out_of_world()
{
this->emit_signal("fell_out_of_world");
}
MeshInstance3D *Character3D::_rebuild_mesh_instance()
{
if (MeshInstance3D *returned_instance = DamageableNode3D::_rebuild_mesh_instance())
{
this->character_skeleton->set_mesh(returned_instance);
return returned_instance;
}
return nullptr;
}
@@ -0,0 +1,81 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "nodes/damageables/damageable_node3d.h"
#include "nodes/damageables/character_skeleton3d.h"
#include <map>
#include <unordered_set>
#include <godot_cpp/classes/character_body3d.hpp>
#include <godot_cpp/classes/material.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/packed_scene.hpp>
#include <godot_cpp/variant/dictionary.hpp>
using namespace godot;
#define CHARACTER3D_TAG "Character3D"
class Character3D : public DamageableNode3D
{
GDCLASS(Character3D, DamageableNode3D);
public:
void set_loose_object_collision_layer(const uint32_t layer) { this->loose_object_collision_layer = layer; }
uint32_t get_loose_object_collision_layer() { return this->loose_object_collision_layer; }
void set_loose_object_collision_mask(const uint32_t mask) { this->loose_object_collision_mask = mask; }
uint32_t get_loose_object_collision_mask() { return this->loose_object_collision_mask; }
virtual void take_damage(const HurtboxDamage &hit_data) override;
CharacterSkeleton3D *get_character_skeleton() const { return this->character_skeleton; }
virtual void _on_fell_out_of_world();
protected:
void set_character_skeleton(CharacterSkeleton3D *cs);
virtual MeshInstance3D *_rebuild_mesh_instance() override;
private:
void _next_hurtbox_in_queue();
virtual void _slice_complete(Ref<MeshEditSliceOutput> data) override;
uint32_t loose_object_collision_layer = 0b1;
uint32_t loose_object_collision_mask = 0b1;
CharacterSkeleton3D *character_skeleton = nullptr;
std::unordered_set<CharacterSkeleton3D*> _skeleton_set;
std::vector<HurtboxDamage> _hurtbox_queue;
// Godot boilerplate below
protected:
static void _bind_methods()
{
ClassDB::bind_method(D_METHOD("set_loose_object_collision_layer", "layer"), &Character3D::set_loose_object_collision_layer);
ClassDB::bind_method(D_METHOD("get_loose_object_collision_layer"), &Character3D::get_loose_object_collision_layer);
ClassDB::add_property(Character3D::get_class_static(), PropertyInfo(Variant::INT, "loose_object_collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_loose_object_collision_layer", "get_loose_object_collision_layer");
ClassDB::bind_method(D_METHOD("set_loose_object_collision_mask", "mask"), &Character3D::set_loose_object_collision_mask);
ClassDB::bind_method(D_METHOD("get_loose_object_collision_mask"), &Character3D::get_loose_object_collision_mask);
ClassDB::add_property(Character3D::get_class_static(), PropertyInfo(Variant::INT, "loose_object_collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_loose_object_collision_mask", "get_loose_object_collision_mask");
BIND_METHOD(Character3D, _on_fell_out_of_world);
ADD_SIGNAL(MethodInfo("fell_out_of_world"));
ADD_GETTER_SETTER_HINTED(Character3D, character_skeleton, Variant::OBJECT, PROPERTY_HINT_NODE_TYPE, "CharacterSkeleton3D");
}
};
@@ -16,33 +16,23 @@
using namespace godot;
std::vector<MeshInstance3D*> CharacterSkeleton3D::set_meshes(TypedArray<ArrayMesh> meshes)
void CharacterSkeleton3D::set_mesh(MeshInstance3D *mesh)
{
if (this->skeleton)
{
this->_old_mesh_instances = this->_mesh_instances;
this->_mesh_instances.clear();
this->_old_mesh_instance = this->_mesh_instance;
uint16_t num_new_meshes = meshes.size();
for (uint16_t i = 0; i < num_new_meshes; i++)
this->_mesh_instance = mesh;
_mesh_instance->set_skeleton_path(this->skeleton->get_path());
this->skeleton->add_child(this->_mesh_instance, false, Node::INTERNAL_MODE_BACK);
CALL_NEXT_FRAME(callable_mp(this, &CharacterSkeleton3D::_delete_old_mesh));
}
}
void CharacterSkeleton3D::_delete_old_mesh()
{
MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
mesh_instance->set_mesh(meshes[i]);
mesh_instance->set_skeleton_path(this->skeleton->get_path());
this->skeleton->add_child(mesh_instance, false, Node::INTERNAL_MODE_BACK);
this->_mesh_instances.emplace_back(mesh_instance);
}
CALL_NEXT_FRAME(callable_mp(this, &CharacterSkeleton3D::_delete_old_meshes));
}
return this->_mesh_instances;
}
void CharacterSkeleton3D::_delete_old_meshes()
{
for (MeshInstance3D *old_mesh : this->_old_mesh_instances)
old_mesh->queue_free();
this->_old_mesh_instances.clear();
if (this->_old_mesh_instance)
this->_old_mesh_instance->queue_free();
}
@@ -26,15 +26,14 @@ class CharacterSkeleton3D : public Node3D
GDCLASS(CharacterSkeleton3D, Node3D);
public:
std::vector<MeshInstance3D*> set_meshes(TypedArray<ArrayMesh> meshes);
void set_mesh(MeshInstance3D *mesh);
Skeleton3D *get_skeleton() const { return this->skeleton; }
PhysicalBoneSimulator3D *get_physical_bone_simulator() const { return this->physical_bone_simulator; }
AnimationPlayer *get_animation_player() const { return this->animation_player; }
AnimationTree *get_animation_tree() const { return this->animation_tree; }
void replace_mesh_instance(const uint16_t index, Ref<ArrayMesh> new_mesh) { this->_mesh_instances[index]->set_mesh(new_mesh); }
std::vector<MeshInstance3D*> get_mesh_instances() const { return this->_mesh_instances; }
MeshInstance3D *get_mesh_instance() const { return this->_mesh_instance; }
protected:
void set_skeleton(Skeleton3D *s) { this->skeleton = s; }
@@ -44,7 +43,7 @@ protected:
private:
// void _refresh_skins_and_meshes();
void _delete_old_meshes();
void _delete_old_mesh();
void _activate_ragdoll();
@@ -53,8 +52,8 @@ private:
AnimationPlayer *animation_player = nullptr;
AnimationTree *animation_tree = nullptr;
std::vector<MeshInstance3D*> _mesh_instances;
std::vector<MeshInstance3D*> _old_mesh_instances;
MeshInstance3D *_mesh_instance = nullptr;
MeshInstance3D *_old_mesh_instance = nullptr;
// Godot boilerplate below
protected:
@@ -0,0 +1,125 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "damageable_node3d.h"
#include "orng_macros.h"
#include "godot_cpp/classes/scene_tree.hpp"
#include "godot_cpp/classes/scene_tree_timer.hpp"
void DamageableNode3D::_ready()
{
this->_rebuild_mesh_instance();
}
void DamageableNode3D::set_mesh(Ref<ArrayMesh> m)
{
this->mesh = m;
this->_rebuild_mesh_instance();
}
void DamageableNode3D::_slice_meshes(Ref<MeshEditSliceInput> data)
{
this->_is_slicing = true;
if (this->_validate_input(data))
{
this->_input_queue.emplace_back(data);
if (this->_slice_state_queue.empty())
this->_new_slice_loop();
}
}
void DamageableNode3D::_new_slice_loop()
{
Ref<MeshEditSliceInput> next_in_queue = this->_input_queue.front();
Ref<MeshEditSliceState> new_state = MeshEditingLibrary::slice_mesh(next_in_queue);
this->_slice_state_queue.emplace_back(new_state);
this->_slice_loop();
}
void DamageableNode3D::_slice_loop()
{
Ref<MeshEditSliceState> current_state = this->_slice_state_queue.front();
switch(current_state->current_stage)
{
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_INIT:
if (MeshEditingLibrary::slice_mesh_init(current_state) > MESH_EDITING_SLICE_LOOP_LIMIT)
break;
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_GET_SKINNED_VERTS:
if (MeshEditingLibrary::slice_mesh_get_skinned_verts(current_state) > MESH_EDITING_SLICE_LOOP_LIMIT)
break;
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_PLANE_SPLIT:
if (MeshEditingLibrary::slice_mesh_plane_split(current_state) > MESH_EDITING_SLICE_LOOP_LIMIT)
break;
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_EDGE_SPLIT:
if (MeshEditingLibrary::slice_mesh_edge_split(current_state) > MESH_EDITING_SLICE_LOOP_LIMIT)
break;
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_APPLY_CAP:
if (MeshEditingLibrary::slice_mesh_apply_cap(current_state) > MESH_EDITING_SLICE_LOOP_LIMIT)
break;
case MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_COMPLETE:
if (this->_slice_loop_end(current_state))
return this->_new_slice_loop();
break;
}
if (!this->_input_queue.empty())
CALL_NEXT_FRAME(callable_mp(this, &DamageableNode3D::_slice_loop));
else
this->_is_slicing = false;
}
bool DamageableNode3D::_slice_loop_end(Ref<MeshEditSliceState> current_state)
{
this->_slice_complete(current_state->output);
this->_input_queue.erase(this->_input_queue.begin());
this->_slice_state_queue.erase(this->_slice_state_queue.begin());
if (!this->_input_queue.empty())
return true;
return false;
}
bool DamageableNode3D::_validate_input(Ref<MeshEditSliceInput> input)
{
if (this->_input_queue.size() >= MAX_SLICE_QUEUE_SIZE)
{
return false;
}
for (Ref<MeshEditSliceInput> &queued_input : this->_input_queue)
{
if (queued_input->skeleton == input->skeleton)
{
return false;
}
}
return true;
}
MeshInstance3D *DamageableNode3D::_rebuild_mesh_instance()
{
if (!this->is_node_ready())
return nullptr;
if (this->_active_mesh_instance)
{
this->_active_mesh_instance->queue_free();
}
this->_active_mesh_instance = memnew(MeshInstance3D);
this->_active_mesh_instance->set_mesh(this->mesh);
if (this->aabb == AABB())
this->aabb = this->_active_mesh_instance->get_aabb();
return this->_active_mesh_instance;
}
@@ -0,0 +1,71 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "singletons/mesh_editing_library.h"
#include "godot_cpp/classes/node.hpp"
using namespace godot;
#define MAX_SLICE_QUEUE_SIZE 4
#define DAMAGEABLE_NODE3D_TAG "DamageableNode3D"
class DamageableNode3D : public Node3D
{
GDCLASS(DamageableNode3D, Node3D);
public:
virtual void _ready() override;
void set_mesh(Ref<ArrayMesh> m);
Ref<ArrayMesh> get_mesh() const { return this->mesh; }
void set_aabb(const AABB &aabb) { this->aabb = aabb; }
AABB get_aabb() const { return this->aabb; }
void set_inner_materials(TypedArray<Material> materials) { this->inner_materials = materials; }
TypedArray<Material> get_inner_materials() const { return this->inner_materials; }
virtual void take_damage(const struct HurtboxDamage &hit_data) = 0;
protected:
MeshInstance3D *_get_active_mesh_instance() { return this->_active_mesh_instance; }
virtual MeshInstance3D *_rebuild_mesh_instance();
void _slice_meshes(Ref<MeshEditSliceInput> data);
virtual void _slice_complete(Ref<MeshEditSliceOutput> data) = 0;
Ref<ArrayMesh> mesh;
AABB aabb;
TypedArray<Material> inner_materials;
private:
void _new_slice_loop();
void _slice_loop();
bool _slice_loop_end(Ref<MeshEditSliceState> current_state);
bool _validate_input(Ref<MeshEditSliceInput> input);
MeshInstance3D *_active_mesh_instance = nullptr;
bool _is_slicing = false;
std::vector<Ref<MeshEditSliceState>> _slice_state_queue;
std::vector<Ref<MeshEditSliceInput>> _input_queue;
// Godot boilerplate below
protected:
static void _bind_methods()
{
ADD_GETTER_SETTER_HINTED(DamageableNode3D, mesh, Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "ArrayMesh");
ADD_GETTER_SETTER(DamageableNode3D, aabb, Variant::AABB);
ADD_GETTER_SETTER_HINTED(DamageableNode3D, inner_materials, Variant::ARRAY, PROPERTY_HINT_ARRAY_TYPE, "Material");
}
};
@@ -0,0 +1,108 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "sliceable_rigid_body3d.h"
#include "orng_macros.h"
#include "nodes/hurtbox/hurtbox_base.h"
#include <godot_cpp/classes/convex_polygon_shape3d.hpp>
#include <godot_cpp/classes/scene_tree.hpp>
#include <godot_cpp/classes/scene_tree_timer.hpp>
using namespace godot;
void SliceableRigidBody3D::_enter_tree()
{
this->rigid_body = memnew(RigidBody3D);
this->collision_shape = memnew(CollisionShape3D);
this->rigid_body->add_child(this->collision_shape);
this->add_child(this->rigid_body);
}
void SliceableRigidBody3D::_ready()
{
this->rigid_body->set_collision_layer(this->collision_layer);
this->rigid_body->set_collision_mask(this->collision_mask);
DamageableNode3D::_ready();
}
void SliceableRigidBody3D::set_collision_layer(const uint32_t layer)
{
this->collision_layer = layer;
if (this->rigid_body)
this->rigid_body->set_collision_layer(this->collision_layer);
}
void SliceableRigidBody3D::set_collision_mask(const uint32_t mask)
{
this->collision_mask = mask;
if (this->rigid_body)
this->rigid_body->set_collision_mask(this->collision_mask);
}
void SliceableRigidBody3D::take_damage(const HurtboxDamage &hit_data)
{
const Plane &local_slice_plane = this->rigid_body->get_global_transform().inverse().xform(Plane(hit_data.global_hit_transform.get_basis().get_column(1), hit_data.global_hit_transform.origin));
Ref<MeshEditSliceInput> input; input.instantiate();
input->mesh_instance = this->_get_active_mesh_instance();
input->skeleton = nullptr;
input->full_aabb = this->aabb;
input->local_plane = local_slice_plane;
input->cap_option = MeshEditingLibrary::CAP_UV_FILL_MESH_BOUNDS;
input->cap_materials = this->inner_materials;
this->_slice_meshes(input);
}
void SliceableRigidBody3D::_slice_complete(Ref<MeshEditSliceOutput> data)
{
// This is here so that the root node and its child RigidBody3D can share the same position,
// making the transform of the new slices much easier to calculate.
if (this->rigid_body)
{
const Transform3D rigid_body_transform = this->rigid_body->get_global_transform();
this->set_global_transform(rigid_body_transform);
this->rigid_body->set_transform(Transform3D());
}
this->set_mesh(data->main_half);
this->apply_central_impulse(data->original_local_plane.get_normal() * 1.0f);
if (data->secondary_half.is_valid())
{
SliceableRigidBody3D *new_rigid_body = memnew(SliceableRigidBody3D);
this->add_sibling(new_rigid_body);
new_rigid_body->set_mesh(data->secondary_half);
new_rigid_body->set_global_transform(this->get_global_transform());
new_rigid_body->set_aabb(data->original_full_aabb);
new_rigid_body->set_collision_layer(this->collision_layer);
new_rigid_body->set_collision_mask(this->collision_mask);
new_rigid_body->set_inner_materials(this->inner_materials);
new_rigid_body->apply_central_impulse(data->original_local_plane.get_normal() * -1.0f);
}
}
MeshInstance3D *SliceableRigidBody3D::_rebuild_mesh_instance()
{
if (MeshInstance3D *returned_instance = DamageableNode3D::_rebuild_mesh_instance())
{
this->rigid_body->add_child(returned_instance);
Ref<ArrayMesh> returned_mesh = returned_instance->get_mesh();
if (returned_mesh.is_valid())
{
Ref<ConvexPolygonShape3D> shape = returned_mesh->create_convex_shape(false, false);
this->collision_shape->set_shape(shape);
}
return returned_instance;
}
return nullptr;
}
@@ -0,0 +1,69 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include "orng_macros.h"
#include "nodes/damageables/damageable_node3d.h"
#include <map>
#include <unordered_set>
#include <godot_cpp/classes/collision_shape3d.hpp>
#include <godot_cpp/classes/material.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/rigid_body3d.hpp>
using namespace godot;
#define SLICEABLE_RIGID_BODY3D_TAG "SliceableRigidBody3D"
class SliceableRigidBody3D : public DamageableNode3D
{
GDCLASS(SliceableRigidBody3D, DamageableNode3D);
public:
virtual void _enter_tree() override;
virtual void _ready() override;
void set_collision_layer(const uint32_t layer);
uint32_t get_collision_layer() const { return this->collision_layer; }
void set_collision_mask(const uint32_t mask);
uint32_t get_collision_mask() const { return this->collision_mask; }
virtual void take_damage(const HurtboxDamage &hit_data) override;
void apply_impulse(const Vector3 &impulse, const Vector3 &position = Vector3(0.0f, 0.0f, 0.0f)) { if (this->rigid_body) this->rigid_body->apply_impulse(impulse, position); }
void apply_central_impulse(const Vector3 &impulse) { if (this->rigid_body) this->rigid_body->apply_central_impulse(impulse); }
protected:
virtual MeshInstance3D *_rebuild_mesh_instance() override;
private:
virtual void _slice_complete(Ref<MeshEditSliceOutput> data) override;
uint32_t collision_layer;
uint32_t collision_mask;
RigidBody3D *rigid_body = nullptr;
CollisionShape3D *collision_shape = nullptr;
// Godot boilerplate below
protected:
static void _bind_methods()
{
ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &SliceableRigidBody3D::set_collision_layer);
ClassDB::bind_method(D_METHOD("get_collision_layer"), &SliceableRigidBody3D::get_collision_layer);
ClassDB::add_property(SliceableRigidBody3D::get_class_static(), PropertyInfo(Variant::INT, "collision_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &SliceableRigidBody3D::set_collision_mask);
ClassDB::bind_method(D_METHOD("get_collision_mask"), &SliceableRigidBody3D::get_collision_mask);
ClassDB::add_property(SliceableRigidBody3D::get_class_static(), PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
}
};
+30 -24
View File
@@ -8,7 +8,8 @@
#include "hurtbox_base.h"
#include "orng_macros.h"
#include "nodes/character_nodes/character_3d.h"
#include "nodes/damageables/character_3d.h"
#include "nodes/damageables/sliceable_rigid_body3d.h"
#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/physical_bone3d.hpp>
@@ -52,7 +53,7 @@ void HurtboxBase::_ready()
this->set_process(false);
this->remaining_life = this->lifetime;
CALL_NEXT_FRAME(callable_mp(this, &HurtboxBase::_send_next_in_queue));
this->_send_next_in_queue();
}
void HurtboxBase::_physics_process(double delta)
@@ -60,7 +61,7 @@ void HurtboxBase::_physics_process(double delta)
const TypedArray<Node3D> &bodies = this->get_overlapping_bodies();
const uint32_t num_bodies = bodies.size();
std::unordered_set<IDamageable*> new_hit_bodies;
std::unordered_set<DamageableNode3D*> new_hit_bodies;
std::vector<CharacterSkeleton3D*> new_hit_skeletons;
for (uint32_t i = 0; i < num_bodies; i++)
@@ -77,59 +78,64 @@ void HurtboxBase::_physics_process(double delta)
if (std::find(new_hit_skeletons.begin(), new_hit_skeletons.end(), character_skeleton) == new_hit_skeletons.end())
{
HurtboxDamage character_damage;
character_damage.hit_points = this->hit_points;
character_damage.global_hit_transform = this->get_global_transform();
HurtboxDamage damage;
damage.hit_points = this->hit_points;
damage.global_hit_transform = this->get_global_transform();
for (uint32_t bone_index = 0; bone_index < num_bodies; bone_index++)
{
if (PhysicalBone3D *bone = cast_to<PhysicalBone3D>(bodies[bone_index]))
{
if (String(bone->get_path()).begins_with(character_skeleton->get_path()))
character_damage.bones[character_skeleton].emplace_back(bone->get_bone_id());
damage.bones[character_skeleton].emplace_back(bone->get_bone_id());
}
}
this->hit_data_queue[body].emplace_back(character_damage);
this->hit_data_queue[body].emplace_back(damage);
new_hit_skeletons.emplace_back(character_skeleton);
}
}
}
}
}
else if (RigidBody3D *rigid_body = cast_to<RigidBody3D>(bodies[i]))
{
if (SliceableRigidBody3D *sliceable_rigid_body = cast_to<SliceableRigidBody3D>(rigid_body->get_parent()))
{
if (std::find(this->hit_bodies.begin(), this->hit_bodies.end(), sliceable_rigid_body) == this->hit_bodies.end())
{
HurtboxDamage damage;
damage.hit_points = this->hit_points;
damage.global_hit_transform = this->get_global_transform();
this->hit_data_queue[sliceable_rigid_body].emplace_back(damage);
new_hit_bodies.emplace(sliceable_rigid_body);
}
}
}
}
for (IDamageable *damageable : new_hit_bodies)
for (DamageableNode3D *damageable : new_hit_bodies)
this->hit_bodies.emplace_back(damageable);
this->remaining_life -= delta;
if (this->remaining_life <= 0.0f)
this->collision_shape->set_disabled(true);
else
this->remaining_life -= delta;
}
void HurtboxBase::_send_next_in_queue()
{
if (!this->hit_data_queue.empty())
for (uint8_t i = 0; i < MAX_HITS_PER_QUEUE_LOOP && !this->hit_data_queue.empty(); i++)
{
IDamageable *closest_damageable = nullptr;
DamageableNode3D *closest_damageable = nullptr;
float shortest_distance_from_hurtbox = FLT_MAX;
bool found_character_3d = false;
for (const auto &[damageable, hit_data_list] : this->hit_data_queue)
{
if (const Character3D *node = (Character3D*)(damageable))
{
const float distance_to_hurtbox = node->get_global_position().distance_squared_to(this->get_global_position());
const float distance_to_hurtbox = damageable->get_global_position().distance_squared_to(this->get_global_position());
if (distance_to_hurtbox < shortest_distance_from_hurtbox)
{
closest_damageable = damageable;
shortest_distance_from_hurtbox = distance_to_hurtbox;
found_character_3d = true;
}
// if (!found_character_3d && const SliceablePhysicsObject3D *node = (SliceablePhysicsObject3D*)(damageable) )
// {
// // This is where we handle regular physics objects.
// }
}
}
if (closest_damageable)
@@ -140,7 +146,7 @@ void HurtboxBase::_send_next_in_queue()
}
}
if (this->hit_data_queue.empty() && this->remaining_life <= 0.0f)
if (this->remaining_life <= -this->lifetime)
{
this->queue_free();
}
+6 -4
View File
@@ -9,14 +9,16 @@
#include "orng_macros.h"
#include "nodes/character_nodes/character_3d.h"
#include "nodes/character_nodes/character_skeleton3d.h"
#include "nodes/damageables/character_3d.h"
#include "nodes/damageables/character_skeleton3d.h"
#include <godot_cpp/classes/collision_shape3d.hpp>
#include <godot_cpp/classes/shape3d.hpp>
#include <godot_cpp/classes/area3d.hpp>
using namespace godot;
#define MAX_HITS_PER_QUEUE_LOOP 1
#define HURTBOX_BASE_TAG "HurtboxBase"
@@ -48,7 +50,7 @@ public:
int32_t get_hit_points() const { return this->hit_points; }
protected:
std::map<class IDamageable*, std::vector<HurtboxDamage>> hit_data_queue;
std::map<class DamageableNode3D*, std::vector<HurtboxDamage>> hit_data_queue;
private:
Dictionary _create_hit_data_struct() const;
@@ -61,7 +63,7 @@ private:
float remaining_life = 0.0f;
int32_t hit_points = 0;
std::vector<class IDamageable*> hit_bodies;
std::vector<class DamageableNode3D*> hit_bodies;
// Godot boilerplate below
+2 -2
View File
@@ -39,7 +39,7 @@ void LevelScene::_scene_ready()
#ifdef DEBUG_ENABLED
if (!this->game_classes.is_valid())
{
PRINT_ERROR(LEVEL_SCENE_TAG, "No GameClasses resource attached to level.");
PRINT_ERROR(LevelScene, "No GameClasses resource attached to level.");
return;
}
#endif
@@ -63,7 +63,7 @@ void LevelScene::_scene_ready()
#ifdef DEBUG_ENABLED
if (!spawn_point)
{
PRINT_ERROR(LEVEL_SCENE_TAG, "Could not find a spawn point named ", current_checkpoint, "; defaulting to origin...");
PRINT_ERROR(LevelScene, "Could not find a spawn point named ", current_checkpoint, "; defaulting to origin...");
spawn_point = spawn_points[PLAYER_ORIGIN_TAG];
DEV_ASSERT(spawn_point);
}
-2
View File
@@ -15,8 +15,6 @@
#include <godot_cpp/classes/resource.hpp>
using namespace godot;
#define LEVEL_SCENE_TAG "LevelScene"
#define FELL_OUT_OF_WORLD_SIGNAL "fell_out_of_world"
#define FELL_OUT_OF_WORLD_METHOD "_on_fell_out_of_world"
-909
View File
@@ -1,909 +0,0 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#include "mesh_editing_library.h"
#include "orng_macros.h"
#include "earcut.hpp"
#include <map>
#include "godot_cpp/classes/immediate_mesh.hpp"
#include "godot_cpp/classes/time.hpp"
#include "godot_cpp/variant/utility_functions.hpp"
using namespace godot;
PackedVector3Array MeshEditingLibrary::slice_mesh(MeshInstance3D *original_mesh_instance, const Skeleton3D *original_skeleton, const AABB &original_aabb, const Plane &local_plane, Ref<ArrayMesh> out_first_half, Ref<ArrayMesh> out_other_half, const MeshEditCapUV cap_option, const TypedArray<Material> &cap_materials)
{
const Time *time = Time::get_singleton();
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Started slicing mesh at ", time->get_ticks_msec(), "ms");
const Mesh *original_mesh = original_mesh_instance->get_mesh().ptr();
const uint8_t num_surfaces = original_mesh->get_surface_count();
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Got skinned vertices at ", time->get_ticks_msec(), "ms");
PackedVector3Array impact_points;
std::vector<bool> surface_has_normal; surface_has_normal.resize(num_surfaces);
std::vector<bool> surface_has_tangent; surface_has_tangent.resize(num_surfaces);
std::vector<bool> surface_has_uv; surface_has_uv.resize(num_surfaces);
std::vector<bool> surface_has_uv2; surface_has_uv2.resize(num_surfaces);
std::vector<bool> surface_has_colour; surface_has_colour.resize(num_surfaces);
std::vector<bool> surface_has_bone; surface_has_bone.resize(num_surfaces);
std::vector<bool> surface_has_weight; surface_has_weight.resize(num_surfaces);
std::vector<uint32_t> surface_bone_array_size; surface_bone_array_size.resize(num_surfaces);
std::vector<uint8_t> surface_num_bones_per_vertex; surface_num_bones_per_vertex.resize(num_surfaces);
std::vector<PackedVector3Array> first_half_vertices; first_half_vertices.resize(num_surfaces);
std::vector<PackedVector3Array> first_half_normals; first_half_normals.resize(num_surfaces);
std::vector<PackedFloat32Array> first_half_tangents; first_half_tangents.resize(num_surfaces);
std::vector<PackedVector2Array> first_half_uvs; first_half_uvs.resize(num_surfaces);
std::vector<PackedVector2Array> first_half_uv2s; first_half_uv2s.resize(num_surfaces);
std::vector<PackedColorArray> first_half_colours; first_half_colours.resize(num_surfaces);
std::vector<PackedInt32Array> first_half_bones; first_half_bones.resize(num_surfaces);
std::vector<PackedFloat32Array> first_half_weights; first_half_weights.resize(num_surfaces);
std::vector<PackedVector3Array> other_half_vertices; other_half_vertices.resize(num_surfaces);
std::vector<PackedVector3Array> other_half_normals; other_half_normals.resize(num_surfaces);
std::vector<PackedFloat32Array> other_half_tangents; other_half_tangents.resize(num_surfaces);
std::vector<PackedVector2Array> other_half_uvs; other_half_uvs.resize(num_surfaces);
std::vector<PackedVector2Array> other_half_uv2s; other_half_uv2s.resize(num_surfaces);
std::vector<PackedColorArray> other_half_colours; other_half_colours.resize(num_surfaces);
std::vector<PackedInt32Array> other_half_bones; other_half_bones.resize(num_surfaces);
std::vector<PackedFloat32Array> other_half_weights; other_half_weights.resize(num_surfaces);
std::vector<PackedInt32Array> first_half_indices; first_half_indices.resize(num_surfaces);
std::vector<PackedInt32Array> other_half_indices; other_half_indices.resize(num_surfaces);
PackedVector3Array cap_section_vertices;
PackedVector3Array cap_section_normals;
PackedVector3Array cap_section_flipped_normals;
PackedFloat32Array cap_section_tangents;
PackedFloat32Array cap_section_flipped_tangents;
PackedVector2Array cap_section_uvs;
PackedVector2Array cap_section_uv2s;
PackedColorArray cap_section_colours;
PackedInt32Array cap_section_bones;
PackedFloat32Array cap_section_weights;
PackedInt32Array cap_section_indices;
std::vector<std::vector<Transform3D>> skinned_vertex_transforms;
std::vector<MeshEditEdge3D> clip_edges;
for (uint8_t surface = 0; surface < num_surfaces; surface++)
{
Ref<Material> original_material = original_mesh->surface_get_material(surface);
std::vector<Transform3D> surface_skinned_vertex_transforms;
const SkinnedVertices &surface_skinned_vertex_positions = MeshEditingLibrary::get_skinned_vertex_positions(surface, original_mesh, original_skeleton, surface_skinned_vertex_transforms);
const Array &surface_arrays = original_mesh->surface_get_arrays(surface);
const PackedVector3Array &surface_vertex_array = surface_arrays[ArrayMesh::ARRAY_VERTEX];
const PackedVector3Array &surface_normal_array = surface_arrays[ArrayMesh::ARRAY_NORMAL];
const PackedFloat32Array &surface_tangent_array = surface_arrays[ArrayMesh::ARRAY_TANGENT];
const PackedVector2Array &surface_uv_array = surface_arrays[ArrayMesh::ARRAY_TEX_UV];
const PackedVector2Array &surface_uv2_array = surface_arrays[ArrayMesh::ARRAY_TEX_UV2];
const PackedColorArray &surface_colour_array = surface_arrays[ArrayMesh::ARRAY_COLOR];
const PackedInt32Array &surface_bone_array = surface_arrays[ArrayMesh::ARRAY_BONES];
const PackedFloat32Array &surface_weight_array = surface_arrays[ArrayMesh::ARRAY_WEIGHTS];
const Vector3 *surface_vertex_array_ptr = surface_vertex_array.ptr();
const uint32_t num_vertices = surface_vertex_array.size();
std::vector<float> vertex_distance;
vertex_distance.resize(num_vertices);
std::map<uint32_t, uint32_t> base_to_sliced_vert_index;
std::map<uint32_t, uint32_t> base_to_other_sliced_vert_index;
const bool has_normal = surface_normal_array.size() >= num_vertices; surface_has_normal[surface] = has_normal;
const bool has_tangent = surface_tangent_array.size() >= num_vertices * 4; surface_has_tangent[surface] = has_tangent;
const bool has_uv = surface_uv_array.size() >= num_vertices; surface_has_uv[surface] = has_uv;
const bool has_uv2 = surface_uv2_array.size() >= num_vertices; surface_has_uv2[surface] = has_uv2;
const bool has_colour = surface_colour_array.size() >= num_vertices; surface_has_colour[surface] = has_colour;
const bool has_bone = surface_bone_array.size() >= num_vertices * 4; surface_has_bone[surface] = has_bone;
const bool has_weight = surface_weight_array.size() >= num_vertices * 4; surface_has_weight[surface] = has_weight;
const uint32_t bone_array_size = surface_bone_array.size();
surface_bone_array_size[surface] = bone_array_size;
const uint8_t num_bones_per_vertex = surface_bone_array_size[surface] / num_vertices;
surface_num_bones_per_vertex[surface] = num_bones_per_vertex;
for (uint32_t vertex = 0; vertex < num_vertices; vertex++)
{
vertex_distance[vertex] = local_plane.distance_to(surface_skinned_vertex_positions[vertex]);
if (vertex_distance[vertex] >= 0.0f)
{
base_to_sliced_vert_index[vertex] = first_half_vertices[surface].size();
first_half_vertices[surface].append(surface_vertex_array_ptr[vertex]);
if (has_normal) { first_half_normals[surface].append(surface_normal_array.ptr()[vertex]); }
if (has_uv) { first_half_uvs[surface].append(surface_uv_array.ptr()[vertex]); }
if (has_uv2) { first_half_uv2s[surface].append(surface_uv2_array.ptr()[vertex]); }
if (has_colour) { first_half_colours[surface].append(surface_colour_array.ptr()[vertex]); }
if (has_tangent)
{
first_half_tangents[surface].append(surface_tangent_array.ptr()[vertex * 4]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 1]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 2]);
first_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 3]);
}
if (has_bone)
{
for (uint8_t i = 0; i < num_bones_per_vertex; i++)
{
first_half_bones[surface].append(surface_bone_array.ptr()[(vertex * num_bones_per_vertex) + i]);
first_half_weights[surface].append(surface_weight_array.ptr()[(vertex * num_bones_per_vertex) + i]);
}
}
}
else
{
base_to_other_sliced_vert_index[vertex] = other_half_vertices[surface].size();
other_half_vertices[surface].append(surface_vertex_array_ptr[vertex]);
if (has_normal) { other_half_normals[surface].append(surface_normal_array.ptr()[vertex]); }
if (has_uv) { other_half_uvs[surface].append(surface_uv_array.ptr()[vertex]); }
if (has_uv2) { other_half_uv2s[surface].append(surface_uv2_array.ptr()[vertex]); }
if (has_colour) { other_half_colours[surface].append(surface_colour_array.ptr()[vertex]); }
if (has_tangent)
{
other_half_tangents[surface].append(surface_tangent_array.ptr()[vertex * 4]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 1]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 2]);
other_half_tangents[surface].append(surface_tangent_array.ptr()[(vertex * 4) + 3]);
}
if (has_bone)
{
for (uint8_t i = 0; i < num_bones_per_vertex; i++)
{
other_half_bones[surface].append(surface_bone_array.ptr()[(vertex * num_bones_per_vertex) + i]);
other_half_weights[surface].append(surface_weight_array.ptr()[(vertex * num_bones_per_vertex) + i]);
}
}
}
}
const PackedInt32Array &surface_index_array = surface_arrays[ArrayMesh::ARRAY_INDEX];
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Surface ", surface, " sorted by plane distance at ", time->get_ticks_msec(), "ms");
if (!(first_half_vertices[surface].size() > 0 && other_half_vertices[surface].size() > 0))
{
if (first_half_vertices[surface].size() > 0)
{
first_half_indices[surface] = surface_index_array;
}
else if (other_half_vertices[surface].size() > 0)
{
other_half_indices[surface] = surface_index_array;
}
}
else
{
const uint32_t num_triangles = surface_index_array.size();
for (uint32_t triangle_index = 0; triangle_index < num_triangles; triangle_index += 3)
{
uint32_t base_v[3];
std::map<uint32_t, uint32_t>::iterator sliced_v[3];
std::map<uint32_t, uint32_t>::iterator sliced_other_v[3];
const std::map<uint32_t, uint32_t>::iterator base_to_sliced_end = base_to_sliced_vert_index.end();
const std::map<uint32_t, uint32_t>::iterator base_to_other_sliced_end = base_to_other_sliced_vert_index.end();
for (uint32_t i = 0; i < 3; i++)
{
base_v[i] = surface_index_array.ptr()[triangle_index + i];
sliced_v[i] = base_to_sliced_vert_index.find(base_v[i]);
sliced_other_v[i] = base_to_other_sliced_vert_index.find(base_v[i]);
// All vertex indices must be represented by one of the two slice index maps.
assert((sliced_v[i] != base_to_sliced_vert_index.end()) != (sliced_other_v[i] != base_to_other_sliced_vert_index.end()));
}
if (sliced_v[0] != base_to_sliced_end && sliced_v[1] != base_to_sliced_end && sliced_v[2] != base_to_sliced_end)
{ // If the triangle is entirely in the first slice, send all the vertices to the first slice.
first_half_indices[surface].append(sliced_v[0]->second);
first_half_indices[surface].append(sliced_v[1]->second);
first_half_indices[surface].append(sliced_v[2]->second);
}
else if (sliced_other_v[0] != base_to_other_sliced_end && sliced_other_v[1] != base_to_other_sliced_end && sliced_other_v[2] != base_to_other_sliced_end)
{ // If the triangle is entirely in the second slice, send all the vertices to the second slice.
other_half_indices[surface].append(sliced_other_v[0]->second);
other_half_indices[surface].append(sliced_other_v[1]->second);
other_half_indices[surface].append(sliced_other_v[2]->second);
}
else
{ // If the triangle is split by the slice plane, then slice the overlapping edges.
uint32_t final_verts[4] = { 0, 0, 0, 0 };
uint8_t num_final_verts = 0;
uint32_t other_final_verts[4] = { 0, 0, 0, 0 };
uint8_t num_other_final_verts = 0;
MeshEditEdge3D new_clip_edge;
uint8_t clipped_edges = 0;
float plane_distance[3] = {
vertex_distance[base_v[0]],
vertex_distance[base_v[1]],
vertex_distance[base_v[2]]
};
for (uint32_t this_vert = 0; this_vert < 3; this_vert++)
{
if (sliced_v[this_vert] != base_to_sliced_end)
{
final_verts[num_final_verts] = sliced_v[this_vert]->second;
num_final_verts++;
}
else
{
other_final_verts[num_other_final_verts] = sliced_other_v[this_vert]->second;
num_other_final_verts++;
}
uint32_t next_vert = (this_vert + 1) % 3;
if ((sliced_v[this_vert] == base_to_sliced_end) != (sliced_v[next_vert] == base_to_sliced_end))
{
const float alpha = UtilityFunctions::clampf(-plane_distance[this_vert] / (plane_distance[next_vert] - plane_distance[this_vert]), 0.0f, 1.0f);
const Vector3 &interp_vert = surface_vertex_array[base_v[this_vert]].lerp(
surface_vertex_array[base_v[next_vert]], alpha);
final_verts[num_final_verts++] = first_half_vertices[surface].size();
other_final_verts[num_other_final_verts++] = other_half_vertices[surface].size();
const Vector3 &skinned_interp_vert = surface_skinned_vertex_positions[base_v[this_vert]].lerp(
surface_skinned_vertex_positions[base_v[next_vert]], alpha);
MeshEditVert3D edge_vertex;
edge_vertex.surface = surface;
edge_vertex.index = first_half_vertices[surface].size();
edge_vertex.position = skinned_interp_vert;
if (clipped_edges == 0)
{
new_clip_edge.v0 = edge_vertex;
}
else
{
new_clip_edge.v1 = edge_vertex;
}
clipped_edges++;
assert(clipped_edges <= 2);
first_half_vertices[surface].append(interp_vert);
other_half_vertices[surface].append(interp_vert);
if (has_normal)
{
const Vector3 interp_normal = surface_normal_array.ptr()[base_v[this_vert]].slerp(surface_normal_array.ptr()[base_v[next_vert]], alpha);
first_half_normals[surface].append(interp_normal);
other_half_normals[surface].append(interp_normal);
}
if (has_tangent)
{
const float *this_tangent_start = (surface_tangent_array.ptr() + (base_v[this_vert] * 4));
const float *next_tangent_start = (surface_tangent_array.ptr() + (base_v[next_vert] * 4));
const Vector3 &this_tangent = Vector3(*this_tangent_start, *(this_tangent_start + 1), *(this_tangent_start + 2));
const Vector3 &next_tangent = Vector3(*next_tangent_start, *(next_tangent_start + 1), *(next_tangent_start + 2));
const float this_binormal = *(this_tangent_start + 3);
const float next_binormal = *(next_tangent_start + 3);
const Vector3 &interp_tangent = this_tangent.slerp(next_tangent, alpha);
const uint8_t &interp_binormal = UtilityFunctions::roundi(UtilityFunctions::lerpf(this_binormal, next_binormal, alpha));
first_half_tangents[surface].append(interp_tangent.x);
first_half_tangents[surface].append(interp_tangent.y);
first_half_tangents[surface].append(interp_tangent.z);
first_half_tangents[surface].append(interp_binormal);
other_half_tangents[surface].append(interp_tangent.x);
other_half_tangents[surface].append(interp_tangent.y);
other_half_tangents[surface].append(interp_tangent.z);
other_half_tangents[surface].append(interp_binormal);
}
if (has_uv)
{
const Vector2 &interp_uv = surface_uv_array.ptr()[base_v[this_vert]].lerp(surface_uv_array.ptr()[base_v[next_vert]], alpha);
first_half_uvs[surface].append(interp_uv);
other_half_uvs[surface].append(interp_uv);
}
if (has_uv2)
{
const Vector2 &interp_uv2 = surface_uv2_array.ptr()[base_v[this_vert]].lerp(surface_uv2_array.ptr()[base_v[next_vert]], alpha);
first_half_uv2s[surface].append(interp_uv2);
other_half_uv2s[surface].append(interp_uv2);
}
if (has_colour)
{
const Color &interp_colour = surface_colour_array.ptr()[base_v[this_vert]].lerp(surface_colour_array.ptr()[base_v[next_vert]], alpha);
first_half_colours[surface].append(interp_colour);
other_half_colours[surface].append(interp_colour);
}
if (has_bone && has_weight)
{
std::map<int32_t, float> positive_side_bones_and_weights;
float normalisation_value = 0.0f;
// First pack all active bones and weights into a list of pairs
uint8_t vertex_bone = 0;
for (vertex_bone = 0; vertex_bone < num_bones_per_vertex; vertex_bone++)
{
const int32_t bone = surface_bone_array[(base_v[this_vert] * num_bones_per_vertex) + vertex_bone];
const float weight = surface_weight_array[(base_v[this_vert] * num_bones_per_vertex) + vertex_bone];
if (weight > TINY_NUMBER) { positive_side_bones_and_weights[bone] = weight; }
}
// Next, find each second half bone that matches one in the first half, and interpolate between them.
// If the second half has a unique bone, interpolate a new value from 0 for it.
// Delete any matches from the first half, leaving only unique bones to add later.
std::map<int32_t, float> negative_side_bones_and_weights;
std::vector<std::pair<int32_t, float>> bone_weight_pairs;
for (uint32_t other_bone_index = 0; other_bone_index < num_bones_per_vertex; other_bone_index++)
{
const uint32_t other_bone = surface_bone_array[(base_v[next_vert] * num_bones_per_vertex) + other_bone_index];
const float other_weight = surface_weight_array[(base_v[next_vert] * num_bones_per_vertex) + other_bone_index];
if (negative_side_bones_and_weights.find(other_bone) != negative_side_bones_and_weights.end())
{
continue;
}
std::map<int32_t, float>::iterator matching_bone_iterator = positive_side_bones_and_weights.find(other_bone);
if (matching_bone_iterator == positive_side_bones_and_weights.end())
{
const float lerped_weight = (float)UtilityFunctions::lerpf(0.0f, other_weight, alpha);
bone_weight_pairs.emplace_back(other_bone, lerped_weight);
normalisation_value += lerped_weight;
}
else
{
const float lerped_weight = (float)UtilityFunctions::lerpf(matching_bone_iterator->second, other_weight, alpha);
bone_weight_pairs.emplace_back(matching_bone_iterator->first, lerped_weight);
positive_side_bones_and_weights.erase(matching_bone_iterator);
normalisation_value += lerped_weight;
}
negative_side_bones_and_weights[other_bone] = other_weight;
}
// Interpolate all remaining bones in the first half and add them to the pairs list.
for (std::map<int32_t, float>::iterator i = positive_side_bones_and_weights.begin(); i != positive_side_bones_and_weights.end(); i++)
{
const float lerped_weight = (float)UtilityFunctions::lerpf(i->second, 0.0f, alpha);
bone_weight_pairs.emplace_back(i->first, lerped_weight);
normalisation_value += lerped_weight;
}
// Sort the list of bones and weights from highest weight to lowest weight
std::sort(bone_weight_pairs.begin(), bone_weight_pairs.end(),
[=](std::pair<int32_t, float> &a, std::pair<int32_t, float> &b) { return a.second > b.second; });
// Finally, add all our new interpolated bones and weights to the arrays
for (vertex_bone = 0; vertex_bone < num_bones_per_vertex; vertex_bone++)
{
if (vertex_bone < bone_weight_pairs.size())
{
const float normalised_weight = bone_weight_pairs[vertex_bone].second / normalisation_value;
first_half_bones[surface].append(bone_weight_pairs[vertex_bone].first);
first_half_weights[surface].append(normalised_weight);
other_half_bones[surface].append(bone_weight_pairs[vertex_bone].first);
other_half_weights[surface].append(normalised_weight);
}
else
{
first_half_bones[surface].append(0);
first_half_weights[surface].append(0.0f);
other_half_bones[surface].append(0);
other_half_weights[surface].append(0.0f);
}
}
}
const Transform3D &interp_bone_transform = surface_skinned_vertex_transforms[base_v[this_vert]].interpolate_with(
surface_skinned_vertex_transforms[base_v[next_vert]], alpha);
surface_skinned_vertex_transforms.emplace_back(interp_bone_transform);
}
}
// There should always be exactly two sliced edges per triangle
assert(clipped_edges == 2);
clip_edges.emplace_back(new_clip_edge);
for (uint32_t vertex_index = 2; vertex_index < num_final_verts; vertex_index++)
{
first_half_indices[surface].append(final_verts[0]);
first_half_indices[surface].append(final_verts[vertex_index - 1]);
first_half_indices[surface].append(final_verts[vertex_index]);
}
for (uint32_t vertex_index = 2; vertex_index < num_other_final_verts; vertex_index++)
{
other_half_indices[surface].append(other_final_verts[0]);
other_half_indices[surface].append(other_final_verts[vertex_index - 1]);
other_half_indices[surface].append(other_final_verts[vertex_index]);
}
}
}
}
if (first_half_vertices[surface].size() > 0 && first_half_indices[surface].size() > 0)
{
Array first_half_section;
first_half_section.resize(ArrayMesh::ARRAY_MAX);
first_half_section[ArrayMesh::ARRAY_VERTEX] = first_half_vertices[surface];
if (has_normal) first_half_section[ArrayMesh::ARRAY_NORMAL] = first_half_normals[surface];
if (has_tangent) first_half_section[ArrayMesh::ARRAY_TANGENT] = first_half_tangents[surface];
if (has_uv) first_half_section[ArrayMesh::ARRAY_TEX_UV] = first_half_uvs[surface];
if (has_uv2) first_half_section[ArrayMesh::ARRAY_TEX_UV2] = first_half_uv2s[surface];
if (has_colour) first_half_section[ArrayMesh::ARRAY_COLOR] = first_half_colours[surface];
if (has_bone) first_half_section[ArrayMesh::ARRAY_BONES] = first_half_bones[surface];
if (has_weight) first_half_section[ArrayMesh::ARRAY_WEIGHTS] = first_half_weights[surface];
first_half_section[ArrayMesh::ARRAY_INDEX] = first_half_indices[surface];
const uint16_t next_surface = out_first_half->get_surface_count();
out_first_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, first_half_section);
out_first_half->surface_set_material(next_surface, original_material);
}
if (other_half_vertices[surface].size() > 0 && other_half_indices[surface].size() > 0)
{
Array other_half_section;
other_half_section.resize(ArrayMesh::ARRAY_MAX);
other_half_section[ArrayMesh::ARRAY_VERTEX] = other_half_vertices[surface];
if (has_normal) other_half_section[ArrayMesh::ARRAY_NORMAL] = other_half_normals[surface];
if (has_tangent) other_half_section[ArrayMesh::ARRAY_TANGENT] = other_half_tangents[surface];
if (has_uv) other_half_section[ArrayMesh::ARRAY_TEX_UV] = other_half_uvs[surface];
if (has_uv2) other_half_section[ArrayMesh::ARRAY_TEX_UV2] = other_half_uv2s[surface];
if (has_colour) other_half_section[ArrayMesh::ARRAY_COLOR] = other_half_colours[surface];
if (has_bone) other_half_section[ArrayMesh::ARRAY_BONES] = other_half_bones[surface];
if (has_weight) other_half_section[ArrayMesh::ARRAY_WEIGHTS] = other_half_weights[surface];
other_half_section[ArrayMesh::ARRAY_INDEX] = other_half_indices[surface];
const uint16_t next_surface = out_other_half->get_surface_count();
out_other_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, other_half_section);
out_other_half->surface_set_material(next_surface, original_material);
}
skinned_vertex_transforms.emplace_back(surface_skinned_vertex_transforms);
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Surface ", surface, " split edges at ", time->get_ticks_msec(), "ms");
}
MeshSlicePlaneOrientation uv_plane = MeshSlicePlaneOrientation::Z;
const Basis &mesh_instance_basis = original_mesh_instance->get_basis();
const Vector3 &local_plane_normal = local_plane.get_normal();
if (UtilityFunctions::absf(local_plane_normal.dot(mesh_instance_basis.xform(Vector3(0.0f, 1.0f, 0.0f)))) > 0.5f)
{
uv_plane = MeshSlicePlaneOrientation::Y;
}
else if (UtilityFunctions::absf(local_plane_normal.dot(mesh_instance_basis.xform(Vector3(1.0f, 0.0f, 0.0f)))) > 0.5f)
{
uv_plane = MeshSlicePlaneOrientation::X;
}
if (clip_edges.size() > 0)
{
std::vector<MeshEditEdge2D> edges_2d;
std::vector<MeshEditPolygon2D> polygon_set;
std::vector<MeshEditPolygon2D> error_polygons;
const Transform3D &plane_inverse_transform = MeshEditingLibrary::project_edges(edges_2d, clip_edges, local_plane);
MeshEditingLibrary::build_2d_polygons_from_edges(polygon_set, edges_2d, error_polygons);
MeshEditingLibrary::draw_debug_polygons(original_mesh_instance, error_polygons, plane_inverse_transform, Color(1.0f, 0.0f, 0.0f, 1.0f));
const Vector3 &mesh_bounds = original_aabb.get_size();
const uint32_t num_polygons = polygon_set.size();
for (uint32_t polygon_index = 0; polygon_index < num_polygons; polygon_index++)
{
using Point = std::array<float,2>;
using Polygon = std::vector<std::vector<Point>>;
Polygon earcut_polygon;
std::vector<Point> sub_polygon;
Vector3 polygon_centroid;
const uint32_t polygon_vertex_base = cap_section_vertices.size();
for (const MeshEditVert2D &vertex : polygon_set[polygon_index].vertices)
{
const Vector3 &position = first_half_vertices[vertex.surface][vertex.index];
const Transform3D &skinned_vertex_transform = skinned_vertex_transforms[vertex.surface][vertex.index];
const Vector3 &local_plane_transformed_normal = skinned_vertex_transform.xform(local_plane_normal).normalized();
cap_section_vertices.append(position);
if (surface_has_normal[vertex.surface])
{
cap_section_normals.append(local_plane_transformed_normal);
cap_section_flipped_normals.append(local_plane_transformed_normal * -1.0f);
}
if (surface_has_colour[vertex.surface]) { cap_section_colours.append(first_half_colours[vertex.surface][vertex.index]); }
if (surface_has_uv[vertex.surface]) { cap_section_uvs.append(MeshEditingLibrary::calculate_planar_uv(position, mesh_bounds, uv_plane)); }
if (surface_has_uv2[vertex.surface]) { cap_section_uv2s.append(first_half_uv2s[vertex.surface][vertex.index]); }
if (surface_has_tangent[vertex.surface])
{
for (uint8_t i = 0; i < 4; i++)
{
cap_section_tangents.append(first_half_tangents[vertex.surface][(vertex.index * 4) + i] * -1.0f);
cap_section_flipped_tangents.append(first_half_tangents[vertex.surface][(vertex.index * 4) + i]);
}
}
if (surface_has_bone[vertex.surface])
{
for (uint8_t i = 0; i < surface_num_bones_per_vertex[vertex.surface]; i++)
{
cap_section_bones.append(first_half_bones[vertex.surface][(vertex.index * surface_num_bones_per_vertex[vertex.surface]) + i]);
}
}
if (surface_has_weight[vertex.surface])
{
for (uint8_t i = 0; i < surface_num_bones_per_vertex[vertex.surface]; i++)
{
cap_section_weights.append(first_half_weights[vertex.surface][(vertex.index * surface_num_bones_per_vertex[vertex.surface]) + i]);
}
}
sub_polygon.push_back({vertex.position.x, vertex.position.y});
polygon_centroid += position;
}
polygon_centroid /= polygon_set[polygon_index].vertices.size();
impact_points.append(polygon_centroid);
earcut_polygon.push_back(sub_polygon);
std::vector<uint32_t> indices = mapbox::earcut<uint32_t>(earcut_polygon);
for (uint32_t i = 0; (i+2) < indices.size(); i += 3)
{
cap_section_indices.append(indices[i+1] + polygon_vertex_base);
cap_section_indices.append(indices[i] + polygon_vertex_base);
cap_section_indices.append(indices[i+2] + polygon_vertex_base);
}
}
}
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Created cap surfaces at ", time->get_ticks_msec(), "ms");
if (cap_section_vertices.size() > 0 && cap_section_indices.size() > 0)
{
Array cap_mesh_section;
cap_mesh_section.resize(ArrayMesh::ARRAY_MAX);
cap_mesh_section[ArrayMesh::ARRAY_VERTEX] = cap_section_vertices;
cap_mesh_section[ArrayMesh::ARRAY_INDEX] = cap_section_indices;
if (cap_section_normals.size()) cap_mesh_section[ArrayMesh::ARRAY_NORMAL] = cap_section_normals;
// if (cap_section_tangents.size()) cap_mesh_section[ArrayMesh::ARRAY_TANGENT] = cap_section_tangents;
if (cap_section_colours.size()) cap_mesh_section[ArrayMesh::ARRAY_COLOR] = cap_section_colours;
if (cap_section_uvs.size()) cap_mesh_section[ArrayMesh::ARRAY_TEX_UV] = cap_section_uvs;
if (cap_section_uv2s.size()) cap_mesh_section[ArrayMesh::ARRAY_TEX_UV2] = cap_section_uv2s;
if (cap_section_bones.size()) cap_mesh_section[ArrayMesh::ARRAY_BONES] = cap_section_bones;
if (cap_section_weights.size()) cap_mesh_section[ArrayMesh::ARRAY_WEIGHTS] = cap_section_weights;
out_first_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, cap_mesh_section);
out_first_half->surface_set_material(out_first_half->get_surface_count()-1, cap_materials[uv_plane]);
const uint32_t num_cap_triangles = cap_section_indices.size();
for (uint32_t i = 0; i < num_cap_triangles; i += 3)
{
const int32_t old_index = cap_section_indices[i];
cap_section_indices[i] = cap_section_indices[i+1];
cap_section_indices[i+1] = old_index;
}
Array cap_other_mesh_section;
cap_other_mesh_section.resize(ArrayMesh::ARRAY_MAX);
cap_other_mesh_section[ArrayMesh::ARRAY_VERTEX] = cap_section_vertices;
cap_other_mesh_section[ArrayMesh::ARRAY_INDEX] = cap_section_indices;
if (cap_section_normals.size()) cap_other_mesh_section[ArrayMesh::ARRAY_NORMAL] = cap_section_flipped_normals;
// if (cap_section_tangents.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TANGENT] = cap_section_flipped_tangents;
if (cap_section_colours.size()) cap_other_mesh_section[ArrayMesh::ARRAY_COLOR] = cap_section_colours;
if (cap_section_uvs.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TEX_UV] = cap_section_uvs;
if (cap_section_uv2s.size()) cap_other_mesh_section[ArrayMesh::ARRAY_TEX_UV2] = cap_section_uv2s;
if (cap_section_bones.size()) cap_other_mesh_section[ArrayMesh::ARRAY_BONES] = cap_section_bones;
if (cap_section_weights.size()) cap_other_mesh_section[ArrayMesh::ARRAY_WEIGHTS] = cap_section_weights;
out_other_half->add_surface_from_arrays(ArrayMesh::PRIMITIVE_TRIANGLES, cap_other_mesh_section);
out_other_half->surface_set_material(out_other_half->get_surface_count()-1, cap_materials[uv_plane]);
PRINT_LOG(MESH_EDITING_LIBRARY_TAG, "Generated final cap surface at ", time->get_ticks_msec(), "ms");
}
return impact_points;
}
SkinnedVertices MeshEditingLibrary::get_skinned_vertex_positions(const uint8_t surface, const Mesh *mesh, const Skeleton3D *skeleton, std::vector<Transform3D> &vertex_transforms)
{
const uint8_t num_surfaces = mesh->get_surface_count();
if (surface > num_surfaces)
{
PRINT_ERROR(MESH_EDITING_LIBRARY_TAG, "This mesh doesn't have that many surfaces! You wrote ", surface, ", but there's only ", num_surfaces, "here!");
}
SkinnedVertices skinned_vertex_array;
if (skeleton)
{
const uint16_t bone_count = skeleton->get_bone_count();
std::vector<Transform3D> bone_transforms;
bone_transforms.resize(bone_count);
for (uint8_t bone_index = 0; bone_index < bone_count; bone_index++)
{
bone_transforms[bone_index] = skeleton->get_bone_global_pose(bone_index) * skeleton->get_bone_global_rest(bone_index).inverse();
}
const Array &mesh_arrays = mesh->surface_get_arrays(surface);
const PackedVector3Array &mesh_vertex_array = mesh_arrays[ArrayMesh::ARRAY_VERTEX];
const uint32_t mesh_vertex_array_size = mesh_vertex_array.size();
skinned_vertex_array.resize(mesh_vertex_array_size);
vertex_transforms.resize(mesh_vertex_array_size);
const PackedInt32Array &mesh_bones_array = mesh_arrays[ArrayMesh::ARRAY_BONES];
const PackedFloat32Array &mesh_weights_array = mesh_arrays[ArrayMesh::ARRAY_WEIGHTS];
const uint8_t num_bones_per_vertex = mesh_bones_array.size() / mesh_vertex_array_size;
for (uint32_t vertex_index = 0; vertex_index < mesh_vertex_array_size; vertex_index++)
{
const Vector3 &vertex = mesh_vertex_array[vertex_index];
Transform3D *transforms = new Transform3D[num_bones_per_vertex];
const uint32_t bone_index_start = (vertex_index * num_bones_per_vertex);
for (uint8_t bone_index_offset = 0; bone_index_offset < num_bones_per_vertex; bone_index_offset++)
{
const float weight = mesh_weights_array[bone_index_start + bone_index_offset];
const uint32_t bone = mesh_bones_array[bone_index_start + bone_index_offset];
transforms[bone_index_offset] = ((Transform3D)bone_transforms[bone]) * weight;
}
Vector3 x_basis, y_basis, z_basis, origin;
for (uint8_t transform = 0; transform < num_bones_per_vertex; transform++)
{
x_basis += transforms[transform].basis.rows[0];
y_basis += transforms[transform].basis.rows[1];
z_basis += transforms[transform].basis.rows[2];
origin += transforms[transform].origin;
}
const Transform3D &final_bone_transform = Transform3D(
x_basis.x, x_basis.y, x_basis.z,
y_basis.x, y_basis.y, y_basis.z,
z_basis.x, z_basis.y, z_basis.z,
origin.x, origin.y, origin.z);
vertex_transforms[vertex_index] = final_bone_transform;
skinned_vertex_array[vertex_index] = final_bone_transform.xform(vertex);
delete transforms;
}
return skinned_vertex_array;
}
else
{
for (uint8_t surface = 0; surface < num_surfaces; surface++)
{
const Array &mesh_arrays = mesh->surface_get_arrays(surface);
const PackedVector3Array &mesh_vertex_array = mesh_arrays[ArrayMesh::ARRAY_VERTEX];
const uint32_t mesh_vertex_array_size = mesh_vertex_array.size();
SkinnedVertices skinned_vertex_array;
skinned_vertex_array.resize(mesh_vertex_array_size);
for (uint32_t vertex_index = 0; vertex_index < mesh_vertex_array_size; vertex_index++)
{
skinned_vertex_array[vertex_index] = mesh_vertex_array[vertex_index];
}
}
return skinned_vertex_array;
}
return SkinnedVertices();
}
const Transform3D MeshEditingLibrary::project_edges(std::vector<MeshEditEdge2D> &out_2d_edges, const std::vector<MeshEditEdge3D> &in_3d_edges, const Plane &plane)
{
out_2d_edges.resize(in_3d_edges.size());
const Transform3D &plane_inverse_transform = Transform3D(Basis::looking_at(plane.get_normal()), plane.center()).inverse();
for (uint32_t i = 0; i < in_3d_edges.size(); i++)
{
MeshEditVert2D v0;
Vector3 p = plane_inverse_transform.xform(in_3d_edges[i].v0.position);
v0.surface = in_3d_edges[i].v0.surface;
v0.index = in_3d_edges[i].v0.index;
v0.position.x = p.x;
v0.position.y = p.y;
MeshEditVert2D v1;
p = plane_inverse_transform.xform(in_3d_edges[i].v1.position);
v1.index = in_3d_edges[i].v1.index;
v1.surface = in_3d_edges[i].v1.surface;
v1.position.x = p.x;
v1.position.y = p.y;
out_2d_edges[i].v0 = v0;
out_2d_edges[i].v1 = v1;
}
return plane_inverse_transform;
}
void MeshEditingLibrary::build_2d_polygons_from_edges(std::vector<MeshEditPolygon2D> &out_polygons, const std::vector<MeshEditEdge2D> &in_edges, std::vector<MeshEditPolygon2D> &error_polygons)
{
std::vector<MeshEditEdge2D> edge_set = in_edges;
while (edge_set.size() > 0)
{
MeshEditPolygon2D new_polygon;
const MeshEditEdge2D &first_edge = edge_set.back();
edge_set.pop_back();
new_polygon.vertices.emplace_back(first_edge.v0);
new_polygon.vertices.emplace_back(first_edge.v1);
MeshEditVert2D &polygon_end = new_polygon.vertices.back();
MeshEditEdge2D next_edge;
while (MeshEditingLibrary::find_next_edge(next_edge, edge_set, polygon_end))
{
new_polygon.vertices.emplace_back(next_edge.v1);
polygon_end = new_polygon.vertices.back();
}
if (new_polygon.vertices.size() >= 4 && (new_polygon.vertices.front().position - new_polygon.vertices.back().position).length_squared() < PRETTY_SMALL_NUMBER)
{
new_polygon.vertices.pop_back();
MeshEditingLibrary::fix_polygon_winding(new_polygon);
out_polygons.emplace_back(new_polygon);
}
else
{
error_polygons.emplace_back(new_polygon);
}
}
}
bool MeshEditingLibrary::find_next_edge(MeshEditEdge2D &out_next_edge, std::vector<MeshEditEdge2D> &in_edge_set, const MeshEditVert2D &start)
{
float closest_squared_distance = FLT_MAX;
int32_t out_edge_index = -1;
// Search the edges for one that starts closest to the starting point
uint32_t num_in_edges = in_edge_set.size();
for (uint32_t i = 0; i < num_in_edges; i++)
{
float distance_squared = (in_edge_set[i].v0.position - start.position).length_squared();
if (distance_squared < closest_squared_distance)
{
closest_squared_distance = distance_squared;
out_next_edge = in_edge_set[i];
out_edge_index = i;
}
distance_squared = (in_edge_set[i].v1.position - start.position).length_squared();
if (distance_squared < closest_squared_distance)
{
closest_squared_distance = distance_squared;
out_next_edge = in_edge_set[i];
std::swap(out_next_edge.v0, out_next_edge.v1);
out_edge_index = i;
}
}
// If the next edge starts close enough, return it
if (closest_squared_distance < TINY_NUMBER)
{
assert(out_edge_index >= 0);
in_edge_set.erase(in_edge_set.begin() + out_edge_index);
return true;
}
return false;
}
void MeshEditingLibrary::fix_polygon_winding(MeshEditPolygon2D &polygon)
{
float total_angle = 0.0f;
for (int32_t i = polygon.vertices.size() - 1; i >= 0; i--)
{
const int32_t a_index = (i - 1) % polygon.vertices.size();
const int32_t b_index = i;
const int32_t c_index = (i + 1) % polygon.vertices.size();
const float ab_dist_squared = (polygon.vertices[b_index].position - polygon.vertices[a_index].position).length_squared();
const Vector2 ab_edge = (polygon.vertices[b_index].position - polygon.vertices[a_index].position).normalized();
const float bc_dist_squared = (polygon.vertices[c_index].position - polygon.vertices[b_index].position).length_squared();
const Vector2 bc_edge = (polygon.vertices[c_index].position - polygon.vertices[b_index].position).normalized();
if (ab_dist_squared < TINY_NUMBER || bc_dist_squared < TINY_NUMBER || (ab_edge - bc_edge).length_squared() < TEENY_TINY_NUMBER)
{
polygon.vertices.erase(polygon.vertices.begin() + i);
}
else
{
total_angle += UtilityFunctions::asin(ab_edge.x * bc_edge.y - ab_edge.y * bc_edge.x);
}
}
if (total_angle < 0.0f)
{
const uint32_t num_vertices = polygon.vertices.size();
std::vector<MeshEditVert2D> new_vertices;
new_vertices.resize(num_vertices);
for (uint32_t i = 0; i < num_vertices; i++)
{
new_vertices[i] = polygon.vertices[num_vertices - (i + 1)];
}
polygon.vertices = new_vertices;
}
}
const Vector2 MeshEditingLibrary::calculate_planar_uv(const Vector3 &vertex, const Vector3 &mesh_bounds, const MeshSlicePlaneOrientation &axis)
{
switch(axis)
{
case MeshSlicePlaneOrientation::X:
return Vector2(1.0f - (vertex.z / mesh_bounds.z) + 0.5f, 1.0f - (vertex.y / mesh_bounds.y));
case MeshSlicePlaneOrientation::Y:
return Vector2(1.0f - (vertex.x / mesh_bounds.x) + 0.5f, (vertex.z / mesh_bounds.z) + 0.5f);
case MeshSlicePlaneOrientation::Z: default:
return Vector2(1.0f - (vertex.x / mesh_bounds.x) + 0.5f, 1.0f - (vertex.y / mesh_bounds.y));
}
}
void MeshEditingLibrary::draw_debug_polygons(Node3D *mesh_parent_node, const std::vector<MeshEditPolygon2D> &polygons, const Transform3D &plane_transform, const Color &colour)
{
#ifdef DEBUG_ENABLED
if (polygons.size() <= 0)
return;
Ref<StandardMaterial3D> material;
material.instantiate();
material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
ImmediateMesh *im = memnew(ImmediateMesh);
im->surface_begin(Mesh::PRIMITIVE_LINE_STRIP, material);
const uint32_t num_polygons = polygons.size();
for (uint32_t i = 0; i < num_polygons; i++)
{
const MeshEditPolygon2D &polygon = polygons[i];
const uint32_t num_points = polygons[i].vertices.size();
for (uint32_t j = 0; j < num_points; j++)
{
const MeshEditVert2D &vertex = polygon.vertices[j];
const Vector3 &transformed_vertex = plane_transform.inverse().xform(Vector3(vertex.position.x, vertex.position.y, 0.0f));
im->surface_set_color(colour);
im->surface_add_vertex(transformed_vertex);
}
const MeshEditVert2D &vertex = polygon.vertices.front();
const Vector3 &transformed_vertex = plane_transform.inverse().xform(Vector3(vertex.position.x, vertex.position.y, 0.0f));
im->surface_set_color(colour);
im->surface_add_vertex(transformed_vertex);
}
im->surface_end();
MeshInstance3D *mi = memnew(MeshInstance3D);
mesh_parent_node->add_child(mi);
mi->set_transform(Transform3D());
mi->set_mesh(im);
#endif // DEBUG_ENABLED
}
-107
View File
@@ -1,107 +0,0 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include <godot_cpp/classes/array_mesh.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/skeleton3d.hpp>
#include <godot_cpp/classes/standard_material3d.hpp>
#include <godot_cpp/variant/plane.hpp>
#include <godot_cpp/variant/vector3.hpp>
using namespace godot;
#include <vector>
#define MESH_EDITING_LIBRARY_TAG "MeshEditingLibrary"
typedef std::vector<Vector3> SkinnedVertices;
typedef std::vector<SkinnedVertices> SkinnedSurfaces;
struct MeshEditVert3D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector3 position; // Position used for generating geometry
};
struct MeshEditVert2D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector2 position; // Position used for generating geometry
};
struct MeshEditEdge2D
{
MeshEditVert2D v0; // Start vertex
MeshEditVert2D v1; // End vertex
};
struct MeshEditEdge3D
{
MeshEditVert3D v0; // Start vertex
MeshEditVert3D v1; // End vertex
};
struct MeshEditPolygon2D
{
std::vector<MeshEditVert2D> vertices; // List of vertices representing a closed 2D polygon
};
class MeshEditingLibrary : public Node
{
GDCLASS(MeshEditingLibrary, Node);
public:
MeshEditingLibrary(){}
~MeshEditingLibrary(){}
enum MeshEditCapUV
{
CAP_UV_FILL_MESH_BOUNDS,
CAP_UV_FILL_CAP_BOUNDS,
CAP_UV_TILED
};
static PackedVector3Array slice_mesh(MeshInstance3D *original_mesh_instance, const Skeleton3D *original_skeleton, const AABB &original_aabb, const Plane &local_plane, Ref<ArrayMesh> out_first_half, Ref<ArrayMesh> out_other_half, const MeshEditCapUV cap_option, const TypedArray<Material> &cap_materials);
protected:
enum MeshSlicePlaneOrientation
{
X,
Y,
Z
};
private:
static const Vector2 calculate_planar_uv(const Vector3 &vertex, const Vector3 &mesh_bounds, const MeshSlicePlaneOrientation &axis);
static SkinnedVertices get_skinned_vertex_positions(const uint8_t surface, const Mesh *mesh, const Skeleton3D *skeleton = nullptr, std::vector<Transform3D> &bone_transforms = std::vector<Transform3D>());
static const Transform3D project_edges(std::vector<MeshEditEdge2D> &out_2d_edges, const std::vector<MeshEditEdge3D> &in_3d_edges, const Plane &plane);
static void build_2d_polygons_from_edges(std::vector<MeshEditPolygon2D> &out_polygons, const std::vector<MeshEditEdge2D> &in_edges, std::vector<MeshEditPolygon2D> &error_polygons);
static bool find_next_edge(MeshEditEdge2D &out_next_edge, std::vector<MeshEditEdge2D> &in_edge_set, const MeshEditVert2D &start);
static void fix_polygon_winding(MeshEditPolygon2D &polygon);
static void draw_debug_polygons(Node3D *mesh_parent_node, const std::vector<MeshEditPolygon2D> &polygons, const Transform3D &plane_transform, const Color &colour);
// Godot boilerplate below
protected:
static void _bind_methods()
{
ClassDB::bind_static_method("MeshEditingLibrary", D_METHOD("slice_mesh", "original_mesh_instance", "original_skeleton", "local_plane", "out_first_half", "out_other_half", "cap_option", "cap_material"), &MeshEditingLibrary::slice_mesh);
BIND_ENUM_CONSTANT(CAP_UV_FILL_MESH_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_FILL_CAP_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_TILED);
}
};
VARIANT_ENUM_CAST(MeshEditingLibrary::MeshEditCapUV);
+1 -1
View File
@@ -68,7 +68,7 @@ bool PlayerOrigin::spawn_player(Node3D *parent, Ref<PackedScene> player) const
#ifdef DEBUG_ENABLED
else
{
PRINT_ERROR(PLAYERSPAWN_LOG_TAG, "Empty sublevel in PlayerSpawn object \"", this->tag, "\"");
PRINT_ERROR(PlayerOrigin, "Empty sublevel in PlayerSpawn object \"", this->tag, "\"");
}
#endif
}
-2
View File
@@ -14,8 +14,6 @@
#include <godot_cpp/classes/packed_scene.hpp>
using namespace godot;
#define PLAYERSPAWN_LOG_TAG "PlayerSpawn"
#define PLAYER_ORIGIN_TAG "origin"
+9 -7
View File
@@ -34,8 +34,10 @@
/**
* Deferred function helpers
*/
#define CALL_ON_TIMEOUT(T,C) \
this->get_tree()->create_timer(T)->connect("timeout", C)
#define CALL_NEXT_FRAME(C) \
this->get_tree()->create_timer(SMALL_NUMBER)->connect("timeout", C)
CALL_ON_TIMEOUT(SMALL_NUMBER,C)
/**
@@ -52,11 +54,11 @@
* Logging helpers
*/
#ifdef DEBUG_ENABLED
#define PRINT_LOG(tag, ...) UtilityFunctions::print("[" tag "] ", __VA_ARGS__)
#define PRINT_WARNING(tag, ...) UtilityFunctions::push_warning("[" tag "] ", __VA_ARGS__)
#define PRINT_ERROR(tag, ...) UtilityFunctions::printerr("[" tag "] ", __VA_ARGS__)
#define PRINT_LOG(class, ...) UtilityFunctions::print("[", ##class::get_class_static(), "] ", __VA_ARGS__)
#define PRINT_WARNING(class, ...) UtilityFunctions::push_warning("[", ##class::get_class_static(), "] ", __VA_ARGS__)
#define PRINT_ERROR(class, ...) UtilityFunctions::printerr("[", ##class::get_class_static(), "] ", __VA_ARGS__)
#else
#define PRINT_LOG(tag, ...)
#define PRINT_WARNING(tag, ...)
#define PRINT_ERROR(tag, ...)
#define PRINT_LOG(class, ...)
#define PRINT_WARNING(class, ...)
#define PRINT_ERROR(class, ...)
#endif // DEBUG_ENABLED
+10 -4
View File
@@ -21,17 +21,17 @@
#include "nodes/player_spawn.h"
#include "nodes/sublevel_loader.h"
#include "nodes/sublevel_scene.h"
#include "nodes/character_nodes/character_3d.h"
#include "nodes/character_nodes/character_skeleton3d.h"
#include "nodes/damageables/character_3d.h"
#include "nodes/damageables/character_skeleton3d.h"
#include "nodes/damageables/sliceable_rigid_body3d.h"
#include "nodes/hurtbox/hurtbox_base.h"
#include "resources/level_metadata_map.h"
#include "resources/level_metadata_resource.h"
#include "nodes/mesh_editing_library.h"
#include "singletons/input_handler.h"
#include "singletons/mesh_editing_library.h"
#include "singletons/save_manager.h"
#include "singletons/scene_loader.h"
// #include "singletons/vendor_service/vendor_service.h"
@@ -66,7 +66,10 @@ void initialize_orng_module(ModuleInitializationLevel p_level) {
ClassDB::register_class<MovementHandler>();
ClassDB::register_abstract_class<DamageableNode3D>();
ClassDB::register_class<Character3D>();
ClassDB::register_class<SliceableRigidBody3D>();
ClassDB::register_class<CharacterSkeleton3D>();
ClassDB::register_class<GameClasses>();
ClassDB::register_class<LevelScene>();
@@ -78,6 +81,9 @@ void initialize_orng_module(ModuleInitializationLevel p_level) {
ClassDB::register_class<SaveFileData>();
ClassDB::register_class<MeshEditingLibrary>();
ClassDB::register_class<MeshEditSliceInput>();
ClassDB::register_class<MeshEditSliceOutput>();
ClassDB::register_class<MeshEditSliceState>();
GDSINGLETON_REGISTER_CLASS(InputHandler, _input_handler_singleton);
GDSINGLETON_REGISTER_CLASS(SaveManager, _save_manager_singleton);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,261 @@
/*
* ©2026 Batty Bovine Productions, LLC. All Rights Reserved.
*
* If this source code makes it to the public internet, this software can be
* considered to be protected by the MIT licence. Have fun with it.
*/
#pragma once
#include <godot_cpp/classes/array_mesh.hpp>
#include <godot_cpp/classes/mesh_instance3d.hpp>
#include <godot_cpp/classes/skeleton3d.hpp>
#include <godot_cpp/classes/standard_material3d.hpp>
#include <godot_cpp/variant/plane.hpp>
#include <godot_cpp/variant/vector3.hpp>
using namespace godot;
#include <map>
#include <vector>
#define MESH_EDITING_SLICE_LOOP_LIMIT 5.555555555555555f
#define START_LOOP_TIMER() const Time *time = Time::get_singleton(); const float start_time = time->get_ticks_msec()
#define RETURN_IF_TIME_IS_UP() if ((time->get_ticks_msec() - start_time) > MESH_EDITING_SLICE_LOOP_LIMIT) return time->get_ticks_msec() - start_time
#define RETURN_LOOP_TIME() return time->get_ticks_msec() - start_time
typedef PackedVector3Array SkinnedVertices;
typedef std::vector<SkinnedVertices> SkinnedSurfaces;
typedef std::vector<Transform3D> SkinnedVertexTransforms;
struct MeshEditVert3D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector3 position; // Position used for generating geometry
};
struct MeshEditVert2D
{
uint8_t surface; // Surface index of the original vertex array
uint32_t index; // Index into the original vertex array
Vector2 position; // Position used for generating geometry
};
struct MeshEditEdge2D
{
MeshEditVert2D v0; // Start vertex
MeshEditVert2D v1; // End vertex
};
struct MeshEditEdge3D
{
MeshEditVert3D v0; // Start vertex
MeshEditVert3D v1; // End vertex
};
struct MeshEditPolygon2D
{
std::vector<MeshEditVert2D> vertices; // List of vertices representing a closed 2D polygon
};
class MeshEditSliceInput;
class MeshEditSliceOutput;
class MeshEditSliceState;
class MeshEditingLibrary : public Node
{
GDCLASS(MeshEditingLibrary, Node);
public:
MeshEditingLibrary(){}
~MeshEditingLibrary(){}
enum MeshEditSliceStage
{
SLICE_STAGE_INIT,
SLICE_STAGE_GET_SKINNED_VERTS,
SLICE_STAGE_PLANE_SPLIT,
SLICE_STAGE_EDGE_SPLIT,
SLICE_STAGE_APPLY_CAP,
SLICE_STAGE_COMPLETE
};
enum MeshEditCapUV
{
CAP_UV_FILL_MESH_BOUNDS,
CAP_UV_FILL_CAP_BOUNDS,
CAP_UV_TILED
};
static Ref<class MeshEditSliceState> slice_mesh(const Ref<class MeshEditSliceInput> input);
static float slice_mesh_init(Ref<class MeshEditSliceState> state);
static float slice_mesh_get_skinned_verts(Ref<class MeshEditSliceState> state);
static float slice_mesh_plane_split(Ref<class MeshEditSliceState> state);
static float slice_mesh_edge_split(Ref<class MeshEditSliceState> state);
static float slice_mesh_apply_cap(Ref<class MeshEditSliceState> state);
static Dictionary MeshEditingLibrary::split_mesh_by_body_part(Ref<ArrayMesh> mesh);
protected:
enum MeshSlicePlaneOrientation
{
X,
Y,
Z
};
private:
static const Vector2 calculate_planar_uv(const Vector3 &vertex, const Vector3 &mesh_bounds, const MeshSlicePlaneOrientation &axis);
static constexpr const uint8_t uv_to_body_part_shift(const float x, const float y) { return (uint8_t(y * 5.0f) * 5) + uint8_t(x * 5.0f); }
static const Transform3D project_edges(std::vector<MeshEditEdge2D> &out_2d_edges, const std::vector<MeshEditEdge3D> &in_3d_edges, const Plane &plane);
static void build_2d_polygons_from_edges(std::vector<MeshEditPolygon2D> &out_polygons, const std::vector<MeshEditEdge2D> &in_edges, std::vector<MeshEditPolygon2D> &error_polygons);
static bool find_next_edge(MeshEditEdge2D &out_next_edge, std::vector<MeshEditEdge2D> &in_edge_set, const MeshEditVert2D &start);
static void fix_polygon_winding(MeshEditPolygon2D &polygon);
static void draw_debug_polygons(Node3D *mesh_parent_node, const std::vector<MeshEditPolygon2D> &polygons, const Transform3D &plane_transform, const Color &colour);
// Godot boilerplate below
protected:
static void _bind_methods()
{
ClassDB::bind_static_method("MeshEditingLibrary", D_METHOD("slice_mesh", "input"), &MeshEditingLibrary::slice_mesh);
BIND_ENUM_CONSTANT(SLICE_STAGE_INIT);
BIND_ENUM_CONSTANT(SLICE_STAGE_GET_SKINNED_VERTS);
BIND_ENUM_CONSTANT(SLICE_STAGE_PLANE_SPLIT);
BIND_ENUM_CONSTANT(SLICE_STAGE_EDGE_SPLIT);
BIND_ENUM_CONSTANT(SLICE_STAGE_APPLY_CAP);
BIND_ENUM_CONSTANT(SLICE_STAGE_COMPLETE);
BIND_ENUM_CONSTANT(CAP_UV_FILL_MESH_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_FILL_CAP_BOUNDS);
BIND_ENUM_CONSTANT(CAP_UV_TILED);
}
};
VARIANT_ENUM_CAST(MeshEditingLibrary::MeshEditSliceStage);
VARIANT_ENUM_CAST(MeshEditingLibrary::MeshEditCapUV);
class MeshEditSliceInput : public RefCounted
{
GDCLASS(MeshEditSliceInput, RefCounted);
public:
MeshInstance3D *mesh_instance = nullptr;
const Skeleton3D *skeleton = nullptr;
AABB full_aabb;
Plane local_plane;
uint32_t hit_mask = 0b1111111111111111111111111;
MeshEditingLibrary::MeshEditCapUV cap_option;
TypedArray<Material> cap_materials;
protected:
static void _bind_methods(){}
};
class MeshEditSliceOutput : public RefCounted
{
GDCLASS(MeshEditSliceOutput, RefCounted);
public:
const Skeleton3D *original_skeleton = nullptr;
AABB original_full_aabb;
Plane original_local_plane;
Ref<ArrayMesh> main_half;
uint32_t main_half_split_map = 0b0000000000000000000000000;
Ref<ArrayMesh> secondary_half;
uint32_t secondary_half_split_map = 0b0000000000000000000000000;
PackedVector3Array impact_points;
uint32_t hit_map = 0b0000000000000000000000000;
protected:
static void _bind_methods(){}
};
class MeshEditSliceState : public RefCounted
{
GDCLASS(MeshEditSliceState, RefCounted);
public:
MeshEditingLibrary::MeshEditSliceStage current_stage = MeshEditingLibrary::MeshEditSliceStage::SLICE_STAGE_INIT;
MeshInstance3D *current_mesh = nullptr;
Ref<MeshEditSliceInput> input;
uint8_t surface = 0;
uint32_t element = 0;
Ref<ArrayMesh> first_half;
Ref<ArrayMesh> other_half;
Ref<ArrayMesh> original_mesh;
uint8_t num_surfaces;
std::vector<Array> surface_arrays_list;
std::vector<SkinnedVertices> skinned_vertex_positions;
std::vector<SkinnedVertexTransforms> skinned_vertex_transforms;
std::vector<bool> has_normal;
std::vector<bool> has_tangent;
std::vector<bool> has_uv;
std::vector<bool> has_uv2;
std::vector<bool> has_colour;
std::vector<bool> has_bone;
std::vector<bool> has_weight;
std::vector<bool> has_custom0;
std::vector<uint8_t> num_bones_per_vertex;
std::vector<uint8_t> num_custom0_per_vertex;
std::vector<PackedVector3Array> first_half_vertices;
std::vector<PackedVector3Array> first_half_normals;
std::vector<PackedFloat32Array> first_half_tangents;
std::vector<PackedVector2Array> first_half_uvs;
std::vector<PackedVector2Array> first_half_uv2s;
std::vector<PackedColorArray> first_half_colours;
std::vector<PackedInt32Array> first_half_bones;
std::vector<PackedFloat32Array> first_half_weights;
std::vector<PackedFloat32Array> first_half_custom0;
std::vector<PackedVector3Array> other_half_vertices;
std::vector<PackedVector3Array> other_half_normals;
std::vector<PackedFloat32Array> other_half_tangents;
std::vector<PackedVector2Array> other_half_uvs;
std::vector<PackedVector2Array> other_half_uv2s;
std::vector<PackedColorArray> other_half_colours;
std::vector<PackedInt32Array> other_half_bones;
std::vector<PackedFloat32Array> other_half_weights;
std::vector<PackedFloat32Array> other_half_custom0;
std::vector<PackedInt32Array> first_half_indices;
std::vector<PackedInt32Array> other_half_indices;
std::vector<std::vector<float>> vertex_distances;
std::vector<std::map<uint32_t, uint32_t>> base_to_first_sliced_vert_indices;
std::vector<std::map<uint32_t, uint32_t>> base_to_other_sliced_vert_indices;
uint32_t first_half_split_map = 0b0000000000000000000000000;
uint32_t other_half_split_map = 0b0000000000000000000000000;
std::vector<MeshEditEdge3D> clip_edges;
Ref<MeshEditSliceOutput> output;
protected:
static void _bind_methods(){}
};
+1 -1
View File
@@ -168,7 +168,7 @@ void SceneLoader::load_scene(const StringName path, Callable callback)
if (!this->resource_loader) return;
if (this->resource_loader->load_threaded_request(path, "PackedScene", true) != Error::OK)
{
PRINT_ERROR("SceneLoader", "Scene ", path, " does not exist.");
PRINT_ERROR(SceneLoader, "Scene ", path, " does not exist.");
return;
}