Add system graph (wip)

This commit is contained in:
SirLynix 2022-07-02 19:45:50 +02:00
parent 4d24be2ae9
commit 1b678defae
18 changed files with 524 additions and 286 deletions

View File

@ -41,26 +41,65 @@ int main()
return __LINE__;
}
std::shared_ptr<Nz::Mesh> spaceshipMesh = Nz::Mesh::LoadFromFile(resourceDir / "Spaceship/spaceship.obj", meshParams);
if (!spaceshipMesh)
std::shared_ptr<Nz::Mesh> sphereMesh = std::make_shared<Nz::Mesh>();
sphereMesh->CreateStatic();
std::shared_ptr<Nz::SubMesh> sphereSubmesh = sphereMesh->BuildSubMesh(Nz::Primitive::UVSphere(1.f, 50, 50));
sphereMesh->SetMaterialCount(1);
sphereMesh->GenerateNormalsAndTangents();
std::shared_ptr<Nz::Mesh> debugMesh = std::make_shared<Nz::Mesh>();
debugMesh->CreateStatic();
{
NazaraError("Failed to load model");
return __LINE__;
Nz::VertexMapper sphereMapper(*sphereSubmesh);
std::size_t vertexCount = sphereMapper.GetVertexCount();
Nz::SparsePtr<Nz::Vector3f> positionPtr = sphereMapper.GetComponentPtr<Nz::Vector3f>(Nz::VertexComponent::Position);
Nz::SparsePtr<Nz::Vector3f> normalPtr = sphereMapper.GetComponentPtr<Nz::Vector3f>(Nz::VertexComponent::Normal);
Nz::SparsePtr<Nz::Vector3f> tangentPtr = sphereMapper.GetComponentPtr<Nz::Vector3f>(Nz::VertexComponent::Tangent);
std::shared_ptr<Nz::VertexDeclaration> debugDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_Color);
std::vector<Nz::VertexStruct_XYZ_Color> debugVertices(vertexCount * 6);
for (std::size_t i = 0; i < vertexCount; ++i)
{
debugVertices[i * 6 + 0].position = positionPtr[i];
debugVertices[i * 6 + 0].color = Nz::Color::Red;
debugVertices[i * 6 + 1].position = positionPtr[i] + normalPtr[i] * 0.05f;
debugVertices[i * 6 + 1].color = Nz::Color::Red;
debugVertices[i * 6 + 2].position = positionPtr[i];
debugVertices[i * 6 + 2].color = Nz::Color::Blue;
debugVertices[i * 6 + 3].position = positionPtr[i] + tangentPtr[i] * 0.05f;
debugVertices[i * 6 + 3].color = Nz::Color::Blue;
Nz::Vector3f bitangent = Nz::Vector3f::CrossProduct(normalPtr[i], tangentPtr[i]);
debugVertices[i * 6 + 4].position = positionPtr[i];
debugVertices[i * 6 + 4].color = Nz::Color::Cyan;
debugVertices[i * 6 + 5].position = positionPtr[i] + bitangent * 0.05f;
debugVertices[i * 6 + 5].color = Nz::Color::Cyan;
}
std::shared_ptr<Nz::VertexBuffer> normalBuffer = std::make_shared<Nz::VertexBuffer>(debugDeclaration, vertexCount * 6, Nz::BufferUsage::Write, Nz::SoftwareBufferFactory, debugVertices.data());
std::shared_ptr<Nz::StaticMesh> staticMesh = std::make_shared<Nz::StaticMesh>(normalBuffer, nullptr);
staticMesh->GenerateAABB();
staticMesh->SetPrimitiveMode(Nz::PrimitiveMode::LineList);
debugMesh->AddSubMesh(std::move(staticMesh));
}
debugMesh->SetMaterialCount(1);
std::shared_ptr<Nz::GraphicalMesh> gfxMesh = Nz::GraphicalMesh::BuildFromMesh(*spaceshipMesh);
// Texture
std::shared_ptr<Nz::Image> diffuseImage = Nz::Image::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png");
if (!diffuseImage || !diffuseImage->Convert(Nz::PixelFormat::RGBA8_SRGB))
{
NazaraError("Failed to load image");
return __LINE__;
}
std::shared_ptr<Nz::GraphicalMesh> gfxMesh = Nz::GraphicalMesh::BuildFromMesh(*sphereMesh);
std::shared_ptr<Nz::GraphicalMesh> gfxDebugMesh = Nz::GraphicalMesh::BuildFromMesh(*debugMesh);
// Textures
Nz::TextureParams texParams;
texParams.renderDevice = device;
texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB;
std::shared_ptr<Nz::Material> material = std::make_shared<Nz::Material>();
@ -70,18 +109,35 @@ int main()
material->AddPass("ForwardPass", forwardPass);
std::shared_ptr<Nz::Texture> normalMap = Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/normal.png", texParams);
std::shared_ptr<Nz::Texture> normalMap = Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_normal.png", texParams);
texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB;
std::shared_ptr<Nz::Material> debugMaterial = std::make_shared<Nz::Material>();
std::shared_ptr<Nz::MaterialPass> debugMaterialPass = std::make_shared<Nz::MaterialPass>(Nz::BasicMaterial::GetSettings());
debugMaterialPass->EnableDepthBuffer(true);
debugMaterialPass->SetPrimitiveMode(Nz::PrimitiveMode::LineList);
debugMaterial->AddPass("ForwardPass", debugMaterialPass);
Nz::BasicMaterial debugMat(*std::make_shared<Nz::MaterialPass>(Nz::BasicMaterial::GetSettings()));
Nz::PhongLightingMaterial phongMat(*forwardPass);
phongMat.EnableAlphaTest(false);
phongMat.SetAlphaMap(Nz::Texture::LoadFromFile(resourceDir / "alphatile.png", texParams));
phongMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams));
phongMat.SetNormalMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/normal.png", texParams));
phongMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_basecolor.png", texParams));
//pbrMat.SetMetallicMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_metallic.png", texParams));
//pbrMat.SetRoughnessMap(Nz::Texture::LoadFromFile(resourceDir / "Rusty/rustediron2_roughness.png", texParams));
phongMat.SetNormalMap(normalMap);
Nz::Model model(std::move(gfxMesh), spaceshipMesh->GetAABB());
Nz::Model model(std::move(gfxMesh), sphereMesh->GetAABB());
for (std::size_t i = 0; i < model.GetSubMeshCount(); ++i)
model.SetMaterial(i, material);
Nz::Model debugModel(std::move(gfxDebugMesh), debugMesh->GetAABB());
for (std::size_t i = 0; i < debugModel.GetSubMeshCount(); ++i)
debugModel.SetMaterial(i, debugMaterial);
Nz::Vector2ui windowSize = window.GetSize();
Nz::Camera camera(window.GetRenderTarget());
@ -104,11 +160,12 @@ int main()
std::size_t worldInstanceIndex1 = framePipeline.RegisterWorldInstance(modelInstance);
std::size_t worldInstanceIndex2 = framePipeline.RegisterWorldInstance(modelInstance2);
framePipeline.RegisterRenderable(worldInstanceIndex1, &model, 0xFFFFFFFF, scissorBox);
//framePipeline.RegisterRenderable(worldInstanceIndex1, &debugModel, 0xFFFFFFFF, scissorBox);
framePipeline.RegisterRenderable(worldInstanceIndex2, &model, 0xFFFFFFFF, scissorBox);
//framePipeline.RegisterRenderable(worldInstanceIndex2, &debugModel, 0xFFFFFFFF, scissorBox);
std::shared_ptr<Nz::SpotLight> light = std::make_shared<Nz::SpotLight>();
light->UpdateInnerAngle(Nz::DegreeAnglef(15.f));
light->UpdateOuterAngle(Nz::DegreeAnglef(20.f));
std::shared_ptr<Nz::DirectionalLight> light = std::make_shared<Nz::DirectionalLight>();
light->UpdateRotation(Nz::EulerAnglesf(-45.f, 0.f, 0.f));
framePipeline.RegisterLight(light, 0xFFFFFFFF);
@ -167,7 +224,7 @@ int main()
camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f);
camQuat = camAngles;
light->UpdateRotation(camQuat);
//light->UpdateRotation(camQuat);
break;
}
@ -212,7 +269,7 @@ int main()
if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl))
viewerPos += Nz::Vector3f::Down() * cameraSpeed;
light->UpdatePosition(viewerPos);
//light->UpdatePosition(viewerPos);
}
Nz::RenderFrame frame = window.AcquireFrame();

