From 770496ee9d0e45480c0e0f8951adb8eee247bfe1 Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Tue, 10 Dec 2024 19:50:26 +0100 Subject: big WIP --- src/crepe/system/CollisionSystem.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 5b136c6..48a8f86 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -85,7 +85,7 @@ public: public: //! Updates the collision system by checking for collisions between colliders and handling them. - void update() override; + void fixed_update() override; private: /** -- cgit v1.2.3 From 387bf02833c610f93326bf743db463eea8032a62 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Mon, 16 Dec 2024 16:43:02 +0100 Subject: added collision features --- src/crepe/api/Rigidbody.h | 3 ++ src/crepe/system/CollisionSystem.cpp | 79 ++++++++++++++++++++++++++++++++---- src/crepe/system/CollisionSystem.h | 18 ++++++++ 3 files changed, 92 insertions(+), 8 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index b08c8db..8169f0c 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -132,6 +132,9 @@ public: */ vec2 offset; + //! Enable collision handeling in collision system + bool kinematic_collision = true; + /** * \brief Defines the collision layers of a GameObject. * diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index af8adce..4e84d8b 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -63,7 +63,7 @@ void CollisionSystem::update() { // For both objects call the collision handler for (auto & collision_pair : collided) { this->collision_handler_request(collision_pair.first, collision_pair.second); - this->collision_handler_request(collision_pair.second, collision_pair.first); + // this->collision_handler_request(collision_pair.second, collision_pair.first); } } @@ -302,16 +302,57 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co } void CollisionSystem::determine_collision_handler(CollisionInfo & info) { - // Check rigidbody type for static - if (info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return; - // If second body is static perform the static collision handler in this system - if (info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) { - this->static_collision_handler(info); - }; - // Call collision event for user + // If both objects are static skip handle call collision script + if(info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return; + + // First body is not dynamic + if(info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) + { + bool static_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; + bool kinematic_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC && info.this_rigidbody.data.kinematic_collision; + // Inverted collision info + CollisionInfo inverted = { + .this_collider = info.other_collider, + .this_transform = info.other_transform, + .this_rigidbody = info.other_rigidbody, + .this_metadata = info.other_metadata, + .other_collider = info.this_collider, + .other_transform = info.this_transform, + .other_rigidbody = info.this_rigidbody, + .other_metadata = info.this_metadata, + .resolution = -info.resolution, + .resolution_direction = info.resolution_direction, + }; + + if(static_collision || kinematic_collision){ + // Static collision + this->static_collision_handler(inverted); + }; + // Call scripts + this->call_collision_events(inverted); + return; + } + + // Second body is not dynamic + if(info.other_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) + { + bool static_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC; + bool kinematic_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.kinematic_collision; + if(static_collision || kinematic_collision) this->static_collision_handler(info); + this->call_collision_events(info); + return; + } + + //dynamic + this->dynamic_collision_handler(info); + this->call_collision_events(info); +} + +void CollisionSystem::call_collision_events(CollisionInfo & info){ CollisionEvent data(info); EventManager & emgr = this->mediator.event_manager; emgr.trigger_event(data, info.this_collider.game_object_id); + emgr.trigger_event(data, info.other_collider.game_object_id); } void CollisionSystem::static_collision_handler(CollisionInfo & info) { @@ -363,6 +404,28 @@ void CollisionSystem::static_collision_handler(CollisionInfo & info) { } } +void CollisionSystem::dynamic_collision_handler(CollisionInfo & info){ + info.this_transform.position += info.resolution/2; + info.other_transform.position += -(info.resolution/2); + + switch (info.resolution_direction) { + case Direction::BOTH: + info.this_rigidbody.data.linear_velocity = {0, 0}; + break; + case Direction::Y_DIRECTION: + info.this_rigidbody.data.linear_velocity.y = 0; + info.this_transform.position.x -= info.resolution.x; + break; + case Direction::X_DIRECTION: + info.this_rigidbody.data.linear_velocity.x = 0; + info.this_transform.position.y -= info.resolution.y; + break; + case Direction::NONE: + // Not possible + break; + } +} + std::vector> CollisionSystem::gather_collisions(std::vector & colliders) { diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 5b136c6..aebb59b 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -194,6 +194,15 @@ private: */ void determine_collision_handler(CollisionInfo & info); + /** + * \brief Calls both collision script + * + * Calls both collision script to let user add additonal handeling or handle full collision. + * + * \param info Collision information containing data about both colliders. + */ + void call_collision_events(CollisionInfo & info); + /** * \brief Handles collisions involving static objects. * @@ -203,6 +212,15 @@ private: */ void static_collision_handler(CollisionInfo & info); + /** + * \brief Handles collisions involving dynamic objects. + * + * Resolves collisions by adjusting positions and modifying velocities if bounce is enabled. + * + * \param info Collision information containing data about both colliders. + */ + void dynamic_collision_handler(CollisionInfo & info); + private: /** * \brief Checks for collisions between colliders. -- cgit v1.2.3 From b2a7105fa88b7d23dcb5b698c3c10b76c19c789b Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Mon, 16 Dec 2024 18:52:06 +0100 Subject: removed rigidbody offset --- src/crepe/api/Rigidbody.h | 10 ------ src/crepe/system/CollisionSystem.cpp | 70 ++++++++++++++++-------------------- src/crepe/system/CollisionSystem.h | 13 ------- 3 files changed, 31 insertions(+), 62 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 8169f0c..8566d00 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -122,16 +122,6 @@ public: */ float elastisity_coefficient = 0.0; - /** - * \brief Offset of all colliders relative to the object's transform position. - * - * The `offset` defines a positional shift applied to all colliders associated with the object, relative to the object's - * transform position. This allows for the colliders to be placed at a different position than the object's actual - * position, without modifying the object's transform itself. - * - */ - vec2 offset; - //! Enable collision handeling in collision system bool kinematic_collision = true; diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index cb6fe2c..fc8c430 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -23,6 +23,23 @@ using namespace crepe; +vec2 get_current_position(const Transform & transform,const vec2 & offset) { + // Get the rotation in radians + float radians1 = transform.rotation * (M_PI / 180.0); + + // Calculate total offset with scale + vec2 total_offset = offset * transform.scale; + + // Rotate + float rotated_total_offset_x1 + = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); + float rotated_total_offset_y1 + = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); + + // Final positions considering scaling and rotation + return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); +} + void CollisionSystem::update() { std::vector all_colliders; game_object_id_t id = 0; @@ -138,10 +155,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform, - data1.rigidbody); - vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, - data2.rigidbody); + vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); + vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -151,10 +166,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform, - data1.rigidbody); - vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, - data2.rigidbody); + vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); + vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2, collider_pos1); break; @@ -164,10 +177,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform, - data1.rigidbody); - vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, - data2.rigidbody); + vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); + vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); resolution = this->get_circle_circle_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -177,10 +188,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform, - data1.rigidbody); - vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, - data2.rigidbody); + vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); + vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -606,8 +615,8 @@ bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxC const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1); - vec2 final_position2 = this->get_current_position(box2.offset, transform2, rigidbody2); + vec2 final_position1 = get_current_position(transform1,box1.offset); + vec2 final_position2 = get_current_position(transform2,box2.offset); // Scale dimensions vec2 scaled_box1 = box1.dimensions * transform1.scale; @@ -633,8 +642,8 @@ bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1); - vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2); + vec2 final_position1 = get_current_position(transform1,box1.offset); + vec2 final_position2 = get_current_position(transform2,circle2.offset); // Scale dimensions vec2 scaled_box = box1.dimensions * transform1.scale; @@ -666,8 +675,8 @@ bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1 const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = this->get_current_position(circle1.offset, transform1, rigidbody1); - vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2); + vec2 final_position1 = get_current_position(transform1,circle1.offset); + vec2 final_position2 = get_current_position(transform2,circle2.offset); // Scale dimensions float scaled_circle1 = circle1.radius * transform1.scale; @@ -684,21 +693,4 @@ bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1 return distance_squared < radius_sum * radius_sum; } -vec2 CollisionSystem::get_current_position(const vec2 & collider_offset, - const Transform & transform, - const Rigidbody & rigidbody) const { - // Get the rotation in radians - float radians1 = transform.rotation * (M_PI / 180.0); - - // Calculate total offset with scale - vec2 total_offset = (rigidbody.data.offset + collider_offset) * transform.scale; - - // Rotate - float rotated_total_offset_x1 - = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); - float rotated_total_offset_y1 - = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); - // Final positions considering scaling and rotation - return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); -} diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index aebb59b..78fce46 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -100,19 +100,6 @@ private: CollisionInternalType get_collider_type(const collider_variant & collider1, const collider_variant & collider2) const; - /** - * \brief Calculates the current position of a collider. - * - * Combines the Collider offset, Transform position, and Rigidbody offset to compute the position of the collider. - * - * \param collider_offset The offset of the collider. - * \param transform The Transform of the associated game object. - * \param rigidbody The Rigidbody of the associated game object. - * \return The calculated position of the collider. - */ - vec2 get_current_position(const vec2 & collider_offset, const Transform & transform, - const Rigidbody & rigidbody) const; - private: /** * \brief Handles collision resolution between two colliders. -- cgit v1.2.3 From 16f3aa77cfbfd3327a50a3f11f27e7d7dd303026 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Mon, 16 Dec 2024 21:14:46 +0100 Subject: Added util for position --- src/crepe/facade/SDLContext.cpp | 2 +- src/crepe/system/CollisionSystem.cpp | 79 +++++++++++++++--------------------- src/crepe/system/CollisionSystem.h | 2 +- src/crepe/system/RenderSystem.cpp | 5 ++- src/crepe/util/AbsoluutPosition.cpp | 21 ++++++++++ src/crepe/util/AbsoluutPosition.h | 17 ++++++++ src/crepe/util/CMakeLists.txt | 2 + src/example/game.cpp | 53 ++++++++++++++++-------- src/test/CollisionTest.cpp | 20 ++++----- 9 files changed, 123 insertions(+), 78 deletions(-) create mode 100644 src/crepe/util/AbsoluutPosition.cpp create mode 100644 src/crepe/util/AbsoluutPosition.h (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 20bb030..ee7d149 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -235,7 +235,7 @@ SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const { } size *= cam_aux_data.render_scale * ctx.img_scale * data.scale_offset; - vec2 screen_pos = (ctx.pos + data.position_offset - cam_aux_data.cam_pos + vec2 screen_pos = (ctx.pos - cam_aux_data.cam_pos + (cam_aux_data.zoomed_viewport) / 2) * cam_aux_data.render_scale - size / 2 + cam_aux_data.bar_size; diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index fc8c430..294e7b3 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -15,31 +15,15 @@ #include "api/Rigidbody.h" #include "api/Transform.h" #include "api/Vector2.h" +#include "util/OptionalRef.h" +#include "util/AbsoluutPosition.h" #include "Collider.h" #include "CollisionSystem.h" #include "types.h" -#include "util/OptionalRef.h" using namespace crepe; -vec2 get_current_position(const Transform & transform,const vec2 & offset) { - // Get the rotation in radians - float radians1 = transform.rotation * (M_PI / 180.0); - - // Calculate total offset with scale - vec2 total_offset = offset * transform.scale; - - // Rotate - float rotated_total_offset_x1 - = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); - float rotated_total_offset_y1 - = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); - - // Final positions considering scaling and rotation - return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); -} - void CollisionSystem::update() { std::vector all_colliders; game_object_id_t id = 0; @@ -155,8 +139,9 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); - vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); + + vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); + vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -166,8 +151,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); - vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); + vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); + vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2, collider_pos1); break; @@ -177,8 +162,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); - vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); + vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); + vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); resolution = this->get_circle_circle_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -188,8 +173,8 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = get_current_position(data1.transform,collider1.offset); - vec2 collider_pos2 = get_current_position(data2.transform,collider2.offset); + vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); + vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -311,15 +296,7 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co } void CollisionSystem::determine_collision_handler(CollisionInfo & info) { - // If both objects are static skip handle call collision script - if(info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return; - - // First body is not dynamic - if(info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) - { - bool static_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; - bool kinematic_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC && info.this_rigidbody.data.kinematic_collision; - // Inverted collision info + // Inverted collision info CollisionInfo inverted = { .this_collider = info.other_collider, .this_transform = info.other_transform, @@ -332,13 +309,22 @@ void CollisionSystem::determine_collision_handler(CollisionInfo & info) { .resolution = -info.resolution, .resolution_direction = info.resolution_direction, }; + // If both objects are static skip handle call collision script + if(info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return; + + // First body is not dynamic + if(info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) + { + bool static_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; + bool kinematic_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC && info.this_rigidbody.data.kinematic_collision; + if(static_collision || kinematic_collision){ // Static collision this->static_collision_handler(inverted); }; // Call scripts - this->call_collision_events(inverted); + this->call_collision_events(inverted,info); return; } @@ -348,20 +334,21 @@ void CollisionSystem::determine_collision_handler(CollisionInfo & info) { bool static_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC; bool kinematic_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.kinematic_collision; if(static_collision || kinematic_collision) this->static_collision_handler(info); - this->call_collision_events(info); + this->call_collision_events(info,inverted); return; } //dynamic this->dynamic_collision_handler(info); - this->call_collision_events(info); + this->call_collision_events(info,inverted); } -void CollisionSystem::call_collision_events(CollisionInfo & info){ +void CollisionSystem::call_collision_events(CollisionInfo & info,CollisionInfo & info_inverted){ CollisionEvent data(info); + CollisionEvent data_inverted(info_inverted); EventManager & emgr = this->mediator.event_manager; emgr.trigger_event(data, info.this_collider.game_object_id); - emgr.trigger_event(data, info.other_collider.game_object_id); + emgr.trigger_event(data_inverted, info_inverted.this_collider.game_object_id); } void CollisionSystem::static_collision_handler(CollisionInfo & info) { @@ -615,8 +602,8 @@ bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxC const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = get_current_position(transform1,box1.offset); - vec2 final_position2 = get_current_position(transform2,box2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1,box1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2,box2.offset); // Scale dimensions vec2 scaled_box1 = box1.dimensions * transform1.scale; @@ -642,8 +629,8 @@ bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = get_current_position(transform1,box1.offset); - vec2 final_position2 = get_current_position(transform2,circle2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1,box1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2,circle2.offset); // Scale dimensions vec2 scaled_box = box1.dimensions * transform1.scale; @@ -675,8 +662,8 @@ bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1 const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = get_current_position(transform1,circle1.offset); - vec2 final_position2 = get_current_position(transform2,circle2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1,circle1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2,circle2.offset); // Scale dimensions float scaled_circle1 = circle1.radius * transform1.scale; diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 78fce46..b802426 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -188,7 +188,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void call_collision_events(CollisionInfo & info); + void call_collision_events(CollisionInfo & info,CollisionInfo & info_inverted); /** * \brief Handles collisions involving static objects. diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index afd9548..d14d78d 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -13,6 +13,7 @@ #include "../facade/Texture.h" #include "../manager/ComponentManager.h" #include "../manager/ResourceManager.h" +#include "util/AbsoluutPosition.h" #include "RenderSystem.h" #include "types.h" @@ -105,11 +106,11 @@ void RenderSystem::render_normal(const Sprite & sprite, const Transform & tm) { SDLContext & ctx = this->mediator.sdl_context; ResourceManager & resource_manager = this->mediator.resource_manager; const Texture & res = resource_manager.get(sprite.source); - + vec2 pos = AbsoluutPosition::get_position(tm,sprite.data.position_offset); ctx.draw(SDLContext::RenderContext{ .sprite = sprite, .texture = res, - .pos = tm.position, + .pos = pos, .angle = tm.rotation, .scale = tm.scale, }); diff --git a/src/crepe/util/AbsoluutPosition.cpp b/src/crepe/util/AbsoluutPosition.cpp new file mode 100644 index 0000000..8be625e --- /dev/null +++ b/src/crepe/util/AbsoluutPosition.cpp @@ -0,0 +1,21 @@ +#include "AbsoluutPosition.h" + +using namespace crepe; + +vec2 AbsoluutPosition::get_position(const Transform & transform,const vec2 & offset) { + // Get the rotation in radians + float radians1 = transform.rotation * (M_PI / 180.0); + + // Calculate total offset with scale + vec2 total_offset = offset * transform.scale; + + // Rotate + float rotated_total_offset_x1 + = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); + float rotated_total_offset_y1 + = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); + + // Final positions considering scaling and rotation + return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); +} + diff --git a/src/crepe/util/AbsoluutPosition.h b/src/crepe/util/AbsoluutPosition.h new file mode 100644 index 0000000..4441f90 --- /dev/null +++ b/src/crepe/util/AbsoluutPosition.h @@ -0,0 +1,17 @@ +#pragma once + + +#include "api/Transform.h" + +#include "types.h" + +namespace crepe { + + +class AbsoluutPosition { +public: + static vec2 get_position(const Transform & transform,const vec2 & offset); + +}; + +} // namespace crepe diff --git a/src/crepe/util/CMakeLists.txt b/src/crepe/util/CMakeLists.txt index 94ed906..b4b9221 100644 --- a/src/crepe/util/CMakeLists.txt +++ b/src/crepe/util/CMakeLists.txt @@ -1,6 +1,7 @@ target_sources(crepe PUBLIC LogColor.cpp Log.cpp + AbsoluutPosition.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -11,5 +12,6 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES Proxy.hpp OptionalRef.h OptionalRef.hpp + AbsoluutPosition.h ) diff --git a/src/example/game.cpp b/src/example/game.cpp index 8ea50ea..3ba15d2 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -3,6 +3,7 @@ #include "manager/ComponentManager.h" #include "manager/Mediator.h" #include "types.h" +#include #include #include #include @@ -66,11 +67,6 @@ class MyScript1 : public Script { //add collider switch break; } - case Keycode::Q: { - Rigidbody & rg = this->get_component(); - rg.data.angular_velocity = 1; - break; - } default: break; } @@ -139,6 +135,31 @@ class MyScript2 : public Script { //add collider switch break; } + case Keycode::J: { + Rigidbody & tf = this->get_component(); + tf.data.linear_velocity.x = -10; + break; + } + case Keycode::I: { + Rigidbody & tf = this->get_component(); + tf.data.linear_velocity.y -= 1; + break; + } + case Keycode::K: { + Rigidbody & tf = this->get_component(); + tf.data.linear_velocity.y += 1; + break; + } + case Keycode::L: { + Rigidbody & tf = this->get_component(); + tf.data.linear_velocity.x = 10; + break; + } + case Keycode::O: { + Rigidbody & tf = this->get_component(); + tf.data.linear_velocity.x = 0; + break; + } default: break; } @@ -175,7 +196,6 @@ public: .mass = 0, .gravity_scale = 0, .body_type = Rigidbody::BodyType::STATIC, - .offset = {0, 0}, .collision_layers = {0}, }); world.add_component( @@ -198,24 +218,26 @@ public: }); GameObject game_object1 = new_object( - "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); + "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 45, 1); game_object1.add_component(Rigidbody::Data{ .mass = 1, - .gravity_scale = 1, - .body_type = Rigidbody::BodyType::DYNAMIC, + .gravity_scale = 0, + .body_type = Rigidbody::BodyType::KINEMATIC, .linear_velocity = {0, 1}, .constraints = {0, 0, 0}, .elastisity_coefficient = 1, - .offset = {0, 0}, .collision_layers = {0}, }); // add box with boxcollider game_object1.add_component(vec2{0, 0}, vec2{20, 20}); game_object1.add_component().set_script(); - Asset img1{"asset/texture/square.png"}; + Asset img1{"asset/texture/test_ap43.png"}; game_object1.add_component(img1, Sprite::Data{ + .sorting_in_layer = 2, + .order_in_layer = 2, .size = {20, 20}, + .position_offset = {0,-10}, }); //add circle with cirlcecollider deactiveated @@ -233,16 +255,15 @@ public: "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); game_object2.add_component(Rigidbody::Data{ .mass = 1, - .gravity_scale = 0, - .body_type = Rigidbody::BodyType::STATIC, + .gravity_scale = 1, + .body_type = Rigidbody::BodyType::KINEMATIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, - .elastisity_coefficient = 1, - .offset = {0, 0}, + .elastisity_coefficient = 0.66, .collision_layers = {0}, }); // add box with boxcollider - game_object2.add_component(vec2{0, 0}, vec2{20, 20}); + game_object2.add_component(vec2{0, 0}, vec2{INFINITY, 20}); game_object2.add_component().set_script(); game_object2.add_component(img1, Sprite::Data{ diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index 2ad65fa..43bf77d 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -66,7 +66,6 @@ public: world.add_component(Rigidbody::Data{ // TODO: remove unrelated properties: .body_type = Rigidbody::BodyType::STATIC, - .offset = {0, 0}, }); // Create a box with an inner size of 10x10 units world.add_component(vec2{0, -100}, vec2{100, 100}); // Top @@ -81,7 +80,6 @@ public: .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, .elastisity_coefficient = 1, - .offset = {0, 0}, .collision_layers = {0}, }); game_object1.add_component(vec2{0, 0}, vec2{10, 10}); @@ -97,7 +95,6 @@ public: .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, .elastisity_coefficient = 1, - .offset = {0, 0}, .collision_layers = {0}, }); game_object2.add_component(vec2{0, 0}, vec2{10, 10}); @@ -138,8 +135,8 @@ TEST_F(CollisionTest, collision_box_box_dynamic_both_no_velocity) { script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; EXPECT_EQ(ev.info.this_collider.game_object_id, 2); - EXPECT_EQ(ev.info.resolution.x, 10); - EXPECT_EQ(ev.info.resolution.y, 10); + EXPECT_EQ(ev.info.resolution.x, -10); + EXPECT_EQ(ev.info.resolution.y, -10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; EXPECT_FALSE(collision_happend); @@ -211,8 +208,8 @@ TEST_F(CollisionTest, collision_box_box_dynamic_both) { script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; EXPECT_EQ(ev.info.this_collider.game_object_id, 2); - EXPECT_EQ(ev.info.resolution.x, 10); - EXPECT_EQ(ev.info.resolution.y, 10); + EXPECT_EQ(ev.info.resolution.x, -10); + EXPECT_EQ(ev.info.resolution.y, -10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; EXPECT_FALSE(collision_happend); @@ -294,8 +291,7 @@ TEST_F(CollisionTest, collision_box_box_static_both) { EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { - // is static should not be called - FAIL(); + collision_happend = true; }; EXPECT_FALSE(collision_happend); Transform & tf = this->mgr.get_components_by_id(1).front().get(); @@ -318,7 +314,7 @@ TEST_F(CollisionTest, collision_box_box_static_x_direction) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { // is static should not be called - FAIL(); + //FAIL(); }; EXPECT_FALSE(collision_happend); Transform & tf = this->mgr.get_components_by_id(1).front().get(); @@ -343,7 +339,7 @@ TEST_F(CollisionTest, collision_box_box_static_y_direction) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { // is static should not be called - FAIL(); + //FAIL(); }; EXPECT_FALSE(collision_happend); Transform & tf = this->mgr.get_components_by_id(1).front().get(); @@ -368,7 +364,7 @@ TEST_F(CollisionTest, collision_box_box_static_multiple) { //todo check visually }; script_object2_ref->test_fn = [&](const CollisionEvent & ev) { // is static should not be called - FAIL(); + //FAIL(); }; EXPECT_FALSE(collision_happend); Transform & tf = this->mgr.get_components_by_id(1).front().get(); -- cgit v1.2.3 From 5bece30f9ad495a0e82097b2c5668e979856fb69 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Mon, 16 Dec 2024 21:22:35 +0100 Subject: make format --- src/crepe/facade/SDLContext.cpp | 3 +- src/crepe/system/CollisionSystem.cpp | 123 +++++++++++++++++++---------------- src/crepe/system/CollisionSystem.h | 2 +- src/crepe/system/ParticleSystem.cpp | 2 +- src/crepe/system/RenderSystem.cpp | 2 +- src/crepe/util/AbsoluutPosition.cpp | 3 +- src/crepe/util/AbsoluutPosition.h | 5 +- src/example/game.cpp | 2 +- src/test/CollisionTest.cpp | 5 +- src/test/Profiling.cpp | 26 ++++---- 10 files changed, 90 insertions(+), 83 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index ee7d149..a1a6f97 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -235,8 +235,7 @@ SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const { } size *= cam_aux_data.render_scale * ctx.img_scale * data.scale_offset; - vec2 screen_pos = (ctx.pos - cam_aux_data.cam_pos - + (cam_aux_data.zoomed_viewport) / 2) + vec2 screen_pos = (ctx.pos - cam_aux_data.cam_pos + (cam_aux_data.zoomed_viewport) / 2) * cam_aux_data.render_scale - size / 2 + cam_aux_data.bar_size; diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 294e7b3..9604543 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -15,8 +15,8 @@ #include "api/Rigidbody.h" #include "api/Transform.h" #include "api/Vector2.h" -#include "util/OptionalRef.h" #include "util/AbsoluutPosition.h" +#include "util/OptionalRef.h" #include "Collider.h" #include "CollisionSystem.h" @@ -139,9 +139,11 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - - vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); - vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); + + vec2 collider_pos1 + = AbsoluutPosition::get_position(data1.transform, collider1.offset); + vec2 collider_pos2 + = AbsoluutPosition::get_position(data2.transform, collider2.offset); resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -151,8 +153,10 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); - vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); + vec2 collider_pos1 + = AbsoluutPosition::get_position(data1.transform, collider1.offset); + vec2 collider_pos2 + = AbsoluutPosition::get_position(data2.transform, collider2.offset); resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2, collider_pos1); break; @@ -162,8 +166,10 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const CircleCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); - vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); + vec2 collider_pos1 + = AbsoluutPosition::get_position(data1.transform, collider1.offset); + vec2 collider_pos2 + = AbsoluutPosition::get_position(data2.transform, collider2.offset); resolution = this->get_circle_circle_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -173,8 +179,10 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal = std::get>(data1.collider); const BoxCollider & collider2 = std::get>(data2.collider); - vec2 collider_pos1 = AbsoluutPosition::get_position(data1.transform,collider1.offset); - vec2 collider_pos2 = AbsoluutPosition::get_position(data2.transform,collider2.offset); + vec2 collider_pos1 + = AbsoluutPosition::get_position(data1.transform, collider1.offset); + vec2 collider_pos2 + = AbsoluutPosition::get_position(data2.transform, collider2.offset); resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; @@ -297,58 +305,67 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co void CollisionSystem::determine_collision_handler(CollisionInfo & info) { // Inverted collision info - CollisionInfo inverted = { - .this_collider = info.other_collider, - .this_transform = info.other_transform, - .this_rigidbody = info.other_rigidbody, - .this_metadata = info.other_metadata, - .other_collider = info.this_collider, - .other_transform = info.this_transform, - .other_rigidbody = info.this_rigidbody, - .other_metadata = info.this_metadata, - .resolution = -info.resolution, - .resolution_direction = info.resolution_direction, - }; + CollisionInfo inverted = { + .this_collider = info.other_collider, + .this_transform = info.other_transform, + .this_rigidbody = info.other_rigidbody, + .this_metadata = info.other_metadata, + .other_collider = info.this_collider, + .other_transform = info.this_transform, + .other_rigidbody = info.this_rigidbody, + .other_metadata = info.this_metadata, + .resolution = -info.resolution, + .resolution_direction = info.resolution_direction, + }; // If both objects are static skip handle call collision script - if(info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return; + if (info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC + && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) + return; // First body is not dynamic - if(info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) - { - bool static_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; - bool kinematic_collision = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC && info.this_rigidbody.data.kinematic_collision; - - - if(static_collision || kinematic_collision){ + if (info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) { + bool static_collision + = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC + && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; + bool kinematic_collision + = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC + && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC + && info.this_rigidbody.data.kinematic_collision; + + if (static_collision || kinematic_collision) { // Static collision this->static_collision_handler(inverted); }; // Call scripts - this->call_collision_events(inverted,info); + this->call_collision_events(inverted, info); return; } // Second body is not dynamic - if(info.other_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) - { - bool static_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC; - bool kinematic_collision = info.other_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC && info.other_rigidbody.data.kinematic_collision; - if(static_collision || kinematic_collision) this->static_collision_handler(info); - this->call_collision_events(info,inverted); + if (info.other_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) { + bool static_collision + = info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC; + bool kinematic_collision + = info.other_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC + && info.other_rigidbody.data.kinematic_collision; + if (static_collision || kinematic_collision) this->static_collision_handler(info); + this->call_collision_events(info, inverted); return; } //dynamic this->dynamic_collision_handler(info); - this->call_collision_events(info,inverted); + this->call_collision_events(info, inverted); } -void CollisionSystem::call_collision_events(CollisionInfo & info,CollisionInfo & info_inverted){ +void CollisionSystem::call_collision_events(CollisionInfo & info, + CollisionInfo & info_inverted) { CollisionEvent data(info); CollisionEvent data_inverted(info_inverted); EventManager & emgr = this->mediator.event_manager; emgr.trigger_event(data, info.this_collider.game_object_id); - emgr.trigger_event(data_inverted, info_inverted.this_collider.game_object_id); + emgr.trigger_event(data_inverted, + info_inverted.this_collider.game_object_id); } void CollisionSystem::static_collision_handler(CollisionInfo & info) { @@ -400,9 +417,9 @@ void CollisionSystem::static_collision_handler(CollisionInfo & info) { } } -void CollisionSystem::dynamic_collision_handler(CollisionInfo & info){ - info.this_transform.position += info.resolution/2; - info.other_transform.position += -(info.resolution/2); +void CollisionSystem::dynamic_collision_handler(CollisionInfo & info) { + info.this_transform.position += info.resolution / 2; + info.other_transform.position += -(info.resolution / 2); switch (info.resolution_direction) { case Direction::BOTH: @@ -410,8 +427,7 @@ void CollisionSystem::dynamic_collision_handler(CollisionInfo & info){ info.this_rigidbody.data.linear_velocity = -info.this_rigidbody.data.linear_velocity * info.this_rigidbody.data.elastisity_coefficient; - } - else { + } else { info.this_rigidbody.data.linear_velocity = {0, 0}; } @@ -419,8 +435,7 @@ void CollisionSystem::dynamic_collision_handler(CollisionInfo & info){ info.other_rigidbody.data.linear_velocity = -info.other_rigidbody.data.linear_velocity * info.other_rigidbody.data.elastisity_coefficient; - } - else { + } else { info.other_rigidbody.data.linear_velocity = {0, 0}; } break; @@ -602,8 +617,8 @@ bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxC const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1,box1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2,box2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1, box1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2, box2.offset); // Scale dimensions vec2 scaled_box1 = box1.dimensions * transform1.scale; @@ -629,8 +644,8 @@ bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1,box1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2,circle2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1, box1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2, circle2.offset); // Scale dimensions vec2 scaled_box = box1.dimensions * transform1.scale; @@ -662,8 +677,8 @@ bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1 const Rigidbody & rigidbody1, const Rigidbody & rigidbody2) const { // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1,circle1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2,circle2.offset); + vec2 final_position1 = AbsoluutPosition::get_position(transform1, circle1.offset); + vec2 final_position2 = AbsoluutPosition::get_position(transform2, circle2.offset); // Scale dimensions float scaled_circle1 = circle1.radius * transform1.scale; @@ -679,5 +694,3 @@ bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1 // Check if the distance between the centers is less than or equal to the sum of the radii return distance_squared < radius_sum * radius_sum; } - - diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index b802426..23752e1 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -188,7 +188,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void call_collision_events(CollisionInfo & info,CollisionInfo & info_inverted); + void call_collision_events(CollisionInfo & info, CollisionInfo & info_inverted); /** * \brief Handles collisions involving static objects. diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp index fb6cfd7..56f1dfd 100644 --- a/src/crepe/system/ParticleSystem.cpp +++ b/src/crepe/system/ParticleSystem.cpp @@ -48,7 +48,7 @@ void ParticleSystem::update() { void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) { constexpr float DEG_TO_RAD = M_PI / 180.0; - + vec2 initial_position = AbsoluutPosition::get_position(transform, emitter.data.offset); float random_angle = this->generate_random_angle(emitter.data.min_angle, emitter.data.max_angle); diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index fcb52c3..c0717fc 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -106,7 +106,7 @@ void RenderSystem::render_normal(const Sprite & sprite, const Transform & tm) { SDLContext & ctx = this->mediator.sdl_context; ResourceManager & resource_manager = this->mediator.resource_manager; const Texture & res = resource_manager.get(sprite.source); - vec2 pos = AbsoluutPosition::get_position(tm,sprite.data.position_offset); + vec2 pos = AbsoluutPosition::get_position(tm, sprite.data.position_offset); ctx.draw(SDLContext::RenderContext{ .sprite = sprite, .texture = res, diff --git a/src/crepe/util/AbsoluutPosition.cpp b/src/crepe/util/AbsoluutPosition.cpp index 8be625e..296cc09 100644 --- a/src/crepe/util/AbsoluutPosition.cpp +++ b/src/crepe/util/AbsoluutPosition.cpp @@ -2,7 +2,7 @@ using namespace crepe; -vec2 AbsoluutPosition::get_position(const Transform & transform,const vec2 & offset) { +vec2 AbsoluutPosition::get_position(const Transform & transform, const vec2 & offset) { // Get the rotation in radians float radians1 = transform.rotation * (M_PI / 180.0); @@ -18,4 +18,3 @@ vec2 AbsoluutPosition::get_position(const Transform & transform,const vec2 & off // Final positions considering scaling and rotation return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); } - diff --git a/src/crepe/util/AbsoluutPosition.h b/src/crepe/util/AbsoluutPosition.h index 4441f90..30a7f93 100644 --- a/src/crepe/util/AbsoluutPosition.h +++ b/src/crepe/util/AbsoluutPosition.h @@ -1,17 +1,14 @@ #pragma once - #include "api/Transform.h" #include "types.h" namespace crepe { - class AbsoluutPosition { public: - static vec2 get_position(const Transform & transform,const vec2 & offset); - + static vec2 get_position(const Transform & transform, const vec2 & offset); }; } // namespace crepe diff --git a/src/example/game.cpp b/src/example/game.cpp index b30166e..01a509f 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -238,7 +238,7 @@ public: .sorting_in_layer = 2, .order_in_layer = 2, .size = {20, 20}, - .position_offset = {0,-10}, + .position_offset = {0, -10}, }); //add circle with cirlcecollider deactiveated diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index 43bf77d..3cb7f33 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -290,9 +290,8 @@ TEST_F(CollisionTest, collision_box_box_static_both) { EXPECT_EQ(ev.info.resolution.y, 10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; - script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { - collision_happend = true; - }; + script_object2_ref->test_fn + = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; }; EXPECT_FALSE(collision_happend); Transform & tf = this->mgr.get_components_by_id(1).front().get(); tf.position = {50, 30}; diff --git a/src/test/Profiling.cpp b/src/test/Profiling.cpp index 1585061..16736b8 100644 --- a/src/test/Profiling.cpp +++ b/src/test/Profiling.cpp @@ -219,19 +219,19 @@ TEST_F(DISABLED_ProfilingTest, Profiling_3) { .order_in_layer = 1, .size = {.y = 500}, }); - auto & test = gameobject.add_component(test_sprite,ParticleEmitter::Data{ - .max_particles = 10, - .emission_rate = 100, - .end_lifespan = 100000, - .boundary{ - .width = 1000, - .height = 1000, - .offset = vec2{0, 0}, - .reset_on_exit = false, - }, - - } - ); + auto & test = gameobject.add_component( + test_sprite, ParticleEmitter::Data{ + .max_particles = 10, + .emission_rate = 100, + .end_lifespan = 100000, + .boundary{ + .width = 1000, + .height = 1000, + .offset = vec2{0, 0}, + .reset_on_exit = false, + }, + + }); } render_sys.update(); this->game_object_count++; -- cgit v1.2.3 From 3855044ad97a41ca71b0d3ea2240f4eee93cc86f Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Wed, 18 Dec 2024 21:13:55 +0100 Subject: updating collision system --- src/crepe/api/Rigidbody.h | 26 +- src/crepe/system/CollisionSystem.cpp | 745 +++++++++++++++++------------------ src/crepe/system/CollisionSystem.h | 115 +++--- src/crepe/system/ParticleSystem.cpp | 4 +- src/crepe/system/RenderSystem.cpp | 4 +- src/crepe/util/AbsolutePosition.cpp | 20 + src/crepe/util/AbsolutePosition.h | 14 + src/crepe/util/AbsoluutPosition.cpp | 20 - src/crepe/util/AbsoluutPosition.h | 14 - src/crepe/util/CMakeLists.txt | 4 +- src/test/CMakeLists.txt | 46 +-- src/test/CollisionTest.cpp | 69 +--- src/test/Profiling.cpp | 2 +- 13 files changed, 514 insertions(+), 569 deletions(-) create mode 100644 src/crepe/util/AbsolutePosition.cpp create mode 100644 src/crepe/util/AbsolutePosition.h delete mode 100644 src/crepe/util/AbsoluutPosition.cpp delete mode 100644 src/crepe/util/AbsoluutPosition.h (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 0f6be21..df97763 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -2,6 +2,7 @@ #include #include +#include #include "../Component.h" @@ -122,7 +123,7 @@ public: */ float elastisity_coefficient = 0.0; - //! Enable collision handeling in collision system + //! Enable static collision handeling for object colliding with kinematic object in collision system bool kinematic_collision = true; /** @@ -130,9 +131,30 @@ public: * * The `collision_layers` specifies the layers that the GameObject will collide with. * Each element represents a layer ID, and the GameObject will only detect - * collisions with other GameObjects that belong to these layers. + * collisions with other GameObjects that belong to that `collision_layer`. */ std::set collision_layers = {0}; + + //! the collision layer of the object. + int collision_layer = 0; + + /** + * \brief Defines the collision layers of a GameObject. + * + * The `collision_names` specifies where the GameObject will collide with. + * Each element represents a name. + */ + std::set collision_names; + + /** + * \brief Defines the collision layers of a GameObject. + * + * The `collision_tags` specifies where the GameObject will collide with. + * Each element represents a tag. + */ + std::set collision_tags; + + }; public: diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 9604543..8bb8a91 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -15,14 +16,23 @@ #include "api/Rigidbody.h" #include "api/Transform.h" #include "api/Vector2.h" -#include "util/AbsoluutPosition.h" +#include "util/AbsolutePosition.h" #include "util/OptionalRef.h" -#include "Collider.h" #include "CollisionSystem.h" #include "types.h" using namespace crepe; +using enum Rigidbody::BodyType; + +CollisionSystem::CollisionInfo CollisionSystem::CollisionInfo::operator-() const { + return { + .self = this->other, + .other = this->self, + .resolution = -this->resolution, + .resolution_direction = this->resolution_direction, + }; +} void CollisionSystem::update() { std::vector all_colliders; @@ -34,6 +44,7 @@ void CollisionSystem::update() { if (!rigidbody.active) continue; id = rigidbody.game_object_id; Transform & transform = mgr.get_components_by_id(id).front().get(); + Metadata & metadata = mgr.get_components_by_id(id).front().get(); // Check if the boxcollider is active and has the same id as the rigidbody. RefVector boxcolliders = mgr.get_components_by_type(); for (BoxCollider & boxcollider : boxcolliders) { @@ -41,8 +52,8 @@ void CollisionSystem::update() { if (!boxcollider.active) continue; all_colliders.push_back({.id = id, .collider = collider_variant{boxcollider}, - .transform = transform, - .rigidbody = rigidbody}); + .info = {transform,rigidbody, metadata} + }); } // Check if the circlecollider is active and has the same id as the rigidbody. RefVector circlecolliders @@ -52,160 +63,299 @@ void CollisionSystem::update() { if (!circlecollider.active) continue; all_colliders.push_back({.id = id, .collider = collider_variant{circlecollider}, - .transform = transform, - .rigidbody = rigidbody}); + .info = {transform,rigidbody, metadata} + }); } } - // Check between all colliders if there is a collision + // Check between all colliders if there is a collision (collision handling) std::vector> collided = this->gather_collisions(all_colliders); // For both objects call the collision handler for (auto & collision_pair : collided) { - this->collision_handler_request(collision_pair.first, collision_pair.second); - // this->collision_handler_request(collision_pair.second, collision_pair.first); + // Determine type + CollisionInternalType type = this->get_collider_type(collision_pair.first.collider, collision_pair.second.collider); + // Determine resolution + std::pair resolution_data = this->get_collision_resolution(collision_pair.first, collision_pair.second, type); + // Convert internal struct to external struct + CollisionInfo info = this->get_collision_info(collision_pair.first, collision_pair.second,type,resolution_data.first,resolution_data.second); + // Determine if and/or what collison handler is needed. + this->determine_collision_handler(info); } } -void CollisionSystem::collision_handler_request(CollisionInternal & this_data, - CollisionInternal & other_data) { +// Below is for collision detection +std::vector> +CollisionSystem::gather_collisions(const std::vector & colliders) const { + + // TODO: + // If no colliders skip + // Check if colliders has rigidbody if not skip + + // TODO: + // If amount is higer than lets say 16 for now use quadtree otwerwise skip + // Quadtree code + // Quadtree is placed over the input vector + + // Return data of collided colliders which are variants + std::vector> collisions_ret; + //using visit to visit the variant to access the active and id. + for (size_t i = 0; i < colliders.size(); ++i) { + for (size_t j = i + 1; j < colliders.size(); ++j) { + if (colliders[i].id == colliders[j].id) continue; + if (!should_collide(colliders[i], colliders[j])) continue; + CollisionInternalType type = get_collider_type(colliders[i].collider, colliders[j].collider); + if (!get_collision(colliders[i],colliders[j],type)) continue; + collisions_ret.emplace_back(colliders[i], colliders[j]); + } + } + return collisions_ret; +} + + +bool CollisionSystem::should_collide(const CollisionInternal & self, const CollisionInternal & other) const{ + + const Rigidbody::Data & self_rigidbody = self.info.rigidbody.data; + const Rigidbody::Data & other_rigidbody = other.info.rigidbody.data; + const Metadata & self_metadata = self.info.metadata; + const Metadata & other_metadata = other.info.metadata; + + // Check collision layers + if(self_rigidbody.collision_layers.contains(other_rigidbody.collision_layer)) return true; + if(other_rigidbody.collision_layers.contains(self_rigidbody.collision_layer)) return true; + + // Check names + if(self_rigidbody.collision_names.contains(other_metadata.name)) return true; + if(other_rigidbody.collision_names.contains(self_metadata.name)) return true; + + // Check tags + if(self_rigidbody.collision_tags.contains(other_metadata.tag)) return true; + if(other_rigidbody.collision_tags.contains(self_metadata.tag)) return true; + + return false; +} + + +CollisionSystem::CollisionInternalType +CollisionSystem::get_collider_type(const collider_variant & collider1, + const collider_variant & collider2) const { + if (std::holds_alternative>(collider1)) { + if (std::holds_alternative>(collider2)) { + return CollisionInternalType::CIRCLE_CIRCLE; + } else { + return CollisionInternalType::CIRCLE_BOX; + } + } else { + if (std::holds_alternative>(collider2)) { + return CollisionInternalType::BOX_CIRCLE; + } else { + return CollisionInternalType::BOX_BOX; + } + } +} + +bool CollisionSystem::get_collision(const CollisionInternal & self,const CollisionInternal & other,const CollisionInternalType & type) const { + const Transform & self_transform = self.info.transform; + const Transform & other_transform = other.info.transform; + const Rigidbody & self_rigidbody = self.info.rigidbody; + const Rigidbody & other_rigidbody = other.info.rigidbody; + const collider_variant & self_collider = self.collider; + const collider_variant & other_collider = other.collider; - CollisionInternalType type - = this->get_collider_type(this_data.collider, other_data.collider); - std::pair resolution_data - = this->collision_handler(this_data, other_data, type); - ComponentManager & mgr = this->mediator.component_manager; - OptionalRef this_metadata - = mgr.get_components_by_id(this_data.id).front().get(); - OptionalRef other_metadata - = mgr.get_components_by_id(other_data.id).front().get(); - OptionalRef this_collider; - OptionalRef other_collider; switch (type) { - case CollisionInternalType::BOX_BOX: { - this_collider = std::get>(this_data.collider); - other_collider - = std::get>(other_data.collider); - break; + case CollisionInternalType::BOX_BOX: { + const BoxCollider & box_collider1 = std::get>(self_collider); + const BoxCollider & box_collider2 = std::get>(other_collider); + return this->get_box_box_collision(box_collider1, box_collider2, + self_transform, other_transform, + self_rigidbody, other_rigidbody); } case CollisionInternalType::BOX_CIRCLE: { - this_collider = std::get>(this_data.collider); - other_collider - = std::get>(other_data.collider); - break; + const BoxCollider & box_collider = std::get>(self_collider); + const CircleCollider & circle_collider = std::get>(other_collider); + return this->get_box_circle_collision(box_collider, circle_collider, + self_transform, other_transform, + self_rigidbody, other_rigidbody); } - case CollisionInternalType::CIRCLE_BOX: { - this_collider - = std::get>(this_data.collider); - other_collider - = std::get>(other_data.collider); - break; + case CollisionInternalType::CIRCLE_CIRCLE: { + const CircleCollider & circle_collider1 = std::get>(self_collider); + const CircleCollider & circle_collider2 = std::get>(other_collider); + return this->get_circle_circle_collision(circle_collider1, circle_collider2, + self_transform, other_transform, + self_rigidbody, other_rigidbody); } - case CollisionInternalType::CIRCLE_CIRCLE: { - this_collider - = std::get>(this_data.collider); - other_collider - = std::get>(other_data.collider); - break; + case CollisionInternalType::CIRCLE_BOX: { + const CircleCollider & circle_collider = std::get>(self_collider); + const BoxCollider & box_collider = std::get>(other_collider); + return this->get_box_circle_collision(box_collider, circle_collider, + other_transform, self_transform, + other_rigidbody, self_rigidbody); } + case CollisionInternalType::NONE: + break; } + return false; +} - // collision info - crepe::CollisionSystem::CollisionInfo collision_info{ - .this_collider = this_collider, - .this_transform = this_data.transform, - .this_rigidbody = this_data.rigidbody, - .this_metadata = this_metadata, - .other_collider = other_collider, - .other_transform = other_data.transform, - .other_rigidbody = other_data.rigidbody, - .other_metadata = other_metadata, - .resolution = resolution_data.first, - .resolution_direction = resolution_data.second, - }; +bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2, + const Transform & transform1, + const Transform & transform2, + const Rigidbody & rigidbody1, + const Rigidbody & rigidbody2) const { + // Get current positions of colliders + vec2 final_position1 = AbsolutePosition::get_position(transform1, box1.offset); + vec2 final_position2 = AbsolutePosition::get_position(transform2, box2.offset); - // Determine if static needs to be called - this->determine_collision_handler(collision_info); + // Scale dimensions + vec2 scaled_box1 = box1.dimensions * transform1.scale; + vec2 scaled_box2 = box2.dimensions * transform2.scale; + + // Calculate half-extents (half width and half height) + float half_width1 = scaled_box1.x / 2.0; + float half_height1 = scaled_box1.y / 2.0; + float half_width2 = scaled_box2.x / 2.0; + float half_height2 = scaled_box2.y / 2.0; + + // Check if the boxes overlap along the X and Y axes + return (final_position1.x + half_width1 > final_position2.x - half_width2 + && final_position1.x - half_width1 < final_position2.x + half_width2 + && final_position1.y + half_height1 > final_position2.y - half_height2 + && final_position1.y - half_height1 < final_position2.y + half_height2); +} + +bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, + const CircleCollider & circle2, + const Transform & transform1, + const Transform & transform2, + const Rigidbody & rigidbody1, + const Rigidbody & rigidbody2) const { + // Get current positions of colliders + vec2 final_position1 = AbsolutePosition::get_position(transform1, box1.offset); + vec2 final_position2 = AbsolutePosition::get_position(transform2, circle2.offset); + + // Scale dimensions + vec2 scaled_box = box1.dimensions * transform1.scale; + float scaled_circle = circle2.radius * transform2.scale; + + // Calculate box half-extents + float half_width = scaled_box.x / 2.0; + float half_height = scaled_box.y / 2.0; + + // Find the closest point on the box to the circle's center + float closest_x = std::max(final_position1.x - half_width, + std::min(final_position2.x, final_position1.x + half_width)); + float closest_y = std::max(final_position1.y - half_height, + std::min(final_position2.y, final_position1.y + half_height)); + + // Calculate the distance squared between the circle's center and the closest point on the box + float distance_x = final_position2.x - closest_x; + float distance_y = final_position2.y - closest_y; + float distance_squared = distance_x * distance_x + distance_y * distance_y; + + // Compare distance squared with the square of the circle's radius + return distance_squared < scaled_circle * scaled_circle; +} + +bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1, + const CircleCollider & circle2, + const Transform & transform1, + const Transform & transform2, + const Rigidbody & rigidbody1, + const Rigidbody & rigidbody2) const { + // Get current positions of colliders + vec2 final_position1 = AbsolutePosition::get_position(transform1, circle1.offset); + vec2 final_position2 = AbsolutePosition::get_position(transform2, circle2.offset); + + // Scale dimensions + float scaled_circle1 = circle1.radius * transform1.scale; + float scaled_circle2 = circle2.radius * transform2.scale; + + float distance_x = final_position1.x - final_position2.x; + float distance_y = final_position1.y - final_position2.y; + float distance_squared = distance_x * distance_x + distance_y * distance_y; + + // Calculate the sum of the radii + float radius_sum = scaled_circle1 + scaled_circle2; + + // Check if the distance between the centers is less than or equal to the sum of the radii + return distance_squared < radius_sum * radius_sum; } std::pair -CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal & data2, - CollisionInternalType type) { +CollisionSystem::get_collision_resolution(const CollisionInternal & self, const CollisionInternal & other, + const CollisionInternalType & type) const { vec2 resolution; switch (type) { case CollisionInternalType::BOX_BOX: { - const BoxCollider & collider1 - = std::get>(data1.collider); - const BoxCollider & collider2 - = std::get>(data2.collider); - - vec2 collider_pos1 - = AbsoluutPosition::get_position(data1.transform, collider1.offset); - vec2 collider_pos2 - = AbsoluutPosition::get_position(data2.transform, collider2.offset); - resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, - collider_pos2); + const BoxCollider & collider1 = std::get>(self.collider); + const BoxCollider & collider2 = std::get>(other.collider); + vec2 collider_pos1 = AbsolutePosition::get_position(self.info.transform, collider1.offset); + vec2 collider_pos2 = AbsolutePosition::get_position(other.info.transform, collider2.offset); + resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; } case CollisionInternalType::BOX_CIRCLE: { const BoxCollider & collider1 - = std::get>(data1.collider); + = std::get>(self.collider); const CircleCollider & collider2 - = std::get>(data2.collider); + = std::get>(other.collider); vec2 collider_pos1 - = AbsoluutPosition::get_position(data1.transform, collider1.offset); + = AbsolutePosition::get_position(self.info.transform, collider1.offset); vec2 collider_pos2 - = AbsoluutPosition::get_position(data2.transform, collider2.offset); + = AbsolutePosition::get_position(other.info.transform, collider2.offset); resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2, collider_pos1); break; } case CollisionInternalType::CIRCLE_CIRCLE: { const CircleCollider & collider1 - = std::get>(data1.collider); + = std::get>(self.collider); const CircleCollider & collider2 - = std::get>(data2.collider); + = std::get>(other.collider); vec2 collider_pos1 - = AbsoluutPosition::get_position(data1.transform, collider1.offset); + = AbsolutePosition::get_position(self.info.transform, collider1.offset); vec2 collider_pos2 - = AbsoluutPosition::get_position(data2.transform, collider2.offset); + = AbsolutePosition::get_position(other.info.transform, collider2.offset); resolution = this->get_circle_circle_resolution(collider1, collider2, collider_pos1, collider_pos2); break; } case CollisionInternalType::CIRCLE_BOX: { const CircleCollider & collider1 - = std::get>(data1.collider); + = std::get>(self.collider); const BoxCollider & collider2 - = std::get>(data2.collider); + = std::get>(other.collider); vec2 collider_pos1 - = AbsoluutPosition::get_position(data1.transform, collider1.offset); + = AbsolutePosition::get_position(self.info.transform, collider1.offset); vec2 collider_pos2 - = AbsoluutPosition::get_position(data2.transform, collider2.offset); + = AbsolutePosition::get_position(other.info.transform, collider2.offset); resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, collider_pos2); break; } + case CollisionInternalType::NONE: + break; } + // Calculate the other value to move back correctly + // If only X or Y has a value determine what is should be to move back. + const Rigidbody::Data & rigidbody = self.info.rigidbody.data; Direction resolution_direction = Direction::NONE; + // If both are not zero a perfect corner has been hit if (resolution.x != 0 && resolution.y != 0) { resolution_direction = Direction::BOTH; + // If x is not zero a horizontal action was latest action. } else if (resolution.x != 0) { resolution_direction = Direction::X_DIRECTION; - //checks if the other velocity has a value and if this object moved - if (data1.rigidbody.data.linear_velocity.x != 0 - && data1.rigidbody.data.linear_velocity.y != 0) - resolution.y = -data1.rigidbody.data.linear_velocity.y - * (resolution.x / data1.rigidbody.data.linear_velocity.x); + // If both are 0 resolution y should not be changed (y_velocity can be 0 by kinematic object movement) + if (rigidbody.linear_velocity.x != 0 && rigidbody.linear_velocity.y != 0) + resolution.y = -rigidbody.linear_velocity.y * (resolution.x / rigidbody.linear_velocity.x); } else if (resolution.y != 0) { resolution_direction = Direction::Y_DIRECTION; - //checks if the other velocity has a value and if this object moved - if (data1.rigidbody.data.linear_velocity.x != 0 - && data1.rigidbody.data.linear_velocity.y != 0) - resolution.x = -data1.rigidbody.data.linear_velocity.x - * (resolution.y / data1.rigidbody.data.linear_velocity.y); + // If both are 0 resolution x should not be changed (x_velocity can be 0 by kinematic object movement) + if (rigidbody.linear_velocity.x != 0 && rigidbody.linear_velocity.y != 0) + resolution.x = -rigidbody.linear_velocity.x * (resolution.y / rigidbody.linear_velocity.y); } return std::make_pair(resolution, resolution_direction); @@ -218,6 +368,9 @@ vec2 CollisionSystem::get_box_box_resolution(const BoxCollider & box_collider1, vec2 resolution; // Default resolution vector vec2 delta = final_position2 - final_position1; + vec2 scaled_box1 = box_collider1.dimensions * transform1.scale; + vec2 scaled_box2 = box_collider2.dimensions * transform2.scale; + // Compute half-dimensions of the boxes float half_width1 = box_collider1.dimensions.x / 2.0; float half_height1 = box_collider1.dimensions.y / 2.0; @@ -303,112 +456,114 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co return resolution; } -void CollisionSystem::determine_collision_handler(CollisionInfo & info) { - // Inverted collision info - CollisionInfo inverted = { - .this_collider = info.other_collider, - .this_transform = info.other_transform, - .this_rigidbody = info.other_rigidbody, - .this_metadata = info.other_metadata, - .other_collider = info.this_collider, - .other_transform = info.this_transform, - .other_rigidbody = info.this_rigidbody, - .other_metadata = info.this_metadata, - .resolution = -info.resolution, - .resolution_direction = info.resolution_direction, +CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const CollisionInternal & in_self, const CollisionInternal & in_other,const CollisionInternalType & type,const vec2 & resolution,const CollisionSystem::Direction & resolution_direction) const{ + + ComponentManager & mgr = this->mediator.component_manager; + + crepe::CollisionSystem::ColliderInfo self { + .transform = in_self.info.transform, + .rigidbody = in_self.info.rigidbody, + .metadata = in_self.info.metadata, + }; + + crepe::CollisionSystem::ColliderInfo other { + .transform = in_other.info.transform, + .rigidbody = in_other.info.rigidbody, + .metadata = in_other.info.metadata, }; + + struct CollisionInfo collision_info{ + .self = self, + .other = other, + .resolution = resolution, + .resolution_direction = resolution_direction, + }; + return collision_info; +} + +// Below is for collision handling +void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { + Rigidbody::BodyType self_type = info.self.rigidbody.data.body_type; + Rigidbody::BodyType other_type = info.self.rigidbody.data.body_type; + bool self_kinematic = info.self.rigidbody.data.kinematic_collision; + bool other_kinematic = info.self.rigidbody.data.kinematic_collision; + // Inverted collision info + CollisionInfo inverted = -info; // If both objects are static skip handle call collision script - if (info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC - && info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) + if (self_type == STATIC + && other_type == STATIC) return; // First body is not dynamic - if (info.this_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) { - bool static_collision - = info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC - && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC; - bool kinematic_collision - = info.this_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC - && info.other_rigidbody.data.body_type == Rigidbody::BodyType::DYNAMIC - && info.this_rigidbody.data.kinematic_collision; - - if (static_collision || kinematic_collision) { - // Static collision - this->static_collision_handler(inverted); - }; + if (self_type != DYNAMIC) { + bool static_collision = self_type == STATIC && other_type == DYNAMIC; + bool kinematic_collision = self_type == KINEMATIC && other_type == DYNAMIC && self_kinematic; + + // Handle collision + if (static_collision || kinematic_collision) this->static_collision_handler(inverted); // Call scripts this->call_collision_events(inverted, info); return; } // Second body is not dynamic - if (info.other_rigidbody.data.body_type != Rigidbody::BodyType::DYNAMIC) { - bool static_collision - = info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC; - bool kinematic_collision - = info.other_rigidbody.data.body_type == Rigidbody::BodyType::KINEMATIC - && info.other_rigidbody.data.kinematic_collision; + if (other_type != DYNAMIC) { + bool static_collision = other_type == STATIC; + bool kinematic_collision = other_type == KINEMATIC && other_kinematic; + // Handle collision if (static_collision || kinematic_collision) this->static_collision_handler(info); + // Call scripts this->call_collision_events(info, inverted); return; } - //dynamic + // Dynamic + // Handle collision this->dynamic_collision_handler(info); + // Call scripts this->call_collision_events(info, inverted); } -void CollisionSystem::call_collision_events(CollisionInfo & info, - CollisionInfo & info_inverted) { - CollisionEvent data(info); - CollisionEvent data_inverted(info_inverted); - EventManager & emgr = this->mediator.event_manager; - emgr.trigger_event(data, info.this_collider.game_object_id); - emgr.trigger_event(data_inverted, - info_inverted.this_collider.game_object_id); -} - -void CollisionSystem::static_collision_handler(CollisionInfo & info) { +void CollisionSystem::static_collision_handler(const CollisionInfo & info) { + + vec2 & transform_pos = info.self.transform.position; + float elastisity = info.self.rigidbody.data.elastisity_coefficient; + vec2 & rigidbody_vel = info.self.rigidbody.data.linear_velocity; + // Move object back using calculate move back value - info.this_transform.position += info.resolution; + transform_pos += info.resolution; switch (info.resolution_direction) { case Direction::BOTH: //bounce - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity - = -info.this_rigidbody.data.linear_velocity - * info.this_rigidbody.data.elastisity_coefficient; + if (elastisity > 0) { + rigidbody_vel = -rigidbody_vel * elastisity; } //stop movement else { - info.this_rigidbody.data.linear_velocity = {0, 0}; + rigidbody_vel = {0, 0}; } break; case Direction::Y_DIRECTION: // Bounce - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity.y - = -info.this_rigidbody.data.linear_velocity.y - * info.this_rigidbody.data.elastisity_coefficient; + if (elastisity > 0) { + rigidbody_vel.y = -rigidbody_vel.y * elastisity; } // Stop movement else { - info.this_rigidbody.data.linear_velocity.y = 0; - info.this_transform.position.x -= info.resolution.x; + rigidbody_vel.y = 0; + transform_pos.x -= info.resolution.x; } break; case Direction::X_DIRECTION: // Bounce - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity.x - = -info.this_rigidbody.data.linear_velocity.x - * info.this_rigidbody.data.elastisity_coefficient; + if (elastisity > 0) { + rigidbody_vel.x = -rigidbody_vel.x * elastisity; } // Stop movement else { - info.this_rigidbody.data.linear_velocity.x = 0; - info.this_transform.position.y -= info.resolution.y; + rigidbody_vel.x = 0; + transform_pos.y -= info.resolution.y; } break; case Direction::NONE: @@ -417,72 +572,68 @@ void CollisionSystem::static_collision_handler(CollisionInfo & info) { } } -void CollisionSystem::dynamic_collision_handler(CollisionInfo & info) { - info.this_transform.position += info.resolution / 2; - info.other_transform.position += -(info.resolution / 2); +void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { + + vec2 & self_transform_pos = info.self.transform.position; + vec2 & other_transform_pos = info.other.transform.position; + float self_elastisity = info.self.rigidbody.data.elastisity_coefficient; + float other_elastisity = info.other.rigidbody.data.elastisity_coefficient; + vec2 & self_rigidbody_vel = info.self.rigidbody.data.linear_velocity; + vec2 & other_rigidbody_vel = info.other.rigidbody.data.linear_velocity; + + self_transform_pos += info.resolution / 2; + other_transform_pos += -(info.resolution / 2); switch (info.resolution_direction) { case Direction::BOTH: - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity - = -info.this_rigidbody.data.linear_velocity - * info.this_rigidbody.data.elastisity_coefficient; + if (self_elastisity > 0) { + self_rigidbody_vel = -self_rigidbody_vel * self_elastisity; } else { - info.this_rigidbody.data.linear_velocity = {0, 0}; + self_rigidbody_vel = {0, 0}; } - if (info.other_rigidbody.data.elastisity_coefficient > 0) { - info.other_rigidbody.data.linear_velocity - = -info.other_rigidbody.data.linear_velocity - * info.other_rigidbody.data.elastisity_coefficient; + if (other_elastisity > 0) { + other_rigidbody_vel = -other_rigidbody_vel * other_elastisity; } else { - info.other_rigidbody.data.linear_velocity = {0, 0}; + other_rigidbody_vel = {0, 0}; } break; case Direction::Y_DIRECTION: - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity.y - = -info.this_rigidbody.data.linear_velocity.y - * info.this_rigidbody.data.elastisity_coefficient; + if (self_elastisity > 0) { + self_rigidbody_vel.y = -self_rigidbody_vel.y * self_elastisity; } // Stop movement else { - info.this_rigidbody.data.linear_velocity.y = 0; - info.this_transform.position.x -= info.resolution.x; + self_rigidbody_vel.y = 0; + self_transform_pos.x -= info.resolution.x; } - if (info.other_rigidbody.data.elastisity_coefficient > 0) { - info.other_rigidbody.data.linear_velocity.y - = -info.other_rigidbody.data.linear_velocity.y - * info.other_rigidbody.data.elastisity_coefficient; + if (other_elastisity > 0) { + other_rigidbody_vel.y = -other_rigidbody_vel.y * other_elastisity; } // Stop movement else { - info.other_rigidbody.data.linear_velocity.y = 0; - info.other_transform.position.x -= info.resolution.x; + other_rigidbody_vel.y = 0; + other_transform_pos.x -= info.resolution.x; } break; case Direction::X_DIRECTION: - if (info.this_rigidbody.data.elastisity_coefficient > 0) { - info.this_rigidbody.data.linear_velocity.x - = -info.this_rigidbody.data.linear_velocity.x - * info.this_rigidbody.data.elastisity_coefficient; + if (self_elastisity > 0) { + self_rigidbody_vel.x = -self_rigidbody_vel.x * self_elastisity; } // Stop movement else { - info.this_rigidbody.data.linear_velocity.x = 0; - info.this_transform.position.y -= info.resolution.y; + self_rigidbody_vel.x = 0; + self_transform_pos.y -= info.resolution.y; } - if (info.other_rigidbody.data.elastisity_coefficient > 0) { - info.other_rigidbody.data.linear_velocity.x - = -info.other_rigidbody.data.linear_velocity.x - * info.other_rigidbody.data.elastisity_coefficient; + if (other_elastisity > 0) { + other_rigidbody_vel.x = -other_rigidbody_vel.x * other_elastisity; } // Stop movement else { - info.other_rigidbody.data.linear_velocity.x = 0; - info.other_transform.position.y -= info.resolution.y; + other_rigidbody_vel.x = 0; + other_transform_pos.y -= info.resolution.y; } break; case Direction::NONE: @@ -491,206 +642,16 @@ void CollisionSystem::dynamic_collision_handler(CollisionInfo & info) { } } -std::vector> -CollisionSystem::gather_collisions(std::vector & colliders) { - - // TODO: - // If no colliders skip - // Check if colliders has rigidbody if not skip - - // TODO: - // If amount is higer than lets say 16 for now use quadtree otwerwise skip - // Quadtree code - // Quadtree is placed over the input vector - - // Return data of collided colliders which are variants - std::vector> collisions_ret; - //using visit to visit the variant to access the active and id. - for (size_t i = 0; i < colliders.size(); ++i) { - for (size_t j = i + 1; j < colliders.size(); ++j) { - if (colliders[i].id == colliders[j].id) continue; - if (!have_common_layer(colliders[i].rigidbody.data.collision_layers, - colliders[j].rigidbody.data.collision_layers)) - continue; - CollisionInternalType type - = get_collider_type(colliders[i].collider, colliders[j].collider); - if (!get_collision( - { - .collider = colliders[i].collider, - .transform = colliders[i].transform, - .rigidbody = colliders[i].rigidbody, - }, - { - .collider = colliders[j].collider, - .transform = colliders[j].transform, - .rigidbody = colliders[j].rigidbody, - }, - type)) - continue; - collisions_ret.emplace_back(colliders[i], colliders[j]); - } - } - - return collisions_ret; -} - -bool CollisionSystem::have_common_layer(const std::set & layers1, - const std::set & layers2) { - - // Check if any number is equal in the layers - for (int num : layers1) { - if (layers2.contains(num)) { - // Common layer found - return true; - break; - } - } - // No common layer found - return false; -} - -CollisionSystem::CollisionInternalType -CollisionSystem::get_collider_type(const collider_variant & collider1, - const collider_variant & collider2) const { - if (std::holds_alternative>(collider1)) { - if (std::holds_alternative>(collider2)) { - return CollisionInternalType::CIRCLE_CIRCLE; - } else { - return CollisionInternalType::CIRCLE_BOX; - } - } else { - if (std::holds_alternative>(collider2)) { - return CollisionInternalType::BOX_CIRCLE; - } else { - return CollisionInternalType::BOX_BOX; - } - } -} - -bool CollisionSystem::get_collision(const CollisionInternal & first_info, - const CollisionInternal & second_info, - CollisionInternalType type) const { - switch (type) { - case CollisionInternalType::BOX_BOX: { - const BoxCollider & box_collider1 - = std::get>(first_info.collider); - const BoxCollider & box_collider2 - = std::get>(second_info.collider); - return this->get_box_box_collision(box_collider1, box_collider2, - first_info.transform, second_info.transform, - second_info.rigidbody, second_info.rigidbody); - } - case CollisionInternalType::BOX_CIRCLE: { - const BoxCollider & box_collider - = std::get>(first_info.collider); - const CircleCollider & circle_collider - = std::get>(second_info.collider); - return this->get_box_circle_collision( - box_collider, circle_collider, first_info.transform, second_info.transform, - second_info.rigidbody, second_info.rigidbody); - } - case CollisionInternalType::CIRCLE_CIRCLE: { - const CircleCollider & circle_collider1 - = std::get>(first_info.collider); - const CircleCollider & circle_collider2 - = std::get>(second_info.collider); - return this->get_circle_circle_collision( - circle_collider1, circle_collider2, first_info.transform, - second_info.transform, second_info.rigidbody, second_info.rigidbody); - } - case CollisionInternalType::CIRCLE_BOX: { - const CircleCollider & circle_collider - = std::get>(first_info.collider); - const BoxCollider & box_collider - = std::get>(second_info.collider); - return this->get_box_circle_collision( - box_collider, circle_collider, first_info.transform, second_info.transform, - second_info.rigidbody, second_info.rigidbody); - } - } - return false; -} - -bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { - // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1, box1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2, box2.offset); - - // Scale dimensions - vec2 scaled_box1 = box1.dimensions * transform1.scale; - vec2 scaled_box2 = box2.dimensions * transform2.scale; - - // Calculate half-extents (half width and half height) - float half_width1 = scaled_box1.x / 2.0; - float half_height1 = scaled_box1.y / 2.0; - float half_width2 = scaled_box2.x / 2.0; - float half_height2 = scaled_box2.y / 2.0; - - // Check if the boxes overlap along the X and Y axes - return (final_position1.x + half_width1 > final_position2.x - half_width2 - && final_position1.x - half_width1 < final_position2.x + half_width2 - && final_position1.y + half_height1 > final_position2.y - half_height2 - && final_position1.y - half_height1 < final_position2.y + half_height2); -} - -bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, - const CircleCollider & circle2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { - // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1, box1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2, circle2.offset); - - // Scale dimensions - vec2 scaled_box = box1.dimensions * transform1.scale; - float scaled_circle = circle2.radius * transform2.scale; - - // Calculate box half-extents - float half_width = scaled_box.x / 2.0; - float half_height = scaled_box.y / 2.0; - - // Find the closest point on the box to the circle's center - float closest_x = std::max(final_position1.x - half_width, - std::min(final_position2.x, final_position1.x + half_width)); - float closest_y = std::max(final_position1.y - half_height, - std::min(final_position2.y, final_position1.y + half_height)); - - // Calculate the distance squared between the circle's center and the closest point on the box - float distance_x = final_position2.x - closest_x; - float distance_y = final_position2.y - closest_y; - float distance_squared = distance_x * distance_x + distance_y * distance_y; - - // Compare distance squared with the square of the circle's radius - return distance_squared < scaled_circle * scaled_circle; +void CollisionSystem::call_collision_events(const CollisionInfo & info, + const CollisionInfo & info_inverted) { + CollisionEvent data(info); + CollisionEvent data_inverted(info_inverted); + EventManager & emgr = this->mediator.event_manager; + emgr.trigger_event(data, info.self.transform.game_object_id); + emgr.trigger_event(data_inverted, + info_inverted.self.transform.game_object_id); } -bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1, - const CircleCollider & circle2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { - // Get current positions of colliders - vec2 final_position1 = AbsoluutPosition::get_position(transform1, circle1.offset); - vec2 final_position2 = AbsoluutPosition::get_position(transform2, circle2.offset); - // Scale dimensions - float scaled_circle1 = circle1.radius * transform1.scale; - float scaled_circle2 = circle2.radius * transform2.scale; - float distance_x = final_position1.x - final_position2.x; - float distance_y = final_position1.y - final_position2.y; - float distance_squared = distance_x * distance_x + distance_y * distance_y; - // Calculate the sum of the radii - float radius_sum = scaled_circle1 + scaled_circle2; - - // Check if the distance between the centers is less than or equal to the sum of the radii - return distance_squared < radius_sum * radius_sum; -} diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 23752e1..01c189e 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -21,6 +21,40 @@ namespace crepe { class CollisionSystem : public System { public: using System::System; +private: + //! Enum representing movement directions during collision resolution. + enum class Direction { + //! No movement required. + NONE, + //! Movement in the X direction. + X_DIRECTION, + //! Movement in the Y direction. + Y_DIRECTION, + //! Movement in both X and Y directions. + BOTH + }; +public: + /** + * \brief Structure representing detailed collision information between two colliders. + * + * Includes information about the colliding objects and the resolution data for handling the collision. + */ + + struct ColliderInfo { + Transform & transform; + Rigidbody & rigidbody; + Metadata & metadata; + }; + + struct CollisionInfo { + ColliderInfo self; + ColliderInfo other; + //! The resolution vector for the collision. + vec2 resolution; + //! The direction of movement for resolving the collision. + Direction resolution_direction = Direction::NONE; + CollisionInfo operator - () const; + }; private: //! A variant type that can hold either a BoxCollider or a CircleCollider. @@ -33,6 +67,7 @@ private: CIRCLE_CIRCLE, BOX_CIRCLE, CIRCLE_BOX, + NONE, }; /** @@ -46,41 +81,7 @@ private: struct CollisionInternal { game_object_id_t id = 0; collider_variant collider; - Transform & transform; - Rigidbody & rigidbody; - }; - - //! Enum representing movement directions during collision resolution. - enum class Direction { - //! No movement required. - NONE, - //! Movement in the X direction. - X_DIRECTION, - //! Movement in the Y direction. - Y_DIRECTION, - //! Movement in both X and Y directions. - BOTH - }; - -public: - /** - * \brief Structure representing detailed collision information between two colliders. - * - * Includes information about the colliding objects and the resolution data for handling the collision. - */ - struct CollisionInfo { - Collider & this_collider; - Transform & this_transform; - Rigidbody & this_rigidbody; - Metadata & this_metadata; - Collider & other_collider; - Transform & other_transform; - Rigidbody & other_rigidbody; - Metadata & other_metadata; - //! The resolution vector for the collision. - vec2 resolution; - //! The direction of movement for resolving the collision. - Direction resolution_direction = Direction::NONE; + ColliderInfo info; }; public: @@ -97,8 +98,7 @@ private: * \param collider2 Second collider variant (BoxCollider or CircleCollider). * \return The combined type of the two colliders. */ - CollisionInternalType get_collider_type(const collider_variant & collider1, - const collider_variant & collider2) const; + CollisionInternalType get_collider_type(const collider_variant & collider1, const collider_variant & collider2) const; private: /** @@ -109,7 +109,7 @@ private: * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. */ - void collision_handler_request(CollisionInternal & data1, CollisionInternal & data2); + CollisionInfo get_collision_info(const CollisionInternal & this_data, const CollisionInternal & other_data,const CollisionInternalType & type,const vec2 & resolution,const CollisionSystem::Direction & resolution_direction) const; //done /** * \brief Resolves collision between two colliders and calculates the movement required. @@ -121,9 +121,7 @@ private: * \param type The type of collider pair. * \return A pair containing the resolution vector and direction for the first collider. */ - std::pair collision_handler(CollisionInternal & data1, - CollisionInternal & data2, - CollisionInternalType type); + std::pair get_collision_resolution(const CollisionInternal & data1,const CollisionInternal & data2, const CollisionInternalType & type) const; //done /** * \brief Calculates the resolution vector for two BoxColliders. @@ -179,7 +177,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void determine_collision_handler(CollisionInfo & info); + void determine_collision_handler(const CollisionInfo & info); //done /** * \brief Calls both collision script @@ -188,7 +186,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void call_collision_events(CollisionInfo & info, CollisionInfo & info_inverted); + void call_collision_events(const CollisionInfo & info, const CollisionInfo & info_inverted); /** * \brief Handles collisions involving static objects. @@ -197,7 +195,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void static_collision_handler(CollisionInfo & info); + void static_collision_handler(const CollisionInfo & info); //done /** * \brief Handles collisions involving dynamic objects. @@ -206,7 +204,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void dynamic_collision_handler(CollisionInfo & info); + void dynamic_collision_handler(const CollisionInfo & info); //done private: /** @@ -218,23 +216,22 @@ private: * \return A list of collision pairs with their associated data. */ std::vector> - gather_collisions(std::vector & colliders); + gather_collisions(const std::vector & colliders) const; //done /** - * \brief Checks if two collision layers have at least one common layer. + * \brief Checks if the settings allow collision * - * This function checks if there is any overlapping layer between the two inputs. - * It compares each layer from the first input to see - * if it exists in the second input. If at least one common layer is found, - * the function returns true, indicating that the two colliders share a common - * collision layer. + * This function checks if there is any collison layer where each object is located in. + * After checking the layers it checks the names and at last the tags. + * if in all three sets nothing is found collision can not happen. * - * \param layers1 all collision layers for the first collider. - * \param layers2 all collision layers for the second collider. - * \return Returns true if there is at least one common layer, false otherwise. + * \param this_rigidbody Rigidbody of first object + * \param other_rigidbody Rigidbody of second collider + * \param this_metadata Rigidbody of first object + * \param other_metadata Rigidbody of second object + * \return Returns true if there is at least one comparision found. */ - - bool have_common_layer(const std::set & layers1, const std::set & layers2); + bool should_collide(const CollisionInternal & self, const CollisionInternal & other) const; //done /** * \brief Checks for collision between two colliders. @@ -246,9 +243,7 @@ private: * \param type The type of collider pair. * \return True if a collision is detected, otherwise false. */ - bool get_collision(const CollisionInternal & first_info, - const CollisionInternal & second_info, - CollisionInternalType type) const; + bool get_collision(const CollisionInternal & first_info, const CollisionInternal & second_info, const CollisionInternalType & type) const; /** * \brief Detects collisions between two BoxColliders. diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp index 56f1dfd..3183fd7 100644 --- a/src/crepe/system/ParticleSystem.cpp +++ b/src/crepe/system/ParticleSystem.cpp @@ -7,7 +7,7 @@ #include "../api/Transform.h" #include "../manager/ComponentManager.h" #include "../manager/LoopTimerManager.h" -#include "util/AbsoluutPosition.h" +#include "util/AbsolutePosition.h" #include "ParticleSystem.h" @@ -49,7 +49,7 @@ void ParticleSystem::update() { void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) { constexpr float DEG_TO_RAD = M_PI / 180.0; - vec2 initial_position = AbsoluutPosition::get_position(transform, emitter.data.offset); + vec2 initial_position = AbsolutePosition::get_position(transform, emitter.data.offset); float random_angle = this->generate_random_angle(emitter.data.min_angle, emitter.data.max_angle); diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index c0717fc..7c48d10 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -13,7 +13,7 @@ #include "../facade/Texture.h" #include "../manager/ComponentManager.h" #include "../manager/ResourceManager.h" -#include "util/AbsoluutPosition.h" +#include "util/AbsolutePosition.h" #include "RenderSystem.h" #include "types.h" @@ -106,7 +106,7 @@ void RenderSystem::render_normal(const Sprite & sprite, const Transform & tm) { SDLContext & ctx = this->mediator.sdl_context; ResourceManager & resource_manager = this->mediator.resource_manager; const Texture & res = resource_manager.get(sprite.source); - vec2 pos = AbsoluutPosition::get_position(tm, sprite.data.position_offset); + vec2 pos = AbsolutePosition::get_position(tm, sprite.data.position_offset); ctx.draw(SDLContext::RenderContext{ .sprite = sprite, .texture = res, diff --git a/src/crepe/util/AbsolutePosition.cpp b/src/crepe/util/AbsolutePosition.cpp new file mode 100644 index 0000000..29ade23 --- /dev/null +++ b/src/crepe/util/AbsolutePosition.cpp @@ -0,0 +1,20 @@ +#include "AbsolutePosition.h" + +using namespace crepe; + +vec2 AbsolutePosition::get_position(const Transform & transform, const vec2 & offset) { + // Get the rotation in radians + float radians1 = transform.rotation * (M_PI / 180.0); + + // Calculate total offset with scale + vec2 total_offset = offset * transform.scale; + + // Rotate + float rotated_total_offset_x1 + = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); + float rotated_total_offset_y1 + = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); + + // Final positions considering scaling and rotation + return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); +} diff --git a/src/crepe/util/AbsolutePosition.h b/src/crepe/util/AbsolutePosition.h new file mode 100644 index 0000000..0bc8748 --- /dev/null +++ b/src/crepe/util/AbsolutePosition.h @@ -0,0 +1,14 @@ +#pragma once + +#include "api/Transform.h" + +#include "types.h" + +namespace crepe { + +class AbsolutePosition { +public: + static vec2 get_position(const Transform & transform, const vec2 & offset); +}; + +} // namespace crepe diff --git a/src/crepe/util/AbsoluutPosition.cpp b/src/crepe/util/AbsoluutPosition.cpp deleted file mode 100644 index 296cc09..0000000 --- a/src/crepe/util/AbsoluutPosition.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "AbsoluutPosition.h" - -using namespace crepe; - -vec2 AbsoluutPosition::get_position(const Transform & transform, const vec2 & offset) { - // Get the rotation in radians - float radians1 = transform.rotation * (M_PI / 180.0); - - // Calculate total offset with scale - vec2 total_offset = offset * transform.scale; - - // Rotate - float rotated_total_offset_x1 - = total_offset.x * cos(radians1) - total_offset.y * sin(radians1); - float rotated_total_offset_y1 - = total_offset.x * sin(radians1) + total_offset.y * cos(radians1); - - // Final positions considering scaling and rotation - return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); -} diff --git a/src/crepe/util/AbsoluutPosition.h b/src/crepe/util/AbsoluutPosition.h deleted file mode 100644 index 30a7f93..0000000 --- a/src/crepe/util/AbsoluutPosition.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "api/Transform.h" - -#include "types.h" - -namespace crepe { - -class AbsoluutPosition { -public: - static vec2 get_position(const Transform & transform, const vec2 & offset); -}; - -} // namespace crepe diff --git a/src/crepe/util/CMakeLists.txt b/src/crepe/util/CMakeLists.txt index b4b9221..33160a7 100644 --- a/src/crepe/util/CMakeLists.txt +++ b/src/crepe/util/CMakeLists.txt @@ -1,7 +1,7 @@ target_sources(crepe PUBLIC LogColor.cpp Log.cpp - AbsoluutPosition.cpp + AbsolutePosition.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -12,6 +12,6 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES Proxy.hpp OptionalRef.h OptionalRef.hpp - AbsoluutPosition.h + AbsolutePosition.h ) diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 11b4ca9..61254f1 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -1,27 +1,27 @@ target_sources(test_main PUBLIC main.cpp CollisionTest.cpp - PhysicsTest.cpp - ScriptTest.cpp - ParticleTest.cpp - AudioTest.cpp - AssetTest.cpp - ResourceManagerTest.cpp - OptionalRefTest.cpp - RenderSystemTest.cpp - EventTest.cpp - ECSTest.cpp - SceneManagerTest.cpp - ValueBrokerTest.cpp - DBTest.cpp - Vector2Test.cpp - LoopManagerTest.cpp - LoopTimerTest.cpp - InputTest.cpp - ScriptEventTest.cpp - ScriptSceneTest.cpp - Profiling.cpp - SaveManagerTest.cpp - ScriptSaveManagerTest.cpp - ScriptECSTest.cpp + # PhysicsTest.cpp + # ScriptTest.cpp + # ParticleTest.cpp + # AudioTest.cpp + # AssetTest.cpp + # ResourceManagerTest.cpp + # OptionalRefTest.cpp + # RenderSystemTest.cpp + # EventTest.cpp + # ECSTest.cpp + # SceneManagerTest.cpp + # ValueBrokerTest.cpp + # DBTest.cpp + # Vector2Test.cpp + # LoopManagerTest.cpp + # LoopTimerTest.cpp + # InputTest.cpp + # ScriptEventTest.cpp + # ScriptSceneTest.cpp + # Profiling.cpp + # SaveManagerTest.cpp + # ScriptSaveManagerTest.cpp + # ScriptECSTest.cpp ) diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index 50e862d..a86f7d3 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -25,6 +25,7 @@ using namespace std::chrono_literals; using namespace crepe; using namespace testing; + class CollisionHandler : public Script { public: int box_id; @@ -112,11 +113,11 @@ TEST_F(CollisionTest, collision_example) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); }; EXPECT_FALSE(collision_happend); collision_sys.update(); @@ -127,14 +128,14 @@ TEST_F(CollisionTest, collision_box_box_dynamic_both_no_velocity) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 10); EXPECT_EQ(ev.info.resolution.y, 10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, -10); EXPECT_EQ(ev.info.resolution.y, -10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); @@ -150,7 +151,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_x_direction_no_velocity) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, -5); EXPECT_EQ(ev.info.resolution.y, 0); EXPECT_EQ(ev.info.resolution_direction, @@ -158,7 +159,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_x_direction_no_velocity) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, 5); EXPECT_EQ(ev.info.resolution.y, 0); EXPECT_EQ(ev.info.resolution_direction, @@ -175,7 +176,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_y_direction_no_velocity) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 0); EXPECT_EQ(ev.info.resolution.y, -5); EXPECT_EQ(ev.info.resolution_direction, @@ -183,7 +184,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_y_direction_no_velocity) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, 0); EXPECT_EQ(ev.info.resolution.y, 5); EXPECT_EQ(ev.info.resolution_direction, @@ -200,14 +201,14 @@ TEST_F(CollisionTest, collision_box_box_dynamic_both) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 10); EXPECT_EQ(ev.info.resolution.y, 10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, -10); EXPECT_EQ(ev.info.resolution.y, -10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); @@ -227,7 +228,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_x_direction) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, -5); EXPECT_EQ(ev.info.resolution.y, 5); EXPECT_EQ(ev.info.resolution_direction, @@ -235,7 +236,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_x_direction) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, 5); EXPECT_EQ(ev.info.resolution.y, -5); EXPECT_EQ(ev.info.resolution_direction, @@ -256,7 +257,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_y_direction) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 5); EXPECT_EQ(ev.info.resolution.y, -5); EXPECT_EQ(ev.info.resolution_direction, @@ -264,7 +265,7 @@ TEST_F(CollisionTest, collision_box_box_dynamic_y_direction) { }; script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 2); + EXPECT_EQ(ev.info.self.transform.game_object_id, 2); EXPECT_EQ(ev.info.resolution.x, -5); EXPECT_EQ(ev.info.resolution.y, 5); EXPECT_EQ(ev.info.resolution_direction, @@ -285,7 +286,7 @@ TEST_F(CollisionTest, collision_box_box_static_both) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 10); EXPECT_EQ(ev.info.resolution.y, 10); EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH); @@ -305,7 +306,7 @@ TEST_F(CollisionTest, collision_box_box_static_x_direction) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, -5); EXPECT_EQ(ev.info.resolution.y, 5); EXPECT_EQ(ev.info.resolution_direction, @@ -330,7 +331,7 @@ TEST_F(CollisionTest, collision_box_box_static_y_direction) { bool collision_happend = false; script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) { collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); + EXPECT_EQ(ev.info.self.transform.game_object_id, 1); EXPECT_EQ(ev.info.resolution.x, 5); EXPECT_EQ(ev.info.resolution.y, -5); EXPECT_EQ(ev.info.resolution_direction, @@ -350,37 +351,3 @@ TEST_F(CollisionTest, collision_box_box_static_y_direction) { collision_sys.update(); EXPECT_TRUE(collision_happend); } - -TEST_F(CollisionTest, collision_box_box_static_multiple) { //todo check visually - bool collision_happend = false; - float offset_value = 0; - float resolution = 0; - script_object1_ref->test_fn = [&](const CollisionEvent & ev) { - collision_happend = true; - EXPECT_EQ(ev.info.this_collider.game_object_id, 1); - EXPECT_EQ(ev.info.this_collider.offset.x, offset_value); - EXPECT_EQ(ev.info.resolution.x, resolution); - }; - script_object2_ref->test_fn = [&](const CollisionEvent & ev) { - // is static should not be called - //FAIL(); - }; - EXPECT_FALSE(collision_happend); - Transform & tf = this->mgr.get_components_by_id(1).front().get(); - tf.position = {45, 30}; - Rigidbody & rg1 = this->mgr.get_components_by_id(1).front().get(); - rg1.data.linear_velocity = {10, 10}; - Rigidbody & rg2 = this->mgr.get_components_by_id(2).front().get(); - rg2.data.body_type = crepe::Rigidbody::BodyType::STATIC; - BoxCollider & bxc = this->mgr.get_components_by_id(1).front().get(); - bxc.offset = {5, 0}; - this->game_object1.add_component(vec2{-5, 0}, vec2{10, 10}); - offset_value = 5; - resolution = 10; - collision_sys.update(); - offset_value = -5; - resolution = 10; - tf.position = {55, 30}; - collision_sys.update(); - EXPECT_TRUE(collision_happend); -} diff --git a/src/test/Profiling.cpp b/src/test/Profiling.cpp index 16736b8..0b2669f 100644 --- a/src/test/Profiling.cpp +++ b/src/test/Profiling.cpp @@ -32,7 +32,7 @@ using namespace testing; class TestScript : public Script { bool oncollision(const CollisionEvent & test) { - Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id); + Log::logf("Box {} script on_collision()", test.info.self.transform.game_object_id); return true; } void init() { -- cgit v1.2.3 From eb8c6c7a7202e560f896dcf25541b345109d8fa7 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Wed, 18 Dec 2024 22:11:49 +0100 Subject: before merging of resolution and handling --- src/crepe/system/CollisionSystem.cpp | 250 +++++++++++++++++++---------------- src/crepe/system/CollisionSystem.h | 45 +++---- 2 files changed, 155 insertions(+), 140 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 8bb8a91..e4f6cb3 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -107,6 +107,7 @@ CollisionSystem::gather_collisions(const std::vector & collid if (!should_collide(colliders[i], colliders[j])) continue; CollisionInternalType type = get_collider_type(colliders[i].collider, colliders[j].collider); if (!get_collision(colliders[i],colliders[j],type)) continue; + //fet collisions_ret.emplace_back(colliders[i], colliders[j]); } } @@ -156,41 +157,60 @@ CollisionSystem::get_collider_type(const collider_variant & collider1, } bool CollisionSystem::get_collision(const CollisionInternal & self,const CollisionInternal & other,const CollisionInternalType & type) const { - const Transform & self_transform = self.info.transform; - const Transform & other_transform = other.info.transform; - const Rigidbody & self_rigidbody = self.info.rigidbody; - const Rigidbody & other_rigidbody = other.info.rigidbody; - const collider_variant & self_collider = self.collider; - const collider_variant & other_collider = other.collider; switch (type) { case CollisionInternalType::BOX_BOX: { - const BoxCollider & box_collider1 = std::get>(self_collider); - const BoxCollider & box_collider2 = std::get>(other_collider); - return this->get_box_box_collision(box_collider1, box_collider2, - self_transform, other_transform, - self_rigidbody, other_rigidbody); + const BoxColliderInternal BOX1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const BoxColliderInternal BOX2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + + return this->get_box_box_collision(BOX1, BOX2); } case CollisionInternalType::BOX_CIRCLE: { - const BoxCollider & box_collider = std::get>(self_collider); - const CircleCollider & circle_collider = std::get>(other_collider); - return this->get_box_circle_collision(box_collider, circle_collider, - self_transform, other_transform, - self_rigidbody, other_rigidbody); + const BoxColliderInternal BOX1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const CircleColliderInternal CIRCLE2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + return this->get_box_circle_collision(BOX1, CIRCLE2); } case CollisionInternalType::CIRCLE_CIRCLE: { - const CircleCollider & circle_collider1 = std::get>(self_collider); - const CircleCollider & circle_collider2 = std::get>(other_collider); - return this->get_circle_circle_collision(circle_collider1, circle_collider2, - self_transform, other_transform, - self_rigidbody, other_rigidbody); + const CircleColliderInternal CIRCLE1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const CircleColliderInternal CIRCLE2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + return this->get_circle_circle_collision(CIRCLE1,CIRCLE2); } case CollisionInternalType::CIRCLE_BOX: { - const CircleCollider & circle_collider = std::get>(self_collider); - const BoxCollider & box_collider = std::get>(other_collider); - return this->get_box_circle_collision(box_collider, circle_collider, - other_transform, self_transform, - other_rigidbody, self_rigidbody); + const CircleColliderInternal CIRCLE1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const BoxColliderInternal BOX2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + return this->get_box_circle_collision(BOX2, CIRCLE1); } case CollisionInternalType::NONE: break; @@ -198,18 +218,14 @@ bool CollisionSystem::get_collision(const CollisionInternal & self,const Collisi return false; } -bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { +bool CollisionSystem::get_box_box_collision(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const { // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(transform1, box1.offset); - vec2 final_position2 = AbsolutePosition::get_position(transform2, box2.offset); + vec2 final_position1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); + vec2 final_position2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); // Scale dimensions - vec2 scaled_box1 = box1.dimensions * transform1.scale; - vec2 scaled_box2 = box2.dimensions * transform2.scale; + vec2 scaled_box1 = box1.collider.dimensions * box1.transform.scale; + vec2 scaled_box2 = box2.collider.dimensions * box2.transform.scale; // Calculate half-extents (half width and half height) float half_width1 = scaled_box1.x / 2.0; @@ -224,19 +240,14 @@ bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxC && final_position1.y - half_height1 < final_position2.y + half_height2); } -bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, - const CircleCollider & circle2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { +bool CollisionSystem::get_box_circle_collision(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const { // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(transform1, box1.offset); - vec2 final_position2 = AbsolutePosition::get_position(transform2, circle2.offset); + vec2 final_position1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); + vec2 final_position2 = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); // Scale dimensions - vec2 scaled_box = box1.dimensions * transform1.scale; - float scaled_circle = circle2.radius * transform2.scale; + vec2 scaled_box = box1.collider.dimensions * box1.transform.scale; + float scaled_circle = circle2.collider.radius * circle2.transform.scale; // Calculate box half-extents float half_width = scaled_box.x / 2.0; @@ -257,19 +268,14 @@ bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, return distance_squared < scaled_circle * scaled_circle; } -bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1, - const CircleCollider & circle2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const { +bool CollisionSystem::get_circle_circle_collision(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(transform1, circle1.offset); - vec2 final_position2 = AbsolutePosition::get_position(transform2, circle2.offset); + vec2 final_position1 = AbsolutePosition::get_position(circle1.transform, circle1.collider.offset); + vec2 final_position2 = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); // Scale dimensions - float scaled_circle1 = circle1.radius * transform1.scale; - float scaled_circle2 = circle2.radius * transform2.scale; + float scaled_circle1 = circle1.collider.radius * circle1.transform.scale; + float scaled_circle2 = circle2.collider.radius * circle2.transform.scale; float distance_x = final_position1.x - final_position2.x; float distance_y = final_position1.y - final_position2.y; @@ -286,52 +292,69 @@ std::pair CollisionSystem::get_collision_resolution(const CollisionInternal & self, const CollisionInternal & other, const CollisionInternalType & type) const { vec2 resolution; + // Fet resolution form correct type switch (type) { case CollisionInternalType::BOX_BOX: { - const BoxCollider & collider1 = std::get>(self.collider); - const BoxCollider & collider2 = std::get>(other.collider); - vec2 collider_pos1 = AbsolutePosition::get_position(self.info.transform, collider1.offset); - vec2 collider_pos2 = AbsolutePosition::get_position(other.info.transform, collider2.offset); - resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1, collider_pos2); + + const BoxColliderInternal BOX1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const BoxColliderInternal BOX2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + resolution = this->get_box_box_resolution(BOX1, BOX2); break; } case CollisionInternalType::BOX_CIRCLE: { - const BoxCollider & collider1 - = std::get>(self.collider); - const CircleCollider & collider2 - = std::get>(other.collider); - vec2 collider_pos1 - = AbsolutePosition::get_position(self.info.transform, collider1.offset); - vec2 collider_pos2 - = AbsolutePosition::get_position(other.info.transform, collider2.offset); - resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2, - collider_pos1); + + const BoxColliderInternal BOX1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const CircleColliderInternal CIRCLE1 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + resolution = -this->get_circle_box_resolution(CIRCLE1,BOX1); break; } case CollisionInternalType::CIRCLE_CIRCLE: { - const CircleCollider & collider1 - = std::get>(self.collider); - const CircleCollider & collider2 - = std::get>(other.collider); - vec2 collider_pos1 - = AbsolutePosition::get_position(self.info.transform, collider1.offset); - vec2 collider_pos2 - = AbsolutePosition::get_position(other.info.transform, collider2.offset); - resolution = this->get_circle_circle_resolution(collider1, collider2, - collider_pos1, collider_pos2); + const CircleColliderInternal CIRCLE1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + const CircleColliderInternal CIRCLE2 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + + resolution = this->get_circle_circle_resolution(CIRCLE1, CIRCLE2); break; } case CollisionInternalType::CIRCLE_BOX: { - const CircleCollider & collider1 - = std::get>(self.collider); - const BoxCollider & collider2 - = std::get>(other.collider); - vec2 collider_pos1 - = AbsolutePosition::get_position(self.info.transform, collider1.offset); - vec2 collider_pos2 - = AbsolutePosition::get_position(other.info.transform, collider2.offset); - resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, - collider_pos2); + + const BoxColliderInternal BOX1 = { + .collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody + }; + const CircleColliderInternal CIRCLE1 = { + .collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody + }; + resolution = -this->get_circle_box_resolution(CIRCLE1,BOX1); + + + resolution = this->get_circle_box_resolution(CIRCLE1, BOX1); break; } case CollisionInternalType::NONE: @@ -361,21 +384,20 @@ CollisionSystem::get_collision_resolution(const CollisionInternal & self, const return std::make_pair(resolution, resolution_direction); } -vec2 CollisionSystem::get_box_box_resolution(const BoxCollider & box_collider1, - const BoxCollider & box_collider2, - const vec2 & final_position1, - const vec2 & final_position2) const { +vec2 CollisionSystem::get_box_box_resolution(const BoxColliderInternal & self, const BoxColliderInternal & other) const { vec2 resolution; // Default resolution vector - vec2 delta = final_position2 - final_position1; + vec2 self_pos = AbsolutePosition::get_position(self.transform, self.collider.offset); + vec2 other_pos = AbsolutePosition::get_position(other.transform, other.collider.offset); + vec2 delta = other_pos - self_pos; - vec2 scaled_box1 = box_collider1.dimensions * transform1.scale; - vec2 scaled_box2 = box_collider2.dimensions * transform2.scale; + vec2 scaled_box1 = self.collider.dimensions * self.transform.scale; + vec2 scaled_box2 = other.collider.dimensions * other.transform.scale; // Compute half-dimensions of the boxes - float half_width1 = box_collider1.dimensions.x / 2.0; - float half_height1 = box_collider1.dimensions.y / 2.0; - float half_width2 = box_collider2.dimensions.x / 2.0; - float half_height2 = box_collider2.dimensions.y / 2.0; + float half_width1 = self.collider.dimensions.x / 2.0; + float half_height1 = self.collider.dimensions.y / 2.0; + float half_width2 = other.collider.dimensions.x / 2.0; + float half_height2 = other.collider.dimensions.y / 2.0; // Calculate overlaps along X and Y axes float overlap_x = (half_width1 + half_width2) - std::abs(delta.x); @@ -400,17 +422,16 @@ vec2 CollisionSystem::get_box_box_resolution(const BoxCollider & box_collider1, return resolution; } -vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle_collider1, - const CircleCollider & circle_collider2, - const vec2 & final_position1, - const vec2 & final_position2) const { - vec2 delta = final_position2 - final_position1; +vec2 CollisionSystem::get_circle_circle_resolution(const CircleColliderInternal & self, const CircleColliderInternal & other) const { + vec2 self_pos = AbsolutePosition::get_position(self.transform, self.collider.offset); + vec2 other_pos = AbsolutePosition::get_position(other.transform, other.collider.offset); + vec2 delta = other_pos - self_pos; // Compute the distance between the two circle centers float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); // Compute the combined radii of the two circles - float combined_radius = circle_collider1.radius + circle_collider2.radius; + float combined_radius = self.collider.radius + other.collider.radius; // Compute the penetration depth float penetration_depth = combined_radius - distance; @@ -424,15 +445,14 @@ vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle return resolution; } -vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_collider, - const BoxCollider & box_collider, - const vec2 & circle_position, - const vec2 & box_position) const { - vec2 delta = circle_position - box_position; +vec2 CollisionSystem::get_circle_box_resolution(const CircleColliderInternal & circle, const BoxColliderInternal & box) const { + vec2 self_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); + vec2 other_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); + vec2 delta = other_pos - self_pos; // Compute half-dimensions of the box - float half_width = box_collider.dimensions.x / 2.0f; - float half_height = box_collider.dimensions.y / 2.0f; + float half_width = box.collider.dimensions.x / 2.0f; + float half_height = box.collider.dimensions.y / 2.0f; // Clamp circle center to the nearest point on the box vec2 closest_point; @@ -448,7 +468,7 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co vec2 collision_normal = closest_delta / distance; // Compute penetration depth - float penetration_depth = circle_collider.radius - distance; + float penetration_depth = circle.collider.radius - distance; // Compute the resolution vector vec2 resolution = collision_normal * penetration_depth; diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 01c189e..a695e61 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -82,6 +82,20 @@ private: game_object_id_t id = 0; collider_variant collider; ColliderInfo info; + vec2 resolution; + Direction resolution_direction = Direction::NONE; + }; + + struct BoxColliderInternal { + BoxCollider & collider; + Transform & transform; + Rigidbody & rigidbody; + }; + + struct CircleColliderInternal { + CircleCollider & collider; + Transform & transform; + Rigidbody & rigidbody; }; public: @@ -134,9 +148,7 @@ private: * \param position2 The position of the second BoxCollider. * \return The resolution vector for the collision. */ - vec2 get_box_box_resolution(const BoxCollider & box_collider1, - const BoxCollider & box_collider2, const vec2 & position1, - const vec2 & position2) const; + vec2 get_box_box_resolution(const BoxColliderInternal & self, const BoxColliderInternal & other) const; //done /** * \brief Calculates the resolution vector for two CircleCollider. @@ -149,10 +161,7 @@ private: * \param final_position2 The position of the second CircleCollider. * \return The resolution vector for the collision. */ - vec2 get_circle_circle_resolution(const CircleCollider & circle_collider1, - const CircleCollider & circle_collider2, - const vec2 & final_position1, - const vec2 & final_position2) const; + vec2 get_circle_circle_resolution(const CircleColliderInternal & self, const CircleColliderInternal & other) const; //done /** * \brief Calculates the resolution vector for two CircleCollider. @@ -165,10 +174,7 @@ private: * \param box_position The position of the BoxCollider. * \return The resolution vector for the collision. */ - vec2 get_circle_box_resolution(const CircleCollider & circle_collider, - const BoxCollider & box_collider, - const vec2 & circle_position, - const vec2 & box_position) const; + vec2 get_circle_box_resolution(const CircleColliderInternal & circle, const BoxColliderInternal & box) const; //done /** * \brief Determines the appropriate collision handler for a collision. @@ -256,10 +262,7 @@ private: * \param rigidbody2 Rigidbody of the second object. * \return True if a collision is detected, otherwise false. */ - bool get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2, - const Transform & transform1, const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const; + bool get_box_box_collision(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; /** * \brief Check collision for box on circle collider @@ -272,10 +275,7 @@ private: * \param rigidbody2 Rigidbody of the second object. * \return True if a collision is detected, otherwise false. */ - bool get_box_circle_collision(const BoxCollider & box1, const CircleCollider & circle2, - const Transform & transform1, const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const; + bool get_box_circle_collision(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; /** * \brief Check collision for circle on circle collider @@ -290,12 +290,7 @@ private: * * \return status of collision */ - bool get_circle_circle_collision(const CircleCollider & circle1, - const CircleCollider & circle2, - const Transform & transform1, - const Transform & transform2, - const Rigidbody & rigidbody1, - const Rigidbody & rigidbody2) const; + bool get_circle_circle_collision(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const; }; /** -- cgit v1.2.3 From 982e12df210b8eb3daa66ebe6a71dd9e92276cec Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Wed, 18 Dec 2024 23:37:30 +0100 Subject: merged detection and resolution functions --- src/crepe/system/CollisionSystem.cpp | 337 +++++++++++++---------------------- src/crepe/system/CollisionSystem.h | 61 +------ src/example/game.cpp | 12 +- 3 files changed, 135 insertions(+), 275 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index e4f6cb3..a9a0523 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -75,11 +75,11 @@ void CollisionSystem::update() { // For both objects call the collision handler for (auto & collision_pair : collided) { // Determine type - CollisionInternalType type = this->get_collider_type(collision_pair.first.collider, collision_pair.second.collider); + //CollisionInternalType type = this->get_collider_type(collision_pair.first.collider, collision_pair.second.collider); // Determine resolution - std::pair resolution_data = this->get_collision_resolution(collision_pair.first, collision_pair.second, type); + //std::pair resolution_data = this->get_collision_resolution(collision_pair.first, collision_pair.second, type); // Convert internal struct to external struct - CollisionInfo info = this->get_collision_info(collision_pair.first, collision_pair.second,type,resolution_data.first,resolution_data.second); + CollisionInfo info = this->get_collision_info(collision_pair.first, collision_pair.second); // Determine if and/or what collison handler is needed. this->determine_collision_handler(info); } @@ -87,7 +87,7 @@ void CollisionSystem::update() { // Below is for collision detection std::vector> -CollisionSystem::gather_collisions(const std::vector & colliders) const { +CollisionSystem::gather_collisions(std::vector & colliders) { // TODO: // If no colliders skip @@ -106,7 +106,7 @@ CollisionSystem::gather_collisions(const std::vector & collid if (colliders[i].id == colliders[j].id) continue; if (!should_collide(colliders[i], colliders[j])) continue; CollisionInternalType type = get_collider_type(colliders[i].collider, colliders[j].collider); - if (!get_collision(colliders[i],colliders[j],type)) continue; + if (!detect_collision(colliders[i],colliders[j],type)) continue; //fet collisions_ret.emplace_back(colliders[i], colliders[j]); } @@ -156,8 +156,8 @@ CollisionSystem::get_collider_type(const collider_variant & collider1, } } -bool CollisionSystem::get_collision(const CollisionInternal & self,const CollisionInternal & other,const CollisionInternalType & type) const { - +bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInternal & other,const CollisionInternalType & type) { + vec2 resolution; switch (type) { case CollisionInternalType::BOX_BOX: { const BoxColliderInternal BOX1 = { @@ -170,8 +170,10 @@ bool CollisionSystem::get_collision(const CollisionInternal & self,const Collisi .transform = other.info.transform, .rigidbody = other.info.rigidbody }; - - return this->get_box_box_collision(BOX1, BOX2); + resolution = this->get_box_box_detection(BOX1, BOX2); + if(resolution == vec2{-1,-1}) return false; + break; + } case CollisionInternalType::BOX_CIRCLE: { const BoxColliderInternal BOX1 = { @@ -184,7 +186,9 @@ bool CollisionSystem::get_collision(const CollisionInternal & self,const Collisi .transform = other.info.transform, .rigidbody = other.info.rigidbody }; - return this->get_box_circle_collision(BOX1, CIRCLE2); + resolution = this->get_box_circle_detection(BOX1, CIRCLE2); + if(resolution == vec2{-1,-1}) return false; + break; } case CollisionInternalType::CIRCLE_CIRCLE: { const CircleColliderInternal CIRCLE1 = { @@ -197,7 +201,9 @@ bool CollisionSystem::get_collision(const CollisionInternal & self,const Collisi .transform = other.info.transform, .rigidbody = other.info.rigidbody }; - return this->get_circle_circle_collision(CIRCLE1,CIRCLE2); + resolution = this->get_circle_circle_detection(CIRCLE1,CIRCLE2); + if(resolution == vec2{-1,-1}) return false; + break; } case CollisionInternalType::CIRCLE_BOX: { const CircleColliderInternal CIRCLE1 = { @@ -210,22 +216,31 @@ bool CollisionSystem::get_collision(const CollisionInternal & self,const Collisi .transform = other.info.transform, .rigidbody = other.info.rigidbody }; - return this->get_box_circle_collision(BOX2, CIRCLE1); + resolution = this->get_box_circle_detection(BOX2, CIRCLE1); + if(resolution == vec2{-1,-1}) return false; + break; } case CollisionInternalType::NONE: break; } - return false; + self.resolution = resolution; + self.resolution_direction = this->resolution_correction(self.resolution, self.info.rigidbody.data); + other.resolution = -self.resolution; + other.resolution_direction = self.resolution_direction; + return true; } -bool CollisionSystem::get_box_box_collision(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const { +vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const { + vec2 resolution; // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); - vec2 final_position2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); + vec2 pos1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); + vec2 pos2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); // Scale dimensions vec2 scaled_box1 = box1.collider.dimensions * box1.transform.scale; vec2 scaled_box2 = box2.collider.dimensions * box2.transform.scale; + vec2 delta = pos2 - pos1; + // Calculate half-extents (half width and half height) float half_width1 = scaled_box1.x / 2.0; @@ -233,42 +248,77 @@ bool CollisionSystem::get_box_box_collision(const BoxColliderInternal & box1, co float half_width2 = scaled_box2.x / 2.0; float half_height2 = scaled_box2.y / 2.0; - // Check if the boxes overlap along the X and Y axes - return (final_position1.x + half_width1 > final_position2.x - half_width2 - && final_position1.x - half_width1 < final_position2.x + half_width2 - && final_position1.y + half_height1 > final_position2.y - half_height2 - && final_position1.y - half_height1 < final_position2.y + half_height2); + if (pos1.x + half_width1 > pos2.x - half_width2 + && pos1.x - half_width1 < pos2.x + half_width2 + && pos1.y + half_height1 > pos2.y - half_height2 + && pos1.y - half_height1 < pos2.y + half_height2) + { + float overlap_x = (half_width1 + half_width2) - std::abs(delta.x); + float overlap_y = (half_height1 + half_height2) - std::abs(delta.y); + if (overlap_x > 0 && overlap_y > 0) { + // Determine the direction of resolution + if (overlap_x < overlap_y) { + // Resolve along the X-axis (smallest overlap) + resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; + } else if (overlap_y < overlap_x) { + // Resolve along the Y-axis (smallest overlap) + resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; + } else { + // Equal overlap, resolve both directions with preference + resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; + resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; + } + } + return resolution; + } + return vec2{-1,-1}; } -bool CollisionSystem::get_box_circle_collision(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const { - // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); - vec2 final_position2 = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); - - // Scale dimensions - vec2 scaled_box = box1.collider.dimensions * box1.transform.scale; - float scaled_circle = circle2.collider.radius * circle2.transform.scale; - - // Calculate box half-extents - float half_width = scaled_box.x / 2.0; - float half_height = scaled_box.y / 2.0; - - // Find the closest point on the box to the circle's center - float closest_x = std::max(final_position1.x - half_width, - std::min(final_position2.x, final_position1.x + half_width)); - float closest_y = std::max(final_position1.y - half_height, - std::min(final_position2.y, final_position1.y + half_height)); - - // Calculate the distance squared between the circle's center and the closest point on the box - float distance_x = final_position2.x - closest_x; - float distance_y = final_position2.y - closest_y; - float distance_squared = distance_x * distance_x + distance_y * distance_y; - - // Compare distance squared with the square of the circle's radius - return distance_squared < scaled_circle * scaled_circle; +vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, const CircleColliderInternal & circle) const { + /// Get current positions of colliders + vec2 box_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); + vec2 circle_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); + + // Scale dimensions + vec2 scaled_box = box.collider.dimensions * box.transform.scale; + float scaled_circle_radius = circle.collider.radius * circle.transform.scale; + + // Calculate box half-extents + float half_width = scaled_box.x / 2.0f; + float half_height = scaled_box.y / 2.0f; + + // Find the closest point on the box to the circle's center + float closest_x = std::max(box_pos.x - half_width, std::min(circle_pos.x, box_pos.x + half_width)); + float closest_y = std::max(box_pos.y - half_height, std::min(circle_pos.y, box_pos.y + half_height)); + + float distance_x = circle_pos.x - closest_x; + float distance_y = circle_pos.y - closest_y; + float distance_squared = distance_x * distance_x + distance_y * distance_y; + if(distance_squared < scaled_circle_radius * scaled_circle_radius){ + vec2 delta = circle_pos - box_pos; + + // Clamp circle center to the nearest point on the box + vec2 closest_point; + closest_point.x = std::clamp(delta.x, -half_width, half_width); + closest_point.y = std::clamp(delta.y, -half_height, half_height); + + // Find the vector from the circle center to the closest point + vec2 closest_delta = delta - closest_point; + + float distance = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y); + vec2 collision_normal = closest_delta / distance; + + // Compute penetration depth + float penetration_depth = scaled_circle_radius - distance; + + // Compute the resolution vector + return vec2{collision_normal * penetration_depth}; + } + // No collision + return vec2{-1,-1}; } -bool CollisionSystem::get_circle_circle_collision(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { +vec2 CollisionSystem::get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { // Get current positions of colliders vec2 final_position1 = AbsolutePosition::get_position(circle1.transform, circle1.collider.offset); vec2 final_position2 = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); @@ -284,86 +334,35 @@ bool CollisionSystem::get_circle_circle_collision(const CircleColliderInternal & // Calculate the sum of the radii float radius_sum = scaled_circle1 + scaled_circle2; - // Check if the distance between the centers is less than or equal to the sum of the radii - return distance_squared < radius_sum * radius_sum; -} + // Check for collision (distance squared must be less than the square of the radius sum) + if (distance_squared < radius_sum * radius_sum) { + vec2 delta = final_position2 - final_position1; -std::pair -CollisionSystem::get_collision_resolution(const CollisionInternal & self, const CollisionInternal & other, - const CollisionInternalType & type) const { - vec2 resolution; - // Fet resolution form correct type - switch (type) { - case CollisionInternalType::BOX_BOX: { + // Compute the distance between the two circle centers + float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); - const BoxColliderInternal BOX1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - const BoxColliderInternal BOX2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; - resolution = this->get_box_box_resolution(BOX1, BOX2); - break; - } - case CollisionInternalType::BOX_CIRCLE: { + // Compute the combined radii of the two circles + float combined_radius = scaled_circle1 + scaled_circle2; - const BoxColliderInternal BOX1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - const CircleColliderInternal CIRCLE1 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; - resolution = -this->get_circle_box_resolution(CIRCLE1,BOX1); - break; - } - case CollisionInternalType::CIRCLE_CIRCLE: { - const CircleColliderInternal CIRCLE1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - const CircleColliderInternal CIRCLE2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; - - resolution = this->get_circle_circle_resolution(CIRCLE1, CIRCLE2); - break; - } - case CollisionInternalType::CIRCLE_BOX: { + // Compute the penetration depth + float penetration_depth = combined_radius - distance; - const BoxColliderInternal BOX1 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; - const CircleColliderInternal CIRCLE1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - resolution = -this->get_circle_box_resolution(CIRCLE1,BOX1); + // Normalize the delta vector to get the collision direction + vec2 collision_normal = delta / distance; - - resolution = this->get_circle_box_resolution(CIRCLE1, BOX1); - break; - } - case CollisionInternalType::NONE: - break; + // Compute the resolution vector + vec2 resolution = -collision_normal * penetration_depth; + + return resolution; } + // No collision + return vec2{-1,-1}; +} + +CollisionSystem::Direction CollisionSystem::resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody) { // Calculate the other value to move back correctly // If only X or Y has a value determine what is should be to move back. - const Rigidbody::Data & rigidbody = self.info.rigidbody.data; Direction resolution_direction = Direction::NONE; // If both are not zero a perfect corner has been hit if (resolution.x != 0 && resolution.y != 0) { @@ -381,102 +380,10 @@ CollisionSystem::get_collision_resolution(const CollisionInternal & self, const resolution.x = -rigidbody.linear_velocity.x * (resolution.y / rigidbody.linear_velocity.y); } - return std::make_pair(resolution, resolution_direction); -} - -vec2 CollisionSystem::get_box_box_resolution(const BoxColliderInternal & self, const BoxColliderInternal & other) const { - vec2 resolution; // Default resolution vector - vec2 self_pos = AbsolutePosition::get_position(self.transform, self.collider.offset); - vec2 other_pos = AbsolutePosition::get_position(other.transform, other.collider.offset); - vec2 delta = other_pos - self_pos; - - vec2 scaled_box1 = self.collider.dimensions * self.transform.scale; - vec2 scaled_box2 = other.collider.dimensions * other.transform.scale; - - // Compute half-dimensions of the boxes - float half_width1 = self.collider.dimensions.x / 2.0; - float half_height1 = self.collider.dimensions.y / 2.0; - float half_width2 = other.collider.dimensions.x / 2.0; - float half_height2 = other.collider.dimensions.y / 2.0; - - // Calculate overlaps along X and Y axes - float overlap_x = (half_width1 + half_width2) - std::abs(delta.x); - float overlap_y = (half_height1 + half_height2) - std::abs(delta.y); - - // Check if there is a collision should always be true - if (overlap_x > 0 && overlap_y > 0) { - // Determine the direction of resolution - if (overlap_x < overlap_y) { - // Resolve along the X-axis (smallest overlap) - resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; - } else if (overlap_y < overlap_x) { - // Resolve along the Y-axis (smallest overlap) - resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; - } else { - // Equal overlap, resolve both directions with preference - resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; - resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; - } - } - - return resolution; -} - -vec2 CollisionSystem::get_circle_circle_resolution(const CircleColliderInternal & self, const CircleColliderInternal & other) const { - vec2 self_pos = AbsolutePosition::get_position(self.transform, self.collider.offset); - vec2 other_pos = AbsolutePosition::get_position(other.transform, other.collider.offset); - vec2 delta = other_pos - self_pos; - - // Compute the distance between the two circle centers - float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); - - // Compute the combined radii of the two circles - float combined_radius = self.collider.radius + other.collider.radius; - - // Compute the penetration depth - float penetration_depth = combined_radius - distance; - - // Normalize the delta vector to get the collision direction - vec2 collision_normal = delta / distance; - - // Compute the resolution vector - vec2 resolution = -collision_normal * penetration_depth; - - return resolution; -} - -vec2 CollisionSystem::get_circle_box_resolution(const CircleColliderInternal & circle, const BoxColliderInternal & box) const { - vec2 self_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); - vec2 other_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); - vec2 delta = other_pos - self_pos; - - // Compute half-dimensions of the box - float half_width = box.collider.dimensions.x / 2.0f; - float half_height = box.collider.dimensions.y / 2.0f; - - // Clamp circle center to the nearest point on the box - vec2 closest_point; - closest_point.x = std::clamp(delta.x, -half_width, half_width); - closest_point.y = std::clamp(delta.y, -half_height, half_height); - - // Find the vector from the circle center to the closest point - vec2 closest_delta = delta - closest_point; - - // Normalize the delta to get the collision direction - float distance - = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y); - vec2 collision_normal = closest_delta / distance; - - // Compute penetration depth - float penetration_depth = circle.collider.radius - distance; - - // Compute the resolution vector - vec2 resolution = collision_normal * penetration_depth; - - return resolution; + return resolution_direction; } -CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const CollisionInternal & in_self, const CollisionInternal & in_other,const CollisionInternalType & type,const vec2 & resolution,const CollisionSystem::Direction & resolution_direction) const{ +CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const CollisionInternal & in_self, const CollisionInternal & in_other) const{ ComponentManager & mgr = this->mediator.component_manager; @@ -495,8 +402,8 @@ CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const Collisi struct CollisionInfo collision_info{ .self = self, .other = other, - .resolution = resolution, - .resolution_direction = resolution_direction, + .resolution = in_self.resolution, + .resolution_direction = in_self.resolution_direction, }; return collision_info; } diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index a695e61..7792e50 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -123,58 +123,11 @@ private: * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. */ - CollisionInfo get_collision_info(const CollisionInternal & this_data, const CollisionInternal & other_data,const CollisionInternalType & type,const vec2 & resolution,const CollisionSystem::Direction & resolution_direction) const; //done + CollisionInfo get_collision_info(const CollisionInternal & this_data, const CollisionInternal & other_data) const; //done - /** - * \brief Resolves collision between two colliders and calculates the movement required. - * - * Determines the displacement and direction needed to separate colliders based on their types. - * - * \param data1 Collision data for the first collider. - * \param data2 Collision data for the second collider. - * \param type The type of collider pair. - * \return A pair containing the resolution vector and direction for the first collider. - */ - std::pair get_collision_resolution(const CollisionInternal & data1,const CollisionInternal & data2, const CollisionInternalType & type) const; //done - - /** - * \brief Calculates the resolution vector for two BoxColliders. - * - * Computes the displacement required to separate two overlapping BoxColliders. - * - * \param box_collider1 The first BoxCollider. - * \param box_collider2 The second BoxCollider. - * \param position1 The position of the first BoxCollider. - * \param position2 The position of the second BoxCollider. - * \return The resolution vector for the collision. - */ - vec2 get_box_box_resolution(const BoxColliderInternal & self, const BoxColliderInternal & other) const; //done - /** - * \brief Calculates the resolution vector for two CircleCollider. - * - * Computes the displacement required to separate two overlapping CircleCollider. - * - * \param circle_collider1 The first CircleCollider. - * \param circle_collider2 The second CircleCollider. - * \param final_position1 The position of the first CircleCollider. - * \param final_position2 The position of the second CircleCollider. - * \return The resolution vector for the collision. - */ - vec2 get_circle_circle_resolution(const CircleColliderInternal & self, const CircleColliderInternal & other) const; //done + Direction resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody); - /** - * \brief Calculates the resolution vector for two CircleCollider. - * - * Computes the displacement required to separate two overlapping CircleCollider. - * - * \param circle_collider The first CircleCollider. - * \param box_collider The second CircleCollider. - * \param circle_position The position of the CircleCollider. - * \param box_position The position of the BoxCollider. - * \return The resolution vector for the collision. - */ - vec2 get_circle_box_resolution(const CircleColliderInternal & circle, const BoxColliderInternal & box) const; //done /** * \brief Determines the appropriate collision handler for a collision. @@ -222,7 +175,7 @@ private: * \return A list of collision pairs with their associated data. */ std::vector> - gather_collisions(const std::vector & colliders) const; //done + gather_collisions(std::vector & colliders); //done /** * \brief Checks if the settings allow collision @@ -249,7 +202,7 @@ private: * \param type The type of collider pair. * \return True if a collision is detected, otherwise false. */ - bool get_collision(const CollisionInternal & first_info, const CollisionInternal & second_info, const CollisionInternalType & type) const; + bool detect_collision(CollisionInternal & first_info, CollisionInternal & second_info, const CollisionInternalType & type); /** * \brief Detects collisions between two BoxColliders. @@ -262,7 +215,7 @@ private: * \param rigidbody2 Rigidbody of the second object. * \return True if a collision is detected, otherwise false. */ - bool get_box_box_collision(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; + vec2 get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; /** * \brief Check collision for box on circle collider @@ -275,7 +228,7 @@ private: * \param rigidbody2 Rigidbody of the second object. * \return True if a collision is detected, otherwise false. */ - bool get_box_circle_collision(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; + vec2 get_box_circle_detection(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; /** * \brief Check collision for circle on circle collider @@ -290,7 +243,7 @@ private: * * \return status of collision */ - bool get_circle_circle_collision(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const; + vec2 get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const; }; /** diff --git a/src/example/game.cpp b/src/example/game.cpp index a8b3d5d..69bfae2 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -24,7 +24,7 @@ using namespace std; class MyScript1 : public Script { bool flip = false; bool oncollision(const CollisionEvent & test) { - Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id); + Log::logf("Box {} script on_collision()", test.info.self.metadata.game_object_id); return true; } bool keypressed(const KeyPressEvent & test) { @@ -93,7 +93,7 @@ class MyScript1 : public Script { class MyScript2 : public Script { bool flip = false; bool oncollision(const CollisionEvent & test) { - Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id); + Log::logf("Box {} script on_collision()", test.info.self.metadata.game_object_id); return true; } bool keypressed(const KeyPressEvent & test) { @@ -195,7 +195,7 @@ public: GameObject world = new_object( "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); world.add_component(Rigidbody::Data{ - .mass = 0, + .mass = 1, .gravity_scale = 0, .body_type = Rigidbody::BodyType::STATIC, }); @@ -220,11 +220,11 @@ public: }); GameObject game_object1 = new_object( - "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 45, 1); + "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2+30}, 0, 1); game_object1.add_component(Rigidbody::Data{ .mass = 1, .gravity_scale = 0, - .body_type = Rigidbody::BodyType::KINEMATIC, + .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 1}, .constraints = {0, 0, 0}, .elastisity_coefficient = 1, @@ -238,7 +238,7 @@ public: .sorting_in_layer = 2, .order_in_layer = 2, .size = {20, 20}, - .position_offset = {0, -10}, + .position_offset = {0, 0}, }); //add circle with cirlcecollider deactiveated -- cgit v1.2.3 From 714edd69d53a6243e9a2b81f62d309c96b71dd8d Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Thu, 19 Dec 2024 08:36:17 +0100 Subject: bug fix and doxygen fix --- src/crepe/system/CollisionSystem.cpp | 4 +-- src/crepe/system/CollisionSystem.h | 66 +++++++++++++++++++----------------- src/example/game.cpp | 4 +-- 3 files changed, 38 insertions(+), 36 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 75e914d..719713c 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -407,9 +407,9 @@ CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const Collisi // Below is for collision handling void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { Rigidbody::BodyType self_type = info.self.rigidbody.data.body_type; - Rigidbody::BodyType other_type = info.self.rigidbody.data.body_type; + Rigidbody::BodyType other_type = info.other.rigidbody.data.body_type; bool self_kinematic = info.self.rigidbody.data.kinematic_collision; - bool other_kinematic = info.self.rigidbody.data.kinematic_collision; + bool other_kinematic = info.other.rigidbody.data.kinematic_collision; // Inverted collision info CollisionInfo inverted = -info; // If both objects are static skip handle call collision script diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 7792e50..13ce8f0 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -34,18 +34,19 @@ private: BOTH }; public: - /** - * \brief Structure representing detailed collision information between two colliders. - * - * Includes information about the colliding objects and the resolution data for handling the collision. - */ - + + //! Structure representing components of the collider struct ColliderInfo { Transform & transform; Rigidbody & rigidbody; Metadata & metadata; }; + /** + * \brief Structure representing detailed collision information between two colliders. + * + * Includes information about the colliding objects and the resolution data for handling the collision. + */ struct CollisionInfo { ColliderInfo self; ColliderInfo other; @@ -86,12 +87,14 @@ private: Direction resolution_direction = Direction::NONE; }; + //! Structure of collider with addtitional components struct BoxColliderInternal { BoxCollider & collider; Transform & transform; Rigidbody & rigidbody; }; + //! Structure of collider with addtitional components struct CircleColliderInternal { CircleCollider & collider; Transform & transform; @@ -123,9 +126,19 @@ private: * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. */ - CollisionInfo get_collision_info(const CollisionInternal & this_data, const CollisionInternal & other_data) const; //done + CollisionInfo get_collision_info(const CollisionInternal & data1, const CollisionInternal & data2) const; + /** + * \brief Corrects the resolution of the collision + * + * This function corrects the resolution by fixing the x or y if it is empty. + * Besides this with the input of the resolution the direction is saved before correction. + * + * \param resolution resolution vector that needs to be corrected + * \param rigidbody rigidbody data used to correct resolution + * \return Direction of resolution + */ Direction resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody); @@ -136,7 +149,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void determine_collision_handler(const CollisionInfo & info); //done + void determine_collision_handler(const CollisionInfo & info); /** * \brief Calls both collision script @@ -144,6 +157,7 @@ private: * Calls both collision script to let user add additonal handeling or handle full collision. * * \param info Collision information containing data about both colliders. + * \param info_inverted Collision information containing data about both colliders in opposite order. */ void call_collision_events(const CollisionInfo & info, const CollisionInfo & info_inverted); @@ -154,7 +168,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void static_collision_handler(const CollisionInfo & info); //done + void static_collision_handler(const CollisionInfo & info); /** * \brief Handles collisions involving dynamic objects. @@ -163,7 +177,7 @@ private: * * \param info Collision information containing data about both colliders. */ - void dynamic_collision_handler(const CollisionInfo & info); //done + void dynamic_collision_handler(const CollisionInfo & info); private: /** @@ -175,7 +189,7 @@ private: * \return A list of collision pairs with their associated data. */ std::vector> - gather_collisions(std::vector & colliders); //done + gather_collisions(std::vector & colliders); /** * \brief Checks if the settings allow collision @@ -207,39 +221,27 @@ private: /** * \brief Detects collisions between two BoxColliders. * - * \param box1 The first BoxCollider. - * \param box2 The second BoxCollider. - * \param transform1 Transform of the first object. - * \param transform2 Transform of the second object. - * \param rigidbody1 Rigidbody of the first object. - * \param rigidbody2 Rigidbody of the second object. - * \return True if a collision is detected, otherwise false. + * \param box1 Information about the first BoxCollider. + * \param box2 Information about the second BoxCollider. + * \return returns resolution vector if collide otherwise returns {-1,-1} */ vec2 get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; /** * \brief Check collision for box on circle collider * - * \param box1 The BoxCollider - * \param circle2 The CircleCollider - * \param transform1 Transform of the first object. - * \param transform2 Transform of the second object. - * \param rigidbody1 Rigidbody of the first object. - * \param rigidbody2 Rigidbody of the second object. - * \return True if a collision is detected, otherwise false. + * \param box1 Information about the BoxCollider. + * \param circle2 Information about the circleCollider. + * \return returns resolution vector if collide otherwise returns {-1,-1} */ vec2 get_box_circle_detection(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; /** * \brief Check collision for circle on circle collider * - * \param circle1 First CircleCollider - * \param circle2 Second CircleCollider - * \param transform1 Transform of the first object. - * \param transform2 Transform of the second object. - * \param rigidbody1 Rigidbody of the first object. - * \param rigidbody2 Rigidbody of the second object. - * \return True if a collision is detected, otherwise false. + * \param circle1 Information about the first circleCollider. + * \param circle2 Information about the second circleCollider. + * \return returns resolution vector if collide otherwise returns {-1,-1} * * \return status of collision */ diff --git a/src/example/game.cpp b/src/example/game.cpp index 01e55d5..f931878 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -206,7 +206,7 @@ public: vec2{world_collider, world_collider}, vec2{0, screen_size_height / 2 + world_collider / 2}); // Bottom world.add_component( - vec2{world_collider, world_collider},git stauts + vec2{world_collider, world_collider}, vec2{0 - (screen_size_width / 2 + world_collider / 2), 0}); // Left world.add_component( vec2{world_collider, world_collider}, @@ -256,7 +256,7 @@ public: "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); game_object2.add_component(Rigidbody::Data{ .mass = 1, - .gravity_scale = 1, + .gravity_scale = 0, .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, -- cgit v1.2.3 From 2c4627673f48196e845fc1bcb7b62b3de72c7ab6 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Thu, 19 Dec 2024 17:50:12 +0100 Subject: improved doxygen --- src/crepe/api/Rigidbody.h | 31 ++++++++++++++++++--------- src/crepe/system/CollisionSystem.cpp | 17 +++++++-------- src/crepe/system/CollisionSystem.h | 41 +++++++++++++++++++----------------- src/example/game.cpp | 15 +++++++------ 4 files changed, 60 insertions(+), 44 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index df97763..9dbb42b 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -123,26 +123,37 @@ public: */ float elastisity_coefficient = 0.0; - //! Enable static collision handeling for object colliding with kinematic object in collision system - bool kinematic_collision = true; - /** - * \brief Defines the collision layers of a GameObject. + * \brief Enables collision handling for objects colliding with kinematic objects. * - * The `collision_layers` specifies the layers that the GameObject will collide with. - * Each element represents a layer ID, and the GameObject will only detect - * collisions with other GameObjects that belong to that `collision_layer`. + * Enables collision handling for objects colliding with kinematic objects in the collision system. + * If `kinematic_collision` is true, dynamic objects cannot pass through this kinematic object. + * This ensures that kinematic objects delegate collision handling to the collision system. */ + bool kinematic_collision = true; + + /** + * \brief Defines the collision layers a GameObject interacts with. + * + * The `collision_layers` represent the set of layers the GameObject can detect collisions with. + * Each element in this set corresponds to a layer ID. The GameObject will only collide with other + * GameObjects that belong to one these layers. + */ std::set collision_layers = {0}; - //! the collision layer of the object. + /** + * \brief Specifies the collision layer of the GameObject. + * + * The `collision_layer` indicates the single layer that this GameObject belongs to. + * This determines which layers other objects must match to detect collisions with this object. + */ int collision_layer = 0; /** * \brief Defines the collision layers of a GameObject. * * The `collision_names` specifies where the GameObject will collide with. - * Each element represents a name. + * Each element represents a name from the Metadata of the gameobject. */ std::set collision_names; @@ -150,7 +161,7 @@ public: * \brief Defines the collision layers of a GameObject. * * The `collision_tags` specifies where the GameObject will collide with. - * Each element represents a tag. + * Each element represents a tag from the Metadata of the gameobject. */ std::set collision_tags; diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 6ed640a..3da8a50 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -167,7 +167,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna .rigidbody = other.info.rigidbody }; resolution = this->get_box_box_detection(BOX1, BOX2); - if(resolution == vec2{-1,-1}) return false; + if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; } @@ -183,7 +183,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna .rigidbody = other.info.rigidbody }; resolution = this->get_box_circle_detection(BOX1, CIRCLE2); - if(resolution == vec2{-1,-1}) return false; + if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; resolution = -resolution; break; } @@ -199,7 +199,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna .rigidbody = other.info.rigidbody }; resolution = this->get_circle_circle_detection(CIRCLE1,CIRCLE2); - if(resolution == vec2{-1,-1}) return false; + if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; } case CollisionInternalType::CIRCLE_BOX: { @@ -214,7 +214,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna .rigidbody = other.info.rigidbody }; resolution = this->get_box_circle_detection(BOX2, CIRCLE1); - if(resolution == vec2{-1,-1}) return false; + if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; } case CollisionInternalType::NONE: @@ -228,7 +228,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna } vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const { - vec2 resolution; + vec2 resolution{std::nanf(""), std::nanf("")}; // Get current positions of colliders vec2 pos1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); vec2 pos2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); @@ -266,9 +266,8 @@ vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, co resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; } } - return resolution; } - return vec2{-1,-1}; + return resolution; } vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, const CircleColliderInternal & circle) const { @@ -312,7 +311,7 @@ vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, return vec2{collision_normal * penetration_depth}; } // No collision - return vec2{-1,-1}; + return vec2{std::nanf(""), std::nanf("")}; } vec2 CollisionSystem::get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { @@ -353,7 +352,7 @@ vec2 CollisionSystem::get_circle_circle_detection(const CircleColliderInternal & return resolution; } // No collision - return vec2{-1,-1}; + return vec2{std::nanf(""), std::nanf("")}; } CollisionSystem::Direction CollisionSystem::resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody) { diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 13ce8f0..2e9901c 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -31,7 +31,7 @@ private: //! Movement in the Y direction. Y_DIRECTION, //! Movement in both X and Y directions. - BOTH + BOTH, }; public: @@ -87,19 +87,17 @@ private: Direction resolution_direction = Direction::NONE; }; - //! Structure of collider with addtitional components - struct BoxColliderInternal { - BoxCollider & collider; - Transform & transform; - Rigidbody & rigidbody; - }; - - //! Structure of collider with addtitional components - struct CircleColliderInternal { - CircleCollider & collider; - Transform & transform; - Rigidbody & rigidbody; + //! Structure of a collider with additional components + template + struct ColliderInternal { + ColliderType& collider; + Transform& transform; + Rigidbody& rigidbody; }; + //! Predefined BoxColliderInternal. (System is only made for this type) + using BoxColliderInternal = ColliderInternal; + //! Predefined CircleColliderInternal. (System is only made for this type) + using CircleColliderInternal = ColliderInternal; public: //! Updates the collision system by checking for collisions between colliders and handling them. @@ -119,9 +117,11 @@ private: private: /** - * \brief Handles collision resolution between two colliders. + * \brief Converts internal collision data into user-accessible collision information. * - * Processes collision data and adjusts objects to resolve collisions and/or calls the user oncollision script function. + * This function processes collision data from two colliding entities and packages it + * into a structured format that is accessible for further use, + * such as resolving collisions and triggering user-defined collision scripts. * * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. @@ -130,14 +130,17 @@ private: /** - * \brief Corrects the resolution of the collision + * \brief Corrects the collision resolution vector and determines its direction. * - * This function corrects the resolution by fixing the x or y if it is empty. - * Besides this with the input of the resolution the direction is saved before correction. + * This function adjusts the provided resolution vector based on the + * rigidbody's linear velocity to ensure consistent collision correction. If the resolution + * vector has only one non-zero component (either x or y), the missing component is computed + * based on the rigidbody's velocity. If both components are non-zero, it indicates a corner + * collision. The function also identifies the direction of the resolution and returns it. * * \param resolution resolution vector that needs to be corrected * \param rigidbody rigidbody data used to correct resolution - * \return Direction of resolution + * \return A Direction indicating the resolution direction */ Direction resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody); diff --git a/src/example/game.cpp b/src/example/game.cpp index 2660055..f757d5f 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -197,7 +197,7 @@ public: world.add_component(Rigidbody::Data{ .mass = 1, .gravity_scale = 0, - .body_type = Rigidbody::BodyType::STATIC, + .body_type = Rigidbody::BodyType::DYNAMIC, }); world.add_component( vec2{world_collider, world_collider}, @@ -224,7 +224,7 @@ public: game_object1.add_component(Rigidbody::Data{ .mass = 1, .gravity_scale = 0, - .body_type = Rigidbody::BodyType::STATIC, + .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, .elastisity_coefficient = 1, @@ -283,20 +283,20 @@ public: }) .active = false; - Asset img5{"asset/texture/test_ap43.png"}; + Asset img5{"asset/texture/square.png"}; GameObject particle = new_object( "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 90, 1); auto & particle_image = particle.add_component(img5, Sprite::Data{ - .size = {20, 20}, + .size = {5, 5}, .angle_offset = 45, - .scale_offset = 2, + .scale_offset = 1, }); auto & test = particle.add_component(particle_image, ParticleEmitter::Data{ .offset = {0, 0}, .max_particles = 256, - .emission_rate = 1, + .emission_rate = 4, .min_speed = 10, .max_speed = 20, .min_angle = -20, @@ -304,6 +304,9 @@ public: .begin_lifespan = 0, .end_lifespan = 5, }); + particle.add_component(Rigidbody::Data{ + .angular_velocity = 20, + }); } string get_name() const { return "scene1"; } -- cgit v1.2.3 From 3a5d4c67dba2edd54a5c888432a8d794d152255e Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Thu, 19 Dec 2024 18:30:33 +0100 Subject: improved doxygen comments --- src/crepe/system/CollisionSystem.cpp | 15 +++++------ src/crepe/system/CollisionSystem.h | 51 +++++++++++++++++++++++++++--------- 2 files changed, 45 insertions(+), 21 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 3da8a50..a8e6181 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -250,6 +250,7 @@ vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, co && pos1.y + half_height1 > pos2.y - half_height2 && pos1.y - half_height1 < pos2.y + half_height2) { + resolution = {0,0}; float overlap_x = (half_width1 + half_width2) - std::abs(delta.x); float overlap_y = (half_height1 + half_height2) - std::abs(delta.y); if (overlap_x > 0 && overlap_y > 0) { @@ -404,7 +405,6 @@ CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const Collisi return collision_info; } -// Below is for collision handling void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { Rigidbody::BodyType self_type = info.self.rigidbody.data.body_type; Rigidbody::BodyType other_type = info.other.rigidbody.data.body_type; @@ -425,7 +425,7 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { // Handle collision if (static_collision || kinematic_collision) this->static_collision_handler(inverted); // Call scripts - this->call_collision_events(inverted, info); + this->call_collision_events(inverted); return; } @@ -436,7 +436,7 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { // Handle collision if (static_collision || kinematic_collision) this->static_collision_handler(info); // Call scripts - this->call_collision_events(info, inverted); + this->call_collision_events(info); return; } @@ -444,7 +444,7 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { // Handle collision this->dynamic_collision_handler(info); // Call scripts - this->call_collision_events(info, inverted); + this->call_collision_events(info); } void CollisionSystem::static_collision_handler(const CollisionInfo & info) { @@ -565,14 +565,13 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { } } -void CollisionSystem::call_collision_events(const CollisionInfo & info, - const CollisionInfo & info_inverted) { +void CollisionSystem::call_collision_events(const CollisionInfo & info) { CollisionEvent data(info); - CollisionEvent data_inverted(info_inverted); + CollisionEvent data_inverted(-info); EventManager & emgr = this->mediator.event_manager; emgr.trigger_event(data, info.self.transform.game_object_id); emgr.trigger_event(data_inverted, - info_inverted.self.transform.game_object_id); + -info.self.transform.game_object_id); } diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 2e9901c..30340b5 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -146,9 +146,12 @@ private: /** - * \brief Determines the appropriate collision handler for a collision. + * \brief Determines the appropriate collision handler for a given collision event. * - * Decides the correct resolution process based on the dynamic or static nature of the colliders involved. + * This function identifies the correct collision resolution process based on the body types + * of the colliders involved in the collision. It delegates + * collision handling to specific handlers and calls collision event scripts + * as needed. * * \param info Collision information containing data about both colliders. */ @@ -160,14 +163,20 @@ private: * Calls both collision script to let user add additonal handeling or handle full collision. * * \param info Collision information containing data about both colliders. - * \param info_inverted Collision information containing data about both colliders in opposite order. */ - void call_collision_events(const CollisionInfo & info, const CollisionInfo & info_inverted); + void call_collision_events(const CollisionInfo & info); /** * \brief Handles collisions involving static objects. * - * Resolves collisions by adjusting positions and modifying velocities if bounce is enabled. + * This function resolves collisions between static and dynamic objects by adjusting + * the position of the static object and modifying the velocity of the dynamic object + * if elasticity is enabled. The position of the static object is corrected + * based on the collision resolution, and the dynamic object's velocity is adjusted + * accordingly to reflect the collision response. + * + * The handling includes stopping movement, applying bouncing based on the elasticity + * coefficient, and adjusting the position of the dynamic object if needed. * * \param info Collision information containing data about both colliders. */ @@ -176,7 +185,10 @@ private: /** * \brief Handles collisions involving dynamic objects. * - * Resolves collisions by adjusting positions and modifying velocities if bounce is enabled. + * Resolves collisions between two dynamic objects by adjusting their positions and modifying + * their velocities based on the collision resolution. If elasticity is enabled, + * the velocity of both objects is reversed and scaled by the respective elasticity coefficient. + * The positions of the objects are adjusted based on the collision resolution. * * \param info Collision information containing data about both colliders. */ @@ -186,7 +198,8 @@ private: /** * \brief Checks for collisions between colliders. * - * Identifies collisions and generates pairs of colliding objects for further processing. + * This function checks all active colliders and identifies pairs of colliding objects. + * For each identified collision, the appropriate collision data is returned as pairs for further processing. * * \param colliders A collection of all active colliders. * \return A list of collision pairs with their associated data. @@ -212,7 +225,9 @@ private: /** * \brief Checks for collision between two colliders. * - * Calls the appropriate collision detection function based on the collider types. + * This function determines whether two colliders are colliding based on their types. + * It calls the appropriate collision detection function based on the collider pair type and stores the collision resolution data. + * If a collision is detected, it returns true, otherwise false. * * \param first_info Collision data for the first collider. * \param second_info Collision data for the second collider. @@ -224,29 +239,39 @@ private: /** * \brief Detects collisions between two BoxColliders. * + * This function checks whether two `BoxCollider` are colliding based on their positions and scaled dimensions. + * If a collision is detected, it calculates the overlap along the X and Y axes and returns the resolution vector. + * If no collision is detected, it returns a vector with NaN values. + * \param box1 Information about the first BoxCollider. * \param box2 Information about the second BoxCollider. - * \return returns resolution vector if collide otherwise returns {-1,-1} + * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ vec2 get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; /** * \brief Check collision for box on circle collider * + * This function detects if a collision occurs between a rectangular box and a circular collider. + * If a collision is detected, the function calculates the resolution vector to resolve the collision. + * If no collision is detected, it returns a vector with NaN values + * * \param box1 Information about the BoxCollider. * \param circle2 Information about the circleCollider. - * \return returns resolution vector if collide otherwise returns {-1,-1} + * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ vec2 get_box_circle_detection(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; /** * \brief Check collision for circle on circle collider + * + * This function detects if a collision occurs between two circular colliders. + * If a collision is detected, it calculates the resolution vector to resolve the collision. + * If no collision is detected, it returns a vector with NaN values. * * \param circle1 Information about the first circleCollider. * \param circle2 Information about the second circleCollider. - * \return returns resolution vector if collide otherwise returns {-1,-1} - * - * \return status of collision + * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ vec2 get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const; }; -- cgit v1.2.3 From dd035ffa17f4573f06316e0ecb83b426f5ed8285 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Thu, 19 Dec 2024 18:58:01 +0100 Subject: updated coments and reverted test cmake --- src/crepe/api/Rigidbody.h | 2 +- src/crepe/system/CollisionSystem.cpp | 46 +++++++++++++++++------------------- src/crepe/system/CollisionSystem.h | 6 ++--- src/example/collisiontest.cpp | 5 ++-- src/example/game.cpp | 4 ++-- src/test/CMakeLists.txt | 46 ++++++++++++++++++------------------ src/test/CollisionTest.cpp | 4 ++-- 7 files changed, 55 insertions(+), 58 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 9dbb42b..28c376b 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -121,7 +121,7 @@ public: * above 0.0. * */ - float elastisity_coefficient = 0.0; + float elasticity_coefficient = 0.0; /** * \brief Enables collision handling for objects colliding with kinematic objects. diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index c9c5c58..00b56a4 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -242,7 +242,7 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna // For the 'other' collider, the resolution is the opposite direction of 'self' other.resolution = -self.resolution; other.resolution_direction = self.resolution_direction; - + // Return true if a collision was detected and resolution was calculated return true; } @@ -402,8 +402,6 @@ CollisionSystem::Direction CollisionSystem::resolution_correction(vec2 & resolut CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const CollisionInternal & in_self, const CollisionInternal & in_other) const{ - ComponentManager & mgr = this->mediator.component_manager; - crepe::CollisionSystem::ColliderInfo self { .transform = in_self.info.transform, .rigidbody = in_self.info.rigidbody, @@ -470,7 +468,7 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { void CollisionSystem::static_collision_handler(const CollisionInfo & info) { vec2 & transform_pos = info.self.transform.position; - float elastisity = info.self.rigidbody.data.elastisity_coefficient; + float elasticity = info.self.rigidbody.data.elasticity_coefficient; vec2 & rigidbody_vel = info.self.rigidbody.data.linear_velocity; // Move object back using calculate move back value @@ -479,8 +477,8 @@ void CollisionSystem::static_collision_handler(const CollisionInfo & info) { switch (info.resolution_direction) { case Direction::BOTH: //bounce - if (elastisity > 0) { - rigidbody_vel = -rigidbody_vel * elastisity; + if (elasticity > 0) { + rigidbody_vel = -rigidbody_vel * elasticity; } //stop movement else { @@ -489,8 +487,8 @@ void CollisionSystem::static_collision_handler(const CollisionInfo & info) { break; case Direction::Y_DIRECTION: // Bounce - if (elastisity > 0) { - rigidbody_vel.y = -rigidbody_vel.y * elastisity; + if (elasticity > 0) { + rigidbody_vel.y = -rigidbody_vel.y * elasticity; } // Stop movement else { @@ -500,8 +498,8 @@ void CollisionSystem::static_collision_handler(const CollisionInfo & info) { break; case Direction::X_DIRECTION: // Bounce - if (elastisity > 0) { - rigidbody_vel.x = -rigidbody_vel.x * elastisity; + if (elasticity > 0) { + rigidbody_vel.x = -rigidbody_vel.x * elasticity; } // Stop movement else { @@ -519,8 +517,8 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { vec2 & self_transform_pos = info.self.transform.position; vec2 & other_transform_pos = info.other.transform.position; - float self_elastisity = info.self.rigidbody.data.elastisity_coefficient; - float other_elastisity = info.other.rigidbody.data.elastisity_coefficient; + float self_elasticity = info.self.rigidbody.data.elasticity_coefficient; + float other_elasticity = info.other.rigidbody.data.elasticity_coefficient; vec2 & self_rigidbody_vel = info.self.rigidbody.data.linear_velocity; vec2 & other_rigidbody_vel = info.other.rigidbody.data.linear_velocity; @@ -529,21 +527,21 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { switch (info.resolution_direction) { case Direction::BOTH: - if (self_elastisity > 0) { - self_rigidbody_vel = -self_rigidbody_vel * self_elastisity; + if (self_elasticity > 0) { + self_rigidbody_vel = -self_rigidbody_vel * self_elasticity; } else { self_rigidbody_vel = {0, 0}; } - if (other_elastisity > 0) { - other_rigidbody_vel = -other_rigidbody_vel * other_elastisity; + if (other_elasticity > 0) { + other_rigidbody_vel = -other_rigidbody_vel * other_elasticity; } else { other_rigidbody_vel = {0, 0}; } break; case Direction::Y_DIRECTION: - if (self_elastisity > 0) { - self_rigidbody_vel.y = -self_rigidbody_vel.y * self_elastisity; + if (self_elasticity > 0) { + self_rigidbody_vel.y = -self_rigidbody_vel.y * self_elasticity; } // Stop movement else { @@ -551,8 +549,8 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { self_transform_pos.x -= info.resolution.x; } - if (other_elastisity > 0) { - other_rigidbody_vel.y = -other_rigidbody_vel.y * other_elastisity; + if (other_elasticity > 0) { + other_rigidbody_vel.y = -other_rigidbody_vel.y * other_elasticity; } // Stop movement else { @@ -561,8 +559,8 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { } break; case Direction::X_DIRECTION: - if (self_elastisity > 0) { - self_rigidbody_vel.x = -self_rigidbody_vel.x * self_elastisity; + if (self_elasticity > 0) { + self_rigidbody_vel.x = -self_rigidbody_vel.x * self_elasticity; } // Stop movement else { @@ -570,8 +568,8 @@ void CollisionSystem::dynamic_collision_handler(const CollisionInfo & info) { self_transform_pos.y -= info.resolution.y; } - if (other_elastisity > 0) { - other_rigidbody_vel.x = -other_rigidbody_vel.x * other_elastisity; + if (other_elasticity > 0) { + other_rigidbody_vel.x = -other_rigidbody_vel.x * other_elasticity; } // Stop movement else { diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 30340b5..b7808f1 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -74,7 +74,7 @@ private: /** * \brief A structure to store the collision data of a single collider. * - * This structure all components and id that are for needed within this system when calculating or handeling collisions. + * This structure all components and id that are for needed within this system when calculating or handling collisions. * The transform and rigidbody are mostly needed for location and rotation. * In rigidbody additional info is written about what the body of the object is, * and how it should respond on a collision. @@ -160,7 +160,7 @@ private: /** * \brief Calls both collision script * - * Calls both collision script to let user add additonal handeling or handle full collision. + * Calls both collision script to let user add additonal handling or handle full collision. * * \param info Collision information containing data about both colliders. */ @@ -218,7 +218,7 @@ private: * \param other_rigidbody Rigidbody of second collider * \param this_metadata Rigidbody of first object * \param other_metadata Rigidbody of second object - * \return Returns true if there is at least one comparision found. + * \return Returns true if there is at least one comparison found. */ bool should_collide(const CollisionInternal & self, const CollisionInternal & other) const; //done diff --git a/src/example/collisiontest.cpp b/src/example/collisiontest.cpp index 95999c6..b0cb92e 100644 --- a/src/example/collisiontest.cpp +++ b/src/example/collisiontest.cpp @@ -75,8 +75,7 @@ class MyScript1 : public Script { } break; - } - case Keycode::Q: { + }case Keycode::Q: { if(movement){ movement = false; Rigidbody & tf = this->get_component(); @@ -136,7 +135,7 @@ public: game_object1.add_component(Rigidbody::Data{ .gravity_scale = 0, .body_type = Rigidbody::BodyType::KINEMATIC, - .elastisity_coefficient = 1, + .elasticity_coefficient = 1, }); // add box with boxcollider game_object1.add_component(vec2{20, 20}); diff --git a/src/example/game.cpp b/src/example/game.cpp index f757d5f..f5b6f4f 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -227,7 +227,7 @@ public: .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, - .elastisity_coefficient = 1, + .elasticity_coefficient = 1, }); // add box with boxcollider game_object1.add_component(vec2{20, 20}); @@ -260,7 +260,7 @@ public: .body_type = Rigidbody::BodyType::STATIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, - .elastisity_coefficient = 1, + .elasticity_coefficient = 1, }); // add box with boxcollider game_object2.add_component(vec2{20, 20}); diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 61254f1..11b4ca9 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -1,27 +1,27 @@ target_sources(test_main PUBLIC main.cpp CollisionTest.cpp - # PhysicsTest.cpp - # ScriptTest.cpp - # ParticleTest.cpp - # AudioTest.cpp - # AssetTest.cpp - # ResourceManagerTest.cpp - # OptionalRefTest.cpp - # RenderSystemTest.cpp - # EventTest.cpp - # ECSTest.cpp - # SceneManagerTest.cpp - # ValueBrokerTest.cpp - # DBTest.cpp - # Vector2Test.cpp - # LoopManagerTest.cpp - # LoopTimerTest.cpp - # InputTest.cpp - # ScriptEventTest.cpp - # ScriptSceneTest.cpp - # Profiling.cpp - # SaveManagerTest.cpp - # ScriptSaveManagerTest.cpp - # ScriptECSTest.cpp + PhysicsTest.cpp + ScriptTest.cpp + ParticleTest.cpp + AudioTest.cpp + AssetTest.cpp + ResourceManagerTest.cpp + OptionalRefTest.cpp + RenderSystemTest.cpp + EventTest.cpp + ECSTest.cpp + SceneManagerTest.cpp + ValueBrokerTest.cpp + DBTest.cpp + Vector2Test.cpp + LoopManagerTest.cpp + LoopTimerTest.cpp + InputTest.cpp + ScriptEventTest.cpp + ScriptSceneTest.cpp + Profiling.cpp + SaveManagerTest.cpp + ScriptSaveManagerTest.cpp + ScriptECSTest.cpp ) diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index a86f7d3..89dfadb 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -80,7 +80,7 @@ public: .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, - .elastisity_coefficient = 1, + .elasticity_coefficient = 1, .collision_layers = {0}, }); game_object1.add_component(vec2{10, 10}, vec2{0, 0}); @@ -95,7 +95,7 @@ public: .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = {0, 0}, .constraints = {0, 0, 0}, - .elastisity_coefficient = 1, + .elasticity_coefficient = 1, .collision_layers = {0}, }); game_object2.add_component(vec2{10, 10}, vec2{0, 0}); -- cgit v1.2.3 From 8cd4b07e866d33589a7218367a5639b602c40c67 Mon Sep 17 00:00:00 2001 From: JAROWMR Date: Thu, 19 Dec 2024 19:45:17 +0100 Subject: make format --- src/crepe/api/Rigidbody.h | 2 - src/crepe/facade/SDLContext.cpp | 8 +- src/crepe/system/CollisionSystem.cpp | 335 +++++++++++++++++------------------ src/crepe/system/CollisionSystem.h | 42 +++-- src/crepe/system/ParticleSystem.cpp | 3 +- src/crepe/system/RenderSystem.cpp | 2 +- src/example/game.cpp | 4 +- src/test/CollisionTest.cpp | 1 - 8 files changed, 198 insertions(+), 199 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index 28c376b..b63d941 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -164,8 +164,6 @@ public: * Each element represents a tag from the Metadata of the gameobject. */ std::set collision_tags; - - }; public: diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index ca45b79..164d35e 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -229,10 +229,10 @@ void SDLContext::draw_text(const RenderText & data) { = {tmp_font_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; vec2 size = text.dimensions * cam_aux_data.render_scale * data.transform.scale; - vec2 screen_pos = (absoluut_pos - cam_aux_data.cam_pos - + (cam_aux_data.zoomed_viewport) / 2) - * cam_aux_data.render_scale - - size / 2 + cam_aux_data.bar_size; + vec2 screen_pos + = (absoluut_pos - cam_aux_data.cam_pos + (cam_aux_data.zoomed_viewport) / 2) + * cam_aux_data.render_scale + - size / 2 + cam_aux_data.bar_size; SDL_FRect dstrect{ .x = screen_pos.x, diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 00b56a4..f0f1fa8 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -26,12 +26,12 @@ using namespace crepe; using enum Rigidbody::BodyType; CollisionSystem::CollisionInfo CollisionSystem::CollisionInfo::operator-() const { - return { - .self = this->other, + return { + .self = this->other, .other = this->self, .resolution = -this->resolution, .resolution_direction = this->resolution_direction, - }; + }; } void CollisionSystem::update() { @@ -52,8 +52,7 @@ void CollisionSystem::update() { if (!boxcollider.active) continue; all_colliders.push_back({.id = id, .collider = collider_variant{boxcollider}, - .info = {transform,rigidbody, metadata} - }); + .info = {transform, rigidbody, metadata}}); } // Check if the circlecollider is active and has the same id as the rigidbody. RefVector circlecolliders @@ -63,8 +62,7 @@ void CollisionSystem::update() { if (!circlecollider.active) continue; all_colliders.push_back({.id = id, .collider = collider_variant{circlecollider}, - .info = {transform,rigidbody, metadata} - }); + .info = {transform, rigidbody, metadata}}); } } @@ -75,13 +73,14 @@ void CollisionSystem::update() { // For the object convert the info and call the collision handler if needed for (auto & collision_pair : collided) { // Convert internal struct to external struct - CollisionInfo info = this->get_collision_info(collision_pair.first, collision_pair.second); + CollisionInfo info + = this->get_collision_info(collision_pair.first, collision_pair.second); // Determine if and/or what collison handler is needed. this->determine_collision_handler(info); } } -// Below is for collision detection +// Below is for collision detection std::vector> CollisionSystem::gather_collisions(std::vector & colliders) { @@ -101,17 +100,18 @@ CollisionSystem::gather_collisions(std::vector & colliders) { for (size_t j = i + 1; j < colliders.size(); ++j) { if (colliders[i].id == colliders[j].id) continue; if (!should_collide(colliders[i], colliders[j])) continue; - CollisionInternalType type = get_collider_type(colliders[i].collider, colliders[j].collider); - if (!detect_collision(colliders[i],colliders[j],type)) continue; - //fet - collisions_ret.emplace_back(colliders[i], colliders[j]); + CollisionInternalType type + = get_collider_type(colliders[i].collider, colliders[j].collider); + if (!detect_collision(colliders[i], colliders[j], type)) continue; + //fet + collisions_ret.emplace_back(colliders[i], colliders[j]); } } return collisions_ret; } - -bool CollisionSystem::should_collide(const CollisionInternal & self, const CollisionInternal & other) const{ +bool CollisionSystem::should_collide(const CollisionInternal & self, + const CollisionInternal & other) const { const Rigidbody::Data & self_rigidbody = self.info.rigidbody.data; const Rigidbody::Data & other_rigidbody = other.info.rigidbody.data; @@ -119,21 +119,20 @@ bool CollisionSystem::should_collide(const CollisionInternal & self, const Colli const Metadata & other_metadata = other.info.metadata; // Check collision layers - if(self_rigidbody.collision_layers.contains(other_rigidbody.collision_layer)) return true; - if(other_rigidbody.collision_layers.contains(self_rigidbody.collision_layer)) return true; + if (self_rigidbody.collision_layers.contains(other_rigidbody.collision_layer)) return true; + if (other_rigidbody.collision_layers.contains(self_rigidbody.collision_layer)) return true; // Check names - if(self_rigidbody.collision_names.contains(other_metadata.name)) return true; - if(other_rigidbody.collision_names.contains(self_metadata.name)) return true; + if (self_rigidbody.collision_names.contains(other_metadata.name)) return true; + if (other_rigidbody.collision_names.contains(self_metadata.name)) return true; // Check tags - if(self_rigidbody.collision_tags.contains(other_metadata.tag)) return true; - if(other_rigidbody.collision_tags.contains(self_metadata.tag)) return true; + if (self_rigidbody.collision_tags.contains(other_metadata.tag)) return true; + if (other_rigidbody.collision_tags.contains(self_metadata.tag)) return true; return false; } - CollisionSystem::CollisionInternalType CollisionSystem::get_collider_type(const collider_variant & collider1, const collider_variant & collider2) const { @@ -152,93 +151,86 @@ CollisionSystem::get_collider_type(const collider_variant & collider1, } } -bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInternal & other,const CollisionInternalType & type) { +bool CollisionSystem::detect_collision(CollisionInternal & self, CollisionInternal & other, + const CollisionInternalType & type) { vec2 resolution; switch (type) { - case CollisionInternalType::BOX_BOX: { + case CollisionInternalType::BOX_BOX: { // Box-Box collision detection - const BoxColliderInternal BOX1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - const BoxColliderInternal BOX2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; + const BoxColliderInternal BOX1 + = {.collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody}; + const BoxColliderInternal BOX2 + = {.collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody}; // Get resolution vector from box-box collision detection resolution = this->get_box_box_detection(BOX1, BOX2); // If no collision (NaN values), return false - if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; + if (std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; - } case CollisionInternalType::BOX_CIRCLE: { // Box-Circle collision detection - const BoxColliderInternal BOX1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; + const BoxColliderInternal BOX1 + = {.collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody}; const CircleColliderInternal CIRCLE2 = { .collider = std::get>(other.collider), .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; + .rigidbody = other.info.rigidbody}; // Get resolution vector from box-circle collision detection resolution = this->get_box_circle_detection(BOX1, CIRCLE2); // If no collision (NaN values), return false - if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; + if (std::isnan(resolution.x) && std::isnan(resolution.y)) return false; // Invert the resolution vector for proper collision response resolution = -resolution; break; } - case CollisionInternalType::CIRCLE_CIRCLE: { + case CollisionInternalType::CIRCLE_CIRCLE: { // Circle-Circle collision detection - const CircleColliderInternal CIRCLE1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; + const CircleColliderInternal CIRCLE1 + = {.collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody}; const CircleColliderInternal CIRCLE2 = { .collider = std::get>(other.collider), .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; + .rigidbody = other.info.rigidbody}; // Get resolution vector from circle-circle collision detection - resolution = this->get_circle_circle_detection(CIRCLE1,CIRCLE2); + resolution = this->get_circle_circle_detection(CIRCLE1, CIRCLE2); // If no collision (NaN values), return false - if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; + if (std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; } - case CollisionInternalType::CIRCLE_BOX: { + case CollisionInternalType::CIRCLE_BOX: { // Circle-Box collision detection - const CircleColliderInternal CIRCLE1 = { - .collider = std::get>(self.collider), - .transform = self.info.transform, - .rigidbody = self.info.rigidbody - }; - const BoxColliderInternal BOX2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody - }; + const CircleColliderInternal CIRCLE1 + = {.collider = std::get>(self.collider), + .transform = self.info.transform, + .rigidbody = self.info.rigidbody}; + const BoxColliderInternal BOX2 + = {.collider = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody}; // Get resolution vector from box-circle collision detection (order swapped) resolution = this->get_box_circle_detection(BOX2, CIRCLE1); // If no collision (NaN values), return false - if(std::isnan(resolution.x) && std::isnan(resolution.y)) return false; + if (std::isnan(resolution.x) && std::isnan(resolution.y)) return false; break; } case CollisionInternalType::NONE: - // No collision detection needed if the type is NONE - return false; - break; + // No collision detection needed if the type is NONE + return false; + break; } - // Store the calculated resolution vector for the 'self' collider + // Store the calculated resolution vector for the 'self' collider self.resolution = resolution; // Calculate the resolution direction based on the rigidbody data - self.resolution_direction = this->resolution_correction(self.resolution, self.info.rigidbody.data); + self.resolution_direction + = this->resolution_correction(self.resolution, self.info.rigidbody.data); // For the 'other' collider, the resolution is the opposite direction of 'self' other.resolution = -self.resolution; other.resolution_direction = self.resolution_direction; @@ -247,18 +239,18 @@ bool CollisionSystem::detect_collision(CollisionInternal & self,CollisionInterna return true; } -vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const { +vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, + const BoxColliderInternal & box2) const { vec2 resolution{std::nanf(""), std::nanf("")}; // Get current positions of colliders - vec2 pos1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); - vec2 pos2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); + vec2 pos1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); + vec2 pos2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); // Scale dimensions vec2 scaled_box1 = box1.collider.dimensions * box1.transform.scale; vec2 scaled_box2 = box2.collider.dimensions * box2.transform.scale; vec2 delta = pos2 - pos1; - // Calculate half-extents (half width and half height) float half_width1 = scaled_box1.x / 2.0; float half_height1 = scaled_box1.y / 2.0; @@ -266,79 +258,85 @@ vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, co float half_height2 = scaled_box2.y / 2.0; if (pos1.x + half_width1 > pos2.x - half_width2 - && pos1.x - half_width1 < pos2.x + half_width2 - && pos1.y + half_height1 > pos2.y - half_height2 - && pos1.y - half_height1 < pos2.y + half_height2) - { - resolution = {0,0}; + && pos1.x - half_width1 < pos2.x + half_width2 + && pos1.y + half_height1 > pos2.y - half_height2 + && pos1.y - half_height1 < pos2.y + half_height2) { + resolution = {0, 0}; float overlap_x = (half_width1 + half_width2) - std::abs(delta.x); float overlap_y = (half_height1 + half_height2) - std::abs(delta.y); if (overlap_x > 0 && overlap_y > 0) { - // Determine the direction of resolution - if (overlap_x < overlap_y) { - // Resolve along the X-axis (smallest overlap) - resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; - } else if (overlap_y < overlap_x) { - // Resolve along the Y-axis (smallest overlap) - resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; - } else { - // Equal overlap, resolve both directions with preference - resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; - resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; + // Determine the direction of resolution + if (overlap_x < overlap_y) { + // Resolve along the X-axis (smallest overlap) + resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; + } else if (overlap_y < overlap_x) { + // Resolve along the Y-axis (smallest overlap) + resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; + } else { + // Equal overlap, resolve both directions with preference + resolution.x = (delta.x > 0) ? -overlap_x : overlap_x; + resolution.y = (delta.y > 0) ? -overlap_y : overlap_y; + } } } - } return resolution; } -vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, const CircleColliderInternal & circle) const { +vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, + const CircleColliderInternal & circle) const { /// Get current positions of colliders - vec2 box_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); - vec2 circle_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); - - // Scale dimensions - vec2 scaled_box = box.collider.dimensions * box.transform.scale; - float scaled_circle_radius = circle.collider.radius * circle.transform.scale; - - // Calculate box half-extents - float half_width = scaled_box.x / 2.0f; - float half_height = scaled_box.y / 2.0f; - - // Find the closest point on the box to the circle's center - float closest_x = std::max(box_pos.x - half_width, std::min(circle_pos.x, box_pos.x + half_width)); - float closest_y = std::max(box_pos.y - half_height, std::min(circle_pos.y, box_pos.y + half_height)); - - float distance_x = circle_pos.x - closest_x; - float distance_y = circle_pos.y - closest_y; - float distance_squared = distance_x * distance_x + distance_y * distance_y; - if(distance_squared < scaled_circle_radius * scaled_circle_radius){ - vec2 delta = circle_pos - box_pos; - - // Clamp circle center to the nearest point on the box - vec2 closest_point; - closest_point.x = std::clamp(delta.x, -half_width, half_width); - closest_point.y = std::clamp(delta.y, -half_height, half_height); - - // Find the vector from the circle center to the closest point - vec2 closest_delta = delta - closest_point; - - float distance = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y); - vec2 collision_normal = closest_delta / distance; - - // Compute penetration depth - float penetration_depth = scaled_circle_radius - distance; - - // Compute the resolution vector - return vec2{collision_normal * penetration_depth}; - } - // No collision - return vec2{std::nanf(""), std::nanf("")}; + vec2 box_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); + vec2 circle_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); + + // Scale dimensions + vec2 scaled_box = box.collider.dimensions * box.transform.scale; + float scaled_circle_radius = circle.collider.radius * circle.transform.scale; + + // Calculate box half-extents + float half_width = scaled_box.x / 2.0f; + float half_height = scaled_box.y / 2.0f; + + // Find the closest point on the box to the circle's center + float closest_x + = std::max(box_pos.x - half_width, std::min(circle_pos.x, box_pos.x + half_width)); + float closest_y + = std::max(box_pos.y - half_height, std::min(circle_pos.y, box_pos.y + half_height)); + + float distance_x = circle_pos.x - closest_x; + float distance_y = circle_pos.y - closest_y; + float distance_squared = distance_x * distance_x + distance_y * distance_y; + if (distance_squared < scaled_circle_radius * scaled_circle_radius) { + vec2 delta = circle_pos - box_pos; + + // Clamp circle center to the nearest point on the box + vec2 closest_point; + closest_point.x = std::clamp(delta.x, -half_width, half_width); + closest_point.y = std::clamp(delta.y, -half_height, half_height); + + // Find the vector from the circle center to the closest point + vec2 closest_delta = delta - closest_point; + + float distance + = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y); + vec2 collision_normal = closest_delta / distance; + + // Compute penetration depth + float penetration_depth = scaled_circle_radius - distance; + + // Compute the resolution vector + return vec2{collision_normal * penetration_depth}; + } + // No collision + return vec2{std::nanf(""), std::nanf("")}; } -vec2 CollisionSystem::get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { +vec2 CollisionSystem::get_circle_circle_detection( + const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { // Get current positions of colliders - vec2 final_position1 = AbsolutePosition::get_position(circle1.transform, circle1.collider.offset); - vec2 final_position2 = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); + vec2 final_position1 + = AbsolutePosition::get_position(circle1.transform, circle1.collider.offset); + vec2 final_position2 + = AbsolutePosition::get_position(circle2.transform, circle2.collider.offset); // Scale dimensions float scaled_circle1 = circle1.collider.radius * circle1.transform.scale; @@ -376,7 +374,8 @@ vec2 CollisionSystem::get_circle_circle_detection(const CircleColliderInternal & return vec2{std::nanf(""), std::nanf("")}; } -CollisionSystem::Direction CollisionSystem::resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody) { +CollisionSystem::Direction +CollisionSystem::resolution_correction(vec2 & resolution, const Rigidbody::Data & rigidbody) { // Calculate the other value to move back correctly // If only X or Y has a value determine what is should be to move back. @@ -384,63 +383,64 @@ CollisionSystem::Direction CollisionSystem::resolution_correction(vec2 & resolut // If both are not zero a perfect corner has been hit if (resolution.x != 0 && resolution.y != 0) { resolution_direction = Direction::BOTH; - // If x is not zero a horizontal action was latest action. + // If x is not zero a horizontal action was latest action. } else if (resolution.x != 0) { resolution_direction = Direction::X_DIRECTION; // If both are 0 resolution y should not be changed (y_velocity can be 0 by kinematic object movement) if (rigidbody.linear_velocity.x != 0 && rigidbody.linear_velocity.y != 0) - resolution.y = -rigidbody.linear_velocity.y * (resolution.x / rigidbody.linear_velocity.x); + resolution.y + = -rigidbody.linear_velocity.y * (resolution.x / rigidbody.linear_velocity.x); } else if (resolution.y != 0) { resolution_direction = Direction::Y_DIRECTION; // If both are 0 resolution x should not be changed (x_velocity can be 0 by kinematic object movement) if (rigidbody.linear_velocity.x != 0 && rigidbody.linear_velocity.y != 0) - resolution.x = -rigidbody.linear_velocity.x * (resolution.y / rigidbody.linear_velocity.y); + resolution.x + = -rigidbody.linear_velocity.x * (resolution.y / rigidbody.linear_velocity.y); } return resolution_direction; } -CollisionSystem::CollisionInfo CollisionSystem::get_collision_info(const CollisionInternal & in_self, const CollisionInternal & in_other) const{ +CollisionSystem::CollisionInfo +CollisionSystem::get_collision_info(const CollisionInternal & in_self, + const CollisionInternal & in_other) const { - crepe::CollisionSystem::ColliderInfo self { - .transform = in_self.info.transform, - .rigidbody = in_self.info.rigidbody, - .metadata = in_self.info.metadata, + crepe::CollisionSystem::ColliderInfo self{ + .transform = in_self.info.transform, + .rigidbody = in_self.info.rigidbody, + .metadata = in_self.info.metadata, }; - crepe::CollisionSystem::ColliderInfo other { - .transform = in_other.info.transform, - .rigidbody = in_other.info.rigidbody, - .metadata = in_other.info.metadata, + crepe::CollisionSystem::ColliderInfo other{ + .transform = in_other.info.transform, + .rigidbody = in_other.info.rigidbody, + .metadata = in_other.info.metadata, }; - struct CollisionInfo collision_info{ - .self = self, - .other = other, - .resolution = in_self.resolution, + struct CollisionInfo collision_info { + .self = self, .other = other, .resolution = in_self.resolution, .resolution_direction = in_self.resolution_direction, }; return collision_info; } void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { - Rigidbody::BodyType self_type = info.self.rigidbody.data.body_type; - Rigidbody::BodyType other_type = info.other.rigidbody.data.body_type; + Rigidbody::BodyType self_type = info.self.rigidbody.data.body_type; + Rigidbody::BodyType other_type = info.other.rigidbody.data.body_type; bool self_kinematic = info.self.rigidbody.data.kinematic_collision; bool other_kinematic = info.other.rigidbody.data.kinematic_collision; // Inverted collision info CollisionInfo inverted = -info; // If both objects are static skip handle call collision script - if (self_type == STATIC - && other_type == STATIC) - return; + if (self_type == STATIC && other_type == STATIC) return; // First body is not dynamic if (self_type != DYNAMIC) { bool static_collision = self_type == STATIC && other_type == DYNAMIC; - bool kinematic_collision = self_type == KINEMATIC && other_type == DYNAMIC && self_kinematic; + bool kinematic_collision + = self_type == KINEMATIC && other_type == DYNAMIC && self_kinematic; - // Handle collision + // Handle collision if (static_collision || kinematic_collision) this->static_collision_handler(inverted); // Call scripts this->call_collision_events(inverted); @@ -451,7 +451,7 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { if (other_type != DYNAMIC) { bool static_collision = other_type == STATIC; bool kinematic_collision = other_type == KINEMATIC && other_kinematic; - // Handle collision + // Handle collision if (static_collision || kinematic_collision) this->static_collision_handler(info); // Call scripts this->call_collision_events(info); @@ -459,18 +459,18 @@ void CollisionSystem::determine_collision_handler(const CollisionInfo & info) { } // Dynamic - // Handle collision + // Handle collision this->dynamic_collision_handler(info); // Call scripts this->call_collision_events(info); } void CollisionSystem::static_collision_handler(const CollisionInfo & info) { - + vec2 & transform_pos = info.self.transform.position; float elasticity = info.self.rigidbody.data.elasticity_coefficient; vec2 & rigidbody_vel = info.self.rigidbody.data.linear_velocity; - + // Move object back using calculate move back value transform_pos += info.resolution; @@ -588,10 +588,5 @@ void CollisionSystem::call_collision_events(const CollisionInfo & info) { CollisionEvent data_inverted(-info); EventManager & emgr = this->mediator.event_manager; emgr.trigger_event(data, info.self.transform.game_object_id); - emgr.trigger_event(data_inverted, - -info.self.transform.game_object_id); + emgr.trigger_event(data_inverted, -info.self.transform.game_object_id); } - - - - diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index b7808f1..7be280a 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -21,6 +21,7 @@ namespace crepe { class CollisionSystem : public System { public: using System::System; + private: //! Enum representing movement directions during collision resolution. enum class Direction { @@ -33,13 +34,13 @@ private: //! Movement in both X and Y directions. BOTH, }; + public: - //! Structure representing components of the collider struct ColliderInfo { - Transform & transform; - Rigidbody & rigidbody; - Metadata & metadata; + Transform & transform; + Rigidbody & rigidbody; + Metadata & metadata; }; /** @@ -54,7 +55,7 @@ public: vec2 resolution; //! The direction of movement for resolving the collision. Direction resolution_direction = Direction::NONE; - CollisionInfo operator - () const; + CollisionInfo operator-() const; }; private: @@ -90,9 +91,9 @@ private: //! Structure of a collider with additional components template struct ColliderInternal { - ColliderType& collider; - Transform& transform; - Rigidbody& rigidbody; + ColliderType & collider; + Transform & transform; + Rigidbody & rigidbody; }; //! Predefined BoxColliderInternal. (System is only made for this type) using BoxColliderInternal = ColliderInternal; @@ -113,7 +114,8 @@ private: * \param collider2 Second collider variant (BoxCollider or CircleCollider). * \return The combined type of the two colliders. */ - CollisionInternalType get_collider_type(const collider_variant & collider1, const collider_variant & collider2) const; + CollisionInternalType get_collider_type(const collider_variant & collider1, + const collider_variant & collider2) const; private: /** @@ -126,8 +128,8 @@ private: * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. */ - CollisionInfo get_collision_info(const CollisionInternal & data1, const CollisionInternal & data2) const; - + CollisionInfo get_collision_info(const CollisionInternal & data1, + const CollisionInternal & data2) const; /** * \brief Corrects the collision resolution vector and determines its direction. @@ -142,8 +144,7 @@ private: * \param rigidbody rigidbody data used to correct resolution * \return A Direction indicating the resolution direction */ - Direction resolution_correction(vec2 & resolution,const Rigidbody::Data & rigidbody); - + Direction resolution_correction(vec2 & resolution, const Rigidbody::Data & rigidbody); /** * \brief Determines the appropriate collision handler for a given collision event. @@ -220,7 +221,8 @@ private: * \param other_metadata Rigidbody of second object * \return Returns true if there is at least one comparison found. */ - bool should_collide(const CollisionInternal & self, const CollisionInternal & other) const; //done + bool should_collide(const CollisionInternal & self, + const CollisionInternal & other) const; //done /** * \brief Checks for collision between two colliders. @@ -234,7 +236,8 @@ private: * \param type The type of collider pair. * \return True if a collision is detected, otherwise false. */ - bool detect_collision(CollisionInternal & first_info, CollisionInternal & second_info, const CollisionInternalType & type); + bool detect_collision(CollisionInternal & first_info, CollisionInternal & second_info, + const CollisionInternalType & type); /** * \brief Detects collisions between two BoxColliders. @@ -247,7 +250,8 @@ private: * \param box2 Information about the second BoxCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_box_box_detection(const BoxColliderInternal & box1, const BoxColliderInternal & box2) const; + vec2 get_box_box_detection(const BoxColliderInternal & box1, + const BoxColliderInternal & box2) const; /** * \brief Check collision for box on circle collider @@ -260,7 +264,8 @@ private: * \param circle2 Information about the circleCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_box_circle_detection(const BoxColliderInternal & box1, const CircleColliderInternal & circle2) const; + vec2 get_box_circle_detection(const BoxColliderInternal & box1, + const CircleColliderInternal & circle2) const; /** * \brief Check collision for circle on circle collider @@ -273,7 +278,8 @@ private: * \param circle2 Information about the second circleCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_circle_circle_detection(const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const; + vec2 get_circle_circle_detection(const CircleColliderInternal & circle1, + const CircleColliderInternal & circle2) const; }; /** diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp index 31c1800..e66c603 100644 --- a/src/crepe/system/ParticleSystem.cpp +++ b/src/crepe/system/ParticleSystem.cpp @@ -51,7 +51,8 @@ void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & vec2 initial_position = AbsolutePosition::get_position(transform, emitter.data.offset); float random_angle - = this->generate_random_angle(emitter.data.min_angle+transform.rotation, emitter.data.max_angle+transform.rotation); + = this->generate_random_angle(emitter.data.min_angle + transform.rotation, + emitter.data.max_angle + transform.rotation); float random_speed = this->generate_random_speed(emitter.data.min_speed, emitter.data.max_speed); diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 9d8e683..8c31743 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -16,9 +16,9 @@ #include "../facade/Texture.h" #include "../manager/ComponentManager.h" #include "../manager/ResourceManager.h" -#include "util/AbsolutePosition.h" #include "api/Text.h" #include "facade/Font.h" +#include "util/AbsolutePosition.h" #include "RenderSystem.h" #include "types.h" diff --git a/src/example/game.cpp b/src/example/game.cpp index 76ea8c2..fb7fb63 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -220,7 +220,7 @@ public: }); GameObject game_object1 = new_object( - "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2+20}, 0, 1); + "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2 + 20}, 0, 1); game_object1.add_component(Rigidbody::Data{ .mass = 1, .gravity_scale = 0, @@ -270,7 +270,7 @@ public: .size = {20, 20}, .angle_offset = 45, .scale_offset = 1, - .position_offset = {0,20}, + .position_offset = {0, 20}, }); //add circle with cirlcecollider deactiveated diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index 8f566df..11916eb 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -25,7 +25,6 @@ using namespace std::chrono_literals; using namespace crepe; using namespace testing; - class CollisionHandler : public Script { public: int box_id; -- cgit v1.2.3 From 61148c757a1f742ff09e40e5347e74e638c7371c Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Sun, 22 Dec 2024 12:32:22 +0100 Subject: update clang-format options --- .clang-format | 3 + game/GameScene.cpp | 20 +- game/MoveCameraManualyScript.cpp | 5 +- game/PlayerSubScene.cpp | 84 ++-- game/background/AquariumSubScene.cpp | 204 ++++---- game/background/ForestParallaxScript.cpp | 5 +- game/background/ForestSubScene.cpp | 194 ++++---- game/background/HallwaySubScene.cpp | 190 ++++--- game/background/HallwaySubScene.h | 11 +- game/background/StartSubScene.cpp | 491 +++++++++++-------- mwe/ecs-homemade/inc/ComponentManager.hpp | 4 +- mwe/ecs-homemade/src/ComponentManager.cpp | 5 +- mwe/events/include/event.h | 4 +- mwe/events/include/eventHandler.h | 7 +- mwe/events/include/eventManager.h | 25 +- mwe/events/src/event.cpp | 5 +- mwe/events/src/eventManager.cpp | 5 +- mwe/events/src/loopManager.cpp | 6 +- mwe/events/src/uiObject.cpp | 6 +- mwe/events/src/window.cpp | 6 +- mwe/gameloop/include/gameObject.h | 5 +- mwe/gameloop/src/gameObject.cpp | 5 +- mwe/gameloop/src/loopManager.cpp | 10 +- mwe/gameloop/src/window.cpp | 6 +- mwe/resource-manager/main.cpp | 5 +- mwe/resource-manager/map_layer.cpp | 18 +- mwe/resource-manager/map_layer.h | 4 +- mwe/resource-manager/stb_image.h | 788 ++++++++++++++++++------------ src/crepe/Particle.cpp | 5 +- src/crepe/Particle.h | 4 +- src/crepe/api/AI.cpp | 33 +- src/crepe/api/AI.h | 12 +- src/crepe/api/Animator.cpp | 6 +- src/crepe/api/Animator.h | 6 +- src/crepe/api/Asset.cpp | 2 +- src/crepe/api/AudioSource.h | 2 +- src/crepe/api/BoxCollider.cpp | 5 +- src/crepe/api/BoxCollider.h | 5 +- src/crepe/api/Camera.cpp | 5 +- src/crepe/api/Camera.h | 6 +- src/crepe/api/CircleCollider.cpp | 5 +- src/crepe/api/CircleCollider.h | 5 +- src/crepe/api/Color.cpp | 16 +- src/crepe/api/Engine.cpp | 12 +- src/crepe/api/Engine.h | 18 +- src/crepe/api/GameObject.cpp | 12 +- src/crepe/api/GameObject.h | 6 +- src/crepe/api/ParticleEmitter.cpp | 7 +- src/crepe/api/Scene.cpp | 6 +- src/crepe/api/Scene.h | 7 +- src/crepe/api/Script.h | 12 +- src/crepe/api/Script.hpp | 11 +- src/crepe/api/Text.cpp | 6 +- src/crepe/api/Text.h | 6 +- src/crepe/api/Transform.cpp | 2 +- src/crepe/facade/FontFacade.cpp | 5 +- src/crepe/facade/SDLContext.cpp | 61 ++- src/crepe/facade/SDLContext.h | 7 +- src/crepe/manager/ComponentManager.cpp | 22 +- src/crepe/manager/ComponentManager.h | 7 +- src/crepe/manager/ComponentManager.hpp | 20 +- src/crepe/manager/EventManager.h | 4 +- src/crepe/manager/EventManager.hpp | 14 +- src/crepe/manager/LoopTimerManager.cpp | 6 +- src/crepe/manager/LoopTimerManager.h | 12 +- src/crepe/manager/ResourceManager.hpp | 13 +- src/crepe/manager/SceneManager.cpp | 10 +- src/crepe/manager/SystemManager.hpp | 10 +- src/crepe/system/AISystem.cpp | 21 +- src/crepe/system/CollisionSystem.cpp | 81 +-- src/crepe/system/CollisionSystem.h | 40 +- src/crepe/system/InputSystem.cpp | 36 +- src/crepe/system/InputSystem.h | 21 +- src/crepe/system/ParticleSystem.cpp | 17 +- src/crepe/system/RenderSystem.cpp | 6 +- src/crepe/system/ScriptSystem.cpp | 5 +- src/crepe/util/dbg.h | 11 +- src/example/AITest.cpp | 50 +- src/example/button.cpp | 16 +- src/example/loadfont.cpp | 12 +- src/example/rendering_particle.cpp | 54 +- src/example/replay.cpp | 19 +- src/test/AssetTest.cpp | 6 +- src/test/AudioTest.cpp | 6 +- src/test/CollisionTest.cpp | 83 ++-- src/test/ECSTest.cpp | 68 +-- src/test/EventTest.cpp | 35 +- src/test/InputTest.cpp | 35 +- src/test/LoopManagerTest.cpp | 2 +- src/test/LoopTimerTest.cpp | 2 +- src/test/ParticleTest.cpp | 76 +-- src/test/PhysicsTest.cpp | 10 +- src/test/Profiling.cpp | 91 ++-- src/test/RenderSystemTest.cpp | 92 ++-- src/test/ReplayManagerTest.cpp | 6 +- src/test/ResourceManagerTest.cpp | 6 +- src/test/SaveManagerTest.cpp | 4 +- src/test/SceneManagerTest.cpp | 20 +- src/test/ScriptSaveManagerTest.cpp | 4 +- src/test/ScriptSceneTest.cpp | 2 +- src/test/ScriptTest.h | 10 +- src/test/ValueBrokerTest.cpp | 4 +- 102 files changed, 2004 insertions(+), 1481 deletions(-) (limited to 'src/crepe/system/CollisionSystem.h') diff --git a/.clang-format b/.clang-format index 1ee37ec..9ebf218 100644 --- a/.clang-format +++ b/.clang-format @@ -24,6 +24,9 @@ AlignEscapedNewlines: DontAlign BreakBeforeBinaryOperators: All AlwaysBreakTemplateDeclarations: Yes PackConstructorInitializers: CurrentLine +# only option that doesn't result in copious indentation +AlignAfterOpenBracket: BlockIndent +SpaceBeforeCpp11BracedList: true ... # vim: ft=yaml diff --git a/game/GameScene.cpp b/game/GameScene.cpp index 91da092..2511567 100644 --- a/game/GameScene.cpp +++ b/game/GameScene.cpp @@ -29,34 +29,36 @@ void GameScene::load_scene() { BackgroundSubScene background(*this); GameObject camera = new_object("camera", "camera", vec2(650, 0)); - camera.add_component(ivec2(990, 720), vec2(VIEWPORT_X, VIEWPORT_Y), - Camera::Data{ - .bg_color = Color::RED, - }); + camera.add_component( + ivec2(990, 720), vec2(VIEWPORT_X, VIEWPORT_Y), + Camera::Data { + .bg_color = Color::RED, + } + ); camera.add_component().set_script(); - camera.add_component(Rigidbody::Data{}); + camera.add_component(Rigidbody::Data {}); PlayerSubScene player(*this); GameObject floor = new_object("floor", "game_world", vec2(0, 325)); - floor.add_component(Rigidbody::Data{ + floor.add_component(Rigidbody::Data { .body_type = Rigidbody::BodyType::STATIC, .collision_layer = COLL_LAY_BOT_TOP, }); floor.add_component(vec2(INFINITY, 200)); GameObject floor_low = new_object("floor_low", "game_world", vec2(0, 350)); - floor_low.add_component(Rigidbody::Data{ + floor_low.add_component(Rigidbody::Data { .body_type = Rigidbody::BodyType::STATIC, .collision_layer = COLL_LAY_BOT_LOW, }); floor_low.add_component(vec2(INFINITY, 200)); GameObject floor_high = new_object("floor_high", "game_world", vec2(0, 300)); - floor_high.add_component(Rigidbody::Data{ + floor_high.add_component(Rigidbody::Data { .body_type = Rigidbody::BodyType::STATIC, .collision_layer = COLL_LAY_BOT_HIGH, }); GameObject ceiling = new_object("ceiling", "game_world", vec2(0, -325)); - ceiling.add_component(Rigidbody::Data{ + ceiling.add_component(Rigidbody::Data { .body_type = Rigidbody::BodyType::STATIC, .collision_layer = COLL_LAY_BOT_TOP, }); diff --git a/game/MoveCameraManualyScript.cpp b/game/MoveCameraManualyScript.cpp index 0181333..9d75a75 100644 --- a/game/MoveCameraManualyScript.cpp +++ b/game/MoveCameraManualyScript.cpp @@ -4,8 +4,9 @@ using namespace crepe; using namespace std; void MoveCameraManualyScript::init() { - subscribe( - [this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); }); + subscribe([this](const KeyPressEvent & ev) -> bool { + return this->keypressed(ev); + }); } bool MoveCameraManualyScript::keypressed(const KeyPressEvent & event) { diff --git a/game/PlayerSubScene.cpp b/game/PlayerSubScene.cpp index b361a82..00b7810 100644 --- a/game/PlayerSubScene.cpp +++ b/game/PlayerSubScene.cpp @@ -13,46 +13,58 @@ using namespace std; PlayerSubScene::PlayerSubScene(Scene & scn) { GameObject player = scn.new_object("player", "player", vec2(-100, 200)); - Asset player_body_asset{"asset/barry/defaultBody.png"}; + Asset player_body_asset {"asset/barry/defaultBody.png"}; Sprite & player_body_sprite = player.add_component( - player_body_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_PLAYER, - .order_in_layer = 0, - .size = vec2(0, 50), - }); - player.add_component(player_body_sprite, ivec2(32, 32), uvec2(4, 8), - Animator::Data{ - .fps = 5, - .looping = true, - }); - Asset player_head_asset{"asset/barry/defaultHead.png"}; + player_body_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_PLAYER, + .order_in_layer = 0, + .size = vec2(0, 50), + } + ); + player.add_component( + player_body_sprite, ivec2(32, 32), uvec2(4, 8), + Animator::Data { + .fps = 5, + .looping = true, + } + ); + Asset player_head_asset {"asset/barry/defaultHead.png"}; Sprite & player_head_sprite = player.add_component( - player_head_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_PLAYER, - .order_in_layer = 1, - .size = vec2(0, 50), - .position_offset = vec2(0, -20), - }); - player.add_component(player_head_sprite, ivec2(32, 32), uvec2(4, 8), - Animator::Data{ - .fps = 5, - .looping = true, - }); - Asset player_jetpack_asset{"asset/barry/jetpackDefault.png"}; + player_head_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_PLAYER, + .order_in_layer = 1, + .size = vec2(0, 50), + .position_offset = vec2(0, -20), + } + ); + player.add_component( + player_head_sprite, ivec2(32, 32), uvec2(4, 8), + Animator::Data { + .fps = 5, + .looping = true, + } + ); + Asset player_jetpack_asset {"asset/barry/jetpackDefault.png"}; Sprite & player_jetpack_sprite = player.add_component( - player_jetpack_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_PLAYER, - .order_in_layer = 2, - .size = vec2(0, 60), - .position_offset = vec2(-20, 0), - }); + player_jetpack_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_PLAYER, + .order_in_layer = 2, + .size = vec2(0, 60), + .position_offset = vec2(-20, 0), + } + ); player_jetpack_sprite.active = false; - player.add_component(player_jetpack_sprite, ivec2(32, 44), uvec2(4, 4), - Animator::Data{ - .fps = 5, - .looping = true, - }); - player.add_component(Rigidbody::Data{ + player.add_component( + player_jetpack_sprite, ivec2(32, 44), uvec2(4, 4), + Animator::Data { + .fps = 5, + .looping = true, + } + ); + player.add_component(Rigidbody::Data { .gravity_scale = 20, .body_type = Rigidbody::BodyType::DYNAMIC, .linear_velocity = vec2(100, 0), diff --git a/game/background/AquariumSubScene.cpp b/game/background/AquariumSubScene.cpp index 579e633..8d5202a 100644 --- a/game/background/AquariumSubScene.cpp +++ b/game/background/AquariumSubScene.cpp @@ -16,73 +16,85 @@ float AquariumSubScene::create(Scene & scn, float begin_x) { GameObject aquarium_begin = scn.new_object("aquarium_begin", "background", vec2(begin_x, 0)); - Asset aquarium_begin_asset{"asset/background/aquarium/glassTubeFG_1_TVOS.png"}; - aquarium_begin.add_component(aquarium_begin_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_begin_asset {"asset/background/aquarium/glassTubeFG_1_TVOS.png"}; + aquarium_begin.add_component( + aquarium_begin_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; GameObject aquarium_middle_1 = scn.new_object("aquarium_middle", "background", vec2(begin_x, 0)); - Asset aquarium_middle_1_asset{"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; - aquarium_middle_1.add_component(aquarium_middle_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_middle_1_asset {"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; + aquarium_middle_1.add_component( + aquarium_middle_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 400; this->add_background(scn, begin_x - 200); GameObject aquarium_middle_2 = scn.new_object("aquarium_middle", "background", vec2(begin_x, 0)); - Asset aquarium_middle_2_asset{"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; - aquarium_middle_2.add_component(aquarium_middle_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 3, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_middle_2_asset {"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; + aquarium_middle_2.add_component( + aquarium_middle_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 3, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 400; GameObject aquarium_middle_3 = scn.new_object("aquarium_middle", "background", vec2(begin_x, 0)); - Asset aquarium_middle_3_asset{"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; - aquarium_middle_3.add_component(aquarium_middle_3_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 4, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_middle_3_asset {"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; + aquarium_middle_3.add_component( + aquarium_middle_3_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 4, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 400; this->add_background(scn, begin_x - 200); GameObject aquarium_middle_4 = scn.new_object("aquarium_middle", "background", vec2(begin_x, 0)); - Asset aquarium_middle_4_asset{"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; - aquarium_middle_4.add_component(aquarium_middle_4_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_middle_4_asset {"asset/background/aquarium/glassTubeFG_3_TVOS.png"}; + aquarium_middle_4.add_component( + aquarium_middle_4_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; this->add_background(scn, begin_x); GameObject aquarium_end = scn.new_object("aquarium_end", "background", vec2(begin_x, 0)); - Asset aquarium_end_asset{"asset/background/aquarium/glassTubeFG_2_TVOS.png"}; - aquarium_end.add_component(aquarium_end_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, GAME_HEIGHT), - }); + Asset aquarium_end_asset {"asset/background/aquarium/glassTubeFG_2_TVOS.png"}; + aquarium_end.add_component( + aquarium_end_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; return begin_x; @@ -90,54 +102,66 @@ float AquariumSubScene::create(Scene & scn, float begin_x) { void AquariumSubScene::add_background(Scene & scn, float begin_x) { GameObject bg_1 = scn.new_object("aquarium_bg_1", "aquarium_background", vec2(begin_x, 0)); - Asset bg_1_1_asset{"asset/background/aquarium/AquariumBG1_1_TVOS.png"}; - bg_1.add_component(bg_1_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, 400), - .position_offset = vec2(-200, 100), - }); - Asset bg_1_2_asset{"asset/background/aquarium/AquariumBG1_2_TVOS.png"}; - bg_1.add_component(bg_1_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, 400), - .position_offset = vec2(200, 100), - }); + Asset bg_1_1_asset {"asset/background/aquarium/AquariumBG1_1_TVOS.png"}; + bg_1.add_component( + bg_1_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, 400), + .position_offset = vec2(-200, 100), + } + ); + Asset bg_1_2_asset {"asset/background/aquarium/AquariumBG1_2_TVOS.png"}; + bg_1.add_component( + bg_1_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, 400), + .position_offset = vec2(200, 100), + } + ); GameObject bg_2 = scn.new_object("aquarium_bg_2", "aquarium_background", vec2(begin_x, 0)); - Asset bg_2_1_asset{"asset/background/aquarium/AquariumBG2_1_TVOS.png"}; - bg_2.add_component(bg_2_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 400), - .position_offset = vec2(200, -50), - }); - Asset bg_2_2_asset{"asset/background/aquarium/AquariumBG2_2_TVOS.png"}; - bg_2.add_component(bg_2_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 400), - .position_offset = vec2(-200, -50), - }); + Asset bg_2_1_asset {"asset/background/aquarium/AquariumBG2_1_TVOS.png"}; + bg_2.add_component( + bg_2_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 400), + .position_offset = vec2(200, -50), + } + ); + Asset bg_2_2_asset {"asset/background/aquarium/AquariumBG2_2_TVOS.png"}; + bg_2.add_component( + bg_2_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 400), + .position_offset = vec2(-200, -50), + } + ); GameObject bg_3 = scn.new_object("aquarium_bg_3", "aquarium_background", vec2(begin_x, 0)); - Asset bg_3_1_asset{"asset/background/aquarium/AquariumBG3_1_TVOS.png"}; - bg_3.add_component(bg_3_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 400), - .position_offset = vec2(200, -200), - }); - Asset bg_3_2_asset{"asset/background/aquarium/AquariumBG3_2_TVOS.png"}; - bg_3.add_component(bg_3_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 400), - .position_offset = vec2(-200, -200), - }); + Asset bg_3_1_asset {"asset/background/aquarium/AquariumBG3_1_TVOS.png"}; + bg_3.add_component( + bg_3_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 400), + .position_offset = vec2(200, -200), + } + ); + Asset bg_3_2_asset {"asset/background/aquarium/AquariumBG3_2_TVOS.png"}; + bg_3.add_component( + bg_3_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 400), + .position_offset = vec2(-200, -200), + } + ); } diff --git a/game/background/ForestParallaxScript.cpp b/game/background/ForestParallaxScript.cpp index 27e30eb..c72f85d 100644 --- a/game/background/ForestParallaxScript.cpp +++ b/game/background/ForestParallaxScript.cpp @@ -3,8 +3,9 @@ using namespace crepe; using namespace std; -ForestParallaxScript::ForestParallaxScript(float begin_x, float end_x, - std::string unique_bg_name) +ForestParallaxScript::ForestParallaxScript( + float begin_x, float end_x, std::string unique_bg_name +) : begin_x(begin_x), end_x(end_x), name(unique_bg_name) {} diff --git a/game/background/ForestSubScene.cpp b/game/background/ForestSubScene.cpp index 7eac53a..a807a36 100644 --- a/game/background/ForestSubScene.cpp +++ b/game/background/ForestSubScene.cpp @@ -17,52 +17,63 @@ using namespace std; float ForestSubScene::create(Scene & scn, float begin_x, std::string unique_bg_name) { GameObject script = scn.new_object("forest_script", "background"); script.add_component().set_script( - begin_x - 400, begin_x + 3000 + 400, unique_bg_name); + begin_x - 400, begin_x + 3000 + 400, unique_bg_name + ); this->add_background(scn, begin_x, unique_bg_name); GameObject begin = scn.new_object("forest_begin", "background", vec2(begin_x, 0)); - Asset begin_asset{"asset/background/forest/forestFG_1_TVOS.png"}; - begin.add_component(begin_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, GAME_HEIGHT), - }); + Asset begin_asset {"asset/background/forest/forestFG_1_TVOS.png"}; + begin.add_component( + begin_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 800; this->add_background(scn, begin_x, unique_bg_name); GameObject middle_1 = scn.new_object("forest_middle", "background", vec2(begin_x, 0)); - Asset middle_1_asset{"asset/background/forest/forestFG_3_TVOS.png"}; - middle_1.add_component(middle_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_1_asset {"asset/background/forest/forestFG_3_TVOS.png"}; + middle_1.add_component( + middle_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 800; this->add_background(scn, begin_x, unique_bg_name); GameObject middle_2 = scn.new_object("forest_middle", "background", vec2(begin_x, 0)); - Asset middle_2_asset{"asset/background/forest/forestFG_3_TVOS.png"}; - middle_2.add_component(middle_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 3, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_2_asset {"asset/background/forest/forestFG_3_TVOS.png"}; + middle_2.add_component( + middle_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 3, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 800; this->add_background(scn, begin_x, unique_bg_name); GameObject end = scn.new_object("forest_end", "background", vec2(begin_x, 0)); - Asset end_asset{"asset/background/forest/forestFG_2_TVOS.png"}; - end.add_component(end_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, GAME_HEIGHT), - }); + Asset end_asset {"asset/background/forest/forestFG_2_TVOS.png"}; + end.add_component( + end_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; this->add_background(scn, begin_x + 200, unique_bg_name); @@ -73,69 +84,84 @@ float ForestSubScene::create(Scene & scn, float begin_x, std::string unique_bg_n void ForestSubScene::add_background(Scene & scn, float begin_x, std::string name) { GameObject bg_1 = scn.new_object("forest_bg_1_" + name, "forest_background", vec2(begin_x, 0)); - Asset bg_1_asset{"asset/background/forest/forestBG1_1_TVOS.png"}; - bg_1.add_component(bg_1_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, 800), - }); + Asset bg_1_asset {"asset/background/forest/forestBG1_1_TVOS.png"}; + bg_1.add_component( + bg_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, 800), + } + ); GameObject bg_2 = scn.new_object("forest_bg_2_" + name, "forest_background", vec2(begin_x, 0)); - Asset bg_2_1_asset{"asset/background/forest/forestBG2_1_TVOS.png"}; - bg_2.add_component(bg_2_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 400), - .position_offset = vec2(200, 0), - }); - Asset bg_2_2_asset{"asset/background/forest/forestBG2_2_TVOS.png"}; - bg_2.add_component(bg_2_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 400), - .position_offset = vec2(-200, 0), - }); + Asset bg_2_1_asset {"asset/background/forest/forestBG2_1_TVOS.png"}; + bg_2.add_component( + bg_2_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 400), + .position_offset = vec2(200, 0), + } + ); + Asset bg_2_2_asset {"asset/background/forest/forestBG2_2_TVOS.png"}; + bg_2.add_component( + bg_2_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 400), + .position_offset = vec2(-200, 0), + } + ); GameObject bg_3 = scn.new_object("forest_bg_3_" + name, "forest_background", vec2(begin_x, 0)); - Asset bg_3_1_asset{"asset/background/forest/forestBG3_1_TVOS.png"}; - bg_3.add_component(bg_3_1_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 200), - .position_offset = vec2(300, 0), - }); - Asset bg_3_2_asset{"asset/background/forest/forestBG3_2_TVOS.png"}; - bg_3.add_component(bg_3_2_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 200), - .position_offset = vec2(100, 0), - }); - Asset bg_3_3_asset{"asset/background/forest/forestBG3_3_TVOS.png"}; - bg_3.add_component(bg_3_3_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 200), - .position_offset = vec2(-100, 0), - }); - Asset bg_3_4_asset{"asset/background/forest/forestBG3_4_TVOS.png"}; - bg_3.add_component(bg_3_4_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 200), - .position_offset = vec2(-300, 0), - }); - - bg_2.add_component(Rigidbody::Data{ + Asset bg_3_1_asset {"asset/background/forest/forestBG3_1_TVOS.png"}; + bg_3.add_component( + bg_3_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 200), + .position_offset = vec2(300, 0), + } + ); + Asset bg_3_2_asset {"asset/background/forest/forestBG3_2_TVOS.png"}; + bg_3.add_component( + bg_3_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 200), + .position_offset = vec2(100, 0), + } + ); + Asset bg_3_3_asset {"asset/background/forest/forestBG3_3_TVOS.png"}; + bg_3.add_component( + bg_3_3_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 200), + .position_offset = vec2(-100, 0), + } + ); + Asset bg_3_4_asset {"asset/background/forest/forestBG3_4_TVOS.png"}; + bg_3.add_component( + bg_3_4_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACK_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 200), + .position_offset = vec2(-300, 0), + } + ); + + bg_2.add_component(Rigidbody::Data { .linear_velocity = vec2(30, 0), }); - bg_3.add_component(Rigidbody::Data{ + bg_3.add_component(Rigidbody::Data { .linear_velocity = vec2(40, 0), }); } diff --git a/game/background/HallwaySubScene.cpp b/game/background/HallwaySubScene.cpp index 2aa9bab..4d96c94 100644 --- a/game/background/HallwaySubScene.cpp +++ b/game/background/HallwaySubScene.cpp @@ -11,15 +11,19 @@ using namespace crepe; using namespace std; -float HallwaySubScene::create(Scene & scn, float begin_x, unsigned int sector_num, - Color sector_color) { +float HallwaySubScene::create( + Scene & scn, float begin_x, unsigned int sector_num, Color sector_color +) { GameObject begin = scn.new_object("hallway_begin", "background", vec2(begin_x, 0)); - Asset begin_asset{"asset/background/hallway/hallway1FG_1_TVOS.png"}; - begin.add_component(begin_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, GAME_HEIGHT), - }); + Asset begin_asset {"asset/background/hallway/hallway1FG_1_TVOS.png"}; + begin.add_component( + begin_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; this->add_sector_number(begin, vec2(-200, 0), sector_num, sector_color); @@ -27,104 +31,128 @@ float HallwaySubScene::create(Scene & scn, float begin_x, unsigned int sector_nu this->add_lamp(begin, vec2(430, -120), 9); GameObject middle_1 = scn.new_object("hallway_middle", "background", vec2(begin_x, 0)); - Asset middle_asset{"asset/background/hallway/hallway1FG_2_TVOS.png"}; - middle_1.add_component(middle_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 2, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_asset {"asset/background/hallway/hallway1FG_2_TVOS.png"}; + middle_1.add_component( + middle_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 2, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; GameObject middle_2 = scn.new_object("hallway_middle", "background", vec2(begin_x, 0)); - Asset middle_asset_2{"asset/background/hallway/hallway1FG_2_TVOS.png"}; - middle_2.add_component(middle_asset_2, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 3, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_asset_2 {"asset/background/hallway/hallway1FG_2_TVOS.png"}; + middle_2.add_component( + middle_asset_2, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 3, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 200; GameObject middle_3 = scn.new_object("hallway_middle", "background", vec2(begin_x, 0)); - Asset middle_asset_3{"asset/background/hallway/hallway1FG_2_TVOS.png"}; - middle_3.add_component(middle_asset_3, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 4, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_asset_3 {"asset/background/hallway/hallway1FG_2_TVOS.png"}; + middle_3.add_component( + middle_asset_3, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 4, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 400; this->add_lamp(middle_3, vec2(0, -120)); GameObject middle_4 = scn.new_object("hallway_middle", "background", vec2(begin_x, 0)); - Asset middle_asset_4{"asset/background/hallway/hallway1FG_2_TVOS.png"}; - middle_4.add_component(middle_asset_4, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, GAME_HEIGHT), - }); + Asset middle_asset_4 {"asset/background/hallway/hallway1FG_2_TVOS.png"}; + middle_4.add_component( + middle_asset_4, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; GameObject end = scn.new_object("hallway_end", "background", vec2(begin_x, 0)); - Asset end_asset{"asset/background/hallway/hallway1FG_1_TVOS.png"}; - end.add_component(end_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, GAME_HEIGHT), - }); + Asset end_asset {"asset/background/hallway/hallway1FG_1_TVOS.png"}; + end.add_component( + end_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 600; return begin_x; } void HallwaySubScene::add_lamp(GameObject & obj, vec2 offset, unsigned int fps) { - Asset lamp_asset{"asset/background/hallway/alarmLight_TVOS.png"}; - obj.add_component(lamp_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset, - }); - Asset lamp_glow_asset{"asset/background/hallway/alarmGlow_TVOS.png"}; + Asset lamp_asset {"asset/background/hallway/alarmLight_TVOS.png"}; + obj.add_component( + lamp_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset, + } + ); + Asset lamp_glow_asset {"asset/background/hallway/alarmGlow_TVOS.png"}; Sprite & lamp_glow_sprite = obj.add_component( - lamp_glow_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 300), - .position_offset = offset - vec2(65, -30), - }); - obj.add_component(lamp_glow_sprite, ivec2(422, 384), uvec2(6, 1), - Animator::Data{ - .fps = fps, - .looping = true, - }); + lamp_glow_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 300), + .position_offset = offset - vec2(65, -30), + } + ); + obj.add_component( + lamp_glow_sprite, ivec2(422, 384), uvec2(6, 1), + Animator::Data { + .fps = fps, + .looping = true, + } + ); } -void HallwaySubScene::add_sector_number(GameObject & obj, vec2 offset, unsigned int sector_num, - Color sector_color) { - Asset sector_text_asset{"asset/background/hallway/sectorText_TVOS.png"}; - obj.add_component(sector_text_asset, - Sprite::Data{ - .color = sector_color, - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset, - }); - Asset sector_num_asset{"asset/background/hallway/sectorNumbers_TVOS.png"}; +void HallwaySubScene::add_sector_number( + GameObject & obj, vec2 offset, unsigned int sector_num, Color sector_color +) { + Asset sector_text_asset {"asset/background/hallway/sectorText_TVOS.png"}; + obj.add_component( + sector_text_asset, + Sprite::Data { + .color = sector_color, + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset, + } + ); + Asset sector_num_asset {"asset/background/hallway/sectorNumbers_TVOS.png"}; Sprite & sector_num_sprite = obj.add_component( - sector_num_asset, Sprite::Data{ - .color = sector_color, - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset + vec2(200, 0), - }); + sector_num_asset, + Sprite::Data { + .color = sector_color, + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset + vec2(200, 0), + } + ); Animator & sector_num_anim = obj.add_component( - sector_num_sprite, ivec2(256, 128), uvec2(4, 4), Animator::Data{}); + sector_num_sprite, ivec2(256, 128), uvec2(4, 4), Animator::Data {} + ); int column = (sector_num - 1) / 4; int row = (sector_num - 1) % 4; sector_num_anim.set_anim(column); diff --git a/game/background/HallwaySubScene.h b/game/background/HallwaySubScene.h index acc9329..c38b4a9 100644 --- a/game/background/HallwaySubScene.h +++ b/game/background/HallwaySubScene.h @@ -10,12 +10,15 @@ class Color; class HallwaySubScene { public: - float create(crepe::Scene & scn, float begin_x, unsigned int sector_num, - crepe::Color sector_color); + float create( + crepe::Scene & scn, float begin_x, unsigned int sector_num, crepe::Color sector_color + ); private: void add_lamp(crepe::GameObject & obj, crepe::vec2 offset, unsigned int fps = 10); - void add_sector_number(crepe::GameObject & obj, crepe::vec2 offset, - unsigned int sector_num, crepe::Color sector_color); + void add_sector_number( + crepe::GameObject & obj, crepe::vec2 offset, unsigned int sector_num, + crepe::Color sector_color + ); }; diff --git a/game/background/StartSubScene.cpp b/game/background/StartSubScene.cpp index a918c05..d68287b 100644 --- a/game/background/StartSubScene.cpp +++ b/game/background/StartSubScene.cpp @@ -18,20 +18,25 @@ float StartSubScene::create(Scene & scn, float begin_x) { this->create_wall_fragments(scn, begin_x - 300); GameObject begin = scn.new_object("start_begin", "background", vec2(begin_x, 0)); - Asset begin_asset{"asset/background/start/titleFG_1_TVOS.png"}; - begin.add_component(begin_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, GAME_HEIGHT), - }); + Asset begin_asset {"asset/background/start/titleFG_1_TVOS.png"}; + begin.add_component( + begin_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, GAME_HEIGHT), + } + ); GameObject hole = scn.new_object("start_hole", "background", vec2(begin_x - 250, 140)); - Asset hole_asset{"asset/background/start/titleWallHole.png"}; + Asset hole_asset {"asset/background/start/titleWallHole.png"}; Sprite & hole_sprite = hole.add_component( - hole_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 200), - }); + hole_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 200), + } + ); hole_sprite.active = false; begin_x += 700; @@ -40,12 +45,15 @@ float StartSubScene::create(Scene & scn, float begin_x) { this->add_jetpack_stand(begin, vec2(-125, 200)); GameObject end = scn.new_object("start_end", "background", vec2(begin_x, 0)); - Asset end_asset{"asset/background/start/titleFG_2_TVOS.png"}; - end.add_component(end_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, GAME_HEIGHT), - }); + Asset end_asset {"asset/background/start/titleFG_2_TVOS.png"}; + end.add_component( + end_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, GAME_HEIGHT), + } + ); begin_x += 100; this->add_lamp(end, vec2(-350, -95)); @@ -54,114 +62,143 @@ float StartSubScene::create(Scene & scn, float begin_x) { } void StartSubScene::add_lamp(GameObject & obj, vec2 offset, unsigned int fps) { - Asset lamp_asset{"asset/background/start/alarmLight_TVOS.png"}; - obj.add_component(lamp_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset, - }); - Asset lamp_glow_asset{"asset/background/start/alarmGlow_TVOS.png"}; + Asset lamp_asset {"asset/background/start/alarmLight_TVOS.png"}; + obj.add_component( + lamp_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset, + } + ); + Asset lamp_glow_asset {"asset/background/start/alarmGlow_TVOS.png"}; Sprite & lamp_glow_sprite = obj.add_component( - lamp_glow_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 300), - .position_offset = offset - vec2(65, -55), - }); + lamp_glow_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 300), + .position_offset = offset - vec2(65, -55), + } + ); lamp_glow_sprite.active = false; - obj.add_component(lamp_glow_sprite, ivec2(422, 384), uvec2(6, 1), - Animator::Data{ - .fps = fps, - .looping = true, - }); + obj.add_component( + lamp_glow_sprite, ivec2(422, 384), uvec2(6, 1), + Animator::Data { + .fps = fps, + .looping = true, + } + ); } void StartSubScene::add_table(GameObject & obj, vec2 offset) { - Asset table_asset{"asset/background/start/table.png"}; - obj.add_component(table_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset, - }); - Asset gramophone_asset{"asset/background/start/gramophone_TVOS.png"}; + Asset table_asset {"asset/background/start/table.png"}; + obj.add_component( + table_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset, + } + ); + Asset gramophone_asset {"asset/background/start/gramophone_TVOS.png"}; Sprite & gramophone_sprite = obj.add_component( - gramophone_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 100), - .position_offset = offset + vec2(0, -50), - }); - obj.add_component(gramophone_sprite, ivec2(64, 128), uvec2(2, 1), - Animator::Data{ - .fps = 10, - .looping = true, - }); + gramophone_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 100), + .position_offset = offset + vec2(0, -50), + } + ); + obj.add_component( + gramophone_sprite, ivec2(64, 128), uvec2(2, 1), + Animator::Data { + .fps = 10, + .looping = true, + } + ); } void StartSubScene::add_light(crepe::GameObject & obj, crepe::vec2 offset) { - Asset light_asset{"asset/background/start/title_light_TVOS.png"}; - obj.add_component(light_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 200), - .position_offset = offset, - }); - Asset light_glow_asset{"asset/background/start/lightEffect2.png"}; - obj.add_component(light_glow_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 100), - .position_offset = offset + vec2(0, 75), - }); - Asset light_effect_asset{"asset/background/start/lightEffect.png"}; - obj.add_component(light_effect_asset, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - .position_offset = offset + vec2(0, 350), - }); + Asset light_asset {"asset/background/start/title_light_TVOS.png"}; + obj.add_component( + light_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 200), + .position_offset = offset, + } + ); + Asset light_glow_asset {"asset/background/start/lightEffect2.png"}; + obj.add_component( + light_glow_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 100), + .position_offset = offset + vec2(0, 75), + } + ); + Asset light_effect_asset {"asset/background/start/lightEffect.png"}; + obj.add_component( + light_effect_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + .position_offset = offset + vec2(0, 350), + } + ); } void StartSubScene::add_jetpack_stand(crepe::GameObject & obj, crepe::vec2 offset) { - Asset jetpack_stand_asset{"asset/background/start/JetpackStand.png"}; + Asset jetpack_stand_asset {"asset/background/start/JetpackStand.png"}; Sprite & jetpeck_stand_sprite = obj.add_component( - jetpack_stand_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 70), - .position_offset = offset, - }); - obj.add_component(jetpeck_stand_sprite, ivec2(34, 46), uvec2(2, 1), - Animator::Data{ - .fps = 10, - .looping = true, - }) + jetpack_stand_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 70), + .position_offset = offset, + } + ); + obj.add_component( + jetpeck_stand_sprite, ivec2(34, 46), uvec2(2, 1), + Animator::Data { + .fps = 10, + .looping = true, + } + ) .pause(); Asset do_not_steal = {"asset/background/start/doNotTouchSign_TVOS.png"}; - obj.add_component(do_not_steal, - Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 1, - .size = vec2(0, 100), - .position_offset = offset + vec2(-75, -25), - }); + obj.add_component( + do_not_steal, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 1, + .size = vec2(0, 100), + .position_offset = offset + vec2(-75, -25), + } + ); } void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { GameObject frag_1 = scn.new_object("frag_1", "wall_fragment", vec2(begin_x, 200)); - Asset frag_1_asset{"asset/background/start/StartWall_frag1.png"}; + Asset frag_1_asset {"asset/background/start/StartWall_frag1.png"}; Sprite & frag_1_sprite = frag_1.add_component( - frag_1_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_1_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_1_sprite.active = false; - Rigidbody & frag_1_rb = frag_1.add_component(Rigidbody::Data{ + Rigidbody & frag_1_rb = frag_1.add_component(Rigidbody::Data { .gravity_scale = 10, .linear_velocity = vec2(400, 400), .linear_velocity_coefficient = vec2(0.5, 0.6), @@ -175,15 +212,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_1.add_component(25); GameObject frag_2 = scn.new_object("frag_2", "wall_fragment", vec2(begin_x, 180)); - Asset frag_2_asset{"asset/background/start/StartWall_frag2.png"}; + Asset frag_2_asset {"asset/background/start/StartWall_frag2.png"}; Sprite & frag_2_sprite = frag_2.add_component( - frag_2_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_2_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_2_sprite.active = false; - Rigidbody & frag_2_rb = frag_2.add_component(Rigidbody::Data{ + Rigidbody & frag_2_rb = frag_2.add_component(Rigidbody::Data { .gravity_scale = 20, .linear_velocity = vec2(400, 400), .linear_velocity_coefficient = vec2(0.35, 0.4), @@ -197,15 +236,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_2.add_component(55); GameObject frag_3 = scn.new_object("frag_3", "wall_fragment", vec2(begin_x, 170)); - Asset frag_3_asset{"asset/background/start/StartWall_frag3.png"}; + Asset frag_3_asset {"asset/background/start/StartWall_frag3.png"}; Sprite & frag_3_sprite = frag_3.add_component( - frag_3_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_3_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_3_sprite.active = false; - Rigidbody & frag_3_rb = frag_3.add_component(Rigidbody::Data{ + Rigidbody & frag_3_rb = frag_3.add_component(Rigidbody::Data { .gravity_scale = 30, .linear_velocity = vec2(400, 400), .linear_velocity_coefficient = vec2(0.3, 0.3), @@ -219,15 +260,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_3.add_component(35); GameObject frag_4 = scn.new_object("frag_4", "wall_fragment", vec2(begin_x, 160)); - Asset frag_4_asset{"asset/background/start/StartWall_frag4.png"}; + Asset frag_4_asset {"asset/background/start/StartWall_frag4.png"}; Sprite & frag_4_sprite = frag_4.add_component( - frag_4_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_4_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_4_sprite.active = false; - Rigidbody & frag_4_rb = frag_4.add_component(Rigidbody::Data{ + Rigidbody & frag_4_rb = frag_4.add_component(Rigidbody::Data { .gravity_scale = 40, .linear_velocity = vec2(700, 400), .linear_velocity_coefficient = vec2(0.2, 0.2), @@ -241,15 +284,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_4.add_component(60); GameObject frag_5 = scn.new_object("frag_5", "wall_fragment", vec2(begin_x, 150)); - Asset frag_5_asset{"asset/background/start/StartWall_frag5.png"}; + Asset frag_5_asset {"asset/background/start/StartWall_frag5.png"}; Sprite & frag_5_sprite = frag_5.add_component( - frag_5_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_5_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_5_sprite.active = false; - Rigidbody & frag_5_rb = frag_5.add_component(Rigidbody::Data{ + Rigidbody & frag_5_rb = frag_5.add_component(Rigidbody::Data { .gravity_scale = 50, .linear_velocity = vec2(600, 800), .linear_velocity_coefficient = vec2(0.25, 0.15), @@ -263,15 +308,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_5.add_component(5); GameObject frag_6 = scn.new_object("frag_6", "wall_fragment", vec2(begin_x, 140)); - Asset frag_6_asset{"asset/background/start/StartWall_frag6.png"}; + Asset frag_6_asset {"asset/background/start/StartWall_frag6.png"}; Sprite & frag_6_sprite = frag_6.add_component( - frag_6_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_6_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_6_sprite.active = false; - Rigidbody & frag_6_rb = frag_6.add_component(Rigidbody::Data{ + Rigidbody & frag_6_rb = frag_6.add_component(Rigidbody::Data { .gravity_scale = 30, .linear_velocity = vec2(300, 800), .linear_velocity_coefficient = vec2(0.35, 0.25), @@ -285,15 +332,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_6.add_component(30); GameObject frag_7 = scn.new_object("frag_7", "wall_fragment", vec2(begin_x, 130)); - Asset frag_7_asset{"asset/background/start/StartWall_frag7.png"}; + Asset frag_7_asset {"asset/background/start/StartWall_frag7.png"}; Sprite & frag_7_sprite = frag_7.add_component( - frag_7_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_7_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_7_sprite.active = false; - Rigidbody & frag_7_rb = frag_7.add_component(Rigidbody::Data{ + Rigidbody & frag_7_rb = frag_7.add_component(Rigidbody::Data { .gravity_scale = 20, .linear_velocity = vec2(400, 500), .linear_velocity_coefficient = vec2(0.45, 0.6), @@ -307,15 +356,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_7.add_component(45); GameObject frag_8 = scn.new_object("frag_8", "wall_fragment", vec2(begin_x, 120)); - Asset frag_8_asset{"asset/background/start/StartWall_frag8.png"}; + Asset frag_8_asset {"asset/background/start/StartWall_frag8.png"}; Sprite & frag_8_sprite = frag_8.add_component( - frag_8_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_8_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_8_sprite.active = false; - Rigidbody & frag_8_rb = frag_8.add_component(Rigidbody::Data{ + Rigidbody & frag_8_rb = frag_8.add_component(Rigidbody::Data { .gravity_scale = 30, .linear_velocity = vec2(400, 400), .linear_velocity_coefficient = vec2(0.5, 0.6), @@ -329,15 +380,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_8.add_component(25); GameObject frag_9 = scn.new_object("frag_9", "wall_fragment", vec2(begin_x, 110)); - Asset frag_9_asset{"asset/background/start/StartWall_frag9.png"}; + Asset frag_9_asset {"asset/background/start/StartWall_frag9.png"}; Sprite & frag_9_sprite = frag_9.add_component( - frag_9_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_9_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_9_sprite.active = false; - Rigidbody & frag_9_rb = frag_9.add_component(Rigidbody::Data{ + Rigidbody & frag_9_rb = frag_9.add_component(Rigidbody::Data { .gravity_scale = 40, .linear_velocity = vec2(200, 400), .linear_velocity_coefficient = vec2(0.5, 0.25), @@ -351,15 +404,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_9.add_component(15); GameObject frag_10 = scn.new_object("frag_10", "wall_fragment", vec2(begin_x, 100)); - Asset frag_10_asset{"asset/background/start/StartWall_frag10.png"}; + Asset frag_10_asset {"asset/background/start/StartWall_frag10.png"}; Sprite & frag_10_sprite = frag_10.add_component( - frag_10_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_10_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_10_sprite.active = false; - Rigidbody & frag_10_rb = frag_10.add_component(Rigidbody::Data{ + Rigidbody & frag_10_rb = frag_10.add_component(Rigidbody::Data { .gravity_scale = 50, .linear_velocity = vec2(400, 900), .linear_velocity_coefficient = vec2(0.35, 0.4), @@ -373,15 +428,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_10.add_component(60); GameObject frag_11 = scn.new_object("frag_11", "wall_fragment", vec2(begin_x, 70)); - Asset frag_11_asset{"asset/background/start/StartWall_frag11.png"}; + Asset frag_11_asset {"asset/background/start/StartWall_frag11.png"}; Sprite & frag_11_sprite = frag_11.add_component( - frag_11_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_11_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_11_sprite.active = false; - Rigidbody & frag_11_rb = frag_11.add_component(Rigidbody::Data{ + Rigidbody & frag_11_rb = frag_11.add_component(Rigidbody::Data { .gravity_scale = 60, .linear_velocity = vec2(600, 800), .linear_velocity_coefficient = vec2(0.3, 0.3), @@ -395,15 +452,17 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { frag_11.add_component(5); GameObject frag_12 = scn.new_object("frag_12", "wall_fragment", vec2(begin_x, 80)); - Asset frag_12_asset{"asset/background/start/StartWall_frag12.png"}; + Asset frag_12_asset {"asset/background/start/StartWall_frag12.png"}; Sprite & frag_12_sprite = frag_12.add_component( - frag_12_asset, Sprite::Data{ - .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, - .order_in_layer = 5, - .size = vec2(0, 50), - }); + frag_12_asset, + Sprite::Data { + .sorting_in_layer = SORT_IN_LAY_FORE_BACKGROUND, + .order_in_layer = 5, + .size = vec2(0, 50), + } + ); frag_12_sprite.active = false; - Rigidbody & frag_12_rb = frag_12.add_component(Rigidbody::Data{ + Rigidbody & frag_12_rb = frag_12.add_component(Rigidbody::Data { .gravity_scale = 70, .linear_velocity = vec2(500, 800), .linear_velocity_coefficient = vec2(0.25, 0.15), @@ -418,43 +477,51 @@ void StartSubScene::create_wall_fragments(crepe::Scene & scn, float begin_x) { GameObject smoke_particles_1 = scn.new_object("smoke_particles", "particle_emitter", vec2(begin_x - 100, 200)); - Asset smoke_asset_1{"asset/particles/smoke.png"}; + Asset smoke_asset_1 {"asset/particles/smoke.png"}; Sprite & smoke_sprite_1 = smoke_particles_1.add_component( - smoke_asset_1, Sprite::Data{ - .color = Color(255, 255, 255, 50), - .sorting_in_layer = SORT_IN_LAY_PARTICLES_FOREGROUND, - .order_in_layer = 0, - .size = vec2(0, 100), - }); + smoke_asset_1, + Sprite::Data { + .color = Color(255, 255, 255, 50), + .sorting_in_layer = SORT_IN_LAY_PARTICLES_FOREGROUND, + .order_in_layer = 0, + .size = vec2(0, 100), + } + ); ParticleEmitter & emitter_1 = smoke_particles_1.add_component( - smoke_sprite_1, ParticleEmitter::Data{ - .emission_rate = 20, - .min_speed = 40, - .max_speed = 100, - .min_angle = -30, - .max_angle = 10, - .end_lifespan = 4, - }); + smoke_sprite_1, + ParticleEmitter::Data { + .emission_rate = 20, + .min_speed = 40, + .max_speed = 100, + .min_angle = -30, + .max_angle = 10, + .end_lifespan = 4, + } + ); emitter_1.active = false; GameObject smoke_particles_2 = scn.new_object("smoke_particles", "particle_emitter", vec2(begin_x - 100, 200)); - Asset smoke_asset_2{"asset/particles/smoke.png"}; + Asset smoke_asset_2 {"asset/particles/smoke.png"}; Sprite & smoke_sprite_2 = smoke_particles_2.add_component( - smoke_asset_2, Sprite::Data{ - .color = Color(255, 255, 255, 50), - .sorting_in_layer = SORT_IN_LAY_PARTICLES_FOREGROUND, - .order_in_layer = 0, - .size = vec2(0, 70), - }); + smoke_asset_2, + Sprite::Data { + .color = Color(255, 255, 255, 50), + .sorting_in_layer = SORT_IN_LAY_PARTICLES_FOREGROUND, + .order_in_layer = 0, + .size = vec2(0, 70), + } + ); ParticleEmitter & emitter_2 = smoke_particles_2.add_component( - smoke_sprite_2, ParticleEmitter::Data{ - .emission_rate = 30, - .min_speed = 40, - .max_speed = 100, - .min_angle = -45, - .max_angle = 5, - .end_lifespan = 3, - }); + smoke_sprite_2, + ParticleEmitter::Data { + .emission_rate = 30, + .min_speed = 40, + .max_speed = 100, + .min_angle = -45, + .max_angle = 5, + .end_lifespan = 3, + } + ); emitter_2.active = false; } diff --git a/mwe/ecs-homemade/inc/ComponentManager.hpp b/mwe/ecs-homemade/inc/ComponentManager.hpp index af9c3a1..7d26df4 100644 --- a/mwe/ecs-homemade/inc/ComponentManager.hpp +++ b/mwe/ecs-homemade/inc/ComponentManager.hpp @@ -54,8 +54,8 @@ void ComponentManager::DeleteComponents() { } template -std::vector> -ComponentManager::GetComponentsByID(std::uint32_t id) const { +std::vector> ComponentManager::GetComponentsByID(std::uint32_t id +) const { //Determine the type of T (this is used as the key of the unordered_map<>) std::type_index type = typeid(T); diff --git a/mwe/ecs-homemade/src/ComponentManager.cpp b/mwe/ecs-homemade/src/ComponentManager.cpp index 33ba12e..835bdda 100644 --- a/mwe/ecs-homemade/src/ComponentManager.cpp +++ b/mwe/ecs-homemade/src/ComponentManager.cpp @@ -9,9 +9,8 @@ ComponentManager::ComponentManager() {} void ComponentManager::DeleteAllComponentsOfId(std::uint32_t id) { for (auto & [type, componentArray] : mComponents) { //Loop through all the types (in the unordered_map<>) - if (id - < componentArray - .size()) { //Make sure that the id (that we are looking for) is within the boundaries of the vector<> + if (id < componentArray.size( + )) { //Make sure that the id (that we are looking for) is within the boundaries of the vector<> componentArray[id].clear(); //Clear the components at this specific id } } diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index ee1bf52..6df98ee 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -27,8 +27,8 @@ public: virtual ~Event() = default; virtual std::uint32_t getEventType() const = 0; virtual std::string toString() const; - void addArgument(const std::string & key, - const std::variant & value); + void + addArgument(const std::string & key, const std::variant & value); std::variant getArgument(const std::string & key) const; diff --git a/mwe/events/include/eventHandler.h b/mwe/events/include/eventHandler.h index 3a83b15..8598cee 100644 --- a/mwe/events/include/eventHandler.h +++ b/mwe/events/include/eventHandler.h @@ -22,8 +22,9 @@ private: template class EventHandlerWrapper : public IEventHandlerWrapper { public: - explicit EventHandlerWrapper(const EventHandler & handler, - const bool destroyOnSuccess = false) + explicit EventHandlerWrapper( + const EventHandler & handler, const bool destroyOnSuccess = false + ) : m_handler(handler), m_handlerType(m_handler.target_type().name()), m_destroyOnSuccess(destroyOnSuccess) { @@ -42,5 +43,5 @@ private: EventHandler m_handler; const std::string m_handlerType; - bool m_destroyOnSuccess{false}; + bool m_destroyOnSuccess {false}; }; diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h index 30e927f..43906e8 100644 --- a/mwe/events/include/eventManager.h +++ b/mwe/events/include/eventManager.h @@ -18,8 +18,8 @@ public: } void shutdown(); - void subscribe(int eventType, std::unique_ptr && handler, - int eventId); + void + subscribe(int eventType, std::unique_ptr && handler, int eventId); void unsubscribe(int eventType, const std::string & handlerName, int eventId); void triggerEvent(const Event & event_, int eventId); void queueEvent(std::unique_ptr && event_, int eventId); @@ -35,19 +35,23 @@ private: }; template -inline void subscribe(const EventHandler & callback, int eventId = 0, - const bool unsubscribeOnSuccess = false) { +inline void subscribe( + const EventHandler & callback, int eventId = 0, + const bool unsubscribeOnSuccess = false +) { std::unique_ptr handler = std::make_unique>(callback, unsubscribeOnSuccess); - EventManager::getInstance().subscribe(EventType::getStaticEventType(), std::move(handler), - eventId); + EventManager::getInstance().subscribe( + EventType::getStaticEventType(), std::move(handler), eventId + ); } template inline void unsubscribe(const EventHandler & callback, int eventId = 0) { const std::string handlerName = callback.target_type().name(); - EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), handlerName, - eventId); + EventManager::getInstance().unsubscribe( + EventType::getStaticEventType(), handlerName, eventId + ); } inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) { @@ -55,6 +59,7 @@ inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) { } inline void queueEvent(std::unique_ptr && queuedEvent, int eventId = 0) { - EventManager::getInstance().queueEvent(std::forward>(queuedEvent), - eventId); + EventManager::getInstance().queueEvent( + std::forward>(queuedEvent), eventId + ); } diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp index 0040c73..5177199 100644 --- a/mwe/events/src/event.cpp +++ b/mwe/events/src/event.cpp @@ -3,8 +3,9 @@ // Event class methods Event::Event(std::string eventType) { eventData["eventType"] = eventType; } -void Event::addArgument(const std::string & key, - const std::variant & value) { +void Event::addArgument( + const std::string & key, const std::variant & value +) { eventData[key] = value; } diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp index 9e7d880..b77a0a3 100644 --- a/mwe/events/src/eventManager.cpp +++ b/mwe/events/src/eventManager.cpp @@ -2,8 +2,9 @@ void EventManager::shutdown() { subscribers.clear(); } -void EventManager::subscribe(int eventType, std::unique_ptr && handler, - int eventId) { +void EventManager::subscribe( + int eventType, std::unique_ptr && handler, int eventId +) { if (eventId) { std::unordered_map< int, std::unordered_map>>>:: diff --git a/mwe/events/src/loopManager.cpp b/mwe/events/src/loopManager.cpp index c58a5e7..7be10df 100644 --- a/mwe/events/src/loopManager.cpp +++ b/mwe/events/src/loopManager.cpp @@ -51,8 +51,10 @@ void onKey(const KeyPressedEvent & e) { std::cout << "keycode pressed: " << keyCode << std::endl; } void onMouse(const MousePressedEvent & e) { - fprintf(stderr, "mouse Position X: %d Y: %d\n", e.getMousePosition().first, - e.getMousePosition().second); + fprintf( + stderr, "mouse Position X: %d Y: %d\n", e.getMousePosition().first, + e.getMousePosition().second + ); } void LoopManager::setup() { gameRunning = window.initWindow(); diff --git a/mwe/events/src/uiObject.cpp b/mwe/events/src/uiObject.cpp index 947d1a2..6b5b326 100644 --- a/mwe/events/src/uiObject.cpp +++ b/mwe/events/src/uiObject.cpp @@ -10,7 +10,7 @@ Text::Text(int width, int height) : UIObject(width, height), size(12), font(nullptr), - color{255, 255, 255} { // Default size and color + color {255, 255, 255} { // Default size and color alignment.horizontal = Alignment::Horizontal::CENTER; alignment.vertical = Alignment::Vertical::MIDDLE; alignment.mode = Alignment::PositioningMode::RELATIVE; @@ -21,8 +21,8 @@ TextInput::TextInput(int width, int height) textBuffer(""), placeholder(""), isActive(false), - textColor{255, 255, 255}, - backgroundColor{0, 0, 0}, + textColor {255, 255, 255}, + backgroundColor {0, 0, 0}, maxLength(100), font(nullptr) { alignment.horizontal = Alignment::Horizontal::LEFT; diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp index af2b627..5cdd425 100644 --- a/mwe/events/src/window.cpp +++ b/mwe/events/src/window.cpp @@ -11,8 +11,10 @@ bool WindowManager::initWindow() { return false; } - window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + window = SDL_CreateWindow( + "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, + SCREEN_HEIGHT, SDL_WINDOW_SHOWN + ); if (!window) { std::cerr << "Error creating SDL Window.\n"; return false; diff --git a/mwe/gameloop/include/gameObject.h b/mwe/gameloop/include/gameObject.h index 2764215..1955b59 100644 --- a/mwe/gameloop/include/gameObject.h +++ b/mwe/gameloop/include/gameObject.h @@ -3,8 +3,9 @@ class GameObject { public: GameObject(); - GameObject(std::string name, float x, float y, float width, float height, float velX, - float velY); + GameObject( + std::string name, float x, float y, float width, float height, float velX, float velY + ); std::string getName() const; float getX() const; float getY() const; diff --git a/mwe/gameloop/src/gameObject.cpp b/mwe/gameloop/src/gameObject.cpp index 809e25f..31503d1 100644 --- a/mwe/gameloop/src/gameObject.cpp +++ b/mwe/gameloop/src/gameObject.cpp @@ -24,8 +24,9 @@ void GameObject::setVelX(float value) { velX = value; } void GameObject::setVelY(float value) { velY = value; } -GameObject::GameObject(std::string name, float x, float y, float width, float height, - float velX, float velY) +GameObject::GameObject( + std::string name, float x, float y, float width, float height, float velX, float velY +) : name(name), x(x), y(y), diff --git a/mwe/gameloop/src/loopManager.cpp b/mwe/gameloop/src/loopManager.cpp index fb06995..70cea4c 100644 --- a/mwe/gameloop/src/loopManager.cpp +++ b/mwe/gameloop/src/loopManager.cpp @@ -18,11 +18,13 @@ void LoopManager::processInput() { if (event.key.keysym.sym == SDLK_ESCAPE) { gameRunning = false; } else if (event.key.keysym.sym == SDLK_i) { - LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale() - + 0.1); + LoopTimer::getInstance().setGameScale( + LoopTimer::getInstance().getGameScale() + 0.1 + ); } else if (event.key.keysym.sym == SDLK_k) { - LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale() - - 0.1); + LoopTimer::getInstance().setGameScale( + LoopTimer::getInstance().getGameScale() - 0.1 + ); } break; diff --git a/mwe/gameloop/src/window.cpp b/mwe/gameloop/src/window.cpp index 8f802e1..df17773 100644 --- a/mwe/gameloop/src/window.cpp +++ b/mwe/gameloop/src/window.cpp @@ -36,8 +36,10 @@ bool WindowManager::initWindow() { fprintf(stderr, "Error inititalising SDL.\n"); return false; } - window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + window = SDL_CreateWindow( + "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, + SCREEN_HEIGHT, SDL_WINDOW_SHOWN + ); if (!window) { fprintf(stderr, "Error creating SDL Window. \n"); return false; diff --git a/mwe/resource-manager/main.cpp b/mwe/resource-manager/main.cpp index 1910af8..e83d35f 100644 --- a/mwe/resource-manager/main.cpp +++ b/mwe/resource-manager/main.cpp @@ -23,8 +23,9 @@ int main() { SDL_Event event; - SDL_Window * window = SDL_CreateWindow("Tessting resources", SDL_WINDOWPOS_UNDEFINED, - SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); + SDL_Window * window = SDL_CreateWindow( + "Tessting resources", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0 + ); SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); diff --git a/mwe/resource-manager/map_layer.cpp b/mwe/resource-manager/map_layer.cpp index 17792a6..82f8f24 100644 --- a/mwe/resource-manager/map_layer.cpp +++ b/mwe/resource-manager/map_layer.cpp @@ -9,8 +9,9 @@ MapLayer::MapLayer() {} MapLayer::~MapLayer() { m_subsets.clear(); } -bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, - const std::vector & textures) { +bool MapLayer::create( + const tmx::Map & map, std::uint32_t layerIndex, const std::vector & textures +) { const auto & layers = map.getLayers(); assert(layers[layerIndex]->getType() == tmx::Layer::Type::Tile); @@ -68,9 +69,10 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, verts.emplace_back(vert); vert = {{tilePosX + mapTileSize.x, tilePosY}, vertColour, {u + uNorm, v}}; verts.emplace_back(vert); - vert = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y}, - vertColour, - {u + uNorm, v + vNorm}}; + vert + = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y}, + vertColour, + {u + uNorm, v + vNorm}}; verts.emplace_back(vert); } } @@ -89,7 +91,9 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex, void MapLayer::draw(SDL_Renderer * renderer) const { assert(renderer); for (const auto & s : m_subsets) { - SDL_RenderGeometry(renderer, s.texture, s.vertexData.data(), - static_cast(s.vertexData.size()), nullptr, 0); + SDL_RenderGeometry( + renderer, s.texture, s.vertexData.data(), + static_cast(s.vertexData.size()), nullptr, 0 + ); } } diff --git a/mwe/resource-manager/map_layer.h b/mwe/resource-manager/map_layer.h index fb656ed..2adbc0f 100644 --- a/mwe/resource-manager/map_layer.h +++ b/mwe/resource-manager/map_layer.h @@ -10,8 +10,8 @@ public: explicit MapLayer(); ~MapLayer(); - bool create(const tmx::Map &, std::uint32_t index, - const std::vector & textures); + bool + create(const tmx::Map &, std::uint32_t index, const std::vector & textures); void draw(SDL_Renderer *) const; private: diff --git a/mwe/resource-manager/stb_image.h b/mwe/resource-manager/stb_image.h index 3462f3a..43fa6a6 100644 --- a/mwe/resource-manager/stb_image.h +++ b/mwe/resource-manager/stb_image.h @@ -409,9 +409,12 @@ extern "C" { typedef struct { int (*read)( void * user, char * data, - int size); // fill 'data' with 'size' bytes. return number of bytes actually read - void (*skip)(void * user, - int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int size + ); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip)( + void * user, + int n + ); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof)(void * user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; @@ -420,24 +423,29 @@ typedef struct { // 8-bits-per-channel interface // -STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user, - int * x, int * y, int * channels_in_file, - int desired_channels); +STBIDEF stbi_uc * stbi_load_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * channels_in_file, + int desired_channels +); +STBIDEF stbi_uc * stbi_load_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * channels_in_file, + int desired_channels +); #ifndef STBI_NO_STDIO -STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * channels_in_file, - int desired_channels); -STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * channels_in_file, - int desired_channels); +STBIDEF stbi_uc * stbi_load( + char const * filename, int * x, int * y, int * channels_in_file, int desired_channels +); +STBIDEF stbi_uc * +stbi_load_from_file(FILE * f, int * x, int * y, int * channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_GIF -STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays, - int * x, int * y, int * z, int * comp, - int req_comp); +STBIDEF stbi_uc * stbi_load_gif_from_memory( + stbi_uc const * buffer, int len, int ** delays, int * x, int * y, int * z, int * comp, + int req_comp +); #endif #ifdef STBI_WINDOWS_UTF8 @@ -449,17 +457,22 @@ STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, const wc // 16-bits-per-channel interface // -STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user, - int * x, int * y, int * channels_in_file, - int desired_channels); +STBIDEF stbi_us * stbi_load_16_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * channels_in_file, + int desired_channels +); +STBIDEF stbi_us * stbi_load_16_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * channels_in_file, + int desired_channels +); #ifndef STBI_NO_STDIO -STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * channels_in_file, - int desired_channels); -STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, int * channels_in_file, - int desired_channels); +STBIDEF stbi_us * stbi_load_16( + char const * filename, int * x, int * y, int * channels_in_file, int desired_channels +); +STBIDEF stbi_us * stbi_load_from_file_16( + FILE * f, int * x, int * y, int * channels_in_file, int desired_channels +); #endif //////////////////////////////////// @@ -467,17 +480,21 @@ STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, int * chann // float-per-channel interface // #ifndef STBI_NO_LINEAR -STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * channels_in_file, int desired_channels); -STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, - int * y, int * channels_in_file, - int desired_channels); +STBIDEF float * stbi_loadf_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * channels_in_file, + int desired_channels +); +STBIDEF float * stbi_loadf_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * channels_in_file, + int desired_channels +); #ifndef STBI_NO_STDIO -STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * channels_in_file, - int desired_channels); -STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * channels_in_file, - int desired_channels); +STBIDEF float * stbi_loadf( + char const * filename, int * x, int * y, int * channels_in_file, int desired_channels +); +STBIDEF float * +stbi_loadf_from_file(FILE * f, int * x, int * y, int * channels_in_file, int desired_channels); #endif #endif @@ -507,10 +524,11 @@ STBIDEF const char * stbi_failure_reason(void); STBIDEF void stbi_image_free(void * retval_from_stbi_load); // get image dimensions & components without fully decoding -STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * comp); -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, - int * y, int * comp); +STBIDEF int +stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, int * comp); +STBIDEF int stbi_info_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * comp +); STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const * buffer, int len); STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * clbk, void * user); @@ -542,17 +560,18 @@ STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_fli // ZLIB client - used by PNG, available for other purposes -STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len, - int initial_size, int * outlen); -STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len, - int initial_size, int * outlen, - int parse_header); +STBIDEF char * stbi_zlib_decode_malloc_guesssize( + const char * buffer, int len, int initial_size, int * outlen +); +STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag( + const char * buffer, int len, int initial_size, int * outlen, int parse_header +); STBIDEF char * stbi_zlib_decode_malloc(const char * buffer, int len, int * outlen); STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, const char * ibuffer, int ilen); STBIDEF char * stbi_zlib_decode_noheader_malloc(const char * buffer, int len, int * outlen); -STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, - int ilen); +STBIDEF int +stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, int ilen); #ifdef __cplusplus } @@ -910,68 +929,79 @@ typedef struct { #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context * s); -static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__jpeg_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__jpeg_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context * s); -static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__png_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__png_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__png_is16(stbi__context * s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context * s); -static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__bmp_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__bmp_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context * s); -static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__tga_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context * s); -static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri, int bpc); +static void * stbi__psd_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri, + int bpc +); static int stbi__psd_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__psd_is16(stbi__context * s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context * s); -static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static float * stbi__hdr_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__hdr_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context * s); -static void * stbi__pic_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__pic_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__pic_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context * s); -static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); -static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z, - int * comp, int req_comp); +static void * stbi__gif_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); +static void * stbi__load_gif_main( + stbi__context * s, int ** delays, int * x, int * y, int * z, int * comp, int req_comp +); static int stbi__gif_info(stbi__context * s, int * x, int * y, int * comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context * s); -static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri); +static void * stbi__pnm_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +); static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp); static int stbi__pnm_is16(stbi__context * s); #endif @@ -1135,8 +1165,10 @@ STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_fli : stbi__vertically_flip_on_load_global) #endif // STBI_THREAD_LOCAL -static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri, int bpc) { +static void * stbi__load_main( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri, + int bpc +) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed @@ -1198,9 +1230,8 @@ static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h, int ch if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) - reduced[i] - = (stbi_uc) ((orig[i] >> 8) - & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + reduced[i] = (stbi_uc) ((orig[i] >> 8) & 0xFF + ); // top half of each byte is sufficient approx of 16->8 bit scaling STBI_FREE(orig); return reduced; @@ -1215,10 +1246,8 @@ static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h, int ch if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) - enlarged[i] - = (stbi__uint16) ((orig[i] << 8) - + orig - [i]); // replicate to high and low byte, maps 0->0, 255->0xffff + enlarged[i] = (stbi__uint16) ((orig[i] << 8) + orig[i] + ); // replicate to high and low byte, maps 0->0, 255->0xffff STBI_FREE(orig); return enlarged; @@ -1248,8 +1277,8 @@ static void stbi__vertical_flip(void * image, int w, int h, int bytes_per_pixel) } #ifndef STBI_NO_GIF -static void stbi__vertical_flip_slices(void * image, int w, int h, int z, - int bytes_per_pixel) { +static void +stbi__vertical_flip_slices(void * image, int w, int h, int z, int bytes_per_pixel) { int slice; int slice_size = w * h * bytes_per_pixel; @@ -1261,8 +1290,9 @@ static void stbi__vertical_flip_slices(void * image, int w, int h, int z, } #endif -static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, int * x, int * y, - int * comp, int req_comp) { +static unsigned char * stbi__load_and_postprocess_8bit( + stbi__context * s, int * x, int * y, int * comp, int req_comp +) { stbi__result_info ri; void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); @@ -1272,8 +1302,9 @@ static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, int * STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 8) { - result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, - req_comp == 0 ? *comp : req_comp); + result = stbi__convert_16_to_8( + (stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp + ); ri.bits_per_channel = 8; } @@ -1287,8 +1318,9 @@ static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, int * return (unsigned char *) result; } -static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, int * x, int * y, - int * comp, int req_comp) { +static stbi__uint16 * stbi__load_and_postprocess_16bit( + stbi__context * s, int * x, int * y, int * comp, int req_comp +) { stbi__result_info ri; void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); @@ -1298,8 +1330,9 @@ static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, int * STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 16) { - result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, - req_comp == 0 ? *comp : req_comp); + result = stbi__convert_8_to_16( + (stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp + ); ri.bits_per_channel = 16; } @@ -1315,8 +1348,8 @@ static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, int * } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) -static void stbi__float_postprocess(float * result, int * x, int * y, int * comp, - int req_comp) { +static void +stbi__float_postprocess(float * result, int * x, int * y, int * comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); @@ -1328,19 +1361,22 @@ static void stbi__float_postprocess(float * result, int * x, int * y, int * comp #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBI_EXTERN -__declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, - const char * str, int cbmb, - wchar_t * widestr, int cchwide); +__declspec(dllimport) int __stdcall MultiByteToWideChar( + unsigned int cp, unsigned long flags, const char * str, int cbmb, wchar_t * widestr, + int cchwide +); STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte( unsigned int cp, unsigned long flags, const wchar_t * widestr, int cchwide, char * str, - int cbmb, const char * defchar, int * used_default); + int cbmb, const char * defchar, int * used_default +); #endif #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, - const wchar_t * input) { - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, - NULL); +STBIDEF int +stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, const wchar_t * input) { + return WideCharToMultiByte( + 65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL + ); } #endif @@ -1350,13 +1386,16 @@ static FILE * stbi__fopen(char const * filename, char const * mode) { wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 - == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, - sizeof(wFilename) / sizeof(*wFilename))) + == MultiByteToWideChar( + 65001 /* UTF8 */, 0, filename, -1, wFilename, + sizeof(wFilename) / sizeof(*wFilename) + )) return 0; if (0 - == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, - sizeof(wMode) / sizeof(*wMode))) + == MultiByteToWideChar( + 65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode) / sizeof(*wMode) + )) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 @@ -1373,8 +1412,8 @@ static FILE * stbi__fopen(char const * filename, char const * mode) { return f; } -STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * comp, - int req_comp) { +STBIDEF stbi_uc * +stbi_load(char const * filename, int * x, int * y, int * comp, int req_comp) { FILE * f = stbi__fopen(filename, "rb"); unsigned char * result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); @@ -1395,8 +1434,8 @@ STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp, in return result; } -STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, int * comp, - int req_comp) { +STBIDEF stbi__uint16 * +stbi_load_from_file_16(FILE * f, int * x, int * y, int * comp, int req_comp) { stbi__uint16 * result; stbi__context s; stbi__start_file(&s, f); @@ -1408,8 +1447,8 @@ STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, int * return result; } -STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * comp, - int req_comp) { +STBIDEF stbi_us * +stbi_load_16(char const * filename, int * x, int * y, int * comp, int req_comp) { FILE * f = stbi__fopen(filename, "rb"); stbi__uint16 * result; if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); @@ -1420,39 +1459,45 @@ STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * co #endif //!STBI_NO_STDIO -STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * channels_in_file, int desired_channels) { +STBIDEF stbi_us * stbi_load_16_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * channels_in_file, + int desired_channels +) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); } -STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user, - int * x, int * y, int * channels_in_file, - int desired_channels) { +STBIDEF stbi_us * stbi_load_16_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * channels_in_file, + int desired_channels +) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); } -STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * comp, int req_comp) { +STBIDEF stbi_uc * stbi_load_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * comp, int req_comp +) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } -STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user, - int * x, int * y, int * comp, int req_comp) { +STBIDEF stbi_uc * stbi_load_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * comp, int req_comp +) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } #ifndef STBI_NO_GIF -STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays, - int * x, int * y, int * z, int * comp, - int req_comp) { +STBIDEF stbi_uc * stbi_load_gif_from_memory( + stbi_uc const * buffer, int len, int ** delays, int * x, int * y, int * z, int * comp, + int req_comp +) { unsigned char * result; stbi__context s; stbi__start_mem(&s, buffer, len); @@ -1467,8 +1512,8 @@ STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int #endif #ifndef STBI_NO_LINEAR -static float * stbi__loadf_main(stbi__context * s, int * x, int * y, int * comp, - int req_comp) { +static float * +stbi__loadf_main(stbi__context * s, int * x, int * y, int * comp, int req_comp) { unsigned char * data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { @@ -1483,15 +1528,17 @@ static float * stbi__loadf_main(stbi__context * s, int * x, int * y, int * comp, return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } -STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * comp, int req_comp) { +STBIDEF float * stbi_loadf_from_memory( + stbi_uc const * buffer, int len, int * x, int * y, int * comp, int req_comp +) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__loadf_main(&s, x, y, comp, req_comp); } -STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x, - int * y, int * comp, int req_comp) { +STBIDEF float * stbi_loadf_from_callbacks( + stbi_io_callbacks const * clbk, void * user, int * x, int * y, int * comp, int req_comp +) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s, x, y, comp, req_comp); @@ -1745,8 +1792,9 @@ static stbi_uc stbi__compute_y(int r, int g, int b) { && defined(STBI_NO_PNM) // nothing #else -static unsigned char * stbi__convert_format(unsigned char * data, int img_n, int req_comp, - unsigned int x, unsigned int y) { +static unsigned char * stbi__convert_format( + unsigned char * data, int img_n, int req_comp, unsigned int x, unsigned int y +) { int i, j; unsigned char * good; @@ -1843,8 +1891,9 @@ static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else -static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, int req_comp, - unsigned int x, unsigned int y) { +static stbi__uint16 * stbi__convert_format16( + stbi__uint16 * data, int img_n, int req_comp, unsigned int x, unsigned int y +) { int i, j; stbi__uint16 * good; @@ -1920,8 +1969,9 @@ static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, int STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); - return (stbi__uint16 *) stbi__errpuc("unsupported", - "Unsupported format conversion"); + return (stbi__uint16 *) stbi__errpuc( + "unsupported", "Unsupported format conversion" + ); } #undef STBI__CASE } @@ -2079,10 +2129,13 @@ typedef struct { // kernels void (*idct_block_kernel)(stbi_uc * out, int out_stride, short data[64]); - void (*YCbCr_to_RGB_kernel)(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, - const stbi_uc * pcr, int count, int step); - stbi_uc * (*resample_row_hv_2_kernel)(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, - int w, int hs); + void (*YCbCr_to_RGB_kernel)( + stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, const stbi_uc * pcr, int count, + int step + ); + stbi_uc * (*resample_row_hv_2_kernel)( + stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs + ); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman * h, int * count) { @@ -2215,8 +2268,9 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, stbi__huffman * h) c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; if (c < 0 || c >= 256) // symbol id out of bounds! return -1; - STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) - == h->code[c]); + STBI_ASSERT( + (((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c] + ); // convert the id to a symbol j->code_bits -= k; @@ -2280,9 +2334,10 @@ static const stbi_uc stbi__jpeg_dezigzag[64 + 15] 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; // decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], stbi__huffman * hdc, - stbi__huffman * hac, stbi__int16 * fac, int b, - stbi__uint16 * dequant) { +static int stbi__jpeg_decode_block( + stbi__jpeg * j, short data[64], stbi__huffman * hdc, stbi__huffman * hac, + stbi__int16 * fac, int b, stbi__uint16 * dequant +) { int diff, dc, k; int t; @@ -2314,8 +2369,9 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], stbi__huffman k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) - return stbi__err("bad huffman code", - "Combined length longer than code bits available"); + return stbi__err( + "bad huffman code", "Combined length longer than code bits available" + ); j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location @@ -2340,8 +2396,8 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], stbi__huffman return 1; } -static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], stbi__huffman * hdc, - int b) { +static int +stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], stbi__huffman * hdc, int b) { int diff, dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); @@ -2371,8 +2427,9 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], stbi_ // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing -static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], stbi__huffman * hac, - stbi__int16 * fac) { +static int stbi__jpeg_decode_block_prog_ac( + stbi__jpeg * j, short data[64], stbi__huffman * hac, stbi__int16 * fac +) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); @@ -2395,8 +2452,9 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], stbi_ k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) - return stbi__err("bad huffman code", - "Combined length longer than code bits available"); + return stbi__err( + "bad huffman code", "Combined length longer than code bits available" + ); j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; @@ -2443,7 +2501,8 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], stbi_ int r, s; int rs = stbi__jpeg_huff_decode( j, - hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + hac + ); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); s = rs & 15; r = rs >> 4; @@ -2691,18 +2750,24 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) { = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f)); - __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), - stbi__f2f(1.175875602f)); - __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), - stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); - __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), - stbi__f2f(-1.961570560f)); - __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), - stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); - __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), - stbi__f2f(-0.390180644f)); - __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), - stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); + __m128i rot1_0 = dct_const( + stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f) + ); + __m128i rot1_1 = dct_const( + stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f) + ); + __m128i rot2_0 = dct_const( + stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), stbi__f2f(-1.961570560f) + ); + __m128i rot2_1 = dct_const( + stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f) + ); + __m128i rot3_0 = dct_const( + stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), stbi__f2f(-0.390180644f) + ); + __m128i rot3_1 = dct_const( + stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f) + ); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); @@ -3091,13 +3156,15 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { for (j = 0; j < h; ++j) { for (i = 0; i < w; ++i) { int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, - z->huff_ac + ha, z->fast_ac[ha], n, - z->dequant[z->img_comp[n].tq])) + if (!stbi__jpeg_decode_block( + z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, + z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq] + )) return 0; - z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 - + i * 8, - z->img_comp[n].w2, data); + z->idct_block_kernel( + z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, + z->img_comp[n].w2, data + ); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); @@ -3124,14 +3191,16 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { int x2 = (i * z->img_comp[n].h + x) * 8; int y2 = (j * z->img_comp[n].v + y) * 8; int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, - z->huff_dc + z->img_comp[n].hd, - z->huff_ac + ha, z->fast_ac[ha], - n, z->dequant[z->img_comp[n].tq])) + if (!stbi__jpeg_decode_block( + z, data, z->huff_dc + z->img_comp[n].hd, + z->huff_ac + ha, z->fast_ac[ha], n, + z->dequant[z->img_comp[n].tq] + )) return 0; - z->idct_block_kernel(z->img_comp[n].data - + z->img_comp[n].w2 * y2 + x2, - z->img_comp[n].w2, data); + z->idct_block_kernel( + z->img_comp[n].data + z->img_comp[n].w2 * y2 + x2, + z->img_comp[n].w2, data + ); } } } @@ -3162,12 +3231,14 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc( - z, data, &z->huff_dc[z->img_comp[n].hd], n)) + z, data, &z->huff_dc[z->img_comp[n].hd], n + )) return 0; } else { int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], - z->fast_ac[ha])) + if (!stbi__jpeg_decode_block_prog_ac( + z, data, &z->huff_ac[ha], z->fast_ac[ha] + )) return 0; } // every data block is an MCU, so countdown the restart interval @@ -3195,7 +3266,8 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) { short * data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc( - z, data, &z->huff_dc[z->img_comp[n].hd], n)) + z, data, &z->huff_dc[z->img_comp[n].hd], n + )) return 0; } } @@ -3231,9 +3303,10 @@ static void stbi__jpeg_finish(stbi__jpeg * z) { short * data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); - z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8 - + i * 8, - z->img_comp[n].w2, data); + z->idct_block_kernel( + z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, + z->img_comp[n].w2, data + ); } } } @@ -3283,7 +3356,8 @@ static int stbi__process_marker(stbi__jpeg * z, int m) { if (n > 256) return stbi__err( "bad DHT header", - "Corrupt JPEG"); // Loop over i < n would write past end of values! + "Corrupt JPEG" + ); // Loop over i < n would write past end of values! L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0; @@ -3410,13 +3484,16 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) - return stbi__err("only 8-bit", - "JPEG format not supported: 8-bit only"); // JPEG baseline + return stbi__err( + "only 8-bit", + "JPEG format not supported: 8-bit only" + ); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err( "no header height", - "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + "JPEG format not supported: delayed height" + ); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires if (s->img_y > STBI_MAX_DIMENSIONS) @@ -3493,8 +3570,9 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { z->img_comp[i].linebuf = NULL; z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) - return stbi__free_jpeg_components(z, i + 1, - stbi__err("outofmem", "Out of memory")); + return stbi__free_jpeg_components( + z, i + 1, stbi__err("outofmem", "Out of memory") + ); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc *) (((size_t) z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { @@ -3504,8 +3582,9 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) { z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) - return stbi__free_jpeg_components(z, i + 1, - stbi__err("outofmem", "Out of memory")); + return stbi__free_jpeg_components( + z, i + 1, stbi__err("outofmem", "Out of memory") + ); z->img_comp[i].coeff = (short *) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } } @@ -3603,13 +3682,14 @@ static int stbi__decode_jpeg_image(stbi__jpeg * j) { // static jfif-centered resampling (across block boundaries) -typedef stbi_uc * (*resample_row_func)(stbi_uc * out, stbi_uc * in0, stbi_uc * in1, int w, - int hs); +typedef stbi_uc * (*resample_row_func)( + stbi_uc * out, stbi_uc * in0, stbi_uc * in1, int w, int hs +); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) -static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, - int hs) { +static stbi_uc * +resample_row_1(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); @@ -3617,8 +3697,8 @@ static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_f return in_near; } -static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, - int w, int hs) { +static stbi_uc * +stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); @@ -3626,8 +3706,8 @@ static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, stbi_u return out; } -static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, - int w, int hs) { +static stbi_uc * +stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc * input = in_near; @@ -3656,8 +3736,8 @@ static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, stbi_u #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) -static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, - int w, int hs) { +static stbi_uc * +stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i, t0, t1; if (w == 1) { @@ -3681,8 +3761,9 @@ static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, stbi_ } #if defined(STBI_SSE2) || defined(STBI_NEON) -static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near, - stbi_uc * in_far, int w, int hs) { +static stbi_uc * stbi__resample_row_hv_2_simd( + stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs +) { // need to generate 2x2 samples for every one in input int i = 0, t0, t1; @@ -3797,8 +3878,8 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near, } #endif -static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, - int w, int hs) { +static stbi_uc * +stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w, int hs) { // resample with nearest-neighbor int i, j; STBI_NOTUSED(in_far); @@ -3810,8 +3891,10 @@ static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, st // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) -static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, - const stbi_uc * pcr, int count, int step) { +static void stbi__YCbCr_to_RGB_row( + stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb, const stbi_uc * pcr, int count, + int step +) { int i; for (i = 0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1 << 19); // rounding @@ -3846,8 +3929,10 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, const stbi_ } #if defined(STBI_SSE2) || defined(STBI_NEON) -static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, stbi_uc const * pcb, - stbi_uc const * pcr, int count, int step) { +static void stbi__YCbCr_to_RGB_simd( + stbi_uc * out, stbi_uc const * y, stbi_uc const * pcb, stbi_uc const * pcr, int count, + int step +) { int i = 0; #ifdef STBI_SSE2 @@ -4031,8 +4116,8 @@ static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { return (stbi_uc) ((t + (t >> 8)) >> 8); } -static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * comp, - int req_comp) { +static stbi_uc * +load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * comp, int req_comp) { int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe @@ -4107,8 +4192,10 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * for (k = 0; k < decode_n; ++k) { stbi__resample * r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); - coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, - y_bot ? r->line0 : r->line1, r->w_lores, r->hs); + coutput[k] = r->resample( + z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, r->w_lores, r->hs + ); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; @@ -4206,8 +4293,9 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * } } -static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__jpeg_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { unsigned char * result; stbi__jpeg * j = (stbi__jpeg *) stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__errpuc("outofmem", "Out of memory"); @@ -4432,8 +4520,10 @@ stbi_inline static int stbi__zhuffman_decode(stbi__zbuf * a, stbi__zhuffman * z) return stbi__zhuffman_decode_slowpath(a, z); } -static int stbi__zexpand(stbi__zbuf * z, char * zout, - int n) // need to make room for n bytes +static int stbi__zexpand( + stbi__zbuf * z, char * zout, + int n +) // need to make room for n bytes { char * q; unsigned int cur, limit, old_limit; @@ -4500,7 +4590,8 @@ static int stbi__parse_huffman_block(stbi__zbuf * a) { if (z >= 286) return stbi__err( "bad huffman code", - "Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + "Corrupt PNG" + ); // per DEFLATE, length codes 286 and 287 must not appear in compressed data z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); @@ -4508,7 +4599,8 @@ static int stbi__parse_huffman_block(stbi__zbuf * a) { if (z < 0 || z >= 30) return stbi__err( "bad huffman code", - "Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + "Corrupt PNG" + ); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG"); @@ -4617,8 +4709,10 @@ static int stbi__parse_zlib_header(stbi__zbuf * a) { if ((cmf * 256 + flg) % 31 != 0) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec if (flg & 32) - return stbi__err("no preset dict", - "Corrupt PNG"); // preset dictionary not allowed in png + return stbi__err( + "no preset dict", + "Corrupt PNG" + ); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression", "Corrupt PNG"); // DEFLATE required for png @@ -4692,8 +4786,9 @@ static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp, int par return stbi__parse_zlib(a, parse_header); } -STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len, - int initial_size, int * outlen) { +STBIDEF char * stbi_zlib_decode_malloc_guesssize( + const char * buffer, int len, int initial_size, int * outlen +) { stbi__zbuf a; char * p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; @@ -4712,9 +4807,9 @@ STBIDEF char * stbi_zlib_decode_malloc(char const * buffer, int len, int * outle return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } -STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len, - int initial_size, int * outlen, - int parse_header) { +STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag( + const char * buffer, int len, int initial_size, int * outlen, int parse_header +) { stbi__zbuf a; char * p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; @@ -4752,8 +4847,8 @@ STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len, in } } -STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, - int ilen) { +STBIDEF int +stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; @@ -4831,8 +4926,8 @@ static const stbi_uc stbi__depth_scale_table[9] = {0, 0xff, 0x55, 0, 0x11, 0, 0, // adds an extra all-255 alpha channel // dest == src is legal // img_n must be 1 or 3 -static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, stbi__uint32 x, - int img_n) { +static void +stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, stbi__uint32 x, int img_n) { int i; // must process data backwards since we allow dest==src if (img_n == 1) { @@ -4852,9 +4947,10 @@ static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, stbi__ } // create the png data from post-deflated data -static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 raw_len, - int out_n, stbi__uint32 x, stbi__uint32 y, int depth, - int color) { +static int stbi__create_png_image_raw( + stbi__png * a, stbi_uc * raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, + stbi__uint32 y, int depth, int color +) { int bytes = (depth == 16 ? 2 : 1); stbi__context * s = a->s; stbi__uint32 i, j, stride = x * out_n * bytes; @@ -4869,8 +4965,10 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); - a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, - 0); // extra bytes to write off the end into + a->out = (stbi_uc *) stbi__malloc_mad3( + x, y, output_bytes, + 0 + ); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); // note: error exits here don't need to clean up a->out individually, @@ -4937,11 +5035,13 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 case STBI__F_paeth: for (k = 0; k < filter_bytes; ++k) cur[k] = STBI__BYTECAST( - raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + raw[k] + prior[k] + ); // prior[k] == stbi__paeth(0,prior[k],0) for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] - + stbi__paeth(cur[k - filter_bytes], prior[k], - prior[k - filter_bytes])); + cur[k] = STBI__BYTECAST( + raw[k] + + stbi__paeth(cur[k - filter_bytes], prior[k], prior[k - filter_bytes]) + ); break; case STBI__F_avg_first: memcpy(cur, raw, filter_bytes); @@ -5022,16 +5122,18 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 return 1; } -static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, - stbi__uint32 image_data_len, int out_n, int depth, int color, - int interlaced) { +static int stbi__create_png_image( + stbi__png * a, stbi_uc * image_data, stbi__uint32 image_data_len, int out_n, int depth, + int color, int interlaced +) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc * final; int p; if (!interlaced) - return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, - a->s->img_y, depth, color); + return stbi__create_png_image_raw( + a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color + ); // de-interlacing final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); @@ -5047,8 +5149,9 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; - if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, - color)) { + if (!stbi__create_png_image_raw( + a, image_data, image_data_len, out_n, x, y, depth, color + )) { STBI_FREE(final); return 0; } @@ -5056,8 +5159,10 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data, for (i = 0; i < x; ++i) { int out_y = j * yspc[p] + yorig[p]; int out_x = i * xspc[p] + xorig[p]; - memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes, - a->out + (j * x + i) * out_bytes, out_bytes); + memcpy( + final + out_y * a->s->img_x * out_bytes + out_x * out_bytes, + a->out + (j * x + i) * out_bytes, out_bytes + ); } } STBI_FREE(a->out); @@ -5270,8 +5375,9 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) - return stbi__err("1/2/4/8/16-bit only", - "PNG not supported: 1/2/4/8/16-bit only"); + return stbi__err( + "1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only" + ); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG"); @@ -5385,15 +5491,17 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag( - (char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + (char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone + ); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n + 1; else s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, - color, interlace)) + if (!stbi__create_png_image( + z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace + )) return 0; if (has_trans) { if (z->depth == 16) { @@ -5432,8 +5540,9 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif - return stbi__err(invalid_chunk, - "PNG not supported: unknown PNG chunk type"); + return stbi__err( + invalid_chunk, "PNG not supported: unknown PNG chunk type" + ); } stbi__skip(s, c.length); break; @@ -5443,25 +5552,30 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) { } } -static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, int req_comp, - stbi__result_info * ri) { +static void * +stbi__do_png(stbi__png * p, int * x, int * y, int * n, int req_comp, stbi__result_info * ri) { void * result = NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth <= 8) ri->bits_per_channel = 8; else if (p->depth == 16) ri->bits_per_channel = 16; else - return stbi__errpuc("bad bits_per_channel", - "PNG not supported: unsupported color depth"); + return stbi__errpuc( + "bad bits_per_channel", "PNG not supported: unsupported color depth" + ); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) - result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, - req_comp, p->s->img_x, p->s->img_y); + result = stbi__convert_format( + (unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, + p->s->img_y + ); else - result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, - req_comp, p->s->img_x, p->s->img_y); + result = stbi__convert_format16( + (stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, + p->s->img_y + ); p->s->img_out_n = req_comp; if (result == NULL) return result; } @@ -5479,8 +5593,9 @@ static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, int req_com return result; } -static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__png_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { stbi__png p; p.s = s; return stbi__do_png(&p, x, y, comp, req_comp, ri); @@ -5667,12 +5782,16 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) { if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); if (compress >= 4) - return stbi__errpuc("BMP JPEG/PNG", - "BMP type not supported: unsupported " - "compression"); // this includes PNG/JPEG modes + return stbi__errpuc( + "BMP JPEG/PNG", + "BMP type not supported: unsupported " + "compression" + ); // this includes PNG/JPEG modes if (compress == 3 && info->bpp != 16 && info->bpp != 32) - return stbi__errpuc("bad BMP", - "bad BMP"); // bitfields requires 16 or 32 bits/pixel + return stbi__errpuc( + "bad BMP", + "bad BMP" + ); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres @@ -5723,8 +5842,9 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) { return (void *) 1; } -static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__bmp_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { stbi_uc * out; unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; stbi_uc pal[256][4]; @@ -5804,8 +5924,9 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, in if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } - stbi__skip(s, info.offset - info.extra_read - info.hsz - - psize * (info.hsz == 12 ? 3 : 4)); + stbi__skip( + s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4) + ); if (info.bpp == 1) width = (s->img_x + 7) >> 3; else if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; @@ -6023,8 +6144,9 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) { } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { - tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, - (tga_image_type == 3) || (tga_image_type == 11), NULL); + tga_comp = stbi__tga_get_comp( + tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL + ); } if (!tga_comp) { stbi__rewind(s); @@ -6087,8 +6209,9 @@ static void stbi__tga_read_rgb16(stbi__context * s, stbi_uc * out) { // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } -static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__tga_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); @@ -6325,8 +6448,10 @@ static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p, int pixelCount) return 1; } -static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri, int bpc) { +static void * stbi__psd_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri, + int bpc +) { int pixelCount; int channelCount, compression; int channel, i; @@ -6349,8 +6474,9 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, in // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) - return stbi__errpuc("wrong channel count", - "Unsupported number of channels in PSD image"); + return stbi__errpuc( + "wrong channel count", "Unsupported number of channels in PSD image" + ); // Read the rows and columns of the image. h = stbi__get32be(s); @@ -6575,8 +6701,8 @@ static void stbi__copyval(int channel, stbi_uc * dest, const stbi_uc * src) { if (channel & mask) dest[i] = src[i]; } -static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, int * comp, - stbi_uc * result) { +static stbi_uc * +stbi__pic_load_core(stbi__context * s, int width, int height, int * comp, stbi_uc * result) { int act_comp = 0, num_packets = 0, y, chained; stbi__pic_packet packets[10]; @@ -6632,8 +6758,9 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, i count = stbi__get8(s); if (stbi__at_eof(s)) - return stbi__errpuc("bad file", - "file too short (pure read count)"); + return stbi__errpuc( + "bad file", "file too short (pure read count)" + ); if (count > left) count = (stbi_uc) left; @@ -6650,8 +6777,9 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, i while (left > 0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) - return stbi__errpuc("bad file", - "file too short (mixed read count)"); + return stbi__errpuc( + "bad file", "file too short (mixed read count)" + ); if (count >= 128) { // Repeated stbi_uc value[4]; @@ -6684,8 +6812,9 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, i return result; } -static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__pic_load( + stbi__context * s, int * px, int * py, int * comp, int req_comp, stbi__result_info * ri +) { stbi_uc * result; int i, x, y, internal_comp; STBI_NOTUSED(ri); @@ -6780,8 +6909,9 @@ static int stbi__gif_test(stbi__context * s) { return r; } -static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4], int num_entries, - int transp) { +static void stbi__gif_parse_colortable( + stbi__context * s, stbi_uc pal[256][4], int num_entries, int transp +) { int i; for (i = 0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); @@ -6957,8 +7087,9 @@ static stbi_uc * stbi__process_gif_raster(stbi__context * s, stbi__gif * g) { // this function is designed to support animated gifs, although stb_image doesn't support it // two back is the image from two frames ago, used for a very specific disposal format -static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * comp, - int req_comp, stbi_uc * two_back) { +static stbi_uc * stbi__gif_load_next( + stbi__context * s, stbi__gif * g, int * comp, int req_comp, stbi_uc * two_back +) { int dispose; int first_frame; int pi; @@ -6983,8 +7114,10 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * com // background colour is only used for pixels that are not rendered first frame, after that "background" // color refers to the color that was there the previous frame. memset(g->out, 0x00, 4 * pcount); - memset(g->background, 0x00, - 4 * pcount); // state of the background (starts transparent) + memset( + g->background, 0x00, + 4 * pcount + ); // state of the background (starts transparent) memset(g->history, 0x00, pcount); // pixels that were affected previous frame first_frame = 1; @@ -7066,8 +7199,10 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * com } if (g->lflags & 0x80) { - stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), - g->eflags & 0x01 ? g->transparent : -1); + stbi__gif_parse_colortable( + s, g->lpal, 2 << (g->lflags & 7), + g->eflags & 0x01 ? g->transparent : -1 + ); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { g->color_table = (stbi_uc *) g->pal; @@ -7101,8 +7236,8 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * com if (len == 4) { g->eflags = stbi__get8(s); g->delay = 10 - * stbi__get16le( - s); // delay - 1/100th of a second, saving as 1/1000ths. + * stbi__get16le(s + ); // delay - 1/100th of a second, saving as 1/1000ths. // unset old transparent if (g->transparent >= 0) { @@ -7148,8 +7283,9 @@ static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out, int ** return stbi__errpuc("outofmem", "Out of memory"); } -static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z, - int * comp, int req_comp) { +static void * stbi__load_gif_main( + stbi__context * s, int ** delays, int * x, int * y, int * z, int * comp, int req_comp +) { if (stbi__gif_test(s)) { int layers = 0; stbi_uc * u = 0; @@ -7188,8 +7324,9 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int } if (delays) { - int * new_delays = (int *) STBI_REALLOC_SIZED(*delays, delays_size, - sizeof(int) * layers); + int * new_delays = (int *) STBI_REALLOC_SIZED( + *delays, delays_size, sizeof(int) * layers + ); if (!new_delays) return stbi__load_gif_main_outofmem(&g, out, delays); *delays = new_delays; delays_size = layers * sizeof(int); @@ -7231,8 +7368,9 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int } } -static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__gif_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { stbi_uc * u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); @@ -7336,8 +7474,9 @@ static void stbi__hdr_convert(float * output, stbi_uc * input, int req_comp) { } } -static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static float * stbi__hdr_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { char buffer[STBI__HDR_BUFLEN]; char * token; int valid = 0; @@ -7404,8 +7543,9 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, i stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); - stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, - req_comp); + stbi__hdr_convert( + hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp + ); } } } else { @@ -7472,8 +7612,9 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, i } } for (i = 0; i < width; ++i) - stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, scanline + i * 4, - req_comp); + stbi__hdr_convert( + hdr_data + (j * width + i) * req_comp, scanline + i * 4, req_comp + ); } if (scanline) STBI_FREE(scanline); } @@ -7689,8 +7830,9 @@ static int stbi__pnm_test(stbi__context * s) { return 1; } -static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp, - stbi__result_info * ri) { +static void * stbi__pnm_load( + stbi__context * s, int * x, int * y, int * comp, int req_comp, stbi__result_info * ri +) { stbi_uc * out; STBI_NOTUSED(ri); @@ -7710,8 +7852,9 @@ static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, in if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) return stbi__errpuc("too large", "PNM too large"); - out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, - 0); + out = (stbi_uc *) stbi__malloc_mad4( + s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0 + ); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { STBI_FREE(out); @@ -7720,8 +7863,9 @@ static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, in if (req_comp && req_comp != s->img_n) { if (ri->bits_per_channel == 16) { - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, - s->img_x, s->img_y); + out = (stbi_uc *) stbi__convert_format16( + (stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y + ); } else { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); } @@ -7753,8 +7897,10 @@ static int stbi__pnm_getinteger(stbi__context * s, char * c) { value = value * 10 + (*c - '0'); *c = (char) stbi__get8(s); if ((value > 214748364) || (value == 214748364 && *c > '7')) - return stbi__err("integer parse overflow", - "Parsing an integer in the PPM header overflowed a 32-bit int"); + return stbi__err( + "integer parse overflow", + "Parsing an integer in the PPM header overflowed a 32-bit int" + ); } return value; @@ -7795,8 +7941,9 @@ static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp) { maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 65535) - return stbi__err("max value > 65535", - "PPM image supports only 8-bit and 16-bit images"); + return stbi__err( + "max value > 65535", "PPM image supports only 8-bit and 16-bit images" + ); else if (maxv > 255) return 16; else return 8; } @@ -7902,15 +8049,16 @@ STBIDEF int stbi_is_16_bit_from_file(FILE * f) { } #endif // !STBI_NO_STDIO -STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, - int * comp) { +STBIDEF int +stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y, int * comp) { stbi__context s; stbi__start_mem(&s, buffer, len); return stbi__info_main(&s, x, y, comp); } -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * c, void * user, int * x, - int * y, int * comp) { +STBIDEF int stbi_info_from_callbacks( + stbi_io_callbacks const * c, void * user, int * x, int * y, int * comp +) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s, x, y, comp); diff --git a/src/crepe/Particle.cpp b/src/crepe/Particle.cpp index b340826..27fa97f 100644 --- a/src/crepe/Particle.cpp +++ b/src/crepe/Particle.cpp @@ -2,8 +2,9 @@ using namespace crepe; -void Particle::reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity, - float angle) { +void Particle::reset( + unsigned int lifespan, const vec2 & position, const vec2 & velocity, float angle +) { // Initialize the particle state this->time_in_life = 0; this->lifespan = lifespan; diff --git a/src/crepe/Particle.h b/src/crepe/Particle.h index ee0cd66..c013de5 100644 --- a/src/crepe/Particle.h +++ b/src/crepe/Particle.h @@ -41,8 +41,8 @@ public: * \param velocity The initial velocity of the particle. * \param angle The angle of the particle's trajectory or orientation. */ - void reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity, - float angle); + void + reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity, float angle); /** * \brief Updates the particle's state. * diff --git a/src/crepe/api/AI.cpp b/src/crepe/api/AI.cpp index 2195249..2fedaf4 100644 --- a/src/crepe/api/AI.cpp +++ b/src/crepe/api/AI.cpp @@ -8,8 +8,9 @@ namespace crepe { AI::AI(game_object_id_t id, float max_force) : Component(id), max_force(max_force) {} -void AI::make_circle_path(float radius, const vec2 & center, float start_angle, - bool clockwise) { +void AI::make_circle_path( + float radius, const vec2 & center, float start_angle, bool clockwise +) { if (radius <= 0) { throw std::runtime_error("Radius must be greater than 0"); } @@ -25,19 +26,25 @@ void AI::make_circle_path(float radius, const vec2 & center, float start_angle, if (clockwise) { for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) { - path.push_back(vec2{static_cast(center.x + radius * cos(i)), - static_cast(center.y + radius * sin(i))}); + path.push_back(vec2 { + static_cast(center.x + radius * cos(i)), + static_cast(center.y + radius * sin(i)) + }); } } else { for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) { - path.push_back(vec2{static_cast(center.x + radius * cos(i)), - static_cast(center.y + radius * sin(i))}); + path.push_back(vec2 { + static_cast(center.x + radius * cos(i)), + static_cast(center.y + radius * sin(i)) + }); } } } -void AI::make_oval_path(float radius_x, float radius_y, const vec2 & center, float start_angle, - bool clockwise, float rotation) { +void AI::make_oval_path( + float radius_x, float radius_y, const vec2 & center, float start_angle, bool clockwise, + float rotation +) { if (radius_x <= 0 && radius_y <= 0) { throw std::runtime_error("Radius must be greater than 0"); } @@ -73,14 +80,16 @@ void AI::make_oval_path(float radius_x, float radius_y, const vec2 & center, flo if (clockwise) { for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) { - vec2 point = {static_cast(center.x + radius_x * cos(i)), - static_cast(center.y + radius_y * sin(i))}; + vec2 point + = {static_cast(center.x + radius_x * cos(i)), + static_cast(center.y + radius_y * sin(i))}; path.push_back(rotate_point(point, center)); } } else { for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) { - vec2 point = {static_cast(center.x + radius_x * cos(i)), - static_cast(center.y + radius_y * sin(i))}; + vec2 point + = {static_cast(center.x + radius_x * cos(i)), + static_cast(center.y + radius_y * sin(i))}; path.push_back(rotate_point(point, center)); } } diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h index c780a91..bee11b3 100644 --- a/src/crepe/api/AI.h +++ b/src/crepe/api/AI.h @@ -70,8 +70,10 @@ public: * \param start_angle The start angle of the circle (in radians) * \param clockwise The direction of the circle */ - void make_circle_path(float radius, const vec2 & center = {0, 0}, float start_angle = 0, - bool clockwise = true); + void make_circle_path( + float radius, const vec2 & center = {0, 0}, float start_angle = 0, + bool clockwise = true + ); /** * \brief Make an oval path (for the path following behavior) * @@ -84,8 +86,10 @@ public: * \param clockwise The direction of the oval * \param rotation The rotation of the oval (in radians) */ - void make_oval_path(float radius_x, float radius_y, const vec2 & center = {0, 0}, - float start_angle = 0, bool clockwise = true, float rotation = 0); + void make_oval_path( + float radius_x, float radius_y, const vec2 & center = {0, 0}, float start_angle = 0, + bool clockwise = true, float rotation = 0 + ); public: //! The maximum force that can be applied to the entity (higher values will make the entity adjust faster) diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index b7eefb8..c558d86 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -7,8 +7,10 @@ using namespace crepe; -Animator::Animator(game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size, - const uvec2 & grid_size, const Animator::Data & data) +Animator::Animator( + game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size, + const uvec2 & grid_size, const Animator::Data & data +) : Component(id), spritesheet(spritesheet), grid_size(grid_size), diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 5918800..102894d 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -83,8 +83,10 @@ public: * This constructor sets up the Animator with the given parameters, and initializes the * animation system. */ - Animator(game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size, - const uvec2 & grid_size, const Animator::Data & data); + Animator( + game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size, + const uvec2 & grid_size, const Animator::Data & data + ); ~Animator(); // dbg_trace public: diff --git a/src/crepe/api/Asset.cpp b/src/crepe/api/Asset.cpp index e148367..bab82e7 100644 --- a/src/crepe/api/Asset.cpp +++ b/src/crepe/api/Asset.cpp @@ -50,5 +50,5 @@ string Asset::whereami() const noexcept { bool Asset::operator==(const Asset & other) const noexcept { return this->src == other.src; } size_t std::hash::operator()(const Asset & asset) const noexcept { - return std::hash{}(asset.get_path()); + return std::hash {}(asset.get_path()); }; diff --git a/src/crepe/api/AudioSource.h b/src/crepe/api/AudioSource.h index b20e490..eaa56e8 100644 --- a/src/crepe/api/AudioSource.h +++ b/src/crepe/api/AudioSource.h @@ -68,7 +68,7 @@ private: typeof(loop) last_loop = loop; //! \} //! This source's voice handle - SoundHandle voice{}; + SoundHandle voice {}; }; } // namespace crepe diff --git a/src/crepe/api/BoxCollider.cpp b/src/crepe/api/BoxCollider.cpp index a893d41..f6b358d 100644 --- a/src/crepe/api/BoxCollider.cpp +++ b/src/crepe/api/BoxCollider.cpp @@ -4,7 +4,8 @@ using namespace crepe; -BoxCollider::BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions, - const vec2 & offset) +BoxCollider::BoxCollider( + game_object_id_t game_object_id, const vec2 & dimensions, const vec2 & offset +) : Collider(game_object_id, offset), dimensions(dimensions) {} diff --git a/src/crepe/api/BoxCollider.h b/src/crepe/api/BoxCollider.h index d643e7f..229b90f 100644 --- a/src/crepe/api/BoxCollider.h +++ b/src/crepe/api/BoxCollider.h @@ -13,8 +13,9 @@ namespace crepe { */ class BoxCollider : public Collider { public: - BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions, - const vec2 & offset = {0, 0}); + BoxCollider( + game_object_id_t game_object_id, const vec2 & dimensions, const vec2 & offset = {0, 0} + ); //! Width and height of the box collider vec2 dimensions; diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp index 19a3296..b1466b5 100644 --- a/src/crepe/api/Camera.cpp +++ b/src/crepe/api/Camera.cpp @@ -6,8 +6,9 @@ using namespace crepe; -Camera::Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, - const Data & data) +Camera::Camera( + game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, const Data & data +) : Component(id), screen(screen), viewport_size(viewport_size), diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index 54d9a73..3191b04 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -44,8 +44,10 @@ public: * \param viewport_size is the view of the world in game units * \param data the camera component data */ - Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, - const Camera::Data & data); + Camera( + game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, + const Camera::Data & data + ); ~Camera(); // dbg_trace only public: diff --git a/src/crepe/api/CircleCollider.cpp b/src/crepe/api/CircleCollider.cpp index 90ab5e7..e72800c 100644 --- a/src/crepe/api/CircleCollider.cpp +++ b/src/crepe/api/CircleCollider.cpp @@ -2,7 +2,8 @@ using namespace crepe; -CircleCollider::CircleCollider(game_object_id_t game_object_id, float radius, - const vec2 & offset) +CircleCollider::CircleCollider( + game_object_id_t game_object_id, float radius, const vec2 & offset +) : Collider(game_object_id, offset), radius(radius) {} diff --git a/src/crepe/api/CircleCollider.h b/src/crepe/api/CircleCollider.h index 22da836..e6ad4fa 100644 --- a/src/crepe/api/CircleCollider.h +++ b/src/crepe/api/CircleCollider.h @@ -13,8 +13,9 @@ namespace crepe { */ class CircleCollider : public Collider { public: - CircleCollider(game_object_id_t game_object_id, float radius, - const vec2 & offset = {0, 0}); + CircleCollider( + game_object_id_t game_object_id, float radius, const vec2 & offset = {0, 0} + ); //! Radius of the circle collider. float radius; diff --git a/src/crepe/api/Color.cpp b/src/crepe/api/Color.cpp index 29bd77a..6858aa8 100644 --- a/src/crepe/api/Color.cpp +++ b/src/crepe/api/Color.cpp @@ -2,11 +2,11 @@ using namespace crepe; -const Color Color::WHITE{0xff, 0xff, 0xff}; -const Color Color::RED{0xff, 0x00, 0x00}; -const Color Color::GREEN{0x00, 0xff, 0x00}; -const Color Color::BLUE{0x00, 0x00, 0xff}; -const Color Color::BLACK{0x00, 0x00, 0x00}; -const Color Color::CYAN{0x00, 0xff, 0xff}; -const Color Color::YELLOW{0xff, 0xff, 0x00}; -const Color Color::MAGENTA{0xff, 0x00, 0xff}; +const Color Color::WHITE {0xff, 0xff, 0xff}; +const Color Color::RED {0xff, 0x00, 0x00}; +const Color Color::GREEN {0x00, 0xff, 0x00}; +const Color Color::BLUE {0x00, 0x00, 0xff}; +const Color Color::BLACK {0x00, 0x00, 0x00}; +const Color Color::CYAN {0x00, 0xff, 0xff}; +const Color Color::YELLOW {0xff, 0xff, 0x00}; +const Color Color::MAGENTA {0xff, 0x00, 0xff}; diff --git a/src/crepe/api/Engine.cpp b/src/crepe/api/Engine.cpp index 2e9d35a..cd9786b 100644 --- a/src/crepe/api/Engine.cpp +++ b/src/crepe/api/Engine.cpp @@ -46,8 +46,10 @@ void Engine::loop() { try { systems.fixed_update(); } catch (const exception & e) { - Log::logf(Log::Level::WARNING, - "Uncaught exception in fixed update function: {}\n", e.what()); + Log::logf( + Log::Level::WARNING, "Uncaught exception in fixed update function: {}\n", + e.what() + ); } timer.advance_fixed_elapsed_time(); } @@ -55,8 +57,10 @@ void Engine::loop() { try { systems.frame_update(); } catch (const exception & e) { - Log::logf(Log::Level::WARNING, "Uncaught exception in frame update function: {}\n", - e.what()); + Log::logf( + Log::Level::WARNING, "Uncaught exception in frame update function: {}\n", + e.what() + ); } timer.enforce_frame_rate(); } diff --git a/src/crepe/api/Engine.h b/src/crepe/api/Engine.h index 700a0cd..452a856 100644 --- a/src/crepe/api/Engine.h +++ b/src/crepe/api/Engine.h @@ -54,26 +54,26 @@ private: Mediator mediator; //! SystemManager - SystemManager system_manager{mediator}; + SystemManager system_manager {mediator}; //! SDLContext instance - SDLContext sdl_context{mediator}; + SDLContext sdl_context {mediator}; //! Resource manager instance - ResourceManager resource_manager{mediator}; + ResourceManager resource_manager {mediator}; //! Component manager instance - ComponentManager component_manager{mediator}; + ComponentManager component_manager {mediator}; //! Scene manager instance - SceneManager scene_manager{mediator}; + SceneManager scene_manager {mediator}; //! LoopTimerManager instance - LoopTimerManager loop_timer{mediator}; + LoopTimerManager loop_timer {mediator}; //! EventManager instance - EventManager event_manager{mediator}; + EventManager event_manager {mediator}; //! Save manager instance - SaveManager save_manager{mediator}; + SaveManager save_manager {mediator}; //! ReplayManager instance - ReplayManager replay_manager{mediator}; + ReplayManager replay_manager {mediator}; }; } // namespace crepe diff --git a/src/crepe/api/GameObject.cpp b/src/crepe/api/GameObject.cpp index 9b94cad..100e210 100644 --- a/src/crepe/api/GameObject.cpp +++ b/src/crepe/api/GameObject.cpp @@ -7,13 +7,15 @@ using namespace crepe; using namespace std; -GameObject::GameObject(Mediator & mediator, game_object_id_t id, const std::string & name, - const std::string & tag, const vec2 & position, double rotation, - double scale) +GameObject::GameObject( + Mediator & mediator, game_object_id_t id, const std::string & name, + const std::string & tag, const vec2 & position, double rotation, double scale +) : id(id), mediator(mediator), - transform(mediator.component_manager->add_component(this->id, position, - rotation, scale)), + transform(mediator.component_manager->add_component( + this->id, position, rotation, scale + )), metadata(mediator.component_manager->add_component(this->id, name, tag)) {} void GameObject::set_parent(const GameObject & parent) { diff --git a/src/crepe/api/GameObject.h b/src/crepe/api/GameObject.h index 572ce3a..043913a 100644 --- a/src/crepe/api/GameObject.h +++ b/src/crepe/api/GameObject.h @@ -30,8 +30,10 @@ private: * \param rotation The rotation of the GameObject * \param scale The scale of the GameObject */ - GameObject(Mediator & mediator, game_object_id_t id, const std::string & name, - const std::string & tag, const vec2 & position, double rotation, double scale); + GameObject( + Mediator & mediator, game_object_id_t id, const std::string & name, + const std::string & tag, const vec2 & position, double rotation, double scale + ); //! ComponentManager instances GameObject friend class ComponentManager; diff --git a/src/crepe/api/ParticleEmitter.cpp b/src/crepe/api/ParticleEmitter.cpp index 9a70334..341c1e2 100644 --- a/src/crepe/api/ParticleEmitter.cpp +++ b/src/crepe/api/ParticleEmitter.cpp @@ -4,8 +4,9 @@ using namespace crepe; using namespace std; -ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Sprite & sprite, - const Data & data) +ParticleEmitter::ParticleEmitter( + game_object_id_t game_object_id, const Sprite & sprite, const Data & data +) : Component(game_object_id), sprite(sprite), data(data) { @@ -15,7 +16,7 @@ ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Sprite & } unique_ptr ParticleEmitter::save() const { - return unique_ptr{new ParticleEmitter(*this)}; + return unique_ptr {new ParticleEmitter(*this)}; } void ParticleEmitter::restore(const Component & snapshot) { diff --git a/src/crepe/api/Scene.cpp b/src/crepe/api/Scene.cpp index ad729d2..84da7e8 100644 --- a/src/crepe/api/Scene.cpp +++ b/src/crepe/api/Scene.cpp @@ -4,8 +4,10 @@ using namespace crepe; SaveManager & Scene::get_save_manager() const { return mediator->save_manager; } -GameObject Scene::new_object(const std::string & name, const std::string & tag, - const vec2 & position, double rotation, double scale) { +GameObject Scene::new_object( + const std::string & name, const std::string & tag, const vec2 & position, double rotation, + double scale +) { // Forward the call to ComponentManager's new_object method return mediator->component_manager->new_object(name, tag, position, rotation, scale); } diff --git a/src/crepe/api/Scene.h b/src/crepe/api/Scene.h index d552a43..b50a0fc 100644 --- a/src/crepe/api/Scene.h +++ b/src/crepe/api/Scene.h @@ -69,9 +69,10 @@ public: SaveManager & get_save_manager() const; //! \copydoc ComponentManager::new_object - GameObject new_object(const std::string & name, const std::string & tag = "", - const vec2 & position = {0, 0}, double rotation = 0, - double scale = 1); + GameObject new_object( + const std::string & name, const std::string & tag = "", const vec2 & position = {0, 0}, + double rotation = 0, double scale = 1 + ); //! \copydoc ResourceManager::set_persistent void set_persistent(const Asset & asset, bool persistent); diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h index bbee920..b000d9d 100644 --- a/src/crepe/api/Script.h +++ b/src/crepe/api/Script.h @@ -129,12 +129,14 @@ protected: void subscribe(const EventHandler & callback); //! \copydoc EventManager::trigger_event template - void trigger_event(const EventType & event = {}, - event_channel_t channel = EventManager::CHANNEL_ALL); + void trigger_event( + const EventType & event = {}, event_channel_t channel = EventManager::CHANNEL_ALL + ); //! \copydoc EventManager::queue_event template - void queue_event(const EventType & event = {}, - event_channel_t channel = EventManager::CHANNEL_ALL); + void queue_event( + const EventType & event = {}, event_channel_t channel = EventManager::CHANNEL_ALL + ); //! \} /** @@ -179,7 +181,7 @@ protected: OptionalRef & mediator; replay(OptionalRef & mediator) : mediator(mediator) {} friend class Script; - } replay{mediator}; + } replay {mediator}; /** * \brief Utility function to retrieve the keyboard state diff --git a/src/crepe/api/Script.hpp b/src/crepe/api/Script.hpp index 4462a41..c7fa6ff 100644 --- a/src/crepe/api/Script.hpp +++ b/src/crepe/api/Script.hpp @@ -14,7 +14,8 @@ T & Script::get_component() const { RefVector all_components = this->get_components(); if (all_components.size() < 1) throw runtime_error( - format("Script: no component found with type = {}", typeid(T).name())); + format("Script: no component found with type = {}", typeid(T).name()) + ); return all_components.back().get(); } @@ -35,8 +36,9 @@ void Script::logf(std::format_string fmt, Args &&... args) { } template -void Script::subscribe_internal(const EventHandler & callback, - event_channel_t channel) { +void Script::subscribe_internal( + const EventHandler & callback, event_channel_t channel +) { EventManager & mgr = this->mediator->event_manager; subscription_t listener = mgr.subscribe( [this, callback](const EventType & data) -> bool { @@ -54,7 +56,8 @@ void Script::subscribe_internal(const EventHandler & callback, // call user-provided callback return callback(data); }, - channel); + channel + ); this->listeners.push_back(listener); } diff --git a/src/crepe/api/Text.cpp b/src/crepe/api/Text.cpp index 4a94180..b24f0ac 100644 --- a/src/crepe/api/Text.cpp +++ b/src/crepe/api/Text.cpp @@ -2,8 +2,10 @@ using namespace crepe; -Text::Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset, - const std::string & font_family, const Data & data, const std::string & text) +Text::Text( + game_object_id_t id, const vec2 & dimensions, const vec2 & offset, + const std::string & font_family, const Data & data, const std::string & text +) : UIObject(id, dimensions, offset), text(text), data(data), diff --git a/src/crepe/api/Text.h b/src/crepe/api/Text.h index da40141..0289b85 100644 --- a/src/crepe/api/Text.h +++ b/src/crepe/api/Text.h @@ -48,8 +48,10 @@ public: * \param data Data struct containing extra text parameters. * \param font Optional font asset that can be passed or left empty. */ - Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset, - const std::string & font_family, const Data & data, const std::string & text = ""); + Text( + game_object_id_t id, const vec2 & dimensions, const vec2 & offset, + const std::string & font_family, const Data & data, const std::string & text = "" + ); //! Label text. std::string text = ""; diff --git a/src/crepe/api/Transform.cpp b/src/crepe/api/Transform.cpp index fcfce14..b70174c 100644 --- a/src/crepe/api/Transform.cpp +++ b/src/crepe/api/Transform.cpp @@ -14,7 +14,7 @@ Transform::Transform(game_object_id_t id, const vec2 & point, double rotation, d } unique_ptr Transform::save() const { - return unique_ptr{new Transform(*this)}; + return unique_ptr {new Transform(*this)}; } void Transform::restore(const Component & snapshot) { diff --git a/src/crepe/facade/FontFacade.cpp b/src/crepe/facade/FontFacade.cpp index 87f95ab..e284f5a 100644 --- a/src/crepe/facade/FontFacade.cpp +++ b/src/crepe/facade/FontFacade.cpp @@ -20,8 +20,9 @@ Asset FontFacade::get_font_asset(const string & font_family) { = FcNameParse(reinterpret_cast(font_family.c_str())); if (raw_pattern == NULL) throw runtime_error("Failed to create font pattern."); - unique_ptr> pattern{ - raw_pattern, [](FcPattern * p) { FcPatternDestroy(p); }}; + unique_ptr> pattern { + raw_pattern, [](FcPattern * p) { FcPatternDestroy(p); } + }; FcConfig * config = FcConfigGetCurrent(); if (config == NULL) throw runtime_error("Failed to get current Fontconfig configuration."); diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 64c1fe2..859f966 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -41,9 +41,10 @@ SDLContext::SDLContext(Mediator & mediator) { } auto & cfg = Config::get_instance().window_settings; - SDL_Window * tmp_window - = SDL_CreateWindow(cfg.window_title.c_str(), SDL_WINDOWPOS_CENTERED, - SDL_WINDOWPOS_CENTERED, cfg.default_size.x, cfg.default_size.y, 0); + SDL_Window * tmp_window = SDL_CreateWindow( + cfg.window_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + cfg.default_size.x, cfg.default_size.y, 0 + ); if (!tmp_window) { throw runtime_error(format("SDLContext: SDL_Window error: {}", SDL_GetError())); } @@ -52,8 +53,8 @@ SDLContext::SDLContext(Mediator & mediator) { SDL_Renderer * tmp_renderer = SDL_CreateRenderer(this->game_window.get(), -1, SDL_RENDERER_ACCELERATED); if (!tmp_renderer) { - throw runtime_error( - format("SDLContext: SDL_CreateRenderer error: {}", SDL_GetError())); + throw runtime_error(format("SDLContext: SDL_CreateRenderer error: {}", SDL_GetError()) + ); } this->game_renderer @@ -108,7 +109,7 @@ const keyboard_state_t & SDLContext::get_keyboard_state() { MouseButton SDLContext::sdl_to_mousebutton(Uint8 sdl_button) { static const std::array MOUSE_BUTTON_LOOKUP_TABLE = [] { - std::array table{}; + std::array table {}; table.fill(MouseButton::NONE); table[SDL_BUTTON_LEFT] = MouseButton::LEFT_MOUSE; @@ -164,7 +165,7 @@ SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const { - size / 2 + cam_aux_data.bar_size; } - return SDL_FRect{ + return SDL_FRect { .x = screen_pos.x, .y = screen_pos.y, .w = size.x, @@ -188,7 +189,7 @@ void SDLContext::draw(const RenderContext & ctx) { srcrect_ptr = &srcrect; } - SDL_FRect dstrect = this->get_dst_rect(SDLContext::DestinationRectangleData{ + SDL_FRect dstrect = this->get_dst_rect(SDLContext::DestinationRectangleData { .sprite = ctx.sprite, .texture = ctx.texture, .pos = ctx.pos, @@ -198,8 +199,10 @@ void SDLContext::draw(const RenderContext & ctx) { double angle = ctx.angle + data.angle_offset; this->set_color_texture(ctx.texture, ctx.sprite.data.color); - SDL_RenderCopyExF(this->game_renderer.get(), ctx.texture.get_img(), srcrect_ptr, &dstrect, - angle, NULL, render_flip); + SDL_RenderCopyExF( + this->game_renderer.get(), ctx.texture.get_img(), srcrect_ptr, &dstrect, angle, NULL, + render_flip + ); } void SDLContext::draw_text(const RenderText & data) { @@ -210,7 +213,7 @@ void SDLContext::draw_text(const RenderText & data) { std::unique_ptr> font_surface; std::unique_ptr> font_texture; - SDL_Color color{ + SDL_Color color { .r = text.data.text_color.r, .g = text.data.text_color.g, .b = text.data.text_color.b, @@ -232,20 +235,21 @@ void SDLContext::draw_text(const RenderText & data) { = {tmp_font_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }}; vec2 size = text.dimensions * cam_aux_data.render_scale * data.transform.scale; - vec2 screen_pos - = (absoluut_pos - cam_aux_data.cam_pos + (cam_aux_data.zoomed_viewport) / 2) - * cam_aux_data.render_scale - - size / 2 + cam_aux_data.bar_size; + vec2 screen_pos = (absoluut_pos - cam_aux_data.cam_pos + (cam_aux_data.zoomed_viewport) / 2 + ) * cam_aux_data.render_scale + - size / 2 + cam_aux_data.bar_size; - SDL_FRect dstrect{ + SDL_FRect dstrect { .x = screen_pos.x, .y = screen_pos.y, .w = size.x, .h = size.y, }; - SDL_RenderCopyExF(this->game_renderer.get(), font_texture.get(), NULL, &dstrect, - data.transform.rotation, NULL, SDL_FLIP_NONE); + SDL_RenderCopyExF( + this->game_renderer.get(), font_texture.get(), NULL, &dstrect, data.transform.rotation, + NULL, SDL_FLIP_NONE + ); } void SDLContext::update_camera_view(const Camera & cam, const vec2 & new_pos) { @@ -291,8 +295,10 @@ void SDLContext::update_camera_view(const Camera & cam, const vec2 & new_pos) { render_scale.x = render_scale.y = scale; } - SDL_SetRenderDrawColor(this->game_renderer.get(), cam_data.bg_color.r, cam_data.bg_color.g, - cam_data.bg_color.b, cam_data.bg_color.a); + SDL_SetRenderDrawColor( + this->game_renderer.get(), cam_data.bg_color.r, cam_data.bg_color.g, + cam_data.bg_color.b, cam_data.bg_color.a + ); SDL_Rect bg = { .x = 0, @@ -427,11 +433,12 @@ std::vector SDLContext::get_events() { return event_list; } -void SDLContext::handle_window_event(const SDL_WindowEvent & window_event, - std::vector & event_list) { +void SDLContext::handle_window_event( + const SDL_WindowEvent & window_event, std::vector & event_list +) { switch (window_event.event) { case SDL_WINDOWEVENT_EXPOSED: - event_list.push_back(EventData{EventType::WINDOW_EXPOSE}); + event_list.push_back(EventData {EventType::WINDOW_EXPOSE}); break; case SDL_WINDOWEVENT_RESIZED: event_list.push_back(EventData{ @@ -455,16 +462,16 @@ void SDLContext::handle_window_event(const SDL_WindowEvent & window_event, break; case SDL_WINDOWEVENT_MINIMIZED: - event_list.push_back(EventData{EventType::WINDOW_MINIMIZE}); + event_list.push_back(EventData {EventType::WINDOW_MINIMIZE}); break; case SDL_WINDOWEVENT_MAXIMIZED: - event_list.push_back(EventData{EventType::WINDOW_MAXIMIZE}); + event_list.push_back(EventData {EventType::WINDOW_MAXIMIZE}); break; case SDL_WINDOWEVENT_FOCUS_GAINED: - event_list.push_back(EventData{EventType::WINDOW_FOCUS_GAIN}); + event_list.push_back(EventData {EventType::WINDOW_FOCUS_GAIN}); break; case SDL_WINDOWEVENT_FOCUS_LOST: - event_list.push_back(EventData{EventType::WINDOW_FOCUS_LOST}); + event_list.push_back(EventData {EventType::WINDOW_FOCUS_LOST}); break; } } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index e570073..bc118f9 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -116,8 +116,9 @@ public: * This method checks if any window events are triggered and adds them to the event_list. * */ - void handle_window_event(const SDL_WindowEvent & window_event, - std::vector & event_list); + void handle_window_event( + const SDL_WindowEvent & window_event, std::vector & event_list + ); /** * \brief Converts an SDL scan code to the custom Keycode type. * @@ -254,7 +255,7 @@ private: private: //! instance of the font_facade - FontFacade font_facade{}; + FontFacade font_facade {}; public: /** diff --git a/src/crepe/manager/ComponentManager.cpp b/src/crepe/manager/ComponentManager.cpp index 745ddae..245419d 100644 --- a/src/crepe/manager/ComponentManager.cpp +++ b/src/crepe/manager/ComponentManager.cpp @@ -46,14 +46,16 @@ void ComponentManager::delete_all_components() { this->next_id = 0; } -GameObject ComponentManager::new_object(const string & name, const string & tag, - const vec2 & position, double rotation, double scale) { +GameObject ComponentManager::new_object( + const string & name, const string & tag, const vec2 & position, double rotation, + double scale +) { // Find the first available id (taking persistent objects into account) while (this->persistent[this->next_id]) { this->next_id++; } - GameObject object{this->mediator, this->next_id, name, tag, position, rotation, scale}; + GameObject object {this->mediator, this->next_id, name, tag, position, rotation, scale}; this->next_id++; return object; @@ -64,23 +66,25 @@ void ComponentManager::set_persistent(game_object_id_t id, bool persistent) { } set ComponentManager::get_objects_by_name(const string & name) const { - return this->get_objects_by_predicate( - [name](const Metadata & data) { return data.name == name; }); + return this->get_objects_by_predicate([name](const Metadata & data) { + return data.name == name; + }); } set ComponentManager::get_objects_by_tag(const string & tag) const { - return this->get_objects_by_predicate( - [tag](const Metadata & data) { return data.tag == tag; }); + return this->get_objects_by_predicate([tag](const Metadata & data) { + return data.tag == tag; + }); } ComponentManager::Snapshot ComponentManager::save() { - Snapshot snapshot{}; + Snapshot snapshot {}; for (const auto & [type, by_id_index] : this->components) { for (game_object_id_t id = 0; id < by_id_index.size(); id++) { const auto & components = by_id_index[id]; for (size_t index = 0; index < components.size(); index++) { const Component & component = *components[index]; - snapshot.components.push_back(SnapshotComponent{ + snapshot.components.push_back(SnapshotComponent { .type = type, .id = id, .index = index, diff --git a/src/crepe/manager/ComponentManager.h b/src/crepe/manager/ComponentManager.h index c3a5b4a..2eb1f7e 100644 --- a/src/crepe/manager/ComponentManager.h +++ b/src/crepe/manager/ComponentManager.h @@ -38,9 +38,10 @@ public: * * \note This method automatically assigns a new entity ID */ - GameObject new_object(const std::string & name, const std::string & tag = "", - const vec2 & position = {0, 0}, double rotation = 0, - double scale = 1); + GameObject new_object( + const std::string & name, const std::string & tag = "", const vec2 & position = {0, 0}, + double rotation = 0, double scale = 1 + ); public: /** diff --git a/src/crepe/manager/ComponentManager.hpp b/src/crepe/manager/ComponentManager.hpp index 9e70865..6d32edb 100644 --- a/src/crepe/manager/ComponentManager.hpp +++ b/src/crepe/manager/ComponentManager.hpp @@ -11,8 +11,10 @@ template T & ComponentManager::add_component(game_object_id_t id, Args &&... args) { using namespace std; - static_assert(is_base_of::value, - "add_component must recieve a derivative class of Component"); + static_assert( + is_base_of::value, + "add_component must recieve a derivative class of Component" + ); // Determine the type of T (this is used as the key of the unordered_map<>) type_index type = typeid(T); @@ -40,8 +42,8 @@ T & ComponentManager::add_component(game_object_id_t id, Args &&... args) { // Check if the vector size is not greater than get_instances_max int max_instances = instance->get_instances_max(); if (max_instances != -1 && components[type][id].size() >= max_instances) { - throw std::runtime_error( - "Exceeded maximum number of instances for this component type"); + throw std::runtime_error("Exceeded maximum number of instances for this component type" + ); } // store its unique_ptr in the vector<> @@ -95,8 +97,10 @@ template RefVector ComponentManager::get_components_by_id(game_object_id_t id) const { using namespace std; - static_assert(is_base_of::value, - "get_components_by_id must recieve a derivative class of Component"); + static_assert( + is_base_of::value, + "get_components_by_id must recieve a derivative class of Component" + ); type_index type = typeid(T); if (!this->components.contains(type)) return {}; @@ -170,8 +174,8 @@ ComponentManager::get_objects_by_predicate(const std::function } template -RefVector -ComponentManager::get_components_by_ids(const std::set & ids) const { +RefVector ComponentManager::get_components_by_ids(const std::set & ids +) const { using namespace std; RefVector out = {}; diff --git a/src/crepe/manager/EventManager.h b/src/crepe/manager/EventManager.h index 0a57fb1..5766a0c 100644 --- a/src/crepe/manager/EventManager.h +++ b/src/crepe/manager/EventManager.h @@ -49,8 +49,8 @@ public: * \return A unique subscription ID associated with the registered callback. */ template - subscription_t subscribe(const EventHandler & callback, - event_channel_t channel = CHANNEL_ALL); + subscription_t + subscribe(const EventHandler & callback, event_channel_t channel = CHANNEL_ALL); /** * \brief Unsubscribe a previously registered callback. diff --git a/src/crepe/manager/EventManager.hpp b/src/crepe/manager/EventManager.hpp index b2090d0..1f44943 100644 --- a/src/crepe/manager/EventManager.hpp +++ b/src/crepe/manager/EventManager.hpp @@ -5,22 +5,24 @@ namespace crepe { template -subscription_t EventManager::subscribe(const EventHandler & callback, - event_channel_t channel) { +subscription_t +EventManager::subscribe(const EventHandler & callback, event_channel_t channel) { subscription_counter++; std::type_index event_type = typeid(EventType); std::unique_ptr> handler = std::make_unique>(callback); std::vector & handlers = this->subscribers[event_type]; - handlers.emplace_back(CallbackEntry{ - .callback = std::move(handler), .channel = channel, .id = subscription_counter}); + handlers.emplace_back(CallbackEntry { + .callback = std::move(handler), .channel = channel, .id = subscription_counter + }); return subscription_counter; } template void EventManager::queue_event(const EventType & event, event_channel_t channel) { - static_assert(std::is_base_of::value, - "EventType must derive from Event"); + static_assert( + std::is_base_of::value, "EventType must derive from Event" + ); this->events_queue.push_back(QueueEntry{ // unique_ptr w/ custom destructor implementation is used because the base Event interface // can't be polymorphic (= have default virtual destructor) diff --git a/src/crepe/manager/LoopTimerManager.cpp b/src/crepe/manager/LoopTimerManager.cpp index e78f92f..b4cd07f 100644 --- a/src/crepe/manager/LoopTimerManager.cpp +++ b/src/crepe/manager/LoopTimerManager.cpp @@ -17,9 +17,9 @@ LoopTimerManager::LoopTimerManager(Mediator & mediator) : Manager(mediator) { void LoopTimerManager::start() { this->last_frame_time = std::chrono::steady_clock::now(); - this->elapsed_time = elapsed_time_t{0}; - this->elapsed_fixed_time = elapsed_time_t{0}; - this->delta_time = duration_t{0}; + this->elapsed_time = elapsed_time_t {0}; + this->elapsed_fixed_time = elapsed_time_t {0}; + this->delta_time = duration_t {0}; } void LoopTimerManager::update() { diff --git a/src/crepe/manager/LoopTimerManager.h b/src/crepe/manager/LoopTimerManager.h index 2f1e6b6..279d6b2 100644 --- a/src/crepe/manager/LoopTimerManager.h +++ b/src/crepe/manager/LoopTimerManager.h @@ -157,17 +157,17 @@ private: //! Time scale for speeding up or slowing down the game (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up). float time_scale = 1; //! Maximum delta time in seconds to avoid large jumps. - duration_t maximum_delta_time{0.25}; + duration_t maximum_delta_time {0.25}; //! Delta time for the current frame in seconds. - duration_t delta_time{0.0}; + duration_t delta_time {0.0}; //! Target time per frame in seconds - duration_t frame_target_time{1.0 / target_fps}; + duration_t frame_target_time {1.0 / target_fps}; //! Fixed delta time for fixed updates in seconds. - duration_t fixed_delta_time{1.0 / 50.0}; + duration_t fixed_delta_time {1.0 / 50.0}; //! Total elapsed game time in microseconds. - elapsed_time_t elapsed_time{0}; + elapsed_time_t elapsed_time {0}; //! Total elapsed time for fixed updates in microseconds. - elapsed_time_t elapsed_fixed_time{0}; + elapsed_time_t elapsed_fixed_time {0}; typedef std::chrono::steady_clock::time_point time_point_t; //! Time of the last frame. diff --git a/src/crepe/manager/ResourceManager.hpp b/src/crepe/manager/ResourceManager.hpp index cf5c949..4ca6be0 100644 --- a/src/crepe/manager/ResourceManager.hpp +++ b/src/crepe/manager/ResourceManager.hpp @@ -9,17 +9,20 @@ namespace crepe { template T & ResourceManager::get(const Asset & asset) { using namespace std; - static_assert(is_base_of::value, - "cache must recieve a derivative class of Resource"); + static_assert( + is_base_of::value, "cache must recieve a derivative class of Resource" + ); CacheEntry & entry = this->get_entry(asset); if (entry.resource == nullptr) entry.resource = make_unique(asset, this->mediator); T * concrete_resource = dynamic_cast(entry.resource.get()); if (concrete_resource == nullptr) - throw runtime_error(format("ResourceManager: mismatch between requested type and " - "actual type of resource ({})", - asset.get_path())); + throw runtime_error(format( + "ResourceManager: mismatch between requested type and " + "actual type of resource ({})", + asset.get_path() + )); return *concrete_resource; } diff --git a/src/crepe/manager/SceneManager.cpp b/src/crepe/manager/SceneManager.cpp index d4ca90b..e6f92db 100644 --- a/src/crepe/manager/SceneManager.cpp +++ b/src/crepe/manager/SceneManager.cpp @@ -17,10 +17,12 @@ void SceneManager::load_next_scene() { // next scene not set if (this->next_scene.empty()) return; - auto it = find_if(this->scenes.begin(), this->scenes.end(), - [&next_scene = this->next_scene](unique_ptr & scene) { - return scene.get()->get_name() == next_scene; - }); + auto it = find_if( + this->scenes.begin(), this->scenes.end(), + [&next_scene = this->next_scene](unique_ptr & scene) { + return scene.get()->get_name() == next_scene; + } + ); // next scene not found if (it == this->scenes.end()) return; diff --git a/src/crepe/manager/SystemManager.hpp b/src/crepe/manager/SystemManager.hpp index 8d06eb1..addd274 100644 --- a/src/crepe/manager/SystemManager.hpp +++ b/src/crepe/manager/SystemManager.hpp @@ -11,8 +11,9 @@ namespace crepe { template T & SystemManager::get_system() { using namespace std; - static_assert(is_base_of::value, - "get_system must recieve a derivative class of System"); + static_assert( + is_base_of::value, "get_system must recieve a derivative class of System" + ); const type_info & type = typeid(T); if (!this->systems.contains(type)) @@ -28,8 +29,9 @@ T & SystemManager::get_system() { template void SystemManager::load_system() { using namespace std; - static_assert(is_base_of::value, - "load_system must recieve a derivative class of System"); + static_assert( + is_base_of::value, "load_system must recieve a derivative class of System" + ); const type_info & type = typeid(T); if (this->systems.contains(type)) diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index 0f35010..94445c7 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -28,7 +28,8 @@ void AISystem::fixed_update() { = mgr.get_components_by_id(ai.game_object_id); if (rigidbodies.empty()) { throw std::runtime_error( - "AI component must be attached to a GameObject with a Rigidbody component"); + "AI component must be attached to a GameObject with a Rigidbody component" + ); } Rigidbody & rigidbody = rigidbodies.front().get(); if (!rigidbody.active) { @@ -110,8 +111,8 @@ bool AISystem::accumulate_force(const AI & ai, vec2 & running_total, vec2 & forc return true; } -vec2 AISystem::seek(const AI & ai, const Rigidbody & rigidbody, - const Transform & transform) const { +vec2 AISystem::seek(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) + const { // Calculate the desired velocity vec2 desired_velocity = ai.seek_target - transform.position; desired_velocity.normalize(); @@ -120,12 +121,12 @@ vec2 AISystem::seek(const AI & ai, const Rigidbody & rigidbody, return desired_velocity - rigidbody.data.linear_velocity; } -vec2 AISystem::flee(const AI & ai, const Rigidbody & rigidbody, - const Transform & transform) const { +vec2 AISystem::flee(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) + const { // Calculate the desired velocity if the entity is within the panic distance vec2 desired_velocity = transform.position - ai.flee_target; if (desired_velocity.length_squared() > ai.square_flee_panic_distance) { - return vec2{0, 0}; + return vec2 {0, 0}; } desired_velocity.normalize(); desired_velocity *= rigidbody.data.max_linear_velocity; @@ -133,8 +134,8 @@ vec2 AISystem::flee(const AI & ai, const Rigidbody & rigidbody, return desired_velocity - rigidbody.data.linear_velocity; } -vec2 AISystem::arrive(const AI & ai, const Rigidbody & rigidbody, - const Transform & transform) const { +vec2 AISystem::arrive(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) + const { // Calculate the desired velocity (taking into account the deceleration rate) vec2 to_target = ai.arrive_target - transform.position; float distance = to_target.length(); @@ -150,12 +151,12 @@ vec2 AISystem::arrive(const AI & ai, const Rigidbody & rigidbody, return desired_velocity - rigidbody.data.linear_velocity; } - return vec2{0, 0}; + return vec2 {0, 0}; } vec2 AISystem::path_follow(AI & ai, const Rigidbody & rigidbody, const Transform & transform) { if (ai.path.empty()) { - return vec2{0, 0}; + return vec2 {0, 0}; } // Get the target node diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 654d4c6..571ac70 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -50,9 +50,11 @@ void CollisionSystem::fixed_update() { for (BoxCollider & boxcollider : boxcolliders) { if (boxcollider.game_object_id != id) continue; if (!boxcollider.active) continue; - all_colliders.push_back({.id = id, - .collider = collider_variant{boxcollider}, - .info = {transform, rigidbody, metadata}}); + all_colliders.push_back( + {.id = id, + .collider = collider_variant {boxcollider}, + .info = {transform, rigidbody, metadata}} + ); } // Check if the circlecollider is active and has the same id as the rigidbody. RefVector circlecolliders @@ -60,9 +62,11 @@ void CollisionSystem::fixed_update() { for (CircleCollider & circlecollider : circlecolliders) { if (circlecollider.game_object_id != id) continue; if (!circlecollider.active) continue; - all_colliders.push_back({.id = id, - .collider = collider_variant{circlecollider}, - .info = {transform, rigidbody, metadata}}); + all_colliders.push_back( + {.id = id, + .collider = collider_variant {circlecollider}, + .info = {transform, rigidbody, metadata}} + ); } } @@ -110,8 +114,9 @@ CollisionSystem::gather_collisions(std::vector & colliders) { return collisions_ret; } -bool CollisionSystem::should_collide(const CollisionInternal & self, - const CollisionInternal & other) const { +bool CollisionSystem::should_collide( + const CollisionInternal & self, const CollisionInternal & other +) const { const Rigidbody::Data & self_rigidbody = self.info.rigidbody.data; const Rigidbody::Data & other_rigidbody = other.info.rigidbody.data; @@ -133,9 +138,9 @@ bool CollisionSystem::should_collide(const CollisionInternal & self, return false; } -CollisionSystem::CollisionInternalType -CollisionSystem::get_collider_type(const collider_variant & collider1, - const collider_variant & collider2) const { +CollisionSystem::CollisionInternalType CollisionSystem::get_collider_type( + const collider_variant & collider1, const collider_variant & collider2 +) const { if (std::holds_alternative>(collider1)) { if (std::holds_alternative>(collider2)) { return CollisionInternalType::CIRCLE_CIRCLE; @@ -151,8 +156,9 @@ CollisionSystem::get_collider_type(const collider_variant & collider1, } } -bool CollisionSystem::detect_collision(CollisionInternal & self, CollisionInternal & other, - const CollisionInternalType & type) { +bool CollisionSystem::detect_collision( + CollisionInternal & self, CollisionInternal & other, const CollisionInternalType & type +) { vec2 resolution; switch (type) { case CollisionInternalType::BOX_BOX: { @@ -177,10 +183,11 @@ bool CollisionSystem::detect_collision(CollisionInternal & self, CollisionIntern = {.collider = std::get>(self.collider), .transform = self.info.transform, .rigidbody = self.info.rigidbody}; - const CircleColliderInternal CIRCLE2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody}; + const CircleColliderInternal CIRCLE2 + = {.collider + = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody}; // Get resolution vector from box-circle collision detection resolution = this->get_box_circle_detection(BOX1, CIRCLE2); // If no collision (NaN values), return false @@ -195,10 +202,11 @@ bool CollisionSystem::detect_collision(CollisionInternal & self, CollisionIntern = {.collider = std::get>(self.collider), .transform = self.info.transform, .rigidbody = self.info.rigidbody}; - const CircleColliderInternal CIRCLE2 = { - .collider = std::get>(other.collider), - .transform = other.info.transform, - .rigidbody = other.info.rigidbody}; + const CircleColliderInternal CIRCLE2 + = {.collider + = std::get>(other.collider), + .transform = other.info.transform, + .rigidbody = other.info.rigidbody}; // Get resolution vector from circle-circle collision detection resolution = this->get_circle_circle_detection(CIRCLE1, CIRCLE2); // If no collision (NaN values), return false @@ -239,9 +247,10 @@ bool CollisionSystem::detect_collision(CollisionInternal & self, CollisionIntern return true; } -vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, - const BoxColliderInternal & box2) const { - vec2 resolution{NAN, NAN}; +vec2 CollisionSystem::get_box_box_detection( + const BoxColliderInternal & box1, const BoxColliderInternal & box2 +) const { + vec2 resolution {NAN, NAN}; // Get current positions of colliders vec2 pos1 = AbsolutePosition::get_position(box1.transform, box1.collider.offset); vec2 pos2 = AbsolutePosition::get_position(box2.transform, box2.collider.offset); @@ -282,8 +291,9 @@ vec2 CollisionSystem::get_box_box_detection(const BoxColliderInternal & box1, return resolution; } -vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, - const CircleColliderInternal & circle) const { +vec2 CollisionSystem::get_box_circle_detection( + const BoxColliderInternal & box, const CircleColliderInternal & circle +) const { /// Get current positions of colliders vec2 box_pos = AbsolutePosition::get_position(box.transform, box.collider.offset); vec2 circle_pos = AbsolutePosition::get_position(circle.transform, circle.collider.offset); @@ -324,14 +334,15 @@ vec2 CollisionSystem::get_box_circle_detection(const BoxColliderInternal & box, float penetration_depth = scaled_circle_radius - distance; // Compute the resolution vector - return vec2{collision_normal * penetration_depth}; + return vec2 {collision_normal * penetration_depth}; } // No collision - return vec2{NAN, NAN}; + return vec2 {NAN, NAN}; } vec2 CollisionSystem::get_circle_circle_detection( - const CircleColliderInternal & circle1, const CircleColliderInternal & circle2) const { + const CircleColliderInternal & circle1, const CircleColliderInternal & circle2 +) const { // Get current positions of colliders vec2 final_position1 = AbsolutePosition::get_position(circle1.transform, circle1.collider.offset); @@ -371,7 +382,7 @@ vec2 CollisionSystem::get_circle_circle_detection( return resolution; } // No collision - return vec2{NAN, NAN}; + return vec2 {NAN, NAN}; ; } @@ -402,17 +413,17 @@ CollisionSystem::resolution_correction(vec2 & resolution, const Rigidbody::Data return resolution_direction; } -CollisionSystem::CollisionInfo -CollisionSystem::get_collision_info(const CollisionInternal & in_self, - const CollisionInternal & in_other) const { +CollisionSystem::CollisionInfo CollisionSystem::get_collision_info( + const CollisionInternal & in_self, const CollisionInternal & in_other +) const { - crepe::CollisionSystem::ColliderInfo self{ + crepe::CollisionSystem::ColliderInfo self { .transform = in_self.info.transform, .rigidbody = in_self.info.rigidbody, .metadata = in_self.info.metadata, }; - crepe::CollisionSystem::ColliderInfo other{ + crepe::CollisionSystem::ColliderInfo other { .transform = in_other.info.transform, .rigidbody = in_other.info.rigidbody, .metadata = in_other.info.metadata, diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index 3fb9723..ff2d35f 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -60,8 +60,8 @@ public: private: //! A variant type that can hold either a BoxCollider or a CircleCollider. - using collider_variant = std::variant, - std::reference_wrapper>; + using collider_variant = std::variant< + std::reference_wrapper, std::reference_wrapper>; //! Enum representing the types of collider pairs for collision detection. enum class CollisionInternalType { @@ -114,8 +114,9 @@ private: * \param collider2 Second collider variant (BoxCollider or CircleCollider). * \return The combined type of the two colliders. */ - CollisionInternalType get_collider_type(const collider_variant & collider1, - const collider_variant & collider2) const; + CollisionInternalType get_collider_type( + const collider_variant & collider1, const collider_variant & collider2 + ) const; private: /** @@ -128,8 +129,8 @@ private: * \param data1 Collision data for the first collider. * \param data2 Collision data for the second collider. */ - CollisionInfo get_collision_info(const CollisionInternal & data1, - const CollisionInternal & data2) const; + CollisionInfo + get_collision_info(const CollisionInternal & data1, const CollisionInternal & data2) const; /** * \brief Corrects the collision resolution vector and determines its direction. @@ -221,8 +222,10 @@ private: * \param other_metadata Rigidbody of second object * \return Returns true if there is at least one comparison found. */ - bool should_collide(const CollisionInternal & self, - const CollisionInternal & other) const; //done + bool should_collide( + const CollisionInternal & self, + const CollisionInternal & other + ) const; //done /** * \brief Checks for collision between two colliders. @@ -236,8 +239,10 @@ private: * \param type The type of collider pair. * \return True if a collision is detected, otherwise false. */ - bool detect_collision(CollisionInternal & first_info, CollisionInternal & second_info, - const CollisionInternalType & type); + bool detect_collision( + CollisionInternal & first_info, CollisionInternal & second_info, + const CollisionInternalType & type + ); /** * \brief Detects collisions between two BoxColliders. @@ -250,8 +255,9 @@ private: * \param box2 Information about the second BoxCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_box_box_detection(const BoxColliderInternal & box1, - const BoxColliderInternal & box2) const; + vec2 get_box_box_detection( + const BoxColliderInternal & box1, const BoxColliderInternal & box2 + ) const; /** * \brief Check collision for box on circle collider @@ -264,8 +270,9 @@ private: * \param circle2 Information about the circleCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_box_circle_detection(const BoxColliderInternal & box1, - const CircleColliderInternal & circle2) const; + vec2 get_box_circle_detection( + const BoxColliderInternal & box1, const CircleColliderInternal & circle2 + ) const; /** * \brief Check collision for circle on circle collider @@ -278,8 +285,9 @@ private: * \param circle2 Information about the second circleCollider. * \return If colliding, returns the resolution vector; otherwise, returns {NaN, NaN}. */ - vec2 get_circle_circle_detection(const CircleColliderInternal & circle1, - const CircleColliderInternal & circle2) const; + vec2 get_circle_circle_detection( + const CircleColliderInternal & circle1, const CircleColliderInternal & circle2 + ) const; }; /** diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp index 8e9f763..b4a0633 100644 --- a/src/crepe/system/InputSystem.cpp +++ b/src/crepe/system/InputSystem.cpp @@ -44,8 +44,9 @@ void InputSystem::fixed_update() { } } -void InputSystem::handle_mouse_event(const EventData & event, const vec2 & camera_origin, - const Camera & current_cam) { +void InputSystem::handle_mouse_event( + const EventData & event, const vec2 & camera_origin, const Camera & current_cam +) { EventManager & event_mgr = this->mediator.event_manager; vec2 adjusted_mouse; adjusted_mouse.x = event.data.mouse_data.mouse_position.x + camera_origin.x; @@ -82,8 +83,9 @@ void InputSystem::handle_mouse_event(const EventData & event, const vec2 & camer .mouse_pos = adjusted_mouse, .button = event.data.mouse_data.mouse_button, }); - this->handle_click(event.data.mouse_data.mouse_button, adjusted_mouse, - current_cam); + this->handle_click( + event.data.mouse_data.mouse_button, adjusted_mouse, current_cam + ); } break; } @@ -115,7 +117,8 @@ void InputSystem::handle_non_mouse_event(const EventData & event) { case EventType::KEY_DOWN: event_mgr.queue_event( - {.repeat = event.data.key_data.key_repeat, .key = event.data.key_data.key}); + {.repeat = event.data.key_data.key_repeat, .key = event.data.key_data.key} + ); break; case EventType::KEY_UP: event_mgr.queue_event({.key = event.data.key_data.key}); @@ -128,11 +131,13 @@ void InputSystem::handle_non_mouse_event(const EventData & event) { break; case EventType::WINDOW_RESIZE: event_mgr.queue_event( - WindowResizeEvent{.dimensions = event.data.window_data.resize_dimension}); + WindowResizeEvent {.dimensions = event.data.window_data.resize_dimension} + ); break; case EventType::WINDOW_MOVE: event_mgr.queue_event( - {.delta_move = event.data.window_data.move_delta}); + {.delta_move = event.data.window_data.move_delta} + ); break; case EventType::WINDOW_MINIMIZE: event_mgr.queue_event({}); @@ -151,8 +156,9 @@ void InputSystem::handle_non_mouse_event(const EventData & event) { } } -void InputSystem::handle_move(const EventData & event_data, const vec2 & mouse_pos, - const Camera & current_cam) { +void InputSystem::handle_move( + const EventData & event_data, const vec2 & mouse_pos, const Camera & current_cam +) { ComponentManager & mgr = this->mediator.component_manager; EventManager & event_mgr = this->mediator.event_manager; const RefVector