Compare commits

...

5 Commits

Author SHA1 Message Date
b18bfe873f Collision 2/2 2025-09-29 13:03:18 +05:30
5f112f7531 Collision 1/2 2025-09-29 03:36:31 +05:30
3380eb993e Debug Draw 2025-09-29 01:24:46 +05:30
fe88538e3c Debug Draw Base 2025-09-29 01:02:02 +05:30
3c5792e975 Remove Box2D 2025-09-28 21:53:23 +05:30
24 changed files with 736 additions and 522 deletions

View File

@ -2,9 +2,9 @@
#include <IAEngine/Input.hpp> #include <IAEngine/Input.hpp>
#include <IAEngine/Rendering/Camera.hpp> #include <IAEngine/Rendering/Camera.hpp>
#include <IAEngine/Components/PhysicsBody2D.hpp> #include <IAEngine/Rendering/DebugDraw.hpp>
#include <IAEngine/Components/BoxCollider2D.hpp>
#include <IAEngine/Components/SpriteRenderer.hpp> #include <IAEngine/Components/SpriteRenderer.hpp>
#include <IAEngine/Components/Physics.hpp>
#include <IACore/File.hpp> #include <IACore/File.hpp>
@ -13,7 +13,7 @@ namespace ia::iae::game
RefPtr<Scene> scene; RefPtr<Scene> scene;
RefPtr<Node> g_player; RefPtr<Node> g_player;
PhysicsBody2DComponent* g_playerPhysicsBody{}; PhysicsComponent* g_playerPhysics;
VOID Game::Initialize() VOID Game::Initialize()
{ {
@ -34,20 +34,18 @@ namespace ia::iae::game
}); });
t->BakeAnimations(); t->BakeAnimations();
} }
{ g_playerPhysics = g_player->AddComponent<PhysicsComponent>();
g_playerPhysicsBody = g_player->AddComponent<PhysicsBody2DComponent>(); g_playerPhysics->AddCollider({
g_playerPhysicsBody->IsDynamic() = true; .IsTrigger = false,
const auto collider = g_player->AddComponent<BoxCollider2DComponent>(); .Position = {
collider->Rect() = { 0.0f, 0.0f,
0, },
0, .Size = {
g_player->DrawnSize().x, 25.0f, 25.0f
g_player->DrawnSize().y, }
}; });
collider->IsDebugDrawEnabled() = true;
}
g_player->Tags() = NODE_TAG_PLAYER; g_player->Tags() = NODE_TAG_PLAYER;
g_player->SetLocalPosition({200, 200}); g_player->SetLocalPosition({200, 300});
const auto obstacle = MakeRefPtr<Node>(); const auto obstacle = MakeRefPtr<Node>();
{ {
@ -56,23 +54,23 @@ namespace ia::iae::game
.ShouldLoop = true, .ShouldLoop = true,
.Keys = { .Keys = {
SpriteRendererComponent::AnimationKeyFrame { SpriteRendererComponent::AnimationKeyFrame {
.Scale = {3.0f, 0.5f}, .Scale = {1.0f, 0.5f},
.ColorOverlay = {0.75f, 0.0f, 0.0f, 1.0f} .ColorOverlay = {0.75f, 0.0f, 0.0f, 1.0f}
} }
}, },
}); });
t->BakeAnimations(); t->BakeAnimations();
} }
{ const auto obstaclePhysics = obstacle->AddComponent<PhysicsComponent>();
obstacle->AddComponent<PhysicsBody2DComponent>(); obstaclePhysics->AddCollider({
const auto collider = obstacle->AddComponent<BoxCollider2DComponent>(); .IsTrigger = false,
collider->Rect() = { .Position = {
0, 0, 0.0f, 0.0f,
obstacle->DrawnSize().x, },
obstacle->DrawnSize().y .Size = {
}; 100.0f, 50.0f
collider->IsDebugDrawEnabled() = true; }
} });
obstacle->Tags() = NODE_TAG_GROUND; obstacle->Tags() = NODE_TAG_GROUND;
obstacle->SetLocalSortIndex(20); obstacle->SetLocalSortIndex(20);
obstacle->SetLocalPosition({200, 400}); obstacle->SetLocalPosition({200, 400});
@ -89,8 +87,7 @@ namespace ia::iae::game
VOID Game::Update() VOID Game::Update()
{ {
if(Input::WasKeyPressed(Input::KEY_SPACE)) const auto d = Input::GetDirectionalInput();
g_playerPhysicsBody->Jump(200.0f); g_playerPhysics->Move(d);
g_playerPhysicsBody->SetVelocityX(Input::GetDirectionalInput().x * 100.0f);
} }
} }

View File

@ -13,9 +13,11 @@ set(IAEngine_Sources
imp/cpp/Rendering/Renderer.cpp imp/cpp/Rendering/Renderer.cpp
imp/cpp/Rendering/GPUBuffer.cpp imp/cpp/Rendering/GPUBuffer.cpp
imp/cpp/Rendering/GPUTexture.cpp imp/cpp/Rendering/GPUTexture.cpp
imp/cpp/Rendering/DebugDraw.cpp
imp/cpp/Rendering/Pipeline/Pipeline.cpp imp/cpp/Rendering/Pipeline/Pipeline.cpp
imp/cpp/Rendering/Pipeline/UnlitMesh.cpp imp/cpp/Rendering/Pipeline/UnlitMesh.cpp
imp/cpp/Rendering/Pipeline/PostProcess.cpp
imp/cpp/Physics/Physics.cpp imp/cpp/Physics/Physics.cpp
@ -25,12 +27,11 @@ set(IAEngine_Sources
imp/cpp/Nodes/Node.cpp imp/cpp/Nodes/Node.cpp
imp/cpp/Components/AtlasRenderer.cpp imp/cpp/Components/AtlasRenderer.cpp
imp/cpp/Components/BoxCollider2D.cpp
imp/cpp/Components/SpriteRenderer.cpp imp/cpp/Components/SpriteRenderer.cpp
imp/cpp/Components/SoundEmitter.cpp imp/cpp/Components/SoundEmitter.cpp
imp/cpp/Components/ParticleEmitter.cpp imp/cpp/Components/ParticleEmitter.cpp
imp/cpp/Components/PhysicsBody2D.cpp
imp/cpp/Components/TextureRenderer.cpp imp/cpp/Components/TextureRenderer.cpp
imp/cpp/Components/Physics.cpp
) )
add_library(IAEngine STATIC ${IAEngine_Sources}) add_library(IAEngine STATIC ${IAEngine_Sources})
@ -39,4 +40,4 @@ target_include_directories(IAEngine PUBLIC inc/)
target_include_directories(IAEngine PRIVATE imp/hpp) target_include_directories(IAEngine PRIVATE imp/hpp)
target_link_libraries(IAEngine PUBLIC IACore ImGui glm::glm) target_link_libraries(IAEngine PUBLIC IACore ImGui glm::glm)
target_link_libraries(IAEngine PRIVATE SDL3::SDL3 SDL3_mixer::SDL3_mixer box2d RmlUi::RmlUi) target_link_libraries(IAEngine PRIVATE SDL3::SDL3 SDL3_mixer::SDL3_mixer RmlUi::RmlUi)

View File