View File

@ -1,4 +1,5 @@
#include <Nazara/Core.hpp>
#include <Nazara/Core/Systems.hpp>
#include <Nazara/Platform.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
@ -40,23 +41,20 @@ int main()
Nz::Modules<Nz::Graphics, Nz::Physics2D> nazara(rendererConfig);
Nz::RenderWindow window;
std::shared_ptr<Nz::RenderDevice> device = Nz::Graphics::Instance()->GetRenderDevice();
std::string windowTitle = "Graphics Test";
if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle))
{
std::cout << "Failed to create Window" << std::endl;
return __LINE__;
}
entt::registry registry;
Nz::Physics2DSystem physSytem(registry);
physSytem.GetPhysWorld().SetGravity({ 0.f, -9.81f });
Nz::SystemGraph systemGraph(registry);
Nz::Physics2DSystem& physSytem = systemGraph.AddSystem<Nz::Physics2DSystem>();
Nz::RenderSystem& renderSystem = systemGraph.AddSystem<Nz::RenderSystem>();
Nz::RenderSystem renderSystem(registry);
std::string windowTitle = "Graphics Test";
Nz::RenderWindow& window = renderSystem.CreateWindow(device, Nz::VideoMode(1920, 1080), windowTitle);
Nz::Vector2ui windowSize = window.GetSize();
physSytem.GetPhysWorld().SetGravity({ 0.f, -9.81f });
entt::entity viewer = registry.create();
{
@ -166,19 +164,10 @@ int main()
{
float updateTime = updateClock.Restart() / 1'000'000.f;
physSytem.Update(registry, 1000.f / 60.f);
physSytem.Update(1000.f / 60.f);
}
Nz::RenderFrame frame = window.AcquireFrame();
if (!frame)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
renderSystem.Render(registry, frame);
frame.Present();
systemGraph.Update();
fps++;

View File

@ -1,4 +1,5 @@
#include <Nazara/Core.hpp>
#include <Nazara/Core/Systems.hpp>
#include <Nazara/Platform.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
@ -39,17 +40,8 @@ int main()
Nz::Modules<Nz::Graphics, Nz::Physics3D> nazara(rendererConfig);
Nz::RenderWindow window;
std::shared_ptr<Nz::RenderDevice> device = Nz::Graphics::Instance()->GetRenderDevice();
std::string windowTitle = "Graphics Test";
if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle))
{
std::cout << "Failed to create Window" << std::endl;
return __LINE__;
}
Nz::MeshParams meshParams;
meshParams.center = true;
meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 0.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f));
@ -119,15 +111,19 @@ int main()
std::shared_ptr<Nz::TextSprite> sprite = std::make_shared<Nz::TextSprite>(spriteMaterial);
sprite->Update(Nz::SimpleTextDrawer::Draw("Voix ambiguë d'un cœur qui, au zéphyr, préfère les jattes de kiwis", 72), 0.01f);
Nz::Vector2ui windowSize = window.GetSize();
Nz::VertexMapper vertexMapper(*spaceshipMesh->GetSubMesh(0));
Nz::SparsePtr<Nz::Vector3f> vertices = vertexMapper.GetComponentPtr<Nz::Vector3f>(Nz::VertexComponent::Position);
entt::registry registry;
Nz::Physics3DSystem physSytem(registry);
Nz::RenderSystem renderSystem(registry);
Nz::SystemGraph systemGraph(registry);
Nz::Physics3DSystem& physSytem = systemGraph.AddSystem<Nz::Physics3DSystem>();
Nz::RenderSystem& renderSystem = systemGraph.AddSystem<Nz::RenderSystem>();
std::string windowTitle = "Graphics Test";
Nz::RenderWindow& window = renderSystem.CreateWindow(device, Nz::VideoMode(1920, 1080, 32), windowTitle);
Nz::Vector2ui windowSize = window.GetSize();
entt::entity viewer = registry.create();
{
@ -187,10 +183,10 @@ int main()
auto& headingNode = registry.emplace<Nz::NodeComponent>(headingEntity);
headingNode.SetInheritRotation(false);
headingNode.SetParent(registry, playerEntity);
headingNode.SetParent(entityNode);
}
registry.get<Nz::NodeComponent>(viewer).SetParent(registry, headingEntity);
registry.get<Nz::NodeComponent>(viewer).SetParent(entt::handle(registry, headingEntity));
registry.get<Nz::NodeComponent>(viewer).SetPosition(Nz::Vector3f::Backward() * 2.5f + Nz::Vector3f::Up() * 1.f);
for (std::size_t x = 0; x < 3; ++x)
@ -310,10 +306,6 @@ int main()
if (updateClock.GetMilliseconds() > 1000 / 60)
{
float updateTime = updateClock.Restart() / 1'000'000.f;
physSytem.Update(registry, 1000.f / 60.f);
auto spaceshipView = registry.view<Nz::NodeComponent, Nz::RigidBody3DComponent>();
for (auto&& [entity, node, _] : spaceshipView.each())
{
@ -360,16 +352,7 @@ int main()
playerShipBody.AddForce(Nz::Vector3f::Down() * 3.f * mass, Nz::CoordSys::Local);
}
Nz::RenderFrame frame = window.AcquireFrame();
if (!frame)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
renderSystem.Render(registry, frame);
frame.Present();
systemGraph.Update();
fps++;

View File

@ -1,5 +1,6 @@
// Sources pour https://github.com/NazaraEngine/NazaraEngine/wiki/(FR)-Tutoriel:-%5B01%5D-Hello-World
#include <Nazara/Core/Systems.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Graphics/Components.hpp>
#include <Nazara/Graphics/Systems.hpp>
@ -15,10 +16,10 @@ int main()
{
Nz::Modules<Nz::Graphics> nazara;
Nz::RenderWindow mainWindow(Nz::Graphics::Instance()->GetRenderDevice(), Nz::VideoMode(1280, 720, 32), "Test");
entt::registry registry;
Nz::RenderSystem renderSystem(registry);
Nz::SystemGraph systemGraph(registry);
Nz::RenderSystem& renderSystem = systemGraph.AddSystem<Nz::RenderSystem>();
Nz::RenderWindow& mainWindow = renderSystem.CreateWindow(Nz::Graphics::Instance()->GetRenderDevice(), Nz::VideoMode(1280, 720), "Tut01 - Hello world");
entt::entity cameraEntity = registry.create();
{
@ -62,17 +63,7 @@ int main()
while (mainWindow.IsOpen())
{
mainWindow.ProcessEvents();
Nz::RenderFrame renderFrame = mainWindow.AcquireFrame();
if (!renderFrame)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
renderSystem.Render(registry, renderFrame);
renderFrame.Present();
systemGraph.Update();
}
return EXIT_SUCCESS;

View File

@ -1,5 +1,6 @@
// Sources pour https://github.com/NazaraEngine/NazaraEngine/wiki/(FR)-Tutoriel:-%5B02%5D-Gestion-des-événements
#include <Nazara/Core/Systems.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Graphics/Components.hpp>
#include <Nazara/Graphics/Systems.hpp>
@ -15,10 +16,10 @@ int main()
{
Nz::Modules<Nz::Graphics> nazara;
Nz::RenderWindow mainWindow(Nz::Graphics::Instance()->GetRenderDevice(), Nz::VideoMode(1280, 720, 32), "Test");
entt::registry registry;
Nz::RenderSystem renderSystem(registry);
Nz::SystemGraph systemGraph(registry);
Nz::RenderSystem& renderSystem = systemGraph.AddSystem<Nz::RenderSystem>();
Nz::RenderWindow& mainWindow = renderSystem.CreateWindow(Nz::Graphics::Instance()->GetRenderDevice(), Nz::VideoMode(1280, 720), "Tut02 - Events");
entt::entity cameraEntity = registry.create();
{
@ -79,17 +80,7 @@ int main()
while (mainWindow.IsOpen())
{
mainWindow.ProcessEvents();
Nz::RenderFrame renderFrame = mainWindow.AcquireFrame();
if (!renderFrame)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
renderSystem.Render(registry, renderFrame);
renderFrame.Present();
systemGraph.Update();
}
return EXIT_SUCCESS;

View File

@ -1,4 +1,5 @@
#include <Nazara/Core.hpp>
#include <Nazara/Core/Systems.hpp>
#include <Nazara/Platform.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
@ -43,14 +44,11 @@ int main()
std::shared_ptr<Nz::RenderDevice> device = Nz::Graphics::Instance()->GetRenderDevice();
std::string windowTitle = "Widget Test";
if (!window.Create(device, Nz::VideoMode(1920, 1080, 32), windowTitle))
{
std::cout << "Failed to create Window" << std::endl;
return __LINE__;
}
entt::registry registry;
Nz::RenderSystem renderSystem(registry);
Nz::SystemGraph systemGraph(registry);
Nz::RenderSystem& renderSystem = systemGraph.AddSystem<Nz::RenderSystem>();
Nz::RenderWindow& mainWindow = renderSystem.CreateWindow(device, Nz::VideoMode(1920, 1080), windowTitle);
Nz::Canvas canvas2D(registry, window.GetEventHandler(), window.GetCursorController().CreateHandle(), 0xFFFFFFFF);
canvas2D.Resize(Nz::Vector2f(window.GetSize()));
@ -148,13 +146,7 @@ int main()
}
}
Nz::RenderFrame frame = window.AcquireFrame();
if (!frame)
continue;
renderSystem.Render(registry, frame);
frame.Present();
systemGraph.Update();
fps++;

View File

@ -30,5 +30,6 @@
#define NAZARA_CORE_SYSTEMS_HPP
#include <Nazara/Core/Systems/LifetimeSystem.hpp>
#include <Nazara/Core/Systems/SystemGraph.hpp>
#endif // NAZARA_CORE_SYSTEMS_HPP

View File

@ -0,0 +1,70 @@
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_CORE_SYSTEMS_SYSTEMGRAPH_HPP
#define NAZARA_CORE_SYSTEMS_SYSTEMGRAPH_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Utils/MovablePtr.hpp>
#include <entt/entt.hpp>
#include <functional>
#include <unordered_map>
#include <vector>
namespace Nz
{
class NAZARA_CORE_API SystemGraph
{
public:
inline SystemGraph(entt::registry& registry);
SystemGraph(const SystemGraph&) = delete;
SystemGraph(SystemGraph&&) = delete;
~SystemGraph() = default;
template<typename T, typename... Args> T& AddSystem(Args&&... args);
template<typename T> T& GetSystem() const;
void Update();
void Update(float elapsedTime);
SystemGraph& operator=(const SystemGraph&) = delete;
SystemGraph& operator=(SystemGraph&&) = delete;
private:
struct NAZARA_CORE_API NodeBase
{
virtual ~NodeBase();
virtual void Update(float elapsedTime) = 0;
Int64 executionOrder;
};
template<typename T>
struct Node : NodeBase
{
template<typename... Args> Node(Args&&... args);
void Update(float elapsedTime) override;
T system;
};
std::unordered_map<entt::id_type, std::size_t /*nodeIndex*/> m_systemToNodes;
std::vector<NodeBase*> m_orderedNodes;
std::vector<std::unique_ptr<NodeBase>> m_nodes;
entt::registry& m_registry;
Nz::Clock m_clock;
bool m_systemOrderUpdated;
};
}
#include <Nazara/Core/Systems/SystemGraph.inl>
#endif // NAZARA_CORE_SYSTEMS_SYSTEMGRAPH_HPP

View File

@ -0,0 +1,74 @@
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Systems/SystemGraph.hpp>
#include <Nazara/Core/Error.hpp>
#include <stdexcept>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
namespace Detail
{
template<typename, typename = void>
struct SystemGraphAllowConcurrent : std::bool_constant<true> {};
template<typename T>
struct SystemGraphAllowConcurrent<T, std::void_t<decltype(T::AllowConcurrent)>> : std::bool_constant<T::AllowConcurrent> {};
template<typename, typename = void>
struct SystemGraphExecutionOrder : std::integral_constant<Int64, 0> {};
template<typename T>
struct SystemGraphExecutionOrder<T, std::void_t<decltype(T::ExecutionOrder)>> : std::integral_constant<Int64, T::ExecutionOrder> {};
}
template<typename T>
template<typename... Args>
SystemGraph::Node<T>::Node(Args&&... args) :
system(std::forward<Args>(args)...)
{
}
template<typename T>
void SystemGraph::Node<T>::Update(float elapsedTime)
{
system.Update(elapsedTime);
}
inline SystemGraph::SystemGraph(entt::registry& registry) :
m_registry(registry),
m_systemOrderUpdated(true)
{
}
template<typename T, typename... Args>
T& SystemGraph::AddSystem(Args&&... args)
{
NazaraAssert(m_systemToNodes.find(entt::type_hash<T>()) == m_systemToNodes.end(), "this system already exists");
auto nodePtr = std::make_unique<Node<T>>(m_registry, std::forward<Args>(args)...);
nodePtr->executionOrder = Detail::SystemGraphExecutionOrder<T>();
T& system = nodePtr->system;
m_nodes.emplace_back(std::move(nodePtr));
m_systemOrderUpdated = false;
return system;
}
template<typename T>
T& SystemGraph::GetSystem() const
{
auto it = m_systemToNodes.find(entt::type_hash<T>());
if (it == m_systemToNodes.end())
throw std::runtime_error("this system is not part of the graph");
auto& node = static_cast<Node<T>&>(*m_nodes[it->second]);
return node.system;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -8,11 +8,11 @@
#define NAZARA_GRAPHICS_GRAPHICALMESH_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Utils/Signal.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utils/Signal.hpp>
#include <memory>
namespace Nz

View File

@ -24,17 +24,23 @@ namespace Nz
class CommandBufferBuilder;
class FramePipeline;
class RenderFrame;
class RenderWindow;
class UploadPool;
class NAZARA_GRAPHICS_API RenderSystem
{
public:
static constexpr bool AllowConcurrent = false;
static constexpr Int64 ExecutionOrder = 1'000;
RenderSystem(entt::registry& registry);
RenderSystem(const RenderSystem&) = delete;
RenderSystem(RenderSystem&&) = delete;
~RenderSystem();
void Render(entt::registry& registry, RenderFrame& renderFrame);
template<typename T = RenderWindow, typename... Args> T& CreateWindow(Args&&... args);
void Update(float elapsedTime);
RenderSystem& operator=(const RenderSystem&) = delete;
RenderSystem& operator=(RenderSystem&&) = delete;
@ -44,8 +50,9 @@ namespace Nz
void OnGraphicsDestroy(entt::registry& registry, entt::entity entity);
void OnLightDestroy(entt::registry& registry, entt::entity entity);
void OnNodeDestroy(entt::registry& registry, entt::entity entity);
void UpdateInstances(entt::registry& registry);
void UpdateVisibility(entt::registry& registry);
void UpdateInstances();
void UpdateObservers();
void UpdateVisibility();
struct CameraEntity
{
@ -89,6 +96,7 @@ namespace Nz
entt::observer m_cameraConstructObserver;
entt::observer m_graphicsConstructObserver;
entt::observer m_lightConstructObserver;
entt::registry& m_registry;
std::set<CameraEntity*> m_invalidatedCameraNode;
std::set<GraphicsEntity*> m_invalidatedGfxWorldNode;
std::set<LightEntity*> m_invalidatedLightWorldNode;
@ -100,6 +108,7 @@ namespace Nz
std::unordered_set<GraphicsEntity*> m_newlyVisibleGfxEntities;
std::unordered_set<LightEntity*> m_newlyHiddenLightEntities;
std::unordered_set<LightEntity*> m_newlyVisibleLightEntities;
std::vector<std::unique_ptr<RenderWindow>> m_renderWindows;
MemoryPool<CameraEntity> m_cameraEntityPool;
MemoryPool<GraphicsEntity> m_graphicsEntityPool;
MemoryPool<LightEntity> m_lightEntityPool;

View File

@ -3,10 +3,23 @@
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/Systems/RenderSystem.hpp>
#include <type_traits>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
template<typename T, typename ...Args>
T& RenderSystem::CreateWindow(Args&& ...args)
{
static_assert(std::is_base_of_v<RenderWindow, T>, "T must inherit RenderWindow");
auto windowPtr = std::make_unique<T>(std::forward<Args>(args)...);
T& windowRef = *windowPtr;
m_renderWindows.emplace_back(std::move(windowPtr));
return windowRef;
}
}
#include <Nazara/Graphics/DebugOff.hpp>

View File

@ -10,6 +10,7 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Physics2D/PhysWorld2D.hpp>
#include <Nazara/Physics2D/Components/RigidBody2DComponent.hpp>
#include <Nazara/Utils/TypeList.hpp>
#include <entt/entt.hpp>
namespace Nz
@ -17,6 +18,9 @@ namespace Nz
class NAZARA_PHYSICS2D_API Physics2DSystem
{
public:
static constexpr Int64 ExecutionOrder = 0;
using Components = TypeList<RigidBody2DComponent, class NodeComponent>;
Physics2DSystem(entt::registry& registry);
Physics2DSystem(const Physics2DSystem&) = delete;
Physics2DSystem(Physics2DSystem&&) = delete;
@ -27,7 +31,7 @@ namespace Nz
inline PhysWorld2D& GetPhysWorld();
inline const PhysWorld2D& GetPhysWorld() const;
void Update(entt::registry& registry, float elapsedTime);
void Update(float elapsedTime);
Physics2DSystem& operator=(const Physics2DSystem&) = delete;
Physics2DSystem& operator=(Physics2DSystem&&) = delete;

View File

@ -10,6 +10,7 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Physics3D/PhysWorld3D.hpp>
#include <Nazara/Physics3D/Components/RigidBody3DComponent.hpp>
#include <Nazara/Utils/TypeList.hpp>
#include <entt/entt.hpp>
namespace Nz
@ -17,6 +18,9 @@ namespace Nz
class NAZARA_PHYSICS3D_API Physics3DSystem
{
public:
static constexpr Int64 ExecutionOrder = 0;
using Components = TypeList<RigidBody3DComponent, class NodeComponent>;
Physics3DSystem(entt::registry& registry);
Physics3DSystem(const Physics3DSystem&) = delete;
Physics3DSystem(Physics3DSystem&&) = delete;
@ -27,7 +31,7 @@ namespace Nz
inline PhysWorld3D& GetPhysWorld();
inline const PhysWorld3D& GetPhysWorld() const;
void Update(entt::registry& registry, float elapsedTime);
void Update(float elapsedTime);
Physics3DSystem& operator=(const Physics3DSystem&) = delete;
Physics3DSystem& operator=(Physics3DSystem&&) = delete;

View File

@ -0,0 +1,37 @@
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Systems/SystemGraph.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
SystemGraph::NodeBase::~NodeBase() = default;
void SystemGraph::Update()
{
return Update(m_clock.Restart() / 1'000'000.f);
}
void SystemGraph::Update(float elapsedTime)
{
if (!m_systemOrderUpdated)
{
m_orderedNodes.clear();
m_orderedNodes.reserve(m_nodes.size());
for (auto& nodePtr : m_nodes)
m_orderedNodes.emplace_back(nodePtr.get());
std::sort(m_orderedNodes.begin(), m_orderedNodes.end(), [](const NodeBase* a, const NodeBase* b)
{
return a->executionOrder < b->executionOrder;
});
m_systemOrderUpdated = true;
}
for (NodeBase* node : m_orderedNodes)
node->Update(elapsedTime);
}
}

View File

@ -10,6 +10,7 @@
#include <Nazara/Graphics/Components/GraphicsComponent.hpp>
#include <Nazara/Renderer/CommandBufferBuilder.hpp>
#include <Nazara/Renderer/RenderFrame.hpp>
#include <Nazara/Renderer/RenderWindow.hpp>
#include <Nazara/Renderer/UploadPool.hpp>
#include <Nazara/Utility/Components/NodeComponent.hpp>
#include <Nazara/Graphics/Debug.hpp>
@ -20,6 +21,7 @@ namespace Nz
m_cameraConstructObserver(registry, entt::collector.group<CameraComponent, NodeComponent>()),
m_graphicsConstructObserver(registry, entt::collector.group<GraphicsComponent, NodeComponent>()),
m_lightConstructObserver(registry, entt::collector.group<LightComponent, NodeComponent>()),
m_registry(registry),
m_cameraEntityPool(8),
m_graphicsEntityPool(1024),
m_lightEntityPool(32)
@ -43,12 +45,181 @@ namespace Nz
m_nodeDestroyConnection.release();
}
void RenderSystem::Render(entt::registry& registry, RenderFrame& renderFrame)
void RenderSystem::Update(float /*elapsedTime*/)
{
UpdateObservers();
UpdateVisibility();
UpdateInstances();
for (auto& windowPtr : m_renderWindows)
{
RenderFrame frame = windowPtr->AcquireFrame();
if (!frame)
continue;
if (!m_cameraEntities.empty())
m_pipeline->Render(frame);
frame.Present();
}
}
void RenderSystem::OnCameraDestroy([[maybe_unused]] entt::registry& registry, entt::entity entity)
{
assert(&m_registry == &registry);
auto it = m_cameraEntities.find(entity);
if (it == m_cameraEntities.end())
return;
CameraEntity* cameraEntity = it->second;
m_cameraEntities.erase(it);
m_invalidatedCameraNode.erase(cameraEntity);
m_pipeline->UnregisterViewer(cameraEntity->viewerIndex);
m_cameraEntityPool.Free(cameraEntity->poolIndex);
}
void RenderSystem::OnGraphicsDestroy([[maybe_unused]] entt::registry& registry, entt::entity entity)
{
assert(&m_registry == &registry);
auto it = m_graphicsEntities.find(entity);
if (it == m_graphicsEntities.end())
return;
GraphicsEntity* graphicsEntity = it->second;
m_graphicsEntities.erase(entity);
m_invalidatedGfxWorldNode.erase(graphicsEntity);
m_newlyHiddenGfxEntities.erase(graphicsEntity);
m_newlyVisibleGfxEntities.erase(graphicsEntity);
GraphicsComponent& entityGfx = m_registry.get<GraphicsComponent>(entity);
if (entityGfx.IsVisible())
{
for (std::size_t renderableIndex = 0; renderableIndex < GraphicsComponent::MaxRenderableCount; ++renderableIndex)
{
const auto& renderableEntry = entityGfx.GetRenderableEntry(renderableIndex);
if (!renderableEntry.renderable)
continue;
m_pipeline->UnregisterRenderable(graphicsEntity->renderableIndices[renderableIndex]);
}
}
m_pipeline->UnregisterWorldInstance(graphicsEntity->worldInstanceIndex);
m_graphicsEntityPool.Free(graphicsEntity->poolIndex);
}
void RenderSystem::OnLightDestroy([[maybe_unused]] entt::registry& registry, entt::entity entity)
{
assert(&m_registry == &registry);
auto it = m_lightEntities.find(entity);
if (it == m_lightEntities.end())
return;
LightEntity* lightEntity = it->second;
m_lightEntities.erase(entity);
m_invalidatedLightWorldNode.erase(lightEntity);
m_newlyHiddenLightEntities.erase(lightEntity);
m_newlyVisibleLightEntities.erase(lightEntity);
LightComponent& entityLight = m_registry.get<LightComponent>(entity);
if (entityLight.IsVisible())
{
for (std::size_t lightIndex = 0; lightIndex < LightComponent::MaxLightCount; ++lightIndex)
{
const auto& lightEntry = entityLight.GetLightEntry(lightIndex);
if (!lightEntry.light)
continue;
m_pipeline->UnregisterLight(lightEntity->lightIndices[lightIndex]);
}
}
m_lightEntityPool.Free(lightEntity->poolIndex);
}
void RenderSystem::OnNodeDestroy(entt::registry& registry, entt::entity entity)
{
assert(&m_registry == &registry);
if (m_registry.try_get<CameraComponent>(entity))
OnCameraDestroy(registry, entity);
if (m_registry.try_get<GraphicsComponent>(entity))
OnGraphicsDestroy(registry, entity);
if (m_registry.try_get<LightComponent>(entity))
OnLightDestroy(registry, entity);
}
void RenderSystem::UpdateInstances()
{
for (CameraEntity* cameraEntity : m_invalidatedCameraNode)
{
entt::entity entity = cameraEntity->entity;
const NodeComponent& entityNode = m_registry.get<const NodeComponent>(entity);
CameraComponent& entityCamera = m_registry.get<CameraComponent>(entity);
Vector3f cameraPosition = entityNode.GetPosition(CoordSys::Global);
ViewerInstance& viewerInstance = entityCamera.GetViewerInstance();
viewerInstance.UpdateEyePosition(cameraPosition);
viewerInstance.UpdateViewMatrix(Nz::Matrix4f::TransformInverse(cameraPosition, entityNode.GetRotation(CoordSys::Global)));
m_pipeline->InvalidateViewer(cameraEntity->viewerIndex);
}
m_invalidatedCameraNode.clear();
for (GraphicsEntity* graphicsEntity : m_invalidatedGfxWorldNode)
{
entt::entity entity = graphicsEntity->entity;
const NodeComponent& entityNode = m_registry.get<const NodeComponent>(entity);
GraphicsComponent& entityGraphics = m_registry.get<GraphicsComponent>(entity);
const WorldInstancePtr& worldInstance = entityGraphics.GetWorldInstance();
worldInstance->UpdateWorldMatrix(entityNode.GetTransformMatrix());
m_pipeline->InvalidateWorldInstance(graphicsEntity->worldInstanceIndex);
}
m_invalidatedGfxWorldNode.clear();
for (LightEntity* lightEntity : m_invalidatedLightWorldNode)
{
entt::entity entity = lightEntity->entity;
const NodeComponent& entityNode = m_registry.get<const NodeComponent>(entity);
LightComponent& entityLight = m_registry.get<LightComponent>(entity);
const Vector3f& position = entityNode.GetPosition(CoordSys::Global);
const Quaternionf& rotation = entityNode.GetRotation(CoordSys::Global);
const Vector3f& scale = entityNode.GetScale(CoordSys::Global);
for (const auto& lightEntry : entityLight.GetLights())
{
if (!lightEntry.light)
continue;
lightEntry.light->UpdateTransform(position, rotation, scale);
}
}
m_invalidatedLightWorldNode.clear();
}
void RenderSystem::UpdateObservers()
{
m_cameraConstructObserver.each([&](entt::entity entity)
{
CameraComponent& entityCamera = registry.get<CameraComponent>(entity);
NodeComponent& entityNode = registry.get<NodeComponent>(entity);
CameraComponent& entityCamera = m_registry.get<CameraComponent>(entity);
NodeComponent& entityNode = m_registry.get<NodeComponent>(entity);
std::size_t poolIndex;
CameraEntity* cameraEntity = m_cameraEntityPool.Allocate(poolIndex);
@ -68,8 +239,8 @@ namespace Nz
m_graphicsConstructObserver.each([&](entt::entity entity)
{
GraphicsComponent& entityGfx = registry.get<GraphicsComponent>(entity);
NodeComponent& entityNode = registry.get<NodeComponent>(entity);
GraphicsComponent& entityGfx = m_registry.get<GraphicsComponent>(entity);
NodeComponent& entityNode = m_registry.get<NodeComponent>(entity);
std::size_t poolIndex;
GraphicsEntity* graphicsEntity = m_graphicsEntityPool.Allocate(poolIndex);
@ -147,8 +318,8 @@ namespace Nz
m_lightConstructObserver.each([&](entt::entity entity)
{
LightComponent& entityLight = registry.get<LightComponent>(entity);
NodeComponent& entityNode = registry.get<NodeComponent>(entity);
LightComponent& entityLight = m_registry.get<LightComponent>(entity);
NodeComponent& entityNode = m_registry.get<NodeComponent>(entity);
std::size_t poolIndex;
LightEntity* lightEntity = m_lightEntityPool.Allocate(poolIndex);
@ -212,162 +383,14 @@ namespace Nz
assert(m_lightEntities.find(entity) == m_lightEntities.end());
m_lightEntities.emplace(entity, lightEntity);
});
UpdateVisibility(registry);
UpdateInstances(registry);
if (!m_cameraEntities.empty())
m_pipeline->Render(renderFrame);
}
void RenderSystem::OnCameraDestroy(entt::registry& /*registry*/, entt::entity entity)
{
auto it = m_cameraEntities.find(entity);
if (it == m_cameraEntities.end())
return;
CameraEntity* cameraEntity = it->second;
m_cameraEntities.erase(it);
m_invalidatedCameraNode.erase(cameraEntity);
m_pipeline->UnregisterViewer(cameraEntity->viewerIndex);
m_cameraEntityPool.Free(cameraEntity->poolIndex);
}
void RenderSystem::OnGraphicsDestroy(entt::registry& registry, entt::entity entity)
{
auto it = m_graphicsEntities.find(entity);
if (it == m_graphicsEntities.end())
return;
GraphicsEntity* graphicsEntity = it->second;
m_graphicsEntities.erase(entity);
m_invalidatedGfxWorldNode.erase(graphicsEntity);
m_newlyHiddenGfxEntities.erase(graphicsEntity);
m_newlyVisibleGfxEntities.erase(graphicsEntity);
GraphicsComponent& entityGfx = registry.get<GraphicsComponent>(entity);
if (entityGfx.IsVisible())
{
for (std::size_t renderableIndex = 0; renderableIndex < GraphicsComponent::MaxRenderableCount; ++renderableIndex)
{
const auto& renderableEntry = entityGfx.GetRenderableEntry(renderableIndex);
if (!renderableEntry.renderable)
continue;
m_pipeline->UnregisterRenderable(graphicsEntity->renderableIndices[renderableIndex]);
}
}
m_pipeline->UnregisterWorldInstance(graphicsEntity->worldInstanceIndex);
m_graphicsEntityPool.Free(graphicsEntity->poolIndex);
}
void RenderSystem::OnLightDestroy(entt::registry& registry, entt::entity entity)
{
auto it = m_lightEntities.find(entity);
if (it == m_lightEntities.end())
return;
LightEntity* lightEntity = it->second;
m_lightEntities.erase(entity);
m_invalidatedLightWorldNode.erase(lightEntity);
m_newlyHiddenLightEntities.erase(lightEntity);
m_newlyVisibleLightEntities.erase(lightEntity);
LightComponent& entityLight = registry.get<LightComponent>(entity);
if (entityLight.IsVisible())
{
for (std::size_t lightIndex = 0; lightIndex < LightComponent::MaxLightCount; ++lightIndex)
{
const auto& lightEntry = entityLight.GetLightEntry(lightIndex);
if (!lightEntry.light)
continue;
m_pipeline->UnregisterLight(lightEntity->lightIndices[lightIndex]);
}
}
m_lightEntityPool.Free(lightEntity->poolIndex);
}
void RenderSystem::OnNodeDestroy(entt::registry& registry, entt::entity entity)
{
if (registry.try_get<CameraComponent>(entity))
OnCameraDestroy(registry, entity);
if (registry.try_get<GraphicsComponent>(entity))
OnGraphicsDestroy(registry, entity);
if (registry.try_get<LightComponent>(entity))
OnLightDestroy(registry, entity);
}
void RenderSystem::UpdateInstances(entt::registry& registry)
{
for (CameraEntity* cameraEntity : m_invalidatedCameraNode)
{
entt::entity entity = cameraEntity->entity;
const NodeComponent& entityNode = registry.get<const NodeComponent>(entity);
CameraComponent& entityCamera = registry.get<CameraComponent>(entity);
Vector3f cameraPosition = entityNode.GetPosition(CoordSys::Global);
ViewerInstance& viewerInstance = entityCamera.GetViewerInstance();
viewerInstance.UpdateEyePosition(cameraPosition);
viewerInstance.UpdateViewMatrix(Nz::Matrix4f::TransformInverse(cameraPosition, entityNode.GetRotation(CoordSys::Global)));
m_pipeline->InvalidateViewer(cameraEntity->viewerIndex);
}
m_invalidatedCameraNode.clear();
for (GraphicsEntity* graphicsEntity : m_invalidatedGfxWorldNode)
{
entt::entity entity = graphicsEntity->entity;
const NodeComponent& entityNode = registry.get<const NodeComponent>(entity);
GraphicsComponent& entityGraphics = registry.get<GraphicsComponent>(entity);
const WorldInstancePtr& worldInstance = entityGraphics.GetWorldInstance();
worldInstance->UpdateWorldMatrix(entityNode.GetTransformMatrix());
m_pipeline->InvalidateWorldInstance(graphicsEntity->worldInstanceIndex);
}
m_invalidatedGfxWorldNode.clear();
for (LightEntity* lightEntity : m_invalidatedLightWorldNode)
{
entt::entity entity = lightEntity->entity;
const NodeComponent& entityNode = registry.get<const NodeComponent>(entity);
LightComponent& entityLight = registry.get<LightComponent>(entity);
const Vector3f& position = entityNode.GetPosition(CoordSys::Global);
const Quaternionf& rotation = entityNode.GetRotation(CoordSys::Global);
const Vector3f& scale = entityNode.GetScale(CoordSys::Global);
for (const auto& lightEntry : entityLight.GetLights())
{
if (!lightEntry.light)
continue;
lightEntry.light->UpdateTransform(position, rotation, scale);
}
}
m_invalidatedLightWorldNode.clear();
}
void RenderSystem::UpdateVisibility(entt::registry& registry)
void RenderSystem::UpdateVisibility()
{
// Unregister drawable for hidden entities
for (GraphicsEntity* graphicsEntity : m_newlyHiddenGfxEntities)
{
GraphicsComponent& entityGfx = registry.get<GraphicsComponent>(graphicsEntity->entity);
GraphicsComponent& entityGfx = m_registry.get<GraphicsComponent>(graphicsEntity->entity);
for (std::size_t renderableIndex = 0; renderableIndex < GraphicsComponent::MaxRenderableCount; ++renderableIndex)
{
@ -383,7 +406,7 @@ namespace Nz
// Register drawable for newly visible entities
for (GraphicsEntity* graphicsEntity : m_newlyVisibleGfxEntities)
{
GraphicsComponent& entityGfx = registry.get<GraphicsComponent>(graphicsEntity->entity);
GraphicsComponent& entityGfx = m_registry.get<GraphicsComponent>(graphicsEntity->entity);
for (std::size_t renderableIndex = 0; renderableIndex < GraphicsComponent::MaxRenderableCount; ++renderableIndex)
{
@ -399,7 +422,7 @@ namespace Nz
// Unregister lights for hidden entities
for (LightEntity* lightEntity : m_newlyHiddenLightEntities)
{
LightComponent& entityLights = registry.get<LightComponent>(lightEntity->entity);
LightComponent& entityLights = m_registry.get<LightComponent>(lightEntity->entity);
for (std::size_t lightIndex = 0; lightIndex < LightComponent::MaxLightCount; ++lightIndex)
{
@ -415,7 +438,7 @@ namespace Nz
// Register lights for newly visible entities
for (LightEntity* lightEntity : m_newlyVisibleLightEntities)
{
LightComponent& entityLights = registry.get<LightComponent>(lightEntity->entity);
LightComponent& entityLights = m_registry.get<LightComponent>(lightEntity->entity);
for (std::size_t renderableIndex = 0; renderableIndex < LightComponent::MaxLightCount; ++renderableIndex)
{

View File

@ -35,12 +35,12 @@ namespace Nz
m_constructConnection.release();
}
void Physics2DSystem::Update(entt::registry& registry, float elapsedTime)
void Physics2DSystem::Update(float elapsedTime)
{
m_physWorld.Step(elapsedTime);
// Replicate rigid body position to their node components
auto view = registry.view<NodeComponent, const RigidBody2DComponent>();
auto view = m_registry.view<NodeComponent, const RigidBody2DComponent>();
for (auto [entity, nodeComponent, rigidBodyComponent] : view.each())
{
if (rigidBodyComponent.IsSleeping())

View File

@ -24,12 +24,12 @@ namespace Nz
m_constructConnection.release();
}
void Physics3DSystem::Update(entt::registry& registry, float elapsedTime)
void Physics3DSystem::Update(float elapsedTime)
{
m_physWorld.Step(elapsedTime);
// Replicate rigid body position to their node components
auto view = registry.view<NodeComponent, const RigidBody3DComponent>();
auto view = m_registry.view<NodeComponent, const RigidBody3DComponent>();
for (auto [entity, nodeComponent, rigidBodyComponent] : view.each())
{
if (rigidBodyComponent.IsSleeping())