@ -1,62 +0,0 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <IAEngine/Components/BoxCollider2D.hpp>
#include <IAEngine/Components/PhysicsBody2D.hpp>
#include <IAEngine/Components/TextureRenderer.hpp>
#include <IAEngine/Rendering/Renderer.hpp>
#include <IAEngine/Physics/Physics.hpp>
#include <IAEngine/Nodes/Node.hpp>
namespace ia::iae
{
EXTERN Texture g_whiteStrokeTexture;
BoxCollider2DComponent::BoxCollider2DComponent(IN Node *node) : IComponent(node)
{
IA_RELEASE_ASSERT(m_body = node->GetComponent<PhysicsBody2DComponent>());
m_physicsHandle = Physics::AddColliderToBody(m_body->PhysicsHandle(), this);
}
VOID BoxCollider2DComponent::Draw()
{
if (!m_isDebugDrawEnabled)
return;
Renderer::Draw(Renderer::GetMesh_Quad(), g_whiteStrokeTexture.GetHandle(), m_node->GetPosition() + glm::vec2{m_rect.x, m_rect.y},
glm::vec2{m_rect.z, m_rect.w}, 0, Renderer::MAX_LAYER_INDEX,
0, {1.0f, 1.0f, 1.0f, 1.0f});
}
VOID BoxCollider2DComponent::Update()
{
}
VOID BoxCollider2DComponent::OnCollisionEnter(IN Node *other)
{
if (other->HasTag(NODE_TAG_GROUND))
m_body->IsGrounded() = true;
if(m_collisionEnterCallback)
m_collisionEnterCallback(other);
}
VOID BoxCollider2DComponent::OnCollisionExit(IN Node *other)
{
if (other->HasTag(NODE_TAG_GROUND))
m_body->IsGrounded() = false;
if(m_collisionExitCallback)
m_collisionExitCallback(other);
}
} // namespace ia::iae

View File

@ -0,0 +1,75 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <IAEngine/Components/Physics.hpp>
#include <IAEngine/Physics/Physics.hpp>
#include <IAEngine/Nodes/Node.hpp>
namespace ia::iae
{
PhysicsComponent::PhysicsComponent(IN Node *node) : IComponent(node)
{
m_physicsHandle = Physics::RegisterComponent(this);
}
PhysicsComponent::~PhysicsComponent()
{
}
VOID PhysicsComponent::Draw()
{
}
VOID PhysicsComponent::Update()
{
}
Handle PhysicsComponent::CreateCollider()
{
m_colliders.pushBack({});
return m_colliders.size() - 1;
}
Handle PhysicsComponent::AddCollider(IN Collider collider)
{
m_colliders.pushBack(collider);
return m_colliders.size() - 1;
}
PhysicsComponent::Collider &PhysicsComponent::GetCollider(IN Handle handle)
{
return m_colliders[handle];
}
VOID PhysicsComponent::Move(IN glm::vec2 direction)
{
const auto v = direction * m_movementSpeed;
for(const auto& t: m_colliders)
{
if(!Physics::CanMove(m_physicsHandle, t, v))
return;
}
m_node->SetLocalPosition(m_node->GetLocalPosition() + v);
}
VOID PhysicsComponent::Jump(IN FLOAT32 force)
{
}
VOID PhysicsComponent::OnCollision(IN PhysicsComponent *other)
{
}
} // namespace ia::iae

View File

@ -1,66 +0,0 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <IAEngine/Components/BoxCollider2D.hpp>
#include <IAEngine/Components/PhysicsBody2D.hpp>
#include <IAEngine/Nodes/Node.hpp>
#include <IAEngine/Physics/Physics.hpp>
namespace ia::iae
{
PhysicsBody2DComponent::PhysicsBody2DComponent(IN Node *node) : IComponent(node)
{
m_physicsHandle = Physics::AddBody(this);
}
VOID PhysicsBody2DComponent::Draw()
{
}
VOID PhysicsBody2DComponent::Update()
{
if (m_isDynamic)
m_node->SetLocalPosition(Physics::GetBodyPosition(m_physicsHandle));
if (!m_isRotationLocked)
m_node->SetLocalRotation(Physics::GetBodyRotation(m_physicsHandle));
}
VOID PhysicsBody2DComponent::SetVelocity(IN glm::vec2 v)
{
Physics::SetBodyVelocity(m_physicsHandle, v);
}
VOID PhysicsBody2DComponent::SetVelocityX(IN FLOAT32 v)
{
Physics::SetBodyVelocityX(m_physicsHandle, v);
}
VOID PhysicsBody2DComponent::SetVelocityY(IN FLOAT32 v)
{
Physics::SetBodyVelocityY(m_physicsHandle, v);
}
VOID PhysicsBody2DComponent::ApplyForce(IN glm::vec2 force)
{
Physics::ApplyBodyForce(m_physicsHandle, force);
}
VOID PhysicsBody2DComponent::Jump(IN FLOAT32 velocity)
{
if(m_isGrounded)
Physics::SetBodyVelocityY(m_physicsHandle, -velocity);
}
} // namespace ia::iae

View File

@ -132,11 +132,12 @@ namespace ia::iae
VOID Engine::UpdateGame() VOID Engine::UpdateGame()
{ {
Physics::Update();
if B_LIKELY (g_activeScene) if B_LIKELY (g_activeScene)
g_activeScene->Update(); g_activeScene->Update();
UI::Update(); UI::Update();
Physics::Update();
} }
VOID Engine::RenderGame() VOID Engine::RenderGame()

View File

@ -19,171 +19,118 @@
#include <IAEngine/Nodes/Node.hpp> #include <IAEngine/Nodes/Node.hpp>
#include <box2d/box2d.h>
#include <map> #include <map>
namespace ia::iae namespace ia::iae
{ {
struct Body Vector<PhysicsComponent *> g_physicsComponents;
{
struct Collider
{
b2ShapeId ShapeId{};
BoxCollider2DComponent *ColliderComponent{};
};
b2BodyId BodyId{.world0 = 0xFFFF}; FLOAT32 Sq(IN FLOAT32 v)
PhysicsBody2DComponent *BodyComponent; {
Vector<Collider> Colliders; return v * v;
}
enum class RectSide
{
NONE,
LEFT,
RIGHT,
TOP,
BOTTOM,
}; };
b2WorldId g_worldId{}; RectSide GetRectSide(IN glm::vec2 d)
Vector<Body> g_bodies;
std::map<Handle, BoxCollider2DComponent*> g_shapeColliders;
INLINE Handle ShapeIdToHandle(IN b2ShapeId id)
{ {
return *reinterpret_cast<Handle*>(&id.index1); const auto dX = abs(d.x);
const auto dY = abs(d.y);
if (d.x >= 0)
{
if (dX >= dY)
{
return RectSide::RIGHT;
}
else
{
return (d.y < 0) ? RectSide::TOP : RectSide::BOTTOM;
}
}
else
{
if (dX >= dY)
{
return RectSide::LEFT;
}
else
{
return (d.y < 0) ? RectSide::TOP : RectSide::BOTTOM;
}
}
return RectSide::NONE;
} }
VOID Physics::Initialize() VOID Physics::Initialize()
{ {
auto worldDef = b2DefaultWorldDef();
worldDef.gravity = b2Vec2{0.0f, 1000.0f};
g_worldId = b2CreateWorld(&worldDef);
} }
VOID Physics::Terminate() VOID Physics::Terminate()
{ {
b2DestroyWorld(g_worldId);
} }
VOID Physics::Update() VOID Physics::Update()
{ {
CONSTEXPR FLOAT32 TIME_STEP = 1.0f / 60.0f;
CONSTEXPR INT32 SUB_STEP_COUNT = 4;
b2World_Step(g_worldId, TIME_STEP, SUB_STEP_COUNT);
// Process contact events
const auto contactEvents = b2World_GetContactEvents(g_worldId);
for(INT32 i = 0; i < contactEvents.beginCount; i++)
{
const auto& shapeA = g_shapeColliders[ShapeIdToHandle(contactEvents.beginEvents[i].shapeIdA)];
const auto& shapeB = g_shapeColliders[ShapeIdToHandle(contactEvents.beginEvents[i].shapeIdB)];
shapeA->OnCollisionEnter(shapeB->GetNode());
shapeB->OnCollisionEnter(shapeA->GetNode());
}
for(INT32 i = 0; i < contactEvents.endCount; i++)
{
const auto& shapeA = g_shapeColliders[ShapeIdToHandle(contactEvents.endEvents[i].shapeIdA)];
const auto& shapeB = g_shapeColliders[ShapeIdToHandle(contactEvents.endEvents[i].shapeIdB)];
shapeA->OnCollisionExit(shapeB->GetNode());
shapeB->OnCollisionExit(shapeA->GetNode());
}
// Process sensor events
const auto sensorEvents = b2World_GetSensorEvents(g_worldId);
for(INT32 i = 0; i < sensorEvents.beginCount; i++)
{
const auto& shapeA = g_shapeColliders[ShapeIdToHandle(sensorEvents.beginEvents[i].sensorShapeId)];
const auto& shapeB = g_shapeColliders[ShapeIdToHandle(sensorEvents.beginEvents[i].visitorShapeId)];
shapeA->OnCollisionEnter(shapeB->GetNode());
shapeB->OnCollisionEnter(shapeA->GetNode());
}
for(INT32 i = 0; i < sensorEvents.endCount; i++)
{
const auto& shapeA = g_shapeColliders[ShapeIdToHandle(sensorEvents.endEvents[i].sensorShapeId)];
const auto& shapeB = g_shapeColliders[ShapeIdToHandle(sensorEvents.endEvents[i].visitorShapeId)];
shapeA->OnCollisionExit(shapeB->GetNode());
shapeB->OnCollisionExit(shapeA->GetNode());
}
} }
VOID Physics::Bake() Handle Physics::RegisterComponent(IN PhysicsComponent *component)
{ {
for (auto &b : g_bodies) g_physicsComponents.pushBack(component);
return g_physicsComponents.size() - 1;
}
BOOL Physics::CanMove(IN Handle handle, IN CONST PhysicsComponent::Collider &collider, IN glm::vec2 movement)
{
const auto comp = g_physicsComponents[handle];
const auto middle = comp->GetNode()->GetPosition() + movement + collider.Position + collider.Size / 2.0f;
const auto halfSize = collider.Size / 2.0f;
for (const auto &t : g_physicsComponents)
{ {
const auto drawnSize = b.BodyComponent->GetNode()->DrawnSize(); if (t == comp)
const auto pos = b.BodyComponent->GetNode()->GetPosition(); continue;
for (const auto &tc : t->Colliders())
auto bodyDef = b2DefaultBodyDef();
if (b.BodyComponent->IsDynamic())
bodyDef.type = b2_dynamicBody;
bodyDef.position = b2Vec2{pos.x + drawnSize.x/2.0f, pos.y + drawnSize.y/2.0f};
if (b.BodyId.world0 != 0xFFFF)
b2DestroyBody(b.BodyId);
b.BodyId = b2CreateBody(g_worldId, &bodyDef);
for (auto &c : b.Colliders)
{ {
const auto rect = c.ColliderComponent->Rect(); BOOL isColliding = false;
const auto halfW = rect.z/2.0f; const auto tMiddle = t->GetNode()->GetPosition() + tc.Position + tc.Size / 2.0f;
const auto halfH = rect.w/2.0f; const auto tHalfSize = tc.Size / 2.0f;
const auto box = b2MakeOffsetBox(halfW, halfH, {rect.x, rect.y}, b2MakeRot(0)); const auto rectSide = GetRectSide(tMiddle - middle);
auto boxShapeDef = b2DefaultShapeDef(); const auto distance = Sq(tMiddle.x - middle.x) + Sq(tMiddle.y - middle.y);
boxShapeDef.density = 1.0f; switch (rectSide)
boxShapeDef.isSensor = c.ColliderComponent->IsTrigger(); {
boxShapeDef.enableContactEvents = c.ColliderComponent->CollisionsEnabled(); case RectSide::LEFT:
boxShapeDef.enableSensorEvents = boxShapeDef.enableContactEvents; case RectSide::RIGHT:
c.ShapeId = b2CreatePolygonShape(b.BodyId, &boxShapeDef, &box); isColliding = (Sq(tHalfSize.x + halfSize.x) >= distance);
g_shapeColliders[ShapeIdToHandle(c.ShapeId)] = c.ColliderComponent; break;
case RectSide::TOP:
case RectSide::BOTTOM:
isColliding = (Sq(tHalfSize.y + halfSize.y) >= distance);
break;
default:
isColliding = false;
break;
}
if (isColliding)
{
// Collision callback
comp->OnCollision(t);
t->OnCollision(comp);
// Overlap block
if (tc.IsTrigger)
continue;
return false;
}
} }
} }
} return true;
Handle Physics::AddBody(IN PhysicsBody2DComponent *body)
{
g_bodies.pushBack(Body{
.BodyComponent = body,
});
return g_bodies.size() - 1;
}
Handle Physics::AddColliderToBody(IN Handle bodyHandle, IN BoxCollider2DComponent *collider)
{
auto &b = g_bodies[bodyHandle];
b.Colliders.pushBack(Body::Collider{
.ColliderComponent = collider,
});
return b.Colliders.size() - 1;
}
FLOAT32 Physics::GetBodyRotation(IN Handle handle)
{
const auto &b = g_bodies[handle];
return acosf(b2Body_GetRotation(b.BodyId).c);
}
glm::vec2 Physics::GetBodyPosition(IN Handle handle)
{
const auto &b = g_bodies[handle];
const auto drawnSize = b.BodyComponent->GetNode()->DrawnSize();
const auto v = b2Body_GetPosition(b.BodyId);
return {v.x - drawnSize.x/2.0f, v.y - drawnSize.y/2.0f};
}
VOID Physics::ApplyBodyForce(IN Handle handle, IN glm::vec2 force)
{
const auto &b = g_bodies[handle];
b2Body_ApplyForce(b.BodyId, {force.x, force.y}, b2Body_GetLocalCenterOfMass(b.BodyId), true);
}
VOID Physics::SetBodyVelocity(IN Handle handle, IN glm::vec2 v)
{
const auto &b = g_bodies[handle];
b2Body_SetLinearVelocity(b.BodyId, {v.x, v.y});
}
VOID Physics::SetBodyVelocityX(IN Handle handle, IN FLOAT32 v)
{
const auto &b = g_bodies[handle];
b2Body_SetLinearVelocity(b.BodyId, {v, b2Body_GetLinearVelocity(b.BodyId).y});
}
VOID Physics::SetBodyVelocityY(IN Handle handle, IN FLOAT32 v)
{
const auto &b = g_bodies[handle];
b2Body_SetLinearVelocity(b.BodyId, {b2Body_GetLinearVelocity(b.BodyId).x, v});
} }
} // namespace ia::iae } // namespace ia::iae

View File

@ -0,0 +1,189 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <IAEngine/IAEngine.hpp>
#include <IAEngine/Rendering/Camera.hpp>
#include <IAEngine/Rendering/DebugDraw.hpp>
#include <IAEngine/Rendering/GPUBuffer.hpp>
#include <IAEngine/Rendering/GPUTexture.hpp>
#include <IAEngine/Rendering/Pipeline/UnlitMesh.hpp>
#include <IAEngine/Rendering/Renderer.hpp>
#include <SDL3/SDL_gpu.h>
#include <backends/imgui_impl_sdl3.h>
#include <backends/imgui_impl_sdlgpu3.h>
namespace ia::iae
{
EXTERN SDL_Window *g_windowHandle;
EXTERN SDL_GPUDevice *g_gpuDevice;
ImGuiIO g_imGUIIO{};
struct ShapeLine
{
ImVec2 To{};
ImVec2 From{};
ImColor Color{};
FLOAT32 Thickness{1.0f};
BOOL Visibility{true};
};
struct ShapeRect
{
ImVec2 TopLeft{};
ImVec2 BottomRight{};
ImColor Color{};
BOOL Visibility{true};
};
struct UIWindow
{
PCCHAR Title{""};
glm::vec2 Position{};
glm::vec2 Size{};
std::function<VOID()> ContentDrawCallback{};
BOOL Visibility{true};
};
Vector<UIWindow> g_debugUIWindows;
Vector<ShapeLine> g_lineShapes;
Vector<ShapeRect> g_rectShapes;
VOID DebugDraw::Initailize()
{
const auto mainScale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
IMGUI_CHECKVERSION();
ImGui::CreateContext();
g_imGUIIO = ImGui::GetIO();
g_imGUIIO.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
g_imGUIIO.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
ImGui::StyleColorsClassic();
ImGuiStyle &style = ImGui::GetStyle();
style.ScaleAllSizes(mainScale);
style.FontScaleDpi = mainScale;
ImGui_ImplSDLGPU3_InitInfo initInfo{.Device = g_gpuDevice,
.ColorTargetFormat =
SDL_GetGPUSwapchainTextureFormat(g_gpuDevice, g_windowHandle),
.PresentMode = SDL_GPU_PRESENTMODE_VSYNC};
ImGui_ImplSDL3_InitForSDLGPU(g_windowHandle);
ImGui_ImplSDLGPU3_Init(&initInfo);
}
VOID DebugDraw::Terminate()
{
ImGui_ImplSDL3_Shutdown();
ImGui_ImplSDLGPU3_Shutdown();
ImGui::DestroyContext();
}
VOID DebugDraw::Draw()
{
for (const auto &w : g_debugUIWindows)
{
if (!w.Visibility)
continue;
ImGui::Begin(w.Title);
ImGui::SetWindowPos({w.Position.x, w.Position.y});
ImGui::SetWindowSize({w.Size.x, w.Size.y});
w.ContentDrawCallback();
ImGui::End();
}
const auto drawList = ImGui::GetForegroundDrawList();
for (const auto &t : g_lineShapes)
{
if (!t.Visibility)
continue;
drawList->AddLine(t.From, t.To, t.Color, t.Thickness);
}
for (const auto &t : g_rectShapes)
{
if (!t.Visibility)
continue;
drawList->AddRectFilled(t.TopLeft, t.BottomRight, t.Color);
}
}
Handle DebugDraw::AddLine(IN CONST glm::vec2 &from, IN CONST glm::vec2 &to, IN CONST glm::vec4 &color,
IN FLOAT32 thickness)
{
g_lineShapes.pushBack(ShapeLine{.To = ImVec2{to.x, to.y},
.From = ImVec2{from.x, from.y},
.Color = IM_COL32(color.x * 255, color.y * 255, color.z * 255, color.w * 255),
.Thickness = thickness});
return g_lineShapes.size() - 1;
}
Handle DebugDraw::AddRect(IN CONST glm::vec2 &position, IN CONST glm::vec2 &size, IN CONST glm::vec4 &color)
{
g_rectShapes.pushBack({
.TopLeft =
ImVec2{
position.x,
position.y,
},
.BottomRight =
ImVec2{
position.x + size.x,
position.y + size.y,
},
.Color = IM_COL32(color.x * 255, color.y * 255, color.z * 255, color.w * 255),
});
return g_rectShapes.size() - 1;
}
Handle DebugDraw::AddUIWindow(IN PCCHAR title, IN CONST glm::vec2 &position, IN CONST glm::vec2 &size,
IN std::function<VOID()> contentDrawCallback)
{
g_debugUIWindows.pushBack(UIWindow{title, position, size, contentDrawCallback});
return g_debugUIWindows.size() - 1;
}
VOID DebugDraw::SetLineVisibility(IN Handle handle, IN BOOL visible)
{
g_lineShapes[handle].Visibility = visible;
}
VOID DebugDraw::SetRectVisibility(IN Handle handle, IN BOOL visible)
{
g_rectShapes[handle].Visibility = visible;
}
VOID DebugDraw::SetUIWindowVisibility(IN Handle handle, IN BOOL visible)
{
g_debugUIWindows[handle].Visibility = visible;
}
VOID DebugDraw::ToggleLineVisibility(IN Handle handle)
{
g_lineShapes[handle].Visibility = !g_lineShapes[handle].Visibility;
}
VOID DebugDraw::ToggleRectVisibility(IN Handle handle)
{
g_rectShapes[handle].Visibility = !g_rectShapes[handle].Visibility;
}
VOID DebugDraw::ToggleUIWindowVisibility(IN Handle handle)
{
g_debugUIWindows[handle].Visibility = !g_debugUIWindows[handle].Visibility;
}
} // namespace ia::iae

View File

@ -0,0 +1,81 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <IAEngine/Rendering/Pipeline/PostProcess.hpp>
#include <SDL3/SDL_gpu.h>
#include <EmbeddedShaders.hpp>
namespace ia::iae
{
EXTERN SDL_GPUDevice *g_gpuDevice;
EXTERN SDL_Window *g_windowHandle;
Pipeline_PostProcess::~Pipeline_PostProcess()
{
if (m_handle)
SDL_ReleaseGPUGraphicsPipeline(g_gpuDevice, (SDL_GPUGraphicsPipeline *) m_handle);
}
RefPtr<Pipeline_PostProcess> Pipeline_PostProcess::Create()
{
const auto res = MakeRefPtr<Pipeline_PostProcess>();
const auto vertexShader = LoadShaderFromMemory(ShaderStage::VERTEX, SHADER_SOURCE_POSTPROCESS_VERT,
sizeof(SHADER_SOURCE_POSTPROCESS_VERT), 0, 0, 0, 0);
const auto pixelShader = LoadShaderFromMemory(ShaderStage::PIXEL, SHADER_SOURCE_POSTPROCESS_FRAG,
sizeof(SHADER_SOURCE_POSTPROCESS_FRAG), 2, 0, 0, 0);
SDL_GPUColorTargetDescription colorTargets[] = {{
.format = SDL_GetGPUSwapchainTextureFormat(g_gpuDevice, g_windowHandle),
}};
SDL_GPUGraphicsPipelineCreateInfo createInfo = {
.vertex_shader = (SDL_GPUShader *) vertexShader,
.fragment_shader = (SDL_GPUShader *) pixelShader,
.vertex_input_state = SDL_GPUVertexInputState{.vertex_buffer_descriptions = nullptr,
.num_vertex_buffers = 0,
.vertex_attributes = nullptr,
.num_vertex_attributes = 0},
.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST,
.rasterizer_state = SDL_GPURasterizerState{.fill_mode = SDL_GPU_FILLMODE_FILL,
.cull_mode = SDL_GPU_CULLMODE_NONE,
.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE},
.target_info = {.color_target_descriptions = colorTargets,
.num_color_targets = sizeof(colorTargets) / sizeof(colorTargets[0]),
.has_depth_stencil_target = false},
};
SDL_GPUGraphicsPipeline *handle{};
if (!(handle = SDL_CreateGPUGraphicsPipeline(g_gpuDevice, &createInfo)))
{
IAE_LOG_ERROR("Failed to create a SDL graphics pipeline: ", SDL_GetError());
return nullptr;
}
UnloadShader(pixelShader);
UnloadShader(vertexShader);
res->m_handle = (Handle) handle;
return res;
}
VOID Pipeline_PostProcess::Bind(IN Handle renderPassHandle)
{
SDL_BindGPUGraphicsPipeline((SDL_GPURenderPass *) renderPassHandle, (SDL_GPUGraphicsPipeline *) m_handle);
}
} // namespace ia::iae

View File

@ -16,8 +16,10 @@
#include <IAEngine/IAEngine.hpp> #include <IAEngine/IAEngine.hpp>
#include <IAEngine/Rendering/Camera.hpp> #include <IAEngine/Rendering/Camera.hpp>
#include <IAEngine/Rendering/DebugDraw.hpp>
#include <IAEngine/Rendering/GPUBuffer.hpp> #include <IAEngine/Rendering/GPUBuffer.hpp>
#include <IAEngine/Rendering/GPUTexture.hpp> #include <IAEngine/Rendering/GPUTexture.hpp>
#include <IAEngine/Rendering/Pipeline/PostProcess.hpp>
#include <IAEngine/Rendering/Pipeline/UnlitMesh.hpp> #include <IAEngine/Rendering/Pipeline/UnlitMesh.hpp>
#include <IAEngine/Rendering/Renderer.hpp> #include <IAEngine/Rendering/Renderer.hpp>
@ -45,7 +47,7 @@ namespace ia::iae
SDL_Rect Scissor{0, 0, 0, 0}; SDL_Rect Scissor{0, 0, 0, 0};
}; };
Vector<Mesh*> g_meshes{}; Vector<Mesh *> g_meshes{};
RenderState g_renderState{}; RenderState g_renderState{};
} // namespace ia::iae } // namespace ia::iae
@ -55,21 +57,21 @@ namespace ia::iae
INT32 Renderer::s_width{}; INT32 Renderer::s_width{};
INT32 Renderer::s_height{}; INT32 Renderer::s_height{};
Vector<Renderer::DebugUIWindow> Renderer::s_debugUIWindows;
SDL_GPUDevice *g_gpuDevice{}; SDL_GPUDevice *g_gpuDevice{};
ImDrawData *g_imDrawData{};
// Render State // Render State
SDL_GPUCommandBuffer *g_cmdBuffer{}; SDL_GPUCommandBuffer *g_cmdBuffer{};
SDL_GPURenderPass *g_renderPass{}; SDL_GPURenderPass *g_renderPass{};
SDL_GPUTexture *g_swpChainTexture{}; SDL_GPUTexture *g_swpChainTexture{};
SDL_GPUTexture *g_depthBufferTexture{}; SDL_GPUTexture *g_depthBufferTexture{};
SDL_GPUTexture *g_sceneDrawBufferTexture{};
// ImGUI State SDL_GPUTexture *g_debugDrawBufferTexture{};
ImGuiIO g_imGUIIO{};
ImDrawData *g_imDrawData{};
RefPtr<Pipeline_UnlitMesh> g_pipelineUnlitMesh; RefPtr<Pipeline_UnlitMesh> g_pipelineUnlitMesh;
RefPtr<Pipeline_PostProcess> g_pipelinePostProcess;
Camera2D g_camera{}; Camera2D g_camera{};
@ -86,6 +88,9 @@ namespace ia::iae
Texture g_whiteFillTexture{}; Texture g_whiteFillTexture{};
Texture g_whiteStrokeTexture{}; Texture g_whiteStrokeTexture{};
SDL_GPUColorTargetInfo colorTargetInfo = {0};
SDL_GPUDepthStencilTargetInfo depthStencilTargetInfo = {0};
BOOL Renderer::Initialize() BOOL Renderer::Initialize()
{ {
SDL_GetWindowSizeInPixels(g_windowHandle, &s_width, &s_height); SDL_GetWindowSizeInPixels(g_windowHandle, &s_width, &s_height);
@ -104,30 +109,24 @@ namespace ia::iae
SDL_SetGPUSwapchainParameters(g_gpuDevice, g_windowHandle, SDL_GPU_SWAPCHAINCOMPOSITION_SDR, SDL_SetGPUSwapchainParameters(g_gpuDevice, g_windowHandle, SDL_GPU_SWAPCHAINCOMPOSITION_SDR,
SDL_GPU_PRESENTMODE_VSYNC); SDL_GPU_PRESENTMODE_VSYNC);
const auto mainScale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay()); DebugDraw::Initailize();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
g_imGUIIO = ImGui::GetIO();
g_imGUIIO.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
g_imGUIIO.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
ImGui::StyleColorsClassic();
ImGuiStyle &style = ImGui::GetStyle();
style.ScaleAllSizes(mainScale);
style.FontScaleDpi = mainScale;
ImGui_ImplSDLGPU3_InitInfo initInfo{.Device = g_gpuDevice,
.ColorTargetFormat =
SDL_GetGPUSwapchainTextureFormat(g_gpuDevice, g_windowHandle),
.PresentMode = SDL_GPU_PRESENTMODE_VSYNC};
ImGui_ImplSDL3_InitForSDLGPU(g_windowHandle);
ImGui_ImplSDLGPU3_Init(&initInfo);
if (!GPUBuffer::InitializeStagingBuffer()) if (!GPUBuffer::InitializeStagingBuffer())
return false; return false;
{
SDL_GPUTextureCreateInfo createInfo{.type = SDL_GPU_TEXTURETYPE_2D,
.format = SDL_GetGPUSwapchainTextureFormat(g_gpuDevice, g_windowHandle),
.usage =
SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER,
.width = (UINT32) s_width,
.height = (UINT32) s_height,
.layer_count_or_depth = 1,
.num_levels = 1,
.sample_count = SDL_GPU_SAMPLECOUNT_1};
g_sceneDrawBufferTexture = SDL_CreateGPUTexture(g_gpuDevice, &createInfo);
g_debugDrawBufferTexture = SDL_CreateGPUTexture(g_gpuDevice, &createInfo);
}
{ {
SDL_GPUTextureCreateInfo createInfo{.type = SDL_GPU_TEXTURETYPE_2D, SDL_GPUTextureCreateInfo createInfo{.type = SDL_GPU_TEXTURETYPE_2D,
.format = SDL_GPU_TEXTUREFORMAT_D16_UNORM, .format = SDL_GPU_TEXTUREFORMAT_D16_UNORM,
@ -143,6 +142,7 @@ namespace ia::iae
GPUTexture::Initialize(); GPUTexture::Initialize();
g_pipelineUnlitMesh = Pipeline_UnlitMesh::Create(); g_pipelineUnlitMesh = Pipeline_UnlitMesh::Create();
g_pipelinePostProcess = Pipeline_PostProcess::Create();
matProjection = glm::orthoLH(0.0f, (FLOAT32) s_width, (FLOAT32) s_height, 0.0f, -2097152.0f, 2097152.0f); matProjection = glm::orthoLH(0.0f, (FLOAT32) s_width, (FLOAT32) s_height, 0.0f, -2097152.0f, 2097152.0f);
@ -182,6 +182,18 @@ namespace ia::iae
}, },
{0, 1, 2, 2, 3, 0}); {0, 1, 2, 2, 3, 0});
colorTargetInfo.clear_color = SDL_FColor{0.33f, 0.33f, 0.33f, 1.0f};
colorTargetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
colorTargetInfo.store_op = SDL_GPU_STOREOP_STORE;
depthStencilTargetInfo.cycle = true;
depthStencilTargetInfo.clear_depth = 0;
depthStencilTargetInfo.clear_stencil = 0;
depthStencilTargetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
depthStencilTargetInfo.store_op = SDL_GPU_STOREOP_STORE;
depthStencilTargetInfo.stencil_load_op = SDL_GPU_LOADOP_CLEAR;
depthStencilTargetInfo.stencil_store_op = SDL_GPU_STOREOP_STORE;
return true; return true;
} }
@ -197,77 +209,32 @@ namespace ia::iae
} }
g_pipelineUnlitMesh.reset(); g_pipelineUnlitMesh.reset();
g_pipelinePostProcess.reset();
GPUTexture::Terminate(); GPUTexture::Terminate();
GPUBuffer::TerminateStagingBuffer(); GPUBuffer::TerminateStagingBuffer();
SDL_ReleaseGPUTexture(g_gpuDevice, g_depthBufferTexture); SDL_ReleaseGPUTexture(g_gpuDevice, g_depthBufferTexture);
SDL_ReleaseGPUTexture(g_gpuDevice, g_sceneDrawBufferTexture);
SDL_ReleaseGPUTexture(g_gpuDevice, g_debugDrawBufferTexture);
ImGui_ImplSDL3_Shutdown(); DebugDraw::Terminate();
ImGui_ImplSDLGPU3_Shutdown();
ImGui::DestroyContext();
SDL_ReleaseWindowFromGPUDevice(g_gpuDevice, g_windowHandle); SDL_ReleaseWindowFromGPUDevice(g_gpuDevice, g_windowHandle);
SDL_DestroyGPUDevice(g_gpuDevice); SDL_DestroyGPUDevice(g_gpuDevice);
} }
VOID Renderer::AddDebugUIWindow(IN PCCHAR title, IN CONST glm::vec2 &position, IN CONST glm::vec2 &size,
IN std::function<VOID()> contentDrawCallback)
{
s_debugUIWindows.pushBack(DebugUIWindow{title, position, size, contentDrawCallback});
}
VOID Renderer::BeginFrame() VOID Renderer::BeginFrame()
{ {
ImGui_ImplSDLGPU3_NewFrame();
ImGui_ImplSDL3_NewFrame();
ImGui::NewFrame();
for (const auto &w : s_debugUIWindows)
{
ImGui::Begin(w.Title);
ImGui::SetWindowPos({w.Position.x, w.Position.y});
ImGui::SetWindowSize({w.Size.x, w.Size.y});
w.ContentDrawCallback();
ImGui::End();
}
ImGui::Render();
if (!(g_cmdBuffer = SDL_AcquireGPUCommandBuffer(g_gpuDevice))) if (!(g_cmdBuffer = SDL_AcquireGPUCommandBuffer(g_gpuDevice)))
{ {
IAE_LOG_ERROR("Couldn't acquire SDL3 GPU command buffer: ", SDL_GetError()); IAE_LOG_ERROR("Couldn't acquire SDL3 GPU command buffer: ", SDL_GetError());
return; return;
} }
if (!SDL_WaitAndAcquireGPUSwapchainTexture(g_cmdBuffer, g_windowHandle, &g_swpChainTexture, (PUINT32) &s_width, colorTargetInfo.texture = g_sceneDrawBufferTexture;
(PUINT32) &s_height))
{
IAE_LOG_ERROR("Couldn't acquire SDL3 GPU Swapchain texture: ", SDL_GetError());
return;
}
if (!g_swpChainTexture)
return;
g_imDrawData = ImGui::GetDrawData();
ImGui_ImplSDLGPU3_PrepareDrawData(g_imDrawData, g_cmdBuffer);
SDL_GPUColorTargetInfo colorTargetInfo = {0};
colorTargetInfo.texture = g_swpChainTexture;
colorTargetInfo.clear_color = SDL_FColor{0.33f, 0.33f, 0.33f, 1.0f};
colorTargetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
colorTargetInfo.store_op = SDL_GPU_STOREOP_STORE;
SDL_GPUDepthStencilTargetInfo depthStencilTargetInfo = {0};
depthStencilTargetInfo.texture = g_depthBufferTexture; depthStencilTargetInfo.texture = g_depthBufferTexture;
depthStencilTargetInfo.cycle = true;
depthStencilTargetInfo.clear_depth = 0;
depthStencilTargetInfo.clear_stencil = 0;
depthStencilTargetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
depthStencilTargetInfo.store_op = SDL_GPU_STOREOP_STORE;
depthStencilTargetInfo.stencil_load_op = SDL_GPU_LOADOP_CLEAR;
depthStencilTargetInfo.stencil_store_op = SDL_GPU_STOREOP_STORE;
g_renderPass = SDL_BeginGPURenderPass(g_cmdBuffer, &colorTargetInfo, 1, &depthStencilTargetInfo); g_renderPass = SDL_BeginGPURenderPass(g_cmdBuffer, &colorTargetInfo, 1, &depthStencilTargetInfo);
@ -279,11 +246,48 @@ namespace ia::iae
VOID Renderer::EndFrame() VOID Renderer::EndFrame()
{ {
SDL_EndGPURenderPass(g_renderPass);
ImGui_ImplSDLGPU3_NewFrame();
ImGui_ImplSDL3_NewFrame();
ImGui::NewFrame();
DebugDraw::Draw();
ImGui::Render();
g_imDrawData = ImGui::GetDrawData();
ImGui_ImplSDLGPU3_PrepareDrawData(g_imDrawData, g_cmdBuffer);
colorTargetInfo.texture = g_debugDrawBufferTexture;
g_renderPass = SDL_BeginGPURenderPass(g_cmdBuffer, &colorTargetInfo, 1, nullptr);
ImGui_ImplSDLGPU3_RenderDrawData(g_imDrawData, g_cmdBuffer, g_renderPass);
SDL_EndGPURenderPass(g_renderPass);
if (!SDL_WaitAndAcquireGPUSwapchainTexture(g_cmdBuffer, g_windowHandle, &g_swpChainTexture, (PUINT32) &s_width,
(PUINT32) &s_height))
{
IAE_LOG_ERROR("Couldn't acquire SDL3 GPU Swapchain texture: ", SDL_GetError());
return;
}
if (!g_swpChainTexture) if (!g_swpChainTexture)
return; return;
ImGui_ImplSDLGPU3_RenderDrawData(g_imDrawData, g_cmdBuffer, g_renderPass); colorTargetInfo.texture = g_swpChainTexture;
g_renderPass = SDL_BeginGPURenderPass(g_cmdBuffer, &colorTargetInfo, 1, nullptr);
g_pipelinePostProcess->Bind((Handle) g_renderPass);
SDL_GPUTextureSamplerBinding textureBindings[2] = {
{
.texture = g_sceneDrawBufferTexture,
.sampler = (SDL_GPUSampler*)GPUTexture::GetDefaultSampler()
},
{
.texture = g_debugDrawBufferTexture,
.sampler = (SDL_GPUSampler*)GPUTexture::GetDefaultSampler()
},
};
SDL_BindGPUFragmentSamplers(g_renderPass, 0, textureBindings, 2);
SDL_DrawGPUPrimitives(g_renderPass, 6, 1, 0, 0);
SDL_EndGPURenderPass(g_renderPass); SDL_EndGPURenderPass(g_renderPass);
SDL_SubmitGPUCommandBuffer(g_cmdBuffer); SDL_SubmitGPUCommandBuffer(g_cmdBuffer);
} }
@ -336,7 +340,7 @@ namespace ia::iae
Handle Renderer::CreateMesh(IN CONST Vector<MeshVertex> &vertices, IN CONST Vector<INT32> &indices) Handle Renderer::CreateMesh(IN CONST Vector<MeshVertex> &vertices, IN CONST Vector<INT32> &indices)
{ {
const auto mesh = CreateUnmanagedMesh(vertices, indices); const auto mesh = CreateUnmanagedMesh(vertices, indices);
g_meshes.pushBack((Mesh*)mesh); g_meshes.pushBack((Mesh *) mesh);
return mesh; return mesh;
} }
@ -344,16 +348,16 @@ namespace ia::iae
{ {
const auto mesh = new Mesh(); const auto mesh = new Mesh();
mesh->VertexBuffer = GPUBuffer::Create(GPUBuffer::Usage::VERTEX, vertices.data(), mesh->VertexBuffer = GPUBuffer::Create(GPUBuffer::Usage::VERTEX, vertices.data(),
static_cast<UINT32>(vertices.size() * sizeof(vertices[0]))); static_cast<UINT32>(vertices.size() * sizeof(vertices[0])));
mesh->IndexBuffer = GPUBuffer::Create(GPUBuffer::Usage::INDEX, indices.data(), mesh->IndexBuffer = GPUBuffer::Create(GPUBuffer::Usage::INDEX, indices.data(),
static_cast<UINT32>(indices.size() * sizeof(indices[0]))); static_cast<UINT32>(indices.size() * sizeof(indices[0])));
mesh->IndexCount = static_cast<UINT32>(indices.size()); mesh->IndexCount = static_cast<UINT32>(indices.size());
return (Handle)mesh; return (Handle) mesh;
} }
VOID Renderer::DestroyUnmanagedMesh(IN Handle handle) VOID Renderer::DestroyUnmanagedMesh(IN Handle handle)
{ {
delete ((Mesh*)handle); delete ((Mesh *) handle);
} }
VOID Renderer::Draw(IN Handle meshHandle, IN Handle textureHandle, IN CONST glm::vec2 &position, VOID Renderer::Draw(IN Handle meshHandle, IN Handle textureHandle, IN CONST glm::vec2 &position,
@ -402,7 +406,7 @@ namespace ia::iae
else else
SDL_SetGPUScissor(g_renderPass, &g_defaultScissor); SDL_SetGPUScissor(g_renderPass, &g_defaultScissor);
const auto mesh = (Mesh*)meshHandle; const auto mesh = (Mesh *) meshHandle;
SDL_GPUBufferBinding bufferBindings[] = { SDL_GPUBufferBinding bufferBindings[] = {
{.buffer = (SDL_GPUBuffer *) mesh->VertexBuffer->GetHandle(), .offset = 0}, {.buffer = (SDL_GPUBuffer *) mesh->VertexBuffer->GetHandle(), .offset = 0},
{.buffer = (SDL_GPUBuffer *) mesh->IndexBuffer->GetHandle(), .offset = 0}}; {.buffer = (SDL_GPUBuffer *) mesh->IndexBuffer->GetHandle(), .offset = 0}};

View File

@ -27,7 +27,6 @@ namespace ia::iae
VOID Scene::OnActivate() VOID Scene::OnActivate()
{ {
Physics::Bake();
} }
VOID Scene::OnDeactivate() VOID Scene::OnDeactivate()

View File

@ -0,0 +1,23 @@
#version 450
#extension GL_ARB_separate_shader_objects : enable
layout(location = 0) in vec2 inTexCoord;
layout(set = 2, binding = 0) uniform sampler2D sceneDrawTexture;
layout(set = 2, binding = 1) uniform sampler2D debugDrawTexture;
layout(location = 0) out vec4 outColor;
vec4 overlay(vec4 background, vec4 foreground) {
return mix(
2.0 * background * foreground,
1.0 - 2.0 * (1.0 - background) * (1.0 - foreground),
step(0.5, background)
);
}
void main()
{
vec2 uv = vec2(inTexCoord.x, 1.0 - inTexCoord.y);
outColor = overlay(texture(debugDrawTexture, uv), texture(sceneDrawTexture, uv));
}

View File

@ -0,0 +1,10 @@
#version 450
#extension GL_ARB_separate_shader_objects : enable
layout(location = 0) out vec2 outTexCoord;
void main()
{
outTexCoord = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2);
gl_Position = vec4(outTexCoord * 2.0f - 1.0f, 0.0f, 1.0f);
}

File diff suppressed because one or more lines are too long

View File

@ -1,85 +0,0 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <IAEngine/Components/Component.hpp>
namespace ia::iae
{
class Physics;
class PhysicsBody2DComponent;
class BoxCollider2DComponent : public IComponent
{
public:
BoxCollider2DComponent(IN Node *node);
VOID OnCollisionEnter(IN Node *other);
VOID OnCollisionExit(IN Node *other);
public:
VOID SetCollisionEnterCallback(IN std::function<VOID(IN Node *)> callback)
{
m_collisionEnterCallback = callback;
}
VOID SetCollisionExitCallback(IN std::function<VOID(IN Node *)> callback)
{
m_collisionExitCallback = callback;
}
public:
BOOL &IsDebugDrawEnabled()
{
return m_isDebugDrawEnabled;
}
BOOL &CollisionsEnabled()
{
return m_collisionsEnabled;
}
BOOL &IsTrigger()
{
return m_isTrigger;
}
glm::vec4 &Rect()
{
return m_rect;
}
Handle PhysicsHandle() CONST
{
return m_physicsHandle;
}
public:
VOID Draw();
VOID Update();
private:
glm::vec4 m_rect{};
BOOL m_isTrigger{false};
BOOL m_isDebugDrawEnabled{false};
BOOL m_collisionsEnabled{true};
Handle m_physicsHandle{INVALID_HANDLE};
PhysicsBody2DComponent *m_body{};
std::function<VOID(IN Node *)> m_collisionEnterCallback{};
std::function<VOID(IN Node *)> m_collisionExitCallback{};
};
} // namespace ia::iae

View File

@ -20,37 +20,42 @@
namespace ia::iae namespace ia::iae
{ {
class PhysicsBody2DComponent : public IComponent class PhysicsComponent : public IComponent
{ {
public: public:
PhysicsBody2DComponent(IN Node *node); struct Collider
{
VOID SetVelocity(IN glm::vec2 v); BOOL IsTrigger{false};
VOID SetVelocityX(IN FLOAT32 v); glm::vec2 Position{};
VOID SetVelocityY(IN FLOAT32 v); glm::vec2 Size{};
VOID ApplyForce(IN glm::vec2 force); };
VOID Jump(IN FLOAT32 velocity);
public: public:
BOOL &IsGrounded() PhysicsComponent(IN Node *node);
{ ~PhysicsComponent();
return m_isGrounded;
}
Handle CreateCollider();
Handle AddCollider(IN Collider collider);
Collider &GetCollider(IN Handle handle);
VOID Move(IN glm::vec2 direction);
VOID Jump(IN FLOAT32 force);
public:
BOOL &IsDynamic() BOOL &IsDynamic()
{ {
return m_isDynamic; return m_isDynamic;
} }
BOOL &IsRotationLocked() FLOAT32 &MovementSpeed()
{ {
return m_isRotationLocked; return m_movementSpeed;
} }
Handle PhysicsHandle() CONST Vector<Collider> &Colliders()
{ {
return m_physicsHandle; return m_colliders;
} }
public: public:
@ -58,9 +63,13 @@ namespace ia::iae
VOID Update(); VOID Update();
private: private:
BOOL m_isDynamic{}; BOOL m_isDynamic{false};
BOOL m_isGrounded{}; FLOAT32 m_movementSpeed{2.0f};
BOOL m_isRotationLocked{true}; Vector<Collider> m_colliders;
Handle m_physicsHandle{INVALID_HANDLE}; Handle m_physicsHandle{INVALID_HANDLE};
VOID OnCollision(IN PhysicsComponent *other);
friend class Physics;
}; };
} // namespace ia::iae } // namespace ia::iae

View File

@ -23,6 +23,30 @@ namespace ia::iae
template<typename _node_type> class Transform template<typename _node_type> class Transform
{ {
public: public:
VOID Translate(IN glm::vec2 v)
{
m_local.Position += v;
RecalculatePosition();
}
VOID Scale(IN FLOAT32 v)
{
m_local.Scale *= v;
RecalculateScale();
}
VOID Scale(IN glm::vec2 v)
{
m_local.Scale *= v;
RecalculateScale();
}
VOID Rotate(IN FLOAT32 v)
{
m_local.Rotation += v;
RecalculateRotation();
}
VOID SetLocalSortIndex(IN INT16 index) VOID SetLocalSortIndex(IN INT16 index)
{ {
m_local.SortIndex = index; m_local.SortIndex = index;

View File

@ -16,29 +16,24 @@
#pragma once #pragma once
#include <IAEngine/Components/BoxCollider2D.hpp> #include <IAEngine/Physics/Physics.hpp>
#include <IAEngine/Components/PhysicsBody2D.hpp> #include <IAEngine/Components/Physics.hpp>
namespace ia::iae namespace ia::iae
{ {
class Physics class Physics
{ {
public: public:
STATIC Handle RegisterComponent(IN PhysicsComponent* component);
STATIC BOOL CanMove(IN Handle handle, IN CONST PhysicsComponent::Collider& collider, IN glm::vec2 movement);
private:
STATIC VOID Initialize(); STATIC VOID Initialize();
STATIC VOID Terminate(); STATIC VOID Terminate();
STATIC VOID Bake();
STATIC VOID Update(); STATIC VOID Update();
STATIC Handle AddBody(IN PhysicsBody2DComponent* body); friend class Engine;
STATIC Handle AddColliderToBody(IN Handle bodyHandle, IN BoxCollider2DComponent* collider);
STATIC FLOAT32 GetBodyRotation(IN Handle handle);
STATIC glm::vec2 GetBodyPosition(IN Handle handle);
STATIC VOID SetBodyVelocity(IN Handle handle, IN glm::vec2 v);
STATIC VOID SetBodyVelocityX(IN Handle handle, IN FLOAT32 v);
STATIC VOID SetBodyVelocityY(IN Handle handle, IN FLOAT32 v);
STATIC VOID ApplyBodyForce(IN Handle handle, IN glm::vec2 force);
}; };
} }

View File

@ -0,0 +1,47 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <IAEngine/Rendering/Types.hpp>
namespace ia::iae
{
class DebugDraw
{
public:
STATIC Handle AddLine(IN CONST glm::vec2& from, IN CONST glm::vec2& to, IN CONST glm::vec4& color, IN FLOAT32 thickness = 1.0f);
STATIC Handle AddRect(IN CONST glm::vec2& position, IN CONST glm::vec2& size, IN CONST glm::vec4& color);
STATIC Handle AddUIWindow(IN PCCHAR title, IN CONST glm::vec2 &position, IN CONST glm::vec2 &size,
IN std::function<VOID()> contentDrawCallback);
STATIC VOID SetLineVisibility(IN Handle handle, IN BOOL visible);
STATIC VOID SetRectVisibility(IN Handle handle, IN BOOL visible);
STATIC VOID SetUIWindowVisibility(IN Handle handle, IN BOOL visible);
STATIC VOID ToggleLineVisibility(IN Handle handle);
STATIC VOID ToggleRectVisibility(IN Handle handle);
STATIC VOID ToggleUIWindowVisibility(IN Handle handle);
private:
STATIC VOID Initailize();
STATIC VOID Terminate();
STATIC VOID Draw();
friend class Renderer;
};
} // namespace ia::iae

View File

@ -0,0 +1,35 @@
// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IAS (ias@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#pragma once
#include <IAEngine/Rendering/Pipeline/Pipeline.hpp>
namespace ia::iae
{
class Pipeline_PostProcess: public IPipeline
{
public:
~Pipeline_PostProcess();
STATIC RefPtr<Pipeline_PostProcess> Create();
VOID Bind(IN Handle renderPassHandle);
private:
Handle m_handle{INVALID_HANDLE};
};
}

View File

@ -24,14 +24,6 @@ namespace ia::iae
class Renderer class Renderer
{ {
struct DebugUIWindow
{
PCCHAR Title{""};
glm::vec2 Position{};
glm::vec2 Size{};
std::function<VOID()> ContentDrawCallback{};
};
public: public:
STATIC CONSTEXPR UINT8 MAX_LAYER_INDEX = 255; STATIC CONSTEXPR UINT8 MAX_LAYER_INDEX = 255;
@ -39,10 +31,6 @@ namespace ia::iae
STATIC BOOL Initialize(); STATIC BOOL Initialize();
STATIC VOID Terminate(); STATIC VOID Terminate();
public:
STATIC VOID AddDebugUIWindow(IN PCCHAR title, IN CONST glm::vec2 &position, IN CONST glm::vec2 &size,
IN std::function<VOID()> contentDrawCallback);
public: public:
STATIC VOID BeginFrame(); STATIC VOID BeginFrame();
STATIC VOID EndFrame(); STATIC VOID EndFrame();
@ -82,6 +70,5 @@ namespace ia::iae
private: private:
STATIC INT32 s_width; STATIC INT32 s_width;
STATIC INT32 s_height; STATIC INT32 s_height;
STATIC Vector<DebugUIWindow> s_debugUIWindows;
}; };
} // namespace ia::iae } // namespace ia::iae

View File

@ -34,7 +34,9 @@ SHADER_SOURCE_PATH = "Src/IAEngine/imp/glsl"
SHADER_SOURCE_FILES = [ SHADER_SOURCE_FILES = [
"UnlitMesh/UnlitMesh.vert", "UnlitMesh/UnlitMesh.vert",
"UnlitMesh/UnlitMesh.frag" "UnlitMesh/UnlitMesh.frag",
"PostProcessing/PostProcess.vert",
"PostProcessing/PostProcess.frag"
] ]
def file_to_source_array(arrayName, filePath): def file_to_source_array(arrayName, filePath):

View File

@ -54,7 +54,3 @@ add_library(Freetype::Freetype ALIAS freetype)
# ----------------------------------------------- # -----------------------------------------------
add_subdirectory(RmlUI/) add_subdirectory(RmlUI/)
# -----------------------------------------------
# Box2D
# -----------------------------------------------
add_subdirectory(box2d/)

1
Vendor/box2d vendored

Submodule Vendor/box2d deleted from f86d1827eb