diff --git a/.github/workflows/linux-build.yml b/.github/workflows/linux-build.yml new file mode 100644 index 000000000..e4a7507fd --- /dev/null +++ b/.github/workflows/linux-build.yml @@ -0,0 +1,83 @@ +name: Linux-Build + +on: + pull_request: + push: + paths-ignore: + - '.github/workflows/windows-build.yml' + - '.gitignore' + - 'LICENSE' + - 'CHANGELOG.md' + - 'README.md' + - 'README_en.md' + - 'README_fr.md' + +jobs: + build: + strategy: + matrix: + os: [ubuntu-20.04] + arch: [x64] + mode: [debug, releasedbg] + + runs-on: ${{ matrix.os }} + if: "!contains(github.event.head_commit.message, 'ci skip')" + + steps: + - uses: actions/checkout@v2 + + # Install Qt (required for shader nodes editor) + - name: Install Qt + uses: jurplel/install-qt-action@v2 + + # Install Nazara dependencies + - name: Update apt repositories + run: sudo apt-get update + + # Install Nazara dependencies + - name: Install system dependencies + run: sudo apt-get install libsndfile1-dev libfreetype6-dev libsdl2-dev mesa-common-dev libxcb-ewmh-dev libxcb-randr0-dev libxcb-icccm4-dev libxcb-keysyms1-dev libgl1-mesa-dev -y + + # Force xmake to a specific folder (for cache) + - name: Set xmake env + run: echo "XMAKE_GLOBALDIR=${{ runner.workspace }}/xmake-global" >> $GITHUB_ENV + + # Install xmake + - name: Setup xmake + uses: xmake-io/github-action-setup-xmake@v1 + with: + xmake-version: branch@dev + + # Update xmake repository (in order to have the file that will be cached) + - name: Update xmake repository + run: xmake repo --update + + # Fetch xmake dephash + - name: Retrieve dependencies hash + id: dep_hash + run: echo "::set-output name=hash::$(xmake l utils.ci.packageskey)" + + # Cache xmake dependencies + - name: Retrieve cached xmake dependencies + uses: actions/cache@v2 + with: + path: ${{ env.XMAKE_GLOBALDIR }}/.xmake/packages + key: ${{ runner.os }}-${{ matrix.arch }}-${{ matrix.mode }}-${{ steps.dep_hash.outputs.hash }} + + # Setup compilation mode and install project dependencies + - name: Configure xmake and install dependencies + run: xmake config --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes --verbose + + # Build the engine + - name: Build Nazara + run: xmake + + # Install the result files + - name: Install Nazara + run: xmake install -vo package + + # Upload artifacts + - uses: actions/upload-artifact@v2 + with: + name: ${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.mode }} + path: package diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml new file mode 100644 index 000000000..135950066 --- /dev/null +++ b/.github/workflows/windows-build.yml @@ -0,0 +1,75 @@ +name: Windows-Build + +on: + pull_request: + push: + paths-ignore: + - '.github/workflows/linux-build.yml' + - '.gitignore' + - 'LICENSE' + - 'CHANGELOG.md' + - 'README.md' + - 'README_en.md' + - 'README_fr.md' + +jobs: + build: + strategy: + matrix: + os: [windows-latest] + arch: [x64] + mode: [debug, releasedbg] + + runs-on: ${{ matrix.os }} + if: "!contains(github.event.head_commit.message, 'ci skip')" + + steps: + - uses: actions/checkout@v2 + + # Install Qt (required for shader nodes editor) + - name: Install Qt + uses: jurplel/install-qt-action@v2 + + # Force xmake to a specific folder (for cache) + - name: Set xmake env + run: echo "XMAKE_GLOBALDIR=${{ runner.workspace }}/xmake-global" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + + # Install xmake + - name: Setup xmake + uses: xmake-io/github-action-setup-xmake@v1 + with: + xmake-version: branch@dev + + # Update xmake repository (in order to have the file that will be cached) + - name: Update xmake repository + run: xmake.exe repo --update + + # Fetch xmake dephash + - name: Retrieve dependencies hash + id: dep_hash + run: echo "::set-output name=hash::$(xmake.exe l utils.ci.packageskey)" + + # Cache xmake dependencies + - name: Retrieve cached xmake dependencies + uses: actions/cache@v2 + with: + path: ${{ env.XMAKE_GLOBALDIR }}\.xmake\packages + key: ${{ runner.os }}-${{ matrix.arch }}-${{ matrix.mode }}-${{ steps.dep_hash.outputs.hash }} + + # Setup compilation mode and install project dependencies + - name: Configure xmake and install dependencies + run: xmake.exe config --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes --verbose + + # Build the engine + - name: Build Nazara + run: xmake.exe + + # Install the result files + - name: Install Nazara + run: xmake.exe install -vo package + + # Upload artifacts + - uses: actions/upload-artifact@v2 + with: + name: ${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.mode }} + path: package diff --git a/.gitignore b/.gitignore index 664c24928..1b9a63d4e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,19 @@ -# Nazara build -build/config.lua +# xmake-related files +.xmake/* +.vs/* +.vscode/* +CMakeLists.txt +Makefile +vs/* +vsxmake*/* + +# Nazara binaries +bin/* +!bin/resources +!bin/resources/* + +# Build files +build/* # Nazara libraries lib/* @@ -166,5 +180,3 @@ DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html - -build/gmake/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 17bccbd36..000000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: - cpp - -sudo: - required - -notifications: - email: true - -services: - - docker - -before_install: - - docker build -t nazara . - -script: - - docker run --name Nazara -v `pwd`:/NazaraEngine nazara - sh -c " - cd build && - ./premake5-linux64 --cc=clang gmake && - cd gmake && - make -j4 && - cd ../../tests && - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../lib/gmake/x64/:../extlibs/lib/gmake/x64/ && - ./NazaraUnitTestsServer - " diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index b1ab55789..000000000 --- a/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM debian:buster - -RUN apt-get update && apt-get install -y build-essential clang libopenal-dev libsndfile1-dev libfreetype6-dev libassimp-dev libsdl2-dev libxcb-keysyms1-dev libxcb-ewmh-dev libx11-dev libfreetype6-dev mesa-common-dev libgl1-mesa-dev - -RUN mkdir /NazaraEngine -WORKDIR /NazaraEngine \ No newline at end of file diff --git a/NazaraModuleTemplate/build/scripts/modules/modulename.lua b/NazaraModuleTemplate/build/scripts/modules/modulename.lua deleted file mode 100644 index 7f954dd6a..000000000 --- a/NazaraModuleTemplate/build/scripts/modules/modulename.lua +++ /dev/null @@ -1,15 +0,0 @@ -MODULE.Name = "ModuleName" - -MODULE.Libraries = { - "NazaraCore" -} - -MODULE.OsFiles.Windows = { - "../src/Nazara/ModuleName/Win32/**.hpp", - "../src/Nazara/ModuleName/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/ModuleName/Posix/**.hpp", - "../src/Nazara/ModuleName/Posix/**.cpp" -} diff --git a/NazaraModuleTemplate/include/Nazara/ModuleName/ClassName.hpp b/NazaraModuleTemplate/include/Nazara/ModuleName/ClassName.hpp deleted file mode 100644 index e4866c2bc..000000000 --- a/NazaraModuleTemplate/include/Nazara/ModuleName/ClassName.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) YEAR AUTHORS -// This file is part of the "Nazara Engine - Module name" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_CLASSNAME_HPP -#define NAZARA_CLASSNAME_HPP - -#include - -namespace Nz -{ - class NAZARA_MODULENAME_API ClassName - { - public: - ClassName(); - - int GetAttribute() const; - - void SetAttribute(int attribute); - - private: - int m_attribute; - }; -} - -#endif // NAZARA_CLASSNAME_HPP diff --git a/NazaraModuleTemplate/include/Nazara/ModuleName/ModuleName.hpp b/NazaraModuleTemplate/include/Nazara/ModuleName/ModuleName.hpp deleted file mode 100644 index c018f899f..000000000 --- a/NazaraModuleTemplate/include/Nazara/ModuleName/ModuleName.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) YEAR AUTHORS -// This file is part of the "Nazara Engine - Module name" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#pragma once - -#ifndef NAZARA_MODULENAME_HPP -#define NAZARA_MODULENAME_HPP - -#include -#include -#include - -namespace Nz -{ - class NAZARA_MODULENAME_API ModuleName - { - public: - ModuleName() = delete; - ~ModuleName() = delete; - - static bool Initialize(); - - static bool IsInitialized(); - - static void Uninitialize(); - - private: - static unsigned int s_moduleReferenceCounter; - }; -} - -#endif // NAZARA_MODULENAME_HPP diff --git a/NazaraModuleTemplate/src/Nazara/ModuleName/ClassName.cpp b/NazaraModuleTemplate/src/Nazara/ModuleName/ClassName.cpp deleted file mode 100644 index 636cb270c..000000000 --- a/NazaraModuleTemplate/src/Nazara/ModuleName/ClassName.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (C) YEAR AUTHORS -// This file is part of the "Nazara Engine - Module name" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include - -namespace Nz -{ - ClassName::ClassName() : - m_attribute(42) - { - } - - int ClassName::GetAttribute() const - { - return m_attribute; - } - - void ClassName::SetAttribute(int attribute) - { - m_attribute = attribute; - } -} - diff --git a/NazaraModuleTemplate/src/Nazara/ModuleName/ModuleName.cpp b/NazaraModuleTemplate/src/Nazara/ModuleName/ModuleName.cpp deleted file mode 100644 index e286520f8..000000000 --- a/NazaraModuleTemplate/src/Nazara/ModuleName/ModuleName.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (C) YEAR AUTHORS -// This file is part of the "Nazara Engine - Module name" -// For conditions of distribution and use, see copyright notice in Config.hpp - -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - bool ModuleName::Initialize() - { - if (s_moduleReferenceCounter > 0) - { - s_moduleReferenceCounter++; - return true; // Already initialized - } - - // Initialize module dependencies - if (!Core::Initialize()) - { - NazaraError("Failed to initialize core module"); - return false; - } - - s_moduleReferenceCounter++; - - CallOnExit onExit(ModuleName::Uninitialize); - - // Initialize module here - - onExit.Reset(); - - NazaraNotice("Initialized: ModuleName module"); - return true; - } - - bool ModuleName::IsInitialized() - { - return s_moduleReferenceCounter != 0; - } - - void ModuleName::Uninitialize() - { - if (s_moduleReferenceCounter != 1) - { - // Either the module is not initialized, either it was initialized multiple times - if (s_moduleReferenceCounter > 1) - s_moduleReferenceCounter--; - - return; - } - - s_moduleReferenceCounter = 0; - - // Uninitialize module here - - NazaraNotice("Uninitialized: ModuleName module"); - - // Free module dependencies - Core::Uninitialize(); - } - - unsigned int ModuleName::s_moduleReferenceCounter = 0; -} - diff --git a/SDK/include/NDK/Application.hpp b/SDK/include/NDK/Application.hpp deleted file mode 100644 index 69e97bdce..000000000 --- a/SDK/include/NDK/Application.hpp +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_APPLICATION_HPP -#define NDK_APPLICATION_HPP - -#include -#include -#include -#include -#include -#include - -#ifndef NDK_SERVER -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace Ndk -{ - class NDK_API Application - { - public: - #ifndef NDK_SERVER - struct ConsoleOverlay; - struct FPSCounterOverlay; - #endif - - inline Application(); - Application(int argc, char* argv[]); - Application(const Application&) = delete; - Application(Application&&) = delete; - inline ~Application(); - - #ifndef NDK_SERVER - template T& AddWindow(Args&&... args); - #endif - template World& AddWorld(Args&&... args); - - #ifndef NDK_SERVER - inline void EnableConsole(bool enable); - inline void EnableFPSCounter(bool enable); - - inline ConsoleOverlay& GetConsoleOverlay(std::size_t windowIndex = 0U); - inline FPSCounterOverlay& GetFPSCounterOverlay(std::size_t windowIndex = 0U); - #endif - - inline const std::set& GetOptions() const; - inline const std::map& GetParameters() const; - - inline float GetUpdateTime() const; - - inline bool HasOption(const Nz::String& option) const; - inline bool HasParameter(const Nz::String& key, Nz::String* value) const; - - #ifndef NDK_SERVER - inline bool IsConsoleEnabled() const; - inline bool IsFPSCounterEnabled() const; - #endif - - bool Run(); - - #ifndef NDK_SERVER - inline void MakeExitOnLastWindowClosed(bool exitOnClosedWindows); - #endif - - inline void Quit(); - - Application& operator=(const Application&) = delete; - Application& operator=(Application&&) = delete; - - inline static Application* Instance(); - - #ifndef NDK_SERVER - struct ConsoleOverlay - { - Console* console; - Nz::LuaInstance lua; - - NazaraSlot(Nz::EventHandler, OnEvent, eventSlot); - NazaraSlot(Nz::EventHandler, OnKeyPressed, keyPressedSlot); - NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, resizedSlot); - NazaraSlot(Nz::Log, OnLogWrite, logSlot); - }; - - struct FPSCounterOverlay - { - Nz::TextSpriteRef sprite; - EntityOwner entity; - float elapsedTime = 0.f; - unsigned int frameCount = 0; - }; - #endif - - private: - #ifndef NDK_SERVER - enum OverlayFlags - { - OverlayFlags_Console = 0x1, - OverlayFlags_FPSCounter = 0x2 - }; - - struct WindowInfo - { - inline WindowInfo(std::unique_ptr&& window); - - Nz::RenderTarget* renderTarget; - std::unique_ptr window; - std::unique_ptr console; - std::unique_ptr canvas; - std::unique_ptr fpsCounter; - std::unique_ptr overlayWorld; - }; - - void SetupConsole(WindowInfo& info); - void SetupFPSCounter(WindowInfo& info); - void SetupOverlay(WindowInfo& info); - - template void SetupWindow(WindowInfo& info, T* renderTarget, std::true_type /*isRenderTarget*/); - template void SetupWindow(WindowInfo& /*info*/, T* /*renderTarget*/, std::false_type /*isNotRenderTarget*/); - - std::vector m_windows; - #endif - - std::map m_parameters; - std::set m_options; - std::list m_worlds; - Nz::Clock m_updateClock; - - #ifndef NDK_SERVER - Nz::UInt32 m_overlayFlags; - bool m_exitOnClosedWindows; - #endif - bool m_shouldQuit; - float m_updateTime; - - static Application* s_application; - }; -} - -#include - -#endif // NDK_APPLICATION_HPP diff --git a/SDK/include/NDK/Application.inl b/SDK/include/NDK/Application.inl deleted file mode 100644 index 42139db0c..000000000 --- a/SDK/include/NDK/Application.inl +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - /*! - * \brief Constructs an Application object without passing command-line arguments - * - * This calls Sdk::Initialize() - * - * \remark Only one Application instance can exist at a time - */ - inline Application::Application() : - #ifndef NDK_SERVER - m_overlayFlags(0U), - m_exitOnClosedWindows(true), - #endif - m_shouldQuit(false), - m_updateTime(0.f) - { - NazaraAssert(s_application == nullptr, "You can create only one application instance per program"); - s_application = this; - - Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true); - - // Initialisation du SDK - Sdk::Initialize(); - } - - /*! - * \brief Destructs the application object - * - * This destroy all worlds and windows and then calls Sdk::Uninitialize - */ - inline Application::~Application() - { - m_worlds.clear(); - #ifndef NDK_SERVER - m_windows.clear(); - #endif - - // Free of SDK - Sdk::Uninitialize(); - - // Automatic free of modules - s_application = nullptr; - } - - /*! - * \brief Adds a window to the application - * \return A reference to the newly created windows - * - * \param args Arguments used to create the window - */ - #ifndef NDK_SERVER - template - T& Application::AddWindow(Args&&... args) - { - static_assert(std::is_base_of::value, "Type must inherit Window"); - - m_windows.emplace_back(std::make_unique(std::forward(args)...)); - WindowInfo& info = m_windows.back(); - - T& window = static_cast(*info.window.get()); //< Warning: ugly - - SetupWindow(info, &window, std::is_base_of()); - - return window; - } - #endif - - /*! - * \brief Adds a world to the application - * \return A reference to the newly created world - * - * \param args Arguments used to create the world - */ - - template - World& Application::AddWorld(Args&&... args) - { - m_worlds.emplace_back(std::forward(args)...); - return m_worlds.back(); - } - - /*! - * \brief Enable/disable debug console - * - * \param enable Should the console overlay be enabled - */ - #ifndef NDK_SERVER - inline void Application::EnableConsole(bool enable) - { - if (enable != ((m_overlayFlags & OverlayFlags_Console) != 0)) - { - if (enable) - { - if (m_overlayFlags == 0) - { - for (WindowInfo& info : m_windows) - SetupOverlay(info); - } - - for (WindowInfo& info : m_windows) - { - if (info.renderTarget) - SetupConsole(info); - } - - m_overlayFlags |= OverlayFlags_Console; - } - else - { - for (WindowInfo& info : m_windows) - info.console.reset(); - - m_overlayFlags &= ~OverlayFlags_Console; - if (m_overlayFlags == 0) - { - for (WindowInfo& info : m_windows) - info.overlayWorld.reset(); - } - } - } - } - #endif - - /*! - * \brief Enable/disable debug FPS counter - * - * \param enable Should the FPS counter be displayed - */ - #ifndef NDK_SERVER - inline void Application::EnableFPSCounter(bool enable) - { - if (enable != ((m_overlayFlags & OverlayFlags_FPSCounter) != 0)) - { - if (enable) - { - if (m_overlayFlags == 0) - { - for (WindowInfo& info : m_windows) - SetupOverlay(info); - } - - for (WindowInfo& info : m_windows) - { - if (info.renderTarget) - SetupFPSCounter(info); - } - - m_overlayFlags |= OverlayFlags_FPSCounter; - - } - else - { - for (WindowInfo& info : m_windows) - info.fpsCounter.reset(); - - m_overlayFlags &= ~OverlayFlags_FPSCounter; - if (m_overlayFlags == 0) - { - for (WindowInfo& info : m_windows) - info.overlayWorld.reset(); - } - } - } - } - #endif - - /*! - * \brief Gets the console overlay for a specific window - * - * \param windowIndex Index of the window to get - * - * \remark The console overlay must be enabled - * - * \return A reference to the console overlay of the window - * - * \see IsConsoleOverlayEnabled - */ - #ifndef NDK_SERVER - inline Application::ConsoleOverlay& Application::GetConsoleOverlay(std::size_t windowIndex) - { - NazaraAssert(m_overlayFlags & OverlayFlags_Console, "Console overlay is not enabled"); - NazaraAssert(windowIndex <= m_windows.size(), "Window index is out of range"); - - return *m_windows[windowIndex].console; - } - #endif - - /*! - * \brief Gets the console overlay for a specific window - * - * \param windowIndex Index of the window to get - * - * \remark The console overlay must be enabled - * - * \return A reference to the console overlay of the window - * - * \see IsFPSCounterEnabled - */ - #ifndef NDK_SERVER - inline Application::FPSCounterOverlay& Application::GetFPSCounterOverlay(std::size_t windowIndex) - { - NazaraAssert(m_overlayFlags & OverlayFlags_FPSCounter, "FPS counter overlay is not enabled"); - NazaraAssert(windowIndex <= m_windows.size(), "Window index is out of range"); - - return *m_windows[windowIndex].fpsCounter; - } - #endif - - /*! - * \brief Gets the options used to start the application - * - * Options are defined as "-optionName" in command-line and are always lower-case - * - * \return Command-line options - */ - inline const std::set& Application::GetOptions() const - { - return m_options; - } - - /*! - * \brief Gets the parameters used to start the application - * - * Parameters are defined as "-key=value" in command-line, their key is lower-case but value capitals are kept. - * - * \return Command-line parameters - */ - inline const std::map& Application::GetParameters() const - { - return m_parameters; - } - - /*! - * \brief Gets the update time of the application - * \return Update rate - */ - inline float Application::GetUpdateTime() const - { - return m_updateTime; - } - - /*! - * \brief Query for a command-line option - * - * \param option Option name - * - * \remark option must be lower-case - * - * \return True if option is present - * - * \see GetOptions - */ - inline bool Application::HasOption(const Nz::String& option) const - { - return m_options.count(option) != 0; - } - - /*! - * \brief Query for a command-line option - * - * \param key Parameter name - * \param value Optional string to receive the parameter value - * - * \remark key must be lower-case - * - * \return True if parameter is present - * - * \see GetParameters - */ - inline bool Application::HasParameter(const Nz::String& key, Nz::String* value) const - { - auto it = m_parameters.find(key); - if (it == m_parameters.end()) - return false; - - if (value) - *value = it->second; - - return true; - } - - /*! - * \brief Checks if the console overlay is enabled - * - * \remark This has nothing to do with the visibility state of the console - * - * \return True if the console overlay is enabled - * - * \see GetConsoleOverlay - */ - #ifndef NDK_SERVER - inline bool Application::IsConsoleEnabled() const - { - return (m_overlayFlags & OverlayFlags_Console) != 0; - } - #endif - - /*! - * \brief Checks if the FPS counter overlay is enabled - * \return True if the FPS counter overlay is enabled - * - * \see GetFPSCounterOverlay - */ - #ifndef NDK_SERVER - inline bool Application::IsFPSCounterEnabled() const - { - return (m_overlayFlags & OverlayFlags_FPSCounter) != 0; - } - #endif - - /*! - * \brief Makes the application exit when there's no more open window - * - * \param exitOnClosedWindows Should exit be called when no more window is open - */ - #ifndef NDK_SERVER - inline void Application::MakeExitOnLastWindowClosed(bool exitOnClosedWindows) - { - m_exitOnClosedWindows = exitOnClosedWindows; - } - #endif - - /*! - * \brief Quits the application - */ - - inline void Application::Quit() - { - m_shouldQuit = true; - } - - /*! - * \brief Gets the singleton instance of the application - * \return Singleton application - */ - - inline Application* Application::Instance() - { - return s_application; - } - - #ifndef NDK_SERVER - template - inline void Application::SetupWindow(WindowInfo& info, T* renderTarget, std::true_type) - { - info.renderTarget = renderTarget; - - if (m_overlayFlags) - { - SetupOverlay(info); - - if (m_overlayFlags & OverlayFlags_Console) - SetupConsole(info); - - if (m_overlayFlags & OverlayFlags_FPSCounter) - SetupFPSCounter(info); - } - } - - template - inline void Application::SetupWindow(WindowInfo&, T*, std::false_type) - { - } - - inline Application::WindowInfo::WindowInfo(std::unique_ptr&& windowPtr) : - renderTarget(nullptr), - window(std::move(windowPtr)) - { - } - #endif -} diff --git a/SDK/include/NDK/BaseWidget.hpp b/SDK/include/NDK/BaseWidget.hpp deleted file mode 100644 index f0061aded..000000000 --- a/SDK/include/NDK/BaseWidget.hpp +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_BASEWIDGET_HPP -#define NDK_BASEWIDGET_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class Canvas; - - class NDK_API BaseWidget : public Nz::Node - { - friend Canvas; - - public: - BaseWidget(BaseWidget* parent); - BaseWidget(const BaseWidget&) = delete; - BaseWidget(BaseWidget&&) = delete; - virtual ~BaseWidget(); - - template T* Add(Args&&... args); - inline void AddChild(std::unique_ptr&& widget); - - inline void Center(); - inline void CenterHorizontal(); - inline void CenterVertical(); - - void ClearFocus(); - inline void ClearRenderingRect(); - - void Destroy(); - - void EnableBackground(bool enable); - - template void ForEachWidgetChild(F iterator); - template void ForEachWidgetChild(F iterator) const; - - //virtual BaseWidget* Clone() const = 0; - - inline const Nz::Color& GetBackgroundColor() const; - inline Canvas* GetCanvas(); - inline Nz::SystemCursor GetCursor() const; - inline float GetHeight() const; - - inline float GetMaximumHeight() const; - inline Nz::Vector2f GetMaximumSize() const; - inline float GetMaximumWidth() const; - - inline float GetMinimumHeight() const; - inline Nz::Vector2f GetMinimumSize() const; - inline float GetMinimumWidth() const; - - inline float GetPreferredHeight() const; - inline Nz::Vector2f GetPreferredSize() const; - inline float GetPreferredWidth() const; - - inline const Nz::Rectf& GetRenderingRect() const; - - inline Nz::Vector2f GetSize() const; - inline float GetWidth() const; - inline std::size_t GetWidgetChildCount() const; - - bool HasFocus() const; - - inline void Hide(); - inline bool IsVisible() const; - - void Resize(const Nz::Vector2f& size); - - void SetBackgroundColor(const Nz::Color& color); - void SetCursor(Nz::SystemCursor systemCursor); - void SetFocus(); - void SetParent(BaseWidget* widget); - - inline void SetFixedHeight(float fixedHeight); - inline void SetFixedSize(const Nz::Vector2f& fixedSize); - inline void SetFixedWidth(float fixedWidth); - - inline void SetMaximumHeight(float maximumHeight); - inline void SetMaximumSize(const Nz::Vector2f& maximumSize); - inline void SetMaximumWidth(float maximumWidth); - - inline void SetMinimumHeight(float minimumHeight); - inline void SetMinimumSize(const Nz::Vector2f& minimumSize); - inline void SetMinimumWidth(float minimumWidth); - - virtual void SetRenderingRect(const Nz::Rectf& renderingRect); - - void Show(bool show = true); - - BaseWidget& operator=(const BaseWidget&) = delete; - BaseWidget& operator=(BaseWidget&&) = delete; - - protected: - const EntityHandle& CreateEntity(); - void DestroyEntity(Entity* entity); - virtual void Layout(); - - void InvalidateNode() override; - - Nz::Rectf GetScissorRect() const; - - virtual bool IsFocusable() const; - virtual void OnFocusLost(); - virtual void OnFocusReceived(); - virtual bool OnKeyPressed(const Nz::WindowEvent::KeyEvent& key); - virtual void OnKeyReleased(const Nz::WindowEvent::KeyEvent& key); - virtual void OnMouseEnter(); - virtual void OnMouseMoved(int x, int y, int deltaX, int deltaY); - virtual void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button); - virtual void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button); - virtual void OnMouseWheelMoved(int x, int y, float delta); - virtual void OnMouseExit(); - virtual void OnParentResized(const Nz::Vector2f& newSize); - virtual void OnTextEntered(char32_t character, bool repeated); - virtual void OnTextEdited(const std::array& characters, int length); - - inline void SetPreferredSize(const Nz::Vector2f& preferredSize); - - virtual void ShowChildren(bool show); - - private: - inline BaseWidget(); - - void DestroyChild(BaseWidget* widget); - void DestroyChildren(); - inline bool IsRegisteredToCanvas() const; - inline void NotifyParentResized(const Nz::Vector2f& newSize); - void RegisterToCanvas(); - inline void UpdateCanvasIndex(std::size_t index); - void UnregisterFromCanvas(); - void UpdatePositionAndSize(); - - struct WidgetEntity - { - EntityOwner handle; - bool isEnabled = true; - - NazaraSlot(Ndk::Entity, OnEntityDisabled, onDisabledSlot); - NazaraSlot(Ndk::Entity, OnEntityEnabled, onEnabledSlot); - }; - - static constexpr std::size_t InvalidCanvasIndex = std::numeric_limits::max(); - - std::size_t m_canvasIndex; - std::vector m_entities; - std::vector> m_children; - Canvas* m_canvas; - EntityOwner m_backgroundEntity; - WorldHandle m_world; - Nz::Color m_backgroundColor; - Nz::Rectf m_renderingRect; - Nz::SpriteRef m_backgroundSprite; - Nz::SystemCursor m_cursor; - Nz::Vector2f m_maximumSize; - Nz::Vector2f m_minimumSize; - Nz::Vector2f m_preferredSize; - Nz::Vector2f m_size; - BaseWidget* m_widgetParent; - bool m_visible; - }; -} - -#include - -#endif // NDK_BASEWIDGET_HPP diff --git a/SDK/include/NDK/BaseWidget.inl b/SDK/include/NDK/BaseWidget.inl deleted file mode 100644 index fc8e1f710..000000000 --- a/SDK/include/NDK/BaseWidget.inl +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - inline BaseWidget::BaseWidget() : - m_canvasIndex(InvalidCanvasIndex), - m_canvas(nullptr), - m_backgroundColor(Nz::Color(230, 230, 230, 255)), - m_renderingRect(-std::numeric_limits::infinity(), -std::numeric_limits::infinity(), std::numeric_limits::infinity(), std::numeric_limits::infinity()), - m_cursor(Nz::SystemCursor_Default), - m_maximumSize(std::numeric_limits::infinity()), - m_minimumSize(0.f), - m_preferredSize(-1), - m_size(50.f, 50.f), - m_widgetParent(nullptr), - m_visible(true) - { - } - - template - inline T* BaseWidget::Add(Args&&... args) - { - std::unique_ptr widget = std::make_unique(this, std::forward(args)...); - T* widgetPtr = widget.get(); - AddChild(std::move(widget)); - - return widgetPtr; - } - - inline void BaseWidget::AddChild(std::unique_ptr&& widget) - { - widget->Show(m_visible); - widget->SetParent(this); - m_children.emplace_back(std::move(widget)); - } - - inline void BaseWidget::Center() - { - NazaraAssert(m_widgetParent, "Widget has no parent"); - - Nz::Vector2f parentSize = m_widgetParent->GetSize(); - Nz::Vector2f mySize = GetSize(); - SetPosition((parentSize.x - mySize.x) / 2.f, (parentSize.y - mySize.y) / 2.f); - } - - inline void BaseWidget::CenterHorizontal() - { - NazaraAssert(m_widgetParent, "Widget has no parent"); - - Nz::Vector2f parentSize = m_widgetParent->GetSize(); - Nz::Vector2f mySize = GetSize(); - SetPosition((parentSize.x - mySize.x) / 2.f, GetPosition(Nz::CoordSys_Local).y); - } - - inline void BaseWidget::CenterVertical() - { - NazaraAssert(m_widgetParent, "Widget has no parent"); - - Nz::Vector2f parentSize = m_widgetParent->GetSize(); - Nz::Vector2f mySize = GetSize(); - SetPosition(GetPosition(Nz::CoordSys_Local).x, (parentSize.y - mySize.y) / 2.f); - } - - inline void BaseWidget::ClearRenderingRect() - { - SetRenderingRect(Nz::Rectf(-std::numeric_limits::infinity(), -std::numeric_limits::infinity(), std::numeric_limits::infinity(), std::numeric_limits::infinity())); - } - - template - inline void BaseWidget::ForEachWidgetChild(F iterator) - { - for (const auto& child : m_children) - iterator(child.get()); - } - - template - inline void BaseWidget::ForEachWidgetChild(F iterator) const - { - for (const auto& child : m_children) - iterator(static_cast(child.get())); - } - - inline const Nz::Color& BaseWidget::GetBackgroundColor() const - { - return m_backgroundColor; - } - - inline Canvas* BaseWidget::GetCanvas() - { - return m_canvas; - } - - inline Nz::SystemCursor BaseWidget::GetCursor() const - { - return m_cursor; - } - - inline float BaseWidget::GetHeight() const - { - return m_size.y; - } - - inline float BaseWidget::GetMaximumHeight() const - { - return m_maximumSize.y; - } - - inline Nz::Vector2f BaseWidget::GetMaximumSize() const - { - return m_maximumSize; - } - - inline float BaseWidget::GetMaximumWidth() const - { - return m_maximumSize.x; - } - - inline float BaseWidget::GetMinimumHeight() const - { - return m_minimumSize.y; - } - - inline Nz::Vector2f BaseWidget::GetMinimumSize() const - { - return m_minimumSize; - } - - inline float BaseWidget::GetMinimumWidth() const - { - return m_minimumSize.x; - } - - inline float BaseWidget::GetPreferredHeight() const - { - return m_preferredSize.y; - } - - inline Nz::Vector2f BaseWidget::GetPreferredSize() const - { - return m_preferredSize; - } - - inline float BaseWidget::GetPreferredWidth() const - { - return m_preferredSize.x; - } - - inline const Nz::Rectf& BaseWidget::GetRenderingRect() const - { - return m_renderingRect; - } - - inline Nz::Vector2f BaseWidget::GetSize() const - { - return Nz::Vector2f(GetWidth(), GetHeight()); - } - - inline float BaseWidget::GetWidth() const - { - return m_size.x; - } - - inline std::size_t BaseWidget::GetWidgetChildCount() const - { - return m_children.size(); - } - - inline void BaseWidget::Hide() - { - return Show(false); - } - - inline bool BaseWidget::IsVisible() const - { - return m_visible; - } - - inline void BaseWidget::SetFixedHeight(float fixedHeight) - { - SetMaximumHeight(fixedHeight); - SetMinimumHeight(fixedHeight); - } - - inline void BaseWidget::SetFixedSize(const Nz::Vector2f& fixedSize) - { - SetMaximumSize(fixedSize); - SetMinimumSize(fixedSize); - } - - inline void BaseWidget::SetFixedWidth(float fixedWidth) - { - SetMaximumWidth(fixedWidth); - SetMinimumWidth(fixedWidth); - } - - inline void BaseWidget::SetMaximumHeight(float maximumHeight) - { - Nz::Vector2f maximumSize = GetMaximumSize(); - maximumSize.y = maximumHeight; - - SetMaximumSize(maximumSize); - } - - inline void BaseWidget::SetMaximumSize(const Nz::Vector2f& maximumSize) - { - m_maximumSize = maximumSize; - - Nz::Vector2f size = GetSize(); - if (size.x > m_maximumSize.x || size.y > m_maximumSize.y) - Resize(size); //< Will clamp automatically - } - - inline void BaseWidget::SetMaximumWidth(float maximumWidth) - { - Nz::Vector2f maximumSize = GetMaximumSize(); - maximumSize.x = maximumWidth; - - SetMaximumSize(maximumSize); - } - - inline void BaseWidget::SetMinimumHeight(float minimumHeight) - { - Nz::Vector2f minimumSize = GetMinimumSize(); - minimumSize.y = minimumHeight; - - SetMinimumSize(minimumSize); - } - - inline void BaseWidget::SetMinimumSize(const Nz::Vector2f& minimumSize) - { - m_minimumSize = minimumSize; - - Nz::Vector2f size = GetSize(); - if (size.x < m_minimumSize.x || size.y < m_minimumSize.y) - Resize(size); //< Will clamp automatically - } - - inline void BaseWidget::SetMinimumWidth(float minimumWidth) - { - Nz::Vector2f minimumSize = GetMinimumSize(); - minimumSize.x = minimumWidth; - - SetMinimumSize(minimumSize); - } - - inline void BaseWidget::SetPreferredSize(const Nz::Vector2f& preferredSize) - { - m_preferredSize = preferredSize; - - //Resize(m_preferredSize); - } - - inline bool BaseWidget::IsRegisteredToCanvas() const - { - return m_canvas && m_canvasIndex != InvalidCanvasIndex; - } - - inline void BaseWidget::NotifyParentResized(const Nz::Vector2f& newSize) - { - for (const auto& widgetPtr : m_children) - widgetPtr->OnParentResized(newSize); - } - - inline void BaseWidget::UpdateCanvasIndex(std::size_t index) - { - m_canvasIndex = index; - } -} diff --git a/SDK/include/NDK/Canvas.hpp b/SDK/include/NDK/Canvas.hpp deleted file mode 100644 index e3f381b34..000000000 --- a/SDK/include/NDK/Canvas.hpp +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_CANVAS_HPP -#define NDK_CANVAS_HPP - -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API Canvas : public BaseWidget - { - friend BaseWidget; - - public: - struct Padding; - - inline Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController); - Canvas(const Canvas&) = delete; - Canvas(Canvas&&) = delete; - inline ~Canvas(); - - inline const WorldHandle& GetWorld() const; - - Canvas& operator=(const Canvas&) = delete; - Canvas& operator=(Canvas&&) = delete; - - NazaraSignal(OnUnhandledKeyPressed, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/); - NazaraSignal(OnUnhandledKeyReleased, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/); - - protected: - inline void ClearKeyboardOwner(std::size_t canvasIndex); - - inline bool IsKeyboardOwner(std::size_t canvasIndex) const; - - inline void NotifyWidgetBoxUpdate(std::size_t index); - inline void NotifyWidgetCursorUpdate(std::size_t index); - - std::size_t RegisterWidget(BaseWidget* widget); - - inline void SetKeyboardOwner(std::size_t canvasIndex); - - void UnregisterWidget(std::size_t index); - - private: - void OnEventMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); - void OnEventMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event); - void OnEventMouseLeft(const Nz::EventHandler* eventHandler); - void OnEventMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event); - void OnEventMouseWheelMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseWheelEvent& event); - void OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); - void OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event); - void OnEventTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event); - void OnEventTextEdited(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::EditEvent& event); - - struct WidgetEntry - { - BaseWidget* widget; - Nz::Boxf box; - Nz::SystemCursor cursor; - }; - - NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot); - NazaraSlot(Nz::EventHandler, OnKeyReleased, m_keyReleasedSlot); - NazaraSlot(Nz::EventHandler, OnMouseButtonPressed, m_mouseButtonPressedSlot); - NazaraSlot(Nz::EventHandler, OnMouseButtonReleased, m_mouseButtonReleasedSlot); - NazaraSlot(Nz::EventHandler, OnMouseLeft, m_mouseLeftSlot); - NazaraSlot(Nz::EventHandler, OnMouseMoved, m_mouseMovedSlot); - NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_mouseWheelMovedSlot); - NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot); - NazaraSlot(Nz::EventHandler, OnTextEdited, m_textEditedSlot); - - std::size_t m_keyboardOwner; - std::size_t m_hoveredWidget; - std::vector m_widgetEntries; - Nz::CursorControllerHandle m_cursorController; - WorldHandle m_world; - }; -} - -#include - -#endif // NDK_CANVAS_HPP diff --git a/SDK/include/NDK/Canvas.inl b/SDK/include/NDK/Canvas.inl deleted file mode 100644 index d36acbf0e..000000000 --- a/SDK/include/NDK/Canvas.inl +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - inline Canvas::Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController) : - m_keyboardOwner(InvalidCanvasIndex), - m_hoveredWidget(InvalidCanvasIndex), - m_cursorController(cursorController), - m_world(std::move(world)) - { - m_canvas = this; - m_widgetParent = nullptr; - - // Register ourselves as a widget to handle cursor change - RegisterToCanvas(); - - // Connect to every meaningful event - m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed); - m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased); - m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed); - m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease); - m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft); - m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved); - m_mouseWheelMovedSlot.Connect(eventHandler.OnMouseWheelMoved, this, &Canvas::OnEventMouseWheelMoved); - m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered); - m_textEditedSlot.Connect(eventHandler.OnTextEdited, this, &Canvas::OnEventTextEdited); - } - - inline Canvas::~Canvas() - { - // Destroy children explicitly because they signal us when getting destroyed, and that can't happen after our own destruction - DestroyChildren(); - - // Prevent our parent from trying to call us - m_canvasIndex = InvalidCanvasIndex; - } - - inline const WorldHandle& Canvas::GetWorld() const - { - return m_world; - } - - inline void Canvas::ClearKeyboardOwner(std::size_t canvasIndex) - { - if (m_keyboardOwner == canvasIndex) - SetKeyboardOwner(InvalidCanvasIndex); - } - - inline bool Canvas::IsKeyboardOwner(std::size_t canvasIndex) const - { - return m_keyboardOwner == canvasIndex; - } - - inline void Canvas::NotifyWidgetBoxUpdate(std::size_t index) - { - WidgetEntry& entry = m_widgetEntries[index]; - - Nz::Vector3f pos = entry.widget->GetPosition(Nz::CoordSys_Global); - Nz::Vector2f size = entry.widget->GetSize(); - - entry.box.Set(pos.x, pos.y, pos.z, size.x, size.y, 1.f); - } - - inline void Canvas::NotifyWidgetCursorUpdate(std::size_t index) - { - WidgetEntry& entry = m_widgetEntries[index]; - - entry.cursor = entry.widget->GetCursor(); - if (m_cursorController && m_hoveredWidget == index) - m_cursorController->UpdateCursor(Nz::Cursor::Get(entry.cursor)); - } - - inline void Canvas::SetKeyboardOwner(std::size_t canvasIndex) - { - if (m_keyboardOwner != canvasIndex) - { - if (m_keyboardOwner != InvalidCanvasIndex) - m_widgetEntries[m_keyboardOwner].widget->OnFocusLost(); - - m_keyboardOwner = canvasIndex; - - if (m_keyboardOwner != InvalidCanvasIndex) - m_widgetEntries[m_keyboardOwner].widget->OnFocusReceived(); - } - } -} diff --git a/SDK/include/NDK/Components.hpp b/SDK/include/NDK/Components.hpp deleted file mode 100644 index cc8c37d93..000000000 --- a/SDK/include/NDK/Components.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// This file was automatically generated - -#pragma once - -#ifndef NDK_COMPONENTS_GLOBAL_HPP -#define NDK_COMPONENTS_GLOBAL_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif // NDK_COMPONENTS_GLOBAL_HPP diff --git a/SDK/include/NDK/Components/CameraComponent.hpp b/SDK/include/NDK/Components/CameraComponent.hpp deleted file mode 100644 index cf835704a..000000000 --- a/SDK/include/NDK/Components/CameraComponent.hpp +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_CAMERACOMPONENT_HPP -#define NDK_COMPONENTS_CAMERACOMPONENT_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class CameraComponent; - - using CameraComponentHandle = Nz::ObjectHandle; - - class NDK_API CameraComponent : public Component, public Nz::AbstractViewer - { - public: - inline CameraComponent(); - inline CameraComponent(const CameraComponent& camera); - ~CameraComponent() = default; - - void ApplyView() const override; - - inline void EnsureFrustumUpdate() const; - inline void EnsureProjectionMatrixUpdate() const; - inline void EnsureViewMatrixUpdate() const; - inline void EnsureViewportUpdate() const; - - float GetAspectRatio() const override; - Nz::Vector3f GetEyePosition() const override; - Nz::Vector3f GetForward() const override; - inline float GetFOV() const; - const Nz::Frustumf& GetFrustum() const override; - inline unsigned int GetLayer() const; - const Nz::Matrix4f& GetProjectionMatrix() const override; - inline const Nz::Vector3f& GetProjectionScale() const; - Nz::ProjectionType GetProjectionType() const override; - inline const Nz::Vector2f& GetSize() const; - const Nz::RenderTarget* GetTarget() const override; - inline const Nz::Rectf& GetTargetRegion() const; - const Nz::Matrix4f& GetViewMatrix() const override; - const Nz::Recti& GetViewport() const override; - float GetZFar() const override; - float GetZNear() const override; - - inline void SetFOV(float fov); - void SetLayer(unsigned int layer); - inline void SetProjectionScale(const Nz::Vector3f& scale); - inline void SetProjectionType(Nz::ProjectionType projection); - inline void SetSize(const Nz::Vector2f& size); - inline void SetSize(float width, float height); - inline void SetTarget(const Nz::RenderTarget* renderTarget); - inline void SetTargetRegion(const Nz::Rectf& region); - inline void SetViewport(const Nz::Recti& viewport); - inline void SetZFar(float zFar); - inline void SetZNear(float zNear); - - inline bool UpdateVisibility(std::size_t visibilityHash); - - static ComponentIndex componentIndex; - - private: - inline void InvalidateFrustum() const; - inline void InvalidateProjectionMatrix() const; - inline void InvalidateViewMatrix() const; - inline void InvalidateViewport() const; - - void OnAttached() override; - void OnComponentAttached(BaseComponent& component) override; - void OnComponentDetached(BaseComponent& component) override; - void OnDetached() override; - void OnNodeInvalidated(const Nz::Node* node); - void OnRenderTargetRelease(const Nz::RenderTarget* renderTarget); - void OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget); - - void UpdateFrustum() const; - void UpdateProjectionMatrix() const; - void UpdateViewMatrix() const; - void UpdateViewport() const; - - NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot); - NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot); - NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot); - - std::size_t m_visibilityHash; - Nz::ProjectionType m_projectionType; - mutable Nz::Frustumf m_frustum; - mutable Nz::Matrix4f m_projectionMatrix; - mutable Nz::Matrix4f m_viewMatrix; - Nz::Rectf m_targetRegion; - mutable Nz::Recti m_viewport; - const Nz::RenderTarget* m_target; - Nz::Vector2f m_size; - Nz::Vector3f m_projectionScale; - mutable bool m_frustumUpdated; - mutable bool m_projectionMatrixUpdated; - mutable bool m_viewMatrixUpdated; - mutable bool m_viewportUpdated; - mutable float m_aspectRatio; - float m_fov; - float m_zFar; - float m_zNear; - unsigned int m_layer; - }; -} - -#include - -#endif // NDK_COMPONENTS_CAMERACOMPONENT_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/CameraComponent.inl b/SDK/include/NDK/Components/CameraComponent.inl deleted file mode 100644 index e059a68b1..000000000 --- a/SDK/include/NDK/Components/CameraComponent.inl +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - /*! - * \brief Constructs an CameraComponent object by default - */ - - inline CameraComponent::CameraComponent() : - m_visibilityHash(0U), - m_projectionType(Nz::ProjectionType_Perspective), - m_targetRegion(0.f, 0.f, 1.f, 1.f), - m_target(nullptr), - m_size(0.f), - m_projectionScale(1.f, 1.f, 1.f), - m_frustumUpdated(false), - m_projectionMatrixUpdated(false), - m_viewMatrixUpdated(false), - m_viewportUpdated(false), - m_aspectRatio(0.f), - m_fov(70.f), - m_zFar(100.f), - m_zNear(1.f), - m_layer(0) - { - } - - /*! - * \brief Constructs a CameraComponent object by copy semantic - * - * \param camera CameraComponent to copy - */ - - inline CameraComponent::CameraComponent(const CameraComponent& camera) : - Component(camera), - AbstractViewer(camera), - m_visibilityHash(camera.m_visibilityHash), - m_projectionType(camera.m_projectionType), - m_targetRegion(camera.m_targetRegion), - m_target(nullptr), - m_size(camera.m_size), - m_projectionScale(camera.m_projectionScale), - m_frustumUpdated(false), - m_projectionMatrixUpdated(false), - m_viewMatrixUpdated(false), - m_viewportUpdated(false), - m_aspectRatio(camera.m_aspectRatio), - m_fov(camera.m_fov), - m_zFar(camera.m_zFar), - m_zNear(camera.m_zNear), - m_layer(camera.m_layer) - { - SetTarget(camera.m_target); - } - - /*! - * \brief Ensures the frustum is up to date - */ - - inline void CameraComponent::EnsureFrustumUpdate() const - { - if (!m_frustumUpdated) - UpdateFrustum(); - } - - /*! - * \brief Ensures the projection matrix is up to date - */ - - inline void CameraComponent::EnsureProjectionMatrixUpdate() const - { - if (!m_projectionMatrixUpdated) - UpdateProjectionMatrix(); - } - - /*! - * \brief Ensures the view matrix is up to date - */ - - inline void CameraComponent::EnsureViewMatrixUpdate() const - { - if (!m_viewMatrixUpdated) - UpdateViewMatrix(); - } - - /*! - * \brief Ensures the view port is up to date - */ - - inline void CameraComponent::EnsureViewportUpdate() const - { - if (!m_viewportUpdated) - UpdateViewport(); - } - - /*! - * \brief Gets the field of view of the camera - * \return Field of view of the camera - */ - inline float CameraComponent::GetFOV() const - { - return m_fov; - } - - /*! - * \brief Gets the layer of the camera - * \return Layer of the camera - */ - - inline unsigned int CameraComponent::GetLayer() const - { - return m_layer; - } - - /*! - * \brief Gets the projection scale of the camera - * \return Projection scale - */ - const Nz::Vector3f& CameraComponent::GetProjectionScale() const - { - return m_projectionScale; - } - - /*! - * \brief Gets the size of the camera - * \return Size of the camera - */ - inline const Nz::Vector2f & CameraComponent::GetSize() const - { - return m_size; - } - - /*! - * \brief Gets the target region of the camera - * \return A constant reference to the target region of the camera - */ - - inline const Nz::Rectf& CameraComponent::GetTargetRegion() const - { - return m_targetRegion; - } - - /*! - * \brief Sets the field of view of the camera - * - * \param fov Field of view of the camera - * - * \remark Produces a NazaraAssert if angle is zero - */ - - inline void CameraComponent::SetFOV(float fov) - { - NazaraAssert(!Nz::NumberEquals(fov, 0.f), "FOV must be different from zero"); - m_fov = fov; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Sets the camera projection scale - * - * \param scale New projection scale - */ - inline void CameraComponent::SetProjectionScale(const Nz::Vector3f& scale) - { - m_projectionScale = scale; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Sets the projection type of the camera - * - * \param projectionType Projection type of the camera - */ - inline void CameraComponent::SetProjectionType(Nz::ProjectionType projectionType) - { - m_projectionType = projectionType; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Sets the size of the camera - * - * \param size Size of the camera - */ - - inline void CameraComponent::SetSize(const Nz::Vector2f& size) - { - m_size = size; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Sets the size of the camera - * - * \param width Size in X of the camera - * \param height Size in Y of the camera - */ - - inline void CameraComponent::SetSize(float width, float height) - { - SetSize({width, height}); - } - - /*! - * \brief Sets the target of the camera - * - * \param renderTarget A constant reference to the render target of the camera - */ - - inline void CameraComponent::SetTarget(const Nz::RenderTarget* renderTarget) - { - m_target = renderTarget; - if (m_target) - { - m_targetResizeSlot.Connect(m_target->OnRenderTargetSizeChange, this, &CameraComponent::OnRenderTargetSizeChange); - m_targetReleaseSlot.Connect(m_target->OnRenderTargetRelease, this, &CameraComponent::OnRenderTargetRelease); - } - else - { - m_targetResizeSlot.Disconnect(); - m_targetReleaseSlot.Disconnect(); - } - } - - /*! - * \brief Sets the target region of the camera - * - * \param region A constant reference to the target region of the camera - */ - - inline void CameraComponent::SetTargetRegion(const Nz::Rectf& region) - { - m_targetRegion = region; - - InvalidateViewport(); - } - - /*! - * \brief Sets the view port of the camera - * - * \param viewport A constant reference to the view port of the camera - * - * \remark Produces a NazaraAssert if the camera has no target - */ - - inline void CameraComponent::SetViewport(const Nz::Recti& viewport) - { - NazaraAssert(m_target, "Component has no render target"); - - // We compute the region necessary to make this view port with the actual size of the target - Nz::Vector2f invSize = 1.f / Nz::Vector2f(m_target->GetSize()); - - SetTargetRegion(Nz::Rectf(invSize.x * viewport.x, invSize.y * viewport.y, invSize.x * viewport.width, invSize.y * viewport.height)); - } - - /*! - * \brief Sets the Z far distance of the camera - * - * \param zFar Z far distance of the camera - */ - - inline void CameraComponent::SetZFar(float zFar) - { - m_zFar = zFar; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Sets the Z near distance of the camera - * - * \param zNear Z near distance of the camera - * - * \remark Produces a NazaraAssert if zNear is zero - */ - - inline void CameraComponent::SetZNear(float zNear) - { - NazaraAssert(!Nz::NumberEquals(zNear, 0.f), "zNear cannot be zero"); - m_zNear = zNear; - - InvalidateProjectionMatrix(); - } - - /*! - * \brief Update the camera component visibility hash - * - * This is used with CullingList (which produce a visibility hash) - * - * \param visibilityHash New visibility hash - * - * \return True if the visibility hash is not the same as before - */ - inline bool CameraComponent::UpdateVisibility(std::size_t visibilityHash) - { - if (m_visibilityHash != visibilityHash) - { - m_visibilityHash = visibilityHash; - return true; - } - - return false; - } - - /*! - * \brief Invalidates the frustum - */ - - inline void CameraComponent::InvalidateFrustum() const - { - m_frustumUpdated = false; - } - - /*! - * \brief Invalidates the projection matrix - */ - - inline void CameraComponent::InvalidateProjectionMatrix() const - { - m_frustumUpdated = false; - m_projectionMatrixUpdated = false; - } - - /*! - * \brief Invalidates the view matrix - */ - - inline void CameraComponent::InvalidateViewMatrix() const - { - m_frustumUpdated = false; - m_viewMatrixUpdated = false; - } - - /*! - * \brief Invalidates the view port - */ - - inline void CameraComponent::InvalidateViewport() const - { - m_frustumUpdated = false; - m_projectionMatrixUpdated = false; - m_viewportUpdated = false; - } -} diff --git a/SDK/include/NDK/Components/DebugComponent.hpp b/SDK/include/NDK/Components/DebugComponent.hpp deleted file mode 100644 index e0993d26d..000000000 --- a/SDK/include/NDK/Components/DebugComponent.hpp +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_DEBUGCOMPONENT_HPP -#define NDK_COMPONENTS_DEBUGCOMPONENT_HPP - -#include -#include -#include - -namespace Ndk -{ - enum class DebugDraw - { - Collider2D, - Collider3D, - GraphicsAABB, - GraphicsOBB, - - Max = GraphicsOBB - }; -} - -namespace Nz -{ - template<> - struct EnumAsFlags - { - static constexpr Ndk::DebugDraw max = Ndk::DebugDraw::GraphicsOBB; - }; -} - -namespace Ndk -{ - using DebugDrawFlags = Nz::Flags; - - constexpr DebugDrawFlags DebugDraw_None = 0; - - class DebugComponent; - class GraphicsComponent; - - using DebugComponentHandle = Nz::ObjectHandle; - - class NDK_API DebugComponent : public Component - { - friend class DebugSystem; - - public: - inline DebugComponent(DebugDrawFlags flags = DebugDraw_None); - inline DebugComponent(const DebugComponent& debug); - ~DebugComponent() = default; - - inline void Disable(DebugDrawFlags flags); - inline void Enable(DebugDrawFlags flags); - - inline DebugDrawFlags GetFlags() const; - - inline bool IsEnabled(DebugDrawFlags flags) const; - - inline DebugComponent& operator=(const DebugComponent& debug); - - static ComponentIndex componentIndex; - - private: - void DetachDebugRenderables(GraphicsComponent& gfxComponent); - - inline const Nz::InstancedRenderableRef& GetDebugRenderable(DebugDraw option) const; - inline DebugDrawFlags GetEnabledFlags() const; - - void OnComponentDetached(BaseComponent& component) override; - void OnDetached() override; - - inline void UpdateDebugRenderable(DebugDraw option, Nz::InstancedRenderableRef renderable); - inline void UpdateEnabledFlags(DebugDrawFlags flags); - - static constexpr std::size_t DebugModeCount = static_cast(DebugDraw::Max) + 1; - - std::array m_debugRenderables; - DebugDrawFlags m_enabledFlags; - DebugDrawFlags m_flags; - }; -} - -#include - -#endif // NDK_COMPONENTS_DEBUGCOMPONENT_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/DebugComponent.inl b/SDK/include/NDK/Components/DebugComponent.inl deleted file mode 100644 index e0f42a560..000000000 --- a/SDK/include/NDK/Components/DebugComponent.inl +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline DebugComponent::DebugComponent(DebugDrawFlags flags) : - m_flags(flags) - { - } - - inline DebugComponent::DebugComponent(const DebugComponent& debug) : - m_flags(debug.m_flags) - { - } - - inline void DebugComponent::Disable(DebugDrawFlags flags) - { - m_flags &= ~flags; - - if (m_entity) - m_entity->Invalidate(); - } - - inline void DebugComponent::Enable(DebugDrawFlags flags) - { - m_flags |= flags; - - if (m_entity) - m_entity->Invalidate(); - } - - inline DebugDrawFlags DebugComponent::GetFlags() const - { - return m_flags; - } - - inline bool DebugComponent::IsEnabled(DebugDrawFlags flags) const - { - return (m_flags & flags) == flags; - } - - inline DebugComponent& DebugComponent::operator=(const DebugComponent& debug) - { - m_flags = debug.m_flags; - - if (m_entity) - m_entity->Invalidate(); - - return *this; - } - - inline const Nz::InstancedRenderableRef& DebugComponent::GetDebugRenderable(DebugDraw option) const - { - return m_debugRenderables[static_cast(option)]; - } - - inline DebugDrawFlags DebugComponent::GetEnabledFlags() const - { - return m_enabledFlags; - } - - inline void DebugComponent::UpdateDebugRenderable(DebugDraw option, Nz::InstancedRenderableRef renderable) - { - m_debugRenderables[static_cast(option)] = std::move(renderable); - } - - inline void DebugComponent::UpdateEnabledFlags(DebugDrawFlags flags) - { - m_enabledFlags = flags; - } -} diff --git a/SDK/include/NDK/Components/GraphicsComponent.hpp b/SDK/include/NDK/Components/GraphicsComponent.hpp deleted file mode 100644 index e7780f3e0..000000000 --- a/SDK/include/NDK/Components/GraphicsComponent.hpp +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP -#define NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class GraphicsComponent; - - using GraphicsComponentCullingList = Nz::CullingList; - using GraphicsComponentHandle = Nz::ObjectHandle; - - class NDK_API GraphicsComponent : public Component - { - friend class RenderSystem; - - public: - using RenderableList = std::vector; - - inline GraphicsComponent(); - inline GraphicsComponent(const GraphicsComponent& graphicsComponent); - ~GraphicsComponent() = default; - - inline void AddToCullingList(GraphicsComponentCullingList* cullingList) const; - void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const; - void AddToRenderQueueByCulling(const Nz::Frustumf& frustum, Nz::AbstractRenderQueue* renderQueue) const; - - inline void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); - void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); - - inline void Clear(); - - inline void Detach(const Nz::InstancedRenderable* renderable); - - inline bool DoesRequireRealTimeReflections() const; - - inline void EnsureBoundingVolumesUpdate() const; - inline void EnsureTransformMatrixUpdate() const; - - template void ForEachRenderable(const Func& func) const; - - inline const Nz::Boxf& GetAABB() const; - - inline void GetAttachedRenderables(RenderableList* renderables) const; - inline std::size_t GetAttachedRenderableCount() const; - - inline const Nz::BoundingVolumef& GetBoundingVolume(std::size_t renderableIndex) const; - inline const Nz::Matrix4f& GetLocalMatrix(std::size_t renderableIndex) const; - inline const Nz::Matrix4f& GetTransformMatrix(std::size_t renderableIndex) const; - - inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const; - - inline void SetScissorRect(const Nz::Recti& scissorRect); - - inline void UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix); - inline void UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder); - - static ComponentIndex componentIndex; - - private: - struct Renderable; - - void ConnectInstancedRenderableSignals(Renderable& renderable); - - inline void ForceCullingInvalidation(); - inline void InvalidateAABB() const; - void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, std::size_t index); - void InvalidateRenderableMaterial(const Nz::InstancedRenderable* renderable, std::size_t skinIndex, std::size_t matIndex, const Nz::MaterialRef& newMat); - inline void InvalidateRenderables(); - void InvalidateReflectionMap(); - inline void InvalidateTransformMatrix(); - - void RegisterMaterial(Nz::Material* material, std::size_t count = 1); - - void OnAttached() override; - void OnComponentAttached(BaseComponent& component) override; - void OnComponentDetached(BaseComponent& component) override; - void OnDetached() override; - - void OnInstancedRenderableResetMaterials(const Nz::InstancedRenderable* renderable, std::size_t newMaterialCount); - void OnInstancedRenderableSkinChange(const Nz::InstancedRenderable* renderable, std::size_t newSkinIndex); - void OnMaterialReflectionChange(const Nz::Material* material, Nz::ReflectionMode reflectionMode); - void OnNodeInvalidated(const Nz::Node* node); - - void UnregisterMaterial(Nz::Material* material); - - void UpdateBoundingVolumes() const; - void UpdateTransformMatrix() const; - - NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot); - - using CullingListBoxEntry = GraphicsComponentCullingList::BoxEntry; - - struct CullingBoxEntry - { - CullingListBoxEntry listEntry; - - NazaraSlot(GraphicsComponentCullingList, OnCullingListRelease, cullingListReleaseSlot); - }; - - struct MaterialEntry - { - NazaraSlot(Nz::Material, OnMaterialReflectionModeChange, reflectionModelChangeSlot); - - std::size_t renderableCounter; - }; - - struct Renderable - { - Renderable(const Nz::Matrix4f& transformMatrix) : - data(transformMatrix), - dataUpdated(false) - { - } - - Renderable(const Renderable&) = delete; - Renderable(Renderable&& rhs) noexcept = default; - - ~Renderable() - { - // Disconnect release slot before releasing instanced renderable reference - renderableReleaseSlot.Disconnect(); - } - - Renderable& operator=(const Renderable&) = delete; - Renderable& operator=(Renderable&& r) noexcept = default; - - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateBoundingVolume, renderableBoundingVolumeInvalidationSlot); - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableDataInvalidationSlot); - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateMaterial, renderableMaterialInvalidationSlot); - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableRelease, renderableReleaseSlot); - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableResetMaterials, renderableResetMaterialsSlot); - NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableSkinChange, renderableSkinChangeSlot); - - mutable Nz::BoundingVolumef boundingVolume; - mutable Nz::InstancedRenderable::InstanceData data; - Nz::InstancedRenderableRef renderable; - mutable bool dataUpdated; - }; - - std::size_t m_reflectiveMaterialCount; - mutable std::vector m_cullingBoxEntries; - std::vector m_renderables; - std::unordered_map m_materialEntries; - mutable Nz::Boxf m_aabb; - mutable Nz::Matrix4f m_transformMatrix; - Nz::Recti m_scissorRect; - Nz::TextureRef m_reflectionMap; - mutable bool m_boundingVolumesUpdated; - mutable bool m_transformMatrixUpdated; - unsigned int m_reflectionMapSize; - }; -} - -#include - -#endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/GraphicsComponent.inl b/SDK/include/NDK/Components/GraphicsComponent.inl deleted file mode 100644 index 37bbd1049..000000000 --- a/SDK/include/NDK/Components/GraphicsComponent.inl +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - inline GraphicsComponent::GraphicsComponent() : - m_reflectiveMaterialCount(0), - m_scissorRect(-1, -1) - { - } - - /*! - * \brief Constructs a GraphicsComponent object by copy semantic - * - * \param graphicsComponent GraphicsComponent to copy - */ - inline GraphicsComponent::GraphicsComponent(const GraphicsComponent& graphicsComponent) : - Component(graphicsComponent), - m_reflectiveMaterialCount(0), - m_aabb(graphicsComponent.m_aabb), - m_transformMatrix(graphicsComponent.m_transformMatrix), - m_scissorRect(graphicsComponent.m_scissorRect), - m_boundingVolumesUpdated(graphicsComponent.m_boundingVolumesUpdated), - m_transformMatrixUpdated(graphicsComponent.m_transformMatrixUpdated) - { - m_renderables.reserve(graphicsComponent.m_renderables.size()); - for (const Renderable& r : graphicsComponent.m_renderables) - Attach(r.renderable, r.data.localMatrix, r.data.renderOrder); - } - - inline void GraphicsComponent::AddToCullingList(GraphicsComponentCullingList* cullingList) const - { - m_cullingBoxEntries.emplace_back(); - CullingBoxEntry& entry = m_cullingBoxEntries.back(); - entry.cullingListReleaseSlot.Connect(cullingList->OnCullingListRelease, this, &GraphicsComponent::RemoveFromCullingList); - entry.listEntry = cullingList->RegisterBoxTest(this); - - InvalidateAABB(); - } - - /*! - * \brief Attaches a renderable to the entity - * - * \param renderable Reference to a renderable element - * \param renderOrder Render order of the element - */ - inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder) - { - return Attach(std::move(renderable), Nz::Matrix4f::Identity(), renderOrder); - } - - /*! - * \brief Clears every renderable elements - */ - - inline void GraphicsComponent::Clear() - { - m_materialEntries.clear(); - m_renderables.clear(); - - if (m_reflectiveMaterialCount > 0) - { - m_reflectiveMaterialCount = 0; - InvalidateReflectionMap(); - } - - InvalidateAABB(); - } - - /*! - * \brief Detaches a renderable to the entity - * - * \param renderable Reference to a renderable element - */ - - inline void GraphicsComponent::Detach(const Nz::InstancedRenderable* renderable) - { - for (auto it = m_renderables.begin(); it != m_renderables.end(); ++it) - { - if (it->renderable == renderable) - { - InvalidateAABB(); - - std::size_t materialCount = renderable->GetMaterialCount(); - for (std::size_t i = 0; i < materialCount; ++i) - UnregisterMaterial(renderable->GetMaterial(i)); - - m_renderables.erase(it); - - ForceCullingInvalidation(); - break; - } - } - } - - /*! - * \brief Checks if this graphics component requires real-time reflections to be generated - * - * If any of the materials attached to a GraphicsComponent (via the attached instanced renderable) needs real-time reflections, this function will return true. - * - * \return True if real-time reflections needs to be generated or false - */ - inline bool GraphicsComponent::DoesRequireRealTimeReflections() const - { - return m_reflectiveMaterialCount != 0 && m_reflectionMap; - } - - /*! - * \brief Ensures the bounding volume is up to date - */ - - inline void GraphicsComponent::EnsureBoundingVolumesUpdate() const - { - if (!m_boundingVolumesUpdated) - UpdateBoundingVolumes(); - } - - /*! - * \brief Ensures the transformation matrix is up to date - */ - - inline void GraphicsComponent::EnsureTransformMatrixUpdate() const - { - if (!m_transformMatrixUpdated) - UpdateTransformMatrix(); - } - - /*! - * \brief Gets the axis-aligned bounding box of the entity - * \return A constant reference to the AABB - */ - inline const Nz::Boxf& GraphicsComponent::GetAABB() const - { - EnsureBoundingVolumesUpdate(); - - return m_aabb; - } - - /*! - * \brief Gets the set of renderable elements - * - * \param renderables Pointer to the list of renderables - * - * \remark Produces a NazaraAssert if renderables is invalid - */ - - inline void GraphicsComponent::GetAttachedRenderables(RenderableList* renderables) const - { - NazaraAssert(renderables, "Invalid renderable list"); - - renderables->reserve(renderables->size() + m_renderables.size()); - for (const Renderable& r : m_renderables) - renderables->push_back(r.renderable); - } - - /*! - * \brief Gets the number of renderable elements attached to the entity - * \return Number of renderable elements - */ - - inline std::size_t GraphicsComponent::GetAttachedRenderableCount() const - { - return m_renderables.size(); - } - - inline const Nz::BoundingVolumef& GraphicsComponent::GetBoundingVolume(std::size_t renderableIndex) const - { - EnsureBoundingVolumesUpdate(); - - assert(renderableIndex < m_renderables.size()); - return m_renderables[renderableIndex].boundingVolume; - } - - inline const Nz::Matrix4f& GraphicsComponent::GetLocalMatrix(std::size_t renderableIndex) const - { - assert(renderableIndex < m_renderables.size()); - return m_renderables[renderableIndex].data.localMatrix; - } - - inline const Nz::Matrix4f& GraphicsComponent::GetTransformMatrix(std::size_t renderableIndex) const - { - EnsureBoundingVolumesUpdate(); - - assert(renderableIndex < m_renderables.size()); - return m_renderables[renderableIndex].data.transformMatrix; - } - - /*! - * \brief Calls a function for every renderable attached to this component - * - * \param func Callback function which will be called with renderable data - */ - template - void GraphicsComponent::ForEachRenderable(const Func& func) const - { - for (const auto& renderableData : m_renderables) - func(renderableData.renderable, renderableData.data.localMatrix, renderableData.data.renderOrder); - } - - inline void GraphicsComponent::RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const - { - for (auto it = m_cullingBoxEntries.begin(); it != m_cullingBoxEntries.end(); ++it) - { - if (it->listEntry.GetParent() == cullingList) - { - if (m_cullingBoxEntries.size() > 1) - *it = std::move(m_cullingBoxEntries.back()); - - m_cullingBoxEntries.pop_back(); - break; - } - } - } - - inline void GraphicsComponent::SetScissorRect(const Nz::Recti& scissorRect) - { - m_scissorRect = scissorRect; - - for (CullingBoxEntry& entry : m_cullingBoxEntries) - entry.listEntry.ForceInvalidation(); //< Invalidate render queues - } - - inline void GraphicsComponent::UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix) - { - for (auto& renderable : m_renderables) - { - if (renderable.renderable == instancedRenderable) - { - renderable.data.localMatrix = localMatrix; - - InvalidateAABB(); - break; - } - } - } - - inline void GraphicsComponent::UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder) - { - for (auto& renderable : m_renderables) - { - if (renderable.renderable == instancedRenderable) - { - renderable.data.renderOrder = renderOrder; - break; - } - } - } - - /*! - * \brief Invalidates the bounding volume - */ - - inline void GraphicsComponent::ForceCullingInvalidation() - { - for (CullingBoxEntry& entry : m_cullingBoxEntries) - entry.listEntry.ForceInvalidation(); //< Invalidate render queues - } - - inline void GraphicsComponent::InvalidateAABB() const - { - m_boundingVolumesUpdated = false; - } - - /*! - * \brief Invalidates every renderable elements - */ - - inline void GraphicsComponent::InvalidateRenderables() - { - for (Renderable& r : m_renderables) - r.dataUpdated = false; - } - - /*! - * \brief Invalidates the transformation matrix - */ - - inline void GraphicsComponent::InvalidateTransformMatrix() - { - m_transformMatrixUpdated = false; - - InvalidateAABB(); - InvalidateRenderables(); - } -} diff --git a/SDK/include/NDK/Components/LightComponent.hpp b/SDK/include/NDK/Components/LightComponent.hpp deleted file mode 100644 index 50a9699be..000000000 --- a/SDK/include/NDK/Components/LightComponent.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_LIGHTCOMPONENT_HPP -#define NDK_COMPONENTS_LIGHTCOMPONENT_HPP - -#include -#include - -namespace Ndk -{ - class LightComponent; - - using LightComponentHandle = Nz::ObjectHandle; - - class NDK_API LightComponent : public Component, public Nz::Light - { - public: - inline LightComponent(Nz::LightType lightType = Nz::LightType_Point); - LightComponent(const LightComponent& light) = default; - ~LightComponent() = default; - - static ComponentIndex componentIndex; - }; -} - -#include - -#endif // NDK_COMPONENTS_LIGHTCOMPONENT_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/LightComponent.inl b/SDK/include/NDK/Components/LightComponent.inl deleted file mode 100644 index 7ddb5d788..000000000 --- a/SDK/include/NDK/Components/LightComponent.inl +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - /*! - * \brief Constructs an LightComponent object with a light type - */ - - inline LightComponent::LightComponent(Nz::LightType lightType) : - Nz::Light(lightType) - { - } -} diff --git a/SDK/include/NDK/Components/ParticleEmitterComponent.hpp b/SDK/include/NDK/Components/ParticleEmitterComponent.hpp deleted file mode 100644 index 0c7497a3b..000000000 --- a/SDK/include/NDK/Components/ParticleEmitterComponent.hpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP -#define NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP - -#include -#include - -namespace Ndk -{ - class ParticleEmitterComponent; - - using ParticleEmitterComponentHandle = Nz::ObjectHandle; - - class NDK_API ParticleEmitterComponent : public Component, public Nz::ParticleEmitter - { - public: - using SetupFunc = std::function; - - inline ParticleEmitterComponent(); - ParticleEmitterComponent(const ParticleEmitterComponent& emitter) = default; - ParticleEmitterComponent(ParticleEmitterComponent&& emitter) = default; - ~ParticleEmitterComponent() = default; - - inline void Enable(bool active = true); - - inline bool IsActive() const; - - inline void SetSetupFunc(SetupFunc func); - - static ComponentIndex componentIndex; - - private: - void SetupParticles(Nz::ParticleMapper& mapper, unsigned int count) const override; - - SetupFunc m_setupFunc; - bool m_isActive; - }; -} - -#include - -#endif // NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP -#endif // NDK_SERVER \ No newline at end of file diff --git a/SDK/include/NDK/Components/ParticleEmitterComponent.inl b/SDK/include/NDK/Components/ParticleEmitterComponent.inl deleted file mode 100644 index dd60f1a88..000000000 --- a/SDK/include/NDK/Components/ParticleEmitterComponent.inl +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - /*! - * \brief Constructs an ParticleEmitterComponent object by default - */ - - inline ParticleEmitterComponent::ParticleEmitterComponent() : - m_isActive(true) - { - } - - /*! - * \brief Enables the emission of particles - * - * \param active Should the emitter be active - */ - - inline void Ndk::ParticleEmitterComponent::Enable(bool active) - { - m_isActive = active; - } - - /*! - * \brief Checks whether the emission of particles is activated - * \param true If it is the case - */ - - inline bool ParticleEmitterComponent::IsActive() const - { - return m_isActive; - } - - /*! - * \brief Sets the function use for setting up particles - * - * \param func Function to set up particles - */ - - inline void Ndk::ParticleEmitterComponent::SetSetupFunc(SetupFunc func) - { - m_setupFunc = std::move(func); - } -} diff --git a/SDK/include/NDK/Components/ParticleGroupComponent.hpp b/SDK/include/NDK/Components/ParticleGroupComponent.hpp deleted file mode 100644 index 9415b8547..000000000 --- a/SDK/include/NDK/Components/ParticleGroupComponent.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP -#define NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP - -#include -#include - -namespace Ndk -{ - class ParticleGroupComponent; - - using ParticleGroupComponentHandle = Nz::ObjectHandle; - - class NDK_API ParticleGroupComponent : public Component, public Nz::ParticleGroup - { - public: - inline ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleLayout layout); - inline ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleDeclarationConstRef declaration); - ParticleGroupComponent(const ParticleGroupComponent&) = default; - ~ParticleGroupComponent() = default; - - void AddEmitter(Entity* emitter); - using ParticleGroup::AddEmitter; - - void RemoveEmitter(Entity* emitter); - using ParticleGroup::RemoveEmitter; - - static ComponentIndex componentIndex; - }; -} - -#include - -#endif // NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Components/ParticleGroupComponent.inl b/SDK/include/NDK/Components/ParticleGroupComponent.inl deleted file mode 100644 index d6225df3b..000000000 --- a/SDK/include/NDK/Components/ParticleGroupComponent.inl +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::ParticleGroupComponent - * \brief NDK class that represents the component for a group of particles - */ - - /*! - * \brief Constructs a ParticleGroupComponent object with a maximal number of particles and a layout - * - * \param maxParticleCount Maximum number of particles to generate - * \param layout Enumeration for the layout of data information for the particles - */ - - inline ParticleGroupComponent::ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleLayout layout) : - ParticleGroup(maxParticleCount, layout) - { - } - - /*! - * \brief Constructs a ParticleGroupComponent object with a maximal number of particles and a particle declaration - * - * \param maxParticleCount Maximum number of particles to generate - * \param declaration Data information for the particles - */ - - inline ParticleGroupComponent::ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleDeclarationConstRef declaration) : - ParticleGroup(maxParticleCount, std::move(declaration)) - { - } - - /*! - * \brief Adds an emitter to the particles - * - * \param emitter Emitter for the particles - * - * \remark Produces a NazaraAssert if emitter is invalid - * \remark Produces a NazaraAssert if entity has no component of type ParticleEmitterComponent - */ - - inline void ParticleGroupComponent::AddEmitter(Entity* emitter) - { - NazaraAssert(emitter && emitter->IsValid(), "Invalid entity"); - NazaraAssert(emitter->HasComponent(), "Entity must have a ParticleEmitterComponent"); - - auto& emitterComponent = emitter->GetComponent(); - ParticleGroup::AddEmitter(&emitterComponent); - } - - - /*! - * \brief Removes an emitter to the particles - * - * \param emitter Emitter for the particles to remove - * - * \remark Produces a NazaraAssert if emitter is invalid - * \remark Produces a NazaraAssert if entity has no component of type ParticleEmitterComponent - */ - - inline void ParticleGroupComponent::RemoveEmitter(Entity* emitter) - { - NazaraAssert(emitter && emitter->IsValid(), "Invalid entity"); - NazaraAssert(emitter->HasComponent(), "Entity must have a ParticleEmitterComponent"); - - auto& emitterComponent = emitter->GetComponent(); - ParticleGroup::RemoveEmitter(&emitterComponent); - } -} diff --git a/SDK/include/NDK/Console.hpp b/SDK/include/NDK/Console.hpp deleted file mode 100644 index 3b4dbbe39..000000000 --- a/SDK/include/NDK/Console.hpp +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_CONSOLE_HPP -#define NDK_CONSOLE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - struct WindowEvent; -} - -namespace Ndk -{ - class AbstractTextAreaWidget; - class Console; - class Entity; - class RichTextAreaWidget; - class ScrollAreaWidget; - class TextAreaWidget; - - using ConsoleHandle = Nz::ObjectHandle; - - class NDK_API Console : public BaseWidget, public Nz::HandledObject - { - public: - Console(BaseWidget* parent); - Console(const Console& console) = delete; - Console(Console&& console) = default; - ~Console() = default; - - void AddLine(const Nz::String& text, const Nz::Color& color = Nz::Color::White); - - void Clear(); - void ClearFocus(); - - inline unsigned int GetCharacterSize() const; - inline const RichTextAreaWidget* GetHistory() const; - inline const TextAreaWidget* GetInput() const; - inline const Nz::FontRef& GetTextFont() const; - - void SetCharacterSize(unsigned int size); - void SetFocus(); - void SetTextFont(Nz::FontRef font); - - Console& operator=(const Console& console) = delete; - Console& operator=(Console&& console) = default; - - NazaraSignal(OnCommand, Console* /*console*/, const Nz::String& /*command*/); - - private: - void ExecuteInput(const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction); - void Layout() override; - - struct Line - { - Nz::Color color; - Nz::String text; - }; - - std::size_t m_historyPosition; - std::vector m_commandHistory; - std::vector m_historyLines; - ScrollAreaWidget* m_historyArea; - RichTextAreaWidget* m_history; - TextAreaWidget* m_input; - Nz::FontRef m_defaultFont; - unsigned int m_characterSize; - unsigned int m_maxHistoryLines; - }; -} - -#include - -#endif // NDK_CONSOLE_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Console.inl b/SDK/include/NDK/Console.inl deleted file mode 100644 index 3cd318ae3..000000000 --- a/SDK/include/NDK/Console.inl +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - /*! - * \brief Gets the character size - * \return Height of the character - */ - - inline unsigned int Console::GetCharacterSize() const - { - return m_characterSize; - } - - /*! - * \brief Gets the entity representing the history of the console - * \return History of the console - */ - - inline const RichTextAreaWidget* Console::GetHistory() const - { - return m_history; - } - - /*! - * \brief Gets the entity representing the input of the console - * \return Input of the console - */ - - inline const TextAreaWidget* Console::GetInput() const - { - return m_input; - } - - /*! - * \brief Gets the font used by the console - * \return A reference to the font currenty used - */ - - inline const Nz::FontRef& Console::GetTextFont() const - { - return m_defaultFont; - } -} diff --git a/SDK/include/NDK/Lua/LuaBinding.hpp b/SDK/include/NDK/Lua/LuaBinding.hpp deleted file mode 100644 index 2a14cb5a5..000000000 --- a/SDK/include/NDK/Lua/LuaBinding.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_HPP -#define NDK_LUABINDING_HPP - -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding - { - friend class LuaBinding_SDK; - - public: - LuaBinding(); - ~LuaBinding() = default; - - template void BindComponent(const Nz::String& name); - - void RegisterClasses(Nz::LuaState& state); - - std::unique_ptr core; - std::unique_ptr math; - std::unique_ptr network; - std::unique_ptr sdk; - std::unique_ptr utility; - - #ifndef NDK_SERVER - std::unique_ptr audio; - std::unique_ptr graphics; - std::unique_ptr renderer; - std::unique_ptr platform; - #endif - - private: - template - static int AddComponentOfType(Nz::LuaState& lua, EntityHandle& handle); - - template - static int PushComponentOfType(Nz::LuaState& lua, BaseComponent& component); - - using AddComponentFunc = int(*)(Nz::LuaState&, EntityHandle&); - using GetComponentFunc = int(*)(Nz::LuaState&, BaseComponent&); - - struct ComponentBinding - { - AddComponentFunc adder; - ComponentIndex index; - GetComponentFunc getter; - Nz::String name; - }; - - ComponentBinding* QueryComponentIndex(Nz::LuaState& lua, int argIndex = 2); - - std::vector m_componentBinding; - std::unordered_map m_componentBindingByName; - }; -} - -#include - -#endif // NDK_LUABINDING_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding.inl b/SDK/include/NDK/Lua/LuaBinding.inl deleted file mode 100644 index 95ea207ab..000000000 --- a/SDK/include/NDK/Lua/LuaBinding.inl +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - namespace Detail - { - template - struct AddComponentIf; - - template<> - struct AddComponentIf - { - template - static int AddComponent(Nz::LuaState& lua, EntityHandle& handle) - { - T& component = handle->AddComponent(); - lua.Push(component.CreateHandle()); - return 1; - } - }; - - template<> - struct AddComponentIf - { - template - static int AddComponent(Nz::LuaState& lua, EntityHandle& /*handle*/) - { - lua.Error("Component has no default constructor and cannot be created from Lua yet"); - return 0; - } - }; - } - - /*! - * \brief Binds a component to a name - * - * \param name Name used to retrieve the component - * - * \remark Produces a NazaraAssert if name is empty - */ - template - void LuaBinding::BindComponent(const Nz::String& name) - { - NazaraAssert(!name.IsEmpty(), "Component name cannot be empty"); - - static_assert(std::is_base_of::value, "ComponentType must inherit BaseComponent"); - - ComponentBinding binding; - binding.adder = &Detail::AddComponentIf::value>::template AddComponent; - binding.getter = &PushComponentOfType; - binding.index = T::componentIndex; - binding.name = name; - - if (m_componentBinding.size() <= T::componentIndex) - m_componentBinding.resize(T::componentIndex + 1); - - m_componentBinding[T::componentIndex] = std::move(binding); - m_componentBindingByName[name] = T::componentIndex; - } - - template - int LuaBinding::PushComponentOfType(Nz::LuaState& lua, BaseComponent& component) - { - T& rightComponent = static_cast(component); - lua.Push(rightComponent.CreateHandle()); - return 1; - } -} diff --git a/SDK/include/NDK/Lua/LuaBinding_Audio.hpp b/SDK/include/NDK/Lua/LuaBinding_Audio.hpp deleted file mode 100644 index f2ee8c1ac..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Audio.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_AUDIO_HPP -#define NDK_LUABINDING_AUDIO_HPP - -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Audio : public LuaBinding_Base - { - public: - LuaBinding_Audio(LuaBinding& binding); - ~LuaBinding_Audio() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass music; - Nz::LuaClass sound; - Nz::LuaClass soundBuffer; - Nz::LuaClass soundEmitter; - }; -} - -#endif // NDK_LUABINDING_CORE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Base.hpp b/SDK/include/NDK/Lua/LuaBinding_Base.hpp deleted file mode 100644 index 5a52e0bc2..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Base.hpp +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_BASE_HPP -#define NDK_LUABINDING_BASE_HPP - -#include -#include -#include - -namespace Ndk -{ - class LuaBinding; - - class LuaBinding_Audio; - class LuaBinding_Core; - class LuaBinding_Graphics; - class LuaBinding_Math; - class LuaBinding_Network; - class LuaBinding_Renderer; - class LuaBinding_SDK; - class LuaBinding_Utility; - class LuaBinding_Platform; - - class NDK_API LuaBinding_Base - { - public: - LuaBinding_Base(LuaBinding& binding); - virtual ~LuaBinding_Base(); - - virtual void Register(Nz::LuaState& state) = 0; - - // Implementation lies in the respective .cpp files (still searching for a cleaner way..) - static std::unique_ptr BindCore(LuaBinding& binding); - static std::unique_ptr BindMath(LuaBinding& binding); - static std::unique_ptr BindNetwork(LuaBinding& binding); - static std::unique_ptr BindSDK(LuaBinding& binding); - static std::unique_ptr BindUtility(LuaBinding& binding); - - #ifndef NDK_SERVER - static std::unique_ptr BindAudio(LuaBinding& binding); - static std::unique_ptr BindGraphics(LuaBinding& binding); - static std::unique_ptr BindRenderer(LuaBinding& binding); - static std::unique_ptr BindPlatform(LuaBinding& binding); - #endif - - protected: - LuaBinding& m_binding; - }; -} - -#endif // NDK_LUABINDING_BASE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Core.hpp b/SDK/include/NDK/Lua/LuaBinding_Core.hpp deleted file mode 100644 index 3149fdcc8..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Core.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_CORE_HPP -#define NDK_LUABINDING_CORE_HPP - -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Core : public LuaBinding_Base - { - public: - LuaBinding_Core(LuaBinding& binding); - ~LuaBinding_Core() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass clock; - Nz::LuaClass directory; - Nz::LuaClass file; - Nz::LuaClass stream; - }; -} - -#endif // NDK_LUABINDING_CORE_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp b/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp deleted file mode 100644 index 7a804dd0f..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Graphics.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_GRAPHICS_HPP -#define NDK_LUABINDING_GRAPHICS_HPP - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Graphics : public LuaBinding_Base - { - public: - LuaBinding_Graphics(LuaBinding& binding); - ~LuaBinding_Graphics() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass abstractViewer; - Nz::LuaClass instancedRenderable; - Nz::LuaClass material; - Nz::LuaClass model; - Nz::LuaClass sprite; - Nz::LuaClass spriteLibrary; - }; -} - -#endif // NDK_LUABINDING_GRAPHICS_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Math.hpp b/SDK/include/NDK/Lua/LuaBinding_Math.hpp deleted file mode 100644 index 5849a7c33..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Math.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_MATH_HPP -#define NDK_LUABINDING_MATH_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Math : public LuaBinding_Base - { - public: - LuaBinding_Math(LuaBinding& binding); - ~LuaBinding_Math() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass eulerAngles; - Nz::LuaClass matrix4d; - Nz::LuaClass quaternion; - Nz::LuaClass rect; - Nz::LuaClass vector2d; - Nz::LuaClass vector3d; - }; -} - -#endif // NDK_LUABINDING_MATH_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Network.hpp b/SDK/include/NDK/Lua/LuaBinding_Network.hpp deleted file mode 100644 index 1b7f32f27..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Network.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_NETWORK_HPP -#define NDK_LUABINDING_NETWORK_HPP - -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Network : public LuaBinding_Base - { - public: - LuaBinding_Network(LuaBinding& binding); - ~LuaBinding_Network() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass abstractSocket; - Nz::LuaClass ipAddress; - Nz::LuaClass udpSocket; - }; -} - -#endif // NDK_LUABINDING_NETWORK_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Platform.hpp b/SDK/include/NDK/Lua/LuaBinding_Platform.hpp deleted file mode 100644 index 2d28841e7..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Platform.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_SYSTEM_HPP -#define NDK_LUABINDING_SYSTEM_HPP - -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Platform : public LuaBinding_Base - { - public: - LuaBinding_Platform(LuaBinding& binding); - ~LuaBinding_Platform() = default; - - void Register(Nz::LuaState& state) override; - - // Platform - Nz::LuaClass keyboard; - }; -} - -#endif // NDK_LUABINDING_SYSTEM_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp b/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp deleted file mode 100644 index daa75e4af..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Renderer.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_RENDERER_HPP -#define NDK_LUABINDING_RENDERER_HPP - -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Renderer : public LuaBinding_Base - { - public: - LuaBinding_Renderer(LuaBinding& binding); - ~LuaBinding_Renderer() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass texture; - Nz::LuaClass textureLibrary; - Nz::LuaClass textureManager; - }; -} - -#endif // NDK_LUABINDING_RENDERER_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_SDK.hpp b/SDK/include/NDK/Lua/LuaBinding_SDK.hpp deleted file mode 100644 index a663edce4..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_SDK.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_SDK_HPP -#define NDK_LUABINDING_SDK_HPP - -#include -#include -#include -#include -#include - -namespace Ndk -{ - class Application; - - class NDK_API LuaBinding_SDK : public LuaBinding_Base - { - public: - LuaBinding_SDK(LuaBinding& binding); - ~LuaBinding_SDK() = default; - - void Register(Nz::LuaState& state) override; - - Nz::LuaClass application; - Nz::LuaClass entity; - Nz::LuaClass nodeComponent; - Nz::LuaClass velocityComponent; - Nz::LuaClass world; - - #ifndef NDK_SERVER - Nz::LuaClass cameraComponent; - Nz::LuaClass console; - Nz::LuaClass graphicsComponent; - #endif - - }; -} - -#endif // NDK_LUABINDING_SDK_HPP diff --git a/SDK/include/NDK/Lua/LuaBinding_Utility.hpp b/SDK/include/NDK/Lua/LuaBinding_Utility.hpp deleted file mode 100644 index 6f7fde64b..000000000 --- a/SDK/include/NDK/Lua/LuaBinding_Utility.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUABINDING_UTILITY_HPP -#define NDK_LUABINDING_UTILITY_HPP - -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API LuaBinding_Utility : public LuaBinding_Base - { - public: - LuaBinding_Utility(LuaBinding& binding); - ~LuaBinding_Utility() = default; - - void Register(Nz::LuaState& state) override; - - // Utility - Nz::LuaClass abstractImage; - Nz::LuaClass font; - Nz::LuaClass node; - }; -} - -#endif // NDK_LUABINDING_UTILITY_HPP diff --git a/SDK/include/NDK/LuaAPI.hpp b/SDK/include/NDK/LuaAPI.hpp deleted file mode 100644 index 457ffb980..000000000 --- a/SDK/include/NDK/LuaAPI.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_LUAINTERFACE_HPP -#define NDK_LUAINTERFACE_HPP - -#include - -namespace Nz -{ - class LuaState; -} - -namespace Ndk -{ - class LuaBinding; - - class NDK_API LuaAPI - { - public: - LuaAPI() = delete; - ~LuaAPI() = delete; - - static LuaBinding* GetBinding(); - - static bool Initialize(); - - static void RegisterClasses(Nz::LuaState& state); - - static void Uninitialize(); - - private: - static LuaBinding* s_binding; - }; -} - -#include - -#endif // NDK_LUAINTERFACE_HPP diff --git a/SDK/include/NDK/LuaAPI.inl b/SDK/include/NDK/LuaAPI.inl deleted file mode 100644 index 01c797e89..000000000 --- a/SDK/include/NDK/LuaAPI.inl +++ /dev/null @@ -1,687 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef NDK_SERVER -#include -#include -#include -#include -#include -#endif - -namespace Nz -{ - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Color* color, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - color->r = state.CheckField("r", index); - color->g = state.CheckField("g", index); - color->b = state.CheckField("b", index); - color->a = state.CheckField("a", 255, index); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesd* angles, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_Table: - angles->Set(state.CheckField("pitch", index), state.CheckField("yaw", index), state.CheckField("roll", index)); - return 1; - - default: - { - if (state.IsOfType(index, "EulerAngles")) - angles->Set(*static_cast(state.ToUserdata(index))); - else - angles->Set(*static_cast(state.CheckUserdata(index, "Quaternion"))); - - return 1; - } - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesf* angles, TypeTag) - { - EulerAnglesd anglesDouble; - unsigned int ret = LuaImplQueryArg(state, index, &anglesDouble, TypeTag()); - - angles->Set(anglesDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontRef* fontRef, TypeTag) - { - *fontRef = *static_cast(state.CheckUserdata(index, "Font")); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontParams* params, TypeTag) - { - NazaraUnused(params); - - state.CheckType(index, Nz::LuaType_Table); - - // Structure is empty for now - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ImageParams* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->levelCount = state.CheckField("LevelCount"); - params->loadFormat = state.CheckField("LoadFormat"); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, IpAddress* address, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_String: - address->BuildFromAddress(state.CheckString(index)); - return 1; - - default: - *address = *static_cast(state.CheckUserdata(index, "IpAddress")); - return 1; - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4d* mat, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_Table: - { - double values[16]; - for (std::size_t i = 0; i < 16; ++i) - { - state.PushInteger(i + 1); - state.GetTable(); - - values[i] = state.CheckNumber(-1); - state.Pop(); - } - - *mat = Matrix4d(values); - return 1; - } - - default: - { - if (state.IsOfType(index, "Matrix4")) - *mat = *static_cast(state.ToUserdata(index)); - - return 1; - } - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4f* mat, TypeTag) - { - Matrix4d matDouble = Matrix4d::Identity(); - unsigned int ret = LuaImplQueryArg(state, index, &matDouble, TypeTag()); - - mat->Set(matDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MeshParams* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->animated = state.CheckField("Animated", params->animated); - params->center = state.CheckField("Center", params->center); - params->matrix = state.CheckField("Matrix", params->matrix); - params->optimizeIndexBuffers = state.CheckField("OptimizeIndexBuffers", params->optimizeIndexBuffers); - params->texCoordOffset = state.CheckField("TexCoordOffset", params->texCoordOffset); - params->texCoordScale = state.CheckField("TexCoordScale", params->texCoordScale); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaterniond* quat, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_Table: - quat->Set(state.CheckField("w", index), state.CheckField("x", index), state.CheckField("y", index), state.CheckField("z", index)); - return 1; - - default: - { - if (state.IsOfType(index, "EulerAngles")) - quat->Set(*static_cast(state.ToUserdata(index))); - else - quat->Set(*static_cast(state.CheckUserdata(index, "Quaternion"))); - - return 1; - } - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaternionf* quat, TypeTag) - { - Quaterniond quatDouble; - unsigned int ret = LuaImplQueryArg(state, index, &quatDouble, TypeTag()); - - quat->Set(quatDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectd* rect, TypeTag) - { - state.CheckType(index, LuaType_Table); - - rect->x = state.CheckField("x", index); - rect->y = state.CheckField("y", index); - rect->width = state.CheckField("width", index); - rect->height = state.CheckField("height", index); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectf* rect, TypeTag) - { - Rectd rectDouble; - unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag()); - - rect->Set(rectDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Recti* rect, TypeTag) - { - Rectd rectDouble; - unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag()); - - rect->Set(rectDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectui* rect, TypeTag) - { - Rectd rectDouble; - unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag()); - - rect->Set(rectDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2d* vec, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_Number: - if (index < 0 && index > -2) - state.Error("Vector2 expected, two numbers are required to convert it"); - - vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1)); - return 2; - - case Nz::LuaType_Table: - vec->Set(state.CheckField("x", index), state.CheckField("y", index)); - return 1; - - default: - vec->Set(*static_cast(state.CheckUserdata(index, "Vector2"))); - return 1; - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2f* vec, TypeTag) - { - Vector2d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2ui* vec, TypeTag) - { - Vector2d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2i* vec, TypeTag) - { - Vector2d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3d* vec, TypeTag) - { - switch (state.GetType(index)) - { - case Nz::LuaType_Number: - if (index < 0 && index > -3) - state.Error("Vector3 expected, three numbers are required to convert it"); - - vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1), state.CheckNumber(index + 2, 0.0)); - return 3; - - case Nz::LuaType_Table: - vec->Set(state.CheckField("x", index), state.CheckField("y", index), state.CheckField("z", 0.0, index)); - return 1; - - default: - vec->Set(*static_cast(state.CheckUserdata(index, "Vector3"))); - return 1; - } - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3f* vec, TypeTag) - { - Vector3d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3ui* vec, TypeTag) - { - Vector3d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3i* vec, TypeTag) - { - Vector3d vecDouble; - unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag()); - - vec->Set(vecDouble); - return ret; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::Entity** handle, TypeTag) - { - if (!state.IsOfType(index, LuaType_Nil)) - *handle = *static_cast(state.CheckUserdata(index, "Entity")); - else - *handle = nullptr; - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::EntityHandle* handle, TypeTag) - { - if (!state.IsOfType(index, LuaType_Nil)) - *handle = *static_cast(state.CheckUserdata(index, "Entity")); - else - handle->Reset(); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::WorldHandle* handle, TypeTag) - { - *handle = *static_cast(state.CheckUserdata(index, "World")); - - return 1; - } - -#ifndef NDK_SERVER - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, InstancedRenderableRef* renderable, TypeTag) - { - if (state.IsOfType(index, "InstancedRenderable") || - state.IsOfType(index, "Model") || - state.IsOfType(index, "Sprite")) - { - *renderable = *static_cast(state.ToUserdata(index)); - } - else - state.ArgError(index, "is not a InstancedRenderable instance"); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialRef* materialRef, TypeTag) - { - *materialRef = *static_cast(state.CheckUserdata(index, "Material")); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialParams* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->loadAlphaMap = state.CheckField("LoadAlphaMap", params->loadAlphaMap); - params->loadDiffuseMap = state.CheckField("LoadDiffuseMap", params->loadDiffuseMap); - params->loadEmissiveMap = state.CheckField("LoadEmissiveMap", params->loadEmissiveMap); - params->loadHeightMap = state.CheckField("LoadHeightMap", params->loadHeightMap); - params->loadNormalMap = state.CheckField("LoadNormalMap", params->loadNormalMap); - params->loadSpecularMap = state.CheckField("LoadSpecularMap", params->loadSpecularMap); - params->shaderName = state.CheckField("ShaderName", params->shaderName); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ModelParameters* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->loadMaterials = state.CheckField("LoadMaterials", params->loadMaterials); - - LuaImplQueryArg(state, -1, ¶ms->material, TypeTag()); - LuaImplQueryArg(state, -1, ¶ms->mesh, TypeTag()); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SoundBufferParams* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->forceMono = state.CheckField("ForceMono", params->forceMono); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SoundStreamParams* params, TypeTag) - { - state.CheckType(index, Nz::LuaType_Table); - - params->forceMono = state.CheckField("ForceMono", params->forceMono); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SpriteRef* spriteRef, TypeTag) - { - *spriteRef = *static_cast(state.CheckUserdata(index, "Sprite")); - - return 1; - } - - inline unsigned int LuaImplQueryArg(const LuaState& state, int index, TextureRef* textureRef, TypeTag) - { - *textureRef = *static_cast(state.CheckUserdata(index, "Texture")); - - return 1; - } -#endif - - inline int LuaImplReplyVal(const LuaState& state, Color&& val, TypeTag) - { - state.PushTable(); - state.PushField("r", val.r); - state.PushField("g", val.g); - state.PushField("b", val.b); - state.PushField("a", val.a); - - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, EulerAnglesd&& val, TypeTag) - { - state.PushInstance("EulerAngles", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, EulerAnglesf&& val, TypeTag) - { - state.PushInstance("EulerAngles", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, FontRef&& val, TypeTag) - { - state.PushInstance("Font", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Font::SizeInfo&& val, TypeTag) - { - state.PushTable(); - state.PushField("LineHeight", val.lineHeight); - state.PushField("SpaceAdvance", val.spaceAdvance); - state.PushField("UnderlinePosition", val.underlinePosition); - state.PushField("UnderlineThickness", val.underlineThickness); - - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, ImageParams&& val, TypeTag) - { - state.PushTable(0, 2); - state.PushField("LevelCount", val.levelCount); - state.PushField("LoadFormat", val.loadFormat); - - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, IpAddress&& val, TypeTag) - { - state.PushInstance("IpAddress", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Matrix4d&& val, TypeTag) - { - state.PushInstance("Matrix4", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Matrix4f&& val, TypeTag) - { - state.PushInstance("Matrix4", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Quaterniond&& val, TypeTag) - { - state.PushInstance("Quaternion", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Quaternionf&& val, TypeTag) - { - state.PushInstance("Quaternion", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Rectd&& val, TypeTag) - { - state.PushInstance("Rect", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Rectf&& val, TypeTag) - { - state.PushInstance("Rect", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Recti&& val, TypeTag) - { - state.PushInstance("Rect", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Rectui&& val, TypeTag) - { - state.PushInstance("Rect", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector2d&& val, TypeTag) - { - state.PushInstance("Vector2", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector2f&& val, TypeTag) - { - state.PushInstance("Vector2", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector2ui&& val, TypeTag) - { - state.PushInstance("Vector2", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector2i&& val, TypeTag) - { - state.PushInstance("Vector2", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector3d&& val, TypeTag) - { - state.PushInstance("Vector3", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector3f&& val, TypeTag) - { - state.PushInstance("Vector3", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector3ui&& val, TypeTag) - { - state.PushInstance("Vector3", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Vector3i&& val, TypeTag) - { - state.PushInstance("Vector3", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::Entity* ptr, TypeTag) - { - state.PushInstance("Entity", ptr); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::Application* ptr, TypeTag) - { - state.PushInstance("Application", ptr); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::EntityHandle&& handle, TypeTag) - { - state.PushInstance("Entity", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::NodeComponentHandle&& handle, TypeTag) - { - state.PushInstance("NodeComponent", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::VelocityComponentHandle&& handle, TypeTag) - { - state.PushInstance("VelocityComponent", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::World* ptr, TypeTag) - { - state.PushInstance("World", ptr); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::WorldHandle&& handle, TypeTag) - { - state.PushInstance("World", handle); - return 1; - } - -#ifndef NDK_SERVER - inline int LuaImplReplyVal(const LuaState& state, MaterialRef&& handle, TypeTag) - { - state.PushInstance("Material", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, ModelRef&& handle, TypeTag) - { - state.PushInstance("Model", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, const SoundBuffer* val, TypeTag) - { - state.PushInstance("SoundBuffer", val); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, SoundBufferRef&& handle, TypeTag) - { - state.PushInstance("SoundBuffer", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, SpriteRef&& handle, TypeTag) - { - state.PushInstance("Sprite", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, TextureRef&& handle, TypeTag) - { - state.PushInstance("Texture", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::CameraComponentHandle&& handle, TypeTag) - { - state.PushInstance("CameraComponent", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::ConsoleHandle&& handle, TypeTag) - { - state.PushInstance("Console", handle); - return 1; - } - - inline int LuaImplReplyVal(const LuaState& state, Ndk::GraphicsComponentHandle&& handle, TypeTag) - { - state.PushInstance("GraphicsComponent", handle); - return 1; - } -#endif - -} diff --git a/SDK/include/NDK/Sdk.hpp b/SDK/include/NDK/Sdk.hpp deleted file mode 100644 index 7b096c583..000000000 --- a/SDK/include/NDK/Sdk.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SDK_HPP -#define NDK_SDK_HPP - -#include - -namespace Ndk -{ - class NDK_API Sdk - { - public: - Sdk() = delete; - ~Sdk() = delete; - - static bool Initialize(); - static bool IsInitialized(); - static void Uninitialize(); - - private: - static unsigned int s_referenceCounter; - }; -} - -#include - -#endif // NDK_SDK_HPP diff --git a/SDK/include/NDK/Sdk.inl b/SDK/include/NDK/Sdk.inl deleted file mode 100644 index 6c8a860e3..000000000 --- a/SDK/include/NDK/Sdk.inl +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - /*! - * \brief Checks whether the module is initialized - * \return true if module is initialized - */ - - inline bool Sdk::IsInitialized() - { - return s_referenceCounter != 0; - } -} diff --git a/SDK/include/NDK/Systems.hpp b/SDK/include/NDK/Systems.hpp deleted file mode 100644 index e9a60f0c3..000000000 --- a/SDK/include/NDK/Systems.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// This file was automatically generated - -#pragma once - -#ifndef NDK_SYSTEMS_GLOBAL_HPP -#define NDK_SYSTEMS_GLOBAL_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -#endif // NDK_SYSTEMS_GLOBAL_HPP diff --git a/SDK/include/NDK/Systems/DebugSystem.hpp b/SDK/include/NDK/Systems/DebugSystem.hpp deleted file mode 100644 index 1d468ea41..000000000 --- a/SDK/include/NDK/Systems/DebugSystem.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_SYSTEMS_DEBUGSYSTEM_HPP -#define NDK_SYSTEMS_DEBUGSYSTEM_HPP - -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API DebugSystem : public System - { - public: - DebugSystem(); - ~DebugSystem() = default; - - void EnableDepthBuffer(bool enable); - - inline bool IsDepthBufferEnabled() const; - - static SystemIndex systemIndex; - - private: - Nz::InstancedRenderableRef GenerateBox(Nz::Boxf box); - Nz::InstancedRenderableRef GenerateCollision2DMesh(Entity* entity, Nz::Vector3f* offset); - Nz::InstancedRenderableRef GenerateCollision3DMesh(Entity* entity); - - std::pair GetBoxMesh(); - Nz::MaterialRef GetCollisionMaterial(); - Nz::MaterialRef GetGlobalAABBMaterial(); - Nz::MaterialRef GetLocalAABBMaterial(); - Nz::MaterialRef GetOBBMaterial(); - - void OnEntityValidation(Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; - - Nz::MaterialRef m_globalAabbMaterial; - Nz::MaterialRef m_localAabbMaterial; - Nz::MaterialRef m_collisionMaterial; - Nz::MaterialRef m_obbMaterial; - Nz::IndexBufferRef m_boxMeshIndexBuffer; - Nz::VertexBufferRef m_boxMeshVertexBuffer; - bool m_isDepthBufferEnabled; - }; -} - -#include - -#endif // NDK_SYSTEMS_DEBUGSYSTEM_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Systems/DebugSystem.inl b/SDK/include/NDK/Systems/DebugSystem.inl deleted file mode 100644 index b72b87f3f..000000000 --- a/SDK/include/NDK/Systems/DebugSystem.inl +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline bool DebugSystem::IsDepthBufferEnabled() const - { - return m_isDepthBufferEnabled; - } -} diff --git a/SDK/include/NDK/Systems/ParticleSystem.hpp b/SDK/include/NDK/Systems/ParticleSystem.hpp deleted file mode 100644 index adbfc7e39..000000000 --- a/SDK/include/NDK/Systems/ParticleSystem.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_SYSTEMS_PARTICLESYSTEM_HPP -#define NDK_SYSTEMS_PARTICLESYSTEM_HPP - -#include - -namespace Ndk -{ - class NDK_API ParticleSystem : public System - { - public: - ParticleSystem(); - ~ParticleSystem() = default; - - static SystemIndex systemIndex; - - private: - void OnUpdate(float elapsedTime) override; - }; -} - -#include - -#endif // NDK_SYSTEMS_PARTICLESYSTEM_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Systems/RenderSystem.hpp b/SDK/include/NDK/Systems/RenderSystem.hpp deleted file mode 100644 index 3b9d3f239..000000000 --- a/SDK/include/NDK/Systems/RenderSystem.hpp +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_SERVER -#ifndef NDK_SYSTEMS_RENDERSYSTEM_HPP -#define NDK_SYSTEMS_RENDERSYSTEM_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class AbstractViewer; - - class NDK_API RenderSystem : public System - { - public: - RenderSystem(); - ~RenderSystem() = default; - - template T& ChangeRenderTechnique(); - inline Nz::AbstractRenderTechnique& ChangeRenderTechnique(std::unique_ptr&& renderTechnique); - - inline void EnableCulling(bool enable); - - inline const Nz::BackgroundRef& GetDefaultBackground() const; - inline const Nz::Matrix4f& GetCoordinateSystemMatrix() const; - inline Nz::Vector3f GetGlobalForward() const; - inline Nz::Vector3f GetGlobalRight() const; - inline Nz::Vector3f GetGlobalUp() const; - inline Nz::AbstractRenderTechnique& GetRenderTechnique() const; - - inline bool IsCullingEnabled() const; - - inline void SetDefaultBackground(Nz::BackgroundRef background); - inline void SetGlobalForward(const Nz::Vector3f& direction); - inline void SetGlobalRight(const Nz::Vector3f& direction); - inline void SetGlobalUp(const Nz::Vector3f& direction); - - static SystemIndex systemIndex; - - private: - inline void InvalidateCoordinateSystem(); - - void OnEntityRemoved(Entity* entity) override; - void OnEntityValidation(Entity* entity, bool justAdded) override; - void OnUpdate(float elapsedTime) override; - - void UpdateDynamicReflections(); - void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer); - void UpdatePointSpotShadowMaps(); - - std::unique_ptr m_renderTechnique; - std::vector m_volumeEntries; - std::vector m_cameras; - EntityList m_drawables; - EntityList m_directionalLights; - EntityList m_lights; - EntityList m_pointSpotLights; - EntityList m_particleGroups; - EntityList m_realtimeReflected; - GraphicsComponentCullingList m_drawableCulling; - Nz::BackgroundRef m_background; - Nz::DepthRenderTechnique m_shadowTechnique; - Nz::Matrix4f m_coordinateSystemMatrix; - Nz::RenderTexture m_shadowRT; - bool m_coordinateSystemInvalidated; - bool m_forceRenderQueueInvalidation; - bool m_isCullingEnabled; - }; -} - -#include - -#endif // NDK_SYSTEMS_RENDERSYSTEM_HPP -#endif // NDK_SERVER diff --git a/SDK/include/NDK/Systems/RenderSystem.inl b/SDK/include/NDK/Systems/RenderSystem.inl deleted file mode 100644 index 335026f17..000000000 --- a/SDK/include/NDK/Systems/RenderSystem.inl +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - /*! - * \brief Changes the render technique used for the system - * \return A reference to the render technique type - */ - - template - inline T& RenderSystem::ChangeRenderTechnique() - { - static_assert(std::is_base_of::value, "RenderTechnique is not a subtype of AbstractRenderTechnique"); - return static_cast(ChangeRenderTechnique(std::make_unique())); - } - - /*! - * \brief Changes the render technique used for the system - * \return A reference to the abstract render technique - * - * \param renderTechnique Render technique to use - */ - - inline Nz::AbstractRenderTechnique& RenderSystem::ChangeRenderTechnique(std::unique_ptr&& renderTechnique) - { - m_renderTechnique = std::move(renderTechnique); - return *m_renderTechnique; - } - - /*! - * \brief Enables/disables object culling - * - * Object culling is an algorithm used by the render system to detect invisible objects (which will not appear on screen) before they are rendered. - * This includes Frustum Culling and potentially Occlusion Culling. - * - * Disabling this is not recommended, as the system will draw every object in the world which could induce a performance loss. - * - * \param enable Whether to enable or disable culling - * - * \see IsCullingEnabled - */ - inline void RenderSystem::EnableCulling(bool enable) - { - m_isCullingEnabled = enable; - } - - /*! - * \brief Gets the background used for rendering - * \return A reference to the background - */ - - inline const Nz::BackgroundRef& RenderSystem::GetDefaultBackground() const - { - return m_background; - } - - /*! - * \brief Gets the coordinates matrix used for rendering - * \return A constant reference to the matrix of coordinates - */ - - inline const Nz::Matrix4f& RenderSystem::GetCoordinateSystemMatrix() const - { - return m_coordinateSystemMatrix; - } - - /*! - * \brief Gets the "forward" global direction - * \return The forward direction, by default, it's -UnitZ() (Right hand coordinates) - */ - - inline Nz::Vector3f RenderSystem::GetGlobalForward() const - { - return Nz::Vector3f(-m_coordinateSystemMatrix.m13, -m_coordinateSystemMatrix.m23, -m_coordinateSystemMatrix.m33); - } - - /*! - * \brief Gets the "right" global direction - * \return The right direction, by default, it's UnitX() (Right hand coordinates) - */ - - inline Nz::Vector3f RenderSystem::GetGlobalRight() const - { - return Nz::Vector3f(m_coordinateSystemMatrix.m11, m_coordinateSystemMatrix.m21, m_coordinateSystemMatrix.m31); - } - - /*! - * \brief Gets the "up" global direction - * \return The up direction, by default, it's UnitY() (Right hand coordinates) - */ - - inline Nz::Vector3f RenderSystem::GetGlobalUp() const - { - return Nz::Vector3f(m_coordinateSystemMatrix.m12, m_coordinateSystemMatrix.m22, m_coordinateSystemMatrix.m32); - } - - /*! - * \brief Gets the render technique used for rendering - * \return A reference to the abstract render technique being used - */ - - inline Nz::AbstractRenderTechnique& RenderSystem::GetRenderTechnique() const - { - return *m_renderTechnique.get(); - } - - /*! - * \brief Query if culling is enabled (enabled by default) - * \return True if culling is enabled, false otherwise - * - * \see EnableCulling - */ - inline bool RenderSystem::IsCullingEnabled() const - { - return m_isCullingEnabled; - } - - /*! - * \brief Sets the background used for rendering - * - * \param background A reference to the background - */ - - inline void RenderSystem::SetDefaultBackground(Nz::BackgroundRef background) - { - m_background = std::move(background); - } - - /*! - * \brief Sets the "forward" global direction - * - * \param direction The new forward direction - */ - - inline void RenderSystem::SetGlobalForward(const Nz::Vector3f& direction) - { - m_coordinateSystemMatrix.m13 = -direction.x; - m_coordinateSystemMatrix.m23 = -direction.y; - m_coordinateSystemMatrix.m33 = -direction.z; - - InvalidateCoordinateSystem(); - } - - /*! - * \brief Sets the "right" global direction - * - * \param direction The new right direction - */ - - inline void RenderSystem::SetGlobalRight(const Nz::Vector3f& direction) - { - m_coordinateSystemMatrix.m11 = direction.x; - m_coordinateSystemMatrix.m21 = direction.y; - m_coordinateSystemMatrix.m31 = direction.z; - - InvalidateCoordinateSystem(); - } - - /*! - * \brief Sets the "up" global direction - * - * \param direction The new up direction - */ - - inline void RenderSystem::SetGlobalUp(const Nz::Vector3f& direction) - { - m_coordinateSystemMatrix.m12 = direction.x; - m_coordinateSystemMatrix.m22 = direction.y; - m_coordinateSystemMatrix.m32 = direction.z; - - InvalidateCoordinateSystem(); - } - - /*! - * \brief Invalidates the matrix of coordinates for the system - */ - - inline void RenderSystem::InvalidateCoordinateSystem() - { - m_coordinateSystemInvalidated = true; - } -} diff --git a/SDK/include/NDK/Widgets.hpp b/SDK/include/NDK/Widgets.hpp deleted file mode 100644 index 9a36e37a2..000000000 --- a/SDK/include/NDK/Widgets.hpp +++ /dev/null @@ -1,20 +0,0 @@ -// This file was automatically generated - -#pragma once - -#ifndef NDK_WIDGETS_GLOBAL_HPP -#define NDK_WIDGETS_GLOBAL_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif // NDK_WIDGETS_GLOBAL_HPP diff --git a/SDK/include/NDK/Widgets/AbstractTextAreaWidget.hpp b/SDK/include/NDK/Widgets/AbstractTextAreaWidget.hpp deleted file mode 100644 index b05f65bce..000000000 --- a/SDK/include/NDK/Widgets/AbstractTextAreaWidget.hpp +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP -#define NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API AbstractTextAreaWidget : public BaseWidget - { - public: - using CharacterFilter = std::function; - - AbstractTextAreaWidget(BaseWidget* parent); - AbstractTextAreaWidget(const AbstractTextAreaWidget&) = delete; - AbstractTextAreaWidget(AbstractTextAreaWidget&&) = default; - ~AbstractTextAreaWidget() = default; - - virtual void Clear(); - - //virtual TextAreaWidget* Clone() const = 0; - - void EnableLineWrap(bool enable = true); - inline void EnableMultiline(bool enable = true); - inline void EnableTabWriting(bool enable = true); - - inline void Erase(std::size_t glyphPosition); - virtual void Erase(std::size_t firstGlyph, std::size_t lastGlyph) = 0; - inline void EraseSelection(); - - inline const CharacterFilter& GetCharacterFilter() const; - inline const Nz::Vector2ui& GetCursorPosition() const; - inline Nz::Vector2ui GetCursorPosition(std::size_t glyphIndex) const; - inline EchoMode GetEchoMode() const; - inline std::size_t GetGlyphIndex() const; - inline std::size_t GetGlyphIndex(const Nz::Vector2ui& cursorPosition) const; - inline const Nz::String& GetText() const; - - Nz::Vector2ui GetHoveredGlyph(float x, float y) const; - - inline bool HasSelection() const; - - inline bool IsLineWrapEnabled() const; - inline bool IsMultilineEnabled() const; - inline bool IsReadOnly() const; - inline bool IsTabWritingEnabled() const; - - inline void MoveCursor(int offset); - inline void MoveCursor(const Nz::Vector2i& offset); - - inline Nz::Vector2ui NormalizeCursorPosition(Nz::Vector2ui cursorPosition) const; - - inline void SetCharacterFilter(CharacterFilter filter); - inline void SetCursorPosition(std::size_t glyphIndex); - inline void SetCursorPosition(Nz::Vector2ui cursorPosition); - inline void SetEchoMode(EchoMode echoMode); - inline void SetReadOnly(bool readOnly = true); - inline void SetSelection(Nz::Vector2ui fromPosition, Nz::Vector2ui toPosition); - - inline void Write(const Nz::String& text); - inline void Write(const Nz::String& text, const Nz::Vector2ui& glyphPosition); - virtual void Write(const Nz::String& text, std::size_t glyphPosition) = 0; - - AbstractTextAreaWidget& operator=(const AbstractTextAreaWidget&) = delete; - AbstractTextAreaWidget& operator=(AbstractTextAreaWidget&&) = default; - - NazaraSignal(OnTextAreaCursorMove, const AbstractTextAreaWidget* /*textArea*/, Nz::Vector2ui* /*newCursorPosition*/); - NazaraSignal(OnTextAreaKeyBackspace, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyDown, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyEnd, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyHome, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyLeft, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyReturn, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyRight, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaKeyUp, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/); - NazaraSignal(OnTextAreaSelection, const AbstractTextAreaWidget* /*textArea*/, Nz::Vector2ui* /*start*/, Nz::Vector2ui* /*end*/); - - protected: - virtual Nz::AbstractTextDrawer& GetTextDrawer() = 0; - virtual const Nz::AbstractTextDrawer& GetTextDrawer() const = 0; - - void Layout() override; - - virtual void HandleIndentation(bool add) = 0; - virtual void HandleSelectionIndentation(bool add) = 0; - virtual void HandleWordCursorMove(bool left) = 0; - - bool IsFocusable() const override; - void OnFocusLost() override; - void OnFocusReceived() override; - bool OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) override; - void OnKeyReleased(const Nz::WindowEvent::KeyEvent& key) override; - void OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button button) override; - void OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button button) override; - void OnMouseEnter() override; - void OnMouseMoved(int x, int y, int deltaX, int deltaY) override; - void OnTextEntered(char32_t character, bool repeated) override; - - inline void SetCursorPositionInternal(std::size_t glyphIndex); - inline void SetCursorPositionInternal(Nz::Vector2ui cursorPosition); - - void RefreshCursor(); - virtual void UpdateDisplayText() = 0; - void UpdateTextSprite(); - - CharacterFilter m_characterFilter; - EchoMode m_echoMode; - EntityHandle m_cursorEntity; - EntityHandle m_textEntity; - Nz::TextSpriteRef m_textSprite; - Nz::Vector2ui m_cursorPositionBegin; - Nz::Vector2ui m_cursorPositionEnd; - Nz::Vector2ui m_selectionCursor; - std::vector m_cursorSprites; - bool m_isLineWrapEnabled; - bool m_isMouseButtonDown; - bool m_multiLineEnabled; - bool m_readOnly; - bool m_tabEnabled; // writes (Shift+)Tab character if set to true - }; -} - -#include - -#endif // NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/AbstractTextAreaWidget.inl b/SDK/include/NDK/Widgets/AbstractTextAreaWidget.inl deleted file mode 100644 index ca40d278b..000000000 --- a/SDK/include/NDK/Widgets/AbstractTextAreaWidget.inl +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline void AbstractTextAreaWidget::EnableMultiline(bool enable) - { - m_multiLineEnabled = enable; - } - - inline void AbstractTextAreaWidget::EnableTabWriting(bool enable) - { - m_tabEnabled = enable; - } - - inline void AbstractTextAreaWidget::Erase(std::size_t glyphPosition) - { - Erase(glyphPosition, glyphPosition + 1U); - } - - inline void AbstractTextAreaWidget::EraseSelection() - { - if (!HasSelection()) - return; - - Erase(GetGlyphIndex(m_cursorPositionBegin), GetGlyphIndex(m_cursorPositionEnd)); - } - - inline const AbstractTextAreaWidget::CharacterFilter& AbstractTextAreaWidget::GetCharacterFilter() const - { - return m_characterFilter; - } - - inline const Nz::Vector2ui& AbstractTextAreaWidget::GetCursorPosition() const - { - return m_cursorPositionBegin; - } - - Nz::Vector2ui AbstractTextAreaWidget::GetCursorPosition(std::size_t glyphIndex) const - { - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - glyphIndex = std::min(glyphIndex, GetTextDrawer().GetGlyphCount()); - - std::size_t lineCount = textDrawer.GetLineCount(); - std::size_t line = 0U; - for (std::size_t i = line + 1; i < lineCount; ++i) - { - if (textDrawer.GetLine(i).glyphIndex > glyphIndex) - break; - - line = i; - } - - const auto& lineInfo = textDrawer.GetLine(line); - - Nz::Vector2ui cursorPos; - cursorPos.y = static_cast(line); - cursorPos.x = static_cast(glyphIndex - lineInfo.glyphIndex); - - return cursorPos; - } - - inline EchoMode AbstractTextAreaWidget::GetEchoMode() const - { - return m_echoMode; - } - - inline std::size_t AbstractTextAreaWidget::GetGlyphIndex() const - { - return GetGlyphIndex(m_cursorPositionBegin); - } - - inline std::size_t AbstractTextAreaWidget::GetGlyphIndex(const Nz::Vector2ui& cursorPosition) const - { - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - std::size_t glyphIndex = textDrawer.GetLine(cursorPosition.y).glyphIndex + cursorPosition.x; - if (textDrawer.GetLineCount() > cursorPosition.y + 1) - glyphIndex = std::min(glyphIndex, textDrawer.GetLine(cursorPosition.y + 1).glyphIndex - 1); - else - glyphIndex = std::min(glyphIndex, textDrawer.GetGlyphCount()); - - return glyphIndex; - } - - inline bool AbstractTextAreaWidget::HasSelection() const - { - return m_cursorPositionBegin != m_cursorPositionEnd; - } - - inline bool AbstractTextAreaWidget::IsLineWrapEnabled() const - { - return m_isLineWrapEnabled; - } - - inline bool AbstractTextAreaWidget::IsMultilineEnabled() const - { - return m_multiLineEnabled; - } - - inline bool AbstractTextAreaWidget::IsTabWritingEnabled() const - { - return m_tabEnabled; - } - - inline bool AbstractTextAreaWidget::IsReadOnly() const - { - return m_readOnly; - } - - inline void AbstractTextAreaWidget::MoveCursor(int offset) - { - std::size_t cursorGlyph = GetGlyphIndex(m_cursorPositionBegin); - if (offset >= 0) - SetCursorPosition(cursorGlyph + static_cast(offset)); - else - { - std::size_t nOffset = static_cast(-offset); - if (nOffset >= cursorGlyph) - SetCursorPosition(0); - else - SetCursorPosition(cursorGlyph - nOffset); - } - } - - inline void AbstractTextAreaWidget::MoveCursor(const Nz::Vector2i& offset) - { - auto ClampOffset = [] (unsigned int cursorPosition, int cursorOffset) -> unsigned int - { - if (cursorOffset >= 0) - return cursorPosition + cursorOffset; - else - { - unsigned int nOffset = static_cast(-cursorOffset); - if (nOffset >= cursorPosition) - return 0; - else - return cursorPosition - nOffset; - } - }; - - Nz::Vector2ui cursorPosition = m_cursorPositionBegin; - cursorPosition.x = ClampOffset(static_cast(cursorPosition.x), offset.x); - cursorPosition.y = ClampOffset(static_cast(cursorPosition.y), offset.y); - - SetCursorPosition(cursorPosition); - } - - inline Nz::Vector2ui AbstractTextAreaWidget::NormalizeCursorPosition(Nz::Vector2ui cursorPosition) const - { - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - std::size_t lineCount = textDrawer.GetLineCount(); - if (cursorPosition.y >= lineCount) - cursorPosition.y = static_cast(lineCount - 1); - - const auto& lineInfo = textDrawer.GetLine(cursorPosition.y); - if (cursorPosition.y + 1 < lineCount) - { - const auto& nextLineInfo = textDrawer.GetLine(cursorPosition.y + 1); - cursorPosition.x = std::min(cursorPosition.x, static_cast(nextLineInfo.glyphIndex - lineInfo.glyphIndex - 1)); - } - - return cursorPosition; - } - - inline void AbstractTextAreaWidget::SetCharacterFilter(CharacterFilter filter) - { - m_characterFilter = std::move(filter); - } - - inline void AbstractTextAreaWidget::SetCursorPosition(std::size_t glyphIndex) - { - Nz::Vector2ui position = GetCursorPosition(glyphIndex); - Nz::Vector2ui newPosition = position; - - OnTextAreaCursorMove(this, &newPosition); - - if (position == newPosition) - SetCursorPositionInternal(position); - else - SetCursorPositionInternal(GetGlyphIndex(newPosition)); - } - - inline void AbstractTextAreaWidget::SetCursorPosition(Nz::Vector2ui cursorPosition) - { - OnTextAreaCursorMove(this, &cursorPosition); - - return SetCursorPositionInternal(NormalizeCursorPosition(cursorPosition)); - } - - inline void AbstractTextAreaWidget::SetEchoMode(EchoMode echoMode) - { - m_echoMode = echoMode; - - UpdateDisplayText(); - } - - inline void AbstractTextAreaWidget::SetReadOnly(bool readOnly) - { - m_readOnly = readOnly; - m_cursorEntity->Enable(!m_readOnly && HasFocus()); - } - - inline void AbstractTextAreaWidget::SetSelection(Nz::Vector2ui fromPosition, Nz::Vector2ui toPosition) - { - // Ensure begin is before end - if (toPosition.y < fromPosition.y || (toPosition.y == fromPosition.y && toPosition.x < fromPosition.x)) - std::swap(fromPosition, toPosition); - - if (m_cursorPositionBegin != fromPosition || m_cursorPositionEnd != toPosition) - { - OnTextAreaSelection(this, &fromPosition, &toPosition); - - // Ensure begin is before end a second time (in case signal changed it) - if (toPosition.y < fromPosition.y || (toPosition.y == fromPosition.y && toPosition.x < fromPosition.x)) - std::swap(fromPosition, toPosition); - - m_cursorPositionBegin = NormalizeCursorPosition(fromPosition); - m_cursorPositionEnd = NormalizeCursorPosition(toPosition); - - RefreshCursor(); - } - } - - inline void AbstractTextAreaWidget::Write(const Nz::String& text) - { - Write(text, GetGlyphIndex(m_cursorPositionBegin)); - } - - inline void AbstractTextAreaWidget::Write(const Nz::String& text, const Nz::Vector2ui& glyphPosition) - { - Write(text, GetGlyphIndex(glyphPosition)); - } - - void AbstractTextAreaWidget::SetCursorPositionInternal(std::size_t glyphIndex) - { - return SetCursorPositionInternal(GetCursorPosition(glyphIndex)); - } - - inline void AbstractTextAreaWidget::SetCursorPositionInternal(Nz::Vector2ui cursorPosition) - { - m_cursorPositionBegin = cursorPosition; - m_cursorPositionEnd = m_cursorPositionBegin; - - RefreshCursor(); - } -} diff --git a/SDK/include/NDK/Widgets/BoxLayout.hpp b/SDK/include/NDK/Widgets/BoxLayout.hpp deleted file mode 100644 index 698b5b2f8..000000000 --- a/SDK/include/NDK/Widgets/BoxLayout.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_BOXLAYOUT_HPP -#define NDK_WIDGETS_BOXLAYOUT_HPP - -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API BoxLayout : public BaseWidget - { - public: - BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation); - BoxLayout(const BoxLayout&) = delete; - BoxLayout(BoxLayout&&) = delete; - ~BoxLayout(); - - void Layout() override; - - BoxLayout& operator=(const BoxLayout&) = delete; - BoxLayout& operator=(BoxLayout&&) = delete; - - private: - struct State; - - std::unique_ptr m_state; - BoxLayoutOrientation m_orientation; - float m_spacing; - }; -} - -#include - -#endif // NDK_WIDGETS_BOXLAYOUT_HPP diff --git a/SDK/include/NDK/Widgets/ButtonWidget.hpp b/SDK/include/NDK/Widgets/ButtonWidget.hpp deleted file mode 100644 index a65429290..000000000 --- a/SDK/include/NDK/Widgets/ButtonWidget.hpp +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_BUTTONWIDGET_HPP -#define NDK_WIDGETS_BUTTONWIDGET_HPP - -#include -#include -#include -#include -#include - -namespace Nz -{ - class AbstractTextDrawer; -} - -namespace Ndk -{ - class NDK_API ButtonWidget : public BaseWidget - { - public: - ButtonWidget(BaseWidget* parent); - ButtonWidget(const ButtonWidget&) = delete; - ButtonWidget(ButtonWidget&&) = default; - ~ButtonWidget() = default; - - inline const Nz::Color& GetColor() const; - inline const Nz::Color& GetCornerColor() const; - inline const Nz::Color& GetHoverColor() const; - inline const Nz::Color& GetHoverCornerColor() const; - inline const Nz::Color& GetPressColor() const; - inline const Nz::Color& GetPressCornerColor() const; - - inline const Nz::TextureRef& GetTexture() const; - inline const Nz::TextureRef& GetHoverTexture() const; - inline const Nz::TextureRef& GetPressTexture() const; - - inline void SetColor(const Nz::Color& color, const Nz::Color& cornerColor); - inline void SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor); - inline void SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor); - - inline void SetTexture(const Nz::TextureRef& texture); - inline void SetHoverTexture(const Nz::TextureRef& texture); - inline void SetPressTexture(const Nz::TextureRef& texture); - - inline void UpdateText(const Nz::AbstractTextDrawer& drawer); - - ButtonWidget& operator=(const ButtonWidget&) = delete; - ButtonWidget& operator=(ButtonWidget&&) = default; - - static const Nz::Color& GetDefaultColor(); - static const Nz::Color& GetDefaultCornerColor(); - static const Nz::Color& GetDefaultHoverColor(); - static const Nz::Color& GetDefaultHoverCornerColor(); - static const Nz::Color& GetDefaultPressColor(); - static const Nz::Color& GetDefaultPressCornerColor(); - - NazaraSignal(OnButtonTrigger, const ButtonWidget* /*button*/); - - private: - void Layout() override; - - void OnMouseEnter() override; - void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) override; - void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override; - void OnMouseExit() override; - - EntityHandle m_textEntity; - EntityHandle m_gradientEntity; - Nz::SpriteRef m_gradientSprite; - Nz::TextSpriteRef m_textSprite; - - Nz::Color m_color; - Nz::Color m_cornerColor; - Nz::Color m_hoverColor; - Nz::Color m_hoverCornerColor; - Nz::Color m_pressColor; - Nz::Color m_pressCornerColor; - - Nz::TextureRef m_texture; - Nz::TextureRef m_hoverTexture; - Nz::TextureRef m_pressTexture; - - static Nz::Color s_color; - static Nz::Color s_cornerColor; - static Nz::Color s_hoverColor; - static Nz::Color s_hoverCornerColor; - static Nz::Color s_pressColor; - static Nz::Color s_pressCornerColor; - }; -} - -#include - -#endif // NDK_WIDGETS_BUTTONWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/ButtonWidget.inl b/SDK/include/NDK/Widgets/ButtonWidget.inl deleted file mode 100644 index 11cf202cf..000000000 --- a/SDK/include/NDK/Widgets/ButtonWidget.inl +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline const Nz::Color& ButtonWidget::GetColor() const - { - return m_color; - } - - inline const Nz::Color& ButtonWidget::GetCornerColor() const - { - return m_cornerColor; - } - - inline const Nz::Color& ButtonWidget::GetHoverColor() const - { - return m_hoverColor; - } - - inline const Nz::Color& ButtonWidget::GetHoverCornerColor() const - { - return m_hoverCornerColor; - } - - inline const Nz::Color& ButtonWidget::GetPressColor() const - { - return m_pressColor; - } - - inline const Nz::Color& ButtonWidget::GetPressCornerColor() const - { - return m_pressCornerColor; - } - - inline const Nz::TextureRef& ButtonWidget::GetTexture() const - { - return m_texture; - } - - inline const Nz::TextureRef& ButtonWidget::GetHoverTexture() const - { - return m_hoverTexture; - } - - inline const Nz::TextureRef& ButtonWidget::GetPressTexture() const - { - return m_pressTexture; - } - - inline void ButtonWidget::SetColor(const Nz::Color& color, const Nz::Color& cornerColor) - { - m_color = color; - m_cornerColor = cornerColor; - - m_gradientSprite->SetColor(m_color); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); - } - - inline void ButtonWidget::SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor) - { - m_hoverColor = color; - m_hoverCornerColor = cornerColor; - } - - inline void ButtonWidget::SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor) - { - m_pressColor = color; - m_pressCornerColor = cornerColor; - } - - inline void ButtonWidget::SetTexture(const Nz::TextureRef& texture) - { - m_texture = texture; - m_gradientSprite->SetTexture(m_texture); - } - - inline void ButtonWidget::SetHoverTexture(const Nz::TextureRef& texture) - { - m_hoverTexture = texture; - } - - inline void ButtonWidget::SetPressTexture(const Nz::TextureRef& texture) - { - m_pressTexture = texture; - } - - inline void ButtonWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) - { - m_textSprite->Update(drawer); - - Nz::Vector2f textSize = Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths()); - SetMinimumSize(textSize); - SetPreferredSize(textSize + Nz::Vector2f(20.f, 10.f)); - - Layout(); - } -} diff --git a/SDK/include/NDK/Widgets/CheckboxWidget.hpp b/SDK/include/NDK/Widgets/CheckboxWidget.hpp deleted file mode 100644 index a9723c20b..000000000 --- a/SDK/include/NDK/Widgets/CheckboxWidget.hpp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_CHECKBOXWIDGET_HPP -#define NDK_WIDGETS_CHECKBOXWIDGET_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Nz -{ - class AbstractTextDrawer; -} - -namespace Ndk -{ - class NDK_API CheckboxWidget : public BaseWidget - { - friend class Sdk; - - public: - CheckboxWidget(BaseWidget* parent); - CheckboxWidget(const CheckboxWidget&) = delete; - CheckboxWidget(CheckboxWidget&&) = default; - ~CheckboxWidget() = default; - - //virtual CheckboxWidget* Clone() const = 0; - - inline void EnableAdaptativeMargin(bool enable = true); - inline void EnableCheckbox(bool enable = true); - inline void EnableTristate(bool enable = true); - - inline bool IsCheckboxEnabled() const; - inline bool IsMarginAdaptative() const; - inline bool IsTristateEnabled() const; - - inline const Nz::Vector2f& GetCheckboxSize() const; - inline Nz::Vector2f GetCheckboxBorderSize() const; - inline CheckboxState GetState() const; - inline float GetTextMargin() const; - - inline void SetCheckboxSize(const Nz::Vector2f& size); - CheckboxState SwitchToNextState(); - void SetState(CheckboxState state); - inline void SetTextMargin(float margin); - - inline void UpdateText(const Nz::AbstractTextDrawer& drawer); - - - CheckboxWidget& operator=(const CheckboxWidget&) = delete; - CheckboxWidget& operator=(CheckboxWidget&&) = default; - - NazaraSignal(OnStateChanged, const CheckboxWidget* /*checkbox*/); - - private: - static bool Initialize(); - static void Uninitialize(); - - void Layout() override; - void UpdateCheckbox(); - void UpdateSize(); - - void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override; - inline bool ContainsCheckbox(int x, int y) const; - - - EntityHandle m_checkboxBorderEntity; - EntityHandle m_checkboxBackgroundEntity; - EntityHandle m_checkboxContentEntity; - EntityHandle m_textEntity; - - Nz::TextureRef m_checkMark; - - Nz::SpriteRef m_checkboxContentSprite; - Nz::SpriteRef m_checkboxBorderSprite; - Nz::SpriteRef m_checkboxBackgroundSprite; - Nz::TextSpriteRef m_textSprite; - - static Nz::Color s_backgroundColor; - static Nz::Color s_disabledBackgroundColor; - static Nz::Color s_disabledBorderColor; - static Nz::Color s_borderColor; - - bool m_adaptativeMargin; - bool m_checkboxEnabled; - bool m_tristateEnabled; - - static float s_borderScale; - float m_textMargin; - CheckboxState m_state; - }; -} - -#include - -#endif // NDK_WIDGETS_CHECKBOXWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/CheckboxWidget.inl b/SDK/include/NDK/Widgets/CheckboxWidget.inl deleted file mode 100644 index 5fa9e30ed..000000000 --- a/SDK/include/NDK/Widgets/CheckboxWidget.inl +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - inline void CheckboxWidget::EnableAdaptativeMargin(bool enable) - { - m_adaptativeMargin = enable; - Layout(); - } - - inline void CheckboxWidget::EnableCheckbox(bool enable) - { - m_checkboxEnabled = enable; - UpdateCheckbox(); - } - - inline void CheckboxWidget::EnableTristate(bool enable) - { - m_tristateEnabled = enable; - - if (m_tristateEnabled && GetState() == CheckboxState_Tristate) - SetState(CheckboxState_Unchecked); - } - - inline bool CheckboxWidget::IsCheckboxEnabled() const - { - return m_checkboxEnabled; - } - - inline bool CheckboxWidget::IsMarginAdaptative() const - { - return m_adaptativeMargin; - } - - inline bool CheckboxWidget::IsTristateEnabled() const - { - return m_tristateEnabled; - } - - inline const Nz::Vector2f& CheckboxWidget::GetCheckboxSize() const - { - return m_checkboxBorderSprite->GetSize(); - } - - inline Nz::Vector2f CheckboxWidget::GetCheckboxBorderSize() const - { - return GetCheckboxSize() / s_borderScale; - } - - inline CheckboxState CheckboxWidget::GetState() const - { - return m_state; - } - - inline float CheckboxWidget::GetTextMargin() const - { - return m_textMargin; - } - - inline void CheckboxWidget::SetCheckboxSize(const Nz::Vector2f& size) - { - m_checkboxBorderSprite->SetSize(size); - m_checkboxBackgroundSprite->SetSize(size - GetCheckboxBorderSize() * 2.f); - m_checkboxContentSprite->SetSize(GetCheckboxSize() - GetCheckboxBorderSize() * 2.f - Nz::Vector2f { 4.f, 4.f }); - - UpdateSize(); - Layout(); - } - - inline void CheckboxWidget::SetTextMargin(float margin) - { - m_textMargin = margin; - Layout(); - } - - inline void CheckboxWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) - { - m_textSprite->Update(drawer); - - UpdateSize(); - Layout(); - } - - inline bool CheckboxWidget::ContainsCheckbox(int x, int y) const - { - Nz::Vector2f checkboxSize = GetCheckboxSize(); - Nz::Vector3f pos = m_checkboxBorderEntity->GetComponent().GetPosition(Nz::CoordSys_Local); - - return x > pos.x && x < pos.x + checkboxSize.x && - y > pos.y && y < pos.y + checkboxSize.y; - } -} diff --git a/SDK/include/NDK/Widgets/Enums.hpp b/SDK/include/NDK/Widgets/Enums.hpp deleted file mode 100644 index a11511694..000000000 --- a/SDK/include/NDK/Widgets/Enums.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NAZARA_ENUMS_SDK_HPP -#define NAZARA_ENUMS_SDK_HPP - -namespace Ndk -{ - enum BoxLayoutOrientation - { - BoxLayoutOrientation_Horizontal, - BoxLayoutOrientation_Vertical - }; - - enum CheckboxState - { - CheckboxState_Checked, - CheckboxState_Tristate, - CheckboxState_Unchecked, - - CheckboxState_Max = CheckboxState_Unchecked - }; - - enum EchoMode - { - EchoMode_Normal, - EchoMode_Password, - EchoMode_PasswordExceptLast, - - EchoMode_Max = EchoMode_PasswordExceptLast - }; -} - -#endif // NAZARA_ENUMS_SDK_HPP diff --git a/SDK/include/NDK/Widgets/ImageWidget.hpp b/SDK/include/NDK/Widgets/ImageWidget.hpp deleted file mode 100644 index d95af8623..000000000 --- a/SDK/include/NDK/Widgets/ImageWidget.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_IMAGEWIDGET_HPP -#define NDK_WIDGETS_IMAGEWIDGET_HPP - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API ImageWidget : public BaseWidget - { - public: - ImageWidget(BaseWidget* parent); - ImageWidget(const ImageWidget&) = delete; - ImageWidget(ImageWidget&&) = default; - ~ImageWidget() = default; - - //virtual ImageWidget* Clone() const = 0; - - inline const Nz::Color& GetColor() const; - inline const Nz::TextureRef& GetTexture() const; - inline const Nz::Rectf& GetTextureCoords() const; - - inline void SetColor(const Nz::Color& color); - inline void SetTexture(const Nz::TextureRef& texture); - inline void SetTextureCoords(const Nz::Rectf& coords); - inline void SetTextureRect(const Nz::Rectui& rect); - - ImageWidget& operator=(const ImageWidget&) = delete; - ImageWidget& operator=(ImageWidget&&) = default; - - private: - void Layout() override; - - Ndk::EntityHandle m_entity; - Nz::SpriteRef m_sprite; - }; -} - -#include - -#endif // NDK_WIDGETS_IMAGEWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/ImageWidget.inl b/SDK/include/NDK/Widgets/ImageWidget.inl deleted file mode 100644 index b1835941b..000000000 --- a/SDK/include/NDK/Widgets/ImageWidget.inl +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline const Nz::Color& ImageWidget::GetColor() const - { - return m_sprite->GetColor(); - } - - inline const Nz::TextureRef& ImageWidget::GetTexture() const - { - return m_sprite->GetMaterial()->GetDiffuseMap(); - } - - inline const Nz::Rectf& ImageWidget::GetTextureCoords() const - { - return m_sprite->GetTextureCoords(); - } - - inline void ImageWidget::SetColor(const Nz::Color& color) - { - m_sprite->SetColor(color); - } - - inline void ImageWidget::SetTexture(const Nz::TextureRef& texture) - { - m_sprite->SetTexture(texture, false); - - Nz::Vector2f textureSize = Nz::Vector2f(Nz::Vector2ui(m_sprite->GetMaterial()->GetDiffuseMap()->GetSize())); - SetMinimumSize(textureSize); - SetPreferredSize(textureSize); - } - - inline void ImageWidget::SetTextureCoords(const Nz::Rectf& coords) - { - m_sprite->SetTextureCoords(coords); - } - - inline void ImageWidget::SetTextureRect(const Nz::Rectui& rect) - { - m_sprite->SetTextureRect(rect); - } -} diff --git a/SDK/include/NDK/Widgets/LabelWidget.hpp b/SDK/include/NDK/Widgets/LabelWidget.hpp deleted file mode 100644 index 6e3b89ee8..000000000 --- a/SDK/include/NDK/Widgets/LabelWidget.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_LABELWIDGET_HPP -#define NDK_WIDGETS_LABELWIDGET_HPP - -#include -#include -#include - -namespace Nz -{ - class AbstractTextDrawer; -} - -namespace Ndk -{ - class NDK_API LabelWidget : public BaseWidget - { - public: - LabelWidget(BaseWidget* parent); - LabelWidget(const LabelWidget&) = delete; - LabelWidget(LabelWidget&&) = default; - ~LabelWidget() = default; - - inline void UpdateText(const Nz::AbstractTextDrawer& drawer); - - LabelWidget& operator=(const LabelWidget&) = delete; - LabelWidget& operator=(LabelWidget&&) = default; - - private: - EntityHandle m_textEntity; - Nz::TextSpriteRef m_textSprite; - }; -} - -#include - -#endif // NDK_WIDGETS_LABELWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/LabelWidget.inl b/SDK/include/NDK/Widgets/LabelWidget.inl deleted file mode 100644 index cf14ea7d0..000000000 --- a/SDK/include/NDK/Widgets/LabelWidget.inl +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline void LabelWidget::UpdateText(const Nz::AbstractTextDrawer& drawer) - { - m_textSprite->Update(drawer); - - Nz::Vector2f size = Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths()); - SetMinimumSize(size); - SetPreferredSize(size); - } -} diff --git a/SDK/include/NDK/Widgets/ProgressBarWidget.hpp b/SDK/include/NDK/Widgets/ProgressBarWidget.hpp deleted file mode 100644 index 2ae334b8c..000000000 --- a/SDK/include/NDK/Widgets/ProgressBarWidget.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_PROGRESSBARWIDGET_HPP -#define NDK_WIDGETS_PROGRESSBARWIDGET_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - class NDK_API ProgressBarWidget : public BaseWidget - { - friend class Sdk; - - public: - ProgressBarWidget(BaseWidget* parent); - ProgressBarWidget(const ProgressBarWidget&) = delete; - ProgressBarWidget(ProgressBarWidget&&) = default; - ~ProgressBarWidget() = default; - - //virtual ProgressBarWidget* Clone() const = 0; - - inline void EnableText(bool enable = true); - inline void EnableBorder(bool enable = true); - - inline bool IsTextEnabled() const; - inline bool IsBorderEnabled() const; - - - inline unsigned GetPercentageValue() const; - inline Nz::Vector2f GetProgressBarSize() const; - inline Nz::Vector2f GetProgressBarBorderSize() const; - inline float GetTextMargin() const; - - - inline const Nz::Color& GetBarBackgroundColor() const; - inline const Nz::Color& GetBarBackgroundCornerColor() const; - inline const Nz::Color& GetBarColor() const; - inline const Nz::Color& GetBarCornerColor() const; - - inline const Nz::TextureRef& GetBarBackgroundTexture() const; - inline const Nz::TextureRef& GetBarTexture() const; - - static const Nz::Color& GetDefaultBarColor(); - static const Nz::Color& GetDefaultBarCornerColor(); - static const Nz::Color& GetDefaultBarBackgroundColor(); - static const Nz::Color& GetDefaultBarBackgroundCornerColor(); - - - inline void SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor); - inline void SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors = true); - inline void SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor); - inline void SetBarTexture(Nz::TextureRef texture, bool resetColors = true); - - - inline void SetPercentageValue(unsigned percentage); - inline void SetTextMargin(float margin); - inline void SetTextColor(const Nz::Color& color); - - NazaraSignal(OnValueChanged, const ProgressBarWidget* /*progressBar*/); - - private: - void Layout() override; - inline void UpdateText(); - - - EntityHandle m_borderEntity; - EntityHandle m_barEntity; - EntityHandle m_textEntity; - - static Nz::Color s_borderColor; - static Nz::Color s_barBackgroundColor; - static Nz::Color s_barBackgroundCornerColor; - static Nz::Color s_barColor; - static Nz::Color s_barCornerColor; - Nz::Color m_textColor; - - Nz::SpriteRef m_borderSprite; - Nz::SpriteRef m_barBackgroundSprite; - Nz::SpriteRef m_barSprite; - Nz::TextSpriteRef m_textSprite; - - static float s_borderScale; - float m_textMargin; - unsigned m_value; - }; -} - -#include - -#endif // NDK_WIDGETS_PROGRESSBARWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/ProgressBarWidget.inl b/SDK/include/NDK/Widgets/ProgressBarWidget.inl deleted file mode 100644 index 9fe2c8382..000000000 --- a/SDK/include/NDK/Widgets/ProgressBarWidget.inl +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -namespace Ndk -{ - inline void ProgressBarWidget::EnableText(bool enable) - { - m_textEntity->Enable(enable); - Layout(); - } - - inline void ProgressBarWidget::EnableBorder(bool enable) - { - m_borderEntity->Enable(enable); - } - - inline bool ProgressBarWidget::IsTextEnabled() const - { - return m_textEntity->IsEnabled(); - } - - inline bool ProgressBarWidget::IsBorderEnabled() const - { - return m_borderEntity->IsEnabled(); - } - - - inline unsigned ProgressBarWidget::GetPercentageValue() const - { - return m_value; - } - - inline Nz::Vector2f ProgressBarWidget::GetProgressBarSize() const - { - Nz::Vector3f progressBarSize = m_borderSprite->GetBoundingVolume().obb.localBox.GetLengths(); - - if (IsTextEnabled()) - { - Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); - progressBarSize -= { textSize.x + m_textMargin, 0.f, 0.f }; - } - - return { progressBarSize.x, progressBarSize.y }; - } - - inline Nz::Vector2f ProgressBarWidget::GetProgressBarBorderSize() const - { - Nz::Vector2f barSize = GetProgressBarSize(); - return { barSize.y / s_borderScale, barSize.y / s_borderScale }; - } - - inline float ProgressBarWidget::GetTextMargin() const - { - return m_textMargin; - } - - - inline const Nz::Color& ProgressBarWidget::GetBarBackgroundColor() const - { - return m_barBackgroundSprite->GetColor(); - } - - inline const Nz::Color& ProgressBarWidget::GetBarBackgroundCornerColor() const - { - return m_barBackgroundSprite->GetCornerColor(Nz::RectCorner_LeftTop); - } - - inline const Nz::Color& ProgressBarWidget::GetBarColor() const - { - return m_barSprite->GetColor(); - } - - inline const Nz::Color& ProgressBarWidget::GetBarCornerColor() const - { - return m_barSprite->GetCornerColor(Nz::RectCorner_LeftTop); - } - - - inline const Nz::TextureRef& ProgressBarWidget::GetBarBackgroundTexture() const - { - return m_barBackgroundSprite->GetMaterial()->GetDiffuseMap(); - } - - inline const Nz::TextureRef& ProgressBarWidget::GetBarTexture() const - { - return m_barSprite->GetMaterial()->GetDiffuseMap(); - } - - - inline void ProgressBarWidget::SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor) - { - m_barBackgroundSprite->SetColor(globalColor); - m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor); - m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor); - m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor); - m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor); - } - - inline void ProgressBarWidget::SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors) - { - m_barBackgroundSprite->SetTexture(texture, false); - - if (resetColors) - SetBarBackgroundColor(Nz::Color::White, Nz::Color::White); - } - - inline void ProgressBarWidget::SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor) - { - m_barSprite->SetColor(globalColor); - m_barSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor); - m_barSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor); - m_barSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor); - m_barSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor); - } - - inline void ProgressBarWidget::SetBarTexture(Nz::TextureRef texture, bool resetColors) - { - m_barSprite->SetTexture(texture, false); - - if (resetColors) - SetBarColor(Nz::Color::White, Nz::Color::White); - } - - - inline void ProgressBarWidget::SetPercentageValue(unsigned percentage) - { - m_value = percentage; - OnValueChanged(this); - Layout(); - } - - inline void ProgressBarWidget::SetTextMargin(float margin) - { - m_textMargin = margin; - - if (IsTextEnabled()) - Layout(); - } - - inline void ProgressBarWidget::SetTextColor(const Nz::Color& color) - { - m_textColor = color; - UpdateText(); - } - - inline void ProgressBarWidget::UpdateText() - { - if (IsTextEnabled()) - { - Nz::Vector2f size = GetSize(); - m_textSprite->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_value).Append('%'), static_cast(std::min(size.x, size.y) / 2.f), 0u, m_textColor)); - } - } -} diff --git a/SDK/include/NDK/Widgets/RichTextAreaWidget.hpp b/SDK/include/NDK/Widgets/RichTextAreaWidget.hpp deleted file mode 100644 index a21a233d2..000000000 --- a/SDK/include/NDK/Widgets/RichTextAreaWidget.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_RICHTEXTAREAWIDGET_HPP -#define NDK_WIDGETS_RICHTEXTAREAWIDGET_HPP - -#include -#include - -namespace Ndk -{ - class NDK_API RichTextAreaWidget : public AbstractTextAreaWidget - { - public: - RichTextAreaWidget(BaseWidget* parent); - RichTextAreaWidget(const RichTextAreaWidget&) = delete; - RichTextAreaWidget(RichTextAreaWidget&&) = default; - ~RichTextAreaWidget() = default; - - void AppendText(const Nz::String& text); - - void Clear() override; - - void Erase(std::size_t firstGlyph, std::size_t lastGlyph) override; - - inline unsigned int GetCharacterSize() const; - inline float GetCharacterSpacingOffset() const; - inline float GetLineSpacingOffset() const; - inline const Nz::Color& GetTextColor() const; - inline Nz::Font* GetTextFont() const; - inline const Nz::Color& GetTextOutlineColor() const; - inline float GetTextOutlineThickness() const; - inline Nz::TextStyleFlags GetTextStyle() const; - - inline void SetCharacterSize(unsigned int characterSize); - inline void SetCharacterSpacingOffset(float offset); - inline void SetLineSpacingOffset(float offset); - inline void SetTextColor(const Nz::Color& color); - inline void SetTextFont(Nz::FontRef font); - inline void SetTextOutlineColor(const Nz::Color& color); - inline void SetTextOutlineThickness(float thickness); - inline void SetTextStyle(Nz::TextStyleFlags style); - - void Write(const Nz::String& text, std::size_t glyphPosition) override; - - RichTextAreaWidget& operator=(const RichTextAreaWidget&) = delete; - RichTextAreaWidget& operator=(RichTextAreaWidget&&) = default; - - private: - Nz::AbstractTextDrawer& GetTextDrawer() override; - const Nz::AbstractTextDrawer& GetTextDrawer() const override; - - void HandleIndentation(bool add) override; - void HandleSelectionIndentation(bool add) override; - void HandleWordCursorMove(bool left) override; - - void UpdateDisplayText() override; - - Nz::RichTextDrawer m_drawer; - }; -} - -#include - -#endif // NDK_WIDGETS_TEXTAREAWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/RichTextAreaWidget.inl b/SDK/include/NDK/Widgets/RichTextAreaWidget.inl deleted file mode 100644 index 4fd7faa10..000000000 --- a/SDK/include/NDK/Widgets/RichTextAreaWidget.inl +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline unsigned int RichTextAreaWidget::GetCharacterSize() const - { - return m_drawer.GetDefaultCharacterSize(); - } - - inline float RichTextAreaWidget::GetCharacterSpacingOffset() const - { - return m_drawer.GetDefaultCharacterSpacingOffset(); - } - - inline float RichTextAreaWidget::GetLineSpacingOffset() const - { - return m_drawer.GetDefaultLineSpacingOffset(); - } - - inline const Nz::Color& RichTextAreaWidget::GetTextColor() const - { - return m_drawer.GetDefaultColor(); - } - - inline Nz::Font* RichTextAreaWidget::GetTextFont() const - { - return m_drawer.GetDefaultFont(); - } - - inline const Nz::Color& RichTextAreaWidget::GetTextOutlineColor() const - { - return m_drawer.GetDefaultOutlineColor(); - } - - inline float RichTextAreaWidget::GetTextOutlineThickness() const - { - return m_drawer.GetDefaultOutlineThickness(); - } - - inline Nz::TextStyleFlags RichTextAreaWidget::GetTextStyle() const - { - return m_drawer.GetDefaultStyle(); - } - - inline void RichTextAreaWidget::SetCharacterSize(unsigned int characterSize) - { - m_drawer.SetDefaultCharacterSize(characterSize); - } - - inline void RichTextAreaWidget::SetCharacterSpacingOffset(float offset) - { - m_drawer.SetDefaultCharacterSpacingOffset(offset); - } - - inline void RichTextAreaWidget::SetLineSpacingOffset(float offset) - { - m_drawer.SetDefaultLineSpacingOffset(offset); - } - - inline void RichTextAreaWidget::SetTextColor(const Nz::Color& color) - { - m_drawer.SetDefaultColor(color); - } - - inline void RichTextAreaWidget::SetTextFont(Nz::FontRef font) - { - m_drawer.SetDefaultFont(std::move(font)); - } - - inline void RichTextAreaWidget::SetTextOutlineColor(const Nz::Color& color) - { - m_drawer.SetDefaultOutlineColor(color); - } - - inline void RichTextAreaWidget::SetTextOutlineThickness(float thickness) - { - m_drawer.SetDefaultOutlineThickness(thickness); - } - - inline void RichTextAreaWidget::SetTextStyle(Nz::TextStyleFlags style) - { - m_drawer.SetDefaultStyle(style); - } -} diff --git a/SDK/include/NDK/Widgets/ScrollAreaWidget.hpp b/SDK/include/NDK/Widgets/ScrollAreaWidget.hpp deleted file mode 100644 index 17ada16ef..000000000 --- a/SDK/include/NDK/Widgets/ScrollAreaWidget.hpp +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) 2019 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_SCROLLAREAWIDGET_HPP -#define NDK_WIDGETS_SCROLLAREAWIDGET_HPP - -#include -#include -#include - -namespace Ndk -{ - class NDK_API ScrollAreaWidget : public BaseWidget - { - public: - ScrollAreaWidget(BaseWidget* parent, BaseWidget* content); - ScrollAreaWidget(const ScrollAreaWidget&) = delete; - ScrollAreaWidget(ScrollAreaWidget&&) = default; - ~ScrollAreaWidget() = default; - - void EnableScrollbar(bool enable); - - inline float GetScrollHeight() const; - inline float GetScrollRatio() const; - - inline bool HasScrollbar() const; - inline bool IsScrollbarEnabled() const; - inline bool IsScrollbarVisible() const; - - inline void ScrollToHeight(float height); - void ScrollToRatio(float ratio); - - ScrollAreaWidget& operator=(const ScrollAreaWidget&) = delete; - ScrollAreaWidget& operator=(ScrollAreaWidget&&) = default; - - private: - enum class ScrollBarStatus - { - Grabbed, - Hovered, - None - }; - - Nz::Rectf GetScrollbarRect() const; - - void Layout() override; - - void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) override; - void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override; - void OnMouseExit() override; - void OnMouseMoved(int x, int y, int deltaX, int deltaY) override; - void OnMouseWheelMoved(int x, int y, float delta) override; - - void UpdateScrollbarStatus(ScrollBarStatus status); - - BaseWidget* m_content; - EntityHandle m_scrollbarBackgroundEntity; - EntityHandle m_scrollbarEntity; - Nz::SpriteRef m_scrollbarBackgroundSprite; - Nz::SpriteRef m_scrollbarSprite; - Nz::Vector2i m_grabbedDelta; - ScrollBarStatus m_scrollbarStatus; - bool m_isScrollbarEnabled; - bool m_hasScrollbar; - float m_scrollRatio; - }; -} - -#include - -#endif // NDK_WIDGETS_SCROLLAREAWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/ScrollAreaWidget.inl b/SDK/include/NDK/Widgets/ScrollAreaWidget.inl deleted file mode 100644 index 89bea6d47..000000000 --- a/SDK/include/NDK/Widgets/ScrollAreaWidget.inl +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2019 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline float ScrollAreaWidget::GetScrollHeight() const - { - return m_scrollRatio * m_content->GetHeight(); - } - - inline float ScrollAreaWidget::GetScrollRatio() const - { - return m_scrollRatio; - } - - inline bool ScrollAreaWidget::HasScrollbar() const - { - return m_hasScrollbar; - } - - inline bool ScrollAreaWidget::IsScrollbarEnabled() const - { - return m_isScrollbarEnabled; - } - - inline bool ScrollAreaWidget::IsScrollbarVisible() const - { - return HasScrollbar() && IsScrollbarEnabled(); - } - - inline void ScrollAreaWidget::ScrollToHeight(float height) - { - float contentHeight = m_content->GetHeight(); - ScrollToRatio(height / contentHeight); - } -} diff --git a/SDK/include/NDK/Widgets/TextAreaWidget.hpp b/SDK/include/NDK/Widgets/TextAreaWidget.hpp deleted file mode 100644 index 8b06e7579..000000000 --- a/SDK/include/NDK/Widgets/TextAreaWidget.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#pragma once - -#ifndef NDK_WIDGETS_TEXTAREAWIDGET_HPP -#define NDK_WIDGETS_TEXTAREAWIDGET_HPP - -#include -#include - -namespace Ndk -{ - class NDK_API TextAreaWidget : public AbstractTextAreaWidget - { - public: - TextAreaWidget(BaseWidget* parent); - TextAreaWidget(const TextAreaWidget&) = delete; - TextAreaWidget(TextAreaWidget&&) = default; - ~TextAreaWidget() = default; - - void AppendText(const Nz::String& text); - - void Clear() override; - - using AbstractTextAreaWidget::Erase; - void Erase(std::size_t firstGlyph, std::size_t lastGlyph) override; - - inline unsigned int GetCharacterSize() const; - inline const Nz::String& GetDisplayText() const; - inline float GetCharacterSpacingOffset() const; - inline float GetLineSpacingOffset() const; - inline const Nz::String& GetText() const; - inline const Nz::Color& GetTextColor() const; - inline Nz::Font* GetTextFont() const; - inline const Nz::Color& GetTextOulineColor() const; - inline float GetTextOulineThickness() const; - inline Nz::TextStyleFlags GetTextStyle() const; - - inline void SetCharacterSize(unsigned int characterSize); - inline void SetCharacterSpacingOffset(float offset); - inline void SetLineSpacingOffset(float offset); - inline void SetText(const Nz::String& text); - inline void SetTextColor(const Nz::Color& text); - inline void SetTextFont(Nz::FontRef font); - inline void SetTextOutlineColor(const Nz::Color& color); - inline void SetTextOutlineThickness(float thickness); - inline void SetTextStyle(Nz::TextStyleFlags style); - - using AbstractTextAreaWidget::Write; - void Write(const Nz::String& text, std::size_t glyphPosition) override; - - TextAreaWidget& operator=(const TextAreaWidget&) = delete; - TextAreaWidget& operator=(TextAreaWidget&&) = default; - - NazaraSignal(OnTextChanged, const AbstractTextAreaWidget* /*textArea*/, const Nz::String& /*text*/); - - private: - Nz::AbstractTextDrawer& GetTextDrawer() override; - const Nz::AbstractTextDrawer& GetTextDrawer() const override; - - void HandleIndentation(bool add) override; - void HandleSelectionIndentation(bool add) override; - void HandleWordCursorMove(bool left) override; - - void UpdateDisplayText() override; - void UpdateMinimumSize(); - - Nz::SimpleTextDrawer m_drawer; - Nz::String m_text; - }; -} - -#include - -#endif // NDK_WIDGETS_TEXTAREAWIDGET_HPP diff --git a/SDK/include/NDK/Widgets/TextAreaWidget.inl b/SDK/include/NDK/Widgets/TextAreaWidget.inl deleted file mode 100644 index f63897420..000000000 --- a/SDK/include/NDK/Widgets/TextAreaWidget.inl +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - inline unsigned int TextAreaWidget::GetCharacterSize() const - { - return m_drawer.GetCharacterSize(); - } - - inline const Nz::String& TextAreaWidget::GetDisplayText() const - { - return m_drawer.GetText(); - } - - inline float TextAreaWidget::GetCharacterSpacingOffset() const - { - return m_drawer.GetCharacterSpacingOffset(); - } - - inline float TextAreaWidget::GetLineSpacingOffset() const - { - return m_drawer.GetLineSpacingOffset(); - } - - inline const Nz::String& TextAreaWidget::GetText() const - { - return m_text; - } - - inline const Nz::Color& TextAreaWidget::GetTextColor() const - { - return m_drawer.GetColor(); - } - - inline Nz::Font* TextAreaWidget::GetTextFont() const - { - return m_drawer.GetFont(); - } - - inline const Nz::Color& TextAreaWidget::GetTextOulineColor() const - { - return m_drawer.GetOutlineColor(); - } - - inline float TextAreaWidget::GetTextOulineThickness() const - { - return m_drawer.GetOutlineThickness(); - } - - inline Nz::TextStyleFlags TextAreaWidget::GetTextStyle() const - { - return m_drawer.GetStyle(); - } - - inline void TextAreaWidget::SetCharacterSize(unsigned int characterSize) - { - m_drawer.SetCharacterSize(characterSize); - - UpdateMinimumSize(); - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetCharacterSpacingOffset(float offset) - { - m_drawer.SetCharacterSpacingOffset(offset); - - UpdateMinimumSize(); - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetLineSpacingOffset(float offset) - { - m_drawer.SetLineSpacingOffset(offset); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetText(const Nz::String& text) - { - m_text = text; - OnTextChanged(this, m_text); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetTextColor(const Nz::Color& text) - { - m_drawer.SetColor(text); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetTextFont(Nz::FontRef font) - { - m_drawer.SetFont(font); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetTextOutlineColor(const Nz::Color& color) - { - m_drawer.SetOutlineColor(color); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetTextOutlineThickness(float thickness) - { - m_drawer.SetOutlineThickness(thickness); - - UpdateDisplayText(); - } - - inline void TextAreaWidget::SetTextStyle(Nz::TextStyleFlags style) - { - m_drawer.SetStyle(style); - - UpdateDisplayText(); - } -} diff --git a/SDK/src/NDK/Application.cpp b/SDK/src/NDK/Application.cpp deleted file mode 100644 index 132947d4e..000000000 --- a/SDK/src/NDK/Application.cpp +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include - -#ifndef NDK_SERVER -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::Application - * \brief NDK class that represents the application, it offers a set of tools to ease the development - */ - - /*! - * \brief Constructs an Application object with command-line arguments - * - * Pass the argc and argv arguments from the main function. - * - * Command-line arguments can be retrieved by application methods - * - * This calls Sdk::Initialize() - * - * \remark Only one Application instance can exist at a time - */ - Application::Application(int argc, char* argv[]) : - Application() - { - std::regex optionRegex(R"(-(\w+))"); - std::regex valueRegex(R"(-(\w+)\s*=\s*(.+))"); - - std::smatch results; - - for (int i = 1; i < argc; ++i) - { - std::string argument(argv[i]); - if (std::regex_match(argument, results, valueRegex)) - { - Nz::String key(results[1].str()); - Nz::String value(results[2].str()); - - m_parameters[key.ToLower()] = value; - NazaraDebug("Registred parameter from command-line: " + key.ToLower() + "=" + value); - } - else if (std::regex_match(argument, results, optionRegex)) - { - Nz::String option(results[1].str()); - - m_options.insert(option); - NazaraDebug("Registred option from command-line: " + option); - } - else - NazaraWarning("Ignored command-line argument #" + Nz::String::Number(i) + " \"" + argument + '"'); - } - - #ifndef NDK_SERVER - if (HasOption("console")) - EnableConsole(true); - - if (HasOption("fpscounter")) - EnableFPSCounter(true); - #endif - } - - /*! - * \brief Runs the application by updating worlds, taking care about windows, ... - */ - bool Application::Run() - { - #ifndef NDK_SERVER - bool hasAtLeastOneActiveWindow = false; - - auto it = m_windows.begin(); - while (it != m_windows.end()) - { - Nz::Window& window = *it->window; - - window.ProcessEvents(); - - if (!window.IsOpen(true)) - { - it = m_windows.erase(it); - continue; - } - - hasAtLeastOneActiveWindow = true; - - ++it; - } - - if (m_exitOnClosedWindows && !hasAtLeastOneActiveWindow) - return false; - #endif - - if (m_shouldQuit) - return false; - - m_updateTime = m_updateClock.Restart() / 1'000'000.f; - - for (World& world : m_worlds) - world.Update(m_updateTime); - - #ifndef NDK_SERVER - for (WindowInfo& info : m_windows) - { - if (!info.overlayWorld) - continue; - - if (info.fpsCounter) - { - FPSCounterOverlay& fpsCounter = *info.fpsCounter; - - fpsCounter.frameCount++; - - fpsCounter.elapsedTime += m_updateTime; - if (fpsCounter.elapsedTime >= 1.f) - { - fpsCounter.sprite->Update(Nz::SimpleTextDrawer::Draw("FPS: " + Nz::String::Number(fpsCounter.frameCount), 36)); - fpsCounter.frameCount = 0; - fpsCounter.elapsedTime = 0.f; - } - } - - info.overlayWorld->Update(m_updateTime); - } - #endif - - return true; - } - - #ifndef NDK_SERVER - void Application::SetupConsole(WindowInfo& info) - { - std::unique_ptr overlay = std::make_unique(); - - Nz::Vector2ui windowDimensions; - if (info.window->IsValid()) - windowDimensions = info.window->GetSize(); - else - windowDimensions.MakeZero(); - - Nz::LuaInstance& lua = overlay->lua; - - overlay->console = info.canvas->Add(); - overlay->console->OnCommand.Connect([&lua](Ndk::Console* console, const Nz::String& command) - { - if (!lua.Execute(command)) - console->AddLine(lua.GetLastError(), Nz::Color::Red); - }); - - Console& consoleRef = *overlay->console; - consoleRef.Resize({float(windowDimensions.x), windowDimensions.y / 4.f}); - consoleRef.Show(false); - - // Redirect logs toward the console - overlay->logSlot.Connect(Nz::Log::OnLogWrite, [&consoleRef] (const Nz::String& str) - { - consoleRef.AddLine(str); - }); - - lua.LoadLibraries(); - LuaAPI::RegisterClasses(lua); - - // Override "print" function to add a line in the console - lua.PushFunction([&consoleRef] (Nz::LuaState& state) - { - Nz::StringStream stream; - - unsigned int argCount = state.GetStackTop(); - state.GetGlobal("tostring"); - for (unsigned int i = 1; i <= argCount; ++i) - { - state.PushValue(-1); // tostring function - state.PushValue(i); // argument - state.Call(1, 1); - - std::size_t length; - const char* str = state.CheckString(-1, &length); - if (i > 1) - stream << '\t'; - - stream << Nz::String(str, length); - state.Pop(1); - } - - consoleRef.AddLine(stream); - return 0; - }); - lua.SetGlobal("print"); - - // Define a few base variables to allow our interface to interact with the application - lua.PushGlobal("Application", Ndk::Application::Instance()); - lua.PushGlobal("Console", consoleRef.CreateHandle()); - - // Setup a few event callback to handle the console - Nz::EventHandler& eventHandler = info.window->GetEventHandler(); - - overlay->keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&consoleRef] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& event) - { - if (event.virtualKey == Nz::Keyboard::VKey::F9) - { - // Toggle console visibility and focus - if (consoleRef.IsVisible()) - { - consoleRef.ClearFocus(); - consoleRef.Show(false); - } - else - { - consoleRef.Show(true); - consoleRef.SetFocus(); - } - } - }); - - overlay->resizedSlot.Connect(info.renderTarget->OnRenderTargetSizeChange, [&consoleRef] (const Nz::RenderTarget* renderTarget) - { - Nz::Vector2ui size = renderTarget->GetSize(); - consoleRef.Resize({float(size.x), size.y / 4.f}); - }); - - info.console = std::move(overlay); - } - - void Application::SetupFPSCounter(WindowInfo& info) - { - std::unique_ptr fpsCounter = std::make_unique(); - fpsCounter->sprite = Nz::TextSprite::New(); - - fpsCounter->entity = info.overlayWorld->CreateEntity(); - fpsCounter->entity->AddComponent(); - fpsCounter->entity->AddComponent().Attach(fpsCounter->sprite); - - info.fpsCounter = std::move(fpsCounter); - } - - void Application::SetupOverlay(WindowInfo& info) - { - info.overlayWorld = std::make_unique(false); //< No default system - - if (info.window->IsValid()) - info.canvas = std::make_unique(info.overlayWorld->CreateHandle(), info.window->GetEventHandler(), info.window->GetCursorController().CreateHandle()); - - RenderSystem& renderSystem = info.overlayWorld->AddSystem(); - renderSystem.ChangeRenderTechnique(); - renderSystem.SetDefaultBackground(nullptr); - renderSystem.SetGlobalUp(Nz::Vector3f::Down()); - - EntityHandle viewer = info.overlayWorld->CreateEntity(); - CameraComponent& camComponent = viewer->AddComponent(); - viewer->AddComponent(); - - camComponent.SetProjectionType(Nz::ProjectionType_Orthogonal); - camComponent.SetTarget(info.renderTarget); - } - #endif - - Application* Application::s_application = nullptr; -} diff --git a/SDK/src/NDK/BaseWidget.cpp b/SDK/src/NDK/BaseWidget.cpp deleted file mode 100644 index 6cee67002..000000000 --- a/SDK/src/NDK/BaseWidget.cpp +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::BaseWidget - * \brief Abstract class serving as a base class for all widgets - */ - - /*! - * \brief Constructs a BaseWidget object using another widget as its parent - * - * \param parent Parent widget, must be valid and attached to a canvas - * - * Constructs a BaseWidget object using another widget as a base. - * This will also register the widget to the canvas owning the top-most widget. - */ - BaseWidget::BaseWidget(BaseWidget* parent) : - BaseWidget() - { - NazaraAssert(parent, "Invalid parent"); - NazaraAssert(parent->GetCanvas(), "Parent has no canvas"); - - m_canvas = parent->GetCanvas(); - m_widgetParent = parent; - m_world = m_canvas->GetWorld(); - - RegisterToCanvas(); - } - - /*! - * \brief Frees the widget, unregistering it from its canvas - */ - BaseWidget::~BaseWidget() - { - UnregisterFromCanvas(); - } - - /*! - * \brief Clears keyboard focus if and only if this widget owns it. - */ - void BaseWidget::ClearFocus() - { - if (IsRegisteredToCanvas()) - m_canvas->ClearKeyboardOwner(m_canvasIndex); - } - - /*! - * \brief Destroy the widget, deleting it in the process. - * - * Calling this function immediately destroys the widget, freeing its memory. - */ - void BaseWidget::Destroy() - { - NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()"); - - m_widgetParent->DestroyChild(this); //< This does delete us - } - - /*! - * \brief Enable or disables the widget background. - */ - void BaseWidget::EnableBackground(bool enable) - { - if (m_backgroundEntity.IsValid() == enable) - return; - - if (enable) - { - m_backgroundSprite = Nz::Sprite::New(); - m_backgroundSprite->SetColor(m_backgroundColor); - m_backgroundSprite->SetMaterial(Nz::Material::New((m_backgroundColor.IsOpaque()) ? "Basic2D" : "Translucent2D")); //< TODO: Use a shared material instead of creating one everytime - - m_backgroundEntity = CreateEntity(); - m_backgroundEntity->AddComponent().Attach(m_backgroundSprite, -1); - m_backgroundEntity->AddComponent().SetParent(this); - - BaseWidget::Layout(); // Only layout background - } - else - { - DestroyEntity(m_backgroundEntity); - m_backgroundEntity.Reset(); - m_backgroundSprite.Reset(); - } - } - - /*! - * \brief Checks if this widget has keyboard focus - * \return true if widget has keyboard focus, false otherwise - */ - bool BaseWidget::HasFocus() const - { - if (!IsRegisteredToCanvas()) - return false; - - return m_canvas->IsKeyboardOwner(m_canvasIndex); - } - - void BaseWidget::Resize(const Nz::Vector2f& size) - { - // Adjust new size - Nz::Vector2f newSize = size; - newSize.Maximize(m_minimumSize); - newSize.Minimize(m_maximumSize); - - NotifyParentResized(newSize); - m_size = newSize; - - Layout(); - } - - void BaseWidget::SetBackgroundColor(const Nz::Color& color) - { - m_backgroundColor = color; - - if (m_backgroundSprite) - { - m_backgroundSprite->SetColor(color); - m_backgroundSprite->GetMaterial()->Configure((color.IsOpaque()) ? "Basic2D" : "Translucent2D"); //< Our sprite has its own material (see EnableBackground) - } - } - - void BaseWidget::SetCursor(Nz::SystemCursor systemCursor) - { - m_cursor = systemCursor; - - if (IsRegisteredToCanvas()) - m_canvas->NotifyWidgetCursorUpdate(m_canvasIndex); - } - - void BaseWidget::SetFocus() - { - if (IsRegisteredToCanvas()) - m_canvas->SetKeyboardOwner(m_canvasIndex); - } - - void BaseWidget::SetParent(BaseWidget* widget) - { - Canvas* oldCanvas = m_canvas; - Canvas* newCanvas = widget->GetCanvas(); - - // Changing a widget canvas is a problem because of the canvas entities - NazaraAssert(oldCanvas == newCanvas, "Transferring a widget between canvas is not yet supported"); - - Node::SetParent(widget); - m_widgetParent = widget; - - Layout(); - } - - void BaseWidget::SetRenderingRect(const Nz::Rectf& renderingRect) - { - m_renderingRect = renderingRect; - - UpdatePositionAndSize(); - for (const auto& widgetPtr : m_children) - widgetPtr->UpdatePositionAndSize(); - } - - void BaseWidget::Show(bool show) - { - if (m_visible != show) - { - m_visible = show; - - if (m_visible) - RegisterToCanvas(); - else - UnregisterFromCanvas(); - - for (WidgetEntity& entity : m_entities) - { - if (entity.isEnabled) - { - entity.handle->Enable(show); //< This will override isEnabled, so reset it next line - entity.isEnabled = true; - } - } - - ShowChildren(show); - } - } - - const EntityHandle& BaseWidget::CreateEntity() - { - const EntityHandle& newEntity = m_world->CreateEntity(); - newEntity->Enable(m_visible); - - m_entities.emplace_back(); - WidgetEntity& newWidgetEntity = m_entities.back(); - newWidgetEntity.handle = newEntity; - newWidgetEntity.onDisabledSlot.Connect(newEntity->OnEntityDisabled, [this](Entity* entity) - { - auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); - NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); - - it->isEnabled = false; - }); - - newWidgetEntity.onEnabledSlot.Connect(newEntity->OnEntityEnabled, [this](Entity* entity) - { - auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); - NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); - - if (!IsVisible()) - entity->Disable(); // Next line will override isEnabled status - - it->isEnabled = true; - }); - - return newEntity; - } - - void BaseWidget::DestroyEntity(Entity* entity) - { - auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; }); - NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget"); - - m_entities.erase(it); - } - - void BaseWidget::Layout() - { - if (m_backgroundSprite) - m_backgroundSprite->SetSize(m_size.x, m_size.y); - - UpdatePositionAndSize(); - } - - void BaseWidget::InvalidateNode() - { - Node::InvalidateNode(); - - UpdatePositionAndSize(); - } - - Nz::Rectf BaseWidget::GetScissorRect() const - { - Nz::Vector2f widgetPos = Nz::Vector2f(GetPosition(Nz::CoordSys_Global)); - Nz::Vector2f widgetSize = GetSize(); - - Nz::Rectf widgetRect(widgetPos.x, widgetPos.y, widgetSize.x, widgetSize.y); - Nz::Rectf widgetRenderingRect(widgetPos.x + m_renderingRect.x, widgetPos.y + m_renderingRect.y, m_renderingRect.width, m_renderingRect.height); - - widgetRect.Intersect(widgetRenderingRect, &widgetRect); - - return widgetRect; - } - - bool BaseWidget::IsFocusable() const - { - return false; - } - - void BaseWidget::OnFocusLost() - { - } - - void BaseWidget::OnFocusReceived() - { - } - - bool BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) - { - return false; - } - - void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) - { - } - - void BaseWidget::OnMouseEnter() - { - } - - void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/) - { - } - - void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) - { - } - - void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/) - { - } - - void BaseWidget::OnMouseWheelMoved(int /*x*/, int /*y*/, float /*delta*/) - { - } - - void BaseWidget::OnMouseExit() - { - } - - void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/) - { - } - - void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/) - { - } - - void BaseWidget::OnTextEdited(const std::array& /*characters*/, int /*length*/) - { - } - - void BaseWidget::ShowChildren(bool show) - { - for (const auto& widgetPtr : m_children) - widgetPtr->Show(show); - } - - void BaseWidget::DestroyChild(BaseWidget* widget) - { - auto it = std::find_if(m_children.begin(), m_children.end(), [widget] (const std::unique_ptr& widgetPtr) -> bool - { - return widgetPtr.get() == widget; - }); - - NazaraAssert(it != m_children.end(), "Child widget not found in parent"); - - m_children.erase(it); - } - - void BaseWidget::DestroyChildren() - { - m_children.clear(); - } - - void BaseWidget::RegisterToCanvas() - { - NazaraAssert(!IsRegisteredToCanvas(), "Widget is already registered to canvas"); - - m_canvasIndex = m_canvas->RegisterWidget(this); - } - - void BaseWidget::UnregisterFromCanvas() - { - if (IsRegisteredToCanvas()) - { - m_canvas->UnregisterWidget(m_canvasIndex); - m_canvasIndex = InvalidCanvasIndex; - } - } - - void BaseWidget::UpdatePositionAndSize() - { - if (IsRegisteredToCanvas()) - m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex); - - Nz::Rectf scissorRect = GetScissorRect(); - - if (m_widgetParent) - { - Nz::Rectf parentScissorRect = m_widgetParent->GetScissorRect(); - - if (!scissorRect.Intersect(parentScissorRect, &scissorRect)) - scissorRect = parentScissorRect; - } - - Nz::Recti fullBounds(scissorRect); - for (WidgetEntity& widgetEntity : m_entities) - { - const Ndk::EntityHandle& entity = widgetEntity.handle; - if (entity->HasComponent()) - entity->GetComponent().SetScissorRect(fullBounds); - } - } -} diff --git a/SDK/src/NDK/Canvas.cpp b/SDK/src/NDK/Canvas.cpp deleted file mode 100644 index e80e2890e..000000000 --- a/SDK/src/NDK/Canvas.cpp +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - std::size_t Canvas::RegisterWidget(BaseWidget* widget) - { - WidgetEntry box; - box.cursor = widget->GetCursor(); - box.widget = widget; - - std::size_t index = m_widgetEntries.size(); - m_widgetEntries.emplace_back(box); - - NotifyWidgetBoxUpdate(index); - return index; - } - - void Canvas::UnregisterWidget(std::size_t index) - { - WidgetEntry& entry = m_widgetEntries[index]; - - if (m_hoveredWidget == index) - m_hoveredWidget = InvalidCanvasIndex; - - if (m_keyboardOwner == index) - m_keyboardOwner = InvalidCanvasIndex; - - if (m_widgetEntries.size() > 1U) - { - WidgetEntry& lastEntry = m_widgetEntries.back(); - std::size_t lastEntryIndex = m_widgetEntries.size() - 1; - - entry = std::move(lastEntry); - entry.widget->UpdateCanvasIndex(index); - - if (m_hoveredWidget == lastEntryIndex) - m_hoveredWidget = index; - - if (m_keyboardOwner == lastEntryIndex) - m_keyboardOwner = index; - } - - m_widgetEntries.pop_back(); - } - - void Canvas::OnEventMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event) - { - if (m_hoveredWidget != InvalidCanvasIndex) - { - WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget]; - - int x = static_cast(std::round(event.x - hoveredWidget.box.x)); - int y = static_cast(std::round(event.y - hoveredWidget.box.y)); - - hoveredWidget.widget->OnMouseButtonPress(x, y, event.button); - } - } - - void Canvas::OnEventMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event) - { - if (m_hoveredWidget != InvalidCanvasIndex) - { - WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget]; - - int x = static_cast(std::round(event.x - hoveredWidget.box.x)); - int y = static_cast(std::round(event.y - hoveredWidget.box.y)); - - hoveredWidget.widget->OnMouseButtonRelease(x, y, event.button); - } - } - - void Canvas::OnEventMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event) - { - std::size_t bestEntry = InvalidCanvasIndex; - float bestEntryArea = std::numeric_limits::infinity(); - - Nz::Vector3f mousePos(float(event.x), float(event.y), 0.f); - for (std::size_t i = 0; i < m_widgetEntries.size(); ++i) - { - const Nz::Boxf& box = m_widgetEntries[i].box; - - if (box.Contains(mousePos)) - { - float area = box.width * box.height; - if (area < bestEntryArea) - { - bestEntry = i; - bestEntryArea = area; - } - } - } - - if (bestEntry != InvalidCanvasIndex) - { - if (m_hoveredWidget != bestEntry) - { - if (m_hoveredWidget != InvalidCanvasIndex) - { - WidgetEntry& previouslyHovered = m_widgetEntries[m_hoveredWidget]; - previouslyHovered.widget->OnMouseExit(); - } - - m_hoveredWidget = bestEntry; - m_widgetEntries[m_hoveredWidget].widget->OnMouseEnter(); - - if (m_cursorController) - m_cursorController->UpdateCursor(Nz::Cursor::Get(m_widgetEntries[m_hoveredWidget].cursor)); - } - - WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget]; - - int x = static_cast(std::round(event.x - hoveredWidget.box.x)); - int y = static_cast(std::round(event.y - hoveredWidget.box.y)); - hoveredWidget.widget->OnMouseMoved(x, y, event.deltaX, event.deltaY); - } - else if (m_hoveredWidget != InvalidCanvasIndex) - { - m_widgetEntries[m_hoveredWidget].widget->OnMouseExit(); - m_hoveredWidget = InvalidCanvasIndex; - - if (m_cursorController) - m_cursorController->UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor_Default)); - } - } - - void Canvas::OnEventMouseWheelMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseWheelEvent& event) - { - if (m_hoveredWidget != InvalidCanvasIndex) - { - WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget]; - - int x = static_cast(std::round(event.x - hoveredWidget.box.x)); - int y = static_cast(std::round(event.y - hoveredWidget.box.y)); - - hoveredWidget.widget->OnMouseWheelMoved(x, y, event.delta); - } - } - - void Canvas::OnEventMouseLeft(const Nz::EventHandler* /*eventHandler*/) - { - if (m_hoveredWidget != InvalidCanvasIndex) - { - m_widgetEntries[m_hoveredWidget].widget->OnMouseExit(); - m_hoveredWidget = InvalidCanvasIndex; - } - } - - void Canvas::OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event) - { - if (m_keyboardOwner != InvalidCanvasIndex) - { - if (m_widgetEntries[m_keyboardOwner].widget->OnKeyPressed(event)) - return; - - if (event.virtualKey == Nz::Keyboard::VKey::Tab) - { - if (!event.shift) - { - // Forward - for (std::size_t i = m_keyboardOwner + 1; i < m_widgetEntries.size(); ++i) - { - if (m_widgetEntries[i].widget->IsFocusable()) - { - SetKeyboardOwner(i); - return; - } - } - - for (std::size_t i = 0; i < m_keyboardOwner; ++i) - { - if (m_widgetEntries[i].widget->IsFocusable()) - { - SetKeyboardOwner(i); - return; - } - } - } - else - { - // Backward - for (decltype(m_widgetEntries)::reverse_iterator rit{ m_widgetEntries.begin() + m_keyboardOwner }; rit != m_widgetEntries.rend(); ++rit) - { - if (rit->widget->IsFocusable()) - { - SetKeyboardOwner(std::distance(m_widgetEntries.begin(), rit.base()) - 1); - return; - } - } - - decltype(m_widgetEntries)::reverse_iterator rend { m_widgetEntries.begin() + m_keyboardOwner }; - for (auto rit = m_widgetEntries.rbegin(); rit != rend; ++rit) - { - if (rit->widget->IsFocusable()) - { - SetKeyboardOwner(std::distance(m_widgetEntries.begin(), rit.base()) - 1); - return; - } - } - } - } - } - - OnUnhandledKeyPressed(eventHandler, event); - } - - void Canvas::OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event) - { - if (m_keyboardOwner != InvalidCanvasIndex) - m_widgetEntries[m_keyboardOwner].widget->OnKeyReleased(event); - - OnUnhandledKeyReleased(eventHandler, event); - } - - void Canvas::OnEventTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event) - { - if (m_keyboardOwner != InvalidCanvasIndex) - m_widgetEntries[m_keyboardOwner].widget->OnTextEntered(event.character, event.repeated); - } - - void Canvas::OnEventTextEdited(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::EditEvent& event) - { - if (m_keyboardOwner != InvalidCanvasIndex) - m_widgetEntries[m_keyboardOwner].widget->OnTextEdited(event.text, event.length); - } -} diff --git a/SDK/src/NDK/Components/CameraComponent.cpp b/SDK/src/NDK/Components/CameraComponent.cpp deleted file mode 100644 index 4a599ab9e..000000000 --- a/SDK/src/NDK/Components/CameraComponent.cpp +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::CameraComponent - * \brief NDK class that represents the component for camera - */ - - /*! - * \brief Applys the view of the camera - * - * \remark Produces a NazaraAssert if the camera has no target - */ - - void CameraComponent::ApplyView() const - { - NazaraAssert(m_target, "CameraComponent has no target"); - - EnsureProjectionMatrixUpdate(); - EnsureViewMatrixUpdate(); - EnsureViewportUpdate(); - - Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, m_projectionMatrix); - Nz::Renderer::SetMatrix(Nz::MatrixType_View, m_viewMatrix); - Nz::Renderer::SetTarget(m_target); - Nz::Renderer::SetViewport(m_viewport); - } - - /*! - * \brief Gets the aspect ratio of the camera - * \return Aspect ratio of the camera - */ - float CameraComponent::GetAspectRatio() const - { - EnsureViewportUpdate(); - - return m_aspectRatio; - } - - /*! - * \brief Gets the eye position of the camera - * - * \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent - */ - - Nz::Vector3f CameraComponent::GetEyePosition() const - { - NazaraAssert(m_entity && m_entity->HasComponent(), "CameraComponent requires NodeComponent"); - - return m_entity->GetComponent().GetPosition(); - } - - /*! - * \brief Gets the forward direction of the camera - * - * \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent - */ - Nz::Vector3f CameraComponent::GetForward() const - { - NazaraAssert(m_entity && m_entity->HasComponent(), "CameraComponent requires NodeComponent"); - - return m_entity->GetComponent().GetForward(); - } - - /*! - * \brief Gets the frutum of the camera - * \return A constant reference to the frustum of the camera - */ - const Nz::Frustumf& CameraComponent::GetFrustum() const - { - EnsureFrustumUpdate(); - - return m_frustum; - } - - /*! - * \brief Gets the projection matrix of the camera - * \return A constant reference to the projection matrix of the camera - */ - const Nz::Matrix4f& CameraComponent::GetProjectionMatrix() const - { - EnsureProjectionMatrixUpdate(); - - return m_projectionMatrix; - } - - - /*! - * \brief Gets the projection type of the camera - * \return Projection type of the camera - */ - Nz::ProjectionType CameraComponent::GetProjectionType() const - { - return m_projectionType; - } - - - /*! - * \brief Gets the target of the camera - * \return A constant reference to the render target of the camera - */ - const Nz::RenderTarget* CameraComponent::GetTarget() const - { - return m_target; - } - - /*! - * \brief Gets the view matrix of the camera - * \return A constant reference to the view matrix of the camera - */ - const Nz::Matrix4f& CameraComponent::GetViewMatrix() const - { - EnsureViewMatrixUpdate(); - - return m_viewMatrix; - } - - /*! - * \brief Gets the view port of the camera - * \return A constant reference to the view port of the camera - */ - const Nz::Recti& CameraComponent::GetViewport() const - { - EnsureViewportUpdate(); - - return m_viewport; - } - - /*! - * \brief Gets the Z far distance of the camera - * \return Z far distance of the camera - */ - float CameraComponent::GetZFar() const - { - return m_zFar; - } - - /*! - * \brief Gets the Z near distance of the camera - * \return Z near distance of the camera - */ - float CameraComponent::GetZNear() const - { - return m_zNear; - } - - /*! - * \brief Sets the layer of the camera in case of multiples layers - * - * \param layer Layer of the camera - */ - void CameraComponent::SetLayer(unsigned int layer) - { - m_layer = layer; - - m_entity->Invalidate(); // Invalidate the entity to make it passes through RenderSystem validation - } - - /*! - * \brief Operation to perform when component is attached to an entity - */ - void CameraComponent::OnAttached() - { - if (m_entity->HasComponent()) - m_nodeInvalidationSlot.Connect(m_entity->GetComponent().OnNodeInvalidation, this, &CameraComponent::OnNodeInvalidated); - - InvalidateViewMatrix(); - } - - /*! - * \brief Operation to perform when component is attached to this component - * - * \param component Component being attached - */ - - void CameraComponent::OnComponentAttached(BaseComponent& component) - { - if (IsComponent(component)) - { - NodeComponent& nodeComponent = static_cast(component); - m_nodeInvalidationSlot.Connect(nodeComponent.OnNodeInvalidation, this, &CameraComponent::OnNodeInvalidated); - - InvalidateViewMatrix(); - } - } - - /*! - * \brief Operation to perform when component is detached from this component - * - * \param component Component being detached - */ - - void CameraComponent::OnComponentDetached(BaseComponent& component) - { - if (IsComponent(component)) - { - m_nodeInvalidationSlot.Disconnect(); - - InvalidateViewMatrix(); - } - } - - /*! - * \brief Operation to perform when component is detached from an entity - */ - - void CameraComponent::OnDetached() - { - m_nodeInvalidationSlot.Disconnect(); - - InvalidateViewMatrix(); - } - - /*! - * \brief Operation to perform when the node is invalidated - * - * \param node Pointer to the node - */ - - void CameraComponent::OnNodeInvalidated(const Nz::Node* node) - { - NazaraUnused(node); - - // Our view matrix depends on NodeComponent position/rotation - InvalidateViewMatrix(); - } - - /*! - * \brief Operation to perform when the render target is released - * - * \param renderTarget Pointer to the RenderTarget - */ - - void CameraComponent::OnRenderTargetRelease(const Nz::RenderTarget* renderTarget) - { - if (renderTarget == m_target) - m_target = nullptr; - else - NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget)); - } - - /*! - * \brief Operation to perform when the render target has its size changed - * - * \param renderTarget Pointer to the RenderTarget - */ - - void CameraComponent::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget) - { - if (renderTarget == m_target) - InvalidateViewport(); - else - NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget)); - } - - /*! - * \brief Updates the frustum of the camera - */ - - void CameraComponent::UpdateFrustum() const - { - EnsureProjectionMatrixUpdate(); - EnsureViewMatrixUpdate(); - - // Extract the frustum from the view and projection matrices - m_frustum.Extract(m_viewMatrix, m_projectionMatrix); - m_frustumUpdated = true; - } - - /*! - * \brief Updates the project matrix of the camera - */ - - void CameraComponent::UpdateProjectionMatrix() const - { - switch (m_projectionType) - { - case Nz::ProjectionType_Orthogonal: - if (m_size.x <= 0.f || m_size.y <= 0.f) - { - EnsureViewportUpdate(); - - m_projectionMatrix.MakeOrtho(0.f, static_cast(m_viewport.width), 0.f, static_cast(m_viewport.height), m_zNear, m_zFar); - } - else - m_projectionMatrix.MakeOrtho(0.f, m_size.x, 0.f, m_size.y, m_zNear, m_zFar); - break; - - case Nz::ProjectionType_Perspective: - EnsureViewportUpdate(); // Can affect aspect ratio - - m_projectionMatrix.MakePerspective(m_fov, m_aspectRatio, m_zNear, m_zFar); - break; - } - - m_projectionMatrix *= Nz::Matrix4f::Scale(m_projectionScale); - - m_projectionMatrixUpdated = true; - } - - /*! - * \brief Updates the view matrix of the camera - * - * \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent - */ - - void CameraComponent::UpdateViewMatrix() const - { - NazaraAssert(m_entity && m_entity->HasComponent(), "CameraComponent requires NodeComponent"); - - NodeComponent& nodeComponent = m_entity->GetComponent(); - - // Build the view matrix using the NodeComponent position/rotation - m_viewMatrix.MakeViewMatrix(nodeComponent.GetPosition(Nz::CoordSys_Global), nodeComponent.GetRotation(Nz::CoordSys_Global)); - m_viewMatrixUpdated = true; - } - - /*! - * \brief Updates the view port of the camera - * - * \remark Produces a NazaraAssert if entity has no target - */ - - void CameraComponent::UpdateViewport() const - { - NazaraAssert(m_target, "CameraComponent has no target"); - - Nz::Vector2ui targetSize = m_target->GetSize(); - targetSize.y = std::max(targetSize.y, 1U); // Let's make sure we won't divide by zero - - // Our target region is expressed as % of the viewport dimensions, let's compute it in pixels - Nz::Rectf fViewport(m_targetRegion); - fViewport.x *= targetSize.x; - fViewport.y *= targetSize.y; - fViewport.width *= targetSize.x; - fViewport.height *= targetSize.y; - - // Compute the new aspect ratio, if it's different we need to invalidate the projection matrix - float aspectRatio = fViewport.width/fViewport.height; - if (!Nz::NumberEquals(m_aspectRatio, aspectRatio, 0.001f)) - { - m_aspectRatio = aspectRatio; - - if (m_projectionType == Nz::ProjectionType_Perspective) - InvalidateProjectionMatrix(); - } - - // Convert it back to int - m_viewport.Set(fViewport); - m_viewportUpdated = true; - } - - ComponentIndex CameraComponent::componentIndex; -} diff --git a/SDK/src/NDK/Components/DebugComponent.cpp b/SDK/src/NDK/Components/DebugComponent.cpp deleted file mode 100644 index 604e1d143..000000000 --- a/SDK/src/NDK/Components/DebugComponent.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - void DebugComponent::DetachDebugRenderables(GraphicsComponent& gfxComponent) - { - for (auto& renderable : m_debugRenderables) - { - if (renderable) - { - gfxComponent.Detach(renderable); - renderable.Reset(); - } - } - } - - void DebugComponent::OnComponentDetached(BaseComponent& component) - { - if (IsComponent(component)) - DetachDebugRenderables(static_cast(component)); - } - - void DebugComponent::OnDetached() - { - if (m_entity->HasComponent()) - DetachDebugRenderables(m_entity->GetComponent()); - } - - ComponentIndex DebugComponent::componentIndex; -} diff --git a/SDK/src/NDK/Components/GraphicsComponent.cpp b/SDK/src/NDK/Components/GraphicsComponent.cpp deleted file mode 100644 index 43bfa3b54..000000000 --- a/SDK/src/NDK/Components/GraphicsComponent.cpp +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::GraphicsComponent - * \brief NDK class that represents the component for graphics - */ - - /*! - * \brief Adds the renderable elements to the render queue - * - * \param renderQueue Queue to be added - */ - void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const - { - EnsureBoundingVolumesUpdate(); - EnsureTransformMatrixUpdate(); - - RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); - - for (const Renderable& object : m_renderables) - { - if (!object.dataUpdated) - { - object.renderable->UpdateData(&object.data); - object.dataUpdated = true; - } - - object.renderable->AddToRenderQueue(renderQueue, object.data, m_scissorRect); - } - } - - /*! - * \brief Adds the renderable elements to the render queue if their bounding volume intersects with the frustum - * - * \param frustum Queue to be added - * \param renderQueue Queue to be added - */ - void GraphicsComponent::AddToRenderQueueByCulling(const Nz::Frustumf& frustum, Nz::AbstractRenderQueue* renderQueue) const - { - EnsureBoundingVolumesUpdate(); - EnsureTransformMatrixUpdate(); - - RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); - - for (const Renderable& object : m_renderables) - { - if (frustum.Contains(object.boundingVolume)) - { - if (!object.dataUpdated) - { - object.renderable->UpdateData(&object.data); - object.dataUpdated = true; - } - - object.renderable->AddToRenderQueue(renderQueue, object.data, m_scissorRect); - } - } - } - - /*! - * \brief Attaches a renderable to the entity with a specific matrix - * - * \param renderable Reference to a renderable element - * \param localMatrix Local matrix that will be applied to the instanced renderable - * \param renderOrder Render order of the element - */ - void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder) - { - m_renderables.emplace_back(m_transformMatrix); - Renderable& entry = m_renderables.back(); - entry.data.localMatrix = localMatrix; - entry.data.renderOrder = renderOrder; - entry.renderable = std::move(renderable); - - ConnectInstancedRenderableSignals(entry); - - std::size_t materialCount = entry.renderable->GetMaterialCount(); - for (std::size_t i = 0; i < materialCount; ++i) - RegisterMaterial(entry.renderable->GetMaterial(i)); - - InvalidateAABB(); - ForceCullingInvalidation(); - } - - void GraphicsComponent::ConnectInstancedRenderableSignals(Renderable& entry) - { - entry.renderableBoundingVolumeInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateBoundingVolume, [this](const Nz::InstancedRenderable*) { InvalidateAABB(); }); - entry.renderableDataInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1)); - entry.renderableMaterialInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateMaterial, this, &GraphicsComponent::InvalidateRenderableMaterial); - entry.renderableReleaseSlot.Connect(entry.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach); - entry.renderableResetMaterialsSlot.Connect(entry.renderable->OnInstancedRenderableResetMaterials, this, &GraphicsComponent::OnInstancedRenderableResetMaterials); - entry.renderableSkinChangeSlot.Connect(entry.renderable->OnInstancedRenderableSkinChange, this, &GraphicsComponent::OnInstancedRenderableSkinChange); - } - - void GraphicsComponent::InvalidateRenderableData(const Nz::InstancedRenderable* renderable , Nz::UInt32 flags, std::size_t index) - { - NazaraAssert(index < m_renderables.size(), "Invalid renderable index"); - NazaraUnused(renderable); - - Renderable& r = m_renderables[index]; - r.dataUpdated = false; - r.renderable->InvalidateData(&r.data, flags); - - ForceCullingInvalidation(); - } - - void GraphicsComponent::InvalidateRenderableMaterial(const Nz::InstancedRenderable* renderable, std::size_t skinIndex, std::size_t matIndex, const Nz::MaterialRef& newMat) - { - // Don't listen to dormant materials - if (renderable->GetSkin() != skinIndex) - return; - - RegisterMaterial(newMat); - - const Nz::MaterialRef& oldMat = renderable->GetMaterial(skinIndex, matIndex); - UnregisterMaterial(oldMat); - - ForceCullingInvalidation(); - } - - void GraphicsComponent::InvalidateReflectionMap() - { - m_entity->Invalidate(); - - if (m_reflectiveMaterialCount > 0) - { - if (!m_reflectionMap) - { - m_reflectionMap = Nz::Texture::New(); - if (!m_reflectionMap->Create(Nz::ImageType_Cubemap, Nz::PixelFormatType_RGB8, m_reflectionMapSize, m_reflectionMapSize)) - { - NazaraWarning("Failed to create reflection map, reflections will be disabled for this entity"); - return; - } - } - } - else - m_reflectionMap.Reset(); - } - - void GraphicsComponent::RegisterMaterial(Nz::Material* material, std::size_t count) - { - auto it = m_materialEntries.find(material); - if (it == m_materialEntries.end()) - { - MaterialEntry matEntry; - matEntry.reflectionModelChangeSlot.Connect(material->OnMaterialReflectionModeChange, this, &GraphicsComponent::OnMaterialReflectionChange); - matEntry.renderableCounter = count; - - if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime) - { - if (m_reflectiveMaterialCount++ == 0) - InvalidateReflectionMap(); - } - - m_materialEntries.emplace(material, std::move(matEntry)); - } - else - it->second.renderableCounter += count; - } - - /*! - * \brief Operation to perform when component is attached to an entity - */ - - void GraphicsComponent::OnAttached() - { - if (m_entity->HasComponent()) - m_nodeInvalidationSlot.Connect(m_entity->GetComponent().OnNodeInvalidation, this, &GraphicsComponent::OnNodeInvalidated); - - InvalidateTransformMatrix(); - } - - /*! - * \brief Operation to perform when component is attached to this component - * - * \param component Component being attached - */ - - void GraphicsComponent::OnComponentAttached(BaseComponent& component) - { - if (IsComponent(component)) - { - NodeComponent& nodeComponent = static_cast(component); - m_nodeInvalidationSlot.Connect(nodeComponent.OnNodeInvalidation, this, &GraphicsComponent::OnNodeInvalidated); - - InvalidateTransformMatrix(); - } - } - - /*! - * \brief Operation to perform when component is detached from this component - * - * \param component Component being detached - */ - - void GraphicsComponent::OnComponentDetached(BaseComponent& component) - { - if (IsComponent(component)) - { - m_nodeInvalidationSlot.Disconnect(); - - InvalidateTransformMatrix(); - } - } - - /*! - * \brief Operation to perform when component is detached from an entity - */ - - void GraphicsComponent::OnDetached() - { - m_nodeInvalidationSlot.Disconnect(); - - InvalidateTransformMatrix(); - } - - void GraphicsComponent::OnInstancedRenderableResetMaterials(const Nz::InstancedRenderable* renderable, std::size_t newMaterialCount) - { - RegisterMaterial(Nz::Material::GetDefault(), newMaterialCount); - - std::size_t materialCount = renderable->GetMaterialCount(); - for (std::size_t i = 0; i < materialCount; ++i) - UnregisterMaterial(renderable->GetMaterial(i)); - - ForceCullingInvalidation(); - } - - void GraphicsComponent::OnInstancedRenderableSkinChange(const Nz::InstancedRenderable* renderable, std::size_t newSkinIndex) - { - std::size_t materialCount = renderable->GetMaterialCount(); - for (std::size_t i = 0; i < materialCount; ++i) - RegisterMaterial(renderable->GetMaterial(newSkinIndex, i)); - - for (std::size_t i = 0; i < materialCount; ++i) - UnregisterMaterial(renderable->GetMaterial(i)); - - ForceCullingInvalidation(); - } - - void GraphicsComponent::OnMaterialReflectionChange(const Nz::Material* material, Nz::ReflectionMode reflectionMode) - { - // Since this signal is only called when the new reflection mode is different from the current one, no need to compare both - if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime) - { - if (--m_reflectiveMaterialCount == 0) - InvalidateReflectionMap(); - } - else if (reflectionMode == Nz::ReflectionMode_RealTime) - { - if (m_reflectiveMaterialCount++ == 0) - InvalidateReflectionMap(); - } - } - - void GraphicsComponent::OnNodeInvalidated(const Nz::Node* node) - { - NazaraUnused(node); - - // Our view matrix depends on NodeComponent position/rotation - InvalidateAABB(); - InvalidateTransformMatrix(); - - ForceCullingInvalidation(); //< Force invalidation on movement for now (FIXME) - } - - void GraphicsComponent::UnregisterMaterial(Nz::Material* material) - { - auto it = m_materialEntries.find(material); - NazaraAssert(it != m_materialEntries.end(), "Material not registered"); - - MaterialEntry& matEntry = it->second; - if (--matEntry.renderableCounter == 0) - { - if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime) - { - if (--m_reflectiveMaterialCount == 0) - InvalidateReflectionMap(); - } - - m_materialEntries.erase(it); - } - } - - /*! - * \brief Updates the bounding volume - */ - - void GraphicsComponent::UpdateBoundingVolumes() const - { - EnsureTransformMatrixUpdate(); - - RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem(); - - m_aabb.Set(-1.f, -1.f, -1.f); - - bool isAabbSet = false; - - for (const Renderable& r : m_renderables) - { - r.boundingVolume = r.renderable->GetBoundingVolume(); - r.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(r.data.localMatrix, m_transformMatrix)); - if (r.boundingVolume.IsFinite()) - { - r.boundingVolume.Update(r.data.transformMatrix); - - if (isAabbSet) - m_aabb.ExtendTo(r.boundingVolume.aabb); - else - { - m_aabb.Set(r.boundingVolume.aabb); - isAabbSet = true; - } - } - } - - m_boundingVolumesUpdated = true; - - for (CullingBoxEntry& entry : m_cullingBoxEntries) - entry.listEntry.UpdateBox(m_aabb); - } - - /*! - * \brief Updates the transform matrix of the renderable - * - * \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent - */ - - void GraphicsComponent::UpdateTransformMatrix() const - { - NazaraAssert(m_entity && m_entity->HasComponent(), "GraphicsComponent requires NodeComponent"); - - m_transformMatrix = m_entity->GetComponent().GetTransformMatrix(); - m_transformMatrixUpdated = true; - } - - ComponentIndex GraphicsComponent::componentIndex; -} diff --git a/SDK/src/NDK/Components/LightComponent.cpp b/SDK/src/NDK/Components/LightComponent.cpp deleted file mode 100644 index 8aeb3f8a9..000000000 --- a/SDK/src/NDK/Components/LightComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - ComponentIndex LightComponent::componentIndex; -} diff --git a/SDK/src/NDK/Components/ParticleEmitterComponent.cpp b/SDK/src/NDK/Components/ParticleEmitterComponent.cpp deleted file mode 100644 index d128f4c16..000000000 --- a/SDK/src/NDK/Components/ParticleEmitterComponent.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::ParticleEmitterComponent - * \brief NDK class that represents the component emitter of particles - */ - - /*! - * \brief Sets up the particles - * - * \param mapper Mapper containing layout information of each particle - * \param count Number of particles - */ - - void ParticleEmitterComponent::SetupParticles(Nz::ParticleMapper& mapper, unsigned int count) const - { - if (m_isActive && m_setupFunc) - m_setupFunc(m_entity, mapper, count); - } - - ComponentIndex ParticleEmitterComponent::componentIndex; -} diff --git a/SDK/src/NDK/Components/ParticleGroupComponent.cpp b/SDK/src/NDK/Components/ParticleGroupComponent.cpp deleted file mode 100644 index 7042eb298..000000000 --- a/SDK/src/NDK/Components/ParticleGroupComponent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - ComponentIndex ParticleGroupComponent::componentIndex; -} diff --git a/SDK/src/NDK/Console.cpp b/SDK/src/NDK/Console.cpp deleted file mode 100644 index 7adf8da99..000000000 --- a/SDK/src/NDK/Console.cpp +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - namespace - { - const char s_inputPrefix[] = "> "; - constexpr std::size_t s_inputPrefixSize = Nz::CountOf(s_inputPrefix) - 1; - } - - /*! - * \ingroup NDK - * \class Ndk::Console - * \brief NDK class that represents a console to help development with Lua scripting - */ - - /*! - * \brief Constructs a Console object with a world to interact with - * - * \param world World to interact with - * \param size (Width, Height) of the console - * \param instance Lua instance that will interact with the world - */ - - Console::Console(BaseWidget* parent) : - BaseWidget(parent), - m_historyPosition(0), - m_defaultFont(Nz::Font::GetDefault()), - m_characterSize(24), - m_maxHistoryLines(200) - { - // History - m_history = Add(); - m_history->EnableBackground(true); - m_history->EnableLineWrap(true); - m_history->SetReadOnly(true); - m_history->SetBackgroundColor(Nz::Color(80, 80, 160, 128)); - - m_historyArea = Add(m_history); - - // Input - m_input = Add(); - m_input->EnableBackground(true); - m_input->SetText(s_inputPrefix); - m_input->SetTextColor(Nz::Color::Black); - - m_input->OnTextAreaKeyReturn.Connect(this, &Console::ExecuteInput); - - // Protect input prefix from erasure/selection - m_input->SetCursorPosition(s_inputPrefixSize); - - m_input->OnTextAreaCursorMove.Connect([](const AbstractTextAreaWidget* textArea, Nz::Vector2ui* newCursorPos) - { - newCursorPos->x = std::max(newCursorPos->x, static_cast(s_inputPrefixSize)); - }); - - m_input->OnTextAreaSelection.Connect([](const AbstractTextAreaWidget* textArea, Nz::Vector2ui* start, Nz::Vector2ui* end) - { - start->x = std::max(start->x, static_cast(s_inputPrefixSize)); - end->x = std::max(end->x, static_cast(s_inputPrefixSize)); - }); - - m_input->OnTextAreaKeyBackspace.Connect([](const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction) - { - if (textArea->GetGlyphIndex() < s_inputPrefixSize) - *ignoreDefaultAction = true; - }); - - // Handle history - m_input->OnTextAreaKeyUp.Connect([&] (const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction) - { - *ignoreDefaultAction = true; - - if (m_commandHistory.empty()) - return; - - if (m_historyPosition > 0) - m_historyPosition--; - - m_input->SetText(s_inputPrefix + m_commandHistory[m_historyPosition]); - }); - - m_input->OnTextAreaKeyDown.Connect([&] (const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction) - { - *ignoreDefaultAction = true; - - if (m_commandHistory.empty()) - return; - - if (++m_historyPosition >= m_commandHistory.size()) - m_historyPosition = 0; - - m_input->SetText(s_inputPrefix + m_commandHistory[m_historyPosition]); - }); - } - - /*! - * \brief Adds a line to the console - * - * \param text New line of text - * \param color Color for the text - */ - void Console::AddLine(const Nz::String& text, const Nz::Color& color) - { - if (m_historyLines.size() >= m_maxHistoryLines) - m_historyLines.erase(m_historyLines.begin()); - - m_historyLines.emplace_back(Line{ color, text }); - m_history->SetTextColor(color); - m_history->AppendText(text + '\n'); - m_history->Resize(m_history->GetPreferredSize()); - m_historyArea->Resize(m_historyArea->GetSize()); - m_historyArea->ScrollToRatio(1.f); - } - - /*! - * \brief Clears the console - * - * Clears the console history and input - */ - void Console::Clear() - { - m_historyLines.clear(); - m_history->Clear(); - m_history->Resize(m_history->GetPreferredSize()); - m_historyArea->Resize(m_historyArea->GetSize()); - m_input->SetText(s_inputPrefix); - } - - /*! - * \brief Clears the console focus - * - * Clear console input widget focus (if owned) - */ - void Console::ClearFocus() - { - m_input->ClearFocus(); - } - - /*! - * \brief Sets the character size - * - * \param size Size of the font - */ - void Console::SetCharacterSize(unsigned int size) - { - m_characterSize = size; - - m_history->SetCharacterSize(size); - m_input->SetCharacterSize(size); - - Layout(); - } - - /*! - * \brief Give the console input focus - * - */ - void Console::SetFocus() - { - m_input->SetFocus(); - } - - /*! - * \brief Sets the text font - * - * \param font Reference to a valid font - * - * \remark Produces a NazaraAssert if font is invalid or null - */ - void Console::SetTextFont(Nz::FontRef font) - { - NazaraAssert(font && font->IsValid(), "Invalid font"); - - m_defaultFont = std::move(font); - m_history->SetTextFont(m_defaultFont); - m_input->SetTextFont(m_defaultFont); - - Layout(); - } - - /*! - * \brief Performs this action when an input is added to the console - */ - void Console::ExecuteInput(const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction) - { - NazaraAssert(textArea == m_input, "Unexpected signal from an other text area"); - - *ignoreDefaultAction = true; - - Nz::String input = m_input->GetText(); - Nz::String inputCmd = input.SubString(s_inputPrefixSize); - m_input->SetText(s_inputPrefix); - - if (m_commandHistory.empty() || m_commandHistory.back() != inputCmd) - m_commandHistory.push_back(inputCmd); - - m_historyPosition = m_commandHistory.size(); - - AddLine(input); //< With the input prefix - - OnCommand(this, inputCmd); - } - - /*! - * \brief Places the console according to its layout - */ - void Console::Layout() - { - Nz::Vector2f origin = Nz::Vector2f(GetPosition()); - const Nz::Vector2f& size = GetSize(); - - unsigned int lineHeight = m_defaultFont->GetSizeInfo(m_characterSize).lineHeight; - float historyHeight = size.y - lineHeight; - - m_historyArea->SetPosition(origin.x, origin.y); - m_historyArea->Resize({ size.x, historyHeight - 4.f }); - - m_input->Resize({size.x, size.y - historyHeight}); - m_input->SetPosition(origin.x, origin.y + historyHeight); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding.cpp b/SDK/src/NDK/Lua/LuaBinding.cpp deleted file mode 100644 index 4bca51e19..000000000 --- a/SDK/src/NDK/Lua/LuaBinding.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::LuaBinding - * \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting - */ - - /*! - * \brief Binds modules to Lua - */ - - LuaBinding::LuaBinding() - { - core = LuaBinding_Base::BindCore(*this); - math = LuaBinding_Base::BindMath(*this); - network = LuaBinding_Base::BindNetwork(*this); - utility = LuaBinding_Base::BindUtility(*this); - - #ifndef NDK_SERVER - audio = LuaBinding_Base::BindAudio(*this); - renderer = LuaBinding_Base::BindRenderer(*this); - graphics = LuaBinding_Base::BindGraphics(*this); - platform = LuaBinding_Base::BindPlatform(*this); - #endif - - sdk = LuaBinding_Base::BindSDK(*this); - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the engine & SDK - */ - - void LuaBinding::RegisterClasses(Nz::LuaState& state) - { - core->Register(state); - math->Register(state); - network->Register(state); - sdk->Register(state); - utility->Register(state); - - #ifndef NDK_SERVER - audio->Register(state); - graphics->Register(state); - renderer->Register(state); - platform->Register(state); - #endif - - // ComponentType (fake enumeration to expose component indexes) - state.PushTable(0, m_componentBinding.size()); - { - for (const ComponentBinding& entry : m_componentBinding) - { - if (entry.name.IsEmpty()) - continue; - - state.PushField(entry.name, entry.index); - } - } - state.SetGlobal("ComponentType"); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Audio.cpp b/SDK/src/NDK/Lua/LuaBinding_Audio.cpp deleted file mode 100644 index c95b5d0ce..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Audio.cpp +++ /dev/null @@ -1,198 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindAudio(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Audio::LuaBinding_Audio(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::SoundEmitter **********************************/ - soundEmitter.Reset("SoundEmitter"); - { - soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping); - soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization); - - soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation); - soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration); - soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance); - soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch); - soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset); - soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition); - soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus); - soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity); - soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume); - - soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping); - soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized); - - soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause); - soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play); - - soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation); - soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance); - soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch); - soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition); - soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity); - soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume); - - soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop); - } - - /*********************************** Nz::Music **********************************/ - music.Reset("Music"); - { - music.Inherit(soundEmitter); - - music.BindDefaultConstructor(); - - //musicClass.SetMethod("Create", &Nz::Music::Create); - //musicClass.SetMethod("Destroy", &Nz::Music::Destroy); - - music.BindMethod("EnableLooping", &Nz::Music::EnableLooping); - - music.BindMethod("GetDuration", &Nz::Music::GetDuration); - music.BindMethod("GetFormat", &Nz::Music::GetFormat); - music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset); - music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount); - music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate); - music.BindMethod("GetStatus", &Nz::Music::GetStatus); - - music.BindMethod("IsLooping", &Nz::Music::IsLooping); - - music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::SoundStreamParams()); - - music.BindMethod("Pause", &Nz::Music::Pause); - music.BindMethod("Play", &Nz::Music::Play); - - music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset); - - music.BindMethod("Stop", &Nz::Music::Stop); - - // Manual - music.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream ss("Music("); - ss << instance.GetFilePath() << ')'; - - lua.PushString(ss); - return 1; - }); - } - - /*********************************** Nz::Sound **********************************/ - sound.Reset("Sound"); - { - sound.Inherit(soundEmitter); - - sound.BindDefaultConstructor(); - - sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer); - - sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable); - sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying); - - sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams()); - - sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset); - - // Manual - sound.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream ss("Sound("); - if (const Nz::SoundBuffer* buffer = instance.GetBuffer()) - ss << buffer; - - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - - /*********************************** Nz::SoundBuffer **********************************/ - soundBuffer.Reset("SoundBuffer"); - { - soundBuffer.SetConstructor([] (Nz::LuaState& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount) - { - NazaraUnused(lua); - NazaraUnused(argumentCount); - - Nz::PlacementNew(instance, Nz::SoundBuffer::New()); - return true; - }); - - soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy); - - soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration); - soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat); - soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount); - soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate); - - soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid); - - soundBuffer.BindStaticMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams()); - - soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported); - - // Manual - soundBuffer.BindMethod("Create", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - int index = 2; - Nz::AudioFormat format = lua.Check(&index); - unsigned int sampleCount = lua.Check(&index); - unsigned int sampleRate = lua.Check(&index); - - std::size_t bufferSize = 0; - const char* buffer = lua.CheckString(index, &bufferSize); - lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer"); - - lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast(buffer))); - return 1; - }); - - soundBuffer.BindMethod("GetSamples", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - lua.PushString(reinterpret_cast(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16)); - return 1; - }); - - soundBuffer.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int - { - Nz::StringStream ss("SoundBuffer("); - if (instance->IsValid()) - { - Nz::String filePath = instance->GetFilePath(); - if (!filePath.IsEmpty()) - ss << "File: " << filePath << ", "; - - ss << "Duration: " << instance->GetDuration() / 1000.f << "s"; - } - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Audio classes - */ - void LuaBinding_Audio::Register(Nz::LuaState& state) - { - music.Register(state); - sound.Register(state); - soundBuffer.Register(state); - soundEmitter.Register(state); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Base.cpp b/SDK/src/NDK/Lua/LuaBinding_Base.cpp deleted file mode 100644 index b9bd44c57..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Base.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include - -namespace Ndk -{ - LuaBinding_Base::LuaBinding_Base(LuaBinding& binding) : - m_binding(binding) - { - } - - LuaBinding_Base::~LuaBinding_Base() = default; -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Core.cpp b/SDK/src/NDK/Lua/LuaBinding_Core.cpp deleted file mode 100644 index 6091c88e2..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Core.cpp +++ /dev/null @@ -1,355 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindCore(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Core::LuaBinding_Core(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::Stream ***********************************/ - stream.Reset("Stream"); - { - stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode); - stream.BindMethod("Flush", &Nz::Stream::Flush); - stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos); - stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory); - stream.BindMethod("GetPath", &Nz::Stream::GetPath); - stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode); - stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions); - stream.BindMethod("GetSize", &Nz::Stream::GetSize); - stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U); - stream.BindMethod("IsReadable", &Nz::Stream::IsReadable); - stream.BindMethod("IsSequential", &Nz::Stream::IsSequential); - stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled); - stream.BindMethod("IsWritable", &Nz::Stream::IsWritable); - stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos); - - stream.BindMethod("Read", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { - int argIndex = 2; - - std::size_t length = lua.Check(&argIndex); - - std::unique_ptr buffer(new char[length]); - std::size_t readLength = instance.Read(buffer.get(), length); - - lua.PushString(Nz::String(buffer.get(), readLength)); - return 1; - }); - - stream.BindMethod("Write", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int { - int argIndex = 2; - - std::size_t bufferSize = 0; - const char* buffer = lua.CheckString(argIndex, &bufferSize); - - if (instance.IsTextModeEnabled()) - lua.Push(instance.Write(Nz::String(buffer, bufferSize))); - else - lua.Push(instance.Write(buffer, bufferSize)); - return 1; - }); - } - - /*********************************** Nz::Clock **********************************/ - clock.Reset("Clock"); - { - clock.SetConstructor([] (Nz::LuaState& lua, Nz::Clock* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(instance); - return true; - - case 1: - { - Nz::Int64 startingValue = lua.Check(&argIndex, 0); - - Nz::PlacementNew(instance, startingValue); - return true; - } - - case 2: - { - Nz::Int64 startingValue = lua.Check(&argIndex, 0); - bool paused = lua.Check(&argIndex, false); - - Nz::PlacementNew(instance, startingValue, paused); - return true; - } - } - - lua.Error("No matching overload for Clock constructor"); - return false; - }); - - clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds); - clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds); - clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds); - clock.BindMethod("IsPaused", &Nz::Clock::IsPaused); - clock.BindMethod("Pause", &Nz::Clock::Pause); - clock.BindMethod("Restart", &Nz::Clock::Restart); - clock.BindMethod("Unpause", &Nz::Clock::Unpause); - - // Manual - clock.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream ss("Clock(Elapsed: "); - ss << instance.GetSeconds(); - ss << "s, Paused: "; - ss << instance.IsPaused(); - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - - /********************************* Nz::Directory ********************************/ - directory.Reset("Directory"); - { - directory.SetConstructor([] (Nz::LuaState& lua, Nz::Directory* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(instance); - return true; - - case 1: - Nz::PlacementNew(instance, lua.Check(&argIndex)); - return true; - } - - return false; - }); - - directory.BindMethod("Close", &Nz::Directory::Close); - directory.BindMethod("Exists", &Nz::Directory::Exists); - directory.BindMethod("GetPath", &Nz::Directory::GetPath); - directory.BindMethod("GetPattern", &Nz::Directory::GetPattern); - directory.BindMethod("GetResultName", &Nz::Directory::GetResultName); - directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath); - directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize); - directory.BindMethod("IsOpen", &Nz::Directory::IsOpen); - directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory); - directory.BindMethod("NextResult", &Nz::Directory::NextResult, true); - directory.BindMethod("Open", &Nz::Directory::Open); - directory.BindMethod("SetPath", &Nz::Directory::SetPath); - directory.BindMethod("SetPattern", &Nz::Directory::SetPattern); - - directory.BindStaticMethod("Copy", Nz::Directory::Copy); - directory.BindStaticMethod("Create", Nz::Directory::Create); - directory.BindStaticMethod("Exists", Nz::Directory::Exists); - directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent); - directory.BindStaticMethod("Remove", Nz::Directory::Remove); - directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent); - - // Manual - directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream ss("Directory("); - ss << instance.GetPath(); - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - - /*********************************** Nz::File ***********************************/ - file.Reset("File"); - { - file.Inherit(stream); - - file.SetConstructor([] (Nz::LuaState& lua, Nz::File* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 1U); - - int argIndex = 2; - switch (argCount) - { - case 0: - Nz::PlacementNew(instance); - return true; - - case 1: - { - Nz::String filePath = lua.Check(&argIndex); - - Nz::PlacementNew(instance, filePath); - return true; - } - - case 2: - { - Nz::String filePath = lua.Check(&argIndex); - Nz::UInt32 openMode = lua.Check(&argIndex); - - Nz::PlacementNew(instance, filePath, openMode); - return true; - } - } - - lua.Error("No matching overload for File constructor"); - return false; - }); - - file.BindMethod("Close", &Nz::File::Close); - file.BindMethod("Copy", &Nz::File::Copy); - file.BindMethod("Delete", &Nz::File::Delete); - file.BindMethod("EndOfFile", &Nz::File::EndOfFile); - file.BindMethod("Exists", &Nz::File::Exists); - file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime); - file.BindMethod("GetFileName", &Nz::File::GetFileName); - file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindMethod("IsOpen", &Nz::File::IsOpen); - file.BindMethod("Rename", &Nz::File::GetLastWriteTime); - file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindMethod("SetFile", &Nz::File::GetLastWriteTime); - - file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath); - file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash); - file.BindStaticMethod("Copy", &Nz::File::Copy); - file.BindStaticMethod("Delete", &Nz::File::Delete); - file.BindStaticMethod("Exists", &Nz::File::Exists); - //fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime); - file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory); - //fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime); - //fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime); - file.BindStaticMethod("GetSize", &Nz::File::GetSize); - file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute); - file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath); - file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators); - file.BindStaticMethod("Rename", &Nz::File::Rename); - - // Manual - file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 0: - case 1: - return lua.Push(instance.Open(lua.Check(&argIndex, Nz::OpenMode_NotOpen))); - - case 2: - { - Nz::String filePath = lua.Check(&argIndex); - Nz::UInt32 openMode = lua.Check(&argIndex, Nz::OpenMode_NotOpen); - return lua.Push(instance.Open(filePath, openMode)); - } - } - - lua.Error("No matching overload for method Open"); - return 0; - }); - - file.BindMethod("SetCursorPos", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 1: - return lua.Push(instance.SetCursorPos(lua.Check(&argIndex))); - - case 2: - { - Nz::CursorPosition curPos = lua.Check(&argIndex); - Nz::Int64 offset = lua.Check(&argIndex); - return lua.Push(instance.SetCursorPos(curPos, offset)); - } - } - - lua.Error("No matching overload for method SetCursorPos"); - return 0; - }); - - file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int { - Nz::StringStream ss("File("); - if (instance.IsOpen()) - ss << "Path: " << instance.GetPath(); - - ss << ')'; - - lua.PushString(ss); - return 1; - }); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Core classes - */ - void LuaBinding_Core::Register(Nz::LuaState& state) - { - // Classes - clock.Register(state); - directory.Register(state); - file.Register(state); - stream.Register(state); - - // Enums - - // Nz::CursorPosition - static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 3); - { - state.PushField("AtBegin", Nz::CursorPosition_AtBegin); - state.PushField("AtCurrent", Nz::CursorPosition_AtCurrent); - state.PushField("AtEnd", Nz::CursorPosition_AtEnd); - } - state.SetGlobal("CursorPosition"); - - // Nz::HashType - static_assert(Nz::HashType_Max + 1 == 10, "Nz::HashType has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 10); - { - state.PushField("CRC32", Nz::HashType_CRC32); - state.PushField("CRC64", Nz::HashType_CRC64); - state.PushField("Fletcher16", Nz::HashType_Fletcher16); - state.PushField("MD5", Nz::HashType_MD5); - state.PushField("SHA1", Nz::HashType_SHA1); - state.PushField("SHA224", Nz::HashType_SHA224); - state.PushField("SHA256", Nz::HashType_SHA256); - state.PushField("SHA384", Nz::HashType_SHA384); - state.PushField("SHA512", Nz::HashType_SHA512); - state.PushField("Whirlpool", Nz::HashType_Whirlpool); - } - state.SetGlobal("HashType"); - - // Nz::OpenMode - static_assert(Nz::OpenMode_Max + 1 == 8, "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding"); - state.PushTable(0, Nz::OpenMode_Max + 1); - { - state.PushField("Append", Nz::OpenMode_Append); - state.PushField("NotOpen", Nz::OpenMode_NotOpen); - state.PushField("Lock", Nz::OpenMode_Lock); - state.PushField("ReadOnly", Nz::OpenMode_ReadOnly); - state.PushField("ReadWrite", Nz::OpenMode_ReadWrite); - state.PushField("Text", Nz::OpenMode_Text); - state.PushField("Truncate", Nz::OpenMode_Truncate); - state.PushField("WriteOnly", Nz::OpenMode_WriteOnly); - } - state.SetGlobal("OpenMode"); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp b/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp deleted file mode 100644 index fc764866a..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Graphics.cpp +++ /dev/null @@ -1,498 +0,0 @@ -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindGraphics(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Graphics::LuaBinding_Graphics(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::AbstractViewer ***********************************/ - abstractViewer.Reset("AbstractViewer"); - { - abstractViewer.BindMethod("GetAspectRatio", &Nz::AbstractViewer::GetAspectRatio); - abstractViewer.BindMethod("GetEyePosition", &Nz::AbstractViewer::GetEyePosition); - abstractViewer.BindMethod("GetForward", &Nz::AbstractViewer::GetForward); - //abstractViewer.BindMethod("GetFrustum", &Nz::AbstractViewer::GetFrustum); - abstractViewer.BindMethod("GetProjectionMatrix", &Nz::AbstractViewer::GetProjectionMatrix); - //abstractViewer.BindMethod("GetTarget", &Nz::AbstractViewer::GetTarget); - abstractViewer.BindMethod("GetViewMatrix", &Nz::AbstractViewer::GetViewMatrix); - abstractViewer.BindMethod("GetViewport", &Nz::AbstractViewer::GetViewport); - abstractViewer.BindMethod("GetZFar", &Nz::AbstractViewer::GetZFar); - abstractViewer.BindMethod("GetZNear", &Nz::AbstractViewer::GetZNear); - } - - /*********************************** Nz::InstancedRenderable ***********************************/ - instancedRenderable.Reset("InstancedRenderable"); - { - instancedRenderable.BindMethod("GetMaterial", [] (Nz::LuaState& lua, Nz::InstancedRenderable* instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - switch (argCount) - { - case 0: - case 1: - { - int argIndex = 2; - std::size_t matIndex(lua.Check(&argIndex, 0)); - - return lua.Push(instance->GetMaterial(matIndex)); - } - - case 2: - { - int argIndex = 2; - std::size_t skinIndex(lua.Check(&argIndex)); - std::size_t matIndex(lua.Check(&argIndex)); - - return lua.Push(instance->GetMaterial(skinIndex, matIndex)); - } - } - - lua.Error("No matching overload for method GetMaterial"); - return 0; - }); - - instancedRenderable.BindMethod("GetMaterialCount", &Nz::InstancedRenderable::GetMaterialCount); - instancedRenderable.BindMethod("GetSkin", &Nz::InstancedRenderable::GetSkin); - instancedRenderable.BindMethod("GetSkinCount", &Nz::InstancedRenderable::GetSkinCount); - - instancedRenderable.BindMethod("SetSkin", &Nz::InstancedRenderable::SetSkin); - instancedRenderable.BindMethod("SetSkinCount", &Nz::InstancedRenderable::SetSkinCount); - } - - /*********************************** Nz::Material ***********************************/ - material.Reset("Material"); - { - material.SetConstructor([] (Nz::LuaState& lua, Nz::MaterialRef* instance, std::size_t argumentCount) - { - switch (argumentCount) - { - case 0: - Nz::PlacementNew(instance, Nz::Material::New()); - return true; - - case 1: - { - int argIndex = 1; - if (lua.IsOfType(argIndex, "MaterialPipeline")) - { - Nz::PlacementNew(instance, Nz::Material::New(*static_cast(lua.ToUserdata(argIndex)))); - return true; - } - else if (lua.IsOfType(argIndex, "Material")) - { - Nz::PlacementNew(instance, Nz::Material::New(**static_cast(lua.ToUserdata(argIndex)))); - return true; - } - else - { - Nz::PlacementNew(instance, Nz::Material::New(lua.Check(&argIndex))); - return true; - } - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - material.BindMethod("Configure", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "MaterialPipeline")) - { - instance->Configure(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - { - lua.Push(instance->Configure(lua.Check(&argIndex))); - return 1; - } - }); - - material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest); - material.BindMethod("EnableBlending", &Nz::Material::EnableBlending); - material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite); - material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer); - material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting); - material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite); - material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling); - material.BindMethod("EnableReflectionMapping", &Nz::Material::EnableReflectionMapping); - material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest); - material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting); - material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive); - material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest); - - material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate); - - material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap); - material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold); - material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor); - material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc); - material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial); - material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor); - material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap); - //material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler); - material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend); - material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap); - material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling); - material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling); - material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap); - material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth); - material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap); - //material.BindMethod("GetPipeline", &Nz::Material::GetPipeline); - //material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo); - material.BindMethod("GetPointSize", &Nz::Material::GetPointSize); - material.BindMethod("GetReflectionMode", &Nz::Material::GetReflectionMode); - //material.BindMethod("GetShader", &Nz::Material::GetShader); - material.BindMethod("GetShininess", &Nz::Material::GetShininess); - material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor); - material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap); - //material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler); - material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend); - - material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap); - material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial); - material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap); - material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap); - material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap); - material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap); - material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap); - - material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled); - material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled); - material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled); - material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled); - material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled); - material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled); - material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled); - material.BindMethod("IsReflectionMappingEnabled", &Nz::Material::IsReflectionMappingEnabled); - material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled); - material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled); - material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled); - material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled); - - material.BindMethod("Reset", &Nz::Material::Reset); - - material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold); - material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor); - material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); - material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc); - material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial); - material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor); - //material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler); - material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend); - material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling); - material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling); - material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth); - material.BindMethod("SetPointSize", &Nz::Material::SetPointSize); - material.BindMethod("SetReflectionMode", &Nz::Material::SetReflectionMode); - material.BindMethod("SetShininess", &Nz::Material::SetShininess); - material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); - material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor); - //material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler); - material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend); - - material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault); - material.BindStaticMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams()); - - material.BindMethod("SetAlphaMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetAlphaMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetAlphaMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetDiffuseMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetDiffuseMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetDiffuseMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetEmissiveMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetEmissiveMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetEmissiveMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetHeightMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetHeightMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetHeightMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetNormalMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetNormalMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetNormalMap(lua.Check(&argIndex))); - }); - - material.BindMethod("SetShader", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "UberShader")) - { - instance->SetShader(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetShader(lua.Check(&argIndex))); - }); - - material.BindMethod("SetSpecularMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - instance->SetSpecularMap(*static_cast(lua.ToUserdata(argIndex))); - return 0; - } - else - return lua.Push(instance->SetSpecularMap(lua.Check(&argIndex))); - }); - } - - /*********************************** Nz::Model ***********************************/ - model.Reset("Model"); - { - model.Inherit(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef* - { - return reinterpret_cast(modelRef); //TODO: Make a ObjectRefCast - }); - - model.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(instance, Nz::Model::New()); - return true; - }); - - //modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh); - - model.BindMethod("IsAnimated", &Nz::Model::IsAnimated); - - model.BindMethod("SetMaterial", [] (Nz::LuaState& lua, Nz::Model* instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 3U); - switch (argCount) - { - case 2: - { - int argIndex = 2; - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - std::size_t matIndex(lua.Check(&argIndex)); - Nz::MaterialRef mat(lua.Check(&argIndex)); - - instance->SetMaterial(matIndex, std::move(mat)); - return 0; - } - else if (lua.IsOfType(argIndex, Nz::LuaType_String)) - { - Nz::String subMesh(lua.Check(&argIndex)); - Nz::MaterialRef mat(lua.Check(&argIndex)); - - instance->SetMaterial(subMesh, std::move(mat)); - return 0; - } - - break; - } - - case 3: - { - int argIndex = 2; - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - std::size_t skinIndex(lua.Check(&argIndex)); - std::size_t matIndex(lua.Check(&argIndex)); - Nz::MaterialRef mat(lua.Check(&argIndex)); - - instance->SetMaterial(skinIndex, matIndex, std::move(mat)); - return 0; - } - else if (lua.IsOfType(argIndex, Nz::LuaType_String)) - { - std::size_t skinIndex(lua.Check(&argIndex)); - Nz::String subMesh(lua.Check(&argIndex)); - Nz::MaterialRef materialRef(lua.Check(&argIndex)); - - instance->SetMaterial(skinIndex, subMesh, std::move(materialRef)); - return 0; - } - - break; - } - } - - lua.Error("No matching overload for method SetMaterial"); - return 0; - }); - - //modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh); - //modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence); - - model.BindStaticMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters()); - } - - /*********************************** Nz::Sprite ***********************************/ - sprite.Reset("Sprite"); - { - sprite.Inherit(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef* - { - return reinterpret_cast(spriteRef); //TODO: Make a ObjectRefCast - }); - - sprite.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(instance, Nz::Sprite::New()); - return true; - }); - - sprite.BindMethod("GetColor", &Nz::Sprite::GetColor); - sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor); - sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin); - sprite.BindMethod("GetSize", &Nz::Sprite::GetSize); - sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords); - - sprite.BindMethod("SetColor", &Nz::Sprite::SetColor); - sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor); - sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial); - sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin); - sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize); - sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords); - sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect); - - sprite.BindMethod("SetMaterial", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Material")) - { - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - instance->SetMaterial(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); - } - else if (lua.IsOfType(argIndex, Nz::LuaType_String)) - { - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - instance->SetMaterial(lua.ToString(argIndex), resizeSprite); - } - else if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - std::size_t skinIndex(lua.Check(&argIndex)); - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - if (lua.IsOfType(argIndex, "Material")) - instance->SetMaterial(skinIndex, *static_cast(lua.ToUserdata(argIndex)), resizeSprite); - else - instance->SetMaterial(skinIndex, lua.Check(&argIndex), resizeSprite); - } - - return 0; - }); - - sprite.BindMethod("SetTexture", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Texture")) - { - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - instance->SetTexture(*static_cast(lua.ToUserdata(argIndex)), resizeSprite); - } - else if (lua.IsOfType(argIndex, Nz::LuaType_String)) - { - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - instance->SetTexture(lua.ToString(argIndex), resizeSprite); - } - else if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - std::size_t skinIndex(lua.Check(&argIndex)); - bool resizeSprite = lua.CheckBoolean(argIndex + 1, true); - - if (lua.IsOfType(argIndex, "Texture")) - instance->SetTexture(skinIndex, *static_cast(lua.ToUserdata(argIndex)), resizeSprite); - else - instance->SetTexture(skinIndex, lua.Check(&argIndex), resizeSprite); - } - - return 0; - }); - } - - /*********************************** Nz::SpriteLibrary ***********************************/ - spriteLibrary.Reset("SpriteLibrary"); - { - spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get); - spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has); - spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register); - spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query); - spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Graphics classes - */ - - void LuaBinding_Graphics::Register(Nz::LuaState& state) - { - abstractViewer.Register(state); - instancedRenderable.Register(state); - material.Register(state); - model.Register(state); - sprite.Register(state); - spriteLibrary.Register(state); - - // Nz::ReflectionMode - static_assert(Nz::ReflectionMode_Max + 1 == 3, "Nz::ReflectionMode has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 3); - { - state.PushField("Probe", Nz::ReflectionMode_Probe); - state.PushField("RealTime", Nz::ReflectionMode_RealTime); - state.PushField("Skybox", Nz::ReflectionMode_Skybox); - } - state.SetGlobal("ReflectionMode"); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Math.cpp b/SDK/src/NDK/Lua/LuaBinding_Math.cpp deleted file mode 100644 index 15deebfab..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Math.cpp +++ /dev/null @@ -1,986 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindMath(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Math::LuaBinding_Math(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::EulerAngles **********************************/ - eulerAngles.Reset("EulerAngles"); - { - eulerAngles.SetConstructor([] (Nz::LuaState& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero()); - return true; - - case 1: - Nz::PlacementNew(instance, *static_cast(lua.CheckUserdata(1, "EulerAngles"))); - return true; - - case 3: - Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3)); - return true; - } - - lua.Error("No matching overload for EulerAngles constructor"); - return false; - }); - - eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize); - eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion); - - eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString); - - eulerAngles.SetGetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance) - { - std::size_t length; - const char* ypr = lua.CheckString(2, &length); - - switch (length) - { - case 1: - { - switch (ypr[0]) - { - case 'p': - lua.Push(instance.pitch); - return true; - - case 'y': - lua.Push(instance.yaw); - return true; - - case 'r': - lua.Push(instance.roll); - return true; - } - break; - } - - case 3: - { - if (std::memcmp(ypr, "yaw", 3) != 0) - break; - - lua.Push(instance.yaw); - return true; - } - - case 4: - { - if (std::memcmp(ypr, "roll", 4) != 0) - break; - - lua.Push(instance.roll); - return true; - } - - case 5: - { - if (std::memcmp(ypr, "pitch", 5) != 0) - break; - - lua.Push(instance.pitch); - return true; - } - } - - return false; - }); - - eulerAngles.SetSetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance) - { - std::size_t length; - const char* ypr = lua.CheckString(2, &length); - double value = lua.CheckNumber(3); - - switch (length) - { - case 1: - { - switch (ypr[0]) - { - case 'p': - instance.pitch = value; - return true; - - case 'y': - instance.yaw = value; - return true; - - case 'r': - instance.roll = value; - return true; - } - break; - } - - case 3: - { - if (std::memcmp(ypr, "yaw", 3) != 0) - break; - - instance.yaw = value; - return true; - } - - case 4: - { - if (std::memcmp(ypr, "roll", 4) != 0) - break; - - instance.roll = value; - return true; - } - - case 5: - { - if (std::memcmp(ypr, "pitch", 5) != 0) - break; - - instance.pitch = value; - return true; - } - } - - return false; - }); - } - - /*********************************** Nz::Matrix4 **********************************/ - matrix4d.Reset("Matrix4"); - { - matrix4d.SetConstructor([] (Nz::LuaState& lua, Nz::Matrix4d* matrix, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(matrix, Nz::Matrix4d::Zero()); - return true; - - case 1: - if (lua.IsOfType(1, "Matrix4")) - Nz::PlacementNew(matrix, *static_cast(lua.ToUserdata(1))); - break; - - case 16: - { - double values[16]; - for (int i = 0; i < 16; ++i) - values[i] = lua.CheckNumber(i); - - Nz::PlacementNew(matrix, values); - - return true; - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation); - matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale); - matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation); - - matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate); - matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); - - //matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn); - matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant); - matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine); - - matrix4d.BindMethod("GetInverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - if (instance.GetInverse(&result)) - return lua.Push(true, result); - else - return lua.Push(false); - }); - - matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - if (instance.GetInverseAffine(&result)) - return lua.Push(true, result); - else - return lua.Push(false); - }); - - matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation); - - //matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow); - matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale); - matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale); - matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation); - - matrix4d.BindMethod("GetTransposed", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - Nz::Matrix4d result; - instance.GetTransposed(&result); - - return lua.Push(result); - }); - - matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale); - matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale); - - matrix4d.BindMethod("Inverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - bool succeeded; - instance.Inverse(&succeeded); - - return lua.Push(succeeded); - }); - - matrix4d.BindMethod("InverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - bool succeeded; - instance.InverseAffine(&succeeded); - - return lua.Push(succeeded); - }); - - matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine); - matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity); - - matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity); - matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up()); - matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0); - matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective); - matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation); - matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale); - matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation); - matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit()); - matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix); - matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero); - - matrix4d.BindMethod("Set", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 3U); - - int argIndex = 2; - switch (argCount) - { - case 1: - if (lua.IsOfType(argIndex, "Matrix4")) - instance = *static_cast(lua.ToUserdata(argIndex)); - break; - - case 16: - { - double values[16]; - for (std::size_t i = 0; i < 16; ++i) - values[i] = lua.CheckNumber(argIndex++); - - instance = Nz::Matrix4d(values); - - return 0; - } - } - - lua.Error("No matching overload for method Set"); - return 0; - }); - - matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation); - matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale); - matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation); - - matrix4d.BindMethod("Transform", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "Vector2")) - { - double z(lua.CheckNumber(argIndex + 1, 0.0)); - double w(lua.CheckNumber(argIndex + 2, 1.0)); - - return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), z, w)); - } - else if (lua.IsOfType(argIndex, "Vector3")) - { - double w(lua.CheckNumber(argIndex + 1, 1.0)); - - return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(argIndex)), w)); - } - //else if (lua.IsOfType(2, "Vector4")) - // return lua.Push(instance.Transform(*static_cast(lua.ToUserdata(1)))); - - lua.Error("No matching overload for method Transform"); - return 0; - }); - - matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose); - - matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString); - - matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate); - matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine); - matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity); - matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up()); - matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0); - matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective); - matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate); - matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale); - matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate); - matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit()); - matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix); - matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero); - - matrix4d.SetGetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance) - { - bool succeeded = false; - std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); - if (!succeeded || index < 1 || index > 16) - return false; - - lua.Push(instance[index - 1]); - return true; - }); - - matrix4d.SetSetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance) - { - bool succeeded = false; - std::size_t index = static_cast(lua.ToInteger(2, &succeeded)); - if (!succeeded || index < 1 || index > 16) - return false; - - instance[index - 1] = lua.CheckNumber(3); - - return true; - }); - } - - /*********************************** Nz::Rect **********************************/ - rect.Reset("Rect"); - { - rect.SetConstructor([] (Nz::LuaState& lua, Nz::Rectd* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 4U); - - switch (argCount) - { - case 0: - case 4: - PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, "Rect")) - PlacementNew(instance, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, Nz::LuaType_Table)) - { - // TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd - PlacementNew(instance, lua.CheckField("x", 1), - lua.CheckField("y", 1), - lua.CheckField("width", 1), - lua.CheckField("height", 1)); - } - else if (lua.IsOfType(1, "Vector2")) - PlacementNew(instance, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - { - if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number)) - PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2)); - else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2")) - PlacementNew(instance, *static_cast(lua.ToUserdata(1)), *static_cast(lua.ToUserdata(2))); - else - break; - - return true; - } - } - - lua.Error("No matching overload for Rect constructor"); - return false; - }); - - rect.BindMethod("__tostring", &Nz::Rectd::ToString); - - rect.SetGetter([] (Nz::LuaState& lua, Nz::Rectd& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - auto index = lua.CheckBoundInteger(2); - if (index < 1 || index > 4) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xywh = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xywh[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'w': - lua.Push(instance.width); - return true; - - case 'h': - lua.Push(instance.height); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - rect.SetSetter([] (Nz::LuaState& lua, Nz::Rectd& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - auto index = lua.CheckBoundInteger(2); - if (index < 1 || index > 4) - return false; - - instance[index - 1] = lua.CheckNumber(2); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xywh = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xywh[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'w': - instance.width = value; - return true; - - case 'h': - instance.height = value; - return true; - } - break; - } - - default: - break; - } - - return false; - }); - } - - /*********************************** Nz::Quaternion **********************************/ - quaternion.Reset("Quaternion"); - { - quaternion.SetConstructor([] (Nz::LuaState& lua, Nz::Quaterniond* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 4U); - - switch (argCount) - { - case 0: - Nz::PlacementNew(instance, Nz::Quaterniond::Zero()); - return true; - - case 1: - { - if (lua.IsOfType(1, "EulerAngles")) - Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, "Quaternion")) - Nz::PlacementNew(instance, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector3"))); - return true; - - case 4: - Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4)); - return true; - - default: - break; - } - - lua.Error("No matching overload for Quaternion constructor"); - return false; - }); - - quaternion.BindMethod("ComputeW", &Nz::Quaterniond::ComputeW); - quaternion.BindMethod("Conjugate", &Nz::Quaterniond::Conjugate); - quaternion.BindMethod("DotProduct", &Nz::Quaterniond::DotProduct); - quaternion.BindMethod("GetConjugate", &Nz::Quaterniond::GetConjugate); - quaternion.BindMethod("GetInverse", &Nz::Quaterniond::GetInverse); - - quaternion.BindMethod("Inverse", &Nz::Quaterniond::Inverse); - quaternion.BindMethod("Magnitude", &Nz::Quaterniond::Magnitude); - - quaternion.BindMethod("SquaredMagnitude", &Nz::Quaterniond::SquaredMagnitude); - quaternion.BindMethod("ToEulerAngles", &Nz::Quaterniond::ToEulerAngles); - - quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString); - - quaternion.BindStaticMethod("Lerp", &Nz::Quaterniond::Lerp); - quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween); - quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp); - - quaternion.BindMethod("GetNormal", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int - { - double length; - - lua.Push(instance.GetNormal(&length)); - lua.Push(length); - - return 2; - }); - - quaternion.BindMethod("Normalize", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int - { - double length; - - instance.Normalize(&length); - lua.Push(1); //< instance - lua.Push(length); - - return 2; - }); - - quaternion.BindStaticMethod("Normalize", [] (Nz::LuaState& state) -> int - { - int argIndex = 1; - Nz::Quaterniond quat = state.Check(&argIndex); - - double length; - - state.Push(Nz::Quaterniond::Normalize(quat, &length)); - state.Push(length); - - return 2; - }); - - quaternion.SetGetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance) - { - std::size_t length; - const char* wxyz = lua.CheckString(2, &length); - - if (length != 1) - return false; - - switch (wxyz[0]) - { - case 'w': - lua.Push(instance.w); - return true; - - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'z': - lua.Push(instance.z); - return true; - } - - return false; - }); - - quaternion.SetSetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance) - { - std::size_t length; - const char* wxyz = lua.CheckString(2, &length); - - if (length != 1) - return false; - - double value = lua.CheckNumber(3); - - switch (wxyz[0]) - { - case 'w': - instance.w = value; - return true; - - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'z': - instance.z = value; - return true; - - default: - break; - } - - return false; - }); - } - - /*********************************** Nz::Vector2 **********************************/ - vector2d.Reset("Vector2"); - { - vector2d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector2d* vector, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 2U); - - switch (argCount) - { - case 0: - case 2: - Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1)); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - } - - lua.Error("No matching overload for Vector2 constructor"); - return false; - }); - - vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString); - - vector2d.SetGetter([] (Nz::LuaState& lua, Nz::Vector2d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 2) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xy = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xy[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - vector2d.SetSetter([] (Nz::LuaState& lua, Nz::Vector2d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 2) - return false; - - instance[index - 1] = lua.CheckNumber(3); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xy = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xy[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - } - - /*********************************** Nz::Vector3 **********************************/ - vector3d.Reset("Vector3"); - { - vector3d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector3d* vector, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 0: - case 3: - Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0)); - return true; - - case 1: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1)); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else if (lua.IsOfType(1, "Vector3")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1))); - else - break; - - return true; - } - - case 2: - { - if (lua.IsOfType(1, Nz::LuaType_Number)) - Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast(lua.CheckUserdata(2, "Vector2"))); - else if (lua.IsOfType(1, "Vector2")) - Nz::PlacementNew(vector, *static_cast(lua.ToUserdata(1)), lua.CheckNumber(2)); - else - break; - - return true; - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString); - - vector3d.SetGetter([] (Nz::LuaState& lua, Nz::Vector3d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 3) - return false; - - lua.Push(instance[index - 1]); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xyz = lua.CheckString(2, &length); - - if (length != 1) - break; - - switch (xyz[0]) - { - case 'x': - lua.Push(instance.x); - return true; - - case 'y': - lua.Push(instance.y); - return true; - - case 'z': - lua.Push(instance.z); - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - - vector3d.SetSetter([] (Nz::LuaState& lua, Nz::Vector3d& instance) - { - switch (lua.GetType(2)) - { - case Nz::LuaType_Number: - { - long long index = lua.CheckInteger(2); - if (index < 1 || index > 3) - return false; - - instance[index - 1] = lua.CheckNumber(3); - return true; - } - - case Nz::LuaType_String: - { - std::size_t length; - const char* xyz = lua.CheckString(2, &length); - - if (length != 1) - break; - - double value = lua.CheckNumber(3); - - switch (xyz[0]) - { - case 'x': - instance.x = value; - return true; - - case 'y': - instance.y = value; - return true; - - case 'z': - instance.z = value; - return true; - - default: - break; - } - break; - } - - default: - break; - } - - return false; - }); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Math classes - */ - void LuaBinding_Math::Register(Nz::LuaState& state) - { - eulerAngles.Register(state); - matrix4d.Register(state); - quaternion.Register(state); - rect.Register(state); - vector2d.Register(state); - vector3d.Register(state); - - quaternion.PushGlobalTable(state); - { - state.PushField("Identity", Nz::Quaterniond::Identity()); - state.PushField("Zero", Nz::Quaterniond::Zero()); - } - state.Pop(); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Network.cpp b/SDK/src/NDK/Lua/LuaBinding_Network.cpp deleted file mode 100644 index f3f82264a..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Network.cpp +++ /dev/null @@ -1,314 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindNetwork(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Network::LuaBinding_Network(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::AbstractSocket **********************************/ - abstractSocket.Reset("AbstractSocket"); - { - abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close); - abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking); - abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError); - abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState); - abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType); - abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled); - abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes); - } - - /*********************************** Nz::IpAddress **********************************/ - ipAddress.Reset("IpAddress"); - { - ipAddress.SetConstructor([] (Nz::LuaState& lua, Nz::IpAddress* instance, std::size_t argumentCount) - { - std::size_t argCount = std::min(argumentCount, 9U); - - int argIndex = 1; - switch (argCount) - { - case 0: - Nz::PlacementNew(instance); - return true; - - case 1: - Nz::PlacementNew(instance, lua.CheckString(argIndex)); - return true; - - case 4: - case 5: - { - Nz::UInt8 a = lua.Check(&argIndex); - Nz::UInt8 b = lua.Check(&argIndex); - Nz::UInt8 c = lua.Check(&argIndex); - Nz::UInt8 d = lua.Check(&argIndex); - Nz::UInt16 port = lua.Check(&argIndex, 0); - - Nz::PlacementNew(instance, a, b, c, d, port); - return true; - } - - case 8: - case 9: - { - Nz::UInt16 a = lua.Check(&argIndex); - Nz::UInt16 b = lua.Check(&argIndex); - Nz::UInt16 c = lua.Check(&argIndex); - Nz::UInt16 d = lua.Check(&argIndex); - Nz::UInt16 e = lua.Check(&argIndex); - Nz::UInt16 f = lua.Check(&argIndex); - Nz::UInt16 g = lua.Check(&argIndex); - Nz::UInt16 h = lua.Check(&argIndex); - Nz::UInt16 port = lua.Check(&argIndex, 0); - - Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port); - return true; - } - } - - lua.Error("No matching overload for constructor"); - return false; - }); - - ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort); - ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol); - ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback); - ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid); - ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32); - ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString); - - ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaState& state) -> int - { - Nz::String service; - Nz::ResolveError error = Nz::ResolveError_Unknown; - - int argIndex = 2; - Nz::String hostName = Nz::IpAddress::ResolveAddress(state.Check(&argIndex), &service, &error); - - if (error == Nz::ResolveError_NoError) - { - state.Push(hostName); - state.Push(service); - return 2; - } - else - { - state.PushBoolean(false); - state.Push(error); - return 2; - } - }); - - ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaState& state) -> int - { - Nz::ResolveError error = Nz::ResolveError_Unknown; - - int argIndex = 2; - Nz::NetProtocol protocol = state.Check(&argIndex); - Nz::String hostname = state.Check(&argIndex); - Nz::String service = state.Check(&argIndex, "http"); - - std::vector addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error); - if (error == Nz::ResolveError_NoError) - { - int index = 1; - state.PushTable(addresses.size()); - for (Nz::HostnameInfo& info : addresses) - { - state.PushInteger(index++); - state.PushTable(0, 4); - state.PushField("Address", std::move(info.address)); - state.PushField("CanonicalName", std::move(info.canonicalName)); - state.PushField("Protocol", std::move(info.protocol)); - state.PushField("SocketType", std::move(info.socketType)); - state.SetTable(); - } - - return 1; - } - else - { - state.PushBoolean(false); - state.Push(error); - return 2; - } - }); - } - - udpSocket.Reset("UdpSocket"); - { - udpSocket.Inherit(abstractSocket); - - udpSocket.BindDefaultConstructor(); - - udpSocket.BindMethod("Create", &Nz::UdpSocket::Create); - udpSocket.BindMethod("EnableBroadcasting", &Nz::UdpSocket::EnableBroadcasting); - udpSocket.BindMethod("GetBoundAddress", &Nz::UdpSocket::GetBoundAddress); - udpSocket.BindMethod("GetBoundPort", &Nz::UdpSocket::GetBoundPort); - udpSocket.BindMethod("IsBroadcastingEnabled", &Nz::UdpSocket::IsBroadcastingEnabled); - udpSocket.BindMethod("QueryMaxDatagramSize", &Nz::UdpSocket::QueryMaxDatagramSize); - - udpSocket.BindMethod("Bind", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - if (lua.IsOfType(argIndex, "IpAddress")) - return lua.Push(socket.Bind(*static_cast(lua.ToUserdata(argIndex)))); - else - return lua.Push(socket.Bind(lua.Check(&argIndex))); - }); - - udpSocket.BindMethod("Receive", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int - { - Nz::IpAddress from; - - std::array buffer; - std::size_t received; - if (socket.Receive(buffer.data(), buffer.size(), &from, &received)) - { - lua.PushBoolean(true); - lua.PushString(from.ToString()); - lua.PushString(buffer.data(), received); - return 3; - } - - lua.PushBoolean(false); - return 1; - }); - - udpSocket.BindMethod("Send", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - Nz::String to = lua.Check(&argIndex); - - std::size_t bufferLength; - const char* buffer = lua.CheckString(argIndex, &bufferLength); - - std::size_t sent; - bool ret; - if ((ret = socket.Send(Nz::IpAddress(to), buffer, bufferLength, &sent)) != true) - sent = 0; - - return lua.Push(std::make_pair(ret, sent)); - }); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Network classes - */ - void LuaBinding_Network::Register(Nz::LuaState& state) - { - // Classes - abstractSocket.Register(state); - ipAddress.Register(state); - udpSocket.Register(state); - - // Enums - - // Nz::NetProtocol - static_assert(Nz::NetProtocol_Max + 1 == 4, "Nz::NetProtocol has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 4); - { - state.PushField("Any", Nz::NetProtocol_Any); - state.PushField("IPv4", Nz::NetProtocol_IPv4); - state.PushField("IPv6", Nz::NetProtocol_IPv6); - state.PushField("Unknown", Nz::NetProtocol_Unknown); - } - state.SetGlobal("NetProtocol"); - - // Nz::PacketPriority - static_assert(Nz::PacketPriority_Max + 1 == 4, "Nz::PacketPriority has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 6); - { - state.PushField("High", Nz::PacketPriority_High); - state.PushField("Highest", Nz::PacketPriority_Highest); - state.PushField("Immediate", Nz::PacketPriority_Immediate); - state.PushField("Medium", Nz::PacketPriority_Medium); - state.PushField("Low", Nz::PacketPriority_Low); - state.PushField("Lowest", Nz::PacketPriority_Lowest); - } - state.SetGlobal("PacketPriority"); - - // Nz::PacketReliability - static_assert(Nz::PacketReliability_Max + 1 == 3, "Nz::PacketReliability has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 3); - { - state.PushField("Reliable", Nz::PacketReliability_Reliable); - state.PushField("ReliableOrdered", Nz::PacketReliability_ReliableOrdered); - state.PushField("Unreliable", Nz::PacketReliability_Unreliable); - } - state.SetGlobal("PacketReliability"); - - // Nz::ResolveError - static_assert(Nz::ResolveError_Max + 1 == 9, "Nz::ResolveError has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 9); - { - state.PushField("Internal", Nz::ResolveError_Internal); - state.PushField("ResourceError", Nz::ResolveError_ResourceError); - state.PushField("NoError", Nz::ResolveError_NoError); - state.PushField("NonRecoverable", Nz::ResolveError_NonRecoverable); - state.PushField("NotFound", Nz::ResolveError_NotFound); - state.PushField("NotInitialized", Nz::ResolveError_NotInitialized); - state.PushField("ProtocolNotSupported", Nz::ResolveError_ProtocolNotSupported); - state.PushField("TemporaryFailure", Nz::ResolveError_TemporaryFailure); - state.PushField("Unknown", Nz::ResolveError_Unknown); - } - state.SetGlobal("ResolveError"); - - // Nz::SocketError - static_assert(Nz::SocketError_Max + 1 == 16, "Nz::SocketError has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 16); - { - state.PushField("AddressNotAvailable", Nz::SocketError_AddressNotAvailable); - state.PushField("ConnectionClosed", Nz::SocketError_ConnectionClosed); - state.PushField("ConnectionRefused", Nz::SocketError_ConnectionRefused); - state.PushField("DatagramSize", Nz::SocketError_DatagramSize); - state.PushField("Internal", Nz::SocketError_Internal); - state.PushField("Interrupted", Nz::SocketError_Interrupted); - state.PushField("Packet", Nz::SocketError_Packet); - state.PushField("NetworkError", Nz::SocketError_NetworkError); - state.PushField("NoError", Nz::SocketError_NoError); - state.PushField("NotInitialized", Nz::SocketError_NotInitialized); - state.PushField("NotSupported", Nz::SocketError_NotSupported); - state.PushField("ResolveError", Nz::SocketError_ResolveError); - state.PushField("ResourceError", Nz::SocketError_ResourceError); - state.PushField("TimedOut", Nz::SocketError_TimedOut); - state.PushField("Unknown", Nz::SocketError_Unknown); - state.PushField("UnreachableHost", Nz::SocketError_UnreachableHost); - } - state.SetGlobal("SocketError"); - - // Nz::SocketState - static_assert(Nz::SocketState_Max + 1 == 5, "Nz::SocketState has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 5); - { - state.PushField("Bound", Nz::SocketState_Bound); - state.PushField("Connecting", Nz::SocketState_Connecting); - state.PushField("Connected", Nz::SocketState_Connected); - state.PushField("NotConnected", Nz::SocketState_NotConnected); - state.PushField("Resolving", Nz::SocketState_Resolving); - } - state.SetGlobal("SocketState"); - - // Nz::SocketType - static_assert(Nz::SocketType_Max + 1 == 4, "Nz::SocketState has been updated but change was not reflected to Lua binding"); - state.PushTable(0, 4); - { - state.PushField("Raw", Nz::SocketType_Raw); - state.PushField("TCP", Nz::SocketType_TCP); - state.PushField("UDP", Nz::SocketType_UDP); - state.PushField("Unknown", Nz::SocketType_Unknown); - } - state.SetGlobal("SocketType"); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Platform.cpp b/SDK/src/NDK/Lua/LuaBinding_Platform.cpp deleted file mode 100644 index 24a218fae..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Platform.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindPlatform(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Platform::LuaBinding_Platform(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::Keyboard **********************************/ - keyboard.Reset("Keyboard"); - { - //keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName); - //keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Utility classes - */ - void LuaBinding_Platform::Register(Nz::LuaState& state) - { - keyboard.Register(state); - - /*keyboard.PushGlobalTable(state); - { - static_assert(Nz::Keyboard::Max == 123, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding"); - - state.PushField("Undefined", Nz::Keyboard::Undefined); - - // A-Z - for (std::size_t i = 0; i < 26; ++i) - state.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i); - - // Numerical - for (std::size_t i = 0; i < 10; ++i) - { - state.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i); - state.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i); - } - - // F1-F15 - for (std::size_t i = 0; i < 15; ++i) - state.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i); - - // And all the others... - state.PushField("Down", Nz::Keyboard::Down); - state.PushField("Left", Nz::Keyboard::Left); - state.PushField("Right", Nz::Keyboard::Right); - state.PushField("Up", Nz::Keyboard::Up); - - state.PushField("Add", Nz::Keyboard::Add); - state.PushField("Decimal", Nz::Keyboard::Decimal); - state.PushField("Divide", Nz::Keyboard::Divide); - state.PushField("Multiply", Nz::Keyboard::Multiply); - state.PushField("Subtract", Nz::Keyboard::Subtract); - state.PushField("NumpadReturn", Nz::Keyboard::NumpadReturn); - - state.PushField("Backslash", Nz::Keyboard::Backslash); - state.PushField("Backspace", Nz::Keyboard::Backspace); - state.PushField("Clear", Nz::Keyboard::Clear); - state.PushField("Comma", Nz::Keyboard::Comma); - state.PushField("Dash", Nz::Keyboard::Dash); - state.PushField("Delete", Nz::Keyboard::Delete); - state.PushField("End", Nz::Keyboard::End); - state.PushField("Equal", Nz::Keyboard::Equal); - state.PushField("Escape", Nz::Keyboard::Escape); - state.PushField("Home", Nz::Keyboard::Home); - state.PushField("Insert", Nz::Keyboard::Insert); - state.PushField("LAlt", Nz::Keyboard::LAlt); - state.PushField("LBracket", Nz::Keyboard::LBracket); - state.PushField("LControl", Nz::Keyboard::LControl); - state.PushField("LShift", Nz::Keyboard::LShift); - state.PushField("LSystem", Nz::Keyboard::LSystem); - state.PushField("PageDown", Nz::Keyboard::PageDown); - state.PushField("PageUp", Nz::Keyboard::PageUp); - state.PushField("Pause", Nz::Keyboard::Pause); - state.PushField("Period", Nz::Keyboard::Period); - state.PushField("Print", Nz::Keyboard::Print); - state.PushField("PrintScreen", Nz::Keyboard::PrintScreen); - state.PushField("Quote", Nz::Keyboard::Quote); - state.PushField("RAlt", Nz::Keyboard::RAlt); - state.PushField("RBracket", Nz::Keyboard::RBracket); - state.PushField("RControl", Nz::Keyboard::RControl); - state.PushField("Return", Nz::Keyboard::Return); - state.PushField("RShift", Nz::Keyboard::RShift); - state.PushField("RSystem", Nz::Keyboard::RSystem); - state.PushField("Semicolon", Nz::Keyboard::Semicolon); - state.PushField("Slash", Nz::Keyboard::Slash); - state.PushField("Space", Nz::Keyboard::Space); - state.PushField("Tab", Nz::Keyboard::Tab); - state.PushField("Tilde", Nz::Keyboard::Tilde); - state.PushField("Menu", Nz::Keyboard::Menu); - state.PushField("ISOBackslash102", Nz::Keyboard::ISOBackslash102); - state.PushField("Browser_Back", Nz::Keyboard::Browser_Back); - state.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites); - state.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward); - state.PushField("Browser_Home", Nz::Keyboard::Browser_Home); - state.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh); - state.PushField("Browser_Search", Nz::Keyboard::Browser_Search); - state.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop); - state.PushField("Media_Next", Nz::Keyboard::Media_Next); - state.PushField("Media_Play", Nz::Keyboard::Media_Play); - state.PushField("Media_Previous", Nz::Keyboard::Media_Previous); - state.PushField("Media_Stop", Nz::Keyboard::Media_Stop); - state.PushField("Volume_Down", Nz::Keyboard::Volume_Down); - state.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute); - state.PushField("Volume_Up", Nz::Keyboard::Volume_Up); - state.PushField("CapsLock", Nz::Keyboard::CapsLock); - state.PushField("NumLock", Nz::Keyboard::NumLock); - state.PushField("ScrollLock", Nz::Keyboard::ScrollLock); - } - state.Pop();*/ - - static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding"); - state.PushTable(0, Nz::WindowStyle_Max + 1); - { - state.PushField("None", Nz::WindowStyle_None); - state.PushField("Fullscreen", Nz::WindowStyle_Fullscreen); - state.PushField("Closable", Nz::WindowStyle_Closable); - state.PushField("Resizable", Nz::WindowStyle_Resizable); - state.PushField("Titlebar", Nz::WindowStyle_Titlebar); - state.PushField("Threaded", Nz::WindowStyle_Threaded); - } - state.SetGlobal("WindowStyle"); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp b/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp deleted file mode 100644 index 8aacf2a1f..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Renderer.cpp +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq, Arnaud Cadot -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindRenderer(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Renderer::LuaBinding_Renderer(LuaBinding& binding) : - LuaBinding_Base(binding) - { - LuaBinding_Utility& utility = static_cast(*m_binding.utility); - - /*********************************** Nz::Texture ***********************************/ - texture.Reset("Texture"); - { - texture.Inherit(utility.abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef* - { - return reinterpret_cast(textureRef); //TODO: Make a ObjectRefCast - }); - - texture.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(instance, Nz::Texture::New()); - return true; - }); - - texture.BindMethod("Create", &Nz::Texture::Create, static_cast(1), 1U); - texture.BindMethod("Destroy", &Nz::Texture::Destroy); - - //texture.BindMethod("Download", &Nz::Texture::Download); - - texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping); - texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate); - texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps); - texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps); - texture.BindMethod("IsValid", &Nz::Texture::IsValid); - - texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams()); - //bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams()); - //bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams()); - - texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams()); - //bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams()); - - texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange); - - texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported); - texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported); - texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported); - - texture.BindStaticMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams()); - //TextureRef LoadFromImage(const Image& image, bool generateMipmaps = true); - //TextureRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true); - //TextureRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true); - - texture.BindStaticMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams()); - //TextureRef LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - //TextureRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - //TextureRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2)); - - //TextureRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - //TextureRef LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams()); - //TextureRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - //TextureRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams()); - } - - /*********************************** Nz::TextureLibrary ***********************************/ - textureLibrary.Reset("TextureLibrary"); - { - textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get); - textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has); - textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register); - textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query); - textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister); - } - - /*********************************** Nz::TextureManager ***********************************/ - textureManager.Reset("TextureManager"); - { - textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear); - textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get); - textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters); - textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge); - textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register); - textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters); - textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Renderer classes - */ - void LuaBinding_Renderer::Register(Nz::LuaState& state) - { - texture.Register(state); - textureLibrary.Register(state); - textureManager.Register(state); - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_SDK.cpp b/SDK/src/NDK/Lua/LuaBinding_SDK.cpp deleted file mode 100644 index 805f7742d..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_SDK.cpp +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq, Arnaud Cadot -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -#ifndef NDK_SERVER -#include -#endif - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindSDK(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_SDK::LuaBinding_SDK(LuaBinding& binding) : - LuaBinding_Base(binding) - { - #ifndef NDK_SERVER - LuaBinding_Graphics& graphics = static_cast(*m_binding.graphics); - #endif - - LuaBinding_Utility& utility = static_cast(*m_binding.utility); - - /*********************************** Ndk::Application **********************************/ - application.Reset("Application"); - { - #ifndef NDK_SERVER - //application.SetMethod("AddWindow", &Application::AddWindow); - - application.BindMethod("EnableConsole", &Application::EnableConsole); - application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter); - - application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled); - application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); - #endif - - application.BindMethod("AddWorld", [] (Nz::LuaState& lua, Application* instance, std::size_t /*argumentCount*/) -> int - { - lua.Push(instance->AddWorld().CreateHandle()); - return 1; - }); - - application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); - application.BindMethod("Quit", &Application::Quit); - } - - /*********************************** Ndk::Console **********************************/ - #ifndef NDK_SERVER - console.Reset("Console"); - { - console.Inherit(utility.node, [] (ConsoleHandle* handle) -> Nz::Node* - { - return handle->GetObject(); - }); - - console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); - console.BindMethod("Clear", &Console::Clear); - console.BindMethod("GetCharacterSize", &Console::GetCharacterSize); - //console.BindMethod("GetHistory", &Console::GetHistory); - //console.BindMethod("GetInput", &Console::GetInput); - console.BindMethod("GetTextFont", &Console::GetTextFont); - - console.BindMethod("IsValidHandle", &ConsoleHandle::IsValid); - - console.BindMethod("SetCharacterSize", &Console::SetCharacterSize); - console.BindMethod("SetTextFont", &Console::SetTextFont); - } - #endif - - /*********************************** Ndk::Entity **********************************/ - entity.Reset("Entity"); - { - entity.BindMethod("Enable", &Entity::Enable, true); - entity.BindMethod("GetId", &Entity::GetId); - entity.BindMethod("GetWorld", &Entity::GetWorld); - entity.BindMethod("Kill", &Entity::Kill); - entity.BindMethod("IsEnabled", &Entity::IsEnabled); - entity.BindMethod("IsValid", &Entity::IsValid); - entity.BindMethod("IsValidHandle", &EntityHandle::IsValid); - entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); - entity.BindMethod("__tostring", &EntityHandle::ToString); - - entity.BindMethod("AddComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); - - return bindingComponent->adder(state, handle); - }); - - entity.BindMethod("HasComponent", [this](Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); - - state.PushBoolean(handle->HasComponent(bindingComponent->index)); - return 1; - }); - - entity.BindMethod("GetComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); - - return bindingComponent->getter(state, handle->GetComponent(bindingComponent->index)); - }); - - entity.BindMethod("RemoveComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int - { - LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state); - - handle->RemoveComponent(bindingComponent->index); - return 0; - }); - } - - /*********************************** Ndk::NodeComponent **********************************/ - nodeComponent.Reset("NodeComponent"); - { - nodeComponent.BindMethod("IsValidHandle", &NodeComponentHandle::IsValid); - - nodeComponent.Inherit(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node* - { - return handle->GetObject(); - }); - } - - /*********************************** Ndk::VelocityComponent **********************************/ - velocityComponent.Reset("VelocityComponent"); - { - velocityComponent.BindMethod("IsValidHandle", &VelocityComponentHandle::IsValid); - - velocityComponent.SetGetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance) - { - std::size_t length; - const char* member = lua.CheckString(2, &length); - - if (std::strcmp(member, "Linear") == 0) - { - lua.Push(instance->linearVelocity); - return true; - } - - return false; - }); - - velocityComponent.SetSetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance) - { - std::size_t length; - const char* member = lua.CheckString(2, &length); - - int argIndex = 3; - if (std::strcmp(member, "Linear") == 0) - { - instance->linearVelocity = lua.Check(&argIndex); - return true; - } - - return false; - }); - } - - /*********************************** Ndk::World **********************************/ - world.Reset("World"); - { - world.BindMethod("CreateEntity", &World::CreateEntity); - world.BindMethod("CreateEntities", &World::CreateEntities); - world.BindMethod("Clear", &World::Clear); - world.BindMethod("DisableProfiler", &World::DisableProfiler); - world.BindMethod("EnableProfiler", &World::EnableProfiler); - world.BindMethod("IsProfilerEnabled", &World::IsProfilerEnabled); - world.BindMethod("Refresh", &World::Refresh); - world.BindMethod("ResetProfiler", &World::ResetProfiler); - world.BindMethod("Update", &World::Update); - - world.BindMethod("IsValidHandle", &WorldHandle::IsValid); - } - - #ifndef NDK_SERVER - /*********************************** Ndk::CameraComponent **********************************/ - cameraComponent.Reset("CameraComponent"); - { - cameraComponent.Inherit(graphics.abstractViewer, [] (CameraComponentHandle* handle) -> Nz::AbstractViewer* - { - return handle->GetObject(); - }); - - cameraComponent.BindMethod("GetFOV", &CameraComponent::GetFOV); - cameraComponent.BindMethod("GetLayer", &CameraComponent::GetLayer); - - cameraComponent.BindMethod("IsValidHandle", &CameraComponentHandle::IsValid); - - cameraComponent.BindMethod("SetFOV", &CameraComponent::SetFOV); - cameraComponent.BindMethod("SetLayer", &CameraComponent::SetLayer); - cameraComponent.BindMethod("SetProjectionType", &CameraComponent::SetProjectionType); - cameraComponent.BindMethod("SetSize", (void(CameraComponent::*)(const Nz::Vector2f&)) &CameraComponent::SetSize); - //cameraComponent.BindMethod("SetTarget", &CameraComponent::SetTarget); - cameraComponent.BindMethod("SetTargetRegion", &CameraComponent::SetTargetRegion); - cameraComponent.BindMethod("SetViewport", &CameraComponent::SetViewport); - cameraComponent.BindMethod("SetZFar", &CameraComponent::SetZFar); - cameraComponent.BindMethod("SetZNear", &CameraComponent::SetZNear); - } - - /*********************************** Ndk::GraphicsComponent **********************************/ - graphicsComponent.Reset("GraphicsComponent"); - { - graphicsComponent.BindMethod("Attach", [] (Nz::LuaState& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int - { - /* - void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0); - void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0); - */ - - std::size_t argCount = std::min(argumentCount, 3U); - - switch (argCount) - { - case 1: - { - int argIndex = 2; - instance->Attach(lua.Check(&argIndex)); - return 0; - } - - case 2: - { - int argIndex = 2; - Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); - - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - int renderOrder = lua.Check(&argIndex); - - instance->Attach(renderable, renderOrder); - } - else if (lua.IsOfType(argIndex, "Matrix4")) - { - Nz::Matrix4f localMatrix = lua.Check(&argIndex); - - instance->Attach(renderable, localMatrix); - } - else - break; - - return 0; - } - - case 3: - { - int argIndex = 2; - Nz::InstancedRenderableRef renderable = lua.Check(&argIndex); - Nz::Matrix4f localMatrix = lua.Check(&argIndex); - int renderOrder = lua.Check(&argIndex); - - instance->Attach(renderable, localMatrix, renderOrder); - return 0; - } - } - - lua.Error("No matching overload for method GetMemoryUsage"); - return 0; - }); - - graphicsComponent.BindMethod("IsValidHandle", &GraphicsComponentHandle::IsValid); - } - #endif - - // Components functions - m_binding.BindComponent("Node"); - m_binding.BindComponent("Velocity"); - - #ifndef NDK_SERVER - m_binding.BindComponent("Camera"); - m_binding.BindComponent("Graphics"); - #endif - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the SDK classes - */ - void LuaBinding_SDK::Register(Nz::LuaState& state) - { - // Classes - application.Register(state); - entity.Register(state); - nodeComponent.Register(state); - velocityComponent.Register(state); - world.Register(state); - - #ifndef NDK_SERVER - cameraComponent.Register(state); - console.Register(state); - graphicsComponent.Register(state); - #endif - - // Enums - } - - /*! - * \brief Gets the index of the component - * \return A pointer to the binding linked to a component - * - * \param instance Lua instance that will interact with the component - * \param argIndex Index of the component - */ - LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaState& state, int argIndex) - { - switch (state.GetType(argIndex)) - { - case Nz::LuaType_Number: - { - ComponentIndex componentIndex = state.Check(&argIndex); - if (componentIndex > m_componentBinding.size()) - { - state.Error("Invalid component index"); - return nullptr; - } - - ComponentBinding& binding = m_componentBinding[componentIndex]; - if (binding.name.IsEmpty()) - { - state.Error("Invalid component index"); - return nullptr; - } - - return &binding; - } - - case Nz::LuaType_String: - { - const char* key = state.CheckString(argIndex); - auto it = m_componentBindingByName.find(key); - if (it == m_componentBindingByName.end()) - { - state.Error("Invalid component name"); - return nullptr; - } - - return &m_componentBinding[it->second]; - } - - default: - break; - } - - state.Error("Invalid component index at #" + Nz::String::Number(argIndex)); - return nullptr; - } -} diff --git a/SDK/src/NDK/Lua/LuaBinding_Utility.cpp b/SDK/src/NDK/Lua/LuaBinding_Utility.cpp deleted file mode 100644 index 262620b12..000000000 --- a/SDK/src/NDK/Lua/LuaBinding_Utility.cpp +++ /dev/null @@ -1,338 +0,0 @@ -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - std::unique_ptr LuaBinding_Base::BindUtility(LuaBinding& binding) - { - return std::make_unique(binding); - } - - LuaBinding_Utility::LuaBinding_Utility(LuaBinding& binding) : - LuaBinding_Base(binding) - { - /*********************************** Nz::AbstractImage **********************************/ - abstractImage.Reset("AbstractImage"); - { - abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel); - abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast(0)); - abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat); - abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast(0)); - abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount); - abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel); - abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast(0)); - abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType); - abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast(0)); - abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed); - abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap); - - abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 1U); - switch (argCount) - { - case 0: - return lua.Push(instance->GetMemoryUsage()); - - case 1: - { - int argIndex = 2; - Nz::UInt8 level(lua.Check(&argIndex)); - - return lua.Push(instance->GetMemoryUsage(level)); - } - } - - lua.Error("No matching overload for method GetMemoryUsage"); - return 0; - }); - - abstractImage.BindMethod("Update", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 6U); - int argIndex = 2; - - std::size_t bufferSize = 0; - const Nz::UInt8* pixels = reinterpret_cast(lua.CheckString(argIndex++, &bufferSize)); - - if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number)) - { - // bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level)); - } - /* Disabled until Box and Rect have been ported - else if (lua.IsOfType(2, "Box")) - { - // bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - Nz::Boxui box = lua.Check(&argIndex); - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); - } - else if (lua.IsOfType(2, "Rect")) - { - // bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0) - Nz::Rectui box = lua.Check(&argIndex); - unsigned int srcWidth = lua.Check(&argIndex, 0); - unsigned int srcHeight = lua.Check(&argIndex, 0); - Nz::UInt8 level = lua.Check(&argIndex, 0); - - ///TODO: Buffer checks (Nz::ByteBufferView ?) - return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level)); - }*/ - - lua.Error("No matching overload for method Update"); - return 0; - }); - } - - /*********************************** Nz::Font **********************************/ - font.Reset("Font"); - { - font.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/) - { - Nz::PlacementNew(instance, Nz::Font::New()); - return true; - }); - - font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache); - font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache); - font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache); - - font.BindMethod("Destroy", &Nz::Font::Destroy); - - font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaState& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 2U); - - int argIndex = 2; - switch (argCount) - { - case 0: - lua.Push(instance->GetCachedGlyphCount()); - return 1; - - case 3: - { - unsigned int characterSize = lua.Check(&argIndex); - Nz::TextStyleFlags style = lua.Check(&argIndex); - float outlineThickness = lua.Check(&argIndex); - - lua.Push(instance->GetCachedGlyphCount(characterSize, style, outlineThickness)); - return 1; - } - } - - lua.Error("No matching overload for method GetCachedGlyphCount"); - return 0; - }); - - font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName); - font.BindMethod("GetKerning", &Nz::Font::GetKerning); - font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder); - font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize); - font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo); - font.BindMethod("GetStyleName", &Nz::Font::GetStyleName); - - font.BindMethod("IsValid", &Nz::Font::IsValid); - - font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::TextStyleFlags, float, const Nz::String&) const) &Nz::Font::Precache); - - font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder); - font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize); - - font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault); - font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder); - font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize); - - font.BindStaticMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams()); - - font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder); - font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize); - } - - /*********************************** Nz::Node **********************************/ - node.Reset("Node"); - { - node.BindMethod("GetBackward", &Nz::Node::GetBackward); - //nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds); - node.BindMethod("GetDown", &Nz::Node::GetDown); - node.BindMethod("GetForward", &Nz::Node::GetForward); - node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); - //nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - node.BindMethod("GetLeft", &Nz::Node::GetLeft); - node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); - //nodeClass.SetMethod("GetParent", &Nz::Node::GetParent); - node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - node.BindMethod("GetRight", &Nz::Node::GetRight); - //nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); - //nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix); - node.BindMethod("GetUp", &Nz::Node::GetUp); - - node.BindMethod("HasChilds", &Nz::Node::HasChilds); - - node.BindMethod("GetBackward", &Nz::Node::GetBackward); - node.BindMethod("GetDown", &Nz::Node::GetDown); - node.BindMethod("GetForward", &Nz::Node::GetForward); - node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition); - node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation); - node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale); - node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition); - node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation); - node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale); - node.BindMethod("GetLeft", &Nz::Node::GetLeft); - node.BindMethod("GetNodeType", &Nz::Node::GetNodeType); - node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global); - node.BindMethod("GetRight", &Nz::Node::GetRight); - node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global); - node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global); - node.BindMethod("GetUp", &Nz::Node::GetUp); - - node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition); - node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation); - - node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local); - node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local); - - node.BindMethod("Move", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - - Nz::Vector3f offset = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - instance.Move(offset, coordSys); - - return 0; - }); - - node.BindMethod("Rotate", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int - { - int argIndex = 2; - - Nz::Quaternionf rotation = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - instance.Rotate(rotation, coordSys); - - return 0; - }); - - node.BindMethod("Scale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - instance.Scale(lua.Check(&argIndex)); - else - instance.Scale(lua.Check(&argIndex)); - - return 0; - } - - case 3: - instance.Scale(lua.Check(&argIndex)); - return 0; - } - - lua.Error("No matching overload for method Scale"); - return 0; - }); - - node.BindMethod("SetScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - case 2: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - { - float scale = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - instance.SetScale(scale, coordSys); - } - else - instance.SetScale(lua.Check(&argIndex)); - - return 0; - } - - case 3: - case 4: - { - Nz::Vector3f scale = lua.Check(&argIndex); - Nz::CoordSys coordSys = lua.Check(&argIndex, Nz::CoordSys_Local); - - instance.SetScale(scale, coordSys); - return 0; - } - } - - lua.Error("No matching overload for method SetScale"); - return 0; - }); - - node.BindMethod("SetInitialScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int - { - std::size_t argCount = std::min(argumentCount, 4U); - - int argIndex = 2; - switch (argCount) - { - case 1: - { - if (lua.IsOfType(argIndex, Nz::LuaType_Number)) - instance.SetInitialScale(lua.Check(&argIndex)); - else - instance.SetInitialScale(lua.Check(&argIndex)); - - return 0; - } - - case 2: - case 3: - instance.SetInitialScale(lua.Check(&argIndex)); - return 0; - } - - lua.Error("No matching overload for method SetInitialScale"); - return 0; - }); - } - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the Utility classes - */ - void LuaBinding_Utility::Register(Nz::LuaState& state) - { - abstractImage.Register(state); - font.Register(state); - node.Register(state); - } -} diff --git a/SDK/src/NDK/LuaAPI.cpp b/SDK/src/NDK/LuaAPI.cpp deleted file mode 100644 index 3a82d2130..000000000 --- a/SDK/src/NDK/LuaAPI.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// This file was automatically generated on 26 May 2014 at 01:05:31 - -#include -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::LuaAPI - * \brief NDK class that represents the api used for Lua - */ - - /*! - * \brief Gets the internal binding for Lua - * \return A pointer to the binding - */ - LuaBinding* LuaAPI::GetBinding() - { - if (!s_binding && !Initialize()) - { - NazaraError("Failed to initialize binding"); - return nullptr; - } - - return s_binding; - } - - /*! - * \brief Initializes the LuaAPI module - * \return true if initialization is successful - */ - - bool LuaAPI::Initialize() - { - s_binding = new LuaBinding; - return true; - } - - /*! - * \brief Registers the classes that will be used by the Lua instance - * - * \param instance Lua instance that will interact with the engine & SDK - */ - - void LuaAPI::RegisterClasses(Nz::LuaState& state) - { - Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true); - GetBinding()->RegisterClasses(state); - } - - /*! - * \brief Uninitializes the LuaAPI module - */ - - void LuaAPI::Uninitialize() - { - delete s_binding; - } - - LuaBinding* LuaAPI::s_binding = nullptr; -} diff --git a/SDK/src/NDK/Sdk.cpp b/SDK/src/NDK/Sdk.cpp deleted file mode 100644 index 341e6f0d5..000000000 --- a/SDK/src/NDK/Sdk.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef NDK_SERVER -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::Sdk - * \brief NDK class that represents the software development kit, a set of tools made to ease the conception of application - */ - - /*! - * \brief Initializes the Sdk module - * \return true if initialization is successful - * - * \remark Produces a NazaraNotice - */ - - bool Sdk::Initialize() - { - if (s_referenceCounter++ > 0) - return true; // Already initialized - - try - { - Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true); - - // Initialize the engine first - - // Shared modules - Nz::Lua::Initialize(); - Nz::Noise::Initialize(); - Nz::Physics2D::Initialize(); - Nz::Physics3D::Initialize(); - Nz::Utility::Initialize(); - - #ifndef NDK_SERVER - // Client modules - Nz::Audio::Initialize(); - Nz::Graphics::Initialize(); - #endif - - // SDK Initialization - - // Components - BaseComponent::Initialize(); - - // Shared components - InitializeComponent("NdkColl2"); - InitializeComponent("NdkColl3"); - InitializeComponent("NdkLiftm"); - InitializeComponent("NdkNode"); - InitializeComponent("NdkPhys2"); - InitializeComponent("NdkPhys3"); - InitializeComponent("NdkVeloc"); - InitializeComponent("NdkCons2"); - - #ifndef NDK_SERVER - // Client components - InitializeComponent("NdkCam"); - InitializeComponent("NdkDebug"); - InitializeComponent("NdkLight"); - InitializeComponent("NdkList"); - InitializeComponent("NdkGfx"); - InitializeComponent("NdkPaEmi"); - InitializeComponent("NdkPaGrp"); - #endif - - // Systems - - BaseSystem::Initialize(); - - // Shared systems - InitializeSystem(); - InitializeSystem(); - InitializeSystem(); - InitializeSystem(); - - #ifndef NDK_SERVER - // Client systems - InitializeSystem(); - InitializeSystem(); - InitializeSystem(); - InitializeSystem(); - - // Widgets - if (!CheckboxWidget::Initialize()) - { - NazaraError("Failed to initialize Checkbox Widget"); - return false; - } - #endif - - NazaraNotice("Initialized: SDK"); - return true; - } - catch (const std::exception& e) - { - NazaraError("Failed to initialize NDK: " + Nz::String(e.what())); - return false; - } - } - - /*! - * \brief Uninitializes the Sdk module - * - * \remark Produces a NazaraNotice - */ - - void Sdk::Uninitialize() - { - if (s_referenceCounter != 1) - { - // Either the module is not initialized, either it was initialized multiple times - if (s_referenceCounter > 1) - s_referenceCounter--; - - return; - } - - // Uninitialize the SDK - s_referenceCounter = 0; - - // Components - BaseComponent::Uninitialize(); - - // Systems - BaseSystem::Uninitialize(); - - // Uninitialize the engine - - #ifndef NDK_SERVER - // Client modules - Nz::Audio::Uninitialize(); - Nz::Graphics::Uninitialize(); - #endif - - // Shared modules - Nz::Lua::Uninitialize(); - Nz::Noise::Uninitialize(); - Nz::Physics2D::Uninitialize(); - Nz::Physics3D::Uninitialize(); - Nz::Utility::Uninitialize(); - - #ifndef NDK_SERVER - // Widgets - CheckboxWidget::Uninitialize(); - #endif - - NazaraNotice("Uninitialized: SDK"); - } - - unsigned int Sdk::s_referenceCounter = 0; -} diff --git a/SDK/src/NDK/Systems/DebugSystem.cpp b/SDK/src/NDK/Systems/DebugSystem.cpp deleted file mode 100644 index 5b8bb7aa6..000000000 --- a/SDK/src/NDK/Systems/DebugSystem.cpp +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - namespace - { - class DebugRenderable : public Nz::InstancedRenderable - { - public: - DebugRenderable(Ndk::Entity* owner, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) : - m_entityOwner(owner), - m_indexBuffer(std::move(indexBuffer)), - m_vertexBuffer(std::move(vertexBuffer)) - { - ResetMaterials(1); - - m_meshData.indexBuffer = m_indexBuffer; - m_meshData.primitiveMode = Nz::PrimitiveMode_LineList; - m_meshData.vertexBuffer = m_vertexBuffer; - } - - void UpdateBoundingVolume(InstanceData* /*instanceData*/) const override - { - } - - void MakeBoundingVolume() const override - { - // We generate an infinite bounding volume so that we're always considered for rendering when culling does occurs - // (bounding volume culling happens only if GraphicsComponent AABB partially fail) - m_boundingVolume.MakeInfinite(); - } - - protected: - Ndk::EntityHandle m_entityOwner; - Nz::IndexBufferRef m_indexBuffer; - Nz::MeshData m_meshData; - Nz::VertexBufferRef m_vertexBuffer; - }; - - class AABBDebugRenderable : public DebugRenderable - { - public: - AABBDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef globalMaterial, Nz::MaterialRef localMaterial, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) : - DebugRenderable(owner, std::move(indexBuffer), std::move(vertexBuffer)), - m_globalMaterial(std::move(globalMaterial)), - m_localMaterial(std::move(localMaterial)) - { - } - - void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override - { - NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); - - const DebugComponent& entityDebug = m_entityOwner->GetComponent(); - const GraphicsComponent& entityGfx = m_entityOwner->GetComponent(); - - auto DrawBox = [&](const Nz::Boxf& box, const Nz::MaterialRef& mat) - { - Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity(); - transformMatrix.SetScale(box.GetLengths()); - transformMatrix.SetTranslation(box.GetCenter()); - - renderQueue->AddMesh(0, mat, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect); - }; - - DrawBox(entityGfx.GetAABB(), m_globalMaterial); - - for (std::size_t i = 0; i < entityGfx.GetAttachedRenderableCount(); ++i) - { - const Nz::BoundingVolumef& boundingVolume = entityGfx.GetBoundingVolume(i); - if (boundingVolume.IsFinite()) - DrawBox(boundingVolume.aabb, m_localMaterial); - } - } - - std::unique_ptr Clone() const override - { - return nullptr; - } - - private: - Nz::MaterialRef m_globalMaterial; - Nz::MaterialRef m_localMaterial; - }; - - class OBBDebugRenderable : public DebugRenderable - { - public: - OBBDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef material, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) : - DebugRenderable(owner, std::move(indexBuffer), std::move(vertexBuffer)), - m_material(std::move(material)) - { - } - - void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override - { - NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); - - const DebugComponent& entityDebug = m_entityOwner->GetComponent(); - const GraphicsComponent& entityGfx = m_entityOwner->GetComponent(); - - auto DrawBox = [&](const Nz::Boxf& box, const Nz::Matrix4f& transformMatrix) - { - Nz::Matrix4f boxMatrix = Nz::Matrix4f::Identity(); - boxMatrix.SetScale(box.GetLengths()); - boxMatrix.SetTranslation(box.GetCenter()); - boxMatrix.ConcatenateAffine(transformMatrix); - - renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), boxMatrix, scissorRect); - }; - - for (std::size_t i = 0; i < entityGfx.GetAttachedRenderableCount(); ++i) - { - const Nz::BoundingVolumef& boundingVolume = entityGfx.GetBoundingVolume(i); - if (boundingVolume.IsFinite()) - DrawBox(boundingVolume.obb.localBox, entityGfx.GetTransformMatrix(i)); - } - } - - std::unique_ptr Clone() const override - { - return nullptr; - } - - private: - Nz::MaterialRef m_material; - }; - } - - /*! - * \ingroup NDK - * \class Ndk::DebugSystem - * \brief NDK class that represents the debug system - * - * \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent - */ - - /*! - * \brief Constructs an DebugSystem object by default - */ - DebugSystem::DebugSystem() : - m_isDepthBufferEnabled(true) - { - Requires(); - SetUpdateOrder(1000); //< Update last - } - - void DebugSystem::EnableDepthBuffer(bool enable) - { - m_isDepthBufferEnabled = enable; - - if (m_collisionMaterial) - m_collisionMaterial->EnableDepthBuffer(enable); - - if (m_globalAabbMaterial) - m_globalAabbMaterial->EnableDepthBuffer(enable); - - if (m_localAabbMaterial) - m_localAabbMaterial->EnableDepthBuffer(enable); - - if (m_obbMaterial) - m_obbMaterial->EnableDepthBuffer(enable); - } - - Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box) - { - Nz::MeshRef mesh = Nz::Mesh::New(); - mesh->CreateStatic(); - - mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths())); - mesh->SetMaterialCount(1); - - Nz::ModelRef model = Nz::Model::New(); - model->SetMesh(mesh); - model->SetMaterial(0, GetOBBMaterial()); - - return model; - } - - Nz::InstancedRenderableRef DebugSystem::GenerateCollision2DMesh(Entity* entity, Nz::Vector3f* offset) - { - if (entity->HasComponent()) - { - CollisionComponent2D& entityCollision = entity->GetComponent(); - const Nz::Collider2DRef& geom = entityCollision.GetGeom(); - - std::vector vertices; - std::vector indices; - - geom->ForEachPolygon([&](const Nz::Vector2f* polygonVertices, std::size_t vertexCount) - { - std::size_t firstIndex = vertices.size(); - - // Don't reserve and let the vector handle its own capacity - for (std::size_t i = 0; i < vertexCount; ++i) - vertices.emplace_back(*polygonVertices++); - - for (std::size_t i = 0; i < vertexCount - 1; ++i) - { - indices.push_back(firstIndex + i); - indices.push_back(firstIndex + i + 1); - } - - indices.push_back(firstIndex + vertexCount - 1); - indices.push_back(firstIndex); - }); - - Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0); - Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly); - - Nz::IndexIterator indexPtr = indexMapper.begin(); - for (std::size_t index : indices) - *indexPtr++ = static_cast(index); - - indexMapper.Unmap(); - - Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0); - vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size())); - - Nz::MeshRef mesh = Nz::Mesh::New(); - mesh->CreateStatic(); - - Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(vertexBuffer, indexBuffer); - subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList); - subMesh->SetMaterialIndex(0); - subMesh->GenerateAABB(); - - mesh->SetMaterialCount(1); - mesh->AddSubMesh(subMesh); - - Nz::ModelRef model = Nz::Model::New(); - model->SetMesh(mesh); - model->SetMaterial(0, GetCollisionMaterial()); - - // Find center of mass - if (entity->HasComponent()) - { - const PhysicsComponent2D& entityPhys = entity->GetComponent(); - *offset = entityPhys.GetMassCenter(Nz::CoordSys_Local) + entityCollision.GetGeomOffset(); - } - else - *offset = entityCollision.GetGeomOffset(); - - return model; - } - else - return nullptr; - } - - Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity) - { - if (entity->HasComponent()) - { - CollisionComponent3D& entityCollision = entity->GetComponent(); - const Nz::Collider3DRef& geom = entityCollision.GetGeom(); - - std::vector vertices; - std::vector indices; - - geom->ForEachPolygon([&](const Nz::Vector3f* polygonVertices, std::size_t vertexCount) - { - std::size_t firstIndex = vertices.size(); - vertices.resize(firstIndex + vertexCount); - std::copy(polygonVertices, polygonVertices + vertexCount, &vertices[firstIndex]); - - for (std::size_t i = 0; i < vertexCount - 1; ++i) - { - indices.push_back(firstIndex + i); - indices.push_back(firstIndex + i + 1); - } - - indices.push_back(firstIndex + vertexCount - 1); - indices.push_back(firstIndex); - }); - - Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0); - Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly); - - Nz::IndexIterator indexPtr = indexMapper.begin(); - for (std::size_t index : indices) - *indexPtr++ = static_cast(index); - - indexMapper.Unmap(); - - Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0); - vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size())); - - Nz::MeshRef mesh = Nz::Mesh::New(); - mesh->CreateStatic(); - - Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(vertexBuffer, indexBuffer); - subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList); - subMesh->SetMaterialIndex(0); - subMesh->GenerateAABB(); - - mesh->SetMaterialCount(1); - mesh->AddSubMesh(subMesh); - - Nz::ModelRef model = Nz::Model::New(); - model->SetMesh(mesh); - model->SetMaterial(0, GetCollisionMaterial()); - - return model; - } - else - return nullptr; - } - - std::pair DebugSystem::GetBoxMesh() - { - if (!m_boxMeshIndexBuffer) - { - std::array indices = { - { - 0, 1, - 1, 2, - 2, 3, - 3, 0, - - 4, 5, - 5, 6, - 6, 7, - 7, 4, - - 0, 4, - 1, 5, - 2, 6, - 3, 7 - } - }; - - m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0); - m_boxMeshIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size())); - } - - if (!m_boxMeshVertexBuffer) - { - Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f); - - std::array positions = { - { - box.GetCorner(Nz::BoxCorner_FarLeftBottom), - box.GetCorner(Nz::BoxCorner_NearLeftBottom), - box.GetCorner(Nz::BoxCorner_NearRightBottom), - box.GetCorner(Nz::BoxCorner_FarRightBottom), - box.GetCorner(Nz::BoxCorner_FarLeftTop), - box.GetCorner(Nz::BoxCorner_NearLeftTop), - box.GetCorner(Nz::BoxCorner_NearRightTop), - box.GetCorner(Nz::BoxCorner_FarRightTop) - } - }; - - m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, 0); - m_boxMeshVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size())); - } - - return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer }; - } - - Nz::MaterialRef DebugSystem::GetGlobalAABBMaterial() - { - if (!m_globalAabbMaterial) - { - m_globalAabbMaterial = Nz::Material::New(); - m_globalAabbMaterial->EnableFaceCulling(false); - m_globalAabbMaterial->EnableDepthBuffer(true); - m_globalAabbMaterial->SetDiffuseColor(Nz::Color::Orange); - m_globalAabbMaterial->SetFaceFilling(Nz::FaceFilling_Line); - //m_globalAabbMaterial->SetLineWidth(2.f); - } - - return m_globalAabbMaterial; - } - - Nz::MaterialRef DebugSystem::GetLocalAABBMaterial() - { - if (!m_localAabbMaterial) - { - m_localAabbMaterial = Nz::Material::New(); - m_localAabbMaterial->EnableFaceCulling(false); - m_localAabbMaterial->EnableDepthBuffer(true); - m_localAabbMaterial->SetDiffuseColor(Nz::Color::Red); - m_localAabbMaterial->SetFaceFilling(Nz::FaceFilling_Line); - //m_localAabbMaterial->SetLineWidth(2.f); - } - - return m_localAabbMaterial; - } - - Nz::MaterialRef DebugSystem::GetCollisionMaterial() - { - if (!m_collisionMaterial) - { - m_collisionMaterial = Nz::Material::New(); - m_collisionMaterial->EnableFaceCulling(false); - m_collisionMaterial->EnableDepthBuffer(true); - m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue); - m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line); - //m_collisionMaterial->SetLineWidth(2.f); - } - - return m_collisionMaterial; - } - - Nz::MaterialRef DebugSystem::GetOBBMaterial() - { - if (!m_obbMaterial) - { - m_obbMaterial = Nz::Material::New(); - m_obbMaterial->EnableFaceCulling(false); - m_obbMaterial->EnableDepthBuffer(true); - m_obbMaterial->SetDiffuseColor(Nz::Color::Green); - m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line); - //m_obbMaterial->SetLineWidth(2.f); - } - - return m_obbMaterial; - } - - void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/) - { - static constexpr int DebugDrawOrder = 1'000; - - DebugComponent& entityDebug = entity->GetComponent(); - GraphicsComponent& entityGfx = entity->GetComponent(); - NodeComponent& entityNode = entity->GetComponent(); - - DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags(); - DebugDrawFlags flags = entityDebug.GetFlags(); - - DebugDrawFlags flagsToEnable = flags & ~enabledFlags; - for (std::size_t i = 0; i <= static_cast(DebugDraw::Max); ++i) - { - DebugDraw option = static_cast(i); - if (flagsToEnable & option) - { - switch (option) - { - case DebugDraw::Collider2D: - { - Nz::Vector3f offset; - Nz::InstancedRenderableRef renderable = GenerateCollision2DMesh(entity, &offset); - if (renderable) - entityGfx.Attach(renderable, Nz::Matrix4f::Translate(offset), DebugDrawOrder); - - entityDebug.UpdateDebugRenderable(option, std::move(renderable)); - break; - } - - case DebugDraw::Collider3D: - { - const Nz::Boxf& obb = entityGfx.GetAABB(); - - Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity); - if (renderable) - entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter() - entityNode.GetPosition()), DebugDrawOrder); - - entityDebug.UpdateDebugRenderable(option, std::move(renderable)); - break; - } - - case DebugDraw::GraphicsAABB: - { - auto indexVertexBuffers = GetBoxMesh(); - - Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetGlobalAABBMaterial(), GetLocalAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); - renderable->SetPersistent(false); - - entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); - - entityDebug.UpdateDebugRenderable(option, std::move(renderable)); - break; - } - - case DebugDraw::GraphicsOBB: - { - auto indexVertexBuffers = GetBoxMesh(); - - Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); - renderable->SetPersistent(false); - - entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); - - entityDebug.UpdateDebugRenderable(option, std::move(renderable)); - break; - } - - default: - break; - } - } - } - - DebugDrawFlags flagsToDisable = enabledFlags & ~flags; - for (std::size_t i = 0; i <= static_cast(DebugDraw::Max); ++i) - { - DebugDraw option = static_cast(i); - if (flagsToDisable & option) - entityGfx.Detach(entityDebug.GetDebugRenderable(option)); - } - - entityDebug.UpdateEnabledFlags(flags); - } - - void DebugSystem::OnUpdate(float elapsedTime) - { - // Nothing to do - } - - SystemIndex DebugSystem::systemIndex; -} diff --git a/SDK/src/NDK/Systems/ParticleSystem.cpp b/SDK/src/NDK/Systems/ParticleSystem.cpp deleted file mode 100644 index b374bf1e7..000000000 --- a/SDK/src/NDK/Systems/ParticleSystem.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::ParticleSystem - * \brief NDK class that represents the particle system - * - * \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: ParticleGroupComponent - */ - - /*! - * \brief Constructs an ParticleSystem object by default - */ - - ParticleSystem::ParticleSystem() - { - Requires(); - } - - /*! - * \brief Operation to perform when system is updated - * - * \param elapsedTime Delta time used for the update - */ - - void ParticleSystem::OnUpdate(float elapsedTime) - { - for (const Ndk::EntityHandle& entity : GetEntities()) - { - ParticleGroupComponent& group = entity->GetComponent(); - - group.Update(elapsedTime); - } - } - - SystemIndex ParticleSystem::systemIndex; -} diff --git a/SDK/src/NDK/Systems/RenderSystem.cpp b/SDK/src/NDK/Systems/RenderSystem.cpp deleted file mode 100644 index 8b4bfe03f..000000000 --- a/SDK/src/NDK/Systems/RenderSystem.cpp +++ /dev/null @@ -1,428 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - /*! - * \ingroup NDK - * \class Ndk::RenderSystem - * \brief NDK class that represents the rendering system - * - * \remark This system is enabled if the entity is a 'camera' with the trait: CameraComponent and NodeComponent - * or a drawable element with trait: GraphicsComponent and NodeComponent - * or a light element with trait: LightComponent and NodeComponent - * or a set of particles with trait: ParticleGroupComponent - */ - - /*! - * \brief Constructs an RenderSystem object by default - */ - RenderSystem::RenderSystem() : - m_coordinateSystemMatrix(Nz::Matrix4f::Identity()), - m_coordinateSystemInvalidated(true), - m_forceRenderQueueInvalidation(false), - m_isCullingEnabled(true) - { - ChangeRenderTechnique(); - SetDefaultBackground(Nz::ColorBackground::New()); - SetUpdateOrder(100); //< Render last, after every movement is done - SetMaximumUpdateRate(0.f); //< We don't want any rate limit - } - - /*! - * \brief Operation to perform when an entity is removed - * - * \param entity Pointer to the entity - */ - void RenderSystem::OnEntityRemoved(Entity* entity) - { - m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list - - for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it) - { - if (it->GetObject() == entity) - { - m_cameras.erase(it); - break; - } - } - - if (entity->HasComponent()) - { - GraphicsComponent& gfxComponent = entity->GetComponent(); - gfxComponent.RemoveFromCullingList(&m_drawableCulling); - } - } - - /*! - * \brief Operation to perform when entity is validated for the system - * - * \param entity Pointer to the entity - * \param justAdded Is the entity newly added - */ - void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded) - { - NazaraUnused(justAdded); - - if (entity->HasComponent() && entity->HasComponent()) - { - m_cameras.emplace_back(entity); - std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2) - { - return handle1->GetComponent().GetLayer() < handle2->GetComponent().GetLayer(); - }); - } - else - { - for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it) - { - if (it->GetObject() == entity) - { - m_cameras.erase(it); - break; - } - } - } - - if (entity->HasComponent() && entity->HasComponent()) - { - m_drawables.Insert(entity); - - GraphicsComponent& gfxComponent = entity->GetComponent(); - if (justAdded) - gfxComponent.AddToCullingList(&m_drawableCulling); - - if (gfxComponent.DoesRequireRealTimeReflections()) - m_realtimeReflected.Insert(entity); - else - m_realtimeReflected.Remove(entity); - } - else - { - m_drawables.Remove(entity); - m_realtimeReflected.Remove(entity); - - if (entity->HasComponent()) - { - GraphicsComponent& gfxComponent = entity->GetComponent(); - gfxComponent.RemoveFromCullingList(&m_drawableCulling); - } - } - - if (entity->HasComponent() && entity->HasComponent()) - { - m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list - - LightComponent& lightComponent = entity->GetComponent(); - if (lightComponent.GetLightType() == Nz::LightType_Directional) - { - m_directionalLights.Insert(entity); - m_pointSpotLights.Remove(entity); - } - else - { - m_directionalLights.Remove(entity); - m_pointSpotLights.Insert(entity); - } - - m_lights.Insert(entity); - } - else - { - m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list - - m_directionalLights.Remove(entity); - m_lights.Remove(entity); - m_pointSpotLights.Remove(entity); - } - - if (entity->HasComponent()) - { - m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list - - m_particleGroups.Insert(entity); - } - else - { - m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list - - m_particleGroups.Remove(entity); - } - } - - /*! - * \brief Operation to perform when system is updated - * - * \param elapsedTime Delta time used for the update - */ - - void RenderSystem::OnUpdate(float /*elapsedTime*/) - { - // Invalidate every renderable if the coordinate system changed - if (m_coordinateSystemInvalidated) - { - for (const Ndk::EntityHandle& drawable : m_drawables) - { - GraphicsComponent& graphicsComponent = drawable->GetComponent(); - graphicsComponent.InvalidateTransformMatrix(); - } - - m_coordinateSystemInvalidated = false; - } - - Nz::SkinningManager::Skin(); - - UpdateDynamicReflections(); - UpdatePointSpotShadowMaps(); - - for (const Ndk::EntityHandle& camera : m_cameras) - { - CameraComponent& camComponent = camera->GetComponent(); - - //UpdateDirectionalShadowMaps(camComponent); - - Nz::AbstractRenderQueue* renderQueue = m_renderTechnique->GetRenderQueue(); - - // To make sure the bounding volumes used by the culling list is updated - for (const Ndk::EntityHandle& drawable : m_drawables) - { - GraphicsComponent& graphicsComponent = drawable->GetComponent(); - graphicsComponent.EnsureBoundingVolumesUpdate(); - } - - bool forceInvalidation = false; - - const Nz::Frustumf& frustum = camComponent.GetFrustum(); - - std::size_t visibilityHash; - if (m_isCullingEnabled) - visibilityHash = m_drawableCulling.Cull(frustum, &forceInvalidation); - else - visibilityHash = m_drawableCulling.FillWithAllEntries(&forceInvalidation); - - // Always regenerate renderqueue if particle groups are present for now (FIXME) - if (!m_lights.empty() || !m_particleGroups.empty()) - forceInvalidation = true; - - if (camComponent.UpdateVisibility(visibilityHash) || m_forceRenderQueueInvalidation || forceInvalidation) - { - renderQueue->Clear(); - for (const GraphicsComponent* gfxComponent : m_drawableCulling.GetFullyVisibleResults()) - gfxComponent->AddToRenderQueue(renderQueue); - - for (const GraphicsComponent* gfxComponent : m_drawableCulling.GetPartiallyVisibleResults()) - gfxComponent->AddToRenderQueueByCulling(frustum, renderQueue); - - for (const Ndk::EntityHandle& light : m_lights) - { - LightComponent& lightComponent = light->GetComponent(); - NodeComponent& lightNode = light->GetComponent(); - - ///TODO: Cache somehow? - lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix())); - } - - for (const Ndk::EntityHandle& particleGroup : m_particleGroups) - { - ParticleGroupComponent& groupComponent = particleGroup->GetComponent(); - - groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use any transform matrix (yet) - } - - m_forceRenderQueueInvalidation = false; - } - - camComponent.ApplyView(); - - Nz::SceneData sceneData; - sceneData.ambientColor = Nz::Color(25, 25, 25); - sceneData.background = m_background; - sceneData.globalReflectionTexture = nullptr; - sceneData.viewer = &camComponent; - - if (m_background && m_background->GetBackgroundType() == Nz::BackgroundType_Skybox) - sceneData.globalReflectionTexture = static_cast(m_background.Get())->GetTexture(); - - m_renderTechnique->Clear(sceneData); - m_renderTechnique->Draw(sceneData); - } - } - - /*! - * \brief Updates the directional shadow maps according to the position of the viewer - * - * \param viewer Viewer of the scene - */ - - void RenderSystem::UpdateDynamicReflections() - { - Nz::SceneData dummySceneData; - dummySceneData.ambientColor = Nz::Color(0, 0, 0); - dummySceneData.background = nullptr; - dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer - - for (const Ndk::EntityHandle& handle : m_realtimeReflected) - { - //NazaraWarning("Realtime reflected: #" + handle->ToString()); - } - } - - void RenderSystem::UpdateDirectionalShadowMaps(const Nz::AbstractViewer& /*viewer*/) - { - if (!m_shadowRT.IsValid()) - m_shadowRT.Create(); - - Nz::SceneData dummySceneData; - dummySceneData.ambientColor = Nz::Color(0, 0, 0); - dummySceneData.background = nullptr; - dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer - - for (const Ndk::EntityHandle& light : m_directionalLights) - { - LightComponent& lightComponent = light->GetComponent(); - NodeComponent& lightNode = light->GetComponent(); - - if (!lightComponent.IsShadowCastingEnabled()) - continue; - - Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize()); - - m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap()); - Nz::Renderer::SetTarget(&m_shadowRT); - Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y)); - - Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); - renderQueue->Clear(); - - ///TODO: Culling - for (const Ndk::EntityHandle& drawable : m_drawables) - { - GraphicsComponent& graphicsComponent = drawable->GetComponent(); - - graphicsComponent.AddToRenderQueue(renderQueue); - } - - ///TODO: Cache the matrices in the light? - Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Ortho(0.f, 100.f, 100.f, 0.f, 1.f, 100.f)); - Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetRotation() * Nz::Vector3f::Forward() * 100.f, lightNode.GetRotation())); - - m_shadowTechnique.Clear(dummySceneData); - m_shadowTechnique.Draw(dummySceneData); - } - } - - /*! - * \brief Updates the point spot shadow maps - */ - - void RenderSystem::UpdatePointSpotShadowMaps() - { - if (!m_shadowRT.IsValid()) - m_shadowRT.Create(); - - Nz::SceneData dummySceneData; - dummySceneData.ambientColor = Nz::Color(0, 0, 0); - dummySceneData.background = nullptr; - dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer - - for (const Ndk::EntityHandle& light : m_pointSpotLights) - { - LightComponent& lightComponent = light->GetComponent(); - NodeComponent& lightNode = light->GetComponent(); - - if (!lightComponent.IsShadowCastingEnabled()) - continue; - - Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize()); - - switch (lightComponent.GetLightType()) - { - case Nz::LightType_Directional: - NazaraInternalError("Directional lights included in point/spot light list"); - break; - - case Nz::LightType_Point: - { - static Nz::Quaternionf rotations[6] = - { - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitX()), // CubemapFace_PositiveX - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitX()), // CubemapFace_NegativeX - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitY()), // CubemapFace_PositiveY - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitY()), // CubemapFace_NegativeY - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitZ()), // CubemapFace_PositiveZ - Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitZ()) // CubemapFace_NegativeZ - }; - - for (unsigned int face = 0; face < 6; ++face) - { - m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap(), face); - Nz::Renderer::SetTarget(&m_shadowRT); - Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y)); - - ///TODO: Cache the matrices in the light? - Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(Nz::FromDegrees(90.f), 1.f, 0.1f, lightComponent.GetRadius())); - Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), rotations[face])); - - Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); - renderQueue->Clear(); - - ///TODO: Culling - for (const Ndk::EntityHandle& drawable : m_drawables) - { - GraphicsComponent& graphicsComponent = drawable->GetComponent(); - - graphicsComponent.AddToRenderQueue(renderQueue); - } - - m_shadowTechnique.Clear(dummySceneData); - m_shadowTechnique.Draw(dummySceneData); - } - break; - } - - case Nz::LightType_Spot: - { - m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap()); - Nz::Renderer::SetTarget(&m_shadowRT); - Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y)); - - ///TODO: Cache the matrices in the light? - Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(lightComponent.GetOuterAngle()*2.f, 1.f, 0.1f, lightComponent.GetRadius())); - Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation())); - - Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue(); - renderQueue->Clear(); - - ///TODO: Culling - for (const Ndk::EntityHandle& drawable : m_drawables) - { - GraphicsComponent& graphicsComponent = drawable->GetComponent(); - - graphicsComponent.AddToRenderQueue(renderQueue); - } - - m_shadowTechnique.Clear(dummySceneData); - m_shadowTechnique.Draw(dummySceneData); - break; - } - } - } - } - - SystemIndex RenderSystem::systemIndex; -} diff --git a/SDK/src/NDK/Widgets/AbstractTextAreaWidget.cpp b/SDK/src/NDK/Widgets/AbstractTextAreaWidget.cpp deleted file mode 100644 index 78df17c6f..000000000 --- a/SDK/src/NDK/Widgets/AbstractTextAreaWidget.cpp +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include - -namespace Ndk -{ - namespace - { - constexpr float paddingWidth = 5.f; - constexpr float paddingHeight = 3.f; - } - - AbstractTextAreaWidget::AbstractTextAreaWidget(BaseWidget* parent) : - BaseWidget(parent), - m_characterFilter(), - m_echoMode(EchoMode_Normal), - m_cursorPositionBegin(0U, 0U), - m_cursorPositionEnd(0U, 0U), - m_isLineWrapEnabled(false), - m_isMouseButtonDown(false), - m_multiLineEnabled(false), - m_readOnly(false), - m_tabEnabled(false) - { - m_textSprite = Nz::TextSprite::New(); - - m_textEntity = CreateEntity(); - m_textEntity->AddComponent().Attach(m_textSprite); - - auto& textNode = m_textEntity->AddComponent(); - textNode.SetParent(this); - textNode.SetPosition(paddingWidth, paddingHeight); - - m_cursorEntity = CreateEntity(); - m_cursorEntity->AddComponent(); - m_cursorEntity->AddComponent().SetParent(m_textEntity); - m_cursorEntity->GetComponent(); - m_cursorEntity->Enable(false); - - SetCursor(Nz::SystemCursor_Text); - - EnableBackground(true); - } - - void AbstractTextAreaWidget::Clear() - { - Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - m_cursorPositionBegin.MakeZero(); - m_cursorPositionEnd.MakeZero(); - textDrawer.Clear(); - m_textSprite->Update(textDrawer); - SetPreferredSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths())); - - RefreshCursor(); - } - - void AbstractTextAreaWidget::EnableLineWrap(bool enable) - { - if (m_isLineWrapEnabled != enable) - { - m_isLineWrapEnabled = enable; - - Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - if (enable) - textDrawer.SetMaxLineWidth(GetWidth()); - else - textDrawer.SetMaxLineWidth(std::numeric_limits::infinity()); - - UpdateTextSprite(); - } - } - - Nz::Vector2ui AbstractTextAreaWidget::GetHoveredGlyph(float x, float y) const - { - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - auto& textNode = m_textEntity->GetComponent(); - Nz::Vector2f textPosition = Nz::Vector2f(textNode.GetPosition(Nz::CoordSys_Local)); - x -= textPosition.x; - y -= textPosition.y; - - std::size_t glyphCount = textDrawer.GetGlyphCount(); - if (glyphCount > 0) - { - std::size_t lineCount = textDrawer.GetLineCount(); - std::size_t line = 0U; - for (; line < lineCount - 1; ++line) - { - Nz::Rectf lineBounds = textDrawer.GetLine(line).bounds; - if (lineBounds.GetMaximum().y > y) - break; - } - - std::size_t upperLimit = (line != lineCount - 1) ? textDrawer.GetLine(line + 1).glyphIndex : glyphCount + 1; - - std::size_t firstLineGlyph = textDrawer.GetLine(line).glyphIndex; - std::size_t i = firstLineGlyph; - for (; i < upperLimit - 1; ++i) - { - Nz::Rectf bounds = textDrawer.GetGlyph(i).bounds; - if (x < bounds.x + bounds.width * 0.75f) - break; - } - - return Nz::Vector2ui(Nz::Vector2(i - firstLineGlyph, line)); - } - - return Nz::Vector2ui::Zero(); - } - - void AbstractTextAreaWidget::Layout() - { - BaseWidget::Layout(); - - if (m_isLineWrapEnabled) - { - Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - textDrawer.SetMaxLineWidth(GetWidth()); - UpdateTextSprite(); - } - - RefreshCursor(); - } - - bool AbstractTextAreaWidget::IsFocusable() const - { - return !m_readOnly; - } - - void AbstractTextAreaWidget::OnFocusLost() - { - m_cursorEntity->Disable(); - } - - void AbstractTextAreaWidget::OnFocusReceived() - { - if (!m_readOnly) - m_cursorEntity->Enable(true); - } - - bool AbstractTextAreaWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) - { - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - switch (key.virtualKey) - { - case Nz::Keyboard::VKey::Backspace: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyBackspace(this, &ignoreDefaultAction); - - std::size_t cursorGlyphEnd = GetGlyphIndex(m_cursorPositionEnd); - - if (ignoreDefaultAction || cursorGlyphEnd == 0) - return true; - - // When a text is selected, delete key does the same as delete and leave the character behind it - if (HasSelection()) - EraseSelection(); - else - { - MoveCursor(-1); - Erase(GetGlyphIndex(m_cursorPositionBegin)); - } - - return true; - } - - case Nz::Keyboard::VKey::Delete: - { - if (HasSelection()) - EraseSelection(); - else - Erase(GetGlyphIndex(m_cursorPositionBegin)); - - return true; - } - - case Nz::Keyboard::VKey::Down: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyDown(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - if (HasSelection()) - SetCursorPosition(m_cursorPositionEnd); - - MoveCursor({0, 1}); - return true; - } - - case Nz::Keyboard::VKey::End: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyEnd(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - std::size_t lineCount = textDrawer.GetLineCount(); - if (key.control && lineCount > 0) - SetCursorPosition({ static_cast(textDrawer.GetLineGlyphCount(lineCount - 1)), static_cast(lineCount - 1) }); - else - SetCursorPosition({ static_cast(textDrawer.GetLineGlyphCount(m_cursorPositionEnd.y)), m_cursorPositionEnd.y }); - - return true; - } - - case Nz::Keyboard::VKey::Home: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyHome(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - SetCursorPosition({ 0U, key.control ? 0U : m_cursorPositionEnd.y }); - return true; - } - - case Nz::Keyboard::VKey::Left: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyLeft(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - if (HasSelection()) - SetCursorPosition(m_cursorPositionBegin); - else if (key.control) - HandleWordCursorMove(true); - else - MoveCursor(-1); - - return true; - } - - case Nz::Keyboard::VKey::Return: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyReturn(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - if (!m_multiLineEnabled) - break; - - if (HasSelection()) - EraseSelection(); - - Write(Nz::String('\n')); - return true;; - } - - case Nz::Keyboard::VKey::Right: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyRight(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - if (HasSelection()) - SetCursorPosition(m_cursorPositionEnd); - else if (key.control) - HandleWordCursorMove(false); - else - MoveCursor(1); - - return true; - } - - case Nz::Keyboard::VKey::Up: - { - bool ignoreDefaultAction = false; - OnTextAreaKeyUp(this, &ignoreDefaultAction); - - if (ignoreDefaultAction) - return true; - - if (HasSelection()) - SetCursorPosition(m_cursorPositionBegin); - - MoveCursor({0, -1}); - return true; - } - - case Nz::Keyboard::VKey::Tab: - { - if (!m_tabEnabled) - return false; - - if (HasSelection()) - HandleSelectionIndentation(!key.shift); - else - HandleIndentation(!key.shift); - - return true; - } - - default: - break; - } - - return false; - } - - void AbstractTextAreaWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/) - { - } - - void AbstractTextAreaWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) - { - if (button == Nz::Mouse::Left) - { - SetFocus(); - - Nz::Vector2ui hoveredGlyph = GetHoveredGlyph(float(x), float(y)); - - // Shift extends selection - if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) - SetSelection(hoveredGlyph, m_selectionCursor); - else - { - SetCursorPosition(hoveredGlyph); - m_selectionCursor = m_cursorPositionBegin; - } - - m_isMouseButtonDown = true; - } - } - - void AbstractTextAreaWidget::OnMouseButtonRelease(int, int, Nz::Mouse::Button button) - { - if (button == Nz::Mouse::Left) - m_isMouseButtonDown = false; - } - - void AbstractTextAreaWidget::OnMouseEnter() - { - if (!Nz::Mouse::IsButtonPressed(Nz::Mouse::Left)) - m_isMouseButtonDown = false; - } - - void AbstractTextAreaWidget::OnMouseMoved(int x, int y, int deltaX, int deltaY) - { - if (m_isMouseButtonDown) - SetSelection(m_selectionCursor, GetHoveredGlyph(float(x), float(y))); - } - - void AbstractTextAreaWidget::OnTextEntered(char32_t character, bool /*repeated*/) - { - if (m_readOnly) - return; - - if (Nz::Unicode::GetCategory(character) == Nz::Unicode::Category_Other_Control || (m_characterFilter && !m_characterFilter(character))) - return; - - if (HasSelection()) - EraseSelection(); - - Write(Nz::String::Unicode(character)); - } - - void AbstractTextAreaWidget::RefreshCursor() - { - if (m_readOnly) - return; - - const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer(); - - auto GetGlyph = [&](const Nz::Vector2ui& glyphPosition, std::size_t* glyphIndex) -> const Nz::AbstractTextDrawer::Glyph* - { - if (glyphPosition.y >= textDrawer.GetLineCount()) - return nullptr; - - const auto& lineInfo = textDrawer.GetLine(glyphPosition.y); - - std::size_t cursorGlyph = GetGlyphIndex({ glyphPosition.x, glyphPosition.y }); - if (glyphIndex) - *glyphIndex = cursorGlyph; - - std::size_t glyphCount = textDrawer.GetGlyphCount(); - if (glyphCount > 0 && lineInfo.glyphIndex < cursorGlyph) - { - const auto& glyph = textDrawer.GetGlyph(std::min(cursorGlyph, glyphCount - 1)); - return &glyph; - } - else - return nullptr; - }; - - // Move text so that cursor is always visible - const auto* lastGlyph = GetGlyph(m_cursorPositionEnd, nullptr); - float glyphPos = (lastGlyph) ? lastGlyph->bounds.x : 0.f; - float glyphWidth = (lastGlyph) ? lastGlyph->bounds.width : 0.f; - - auto& node = m_textEntity->GetComponent(); - float textPosition = node.GetPosition(Nz::CoordSys_Local).x - paddingWidth; - float cursorPosition = glyphPos + textPosition; - float width = GetWidth(); - - if (width <= textDrawer.GetBounds().width) - { - if (cursorPosition + glyphWidth > width) - node.Move(width - cursorPosition - glyphWidth, 0.f); - else if (cursorPosition - glyphWidth < 0.f) - node.Move(-cursorPosition + glyphWidth, 0.f); - } - else - node.Move(-textPosition, 0.f); // Reset text position if we have enough room to show everything - - // Show cursor/selection - std::size_t selectionLineCount = m_cursorPositionEnd.y - m_cursorPositionBegin.y + 1; - std::size_t oldSpriteCount = m_cursorSprites.size(); - if (m_cursorSprites.size() != selectionLineCount) - { - m_cursorSprites.resize(m_cursorPositionEnd.y - m_cursorPositionBegin.y + 1); - for (std::size_t i = oldSpriteCount; i < m_cursorSprites.size(); ++i) - { - m_cursorSprites[i] = Nz::Sprite::New(); - m_cursorSprites[i]->SetMaterial(Nz::Material::New("Translucent2D")); - } - } - - GraphicsComponent& gfxComponent = m_cursorEntity->GetComponent(); - gfxComponent.Clear(); - - for (unsigned int i = m_cursorPositionBegin.y; i <= m_cursorPositionEnd.y; ++i) - { - const auto& lineInfo = textDrawer.GetLine(i); - - Nz::SpriteRef& cursorSprite = m_cursorSprites[i - m_cursorPositionBegin.y]; - if (i == m_cursorPositionBegin.y || i == m_cursorPositionEnd.y) - { - auto GetGlyphPos = [&](const Nz::Vector2ui& glyphPosition) - { - std::size_t glyphIndex; - const auto* glyph = GetGlyph(glyphPosition, &glyphIndex); - if (glyph) - { - float position = glyph->bounds.x; - if (glyphIndex >= textDrawer.GetGlyphCount()) - position += glyph->bounds.width; - - return position; - } - else - return 0.f; - }; - - float beginX = (i == m_cursorPositionBegin.y) ? GetGlyphPos({ m_cursorPositionBegin.x, i }) : 0.f; - float endX = (i == m_cursorPositionEnd.y) ? GetGlyphPos({ m_cursorPositionEnd.x, i }) : lineInfo.bounds.width; - float spriteSize = std::max(endX - beginX, 1.f); - - cursorSprite->SetColor((m_cursorPositionBegin == m_cursorPositionEnd) ? Nz::Color::Black : Nz::Color(0, 0, 0, 50)); - cursorSprite->SetSize(spriteSize, lineInfo.bounds.height); - - gfxComponent.Attach(cursorSprite, Nz::Matrix4f::Translate({ beginX, lineInfo.bounds.y, 0.f })); - } - else - { - cursorSprite->SetColor(Nz::Color(0, 0, 0, 50)); - cursorSprite->SetSize(lineInfo.bounds.width, lineInfo.bounds.height); - - gfxComponent.Attach(cursorSprite, Nz::Matrix4f::Translate({ 0.f, lineInfo.bounds.y, 0.f })); - } - } - } - - void AbstractTextAreaWidget::UpdateTextSprite() - { - m_textSprite->Update(GetTextDrawer()); - SetPreferredSize(Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths())); - } -} diff --git a/SDK/src/NDK/Widgets/BoxLayout.cpp b/SDK/src/NDK/Widgets/BoxLayout.cpp deleted file mode 100644 index bcef8a3c3..000000000 --- a/SDK/src/NDK/Widgets/BoxLayout.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include -#include - -namespace Ndk -{ - struct BoxLayout::State - { - std::vector sizeVar; - kiwi::Solver solver; - }; - - BoxLayout::BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation) : - BaseWidget(parent), - m_orientation(orientation), - m_spacing(5.f) - { - m_state = std::make_unique(); - } - - BoxLayout::~BoxLayout() = default; - - void BoxLayout::Layout() - { - BaseWidget::Layout(); - - std::size_t axis; - - switch (m_orientation) - { - case BoxLayoutOrientation_Horizontal: - axis = 0; //< x - break; - - case BoxLayoutOrientation_Vertical: - axis = 1; //< y - break; - - default: - assert(false); - break; - } - - //TODO: Keep solver state when widgets don't change - std::size_t widgetChildCount = GetWidgetChildCount(); - if (widgetChildCount == 0) - return; - - m_state->solver.reset(); - - m_state->sizeVar.clear(); - m_state->sizeVar.reserve(widgetChildCount); - - kiwi::Expression sizeSum; - - Nz::Vector2f layoutSize = GetSize(); - float availableSpace = layoutSize[axis] - m_spacing * (widgetChildCount - 1); - float perfectSpacePerWidget = availableSpace / widgetChildCount; - - // Handle size - ForEachWidgetChild([&](BaseWidget* child) - { - if (!child->IsVisible()) - return; - - float maximumSize = child->GetMaximumSize()[axis]; - float minimumSize = child->GetMinimumSize()[axis]; - - m_state->sizeVar.emplace_back(); - auto& sizeVar = m_state->sizeVar.back(); - - m_state->solver.addConstraint({ sizeVar >= minimumSize | kiwi::strength::required }); - - if (maximumSize < std::numeric_limits::infinity()) - m_state->solver.addConstraint({ sizeVar <= maximumSize | kiwi::strength::required }); - - m_state->solver.addConstraint({ sizeVar >= perfectSpacePerWidget | kiwi::strength::medium }); - - sizeSum = sizeSum + sizeVar; - }); - - kiwi::Variable targetSize("LayoutSize"); - - m_state->solver.addConstraint(sizeSum <= targetSize | kiwi::strength::strong); - - m_state->solver.addEditVariable(targetSize, kiwi::strength::strong); - m_state->solver.suggestValue(targetSize, availableSpace); - - m_state->solver.updateVariables(); - - std::size_t varIndex = 0; - - float remainingSize = availableSpace; - - ForEachWidgetChild([&](BaseWidget* child) - { - if (!child->IsVisible()) - return; - - Nz::Vector2f newSize = layoutSize; - newSize[axis] = m_state->sizeVar[varIndex].value(); - - child->Resize(newSize); - remainingSize -= newSize[axis]; - - varIndex++; - }); - - float spacing = m_spacing + remainingSize / (widgetChildCount - 1); - - // Handle position - float cursor = 0.f; - bool first = true; - ForEachWidgetChild([&](BaseWidget* child) - { - if (first) - first = false; - else - cursor += spacing; - - Nz::Vector2f position = Nz::Vector2f(0.f, 0.f); - position[axis] = cursor; - - child->SetPosition(position); - - cursor += child->GetSize()[axis]; - }); - } -} diff --git a/SDK/src/NDK/Widgets/ButtonWidget.cpp b/SDK/src/NDK/Widgets/ButtonWidget.cpp deleted file mode 100644 index c88645e44..000000000 --- a/SDK/src/NDK/Widgets/ButtonWidget.cpp +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include - -namespace Ndk -{ - Nz::Color ButtonWidget::s_color { 74, 74, 74 }; - Nz::Color ButtonWidget::s_cornerColor { 180, 180, 180 }; - Nz::Color ButtonWidget::s_hoverColor { 128, 128, 128 }; - Nz::Color ButtonWidget::s_hoverCornerColor { s_cornerColor }; - Nz::Color ButtonWidget::s_pressColor { s_cornerColor }; - Nz::Color ButtonWidget::s_pressCornerColor { s_color }; - - ButtonWidget::ButtonWidget(BaseWidget* parent) : - BaseWidget(parent), - m_color { s_color }, - m_cornerColor { s_cornerColor }, - m_hoverColor { s_hoverColor }, - m_hoverCornerColor { s_hoverCornerColor }, - m_pressColor { s_pressColor }, - m_pressCornerColor { s_pressCornerColor } - { - m_gradientSprite = Nz::Sprite::New(); - m_gradientSprite->SetColor(m_color); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); - m_gradientSprite->SetMaterial(Nz::Material::New("Basic2D")); - - m_gradientEntity = CreateEntity(); - m_gradientEntity->AddComponent().SetParent(this); - m_gradientEntity->AddComponent().Attach(m_gradientSprite); - - m_textSprite = Nz::TextSprite::New(); - - m_textEntity = CreateEntity(); - m_textEntity->AddComponent().SetParent(this); - m_textEntity->AddComponent().Attach(m_textSprite, 1); - - Layout(); - } - - const Nz::Color& ButtonWidget::GetDefaultColor() - { - return s_color; - } - - const Nz::Color& ButtonWidget::GetDefaultCornerColor() - { - return s_cornerColor; - } - - const Nz::Color& ButtonWidget::GetDefaultHoverColor() - { - return s_hoverColor; - } - - const Nz::Color& ButtonWidget::GetDefaultHoverCornerColor() - { - return s_hoverCornerColor; - } - - const Nz::Color& ButtonWidget::GetDefaultPressColor() - { - return s_pressColor; - } - - const Nz::Color& ButtonWidget::GetDefaultPressCornerColor() - { - return s_pressCornerColor; - } - - void ButtonWidget::Layout() - { - BaseWidget::Layout(); - - Nz::Vector2f size = GetSize(); - m_gradientSprite->SetSize(size); - - Nz::Boxf textBox = m_textEntity->GetComponent().GetAABB(); - m_textEntity->GetComponent().SetPosition(size.x / 2.f - textBox.width / 2.f, size.y / 2.f - textBox.height / 2.f); - } - - void ButtonWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button button) - { - if (button == Nz::Mouse::Left) - { - m_gradientSprite->SetColor(m_pressColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_pressCornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_pressCornerColor); - m_gradientSprite->SetTexture(m_pressTexture, false); - } - } - - void ButtonWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button button) - { - if (button == Nz::Mouse::Left) - { - m_gradientSprite->SetColor(m_hoverColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_hoverCornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_hoverCornerColor); - m_gradientSprite->SetTexture(m_hoverTexture, false); - - OnButtonTrigger(this); - } - } - - void ButtonWidget::OnMouseEnter() - { - m_gradientSprite->SetColor(m_hoverColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_hoverCornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_hoverCornerColor); - m_gradientSprite->SetTexture(m_hoverTexture, false); - } - - void ButtonWidget::OnMouseExit() - { - m_gradientSprite->SetColor(m_color); - m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor); - m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor); - m_gradientSprite->SetTexture(m_texture, false); - } -} diff --git a/SDK/src/NDK/Widgets/CheckboxWidget.cpp b/SDK/src/NDK/Widgets/CheckboxWidget.cpp deleted file mode 100644 index 7d906d8d1..000000000 --- a/SDK/src/NDK/Widgets/CheckboxWidget.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - Nz::Color CheckboxWidget::s_backgroundColor { Nz::Color::White }; - Nz::Color CheckboxWidget::s_disabledBackgroundColor { 201, 201, 201 }; - Nz::Color CheckboxWidget::s_disabledBorderColor { 62, 62, 62 }; - Nz::Color CheckboxWidget::s_borderColor { Nz::Color::Black }; - float CheckboxWidget::s_borderScale { 16.f }; - - CheckboxWidget::CheckboxWidget(BaseWidget* parent) : - BaseWidget(parent), - m_adaptativeMargin { true }, - m_checkboxEnabled { true }, - m_tristateEnabled { false }, - m_textMargin { 16.f }, - m_state { CheckboxState_Unchecked } - { - m_checkboxBorderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); - m_checkboxBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); - m_checkboxContentSprite = Nz::Sprite::New(Nz::Material::New("Translucent2D")); - m_textSprite = Nz::TextSprite::New(); - - m_checkboxBorderEntity = CreateEntity(); - m_checkboxBorderEntity->AddComponent().SetParent(this); - m_checkboxBorderEntity->AddComponent().Attach(m_checkboxBorderSprite); - - m_checkboxBackgroundEntity = CreateEntity(); - m_checkboxBackgroundEntity->AddComponent().SetParent(this); - m_checkboxBackgroundEntity->AddComponent().Attach(m_checkboxBackgroundSprite, 1); - - m_checkboxContentEntity = CreateEntity(); - m_checkboxContentEntity->AddComponent().SetParent(this); - m_checkboxContentEntity->AddComponent().Attach(m_checkboxContentSprite, 2); - - m_textEntity = CreateEntity(); - m_textEntity->AddComponent().SetParent(this); - m_textEntity->AddComponent().Attach(m_textSprite); - - m_checkMark = Nz::TextureLibrary::Get("Ndk::CheckboxWidget::checkmark"); - - SetCheckboxSize({ 32.f, 32.f }); - UpdateCheckbox(); - } - - bool CheckboxWidget::Initialize() - { - const Nz::UInt8 r_checkmark[] = - { - #include - }; - - Nz::TextureRef checkmarkTexture = Nz::Texture::LoadFromMemory(r_checkmark, sizeof(r_checkmark) / sizeof(r_checkmark[0])); - if (!checkmarkTexture) - { - NazaraError("Failed to load embedded checkmark"); - return false; - } - - Nz::TextureLibrary::Register("Ndk::CheckboxWidget::checkmark", std::move(checkmarkTexture)); - return true; - } - - void CheckboxWidget::Uninitialize() - { - Nz::TextureLibrary::Unregister("Ndk::CheckboxWidget::checkmark"); - } - - void CheckboxWidget::SetState(CheckboxState state) - { - if (!m_checkboxEnabled) - return; - - if (state == CheckboxState_Tristate) - m_tristateEnabled = true; - - m_state = state; - UpdateCheckbox(); - } - - CheckboxState CheckboxWidget::SwitchToNextState() - { - if (!m_checkboxEnabled) - return m_state; - - switch (m_state) - { - case CheckboxState_Unchecked: - SetState(CheckboxState_Checked); - break; - - case CheckboxState_Checked: - SetState(m_tristateEnabled ? CheckboxState_Tristate : CheckboxState_Unchecked); - break; - - case CheckboxState_Tristate: - SetState(CheckboxState_Unchecked); - break; - } - - return m_state; - } - - void CheckboxWidget::Layout() - { - BaseWidget::Layout(); - - Nz::Vector2f checkboxSize = GetCheckboxSize(); - Nz::Vector2f borderSize = GetCheckboxBorderSize(); - - m_checkboxBackgroundEntity->GetComponent().SetPosition(borderSize); - - Nz::Vector3f checkboxBox = m_checkboxContentSprite->GetBoundingVolume().obb.localBox.GetLengths(); - m_checkboxContentEntity->GetComponent().SetPosition(checkboxSize.x / 2.f - checkboxBox.x / 2.f, checkboxSize.y / 2.f - checkboxBox.y / 2.f); - - Nz::Vector3f textBox = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); - m_textEntity->GetComponent().SetPosition(checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin), checkboxSize.y / 2.f - textBox.y / 2.f); - } - - void CheckboxWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) - { - if (button == Nz::Mouse::Left && ContainsCheckbox(x, y) && IsCheckboxEnabled()) - { - SwitchToNextState(); - OnStateChanged(this); - } - } - - void CheckboxWidget::UpdateCheckbox() - { - if (m_checkboxEnabled) - { - m_checkboxBorderSprite->SetColor(s_borderColor); - m_checkboxBackgroundSprite->SetColor(s_backgroundColor); - } - else - { - m_checkboxBorderSprite->SetColor(s_disabledBorderColor); - m_checkboxBackgroundSprite->SetColor(s_disabledBackgroundColor); - } - - - if (m_state == CheckboxState_Unchecked) - { - m_checkboxContentEntity->Enable(false); - return; - } - else if (m_state == CheckboxState_Checked) - { - m_checkboxContentEntity->Enable(); - m_checkboxContentSprite->SetColor(Nz::Color::White); - m_checkboxContentSprite->SetTexture(m_checkMark, false); - } - else // Tristate - { - m_checkboxContentEntity->Enable(); - m_checkboxContentSprite->SetColor(Nz::Color::Black); - m_checkboxContentSprite->SetTexture(Nz::TextureRef {}); - } - } - - void CheckboxWidget::UpdateSize() - { - Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); - Nz::Vector2f checkboxSize = GetCheckboxSize(); - - Nz::Vector2f finalSize { checkboxSize.x + (m_adaptativeMargin ? checkboxSize.x / 2.f : m_textMargin) + textSize.x, std::max(textSize.y, checkboxSize.y) }; - SetMinimumSize(finalSize); - SetPreferredSize(finalSize); - } -} diff --git a/SDK/src/NDK/Widgets/ImageWidget.cpp b/SDK/src/NDK/Widgets/ImageWidget.cpp deleted file mode 100644 index 0a1cfdc81..000000000 --- a/SDK/src/NDK/Widgets/ImageWidget.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include - -namespace Ndk -{ - ImageWidget::ImageWidget(BaseWidget* parent) : - BaseWidget(parent) - { - m_entity = CreateEntity(); - m_entity->AddComponent().SetParent(this); - auto& gfx = m_entity->AddComponent(); - - m_sprite = Nz::Sprite::New(); - gfx.Attach(m_sprite); - } - - void ImageWidget::Layout() - { - BaseWidget::Layout(); - - m_sprite->SetSize(GetSize()); - } -} diff --git a/SDK/src/NDK/Widgets/LabelWidget.cpp b/SDK/src/NDK/Widgets/LabelWidget.cpp deleted file mode 100644 index 813295622..000000000 --- a/SDK/src/NDK/Widgets/LabelWidget.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include - -namespace Ndk -{ - LabelWidget::LabelWidget(BaseWidget* parent) : - BaseWidget(parent) - { - m_textSprite = Nz::TextSprite::New(); - - m_textEntity = CreateEntity(); - m_textEntity->AddComponent().Attach(m_textSprite); - m_textEntity->AddComponent().SetParent(this); - - Layout(); - } -} diff --git a/SDK/src/NDK/Widgets/ProgressBarWidget.cpp b/SDK/src/NDK/Widgets/ProgressBarWidget.cpp deleted file mode 100644 index cc3f4f2d9..000000000 --- a/SDK/src/NDK/Widgets/ProgressBarWidget.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (C) 2017 Samy Bensaid -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include - -namespace Ndk -{ - float ProgressBarWidget::s_borderScale { 16.f }; - Nz::Color ProgressBarWidget::s_borderColor { Nz::Color::Black }; - Nz::Color ProgressBarWidget::s_barBackgroundColor { Nz::Color { 225, 225, 225 } }; - Nz::Color ProgressBarWidget::s_barBackgroundCornerColor { Nz::Color { 255, 255, 255 } }; - Nz::Color ProgressBarWidget::s_barColor { Nz::Color { 0, 225, 0 } }; - Nz::Color ProgressBarWidget::s_barCornerColor { Nz::Color { 220, 255, 220 } }; - - ProgressBarWidget::ProgressBarWidget(BaseWidget* parent) : - BaseWidget(parent), - m_textColor { Nz::Color::Black }, - m_textMargin { 16.f }, - m_value { 0u } - { - m_borderSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); - m_barBackgroundSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); - m_barSprite = Nz::Sprite::New(Nz::Material::New("Basic2D")); - - m_borderSprite->SetColor(s_borderColor); - SetBarBackgroundColor(s_barBackgroundColor, s_barBackgroundCornerColor); - SetBarColor(s_barColor, s_barCornerColor); - - - m_borderEntity = CreateEntity(); - m_borderEntity->AddComponent().SetParent(this); - m_borderEntity->AddComponent().Attach(m_borderSprite); - - m_barEntity = CreateEntity(); - m_barEntity->AddComponent().SetParent(this); - GraphicsComponent& graphics = m_barEntity->AddComponent(); - - graphics.Attach(m_barBackgroundSprite, 1); - graphics.Attach(m_barSprite, 2); - - - m_textSprite = Nz::TextSprite::New(); - m_textEntity = CreateEntity(); - - m_textEntity->AddComponent().SetParent(this); - m_textEntity->AddComponent().Attach(m_textSprite); - - UpdateText(); - Layout(); - } - - - const Nz::Color& ProgressBarWidget::GetDefaultBarColor() - { - return s_barColor; - } - - const Nz::Color& ProgressBarWidget::GetDefaultBarCornerColor() - { - return s_barCornerColor; - } - - const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundColor() - { - return s_barBackgroundColor; - } - - const Nz::Color& ProgressBarWidget::GetDefaultBarBackgroundCornerColor() - { - return s_barBackgroundCornerColor; - } - - - void ProgressBarWidget::Layout() - { - Nz::Vector2f size = GetSize(); - Nz::Vector2f progressBarSize = size; - - if (IsTextEnabled()) - { - UpdateText(); - - Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths(); - m_textEntity->GetComponent().SetPosition(size.x - textSize.x, size.y / 2.f - textSize.y); - - progressBarSize -= { textSize.x + m_textMargin, 0.f }; - } - - m_borderSprite->SetSize(progressBarSize); - Nz::Vector2f borderSize = GetProgressBarBorderSize(); - - m_barBackgroundSprite->SetSize(progressBarSize - (borderSize * 2.f)); - m_barSprite->SetSize((progressBarSize.x - (borderSize.x * 2.f)) / 100.f * static_cast(m_value), progressBarSize.y - (borderSize.y * 2.f)); - - m_barEntity->GetComponent().SetPosition(borderSize.x, borderSize.y); - } -} diff --git a/SDK/src/NDK/Widgets/RichTextAreaWidget.cpp b/SDK/src/NDK/Widgets/RichTextAreaWidget.cpp deleted file mode 100644 index 35abb6e06..000000000 --- a/SDK/src/NDK/Widgets/RichTextAreaWidget.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include - -namespace Ndk -{ - RichTextAreaWidget::RichTextAreaWidget(BaseWidget* parent) : - AbstractTextAreaWidget(parent) - { - Layout(); - } - - void RichTextAreaWidget::AppendText(const Nz::String& text) - { - //m_text += text; - switch (m_echoMode) - { - case EchoMode_Normal: - m_drawer.AppendText(text); - break; - - case EchoMode_Password: - m_drawer.AppendText(Nz::String(text.GetLength(), '*')); - break; - - case EchoMode_PasswordExceptLast: - { - /*m_drawer.Clear(); - std::size_t textLength = m_text.GetLength(); - if (textLength >= 2) - { - std::size_t lastCharacterPosition = m_text.GetCharacterPosition(textLength - 2); - if (lastCharacterPosition != Nz::String::npos) - m_drawer.AppendText(Nz::String(textLength - 1, '*')); - } - - if (textLength >= 1) - m_drawer.AppendText(m_text.SubString(m_text.GetCharacterPosition(textLength - 1)));*/ - - break; - } - } - - UpdateTextSprite(); - - //OnTextChanged(this, m_text); - } - - void RichTextAreaWidget::Clear() - { - AbstractTextAreaWidget::Clear(); - } - - void RichTextAreaWidget::Erase(std::size_t firstGlyph, std::size_t lastGlyph) - { - if (firstGlyph > lastGlyph) - std::swap(firstGlyph, lastGlyph); - - std::size_t textLength = m_drawer.GetGlyphCount(); - if (firstGlyph > textLength) - return; - - std::size_t firstBlock = m_drawer.FindBlock(firstGlyph); - std::size_t lastBlock = m_drawer.FindBlock((lastGlyph > 0) ? lastGlyph - 1 : lastGlyph); - if (firstBlock == lastBlock) - { - const Nz::String& blockText = m_drawer.GetBlockText(firstBlock); - std::size_t blockFirstGlyph = m_drawer.GetBlockFirstGlyphIndex(firstBlock); - - Nz::String newText; - if (firstGlyph > blockFirstGlyph) - { - std::size_t characterPosition = blockText.GetCharacterPosition(firstGlyph - blockFirstGlyph); - NazaraAssert(characterPosition != Nz::String::npos, "Invalid character position"); - - newText.Append(blockText.SubString(0, characterPosition - 1)); - } - - if (lastGlyph < textLength) - newText.Append(blockText.SubString(blockText.GetCharacterPosition(lastGlyph - blockFirstGlyph))); - - if (!newText.IsEmpty()) - m_drawer.SetBlockText(firstBlock, std::move(newText)); - else - m_drawer.RemoveBlock(firstBlock); - } - else - { - const Nz::String& lastBlockText = m_drawer.GetBlockText(lastBlock); - std::size_t lastBlockGlyphIndex = m_drawer.GetBlockFirstGlyphIndex(lastBlock); - - // First, update/delete last block - std::size_t lastCharPos = lastBlockText.GetCharacterPosition(lastGlyph - lastBlockGlyphIndex); - if (lastCharPos != Nz::String::npos) - { - Nz::String newText = lastBlockText.SubString(lastCharPos); - if (!newText.IsEmpty()) - m_drawer.SetBlockText(lastBlock, std::move(newText)); - else - m_drawer.RemoveBlock(lastBlock); - } - - // And then remove all middle blocks, remove in reverse order because of index shifting - assert(lastBlock > 0); - for (std::size_t i = lastBlock - 1; i > firstBlock; --i) - m_drawer.RemoveBlock(i); - - const Nz::String& firstBlockText = m_drawer.GetBlockText(firstBlock); - std::size_t firstBlockGlyphIndex = m_drawer.GetBlockFirstGlyphIndex(firstBlock); - - // And finally update/delete first block - if (firstGlyph > firstBlockGlyphIndex) - { - std::size_t firstCharPos = firstBlockText.GetCharacterPosition(firstGlyph - firstBlockGlyphIndex - 1); - if (firstCharPos != Nz::String::npos) - { - Nz::String newText = firstBlockText.SubString(0, firstCharPos); - if (!newText.IsEmpty()) - m_drawer.SetBlockText(firstBlock, std::move(newText)); - else - m_drawer.RemoveBlock(firstBlock); - } - } - else - m_drawer.RemoveBlock(firstBlock); - } - - UpdateDisplayText(); - } - - void RichTextAreaWidget::Write(const Nz::String& text, std::size_t glyphPosition) - { - if (m_drawer.HasBlocks()) - { - auto block = m_drawer.GetBlock(m_drawer.FindBlock((glyphPosition > 0) ? glyphPosition - 1 : glyphPosition)); - std::size_t firstGlyph = block.GetFirstGlyphIndex(); - assert(glyphPosition >= firstGlyph); - - Nz::String blockText = block.GetText(); - std::size_t characterPosition = blockText.GetCharacterPosition(glyphPosition - firstGlyph); - blockText.Insert(characterPosition, text); - - block.SetText(blockText); - } - else - m_drawer.AppendText(text); - - SetCursorPosition(glyphPosition + text.GetLength()); - - UpdateDisplayText(); - } - - Nz::AbstractTextDrawer& RichTextAreaWidget::GetTextDrawer() - { - return m_drawer; - } - - const Nz::AbstractTextDrawer& RichTextAreaWidget::GetTextDrawer() const - { - return m_drawer; - } - - void RichTextAreaWidget::HandleIndentation(bool add) - { - } - - void RichTextAreaWidget::HandleSelectionIndentation(bool add) - { - } - - void RichTextAreaWidget::HandleWordCursorMove(bool left) - { - } - - void RichTextAreaWidget::UpdateDisplayText() - { - /*m_drawer.Clear(); - switch (m_echoMode) - { - case EchoMode_Normal: - m_drawer.AppendText(m_text); - break; - - case EchoMode_Password: - case EchoMode_PasswordExceptLast: - m_drawer.AppendText(Nz::String(m_text.GetLength(), '*')); - break; - }*/ - - UpdateTextSprite(); - - SetCursorPosition(m_cursorPositionBegin); //< Refresh cursor position (prevent it from being outside of the text) - } -} diff --git a/SDK/src/NDK/Widgets/ScrollAreaWidget.cpp b/SDK/src/NDK/Widgets/ScrollAreaWidget.cpp deleted file mode 100644 index 0d7c1f934..000000000 --- a/SDK/src/NDK/Widgets/ScrollAreaWidget.cpp +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (C) 2019 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include - -namespace Ndk -{ - namespace - { - constexpr float scrollbarPadding = 5.f; - } - - ScrollAreaWidget::ScrollAreaWidget(BaseWidget* parent, BaseWidget* content) : - BaseWidget(parent), - m_content(content), - m_scrollbarStatus(ScrollBarStatus::None), - m_isScrollbarEnabled(true), - m_scrollRatio(0.f) - { - m_content->SetParent(this); - m_content->SetPosition(Nz::Vector3f::Zero()); - - m_scrollbarBackgroundSprite = Nz::Sprite::New(); - m_scrollbarBackgroundSprite->SetColor(Nz::Color(62, 62, 62)); - - m_scrollbarBackgroundEntity = CreateEntity(); - m_scrollbarBackgroundEntity->AddComponent().SetParent(this); - m_scrollbarBackgroundEntity->AddComponent().Attach(m_scrollbarBackgroundSprite, 1); - - m_scrollbarSprite = Nz::Sprite::New(); - m_scrollbarSprite->SetColor(Nz::Color(104, 104, 104)); - - m_scrollbarEntity = CreateEntity(); - m_scrollbarEntity->AddComponent().SetParent(this); - m_scrollbarEntity->AddComponent().Attach(m_scrollbarSprite); - - Resize(m_content->GetSize()); - } - - void ScrollAreaWidget::EnableScrollbar(bool enable) - { - if (m_isScrollbarEnabled != enable) - { - m_isScrollbarEnabled = enable; - - bool isVisible = IsScrollbarVisible(); - m_scrollbarEntity->Enable(isVisible); - m_scrollbarBackgroundEntity->Enable(isVisible); - } - } - - void ScrollAreaWidget::ScrollToRatio(float ratio) - { - m_scrollRatio = Nz::Clamp(ratio, 0.f, 1.f); - - float widgetHeight = GetHeight(); - float maxHeight = widgetHeight - m_scrollbarSprite->GetSize().y - 2.f * scrollbarPadding; - - auto& scrollbarNode = m_scrollbarEntity->GetComponent(); - scrollbarNode.SetPosition(Nz::Vector2f(scrollbarNode.GetPosition(Nz::CoordSys_Local).x, scrollbarPadding + m_scrollRatio * maxHeight)); - - float contentPosition = m_scrollRatio * (widgetHeight - m_content->GetHeight()); - - m_content->SetPosition(0.f, contentPosition); - m_content->SetRenderingRect(Nz::Rectf(-std::numeric_limits::infinity(), -contentPosition, std::numeric_limits::infinity(), widgetHeight)); - } - - Nz::Rectf ScrollAreaWidget::GetScrollbarRect() const - { - Nz::Vector2f scrollBarPosition = Nz::Vector2f(m_scrollbarEntity->GetComponent().GetPosition(Nz::CoordSys_Local)); - Nz::Vector2f scrollBarSize = m_scrollbarSprite->GetSize(); - return Nz::Rectf(scrollBarPosition.x, scrollBarPosition.y, scrollBarSize.x, scrollBarSize.y); - } - - void ScrollAreaWidget::Layout() - { - constexpr float scrollBarBackgroundWidth = 20.f; - constexpr float scrollBarWidth = scrollBarBackgroundWidth - 2.f * scrollbarPadding; - - float areaHeight = GetHeight(); - float contentHeight = m_content->GetHeight(); - - if (contentHeight > areaHeight) - { - m_hasScrollbar = true; - - Nz::Vector2f contentSize(GetWidth() - scrollBarBackgroundWidth, contentHeight); - m_content->Resize(contentSize); - - if (m_isScrollbarEnabled) - { - m_scrollbarEntity->Enable(); - m_scrollbarBackgroundEntity->Enable(); - } - - float scrollBarHeight = std::max(std::floor(areaHeight * (areaHeight / contentHeight)), 20.f); - - m_scrollbarBackgroundSprite->SetSize(scrollBarBackgroundWidth, areaHeight); - m_scrollbarSprite->SetSize(scrollBarWidth, scrollBarHeight); - - m_scrollbarBackgroundEntity->GetComponent().SetPosition(contentSize.x, 0.f); - m_scrollbarEntity->GetComponent().SetPosition(contentSize.x + (scrollBarBackgroundWidth - scrollBarWidth) / 2.f, 0.f); - - ScrollToRatio(m_scrollRatio); - } - else - { - m_hasScrollbar = false; - - m_content->Resize(GetSize()); - - m_scrollbarEntity->Disable(); - m_scrollbarBackgroundEntity->Disable(); - - ScrollToRatio(0.f); - } - - BaseWidget::Layout(); - } - - void ScrollAreaWidget::OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) - { - if (button != Nz::Mouse::Left) - return; - - if (m_scrollbarStatus == ScrollBarStatus::Hovered) - { - UpdateScrollbarStatus(ScrollBarStatus::Grabbed); - - auto& scrollbarNode = m_scrollbarEntity->GetComponent(); - - m_grabbedDelta.Set(x, int(y - scrollbarNode.GetPosition(Nz::CoordSys_Local).y)); - } - } - - void ScrollAreaWidget::OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) - { - if (button != Nz::Mouse::Left) - return; - - if (m_scrollbarStatus == ScrollBarStatus::Grabbed) - { - Nz::Rectf scrollBarRect = GetScrollbarRect(); - UpdateScrollbarStatus((scrollBarRect.Contains(Nz::Vector2f(float(x), float(y)))) ? ScrollBarStatus::Hovered : ScrollBarStatus::None); - } - } - - void ScrollAreaWidget::OnMouseExit() - { - //if (m_scrollbarStatus == ScrollBarStatus::Hovered) - UpdateScrollbarStatus(ScrollBarStatus::None); - } - - void ScrollAreaWidget::OnMouseMoved(int x, int y, int /*deltaX*/, int /*deltaY*/) - { - if (m_scrollbarStatus == ScrollBarStatus::Grabbed) - { - float height = GetHeight(); - float maxHeight = height - m_scrollbarSprite->GetSize().y; - float newHeight = Nz::Clamp(float(y - m_grabbedDelta.y), 0.f, maxHeight); - - ScrollToHeight(newHeight / maxHeight * m_content->GetHeight()); - } - else - { - Nz::Rectf scrollBarRect = GetScrollbarRect(); - UpdateScrollbarStatus((scrollBarRect.Contains(Nz::Vector2f(float(x), float(y)))) ? ScrollBarStatus::Hovered : ScrollBarStatus::None); - } - } - - void ScrollAreaWidget::OnMouseWheelMoved(int /*x*/, int /*y*/, float delta) - { - constexpr float scrollStep = 100.f; - - ScrollToHeight(GetScrollHeight() - scrollStep * delta); - } - - void ScrollAreaWidget::UpdateScrollbarStatus(ScrollBarStatus status) - { - if (m_scrollbarStatus != status) - { - Nz::Color newColor; - switch (status) - { - case ScrollBarStatus::Grabbed: newColor = Nz::Color(235, 235, 235); break; - case ScrollBarStatus::Hovered: newColor = Nz::Color(152, 152, 152); break; - case ScrollBarStatus::None: newColor = Nz::Color(104, 104, 104); break; - } - - m_scrollbarSprite->SetColor(newColor); - m_scrollbarStatus = status; - } - } -} diff --git a/SDK/src/NDK/Widgets/TextAreaWidget.cpp b/SDK/src/NDK/Widgets/TextAreaWidget.cpp deleted file mode 100644 index 4271f43a1..000000000 --- a/SDK/src/NDK/Widgets/TextAreaWidget.cpp +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (C) 2017 Jérôme Leclercq -// This file is part of the "Nazara Development Kit" -// For conditions of distribution and use, see copyright notice in Prerequisites.hpp - -#include -#include -#include -#include -#include - -namespace Ndk -{ - TextAreaWidget::TextAreaWidget(BaseWidget* parent) : - AbstractTextAreaWidget(parent) - { - SetCharacterSize(GetCharacterSize()); //< Actualize minimum / preferred size - - Layout(); - } - - void TextAreaWidget::AppendText(const Nz::String& text) - { - m_text += text; - switch (m_echoMode) - { - case EchoMode_Normal: - m_drawer.AppendText(text); - break; - - case EchoMode_Password: - m_drawer.AppendText(Nz::String(text.GetLength(), '*')); - break; - - case EchoMode_PasswordExceptLast: - { - m_drawer.Clear(); - std::size_t textLength = m_text.GetLength(); - if (textLength >= 2) - { - std::size_t lastCharacterPosition = m_text.GetCharacterPosition(textLength - 2); - if (lastCharacterPosition != Nz::String::npos) - m_drawer.AppendText(Nz::String(textLength - 1, '*')); - } - - if (textLength >= 1) - m_drawer.AppendText(m_text.SubString(m_text.GetCharacterPosition(textLength - 1))); - - break; - } - } - - UpdateTextSprite(); - - OnTextChanged(this, m_text); - } - - void TextAreaWidget::Clear() - { - AbstractTextAreaWidget::Clear(); - - m_text.Clear(); - OnTextChanged(this, m_text); - } - - void TextAreaWidget::Erase(std::size_t firstGlyph, std::size_t lastGlyph) - { - if (firstGlyph > lastGlyph) - std::swap(firstGlyph, lastGlyph); - - std::size_t textLength = m_text.GetLength(); - if (firstGlyph > textLength) - return; - - Nz::String newText; - if (firstGlyph > 0) - { - std::size_t characterPosition = m_text.GetCharacterPosition(firstGlyph); - NazaraAssert(characterPosition != Nz::String::npos, "Invalid character position"); - - newText.Append(m_text.SubString(0, characterPosition - 1)); - } - - if (lastGlyph < textLength) - { - std::size_t characterPosition = m_text.GetCharacterPosition(lastGlyph); - NazaraAssert(characterPosition != Nz::String::npos, "Invalid character position"); - - newText.Append(m_text.SubString(characterPosition)); - } - - SetText(newText); - } - - void TextAreaWidget::Write(const Nz::String& text, std::size_t glyphPosition) - { - if (glyphPosition >= m_drawer.GetGlyphCount()) - { - // It's faster to append than to insert in the middle - AppendText(text); - SetCursorPosition(m_drawer.GetGlyphCount()); - } - else - { - m_text.Insert(m_text.GetCharacterPosition(glyphPosition), text); - SetText(m_text); - - SetCursorPosition(glyphPosition + text.GetLength()); - } - } - - Nz::AbstractTextDrawer& TextAreaWidget::GetTextDrawer() - { - return m_drawer; - } - - const Nz::AbstractTextDrawer& TextAreaWidget::GetTextDrawer() const - { - return m_drawer; - } - - void TextAreaWidget::HandleIndentation(bool add) - { - if (add) - Write(Nz::String('\t')); - else - { - std::size_t currentGlyph = GetGlyphIndex(m_cursorPositionBegin); - - if (currentGlyph > 0 && m_text[m_text.GetCharacterPosition(currentGlyph - 1U)] == '\t') // Check if previous glyph is a tab - { - Erase(currentGlyph - 1U); - - if (m_cursorPositionBegin.x < static_cast(m_drawer.GetLineGlyphCount(m_cursorPositionBegin.y))) - MoveCursor(-1); - } - } - } - - void TextAreaWidget::HandleSelectionIndentation(bool add) - { - for (unsigned line = m_cursorPositionBegin.y; line <= m_cursorPositionEnd.y; ++line) - { - const Nz::Vector2ui cursorPositionBegin = m_cursorPositionBegin; - const Nz::Vector2ui cursorPositionEnd = m_cursorPositionEnd; - - if (add) - { - Write(Nz::String('\t'), { 0U, line }); - SetSelection(cursorPositionBegin + (cursorPositionBegin.y == line && cursorPositionBegin.x != 0U ? Nz::Vector2ui{ 1U, 0U } : Nz::Vector2ui{}), - cursorPositionEnd + (cursorPositionEnd.y == line ? Nz::Vector2ui{ 1U, 0U } : Nz::Vector2ui{})); - } - else - { - if (m_drawer.GetLineGlyphCount(line) == 0) - continue; - - std::size_t firstGlyph = GetGlyphIndex({ 0U, line }); - - if (m_text[m_text.GetCharacterPosition(firstGlyph)] == '\t') - { - Erase(firstGlyph); - SetSelection(cursorPositionBegin - (cursorPositionBegin.y == line && cursorPositionBegin.x != 0U ? Nz::Vector2ui{ 1U, 0U } : Nz::Vector2ui{}), - cursorPositionEnd - (cursorPositionEnd.y == line && cursorPositionEnd.x != 0U ? Nz::Vector2ui{ 1U, 0U } : Nz::Vector2ui{})); - } - } - } - } - - void TextAreaWidget::HandleWordCursorMove(bool left) - { - if (left) - { - std::size_t index = GetGlyphIndex(m_cursorPositionBegin); - if (index == 0) - return; - - std::size_t spaceIndex = m_text.FindLast(' ', index - 2); - std::size_t endlIndex = m_text.FindLast('\n', index - 1); - - if ((spaceIndex > endlIndex || endlIndex == Nz::String::npos) && spaceIndex != Nz::String::npos) - SetCursorPosition(spaceIndex + 1); - else if (endlIndex != Nz::String::npos) - { - if (index == endlIndex + 1) - SetCursorPosition(endlIndex); - else - SetCursorPosition(endlIndex + 1); - } - else - SetCursorPosition({ 0U, m_cursorPositionBegin.y }); - } - else - { - std::size_t index = GetGlyphIndex(m_cursorPositionEnd); - std::size_t spaceIndex = m_text.Find(' ', index); - std::size_t endlIndex = m_text.Find('\n', index); - - if (spaceIndex < endlIndex && spaceIndex != Nz::String::npos) - { - if (m_text.GetSize() > spaceIndex) - SetCursorPosition(spaceIndex + 1); - else - SetCursorPosition({ static_cast(m_drawer.GetLineGlyphCount(m_cursorPositionEnd.y)), m_cursorPositionEnd.y }); - } - else if (endlIndex != Nz::String::npos) - { - if (index == endlIndex) - SetCursorPosition(endlIndex + 1); - else - SetCursorPosition(endlIndex); - } - else - SetCursorPosition({ static_cast(m_drawer.GetLineGlyphCount(m_cursorPositionEnd.y)), m_cursorPositionEnd.y }); - } - } - - void TextAreaWidget::UpdateDisplayText() - { - switch (m_echoMode) - { - case EchoMode_Normal: - m_drawer.SetText(m_text); - break; - - case EchoMode_Password: - case EchoMode_PasswordExceptLast: - m_drawer.SetText(Nz::String(m_text.GetLength(), '*')); - break; - } - - UpdateTextSprite(); - - SetCursorPosition(m_cursorPositionBegin); //< Refresh cursor position (prevent it from being outside of the text) - } - - void TextAreaWidget::UpdateMinimumSize() - { - std::size_t fontCount = m_drawer.GetFontCount(); - float lineHeight = 0; - int spaceAdvance = 0; - for (std::size_t i = 0; i < fontCount; ++i) - { - Nz::Font* font = m_drawer.GetFont(i); - - const Nz::Font::SizeInfo& sizeInfo = font->GetSizeInfo(m_drawer.GetCharacterSize()); - lineHeight = std::max(lineHeight, m_drawer.GetLineHeight()); - spaceAdvance = std::max(spaceAdvance, sizeInfo.spaceAdvance); - } - - Nz::Vector2f size = { float(spaceAdvance), lineHeight + 5.f }; - SetMinimumSize(size); - } -} diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 197fbd440..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,61 +0,0 @@ -version: '{branch}-rev{build}' - -shallow_clone: true - -branches: - only: - - master - -skip_commits: - files: - - .travis.yml - - Doxyfile - - LICENSE - - License-Cabin.txt - - Logo.png - - LogoMini.png - - readme.md - - readme_fr.md - - 'writing style.md' - - doc/* - - NazaraModuleTemplate/* - -os: - - Visual Studio 2019 - -environment: - matrix: - - TOOLSET: vs2019 - -install: - - cd build && "./premake5.exe" %TOOLSET% && cd .. - -configuration: - - DebugDynamic - - ReleaseDynamic - -platform: - - Win32 - - x64 - -build: - project: build/$(TOOLSET)/NazaraEngine.sln - -after_build: - - cd build && "./premake5.exe" package && cd ../package - - 7z a NazaraEngine.7z * && cd .. - -artifacts: - - path: package/NazaraEngine.7z - name: 'NazaraEngine-$(CONFIGURATION)-$(PLATFORM)-$(APPVEYOR_REPO_COMMIT)' - -on_success: - - cd tests && "./NazaraUnitTestsServer.exe" - -notifications: - - provider: Slack - incoming_webhook: - secure: 5FSnJzsZCMXNDqPYGhN4ZSX7qa1KMmbV0UGT9i0LcElk3X91z3fs1TZRpZZ3++Tkw8qAk1G/qDChom5GQ7Vj7X29cScQHvGHXffl3qaC5EdSiGpjloMZKfeiGTnf798IX0n/ABSlDHG7GrB8IiulRGx3iVOpPQmrPWCiz9ZPtY8h84xpd65FGd8gETKG/sYk - on_build_success: true - on_build_failure: true - on_build_status_changed: false diff --git a/tests/resources/Engine/Audio/Cat.flac.REMOVED.git-id b/bin/resources/Engine/Audio/Cat.flac.REMOVED.git-id similarity index 100% rename from tests/resources/Engine/Audio/Cat.flac.REMOVED.git-id rename to bin/resources/Engine/Audio/Cat.flac.REMOVED.git-id diff --git a/tests/resources/Engine/Audio/The_Brabanconne.ogg.REMOVED.git-id b/bin/resources/Engine/Audio/The_Brabanconne.ogg.REMOVED.git-id similarity index 100% rename from tests/resources/Engine/Audio/The_Brabanconne.ogg.REMOVED.git-id rename to bin/resources/Engine/Audio/The_Brabanconne.ogg.REMOVED.git-id diff --git a/tests/resources/Engine/Audio/copyrights.txt b/bin/resources/Engine/Audio/copyrights.txt similarity index 100% rename from tests/resources/Engine/Audio/copyrights.txt rename to bin/resources/Engine/Audio/copyrights.txt diff --git a/tests/resources/Engine/Core/FileTest.txt b/bin/resources/Engine/Core/FileTest.txt similarity index 100% rename from tests/resources/Engine/Core/FileTest.txt rename to bin/resources/Engine/Core/FileTest.txt diff --git a/tests/resources/Engine/Graphics/Bob lamp/Readme.txt b/bin/resources/Engine/Graphics/Bob lamp/Readme.txt similarity index 100% rename from tests/resources/Engine/Graphics/Bob lamp/Readme.txt rename to bin/resources/Engine/Graphics/Bob lamp/Readme.txt diff --git a/tests/resources/Engine/Graphics/copyrights.txt b/bin/resources/Engine/Graphics/copyrights.txt similarity index 100% rename from tests/resources/Engine/Graphics/copyrights.txt rename to bin/resources/Engine/Graphics/copyrights.txt diff --git a/tests/resources/Engine/Graphics/dragon_recon/README b/bin/resources/Engine/Graphics/dragon_recon/README similarity index 100% rename from tests/resources/Engine/Graphics/dragon_recon/README rename to bin/resources/Engine/Graphics/dragon_recon/README diff --git a/examples/bin/resources/Spaceship/readme.txt b/bin/resources/Spaceship/readme.txt similarity index 100% rename from examples/bin/resources/Spaceship/readme.txt rename to bin/resources/Spaceship/readme.txt diff --git a/bin/resources/bloom_bright.nzsl b/bin/resources/bloom_bright.nzsl new file mode 100644 index 000000000..3aa31d795 --- /dev/null +++ b/bin/resources/bloom_bright.nzsl @@ -0,0 +1,69 @@ +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(0), binding(0)] viewerData: uniform, + [set(1), binding(0)] colorTexture: sampler2D, +} + +struct FragIn +{ + [builtin(fragcoord)] fragcoord: vec4 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +struct VertIn +{ + [location(0)] pos: vec3 +} + +struct VertOut +{ + [builtin(position)] position: vec4 +} + +[entry(frag)] +fn main(input: FragIn) -> FragOut +{ + let BrightLuminance = 0.8; + let BrightMiddleGrey = 0.5; + let BrightThreshold = 0.7; + + let fragcoord = input.fragcoord.xy * viewerData.invRenderTargetSize * 10.0; + + let color = colorTexture.Sample(fragcoord).rgb; + color = color * (BrightMiddleGrey/BrightLuminance); + color = color * (vec3(1.0, 1.0, 1.0) + (color / (BrightThreshold*BrightThreshold))); + color = color - vec3(0.5, 0.5, 0.5); + color = color / (vec3(1.0, 1.0, 1.0) + color); + + let output: FragOut; + output.color = vec4(color, 1.0); + + return output; +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + let output: VertOut; + output.position = vec4(input.pos, 1.0); + + return output; +} diff --git a/bin/resources/bloom_final.nzsl b/bin/resources/bloom_final.nzsl new file mode 100644 index 000000000..1f218731c --- /dev/null +++ b/bin/resources/bloom_final.nzsl @@ -0,0 +1,60 @@ +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(0), binding(0)] viewerData: uniform, + [set(1), binding(0)] colorTexture: sampler2D, + [set(1), binding(1)] bloomTexture: sampler2D, +} + +struct FragIn +{ + [builtin(fragcoord)] fragcoord: vec4 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +struct VertIn +{ + [location(0)] pos: vec3 +} + +struct VertOut +{ + [builtin(position)] position: vec4 +} + +[entry(frag)] +fn main(input: FragIn) -> FragOut +{ + let fragcoord = input.fragcoord.xy * viewerData.invRenderTargetSize; + + let output: FragOut; + output.color = colorTexture.Sample(fragcoord) + bloomTexture.Sample(fragcoord); + + return output; +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + let output: VertOut; + output.position = vec4(input.pos, 1.0); + + return output; +} diff --git a/bin/resources/deferred_frag.nzsl b/bin/resources/deferred_frag.nzsl new file mode 100644 index 000000000..609043912 --- /dev/null +++ b/bin/resources/deferred_frag.nzsl @@ -0,0 +1,71 @@ +option HAS_DIFFUSE_TEXTURE: bool; +option HAS_ALPHA_TEXTURE: bool; +option ALPHA_TEST: bool; + +[layout(std140)] +struct BasicSettings +{ + AlphaThreshold: f32, + DiffuseColor: vec4 +} + +[layout(std140)] +struct InstanceData +{ + worldMatrix: mat4, + invWorldMatrix: mat4 +} + +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(0), binding(0)] viewerData: uniform, + [set(1), binding(0)] instanceData: uniform, + [set(2), binding(0)] settings: uniform, + [set(2), binding(2)] MaterialAlphaMap: sampler2D, + [set(2), binding(1)] MaterialDiffuseMap: sampler2D +} + +struct InputData +{ + [location(0)] vertNormal: vec3, + [location(1)] vertUV: vec2, + [location(2)] vertPos: vec3 +} + +struct OutputData +{ + [location(0)] diffuseMap: vec4, + [location(1)] normalMap: vec4, + [location(2)] positionMap: vec4 +} + +[entry(frag)] +fn main(input: InputData) -> OutputData +{ + let textureColor = select_opt(HAS_DIFFUSE_TEXTURE, MaterialDiffuseMap.Sample(input.vertUV) * settings.DiffuseColor, settings.DiffuseColor); + let alpha = select_opt(HAS_ALPHA_TEXTURE, MaterialAlphaMap.Sample(input.vertUV).x * textureColor.w, 1.0); + /*if ((select_opt(ALPHA_TEST, var0.w < settings.AlphaThreshold, false)) == (true)) + { + discard; + }*/ + + let output: OutputData; + output.diffuseMap = textureColor; + output.normalMap = vec4((vec3(1.0, 1.0, 1.0) + input.vertNormal) * 0.5, 1.0); + output.positionMap = vec4(input.vertPos, 1.0); + return output; +} diff --git a/bin/resources/deferred_vert.nzsl b/bin/resources/deferred_vert.nzsl new file mode 100644 index 000000000..68cf179a9 --- /dev/null +++ b/bin/resources/deferred_vert.nzsl @@ -0,0 +1,62 @@ +[layout(std140)] +struct BasicSettings +{ + AlphaThreshold: f32, + DiffuseColor: vec4 +} + +[layout(std140)] +struct InstanceData +{ + worldMatrix: mat4, + invWorldMatrix: mat4 +} + +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(0), binding(0)] viewerData: uniform, + [set(1), binding(0)] instanceData: uniform, + [set(2), binding(0)] settings: uniform, +} + +struct InputData +{ + [location(0)] inPos: vec3, + [location(1)] inNormals: vec3, + [location(2)] inTexCoord: vec2 +} + +struct OutputData +{ + [location(0)] vertNormal: vec3, + [location(1)] vertUV: vec2, + [location(2)] vertPos: vec3, + [builtin(position)] position: vec4 +} + +[entry(vert)] +fn main(input: InputData) -> OutputData +{ + let worldPos = instanceData.worldMatrix * vec4(input.inPos, 1.0); + + let output: OutputData; + output.vertUV = input.inTexCoord; + output.vertNormal = input.inNormals; + output.vertPos = worldPos.xyz; + output.position = viewerData.viewProjMatrix * instanceData.worldMatrix * vec4(input.inPos, 1.0); + return output; +} diff --git a/bin/resources/file_example_MP3_700KB.txt b/bin/resources/file_example_MP3_700KB.txt new file mode 100644 index 000000000..fca4d8ad8 --- /dev/null +++ b/bin/resources/file_example_MP3_700KB.txt @@ -0,0 +1 @@ +https://file-examples.com/index.php/sample-audio-files/sample-mp3-download/ \ No newline at end of file diff --git a/bin/resources/gamma.nzsl b/bin/resources/gamma.nzsl new file mode 100644 index 000000000..beb9ffce6 --- /dev/null +++ b/bin/resources/gamma.nzsl @@ -0,0 +1,46 @@ +external +{ + [binding(0)] colorTexture: sampler2D +} + +struct FragIn +{ + [location(0)] uv: vec2 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +struct VertIn +{ + [location(0)] pos: vec3, + [location(1)] uv: vec2 +} + +struct VertOut +{ + [location(0)] vertUV: vec2, + [builtin(position)] position: vec4 +} + +[entry(frag)] +fn main(input: FragIn) -> FragOut +{ + let gamma = 2.2; + + let output: FragOut; + output.color = colorTexture.Sample(input.uv); + //output.color = pow(colorTexture.Sample(input.uv), vec4(1.0 / gamma, 1.0 / gamma, 1.0 / gamma, 1.0)); + return output; +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + let output: VertOut; + output.position = vec4(input.pos, 1.0); + output.vertUV = input.uv; + return output; +} diff --git a/bin/resources/gaussian_blur.nzsl b/bin/resources/gaussian_blur.nzsl new file mode 100644 index 000000000..2a8221d9b --- /dev/null +++ b/bin/resources/gaussian_blur.nzsl @@ -0,0 +1,78 @@ +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(0), binding(0)] viewerData: uniform, + [set(1), binding(0)] colorTexture: sampler2D, +} + +struct FragIn +{ + [builtin(fragcoord)] fragcoord: vec4 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +struct VertIn +{ + [location(0)] pos: vec3 +} + +struct VertOut +{ + [builtin(position)] position: vec4 +} + +[entry(frag)] +fn main(input: FragIn) -> FragOut +{ + let invTargetSize = viewerData.invRenderTargetSize * 10.0; + let fragcoord = input.fragcoord.xy * invTargetSize; + + let color = colorTexture.Sample(fragcoord).rgb * 0.2270270270; + + let filter = vec2(1.0, 0.0); + + color = color + colorTexture.Sample(fragcoord + filter * 1.3846153846 * invTargetSize).rgb * 0.3162162162; + color = color + colorTexture.Sample(fragcoord - filter * 1.3846153846 * invTargetSize).rgb * 0.3162162162; + + color = color + colorTexture.Sample(fragcoord + filter * 3.2307692308 * invTargetSize).rgb * 0.0702702703; + color = color + colorTexture.Sample(fragcoord - filter * 3.2307692308 * invTargetSize).rgb * 0.0702702703; + + filter = vec2(0.0, 1.0); + + color = color + colorTexture.Sample(fragcoord + filter * 1.3846153846 * invTargetSize).rgb * 0.3162162162; + color = color + colorTexture.Sample(fragcoord - filter * 1.3846153846 * invTargetSize).rgb * 0.3162162162; + + color = color + colorTexture.Sample(fragcoord + filter * 3.2307692308 * invTargetSize).rgb * 0.0702702703; + color = color + colorTexture.Sample(fragcoord - filter * 3.2307692308 * invTargetSize).rgb * 0.0702702703; + + let output: FragOut; + output.color = vec4(color, 1.0); + + return output; +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + let output: VertOut; + output.position = vec4(input.pos, 1.0); + + return output; +} diff --git a/bin/resources/lighting.nzsl b/bin/resources/lighting.nzsl new file mode 100644 index 000000000..176bd4f3e --- /dev/null +++ b/bin/resources/lighting.nzsl @@ -0,0 +1,119 @@ +[layout(std140)] +struct PointLight +{ + color: vec3, + position: vec3, + + radius: f32, + invRadius: f32, +} + +[layout(std140)] +struct SpotLight +{ + transformMatrix: mat4, + + color: vec3, + position: vec3, + direction: vec3, + + radius: f32, + invRadius: f32, + + innerAngle: f32, + outerAngle: f32 +} + +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +[set(0)] +external +{ + [binding(0)] viewerData: uniform +} + +[set(1)] +external +{ + [binding(0)] colorTexture: sampler2D, + [binding(1)] normalTexture: sampler2D, + [binding(2)] positionTexture: sampler2D, +} + +[set(2)] +external +{ + [binding(0)] lightParameters: uniform, +} + +struct FragIn +{ + [builtin(fragcoord)] fragcoord: vec4 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +struct VertIn +{ + [location(0)] pos: vec3 +} + +struct VertOut +{ + [builtin(position)] position: vec4 +} + +[entry(frag)] +fn main(input: FragIn) -> FragOut +{ + let fragcoord = input.fragcoord.xy * viewerData.invRenderTargetSize; + let normal = normalTexture.Sample(fragcoord).xyz * 2.0 - vec3(1.0, 1.0, 1.0); + let position = positionTexture.Sample(fragcoord).xyz; + + let attenuation = compute_attenuation(position, normal); + + let output: FragOut; + output.color = vec4(lightParameters.color, 1.0) * attenuation * colorTexture.Sample(fragcoord); + + return output; +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + let output: VertOut; + output.position = viewerData.projectionMatrix * viewerData.viewMatrix * lightParameters.transformMatrix * vec4(input.pos, 1.0); + + return output; +} + +fn compute_attenuation(worldPos: vec3, normal: vec3) -> f32 +{ + let distance = length(lightParameters.position - worldPos); + + let posToLight = (lightParameters.position - worldPos) / distance; + let lambert = dot(normal, posToLight); + + let curAngle = dot(lightParameters.direction, -posToLight); + let innerMinusOuterAngle = lightParameters.innerAngle - lightParameters.outerAngle; + + let attenuation = max(1.0 - distance * lightParameters.invRadius, 0.0); + attenuation = attenuation * lambert * max((curAngle - lightParameters.outerAngle) / innerMinusOuterAngle, 0.0); + + return attenuation; +} diff --git a/bin/resources/shaders/spirv-triangle.bat b/bin/resources/shaders/spirv-triangle.bat new file mode 100644 index 000000000..af7bd2eda --- /dev/null +++ b/bin/resources/shaders/spirv-triangle.bat @@ -0,0 +1,3 @@ +glslangvalidator -V triangle.vert -o triangle.vert.spv --client opengl100 +glslangvalidator -V triangle.frag -o triangle.frag.spv --client opengl100 + diff --git a/bin/resources/shaders/triangle.frag b/bin/resources/shaders/triangle.frag new file mode 100644 index 000000000..f2ddf7dec --- /dev/null +++ b/bin/resources/shaders/triangle.frag @@ -0,0 +1,20 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout(binding = 1) uniform sampler2D texSampler; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec3 lightDir = vec3(0.0, -0.707, 0.707); + float lightFactor = dot(inNormal, lightDir); + + float gamma = 2.2; + outFragColor = lightFactor * vec4(pow(texture(texSampler, inUV).xyz, vec3(1.0/gamma)), 1.0); +} diff --git a/bin/resources/shaders/triangle.frag.spv b/bin/resources/shaders/triangle.frag.spv new file mode 100644 index 000000000..37fc46adf Binary files /dev/null and b/bin/resources/shaders/triangle.frag.spv differ diff --git a/bin/resources/shaders/triangle.vert b/bin/resources/shaders/triangle.vert new file mode 100644 index 000000000..de648f231 --- /dev/null +++ b/bin/resources/shaders/triangle.vert @@ -0,0 +1,32 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormals; +layout (location = 2) in vec2 inTexCoord; + +layout (binding = 0) uniform UBO +{ + mat4 projectionMatrix; + mat4 modelMatrix; + mat4 viewMatrix; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outTexCoords; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + + +void main() +{ + outNormal = inNormals; + outTexCoords = inTexCoord; + gl_Position = ubo.projectionMatrix * ubo.viewMatrix * ubo.modelMatrix * vec4(inPos, 1.0); + gl_Position.y = -gl_Position.y; +} diff --git a/bin/resources/shaders/triangle.vert.spv b/bin/resources/shaders/triangle.vert.spv new file mode 100644 index 000000000..5692ffb02 Binary files /dev/null and b/bin/resources/shaders/triangle.vert.spv differ diff --git a/bin/resources/skybox.nzsl b/bin/resources/skybox.nzsl new file mode 100644 index 000000000..e51b81d0f --- /dev/null +++ b/bin/resources/skybox.nzsl @@ -0,0 +1,68 @@ +[layout(std140)] +struct ViewerData +{ + projectionMatrix: mat4, + invProjectionMatrix: mat4, + viewMatrix: mat4, + invViewMatrix: mat4, + viewProjMatrix: mat4, + invViewProjMatrix: mat4, + renderTargetSize: vec2, + invRenderTargetSize: vec2, + eyePosition: vec3 +} + +external +{ + [set(1), binding(0)] skybox: samplerCube +} + +struct VertOut +{ + [location(0)] uvw: vec3, + [builtin(position)] position: vec4 +} + +struct FragOut +{ + [location(0)] color: vec4, + [builtin(fragdepth)] depth: f32 +} + +[entry(frag)] +[depth_write(greater)] +fn main(input: VertOut) -> FragOut +{ + let output: FragOut; + output.color = skybox.Sample(input.uvw); + output.depth = 1.0; + + return output; +} + +external +{ + [set(0), binding(0)] viewerData: uniform +} + +struct VertIn +{ + [location(0)] position: vec3 +} + +[entry(vert)] +fn main(input: VertIn) -> VertOut +{ + // Set translation part to zero + let rotationMat = viewerData.viewMatrix; + // rotationMat[3].xyz = vec3(0.0, 0.0, 0.0); // Requires SPIRV generator to handle swizzle for store expressions + rotationMat[3][0] = 0.0; + rotationMat[3][1] = 0.0; + rotationMat[3][2] = 0.0; + + let output: VertOut; + output.position = viewerData.projectionMatrix * rotationMat * vec4(input.position, 1.0); + output.uvw = input.position.xyz; + + return output; +} diff --git a/build/Build_CodeBlocks.bat b/build/Build_CodeBlocks.bat deleted file mode 100644 index f660c144d..000000000 --- a/build/Build_CodeBlocks.bat +++ /dev/null @@ -1 +0,0 @@ -.\premake5.exe codeblocks diff --git a/build/Build_CodeLite.bat b/build/Build_CodeLite.bat deleted file mode 100644 index 2a1634776..000000000 --- a/build/Build_CodeLite.bat +++ /dev/null @@ -1 +0,0 @@ -.\premake5.exe codelite diff --git a/build/Build_VS2015.bat b/build/Build_VS2015.bat deleted file mode 100644 index 8657a02cb..000000000 --- a/build/Build_VS2015.bat +++ /dev/null @@ -1 +0,0 @@ -.\premake5.exe --premakeproject vs2015 diff --git a/build/Build_VS2017.bat b/build/Build_VS2017.bat deleted file mode 100644 index c172c5a59..000000000 --- a/build/Build_VS2017.bat +++ /dev/null @@ -1 +0,0 @@ -.\premake5.exe --premakeproject vs2017 diff --git a/build/Build_VS2019.bat b/build/Build_VS2019.bat deleted file mode 100644 index f9dd7c987..000000000 --- a/build/Build_VS2019.bat +++ /dev/null @@ -1 +0,0 @@ -.\premake5.exe --premakeproject vs2019 diff --git a/build/EncodeResources.bat b/build/EncodeResources.bat deleted file mode 100644 index b7dc0f860..000000000 --- a/build/EncodeResources.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe encoderesources -pause diff --git a/build/Generate_GlobalIncludes.bat b/build/Generate_GlobalIncludes.bat deleted file mode 100644 index df132e9ad..000000000 --- a/build/Generate_GlobalIncludes.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe generateheaders -pause diff --git a/build/Generate_UnicodeData.bat b/build/Generate_UnicodeData.bat deleted file mode 100644 index cff81bd31..000000000 --- a/build/Generate_UnicodeData.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe parseunicode -pause diff --git a/build/Package_AutoDetect.bat b/build/Package_AutoDetect.bat deleted file mode 100644 index f86a8c6e5..000000000 --- a/build/Package_AutoDetect.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe package -pause diff --git a/build/Package_MSVC.bat b/build/Package_MSVC.bat deleted file mode 100644 index c39f1cd6c..000000000 --- a/build/Package_MSVC.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe --pack-libdir=msvc package -pause diff --git a/build/Package_MinGW.bat b/build/Package_MinGW.bat deleted file mode 100644 index 21d4c01fc..000000000 --- a/build/Package_MinGW.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\premake5.exe --pack-libdir=mingw package -pause diff --git a/build/config.lua b/build/config.lua deleted file mode 100644 index 16bf08d33..000000000 --- a/build/config.lua +++ /dev/null @@ -1,26 +0,0 @@ --- This file contains special configurations values, such as directories to extern libraries (Qt) --- Editing this file is not required to use/compile the engine, as default values should be enough - --- Additionnal compilation options ---AdditionalCompilationOptions = "-fsanitize=address" -- Enable ASan - --- Builds Nazara extern libraries (such as lua/STB) -BuildDependencies = true - --- Builds Nazara examples -BuildExamples = true - --- Setup configurations array (valid values: Debug, Release, ReleaseWithDebug) -Configurations = "Debug,Release,ReleaseWithDebug" -- "Debug,Release,ReleaseWithDebug" - --- Setup additionnals install directories, separated by a semi-colon ; (library binaries will be copied there) ---InstallDir = "/usr/local/lib64" - --- Adds a project which will recall premake with its original arguments when built (only works on Windows for now) -PremakeProject = false - --- Excludes client-only modules/tools/examples -ServerMode = false - --- Builds modules as one united library (useless on POSIX systems) -UniteModules = false diff --git a/build/scripts/actions/codeblocks.lua b/build/scripts/actions/codeblocks.lua deleted file mode 100644 index f96a6d591..000000000 --- a/build/scripts/actions/codeblocks.lua +++ /dev/null @@ -1,4 +0,0 @@ -dofile("codeblocks/_codeblocks.lua") -dofile("codeblocks/codeblocks.lua") - -ACTION.Manual = true diff --git a/build/scripts/actions/codeblocks/_codeblocks.lua b/build/scripts/actions/codeblocks/_codeblocks.lua deleted file mode 100644 index 6a52bc404..000000000 --- a/build/scripts/actions/codeblocks/_codeblocks.lua +++ /dev/null @@ -1,44 +0,0 @@ --- --- _codeblocks.lua --- Define the Code::Blocks action(s). --- Copyright (c) 2002-2011 Jason Perkins and the Premake project --- - local p = premake - - p.modules.codeblocks = {} - p.modules.codeblocks._VERSION = p._VERSION - - local codeblocks = p.modules.codeblocks - - newaction { - trigger = "codeblocks", - shortname = "Code::Blocks", - description = "Generate Code::Blocks project files", - - valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib" }, - - valid_languages = { "C", "C++" }, - - valid_tools = { - cc = { "clang", "gcc", "ow" }, - }, - - onWorkspace = function(wks) - p.modules.codeblocks.generateWorkspace(wks) - end, - - onProject = function(prj) - p.modules.codeblocks.generateProject(prj) - end, - - onCleanWorkspace = function(wks) - p.clean.file(wks, wks.name .. ".workspace") - p.clean.file(wks, wks.name .. ".workspace.layout") - end, - - onCleanProject = function(prj) - p.clean.file(prj, prj.name .. ".workspace") - p.clean.file(prj, prj.name .. ".depend") - p.clean.file(prj, prj.name .. ".layout") - end - } diff --git a/build/scripts/actions/codeblocks/codeblocks.lua b/build/scripts/actions/codeblocks/codeblocks.lua deleted file mode 100644 index ebd8d11fa..000000000 --- a/build/scripts/actions/codeblocks/codeblocks.lua +++ /dev/null @@ -1,67 +0,0 @@ --- --- codeblocks_workspace.lua --- Generate a Code::Blocks workspace. --- Copyright (c) 2009 Jason Perkins and the Premake project --- - - local p = premake - - p.modules.codeblocks = {} - p.modules.codeblocks._VERSION = p._VERSION - - local codeblocks = p.modules.codeblocks - local project = p.project - - - function codeblocks.cfgname(cfg) - local cfgname = cfg.buildcfg - if codeblocks.workspace.multiplePlatforms then - cfgname = string.format("%s|%s", cfg.platform, cfg.buildcfg) - end - return cfgname - end - - function codeblocks.esc(value) - local result = value:gsub('"', '"') - result = result:gsub('<', '<') - result = result:gsub('>', '>') - return result - end - - function codeblocks.generateWorkspace(wks) - p.eol("\r\n") - p.indent("\t") - p.escaper(codeblocks.esc) - - p.generate(wks, ".workspace", codeblocks.workspace.generate) - end - - function codeblocks.generateProject(prj) - p.eol("\r\n") - p.indent("\t") - p.escaper(codeblocks.esc) - - if project.iscpp(prj) then - p.generate(prj, ".cbp", codeblocks.project.generate) - end - end - - function codeblocks.cleanWorkspace(wks) - p.clean.file(wks, wks.name .. ".workspace") - p.clean.file(wks, wks.name .. ".workspace.layout") - end - - function codeblocks.cleanProject(prj) - p.clean.file(prj, prj.name .. ".workspace") - p.clean.file(prj, prj.name .. ".depend") - p.clean.file(prj, prj.name .. ".layout") - end - - function codeblocks.cleanTarget(prj) - -- TODO.. - end - - include("codeblocks_workspace.lua") - include("codeblocks_project.lua") - - diff --git a/build/scripts/actions/codeblocks/codeblocks_project.lua b/build/scripts/actions/codeblocks/codeblocks_project.lua deleted file mode 100644 index acfede4c2..000000000 --- a/build/scripts/actions/codeblocks/codeblocks_project.lua +++ /dev/null @@ -1,243 +0,0 @@ --- --- codeblocks_cbp.lua --- Generate a Code::Blocks C/C++ project. --- Copyright (c) 2009, 2011 Jason Perkins and the Premake project --- - - local p = premake - local project = p.project - local config = p.config - local tree = p.tree - local codeblocks = p.modules.codeblocks - - codeblocks.project = {} - local m = codeblocks.project - m.elements = {} - - m.ctools = { - gcc = "gcc", - msc = "Visual C++", - } - - function m.getcompilername(cfg) - local tool = _OPTIONS.cc or cfg.toolset or p.GCC - - local toolset = p.tools[tool] - if not toolset then - error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") - end - - return m.ctools[tool] - end - - function m.getcompiler(cfg) - local toolset = p.tools[_OPTIONS.cc or cfg.toolset or p.GCC] - if not toolset then - error("Invalid toolset '" + (_OPTIONS.cc or cfg.toolset) + "'") - end - return toolset - end - - function m.header(prj) - _p('') - _p('') - _p(1,'') - - -- write project block header - _p(1,'') - _p(2,'') - _p('') - end - - m.elements.project = function(prj) - return { - m.header, - m.configurations, - m.files, - m.extensions, - m.footer - } - end - --- --- Project: Generate the CodeBlocks project file. --- - function m.generate(prj) - p.utf8() - - p.callArray(m.elements.project, prj) - end - - function m.configurations(prj) - -- write configuration blocks - _p(2,'') - local platforms = {} - for cfg in project.eachconfig(prj) do - local found = false - for k,v in pairs(platforms) do - if (v.platform == cfg.platform) then - table.insert(v.configs, cfg) - found = true - break - end - end - - if (not found) then - table.insert(platforms, {platform = cfg.platform, configs = {cfg}}) - end - end - - for k,platform in pairs(platforms) do - for k,cfg in pairs(platform.configs) do - local compiler = m.getcompiler(cfg) - - _p(3,'', cfg.longname) - - _p(4,'') - end - end - _p(2,'') - end - --- --- Write out a list of the source code files in the project. --- - - function m.files(prj) - local pchheader - if (prj.pchheader) then - pchheader = path.getrelative(prj.location, prj.pchheader) - end - - local tr = project.getsourcetree(prj) - tree.traverse(tr, { - -- source files are handled at the leaves - onleaf = function(node, depth) - if node.relpath == node.vpath then - _p(2,'', node.relpath) - else - _p(2,'', node.name) - _p(3,'') - - end, - }, false, 1) - end - - function m.extensions(prj) - for cfg in project.eachconfig(prj) do - if cfg.debugenvs and #cfg.debugenvs > 0 then - --Assumption: if gcc is being used then so is gdb although this section will be ignored by - --other debuggers. If using gcc and not gdb it will silently not pass the - --environment arguments to the debugger - if m.getcompilername(cfg) == "gcc" then - _p(3,'') - _p(4,'', p.esc(cfg.longname)) - local args = '' - local sz = #cfg.debugenvs - for idx, v in ipairs(cfg.debugenvs) do - args = args .. 'set env ' .. v - if sz ~= idx then args = args .. ' ' end - end - _p(5,'',args) - _p(4,'') - _p(3,'') - else - error('Sorry at this moment there is no support for debug environment variables with this debugger and codeblocks') - end - end - end - end diff --git a/build/scripts/actions/codeblocks/codeblocks_workspace.lua b/build/scripts/actions/codeblocks/codeblocks_workspace.lua deleted file mode 100644 index 3de935877..000000000 --- a/build/scripts/actions/codeblocks/codeblocks_workspace.lua +++ /dev/null @@ -1,44 +0,0 @@ --- --- Name: codelite/codelite_workspace.lua --- Purpose: Generate a CodeLite workspace. --- Author: Ryan Pusztai --- Modified by: Andrea Zanellato --- Manu Evans --- Created: 2013/05/06 --- Copyright: (c) 2008-2015 Jason Perkins and the Premake project --- - - local p = premake - local project = p.project - local workspace = p.workspace - local tree = p.tree - local codeblocks = p.modules.codeblocks - - codeblocks.workspace = {} - local m = codeblocks.workspace - --- --- Generate a CodeBlocks workspace --- - function m.generate(wks) - p.utf8() - - _p('') - _p('') - _p(1,'', wks.name) - - for prj in workspace.eachproject(wks) do - local fname = path.join(path.getrelative(wks.location, prj.location), prj.name) - local active = iif(prj.project == wks.projects[1], ' active="1"', '') - - _p(2,'', fname, active) - for _,dep in ipairs(project.getdependencies(prj)) do - _p(3,'', path.join(path.getrelative(wks.location, dep.location), dep.name)) - end - - _p(2,'') - end - - _p(1,'') - _p('') - end \ No newline at end of file diff --git a/build/scripts/actions/encodesresources.lua b/build/scripts/actions/encodesresources.lua deleted file mode 100644 index f508c5c69..000000000 --- a/build/scripts/actions/encodesresources.lua +++ /dev/null @@ -1,49 +0,0 @@ -ACTION.Name = "EncodeResources" -ACTION.Description = "Generate a includable header version of resources" - -ACTION.Function = function () - print("Encoding resources ...") - local startClock = os.clock() - local modules = os.matchdirs("../src/Nazara/*") - table.insert(modules, "../SDK/src/NDK") - for k, modulePath in pairs(modules) do - local moduleName - if (modulePath:sub(4, 6) == "src") then - moduleName = modulePath:sub(15, -1) - else - moduleName = "SDK" - end - local files = os.matchfiles(modulePath .. "/Resources/**") - for k, filePath in pairs(files) do - if (filePath:sub(-2) ~= ".h") then - local file = filePath:sub(modulePath:len() + 12, -1) - local resource, err = io.open(filePath, "rb") - if (not resource) then - error("Failed to read resource file " .. file .. ": " .. err) - end - - local resourceContent = resource:read("*a") - resource:close() - - local contentLength = resourceContent:len() - - local headerContentTable = {} - for i = 1, contentLength do - table.insert(headerContentTable, string.format("%d,", resourceContent:byte(i))) - end - local headerContent = table.concat(headerContentTable) - - local header, err = io.open(filePath .. ".h", "w+") - if (not header) then - error("Failed to create header file for " .. file .. ": " .. err) - end - - header:write(headerContent) - header:close() - - print(string.format("%s: %s (raw: %.3g kB, header: %.3g kB)", moduleName, file, contentLength/1024, string.format("%.3g", headerContent:len()/1024))) - end - end - end - print("Finished (took " .. os.clock() - startClock .. "s)") -end diff --git a/build/scripts/actions/generatefeatures.lua b/build/scripts/actions/generatefeatures.lua deleted file mode 100644 index 50c3f6334..000000000 --- a/build/scripts/actions/generatefeatures.lua +++ /dev/null @@ -1,237 +0,0 @@ -function PrintTable ( t, indent, done ) - done = done or {} - indent = indent or 0 - - local txt = {} - for key, value in pairs (t) do - table.insert(txt, string.rep (" ", indent)) - if (type(value) == "table" and not done[value]) then - done [value] = true - table.insert(txt, tostring(key) .. ":" .. "\n") - table.insert(txt, PrintTable (value, indent + 2, done)) - else - table.insert(txt, tostring (key) .. "\t=\t" ) - table.insert(txt, tostring(value) .. "\n" ) - end - end - - return table.concat(txt) -end - -Feature = {} - --- Tables de vérité -local andTable = -{ - {0,0}, - {0,1}, -} -local orTable = -{ - {0,1}, - {1,1}, -} - -local xorTable = -{ - {0,1}, - {1,0}, -} - -local bitFunc = function (a, b, truthTable) - local power = 1 - local c = 0 - while (a > 0 or b > 0) do - c = c + (truthTable[(a % 2)+1][(b % 2)+1] * power) - a = math.floor(a/2) - b = math.floor(b/2) - power = power * 2 - end - - return c -end - -function Feature.AND(a, b) - return bitFunc(a, b, andTable) -end - -function Feature.OR(a, b) - return bitFunc(a, b, orTable) -end - -function Feature.XOR(a, b) - return bitFunc(a, b, xorTable) -end - -Feature.NotApplicable = 0 -Feature.Windows = 2 ^ 0 -Feature.Linux = 2 ^ 1 -Feature.MacOSX = 2 ^ 2 -Feature.RaspberryPi = 2 ^ 3 -Feature.POSIX = Feature.Linux + Feature.MacOSX + Feature.RaspberryPi - -function Feature.CompleteData(tab, requiredPortability) - if (not requiredPortability) then - assert(tab.RequiredPortability) - requiredPortability = tab.RequiredPortability - elseif (tab.RequiredPortability) then - requiredPortability = Feature.OR(requiredPortability, tab.RequiredPortability) - end - - tab.RequiredPortability = requiredPortability - - if (not tab.Portability) then - tab.Portability = Feature.NotApplicable - end - - if (tab.Features) then - local acc = 0 - for k,v in pairs(tab.Features) do - if (type(v) == "string") then - v = {Title = v} - tab.Features[k] = v - end - - Feature.CompleteData(v, requiredPortability) - - v.Progress = v.Progress or 100 - - acc = acc + v.Progress - end - - tab.Progress = acc/#tab.Features - end -end - -function Feature.Generate() - local files = os.matchfiles("scripts/features/*.lua") - - local modules = {} - - for k, filePath in pairs(files) do - local moduleName = filePath:match(".*/(.*).lua") - - local data = dofile(filePath) - Feature.CompleteData(data) - - modules[moduleName] = data - end - - local content = {} - - local contentType = - { - ["(%s*)%%MODULELIST%%"] = Feature.GenerateModuleList, - ["(%s*)%%MODULEDESCRIPTION%%"] = Feature.GenerateModuleDescriptions, - ["(%s*)%%DATE%%"] = function (dontcare, space, content) - table.insert(content, string.format("%s%s", space, os.date("%d/%m/%Y"))) - end, - } - - local index = io.open("scripts/features/index_template.html") - for line in index:lines() do - local matched = false - for k,v in pairs(contentType) do - local space = line:match(k) - if (space) then - matched = true - v(modules, space, content) - break - end - end - - if (not matched) then - table.insert(content, line) - end - end - - io.open("scripts/features/index.html", "w+"):write(table.concat(content, "\n")) -end - -function Feature.Interpolate(from, to, p) - return from + (to - from)*p -end - -function Feature.ComputeColor(progress) - local stable = {0, 200, 0} - local partial = {255, 127, 0} - local unusable = {255, 0, 0} - - local a, b, p - if (progress < 20) then - a = unusable - b = partial - p = progress/20.0 - else - a = partial - b = stable - p = math.min(20 * 1.020321705^(progress - 20), 100.0)/100.0 -- Je me complique certainement la vie pour ce qui est d'avoir une interpolation exponentielle, mais ça remonte tout ça ... - end - - local color = {nil, nil, nil} - for i = 1, 3 do - color[i] = Feature.Interpolate(a[i], b[i], p) - end - - return color -end - -function Feature.GenerateModuleList(modules, space, content) - for k,v in pairs(modules) do - local c = Feature.ComputeColor(v.Progress) - - table.insert(content, string.format([[%s]], space)) - table.insert(content, string.format([[%s %s]], space, k, v.Title)) - table.insert(content, string.format([[%s %d%%]], space, c[1], c[2], c[3], v.Progress)) - table.insert(content, string.format([[%s]], space)) - end -end - -function Feature.GenerateModuleDescriptions(modules, space, content) - for k,v in pairs(modules) do - table.insert(content, string.format([[%s
]], space)) - table.insert(content, string.format([[%s
]], space, k, v.Title)) - table.insert(content, string.format([[%s %s (%s) : %d%%]], space, k, v.Title, v.LibName, math.floor(v.Progress))) - - table.insert(content, string.format([[%s

Fonctionnalités:

]], space)) - Feature.GenerateFeatureList(v.Features, space .. "\t\t", content) - - table.insert(content, string.format([[%s
]], space)) - end -end - -function Feature.GenerateFeatureList(featureTable, space, content) - table.insert(content, string.format("%s
    ", space)) - for k,v in pairs(featureTable) do - local progress = v.Progress - local c = Feature.ComputeColor(progress) - local desc = (progress == 100) and "" or string.format(" (%d%%)", math.floor(progress)) - - table.insert(content, string.format("%s
  • ", space)) - table.insert(content, string.format([[%s %s%s]], space, c[1], c[2], c[3], v.Title, desc)) - - if (v.Description) then - table.insert(content, string.format([[%s
    %s]], space, v.Description)) - end - - if (v.Features) then - Feature.GenerateFeatureList(v.Features, space .. "\t\t\t", content) - end - - if (v.Note) then - table.insert(content, string.format([[%s
    Note: %s]], space, v.Note)) - end - - if (v.Portability ~= Feature.NotApplicable and Feature.AND(v.Portability, v.RequiredPortability) ~= v.RequiredPortability) then - table.insert(content, string.format([[%s
    Il manque une implémentation sur au moins un des OS supportés]], space)) - end - - table.insert(content, string.format("%s
  • ", space)) - end - table.insert(content, string.format("%s
", space)) -end - -ACTION.Name = "GenerateFeatures" -ACTION.Description = "Generate a web page describing each module's feature" - -ACTION.Function = Feature.Generate diff --git a/build/scripts/actions/generateheaders.lua b/build/scripts/actions/generateheaders.lua deleted file mode 100644 index 2e35f8226..000000000 --- a/build/scripts/actions/generateheaders.lua +++ /dev/null @@ -1,103 +0,0 @@ -ACTION.Name = "GenerateHeaders" -ACTION.Description = "Generate a global header for each module" - -ACTION.ModuleExcludes = {} -ACTION.ModuleExcludes["ConfigCheck.hpp"] = true -ACTION.ModuleExcludes["Debug.hpp"] = true -ACTION.ModuleExcludes["DebugOff.hpp"] = true -ACTION.ModuleExcludes["ThreadSafety.hpp"] = true -ACTION.ModuleExcludes["ThreadSafetyOff.hpp"] = true - -local action = ACTION -ACTION.Function = function () - local paths = {} - - local modules = os.matchdirs("../include/Nazara/*") - for k, modulePath in pairs(modules) do - local moduleName = modulePath:match(".*/(.*)") - - local config, err = io.open(modulePath .. "/Config.hpp", "r") - local head = "" - if (not config) then - error("Failed to read config file: " .. err) - end - - for line in config:lines() do - if (line == "#pragma once") then -- Stop before including the #pragma once as it's already written automatically - break - end - head = head .. line .. "\n" - end - - config:close() - - table.insert(paths, { - Excludes = action.ModuleExcludes, - Header = head, - HeaderGuard = "NAZARA_GLOBAL_" .. moduleName:upper() .. "_HPP", - Name = "Nazara" .. moduleName, - SearchDir = modulePath, - Target = modulePath .. ".hpp", - TopDir = "Nazara" - }) - end - - table.insert(paths, { - Excludes = {}, - HeaderGuard = "NDK_COMPONENTS_GLOBAL_HPP", - Name = "NDK Components", - SearchDir = "../SDK/include/NDK/Components", - TopDir = "NDK", - Target = "../SDK/include/NDK/Components.hpp" - }) - - table.insert(paths, { - Excludes = {}, - HeaderGuard = "NDK_SYSTEMS_GLOBAL_HPP", - Name = "NDK Systems", - SearchDir = "../SDK/include/NDK/Systems", - TopDir = "NDK", - Target = "../SDK/include/NDK/Systems.hpp" - }) - - table.insert(paths, { - Excludes = {}, - HeaderGuard = "NDK_WIDGETS_GLOBAL_HPP", - Name = "NDK Widgets", - SearchDir = "../SDK/include/NDK/Widgets", - TopDir = "NDK", - Target = "../SDK/include/NDK/Widgets.hpp" - }) - - for k,v in ipairs(paths) do - print(v.Name) - local header, err = io.open(v.Target, "w+") - if (not header) then - error("Failed to create header file (" .. v.Target .. "): " .. err) - end - - header:write("// This file was automatically generated\n\n") - if (v.Header) then - header:write(v.Header) - end - - header:write("#pragma once\n\n") - header:write("#ifndef " .. v.HeaderGuard .. "\n") - header:write("#define " .. v.HeaderGuard .. "\n\n") - - local files = os.matchfiles(v.SearchDir .. "/*.hpp") - local count = 0 - for k, filePath in pairs(files) do - local include, fileName = filePath:match(".*(" .. v.TopDir .. "/.*/(.*))") - if (not v.Excludes[fileName]) then - header:write("#include <" .. include .. ">\n") - count = count + 1 - end - end - - header:write("\n#endif // " .. v.HeaderGuard .. "\n") - header:close() - - print(string.format("-#include count: %d", count)) - end -end diff --git a/build/scripts/actions/package.lua b/build/scripts/actions/package.lua deleted file mode 100644 index f263f8faf..000000000 --- a/build/scripts/actions/package.lua +++ /dev/null @@ -1,200 +0,0 @@ -newoption({ - trigger = "pack-libdir", - description = "Specifies the subdirectory in lib/ to be used when packaging the project" -}) - -ACTION.Name = "Package" -ACTION.Description = "Pack Nazara binaries/include/lib together" - -ACTION.Function = function () - local libDir = _OPTIONS["pack-libdir"] - if (not libDir or #libDir == 0) then - local libDirs = os.matchdirs("../lib/*") - if (#libDirs > 1) then - error("More than one subdirectory was found in the lib directory, please use the --pack-libdir command to clarify which directory should be used") - elseif (#libDirs == 0) then - error("No subdirectory was found in the lib directory, have you built the engine yet?") - else - libDir = path.getname(libDirs[1]) - print("No directory was set by the --pack-libdir command, \"" .. libDir .. "\" will be used") - end - end - - local realLibDir = "../lib/" .. libDir .. "/" - if (not os.isdir(realLibDir)) then - error(string.format("\"%s\" doesn't seem to be an existing directory", realLibDir)) - end - - local archEnabled = { - ["x64"] = false, - ["x86"] = false - } - - local enabledArchs = {} - for k,v in pairs(os.matchdirs(realLibDir .. "*")) do - local arch = path.getname(v) - if (archEnabled[arch] ~= nil) then - archEnabled[arch] = true - table.insert(enabledArchs, arch) - else - print("Unknown directory " .. v .. " found, ignored") - end - end - enabledArchs = table.concat(enabledArchs, ", ") - print(enabledArchs .. " arch found") - - local packageDir = "../package/" - - local copyTargets = { - { -- Engine headers - Masks = {"**.hpp", "**.inl"}, - Source = "../include/", - Target = "include/" - }, - { -- SDK headers - Masks = {"**.hpp", "**.inl"}, - Source = "../SDK/include/", - Target = "include/" - }, - { -- Examples files - Masks = {"**.hpp", "**.inl", "**.cpp"}, - Source = "../examples/", - Target = "examples/" - }, - { -- Demo resources - Masks = {"**.*"}, - Source = "../examples/bin/resources/", - Target = "examples/bin/resources/" - }, - -- Unit test sources - { - Masks = {"**.hpp", "**.inl", "**.cpp"}, - Source = "../tests/", - Target = "tests/src/" - }, - -- Unit test resources - { - Masks = {"**.*"}, - Source = "../tests/resources/", - Target = "tests/resources/" - } - } - - local binFileMasks - local libFileMasks - local exeFileExt - local exeFilterFunc - if (os.ishost("windows")) then - binFileMasks = {"**.dll", "**.pdb"} - libFileMasks = {"**.lib", "**.a"} - exeFileExt = ".exe" - exeFilterFunc = function (filePath) return true end - else - if (os.ishost("macosx")) then - binFileMasks = {"**.dynlib"} - else - binFileMasks = {"**.so"} - end - - libFileMasks = {"**.a"} - exeFileExt = "" - exeFilterFunc = function (filePath) return path.getextension(filePath):contains('/') end - end - - for arch, enabled in pairs(archEnabled) do - if (enabled) then - local archLibSrc = realLibDir .. arch .. "/" - local arch3rdPartyBinSrc = "../thirdparty/lib/common/" .. arch .. "/" - local archBinDst = "bin/" .. arch .. "/" - local archLibDst = "lib/" .. arch .. "/" - - -- Engine/SDK binaries - table.insert(copyTargets, { - Masks = binFileMasks, - Source = archLibSrc, - Target = archBinDst - }) - - -- Engine/SDK libraries - table.insert(copyTargets, { - Masks = libFileMasks, - Source = archLibSrc, - Target = archLibDst - }) - - -- 3rd party binary dep - table.insert(copyTargets, { - Masks = binFileMasks, - Source = arch3rdPartyBinSrc, - Target = archBinDst - }) - end - end - - -- Demo executable - table.insert(copyTargets, { - Masks = {"Demo*" .. exeFileExt}, - Filter = exeFilterFunc, - Source = "../examples/bin/", - Target = "examples/bin/" - }) - - -- Unit test - table.insert(copyTargets, { - Masks = {"*" .. exeFileExt}, - Filter = exeFilterFunc, - Source = "../tests/", - Target = "tests/" - }) - - -- Processing - os.mkdir(packageDir) - - local size = 0 - for k,v in pairs(copyTargets) do - local target = packageDir .. v.Target - local includePrefix = v.Source - - local targetFiles = {} - for k, mask in pairs(v.Masks) do - print(includePrefix .. mask .. " => " .. target) - local files = os.matchfiles(includePrefix .. mask) - if (v.Filter) then - for k,path in pairs(files) do - if (not v.Filter(path)) then - files[k] = nil - end - end - end - - targetFiles = table.join(targetFiles, files) - end - - for k,v in pairs(targetFiles) do - local relPath = v:sub(#includePrefix + 1) - - local targetPath = target .. relPath - local targetDir = path.getdirectory(targetPath) - - if (not os.isdir(targetDir)) then - local ok, err = os.mkdir(targetDir) - if (not ok) then - print("Failed to create directory \"" .. targetDir .. "\": " .. err) - end - end - - local ok, err = os.copyfile(v, targetPath) - if (not ok) then - print("Failed to copy \"" .. v .. "\" to \"" .. targetPath .. "\": " .. err) - end - - local stat = os.stat(targetPath) - if (stat) then - size = size + stat.size - end - end - end - - local config = libDir .. " - " .. enabledArchs - print(string.format("Package successfully created at \"%s\" (%u MB, %s)", packageDir, size // (1024 * 1024), config)) -end diff --git a/build/scripts/common.lua b/build/scripts/common.lua deleted file mode 100644 index dbba87b1b..000000000 --- a/build/scripts/common.lua +++ /dev/null @@ -1,1169 +0,0 @@ -NazaraBuild = {} - --- I wish Premake had a way to know the compiler in advance -local clangGccActions = "action:" .. table.concat({"codeblocks", "codelite", "gmake*", "xcode3", "xcode4"}, " or ") - -function NazaraBuild:AddExecutablePath(path) - self.ExecutableDir[path] = true - - self:AddInstallPath(path) -end - -function NazaraBuild:AddInstallPath(path) - self.InstallDir[path] = true -end - -function NazaraBuild:FilterLibDirectory(prefix, func) - filter({"action:codeblocks or codelite or gmake*", "architecture:x86", "system:Windows"}) - func(prefix .. "mingw/x86") - - filter({"action:codeblocks or codelite or gmake*", "architecture:x86_64", "system:Windows"}) - func(prefix .. "mingw/x64") - - filter({"action:codeblocks or codelite or gmake*", "architecture:x86", "system:not Windows"}) - func(prefix .. "gmake/x86") - - filter({"action:codeblocks or codelite or gmake*", "architecture:x86_64", "system:not Windows"}) - func(prefix .. "gmake/x64") - - filter({"action:vs*", "architecture:x86"}) - func(prefix .. "msvc/x86") - - filter({"action:vs*", "architecture:x86_64"}) - func(prefix .. "msvc/x64") - - filter({"action:xcode3 or xcode4", "architecture:x86"}) - func(prefix .. "xcode/x86") - - filter({"action:xcode3 or xcode4", "architecture:x86_64"}) - func(prefix .. "xcode/x64") - - filter({}) -end - -function NazaraBuild:Execute() - if (_ACTION == nil) then -- If no action is specified, the user probably only wants to know how all of this works - return - end - - local platformData - if (os.is64bit()) then - platformData = {"x64", "x86"} - else - platformData = {"x86", "x64"} - end - - if (self.Actions[_ACTION] == nil) then - -- Start defining projects - workspace("NazaraEngine") - platforms(platformData) - - startproject "DemoFirstScene" - location(_ACTION) - - do - local linkTypes = {"Dynamic"} -- {"Static", "Dynamic"} - local configs = {} - for k,linkType in pairs(linkTypes) do - for k,config in pairs(self.Config["Configurations"]) do - table.insert(configs, config .. linkType) - end - end - - configurations(configs) - end - - if (self.Config["PremakeProject"] and os.ishost("windows")) then - group("_Premake") - - local commandLine = "premake5.exe " .. table.concat(_ARGV, ' ') - project("Regenerate premake") - kind("Utility") - prebuildcommands("cd .. && " .. commandLine) - end - - -- Extern libraries - if (self.Config["BuildDependencies"]) then - group("Thirdparties") - - for k, libTable in ipairs(self.OrderedExtLibs) do - project(libTable.Name) - - self:PrepareGeneric() - - language(libTable.Language) - location(_ACTION .. "/thirdparty") - - files(libTable.Files) - excludes(libTable.FilesExcluded) - - defines(libTable.Defines) - flags(libTable.Flags) - kind("StaticLib") -- Force them as static libs - includedirs("../thirdparty/include") - includedirs(libTable.Includes) - links(libTable.Libraries) - libdirs("../thirdparty/lib/common") - - self:FilterLibDirectory("../thirdparty/genlib/", targetdir) -- For generated libraries - - filter(clangGccActions) - buildoptions("-U__STRICT_ANSI__") - - filter("architecture:x86") - libdirs(libTable.LibraryPaths.x86) - - filter("architecture:x86_64") - libdirs(libTable.LibraryPaths.x64) - - for k,v in pairs(libTable.ConfigurationLibraries) do - filter(k) - links(v) - end - - filter({}) - - if (libTable.Custom) then - libTable.Custom() - end - end - end - - -- Modules - group("Engine Modules") - - if (_OPTIONS["united"]) then - project("NazaraEngine") - - self:PrepareMainWorkspace() - end - - for k, moduleTable in ipairs(self.OrderedModules) do - if (not _OPTIONS["united"]) then - project("Nazara" .. moduleTable.Name) - - self:PrepareMainWorkspace() - end - - location(_ACTION .. "/modules") - - includedirs({ - "../include", - "../src/", - "../thirdparty/include" - }) - - files(moduleTable.Files) - excludes(moduleTable.FilesExcluded) - - defines(moduleTable.Defines) - flags(moduleTable.Flags) - includedirs(moduleTable.Includes) - links(moduleTable.Libraries) - - libdirs({ - "../thirdparty/lib/common", - "../lib" - }) - - -- Output to lib/conf/arch - self:FilterLibDirectory("../lib/", targetdir) - - -- Copy the module binaries to the example folder - self:MakeInstallCommands(moduleTable) - - filter("architecture:x86") - libdirs(moduleTable.LibraryPaths.x86) - - filter("architecture:x86_64") - libdirs(moduleTable.LibraryPaths.x64) - - for k,v in pairs(moduleTable.ConfigurationLibraries) do - filter(k) - links(v) - end - - filter({}) - - if (moduleTable.Custom) then - moduleTable.Custom() - end - end - - -- Tools - group("Engine SDK - Tools") - - for k, toolTable in ipairs(self.OrderedTools) do - local prefix = "Nazara" - if (toolTable.Kind == "plugin") then - prefix = "Plugin" - end - - project(prefix .. toolTable.Name) - - self:PrepareMainWorkspace() - - location(_ACTION .. "/tools") - - if (toolTable.Kind == "plugin" or toolTable.Kind == "library") then - kind("SharedLib") - - -- Copy the tool binaries to the example folder - self:MakeInstallCommands(toolTable) - elseif (toolTable.Kind == "application") then - debugdir(toolTable.TargetDirectory) - targetdir(toolTable.TargetDirectory) - if (toolTable.EnableConsole) then - kind("ConsoleApp") - else - kind("WindowedApp") - end - else - assert(false, "Invalid tool kind") - end - - includedirs({ - "../include", - "../thirdparty/include" - }) - - libdirs({ - "../thirdparty/lib/common", - "../lib" - }) - - files(toolTable.Files) - excludes(toolTable.FilesExcluded) - - defines(toolTable.Defines) - flags(toolTable.Flags) - includedirs(toolTable.Includes) - links(toolTable.Libraries) - - -- Output to lib/conf/arch - if (toolTable.Kind == "library") then - self:FilterLibDirectory(toolTable.TargetDirectory .. "/", targetdir) - elseif (toolTable.Kind == "plugin") then - self:FilterLibDirectory("../plugins/lib/", targetdir) - end - - filter("architecture:x86") - libdirs(toolTable.LibraryPaths.x86) - - filter("architecture:x86_64") - libdirs(toolTable.LibraryPaths.x64) - - for k,v in pairs(toolTable.ConfigurationLibraries) do - filter(k) - links(v) - end - - filter({}) - - if (toolTable.Custom) then - toolTable.Custom() - end - end - - group("Examples") - - for k, exampleTable in ipairs(self.OrderedExamples) do - local destPath = "../examples/bin" - - project("Demo" .. exampleTable.Name) - - self:PrepareMainWorkspace() - - location(_ACTION .. "/examples") - - if (exampleTable.Kind == "plugin" or exampleTable.Kind == "library") then - kind("SharedLib") - - self:MakeInstallCommands(toolTable) - elseif (exampleTable.Kind == "application") then - debugdir(exampleTable.TargetDirectory) - if (exampleTable.EnableConsole) then - kind("ConsoleApp") - else - kind("WindowedApp") - end - else - assert(false, "Invalid tool Kind") - end - - debugdir(destPath) - includedirs({ - "../include", - "../thirdparty/include" - }) - libdirs("../lib") - - files(exampleTable.Files) - excludes(exampleTable.FilesExcluded) - - defines(exampleTable.Defines) - flags(exampleTable.Flags) - includedirs(exampleTable.Includes) - links(exampleTable.Libraries) - targetdir(destPath) - - for k,v in pairs(exampleTable.ConfigurationLibraries) do - filter(k) - links(v) - end - - filter({}) - - if (exampleTable.Custom) then - exampleTable.Custom() - end - end - end -end - -function NazaraBuild:GetConfig() - return self.Config -end - -function NazaraBuild:GetDependency(infoTable, name) - local projectName = name:match("Nazara(%w+)") - if (projectName) then - -- tool or module - local moduleTable = self.Modules[projectName:lower()] - if (moduleTable) then - return moduleTable - else - local toolTable = self.Tools[projectName:lower()] - if (toolTable) then - return toolTable - end - end - else - return self.ExtLibs[name:lower()] - end -end - -function NazaraBuild:Initialize() - self.Actions = {} - self.Examples = {} - self.ExecutableDir = {} - self.ExtLibs = {} - self.InstallDir = {} - self.Modules = {} - self.Tools = {} - - self.Config = {} - self:LoadConfig() - - -- Actions - modules = os.matchfiles("scripts/actions/*.lua") - for k,v in pairs(modules) do - local f, err = loadfile(v) - if (f) then - ACTION = {} - - f() - - local succeed, err = self:RegisterAction(ACTION) - if (not succeed) then - print("Unable to register action: " .. err) - end - else - print("Unable to load action file: " .. err) - end - end - ACTION = nil - - -- Extern libraries - local extlibs = os.matchfiles("../thirdparty/build/*.lua") - for k,v in pairs(extlibs) do - local f, err = loadfile(v) - if (f) then - LIBRARY = {} - self:SetupExtlibTable(LIBRARY) - - f() - - local succeed, err = self:RegisterExternLibrary(LIBRARY) - if (not succeed) then - print("Unable to register extern library: " .. err) - end - else - print("Unable to load extern library file: " .. err) - end - end - LIBRARY = nil - - -- Then the modules - local modules = os.matchfiles("scripts/modules/*.lua") - for k,v in pairs(modules) do - local moduleName = v:match(".*/(.*).lua") - local moduleNameLower = moduleName:lower() - - local f, err = loadfile(v) - if (f) then - MODULE = {} - self:SetupModuleTable(MODULE) - Config = self.Config - - f() - - local succeed, err = self:RegisterModule(MODULE) - if (not succeed) then - print("Unable to register module: " .. err) - end - else - print("Unable to load module file: " .. err) - end - end - MODULE = nil - - -- Continue with the tools (ex: SDK) - local tools = os.matchfiles("scripts/tools/*.lua") - for k,v in pairs(tools) do - local toolName = v:match(".*/(.*).lua") - local toolNameLower = toolName:lower() - - local f, err = loadfile(v) - if (f) then - TOOL = {} - self:SetupToolTable(TOOL) - - f() - - local succeed, err = self:RegisterTool(TOOL) - if (not succeed) then - print("Unable to register tool " .. tostring(TOOL.Name) .. ": " .. err) - end - else - print("Unable to load tool file " .. v .. ": " .. err) - end - end - TOOL = nil - - -- Examples - if (self.Config["BuildExamples"]) then - local examples = os.matchdirs("../examples/*") - for k,v in pairs(examples) do - local dirName = v:match(".*/(.*)") - if (dirName ~= "bin" and dirName ~= "build") then - local f, err = loadfile(v .. "/build.lua") - if (f) then - EXAMPLE = {} - EXAMPLE.Directory = dirName - self:SetupExampleTable(EXAMPLE) - - f() - - local succeed, err = self:RegisterExample(EXAMPLE) - if (not succeed) then - print("Unable to register example: " .. err) - end - else - print("Unable to load example file: " .. err) - end - end - end - EXAMPLE = nil - end - - -- Once everything is registred, let's process all the tables - self.OrderedExamples = {} - self.OrderedExtLibs = {} - self.OrderedModules = {} - self.OrderedTools = {} - local tables = {self.ExtLibs, self.Modules, self.Tools, self.Examples} - local orderedTables = {self.OrderedExtLibs, self.OrderedModules, self.OrderedTools, self.OrderedExamples} - for k,projects in ipairs(tables) do - -- Begin by resolving every project (because of dependencies in the same category) - for projectId,projectTable in pairs(projects) do - self:Resolve(projectTable) - end - - for projectId,projectTable in pairs(projects) do - if (self:Process(projectTable)) then - table.insert(orderedTables[k], projectTable) - else - print("Rejected " .. projectTable.Name .. " " .. string.lower(projectTable.Category) .. ": " .. projectTable.ExcludeReason) - end - end - - table.sort(orderedTables[k], function (a, b) return a.Name < b.Name end) - end -end - -function NazaraBuild:LoadConfig() - local f = io.open("config.lua", "r") - if (f) then - local content = f:read("*a") - f:close() - - local func, err = load(content, "Config file", "t", self.Config) - if (func) then - local status, err = pcall(func) - if (not status) then - print("Failed to load config.lua: " .. err) - end - else - print("Failed to parse config.lua: " .. err) - end - else - print("Failed to open config.lua") - end - - local configTable = self.Config - local AddBoolOption = function (option, name, description) - newoption({ - trigger = name, - description = description - }) - - local str = _OPTIONS[name] - if (str) then - if (#str == 0 or str == "1" or str == "yes" or str == "true") then - configTable[option] = true - elseif (str == "0" or str == "no" or str == "false") then - configTable[option] = false - else - error("Invalid entry for " .. name .. " option: \"" .. str .. "\"") - end - end - end - - local AddStringOption = function (option, name, description) - newoption({ - trigger = name, - description = description - }) - - local str = _OPTIONS[name] - if (str) then - configTable[option] = str - end - end - - AddBoolOption("BuildDependencies", "with-extlibs", "Builds the extern libraries") - AddBoolOption("BuildExamples", "with-examples", "Builds the examples") - AddBoolOption("PremakeProject", "premakeproject", "Add a PremakeProject as a shortcut to call Premake") - AddBoolOption("ServerMode", "server", "Excludes client-only modules/tools/examples") - AddBoolOption("UniteModules", "united", "Builds all the modules as one united library") - AddBoolOption("PlatformSDL2", "platform-sdl2", "Use SDL2 instead of native APIs") - - -- AdditionalCompilationOptions - do - newoption({ - trigger = "compile-options", - description = "Specify additionnal compilation options to be added to every generated project." - }) - - configTable["AdditionalCompilationOptions"] = configTable["AdditionalCompilationOptions"] or "" - if (_OPTIONS["compile-options"] ~= nil) then - configTable["AdditionalCompilationOptions"] = configTable["AdditionalCompilationOptions"] .. ";" .. _OPTIONS["compile-options"] - end - - local configs = {} - local paths = string.explode(configTable["AdditionalCompilationOptions"], ";") - for k,v in pairs(paths) do - if (#v > 0) then - table.insert(configs, v) - end - end - - configTable["AdditionalCompilationOptions"] = configs - end - - -- Configurations - do - newoption({ - trigger = "configurations", - description = "Override configurations target by a new set, separated by commas." - }) - - configTable["Configurations"] = configTable["Configurations"] or "" - if (_OPTIONS["configurations"] ~= nil) then - configTable["Configurations"] = _OPTIONS["configurations"] - end - - local configs = {} - local validConfigs = {"Debug", "Release", "ReleaseWithDebug"} - local paths = string.explode(configTable["Configurations"], ",") - for k,v in pairs(paths) do - v = v:match("^%s*(.-)%s*$") -- Trim - if (#v > 0) then - if (table.contains(validConfigs, v)) then - table.insert(configs, v) - else - error("Invalid entry for configurations option: \"" .. v .. "\"") - end - end - end - - if (#configs == 0) then - error("Invalid entry for configurations option: no option") - end - - configTable["Configurations"] = configs - end - - -- InstallDir - do - newoption({ - trigger = "install-path", - description = "Setup additionnals install directories (library binaries will be copied there), separated by commas" - }) - - configTable["InstallDir"] = configTable["InstallDir"] or "" - if (_OPTIONS["install-path"] ~= nil) then - configTable["InstallDir"] = configTable["InstallDir"] .. ";" .. _OPTIONS["install-path"] - end - - local paths = string.explode(configTable["InstallDir"], ";") - for k,v in pairs(paths) do - if (#v > 0) then - self:AddInstallPath(v) - end - end - end -end - -function NazaraBuild:MakeInstallCommands(infoTable) - if (os.ishost("windows")) then - filter("kind:SharedLib") - - postbuildmessage("Copying " .. infoTable.Name .. " library and its dependencies to install/executable directories...") - - -- Copy built file to install directory - local installCommands = {} - for installPath,_ in pairs(self.InstallDir) do - local destPath = path.translate(path.isabsolute(installPath) and installPath or "../../" .. installPath) - table.insert(installCommands, [[xcopy "%{path.translate(cfg.buildtarget.relpath)}" "]] .. destPath .. [[\" /E /Y]]) - end - table.sort(installCommands) - - for k,command in pairs(installCommands) do - postbuildcommands({command}) - end - - -- Copy additional dependencies to executable directories too - for k,fileName in pairs(table.join(infoTable.Libraries, infoTable.DynLib)) do - local paths = {} - for k,v in pairs(infoTable.BinaryPaths.x86) do - table.insert(paths, {"x86", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x86", v .. "/lib" .. fileName .. ".dll"}) - end - - for k,v in pairs(infoTable.BinaryPaths.x64) do - table.insert(paths, {"x86_64", v .. "/" .. fileName .. ".dll"}) - table.insert(paths, {"x86_64", v .. "/lib" .. fileName .. ".dll"}) - end - - for k,v in pairs(paths) do - local arch = v[1] - local srcPath = v[2] - if (os.isfile(srcPath)) then - if (infoTable.Kind == "plugin") then - srcPath = "../../" .. srcPath - end - - filter("architecture:" .. arch) - - local executableCommands = {} - for execPath,_ in pairs(self.ExecutableDir) do - local srcPath = path.isabsolute(srcPath) and path.translate(srcPath) or [[%{path.translate(cfg.linktarget.relpath:sub(1, -#cfg.linktarget.name - 1) .. "../../]] .. srcPath .. [[")}]] - local destPath = path.translate(path.isabsolute(execPath) and execPath or "../../" .. execPath) - table.insert(executableCommands, [[xcopy "]] .. srcPath .. [[" "]] .. destPath .. [[\" /E /Y]]) - end - - table.sort(executableCommands) - - for k,command in pairs(executableCommands) do - postbuildcommands({command}) - end - end - end - end - - filter({}) - end -end - -local PosixOSes = { - ["bsd"] = true, - ["linux"] = true, - ["macosx"] = true, - ["solaris"] = true -} - -function NazaraBuild:Process(infoTable) - if (infoTable.Excluded) then - return false - end - - local libraries = {} - for k, library in pairs(infoTable.Libraries) do - local libraryTable = self:GetDependency(infoTable, library) - if (libraryTable) then - if (libraryTable.Excluded) then - infoTable.Excluded = true - infoTable.ExcludeReason = "depends on excluded " .. library .. " " .. libraryTable.Category:lower() - return false - end - - if (libraryTable.Type == "Module") then - if (_OPTIONS["united"]) then - library = "NazaraEngine" - else - library = "Nazara" .. libraryTable.Name - end - - if (not self.Config["UniteModules"] or infoTable.Type ~= "Module") then - table.insert(infoTable.ConfigurationLibraries.DebugStatic, library .. "-s-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.DebugDynamic, library .. "-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseDynamic, library) - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugDynamic, library) - end - elseif (libraryTable.Type == "ExternLib") then - library = libraryTable.Name - - if (self.Config["BuildDependencies"]) then - table.insert(libraries, library) - else - table.insert(infoTable.ConfigurationLibraries.DebugStatic, library .. "-s-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.DebugDynamic, library .. "-s-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseDynamic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugDynamic, library .. "-s") - end - elseif (libraryTable.Type == "Tool") then - library = "Nazara" .. libraryTable.Name - - -- Import tools includes - for k,v in ipairs(libraryTable.Includes) do - table.insert(infoTable.Includes, v) - end - - -- And libraries - for k, v in pairs(libraryTable.Libraries) do - table.insert(infoTable.Libraries, v) - end - - for config, libs in pairs(libraryTable.ConfigurationLibraries) do - for k,v in pairs(libs) do - table.insert(infoTable.ConfigurationLibraries[config], v) - end - end - - table.insert(infoTable.ConfigurationLibraries.DebugStatic, library .. "-s-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugStatic, library .. "-s") - table.insert(infoTable.ConfigurationLibraries.DebugDynamic, library .. "-d") - table.insert(infoTable.ConfigurationLibraries.ReleaseDynamic, library) - table.insert(infoTable.ConfigurationLibraries.ReleaseWithDebugDynamic, library) - else - infoTable.Excluded = true - infoTable.ExcludeReason = "dependency " .. library .. " has invalid type \"" .. libraryTable.Type .. "\"" - return false - end - else - table.insert(libraries, library) - end - end - infoTable.Libraries = libraries - - for k,v in pairs(infoTable) do - local target = k:match("Os(%w+)") - if (target) then - local targetTable = infoTable[target] - if (targetTable) then - local excludeTargetTable = infoTable[target .. "Excluded"] - for platform, defineTable in pairs(v) do - platform = string.lower(platform) - if (platform == "posix") then - local osname = os.target() - if (PosixOSes[osname]) then - platform = osname - end - end - - if (os.istarget(platform)) then - for k,v in ipairs(defineTable) do - table.insert(targetTable, v) - end - elseif (excludeTargetTable) then - for k,v in ipairs(defineTable) do - table.insert(excludeTargetTable, v) - end - end - end - - infoTable[k] = nil - end - end - end - - if (infoTable.Kind == "application") then - self:AddExecutablePath(infoTable.TargetDirectory) - end - - if (infoTable.Validate) then - local ret, err = infoTable:Validate() - if (not ret) then - infoTable.Excluded = true - infoTable.ExcludeReason = "validation failed: " .. err - return false - end - end - - return true -end - -function NazaraBuild:PrepareGeneric() - flags({ - "MultiProcessorCompile", - "NoMinimalRebuild", - "RelativeLinks", - "ShadowedVariables", - "UndefinedIdentifiers" - }) - - cppdialect("C++14") - - self:FilterLibDirectory("../thirdparty/genlib/", libdirs) - self:FilterLibDirectory("../thirdparty/lib/", libdirs) - - -- Fixes Premake stuff - filter({"kind:SharedLib", clangGccActions}) - implibprefix("lib") - filter({"kind:*Lib", clangGccActions, "system:Windows"}) - implibextension(".a") - filter({"kind:StaticLib", clangGccActions}) - targetextension(".a") - targetprefix("lib") - - -- General configuration - filter("kind:*Lib") - pic("On") - - filter({"kind:StaticLib", "configurations:Debug*"}) - targetsuffix("-s-d") - - filter({"kind:StaticLib", "configurations:Release*"}) - targetsuffix("-s") - - filter({"kind:SharedLib", "configurations:Debug*"}) - targetsuffix("-d") - - filter("configurations:*Debug*") - optimize("Debug") - symbols("On") - - filter("configurations:not *Debug*") - omitframepointer("On") - - -- Setup some optimizations for release - filter("configurations:Release*") - defines("NDEBUG") - optimize("Speed") - vectorextensions("SSE2") - - filter("configurations:*Static") - kind("StaticLib") - - filter("configurations:*Dynamic") - kind("SharedLib") - - -- Enable MSVC conformance (not required but better) - filter("action:vs*") - buildoptions({"/permissive-", "/Zc:__cplusplus", "/Zc:referenceBinding", "/Zc:throwingNew"}) - - -- Enable SSE math and vectorization optimizations - filter({"configurations:Release*", clangGccActions}) - buildoptions("-mfpmath=sse") - buildoptions("-ftree-vectorize") - - filter({}) - - buildoptions(self.Config["AdditionalCompilationOptions"]) -end - -function NazaraBuild:PrepareMainWorkspace() - self:PrepareGeneric() - - language("C++") - - -- Add lib/conf/arch to library search path - self:FilterLibDirectory("../lib/", libdirs) - self:FilterLibDirectory("../lib/", runpathdirs) - - filter("action:vs*") - buildoptions({"/MP", "/bigobj"}) -- Multiprocessus build and big .obj - defines("_CRT_SECURE_NO_WARNINGS") - defines("_SCL_SECURE_NO_WARNINGS") - - filter("architecture:x86_64") - defines("NAZARA_PLATFORM_x64") - - filter("configurations:Debug*") - defines("NAZARA_DEBUG") - - filter("configurations:*Static") - defines("NAZARA_STATIC") - - filter("kind:*Lib") - defines("NAZARA_BUILD") - - filter({"system:Windows", clangGccActions}) - buildoptions("-Wa,-mbig-obj") -- big object - - filter({"system:not Windows", clangGccActions}) - buildoptions("-fvisibility=hidden") - - filter({}) -end - -function NazaraBuild:RegisterAction(actionTable) - if (not actionTable.Manual) then - if (actionTable.Name == nil or type(actionTable.Name) ~= "string" or string.len(actionTable.Name) == 0) then - return false, "Invalid action name" - end - - local lowerCaseName = string.lower(actionTable.Name) - if (self.Actions[lowerCaseName] ~= nil) then - return false, "This action name is already in use" - end - - if (actionTable.Description == nil or type(actionTable.Description) ~= "string") then - return false, "Action description is invalid" - end - - if (string.len(actionTable.Description) == 0) then - return false, "Action description is empty" - end - - if (actionTable.Function == nil or type(actionTable.Function) ~= "function") then - return false, "Action function is invalid" - end - - self.Actions[lowerCaseName] = actionTable - - newaction - { - trigger = lowerCaseName, - description = actionTable.Description, - execute = function () actionTable:Function() end - } - end - - return true -end - -function NazaraBuild:RegisterExample(exampleTable) - if (exampleTable.Name == nil or type(exampleTable.Name) ~= "string" or string.len(exampleTable.Name) == 0) then - return false, "Invalid example name" - end - - local lowerCaseName = exampleTable.Name:lower() - if (self.Examples[lowerCaseName] ~= nil) then - return false, "This library name is already in use" - end - - if (exampleTable.Files == nil or type(exampleTable.Files) ~= "table") then - return false, "Example files table is invalid" - end - - if (#exampleTable.Files == 0) then - return false, "This example has no files" - end - - local files = {} - for k, file in ipairs(exampleTable.Files) do - table.insert(files, "../examples/" .. exampleTable.Directory .. "/" .. file) - end - exampleTable.Files = files - - exampleTable.Type = "Example" - exampleTable.Category = exampleTable.Category or exampleTable.Type - - self.Examples[lowerCaseName] = exampleTable - return true -end - -function NazaraBuild:RegisterExternLibrary(libTable) - if (libTable.Name == nil or type(libTable.Name) ~= "string" or string.len(libTable.Name) == 0) then - return false, "Invalid library name" - end - - local lowerCaseName = libTable.Name:lower() - if (self.ExtLibs[lowerCaseName] ~= nil) then - return false, "This library name is already in use" - end - - if (libTable.Files == nil or type(libTable.Files) ~= "table") then - return false, "Invalid file table" - end - - if (#libTable.Files == 0) then - return false, "This library has no files" - end - - libTable.Type = "ExternLib" - libTable.Category = libTable.Category or libTable.Type - - self.ExtLibs[lowerCaseName] = libTable - return true -end - -function NazaraBuild:RegisterModule(moduleTable) - if (moduleTable.Name == nil or type(moduleTable.Name) ~= "string" or string.len(moduleTable.Name) == 0) then - return false, "Invalid module name" - end - - local lowerCaseName = moduleTable.Name:lower() - if (self.Modules[lowerCaseName] ~= nil) then - return false, "This module name is already in use" - end - - table.insert(moduleTable.Defines, "NAZARA_" .. moduleTable.Name:upper() .. "_BUILD") - table.insert(moduleTable.Files, "../include/Nazara/" .. moduleTable.Name .. "/**.hpp") - table.insert(moduleTable.Files, "../include/Nazara/" .. moduleTable.Name .. "/**.inl") - table.insert(moduleTable.Files, "../src/Nazara/" .. moduleTable.Name .. "/**.hpp") - table.insert(moduleTable.Files, "../src/Nazara/" .. moduleTable.Name .. "/**.inl") - table.insert(moduleTable.Files, "../src/Nazara/" .. moduleTable.Name .. "/**.cpp") - - if (self.Config["UniteModules"] and lowerCaseName ~= "core") then - table.insert(moduleTable.FilesExcluded, "../src/Nazara/" .. moduleTable.Name .. "/Debug/NewOverload.cpp") - end - - moduleTable.Type = "Module" - moduleTable.Category = moduleTable.Category or moduleTable.Type - - self.Modules[lowerCaseName] = moduleTable - return true -end - -function NazaraBuild:RegisterTool(toolTable) - if (toolTable.Name == nil or type(toolTable.Name) ~= "string" or string.len(toolTable.Name) == 0) then - return false, "Invalid tool name" - end - - local lowerCaseName = toolTable.Name:lower() - if (self.Tools[lowerCaseName] ~= nil) then - return false, "This tool name is already in use" - end - - if (toolTable.Kind == nil or type(toolTable.Kind) ~= "string" or string.len(toolTable.Kind) == 0) then - return false, "Invalid tool type" - end - - local lowerCaseKind = toolTable.Kind:lower() - if (lowerCaseKind == "library" or lowerCaseKind == "plugin" or lowerCaseKind == "application") then - toolTable.Kind = lowerCaseKind - else - return false, "Invalid tool type" - end - - if (lowerCaseKind ~= "plugin" and (toolTable.TargetDirectory == nil or type(toolTable.TargetDirectory) ~= "string" or string.len(toolTable.TargetDirectory) == 0)) then - return false, "Invalid tool directory" - end - - toolTable.Type = "Tool" - toolTable.Category = toolTable.Category or toolTable.Type - - self.Tools[lowerCaseName] = toolTable - return true -end - -local globalExcludes = {} -function NazaraBuild:Resolve(infoTable) - if (infoTable.ClientOnly and self.Config["ServerMode"]) then - infoTable.Excluded = true - infoTable.ExcludeReason = "excluded by command-line options (client-only)" - end - - if (infoTable.Excludable) then - local globalExcludeOption = "excludes-" .. infoTable.Category:lower() .. "s" - if (not globalExcludes[infoTable.Category]) then - newoption({ - trigger = globalExcludeOption, - description = "Excludes all " .. string.lower(infoTable.Category) .. "s and projects relying on it" - }) - - globalExcludes[infoTable.Category] = true - end - - local specificExcludeOption = "excludes-" .. string.lower(infoTable.Category .. "-" .. infoTable.Name) - newoption({ - trigger = specificExcludeOption, - description = "Excludes the " .. infoTable.Name .. " " .. string.lower(infoTable.Category) .. " and projects relying on it" - }) - - if (_OPTIONS[globalExcludeOption]) then - infoTable.Excluded = true - infoTable.ExcludeReason = "excluded by global command-line options" - elseif (_OPTIONS[specificExcludeOption]) then - infoTable.Excluded = true - infoTable.ExcludeReason = "excluded by specific command-line options" - end - end - - if (type(infoTable.Libraries) == "function") then - infoTable.Libraries = infoTable.Libraries() - end -end - -function NazaraBuild:SetupInfoTable(infoTable) - infoTable.BinaryPaths = {} - infoTable.BinaryPaths.x86 = {} - infoTable.BinaryPaths.x64 = {} - infoTable.ConfigurationLibraries = {} - infoTable.ConfigurationLibraries.DebugStatic = {} - infoTable.ConfigurationLibraries.ReleaseStatic = {} - infoTable.ConfigurationLibraries.ReleaseWithDebugStatic = {} - infoTable.ConfigurationLibraries.DebugDynamic = {} - infoTable.ConfigurationLibraries.ReleaseDynamic = {} - infoTable.ConfigurationLibraries.ReleaseWithDebugDynamic = {} - infoTable.Excludable = true - infoTable.LibraryPaths = {} - infoTable.LibraryPaths.x86 = {} - infoTable.LibraryPaths.x64 = {} - - local infos = {"Defines", "DynLib", "Files", "FilesExcluded", "Flags", "Includes", "Libraries"} - for k,v in ipairs(infos) do - infoTable[v] = {} - infoTable["Os" .. v] = {} - end -end - -function NazaraBuild:SetupExampleTable(infoTable) - self:SetupInfoTable(infoTable) - - infoTable.Kind = "application" - infoTable.TargetDirectory = "../examples/bin" -end - -function NazaraBuild:SetupExtlibTable(infoTable) - self:SetupInfoTable(infoTable) - - infoTable.Kind = "library" - - table.insert(infoTable.BinaryPaths.x86, "../thirdparty/lib/common/x86") - table.insert(infoTable.BinaryPaths.x64, "../thirdparty/lib/common/x64") - table.insert(infoTable.LibraryPaths.x86, "../thirdparty/lib/common/x86") - table.insert(infoTable.LibraryPaths.x64, "../thirdparty/lib/common/x64") -end - -function NazaraBuild:SetupModuleTable(infoTable) - self:SetupInfoTable(infoTable) - - infoTable.Kind = "library" - - table.insert(infoTable.BinaryPaths.x86, "../thirdparty/lib/common/x86") - table.insert(infoTable.BinaryPaths.x64, "../thirdparty/lib/common/x64") - table.insert(infoTable.LibraryPaths.x86, "../thirdparty/lib/common/x86") - table.insert(infoTable.LibraryPaths.x64, "../thirdparty/lib/common/x64") -end - -NazaraBuild.SetupToolTable = NazaraBuild.SetupInfoTable diff --git a/build/scripts/features/audio.lua b/build/scripts/features/audio.lua deleted file mode 100644 index 3c6a7dea7..000000000 --- a/build/scripts/features/audio.lua +++ /dev/null @@ -1,89 +0,0 @@ -return { - Title = "Module audio", - LibName = "NazaraAudio", - Description = "Module permettant de charger et jouer des sons, ainsi que d'accéder au microphone", - RequiredPortability = Feature.Windows + Feature.POSIX, - - Features = - { - { - Title = "Gestion des émetteurs de sons (SoundEmitter)", - Description = "Classe de base dont héritent les sources sonores (Music, Sound)", - Features = - { - "Positionnement 3D (spatialisation) si désiré", - "Configuration de l'atténuation", - "Prise en charge de l'effet Doppler (vitesse du son)", - "Altération du ton (pitch)" - } - }, - { - Title = "Gestion des tampons sonores (SoundBuffer)", - Description = "Tampon (buffer) stockant les échantillons (samples) décompressés, chargés à partir de fichiers sonores.", - Features = - { - { - Title = "Mixage mono", - Description = "Permet de mixer les différents canaux en un seul (mono), permettant la spatialisation.", - Note = "Le mixage mono n'est actuellement possible qu'au chargement du tampon depuis un fichier", - Progress = 90 - } - } - }, - { - Title = "Gestion des flux sonores (SoundStream)", - Description = "Interface permettant de définir un flux sonore de source indéfinie (fichier, réseau, etc.)" - }, - { - Title = "Sons (Sound)", - Description = "Classe permettant de jouer un tampon sonore", - Features = - { - "Bouclage", - "Mise en pause", - "Récupération/positionnement de l'indice de lecture (offset)" - } - }, - { - Title = "Sons streamés (Music)", - Description = "Classe permettant de jouer un son depuis un flux quelconque (SoundStream)", - Features = - { - "Streaming depuis un fichier sonore (+ mixage mono si demandé)", - "Bouclage", - "Mise en pause", - {Title = "Mixage mono", Note = "Le mixage mono devrait être possible au niveau du son lui-même plutôt qu'au niveau du loader", Progress = 0}, - {Title = "Récupération/positionnement de l'indice de lecture (offset)", Progress = 0} - } - }, - { - Title = "Configuration globale (Audio)", - Description = "Classe permettant de régler les différents paramètres généraux de l'environnement sonore", - Features = - { - "Positionnement/Orientation du listener", - "Réglage du volume général", - "Réglage de la vitesse du son/facteur Doppler" - } - }, - { - Title = "Microphone", - Description = "Classe permettant l'accès aux microphones connectés à l'ordinateur", - Progress = 0 - }, - { - Title = "Environnement (EFX)", - Description = "Prise en charge de l'environnement", - Progress = 0 - }, - { - Title = "Formats supportés (chargement/streaming)", - Description = "Liste des formats de fichiers supportés par le loader inclus par le module (libsndfile)", - Note = "Le populaire format MP3 n'est pas supporté pour des raisons de royalties (mais la flexibilité du moteur vous permet de rajouter votre propre loader MP3)", - Features = - { - "aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k", "nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve" - } - } - } -} \ No newline at end of file diff --git a/build/scripts/features/core.lua b/build/scripts/features/core.lua deleted file mode 100644 index 0c71af179..000000000 --- a/build/scripts/features/core.lua +++ /dev/null @@ -1,203 +0,0 @@ -return { - Title = "Noyau", - LibName = "NazaraCore", - Description = "Noyau du moteur, possède les fonctionnalités utilisées partout ailleurs dans le moteur.", - RequiredPortability = Feature.Windows + Feature.POSIX, - - Features = - { - { - Title = "Classes utilitaires de base", - Description = "Classes assurant certaines fonctionnalités de base destinées à aider le programmeur.", - Features = - { - { - Title = "Chaînes de caractère unicode (String)", - Description = "Classe supplantant std::string, rajoutant le support de l'UTF-8 et quelques opérations utiles (rechercher/remplacer, correspondance par motif, ..)." - }, - { - Title = "Exécution de code lors de la destruction (CallOnExit)", - Description = "Permet l'appel d'une fonction/lambda à la destruction de cet objet, en accordance avec le RAII/RRID." - }, - { - Title = "Gestion de l'initialisation/libération statique de classes, en accordance avec le RAII/RRID", - Description = "Permet d'initialiser et de libérer automatiquement des classes possédant des fonctions membres statiques Initialize/Uninitialize, selon un ordre de dépendance, comme par exemple les classes des modules du moteur lui-même." - }, - { - Title = "Gestion des couleurs (Color)", - Description = "Classe permettant de stocker et effectuer des opérations sur des couleurs (conversion, mélange, etc.)." - }, - { - Title = "Gestion de primitives, au sens géométrique (Primitive, PrimitiveList)", - Description = "Structures définissant certaines primitives géométriques (boite, cône, plan, sphère), utiles pour la génération de meshs (de rendu ou physiques)." - }, - { - Title = "OffsetOf", - Description = "Fonction permettant de récupérer à la compilation l'adresse locale (décalage d'octets) d'un membre de n'importe quelle structure/classe." - }, - { - Title = "Pointeurs à écart (stride) indépendant (SparsePtr)", - Description = "Classe se comportant comme un pointeur, à l'exception de l'écart entre deux éléments (opérations d'accès, d'addition et de soustraction) qui est indépendant du type pointé." - }, - { - Title = "Stockage et gestion de champs de bits dynamiques (Bitset)", - Description = "Classe permettant le stockage et la manipulation optimisée d'un nombre élevé et dynamique de bits (=booléens, opérations de comptage, recherche de bits activés, opérations entre champs de bits, etc.)", - Note = "Il manque une spécialisation de la fonction de hachage", - Progress = 95 - } - } - }, - { - Title = "Gestion de fichiers et dossiers (File/Directory)", - Description = "Classes supportant les chemins unicodes et les tailles 64 bits, ainsi que quelques opérations sur les chemins (normalisation, transformation d'un chemin relatif en chemin absolu).", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "Gestion de l'endianness", - Description = "Boutisme, récupération à la compilation ou à l'exécution, possibilité de lire des fichiers en corrigeant le boutisme des objets lors de la lecture." - }, - { - Title = "Gestion de bibliothèques dynamiques (DynLib)", - Description = "Classe permettant de charger à l'exécution des bibliothèques dynamiques (selon la plateforme: .dll/.so/.dynlib) et d'en extraire des fonctions.", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "Fonctions de hachage", - Description = "Possibilité de hacher (calculer une somme de contrôle) de n'importe quelles données, chaîne de caractère ou fichier.", - Features = - { - {Title = "CRC16", Progress = 0}, - "CRC32", - "Fletcher16", - {Title = "Fletcher32", Progress = 0}, - "MD5", - "SHA-1", - "SHA-224", - "SHA-256", - "SHA-384", - "SHA-512", - "Whirlpool" - } - }, - { - Title = "Gestion de la mémoire", - Description = "Set de fonctionnalités permettant d'aider le programmeur à gérer la mémoire de son programme.", - Features = - { - { - Title = "MemoryManager", - Description = "Classe permettant de suivre les allocations de mémoire et éventuels leaks, peut suivre automatiquement chaque allocation du programme." - }, - { - Title = "MemoryPool", - Description = "Classe permettant d'allouer/libérer des blocs de mémoire de taille prédéfinie à coût constant." - } - } - }, - { - Title = "Gestion de l'exécution concurrentielle", - Description = "Set de fonctionnalités liées à l'exécution et la synchronisation entre processus légers (threads) sans dépendance sur la bibliothèque standard.", - Features = - { - { - Title = "Thread", - Description = "Classe permettant d'appeler une fonction (avec passage d'arguments) dans un thread, supporte une interface similaire à std::thread.", - Note = "Il n'est pas encore possible de récupérer le Thread::Id courant", - Progress = 95, - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "Mutex", - Description = "Primitive de synchronisation binaire (exclusion mutuelle).", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "Semaphore", - Description = "Primitive de synchronisation à N concurrents simultanés.", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "ConditionVariable", - Description = "Primitive de synchronisation à signaux.", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "LockGuard", - Description = "Classe utilitaire permettant de verrouiller/déverrouiller une mutex en accordance avec le RAII/RRID." - }, - { - Title = "TaskScheduler", - Description = "Classe permettant de répartir X tâches sur Y workers de façon efficace.", - Portability = Feature.Windows + Feature.POSIX - } - } - }, - { - Title = "Gestion du temps", - Description = "Classes/fonctions permettant de gérer le temps dans un programme.", - Features = - { - { - Title = "Récupération du temps en millisecondes ou en microsecondes", - Description = "Permet de récupérer le nombre de millisecondes ou de microsecondes (si supporté par le système) écoulées depuis un référentiel constant (référentiel indéterminé).", - Portability = Feature.Windows + Feature.POSIX - }, - { - Title = "Clock", - Description = "Classe chronomètre permettant de mesurer le temps écoulé depuis un évènement précis, supporte la mise en pause." - } - } - }, - { - Title = "Gestion de compteurs de référence", - Description = "Set de classes permettant de gérer des pointeurs intelligents partagés intrusifs.", - }, - { - Title = "Gestion de liste de paramètres", - Description = "Classe gérant une liste de paramètres nommées à type variable.", - }, - { - Title = "Gestion de ressources (chargement/gestion)", - Description = "Set de classes s'occupant du chargement et de la gestion de certaines classes spéciales, appartenant au groupe des ressources (ex: chargée depuis un fichier).", - Features = - { - { - Title = "ResourceLibrary", - Description = "Classe template chargée du stockage de ressources de façon nommée." - }, - { - Title = "ResourceLoader", - Description = "Classe template chargée de stocker et gérer des loaders (fonctions s'occupant de transformer un flux de données en ressource)." - }, - { - Title = "ResourceManager", - Description = "Classe template chargée de charger et mettre en cache des ressources depuis un chemin de fichier." - } - } - }, - { - Title = "Gestion des plugins", - Description = "Capacité d'extension du moteur à l'aide de bibliothèques dynamiques conçues dans cette optique.", - Note = "Nécessite une révision, permettant aux plugins de se signaler (nom, version)", - Progress = 80 - }, - { - Title = "Gestion de l'empaquetage bidimensionnel", - Description = "Algorithmes permettant de placer des rectangles 2D arbitraires dans un espace prédéfini de façon à minimiser la perte d'espace.", - Note = "Algorithme Guillotine terminé, algorithme Skyline manquant", - Progress = 60 - }, - { - Title = "Gestion de l'Unicode", - Description = "Récupération d'informations sur les caractères Unicode (si les données Unicode sont incorporées au programme).", - Note = "Il manque l'intégration des UnicodeData dans le moteur", - Progress = 20 - }, - { - Title = "Récupération d'informations sur le hardware", - Description = "Classe permettant, si la plateforme le supporte, de récupérer des informations utiles sur le matériel: nom et fabricant du processeur, nombre de coeurs, support d'un set d'extension (exemple: SSE), quantité de mémoire vive, exécution de l'instruction CPUID.", - Progress = 100, - Portability = Feature.Windows + Feature.POSIX - } - } -} \ No newline at end of file diff --git a/build/scripts/features/index_template.html b/build/scripts/features/index_template.html deleted file mode 100644 index 43bf5aea9..000000000 --- a/build/scripts/features/index_template.html +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - Avancement de Nazara - - -
- Nazara Engine - -
- - Retrouvez le moteur sur GitHub !
- Dépôt GitHub

- Venez vous renseigner sur les topics dédiés à Nazara présents sur plusieurs sites web :
- OpenClassrooms, Progdupeupl ou ZesteDeSavoir -

- ... ou pourquoi ne pas venir faire un tour sur le forum dédié au moteur ? - -
- -

Fonctionnalités de Nazara

- -
Dernière mise à jour : - %DATE% -
- -

Important:

-

Afin de faciliter la mise à jour, la page que vous voyez ici a été générée automatiquement par un script Lua, ce qui m'oblige néanmoins à encoder les fonctionnalités de chaque module dans un premier temps. - C'est un travail assez long (pour vous donner une idée, les données du noyau représentent un fichier de 200 lignes), et il n'est pas encore complet, c'est pourquoi des modules manquent sur cette page.
- Gardez donc à l'esprit que le moteur possède plus de fonctionnalités que ce qui est décrit actuellement sur cette page.

- -

Oh et bien sûr je ne suis pas concepteur de site web, c'est pourquoi cette page est moche (j'ai essayé de minimiser les dégâts).
- Si vous sentez en vous l'irrésistible envie d'améliorer cette page, sachez que votre aide serait grandement appréciée (vous pouvez me contacter via le lien de votre choix plus haut).

- -

Le pourcentage indiqué est calculé automatiquement en fonction des fonctionnalités, cela signifie qu'une fonctionnalité présente sera comptée à 100% à partir du moment où son implémentation de base est considérée fonctionnelle, cela n'est donc pas une assurance qu'aucun bug n'existe concernant cette fonctionnalité (cependant cela signifie que la fonctionnalité est utilisable).
- Et bien entendu, un module ou une fonctionnalité ayant atteint les 100% peut toujours évoluer par la suite.

- -
- - - - - - - - - - - %MODULELIST% - -
Sommaire
ModuleAvancement
- - %MODULEDESCRIPTION% -
- - - - - - - - - - %MODULELIST% - -
Sommaire
ModulePourcentage
-
- - \ No newline at end of file diff --git a/build/scripts/features/style.css b/build/scripts/features/style.css deleted file mode 100644 index ff83f706c..000000000 --- a/build/scripts/features/style.css +++ /dev/null @@ -1,121 +0,0 @@ -/* Je ne suis pas développeur HTML/CSS, je dois y toucher une fois l'an, désolé pour les quelques atrocités que vous pourrez trouver ici */ - -body -{ - font-family: sans-serif; - text-align: center; - margin: 0; - background-color: #f1f1f1; -} - -#englob { - display: block; - margin-left: auto; - margin-right: auto; - background-color: white; - width: 50%; - min-width: 765px; - padding: 0 20px; -} - -hr { - height: 0; - border: 0; - border-top: 1px solid #eee; -} - -a -{ - color: #007ACC; -} - -a:hover -{ - color: lightblue; -} - -h1 -{ - display: inline; -} - -h2 -{ - display: inline; - text-decoration: underline; -} - -h4 -{ - text-decoration: underline; -} - -p { - text-align: justify; -} - -ol -{ - list-style-type: none; -} - -table -{ - border-collapse: collapse; - text-align: center; - display: inline-block; - border: white groove; - border-radius: 10px; - box-shadow: 0px 0px 10px lightblue; -} - -th -{ - text-shadow: 2px 2px 4px black; -} - -tr -{ - border: 1px solid white; -} - -tbody tr:hover -{ - text-shadow: 0px 0px 4px white; -} - -.description -{ - margin-left: 20px; -} - -.lastupdate -{ - font-size: x-large; - font-weight: bold; - color: #f1c40f; -} - -.modulename -{ - font-size: x-large; - font-weight: bold; - text-shadow: 2px 2px 10px #007ACC; -} - -.note -{ - margin-left: 20px; - color: #007ACC; -} - -.notedesc -{ - color: rgb(200, 200, 255); -} - -.portability -{ - margin-left: 20px; - color: red; -} \ No newline at end of file diff --git a/build/scripts/modules/audio.lua b/build/scripts/modules/audio.lua deleted file mode 100644 index 509972dc3..000000000 --- a/build/scripts/modules/audio.lua +++ /dev/null @@ -1,33 +0,0 @@ -MODULE.Name = "Audio" - -MODULE.ClientOnly = true - -MODULE.Defines = { - "NAZARA_AUDIO_OPENAL" -} - -MODULE.Libraries = { - "NazaraCore" -} - -MODULE.OsLibraries.Windows = { - "sndfile-1" -} - -MODULE.OsLibraries.Posix = { - "sndfile" -} - -MODULE.OsDynLib.Windows = { - "soft_oal" -} - -MODULE.OsFiles.Windows = { - "../src/Nazara/Audio/Win32/**.hpp", - "../src/Nazara/Audio/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/Audio/Posix/**.hpp", - "../src/Nazara/Audio/Posix/**.cpp" -} diff --git a/build/scripts/modules/core.lua b/build/scripts/modules/core.lua deleted file mode 100644 index e998080f8..000000000 --- a/build/scripts/modules/core.lua +++ /dev/null @@ -1,24 +0,0 @@ -MODULE.Name = "Core" -MODULE.Excludable = false -- Excluding the core makes no sense as everything relies on it - -MODULE.Files = { -- Other files will be automatically added - "../include/Nazara/Prerequisites.hpp", - "../include/Nazara/Math/**.hpp", - "../include/Nazara/Math/**.inl", -} - -MODULE.OsFiles.Windows = { - "../src/Nazara/Core/Win32/**.hpp", - "../src/Nazara/Core/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/Core/Posix/**.hpp", - "../src/Nazara/Core/Posix/**.cpp" -} - -MODULE.OsLibraries.Posix = { - "dl", - "m", -- Math library (for sincos()) - "pthread" -} diff --git a/build/scripts/modules/graphics.lua b/build/scripts/modules/graphics.lua deleted file mode 100644 index 5c0bf4224..000000000 --- a/build/scripts/modules/graphics.lua +++ /dev/null @@ -1,8 +0,0 @@ -MODULE.Name = "Graphics" - -MODULE.Libraries = { - "NazaraCore", - "NazaraUtility", - "NazaraPlatform", - "NazaraRenderer" -} diff --git a/build/scripts/modules/lua.lua b/build/scripts/modules/lua.lua deleted file mode 100644 index 96fe0cbc1..000000000 --- a/build/scripts/modules/lua.lua +++ /dev/null @@ -1,7 +0,0 @@ --- Quelle ironie -MODULE.Name = "Lua" - -MODULE.Libraries = { - "lua", - "NazaraCore" -} diff --git a/build/scripts/modules/network.lua b/build/scripts/modules/network.lua deleted file mode 100644 index 9245d72f3..000000000 --- a/build/scripts/modules/network.lua +++ /dev/null @@ -1,29 +0,0 @@ -MODULE.Name = "Network" - -MODULE.Libraries = { - "NazaraCore" -} - -MODULE.OsFiles.Windows = { - "../src/Nazara/Network/Win32/**.hpp", - "../src/Nazara/Network/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/Network/Posix/**.hpp", - "../src/Nazara/Network/Posix/**.cpp" -} - -MODULE.OsFiles.Linux = { - "../src/Nazara/Network/Linux/**.hpp", - "../src/Nazara/Network/Linux/**.cpp" -} - -MODULE.OsFilesExcluded.Linux = { - "../src/Nazara/Network/Posix/SocketPollerImpl.hpp", - "../src/Nazara/Network/Posix/SocketPollerImpl.cpp" -} - -MODULE.OsLibraries.Windows = { - "ws2_32" -} diff --git a/build/scripts/modules/noise.lua b/build/scripts/modules/noise.lua deleted file mode 100644 index 155cd83be..000000000 --- a/build/scripts/modules/noise.lua +++ /dev/null @@ -1,5 +0,0 @@ -MODULE.Name = "Noise" - -MODULE.Libraries = { - "NazaraCore" -} diff --git a/build/scripts/modules/physics2d.lua b/build/scripts/modules/physics2d.lua deleted file mode 100644 index a7cf10ffb..000000000 --- a/build/scripts/modules/physics2d.lua +++ /dev/null @@ -1,8 +0,0 @@ -MODULE.Name = "Physics2D" - -MODULE.Defines = {"CP_USE_CGTYPES=0", "TARGET_OS_IPHONE=0", "TARGET_OS_MAC=0"} - -MODULE.Libraries = { - "NazaraCore", - "chipmunk" -} diff --git a/build/scripts/modules/physics3d.lua b/build/scripts/modules/physics3d.lua deleted file mode 100644 index d8b9ea352..000000000 --- a/build/scripts/modules/physics3d.lua +++ /dev/null @@ -1,24 +0,0 @@ -MODULE.Name = "Physics3D" - -MODULE.Defines = { - "_NEWTON_STATIC_LIB" -} - -MODULE.OsDefines.Windows = { - "_WINDOWS" -} - -MODULE.Libraries = { - "NazaraCore", - "newton" -- Newton Game Dynamics -} - -MODULE.Custom = function() - vectorextensions("SSE3") - - filter({"architecture:x86_64", "system:linux"}) - defines("_POSIX_VER_64") - - filter({"architecture:x86", "system:linux"}) - defines("_POSIX_VER") -end diff --git a/build/scripts/modules/platform.lua b/build/scripts/modules/platform.lua deleted file mode 100644 index e3be1e0be..000000000 --- a/build/scripts/modules/platform.lua +++ /dev/null @@ -1,27 +0,0 @@ -MODULE.Name = "Platform" - -MODULE.ClientOnly = true - -MODULE.Defines = { - "NAZARA_PLATFORM_SDL2" -} - -MODULE.Libraries = { - "NazaraCore", - "NazaraUtility", - "SDL2" -} - -MODULE.Files = { - "../src/Nazara/Platform/SDL2/**.hpp", - "../src/Nazara/Platform/SDL2/**.cpp" -} - -MODULE.OsDefines.Windows = { - "SDL_VIDEO_DRIVER_WINDOWS=1" -} - -MODULE.OsDefines.Posix = { - "SDL_VIDEO_DRIVER_X11=1", - "SDL_VIDEO_DRIVER_WAYLAND=1", -} diff --git a/build/scripts/modules/renderer.lua b/build/scripts/modules/renderer.lua deleted file mode 100644 index af1061f45..000000000 --- a/build/scripts/modules/renderer.lua +++ /dev/null @@ -1,37 +0,0 @@ -MODULE.Name = "Renderer" - -MODULE.ClientOnly = true - -MODULE.Defines = { - "NAZARA_RENDERER_OPENGL" -} - -MODULE.Libraries = { - "NazaraCore", - "NazaraUtility", - "NazaraPlatform" -} - -MODULE.OsFiles.Windows = { - "../src/Nazara/Renderer/Win32/**.hpp", - "../src/Nazara/Renderer/Win32/**.cpp" -} - -MODULE.OsFiles.Posix = { - "../src/Nazara/Renderer/GLX/**.hpp", - "../src/Nazara/Renderer/GLX/**.cpp" -} - -MODULE.OsLibraries.Windows = { - "gdi32", - "opengl32", - "winmm" -} - -MODULE.OsLibraries.Posix = { - "GL", - "X11", - "xcb", - "xcb-ewmh", - "xcb-keysyms" -} diff --git a/build/scripts/modules/utility.lua b/build/scripts/modules/utility.lua deleted file mode 100644 index fc4c989d8..000000000 --- a/build/scripts/modules/utility.lua +++ /dev/null @@ -1,15 +0,0 @@ -MODULE.Name = "Utility" - -MODULE.Libraries = { - "NazaraCore", - "stb_image" -} - -MODULE.OsLibraries.Windows = { - "freetype-s" -} - -MODULE.OsLibraries.Posix = { - "freetype" -} - diff --git a/build/scripts/tools/assimp.lua b/build/scripts/tools/assimp.lua deleted file mode 100644 index 09374bca1..000000000 --- a/build/scripts/tools/assimp.lua +++ /dev/null @@ -1,22 +0,0 @@ -TOOL.Name = "Assimp" - -TOOL.Directory = "../plugins/Assimp" -TOOL.Kind = "Plugin" - -TOOL.Includes = { - "../thirdparty/include", - "../include", - "../plugins/Assimp" -} - -TOOL.Files = { - "../plugins/Assimp/**.hpp", - "../plugins/Assimp/**.inl", - "../plugins/Assimp/**.cpp" -} - -TOOL.Libraries = { - "NazaraCore", - "NazaraUtility", - "assimp" -} diff --git a/build/scripts/tools/ndk.lua b/build/scripts/tools/ndk.lua deleted file mode 100644 index 7cb1f24a5..000000000 --- a/build/scripts/tools/ndk.lua +++ /dev/null @@ -1,34 +0,0 @@ -TOOL.Name = "SDK" - -TOOL.Directory = "../SDK" -TOOL.Kind = "Library" -TOOL.TargetDirectory = "../lib" - -TOOL.Defines = { - "NDK_BUILD" -} - -TOOL.Includes = { - "../SDK/include", - "../SDK/src" -} - -TOOL.Files = { - "../SDK/include/NDK/**.hpp", - "../SDK/include/NDK/**.inl", - "../SDK/src/NDK/**.hpp", - "../SDK/src/NDK/**.inl", - "../SDK/src/NDK/**.cpp" -} - -TOOL.Libraries = function() - local libraries = {} - for k,v in pairs(NazaraBuild.Modules) do - table.insert(libraries, "Nazara" .. v.Name) - end - - -- Keep libraries in the same order to prevent useless premake regeneration - table.sort(libraries) - - return libraries -end \ No newline at end of file diff --git a/build/scripts/tools/ndk_server.lua b/build/scripts/tools/ndk_server.lua deleted file mode 100644 index 2fd17e7f1..000000000 --- a/build/scripts/tools/ndk_server.lua +++ /dev/null @@ -1,56 +0,0 @@ -TOOL.Name = "SDKServer" - -TOOL.Directory = "../SDK" -TOOL.Kind = "Library" -TOOL.TargetDirectory = "../lib" - -TOOL.Defines = { - "NDK_BUILD", - "NDK_SERVER" -} - -TOOL.Includes = { - "../SDK/include", - "../SDK/src" -} - -TOOL.Files = { - "../SDK/include/NDK/**.hpp", - "../SDK/include/NDK/**.inl", - "../SDK/src/NDK/**.hpp", - "../SDK/src/NDK/**.inl", - "../SDK/src/NDK/**.cpp" -} - --- Excludes client-only files -TOOL.FilesExcluded = { - "../SDK/**/CameraComponent.*", - "../SDK/**/Canvas.*", - "../SDK/**/Console.*", - "../SDK/**/DebugComponent.*", - "../SDK/**/DebugSystem.*", - "../SDK/**/GraphicsComponent.*", - "../SDK/**/LightComponent.*", - "../SDK/**/ListenerComponent.*", - "../SDK/**/ListenerSystem.*", - "../SDK/**/Particle*Component.*", - "../SDK/**/ParticleSystem.*", - "../SDK/**/RenderSystem.*", - "../SDK/**/*Layout*.*", - "../SDK/**/*Widget*.*", - "../SDK/**/LuaBinding_Audio.*", - "../SDK/**/LuaBinding_Graphics.*", - "../SDK/**/LuaBinding_Renderer.*", - "../SDK/**/LuaBinding_Platform.*" -} - - -TOOL.Libraries = { - "NazaraCore", - "NazaraLua", - "NazaraNetwork", - "NazaraNoise", - "NazaraPhysics2D", - "NazaraPhysics3D", - "NazaraUtility" -} diff --git a/build/scripts/tools/unittests.lua b/build/scripts/tools/unittests.lua deleted file mode 100644 index adf06a97a..000000000 --- a/build/scripts/tools/unittests.lua +++ /dev/null @@ -1,27 +0,0 @@ -TOOL.Name = "UnitTests" - -TOOL.Category = "Test" -TOOL.Directory = "../tests" -TOOL.EnableConsole = true -TOOL.Kind = "Application" -TOOL.TargetDirectory = TOOL.Directory - -TOOL.Defines = { -} - -TOOL.Includes = { - "../include" -} - -TOOL.Files = { - "../tests/main.cpp", - "../tests/Engine/**.hpp", - "../tests/Engine/**.cpp", - "../tests/SDK/**.hpp", - "../tests/SDK/**.cpp" -} - -TOOL.Libraries = { - "NazaraNetwork", - "NazaraSDK" -} diff --git a/build/scripts/tools/unittests_server.lua b/build/scripts/tools/unittests_server.lua deleted file mode 100644 index b42c62185..000000000 --- a/build/scripts/tools/unittests_server.lua +++ /dev/null @@ -1,38 +0,0 @@ -TOOL.Name = "UnitTestsServer" - -TOOL.Category = "Test" -TOOL.Directory = "../tests" -TOOL.EnableConsole = true -TOOL.Kind = "Application" -TOOL.TargetDirectory = TOOL.Directory - -TOOL.Defines = { - "NDK_SERVER" -} - -TOOL.Includes = { - "../include" -} - -TOOL.Files = { - "../tests/main.cpp", - "../tests/Engine/**.hpp", - "../tests/Engine/**.cpp", - "../tests/SDK/**.hpp", - "../tests/SDK/**.cpp" -} - --- Excludes client-only files -TOOL.FilesExcluded = { - "../tests/Engine/Audio/**", - "../tests/Engine/Graphics/**", - "../tests/Engine/Platform/**", - "../tests/SDK/NDK/Application.cpp", - "../tests/SDK/NDK/Systems/ListenerSystem.cpp", - "../tests/SDK/NDK/Systems/RenderSystem.cpp" -} - -TOOL.Libraries = { - "NazaraNetwork", - "NazaraSDKServer" -} diff --git a/examples/DeferredShading/main.cpp b/examples/DeferredShading/main.cpp new file mode 100644 index 000000000..00f6fdc16 --- /dev/null +++ b/examples/DeferredShading/main.cpp @@ -0,0 +1,1145 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +[layout(std140)] +struct PointLight +{ + color: vec3, + position: vec3, + + constant: f32, + linear: f32, + quadratic: f32, +} + +[layout(std140)] +struct SpotLight +{ + color: vec3, + position: vec3, + direction: vec3, + + constant: f32, + linear: f32, + quadratic: f32, + + innerAngle: f32, + outerAngle: f32, +} +*/ + +struct PointLight +{ + Nz::Color color = Nz::Color::White; + Nz::Vector3f position = Nz::Vector3f::Zero(); + + float radius = 1.f; +}; + +struct SpotLight +{ + Nz::Color color = Nz::Color::White; + Nz::Matrix4f transformMatrix; + Nz::Vector3f position = Nz::Vector3f::Zero(); + Nz::Vector3f direction = Nz::Vector3f::Forward(); + + float radius = 1.f; + + Nz::RadianAnglef innerAngle = Nz::DegreeAnglef(15.f); + Nz::RadianAnglef outerAngle = Nz::DegreeAnglef(20.f); +}; + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Renderer::Config rendererConfig; + std::cout << "Run using Vulkan? (y/n)" << std::endl; + if (std::getchar() == 'y') + rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; + else + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + Nz::Modules nazara(rendererConfig); + + Nz::RenderWindow window; + + Nz::MeshParams meshParams; + meshParams.storage = Nz::DataStorage::Software; + meshParams.center = true; + meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 0.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f)); + meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_Normal_UV); + + std::shared_ptr device = Nz::Graphics::Instance()->GetRenderDevice(); + const Nz::RenderDeviceInfo& deviceInfo = device->GetDeviceInfo(); + + 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__; + } + + std::shared_ptr spaceship = Nz::Mesh::LoadFromFile(resourceDir / "Spaceship/spaceship.obj", meshParams); + if (!spaceship) + { + NazaraError("Failed to load model"); + return __LINE__; + } + + std::shared_ptr gfxMesh = std::make_shared(*spaceship); + + Nz::TextureParams texParams; + texParams.renderDevice = device; + texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; + + // Plane + Nz::MeshParams meshPrimitiveParams; + meshPrimitiveParams.storage = Nz::DataStorage::Software; + + std::shared_ptr planeMesh = std::make_shared(); + planeMesh->CreateStatic(); + planeMesh->BuildSubMesh(Nz::Primitive::Plane(Nz::Vector2f(25.f, 25.f), Nz::Vector2ui(0u), Nz::Matrix4f::Identity(), Nz::Rectf(0.f, 0.f, 10.f, 10.f)), meshPrimitiveParams); + //planeMesh->BuildSubMesh(Nz::Primitive::Cone(1.f, 1.f, 16, Nz::Matrix4f::Rotate(Nz::EulerAnglesf(90.f, 0.f, 0.f))), planeParams); + planeMesh->SetMaterialCount(1); + + std::shared_ptr planeMeshGfx = std::make_shared(*planeMesh); + + // Skybox + meshPrimitiveParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ); + + std::shared_ptr cubeMesh = std::make_shared(); + cubeMesh->CreateStatic(); + cubeMesh->BuildSubMesh(Nz::Primitive::Box(Nz::Vector3f::Unit(), Nz::Vector3ui(0), Nz::Matrix4f::Scale({ 1.f, -1.f, 1.f })), meshPrimitiveParams); + cubeMesh->SetMaterialCount(1); + + std::shared_ptr cubeMeshGfx = std::make_shared(*cubeMesh); + + Nz::RenderPipelineLayoutInfo skyboxPipelineLayoutInfo; + Nz::Graphics::FillViewerPipelineLayout(skyboxPipelineLayoutInfo); + + auto& textureBinding = skyboxPipelineLayoutInfo.bindings.emplace_back(); + textureBinding.setIndex = 1; + textureBinding.bindingIndex = 0; + textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; + textureBinding.type = Nz::ShaderBindingType::Texture; + + std::shared_ptr skyboxPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(skyboxPipelineLayoutInfo)); + + Nz::RenderPipelineInfo skyboxPipelineInfo; + skyboxPipelineInfo.depthBuffer = true; + skyboxPipelineInfo.depthCompare = Nz::RendererComparison::Equal; + skyboxPipelineInfo.faceCulling = true; + skyboxPipelineInfo.cullingSide = Nz::FaceSide::Front; + skyboxPipelineInfo.pipelineLayout = skyboxPipelineLayout; + skyboxPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "skybox.nzsl", {})); + skyboxPipelineInfo.vertexBuffers.push_back({ + 0, + meshPrimitiveParams.vertexDeclaration + }); + + std::shared_ptr skyboxPipeline = device->InstantiateRenderPipeline(std::move(skyboxPipelineInfo)); + + // Skybox + std::shared_ptr skyboxTexture; + { + Nz::Image skyboxImage(Nz::ImageType::Cubemap, Nz::PixelFormat::RGBA8, 2048, 2048); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::PositiveX, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_right1.png"); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::PositiveY, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_top3.png"); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::PositiveZ, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_front5.png"); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::NegativeX, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_left2.png"); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::NegativeY, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_bottom4.png"); + skyboxImage.LoadFaceFromFile(Nz::CubemapFace::NegativeZ, resourceDir / "purple_nebula_skybox/purple_nebula_skybox_back6.png"); + + skyboxTexture = Nz::Texture::CreateFromImage(skyboxImage, texParams); + } + + + // Cone mesh + std::shared_ptr coneMesh = std::make_shared(); + coneMesh->CreateStatic(); + coneMesh->BuildSubMesh(Nz::Primitive::Cone(1.f, 1.f, 16, Nz::Matrix4f::Rotate(Nz::EulerAnglesf(90.f, 0.f, 0.f))), meshPrimitiveParams); + coneMesh->SetMaterialCount(1); + + std::shared_ptr coneMeshGfx = std::make_shared(*coneMesh); + + auto customSettings = Nz::BasicMaterial::GetSettings()->GetBuilderData(); + customSettings.shaders[UnderlyingCast(Nz::ShaderStageType::Fragment)] = std::make_shared(Nz::ShaderStageType::Fragment, Nz::ShaderLang::Parse(resourceDir / "deferred_frag.nzsl")); + customSettings.shaders[UnderlyingCast(Nz::ShaderStageType::Vertex)] = std::make_shared(Nz::ShaderStageType::Vertex, Nz::ShaderLang::Parse(resourceDir / "deferred_vert.nzsl")); + + auto customMatSettings = std::make_shared(std::move(customSettings)); + + std::shared_ptr spaceshipMat = std::make_shared(customMatSettings); + spaceshipMat->EnableDepthBuffer(true); + { + Nz::BasicMaterial basicMat(*spaceshipMat); + basicMat.EnableAlphaTest(false); + basicMat.SetAlphaMap(Nz::Texture::LoadFromFile(resourceDir / "alphatile.png", texParams)); + basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams)); + } + + std::shared_ptr planeMat = std::make_shared(customMatSettings); + planeMat->EnableDepthBuffer(true); + { + Nz::BasicMaterial basicMat(*planeMat); + basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "dev_grey.png", texParams)); + + Nz::TextureSamplerInfo planeSampler; + planeSampler.anisotropyLevel = 16; + planeSampler.wrapModeU = Nz::SamplerWrap::Repeat; + planeSampler.wrapModeV = Nz::SamplerWrap::Repeat; + basicMat.SetDiffuseSampler(planeSampler); + } + + Nz::Model spaceshipModel(std::move(gfxMesh)); + for (std::size_t i = 0; i < spaceshipModel.GetSubMeshCount(); ++i) + spaceshipModel.SetMaterial(i, spaceshipMat); + + Nz::Model planeModel(std::move(planeMeshGfx)); + for (std::size_t i = 0; i < planeModel.GetSubMeshCount(); ++i) + planeModel.SetMaterial(i, planeMat); + + Nz::PredefinedInstanceData instanceUboOffsets = Nz::PredefinedInstanceData::GetOffsets(); + Nz::PredefinedViewerData viewerUboOffsets = Nz::PredefinedViewerData::GetOffsets(); + + Nz::Vector2ui windowSize = window.GetSize(); + + Nz::ViewerInstance viewerInstance; + viewerInstance.UpdateTargetSize(Nz::Vector2f(windowSize)); + viewerInstance.UpdateProjViewMatrices(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f), Nz::Matrix4f::Translate(Nz::Vector3f::Up() * 1)); + + Nz::WorldInstance modelInstance1; + modelInstance1.UpdateWorldMatrix(Nz::Matrix4f::Translate(Nz::Vector3f::Left() + Nz::Vector3f::Up())); + + Nz::WorldInstance modelInstance2; + modelInstance2.UpdateWorldMatrix(Nz::Matrix4f::Translate(Nz::Vector3f::Right() + Nz::Vector3f::Up())); + + Nz::WorldInstance planeInstance; + + Nz::RenderWindowImpl* windowImpl = window.GetImpl(); + std::shared_ptr commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); + + + Nz::RenderPipelineLayoutInfo lightingPipelineLayoutInfo; + Nz::Graphics::FillViewerPipelineLayout(lightingPipelineLayoutInfo); + + for (unsigned int i = 0; i < 3; ++i) + { + lightingPipelineLayoutInfo.bindings.push_back({ + 1, + i, + Nz::ShaderBindingType::Texture, + Nz::ShaderStageType::Fragment, + }); + } + + lightingPipelineLayoutInfo.bindings.push_back({ + 2, + 0, + Nz::ShaderBindingType::UniformBuffer, + Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, + }); + + /*Nz::FieldOffsets pointLightOffsets(Nz::StructLayout::Std140); + std::size_t colorOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float3); + std::size_t positionOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float3); + std::size_t constantOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); + std::size_t linearOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); + std::size_t quadraticOffset = pointLightOffsets.AddField(Nz::StructFieldType::Float1); + + std::size_t alignedPointLightSize = Nz::Align(pointLightOffsets.GetSize(), static_cast(deviceInfo.limits.minUniformBufferOffsetAlignment));*/ + + /* + [layout(std140)] + struct SpotLight + { + color: vec3, + position: vec3, + direction: vec3, + + constant: f32, + linear: f32, + quadratic: f32, + + innerAngle: f32, + outerAngle: f32, + } + */ + + Nz::FieldOffsets spotLightOffsets(Nz::StructLayout::Std140); + std::size_t transformMatrixOffset = spotLightOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true); + std::size_t colorOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); + std::size_t positionOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); + std::size_t directionOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float3); + std::size_t radiusOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); + std::size_t invRadiusOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); + std::size_t innerAngleOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); + std::size_t outerAngleOffset = spotLightOffsets.AddField(Nz::StructFieldType::Float1); + + std::size_t alignedSpotLightSize = Nz::Align(spotLightOffsets.GetAlignedSize(), static_cast(deviceInfo.limits.minUniformBufferOffsetAlignment)); + + constexpr std::size_t MaxPointLight = 2000; + + std::shared_ptr lightUbo = device->InstantiateBuffer(Nz::BufferType::Uniform); + if (!lightUbo->Initialize(MaxPointLight * alignedSpotLightSize, Nz::BufferUsage::DeviceLocal | Nz::BufferUsage::Dynamic)) + return __LINE__; + + std::vector spotLights; + /*auto& firstSpot = spotLights.emplace_back(); + firstSpot.position = Nz::Vector3f::Right() + Nz::Vector3f::Forward(); + firstSpot.direction = Nz::Vector3f::Up();*/ + + std::random_device rng; + std::mt19937 randomEngine(rng()); + std::uniform_int_distribution colorDis(0, 255); + std::uniform_real_distribution heightDis(0.15f, 1.f); + std::uniform_real_distribution posDis(-10.f, 10.f); + std::uniform_real_distribution dirDis(-1.f, 1.f); + std::uniform_real_distribution dirYDis(-0.33f, 0.f); + std::uniform_real_distribution radiusDis(1.f, 5.f); + + for (std::size_t i = 0; i < 1000; ++i) + { + auto& light = spotLights.emplace_back(); + light.color = Nz::Color(colorDis(randomEngine), colorDis(randomEngine), colorDis(randomEngine)); + light.position = Nz::Vector3f(posDis(randomEngine), heightDis(randomEngine), posDis(randomEngine)); + light.direction = Nz::Vector3f(dirDis(randomEngine), dirYDis(randomEngine), dirDis(randomEngine)).GetNormal(); + light.radius = radiusDis(randomEngine); + } + + + const std::shared_ptr& fullscreenVertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_UV); + + + unsigned int offscreenWidth = window.GetSize().x; + unsigned int offscreenHeight = window.GetSize().y; + + // Bloom data + + Nz::RenderPipelineLayoutInfo bloomPipelineLayoutInfo; + Nz::Graphics::FillViewerPipelineLayout(bloomPipelineLayoutInfo); + + bloomPipelineLayoutInfo.bindings.push_back({ + 1, 0, + Nz::ShaderBindingType::Texture, + Nz::ShaderStageType::Fragment, + }); + + Nz::RenderPipelineInfo bloomPipelineInfo; + bloomPipelineInfo.primitiveMode = Nz::PrimitiveMode::TriangleList; + bloomPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(bloomPipelineLayoutInfo); + bloomPipelineInfo.vertexBuffers.push_back({ + 0, + fullscreenVertexDeclaration + }); + + bloomPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_bright.nzsl", {})); + + std::shared_ptr bloomBrightShaderBinding = bloomPipelineInfo.pipelineLayout->AllocateShaderBinding(1); + std::shared_ptr gaussianBlurShaderBinding = bloomPipelineInfo.pipelineLayout->AllocateShaderBinding(1); + + std::shared_ptr bloomBrightPipeline = device->InstantiateRenderPipeline(bloomPipelineInfo); + + bloomPipelineInfo.shaderModules.clear(); + bloomPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gaussian_blur.nzsl", {})); + + + Nz::RenderPipelineLayoutInfo bloomBlendPipelineLayoutInfo; + Nz::Graphics::FillViewerPipelineLayout(bloomBlendPipelineLayoutInfo); + + bloomBlendPipelineLayoutInfo.bindings.push_back({ + 1, 0, + Nz::ShaderBindingType::Texture, + Nz::ShaderStageType::Fragment, + }); + + bloomBlendPipelineLayoutInfo.bindings.push_back({ + 1, 1, + Nz::ShaderBindingType::Texture, + Nz::ShaderStageType::Fragment, + }); + + + std::shared_ptr gaussianBlurPipeline = device->InstantiateRenderPipeline(bloomPipelineInfo); + + Nz::RenderPipelineInfo bloomBlendPipelineInfo; + bloomBlendPipelineInfo.primitiveMode = Nz::PrimitiveMode::TriangleList; + bloomBlendPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(bloomBlendPipelineLayoutInfo); + bloomBlendPipelineInfo.vertexBuffers.push_back({ + 0, + fullscreenVertexDeclaration + }); + + bloomBlendPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "bloom_final.nzsl", {})); + + std::shared_ptr bloomBlendPipeline = device->InstantiateRenderPipeline(bloomBlendPipelineInfo); + + std::shared_ptr bloomBlendShaderBinding = bloomBlendPipelineInfo.pipelineLayout->AllocateShaderBinding(1); + + // Fullscreen data + + Nz::RenderPipelineLayoutInfo fullscreenPipelineLayoutInfo; + + fullscreenPipelineLayoutInfo.bindings.push_back({ + 0, 0, + Nz::ShaderBindingType::Texture, + Nz::ShaderStageType::Fragment, + }); + + Nz::RenderPipelineInfo fullscreenPipelineInfo; + fullscreenPipelineInfo.primitiveMode = Nz::PrimitiveMode::TriangleList; + fullscreenPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(fullscreenPipelineLayoutInfo); + fullscreenPipelineInfo.vertexBuffers.push_back({ + 0, + fullscreenVertexDeclaration + }); + + fullscreenPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "gamma.nzsl", {})); + + + const std::shared_ptr& lightingVertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_UV); + + std::shared_ptr fullscreenPipeline = device->InstantiateRenderPipeline(fullscreenPipelineInfo); + + Nz::RenderPipelineInfo lightingPipelineInfo; + lightingPipelineInfo.blending = true; + lightingPipelineInfo.blend.dstColor = Nz::BlendFunc::One; + lightingPipelineInfo.blend.srcColor = Nz::BlendFunc::One; + lightingPipelineInfo.primitiveMode = Nz::PrimitiveMode::TriangleList; + lightingPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(lightingPipelineLayoutInfo); + lightingPipelineInfo.vertexBuffers.push_back({ + 0, + meshPrimitiveParams.vertexDeclaration + }); + lightingPipelineInfo.depthBuffer = false; + lightingPipelineInfo.faceCulling = true; + lightingPipelineInfo.cullingSide = Nz::FaceSide::Front; + lightingPipelineInfo.stencilTest = true; + lightingPipelineInfo.stencilBack.compare = Nz::RendererComparison::NotEqual; + lightingPipelineInfo.stencilBack.fail = Nz::StencilOperation::Zero; + lightingPipelineInfo.stencilBack.depthFail = Nz::StencilOperation::Zero; + lightingPipelineInfo.stencilBack.pass = Nz::StencilOperation::Zero; + + lightingPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", {})); + + std::shared_ptr lightingPipeline = device->InstantiateRenderPipeline(lightingPipelineInfo); + + Nz::RenderPipelineInfo stencilPipelineInfo; + stencilPipelineInfo.primitiveMode = Nz::PrimitiveMode::TriangleList; + stencilPipelineInfo.pipelineLayout = device->InstantiateRenderPipelineLayout(lightingPipelineLayoutInfo); + stencilPipelineInfo.vertexBuffers.push_back({ + 0, + meshPrimitiveParams.vertexDeclaration + }); + + stencilPipelineInfo.colorWrite = false; + stencilPipelineInfo.depthBuffer = true; + stencilPipelineInfo.depthWrite = false; + stencilPipelineInfo.faceCulling = false; + stencilPipelineInfo.stencilTest = true; + stencilPipelineInfo.stencilFront.compare = Nz::RendererComparison::Always; + stencilPipelineInfo.stencilFront.depthFail = Nz::StencilOperation::Invert; + stencilPipelineInfo.stencilBack.compare = Nz::RendererComparison::Always; + stencilPipelineInfo.stencilBack.depthFail = Nz::StencilOperation::Invert; + + stencilPipelineInfo.shaderModules.push_back(device->InstantiateShaderModule(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, resourceDir / "lighting.nzsl", {})); + + std::shared_ptr stencilPipeline = device->InstantiateRenderPipeline(stencilPipelineInfo); + + + std::vector> lightingShaderBindings; + + std::array vertexData = { + { + { + Nz::Vector3f(-1.f, 1.f, 0.0f), + Nz::Vector2f(0.0f, 1.0f), + }, + { + Nz::Vector3f(-1.f, -3.f, 0.0f), + Nz::Vector2f(0.0f, -1.0f), + }, + { + Nz::Vector3f(3.f, 1.f, 0.0f), + Nz::Vector2f(2.0f, 1.0f), + } + } + }; + + /*std::array vertexData = { + { + { + Nz::Vector3f(-1.f, -1.f, 0.0f), + Nz::Vector2f(0.0f, 0.0f), + }, + { + Nz::Vector3f(1.f, -1.f, 0.0f), + Nz::Vector2f(1.0f, 0.0f), + }, + { + Nz::Vector3f(-1.f, 1.f, 0.0f), + Nz::Vector2f(0.0f, 1.0f), + }, + { + Nz::Vector3f(1.f, 1.f, 0.0f), + Nz::Vector2f(1.0f, 1.0f), + }, + } + };*/ + + std::shared_ptr fullscreenVertexBuffer = device->InstantiateBuffer(Nz::BufferType::Vertex); + if (!fullscreenVertexBuffer->Initialize(fullscreenVertexDeclaration->GetStride() * vertexData.size(), Nz::BufferUsage::DeviceLocal)) + return __LINE__; + + if (!fullscreenVertexBuffer->Fill(vertexData.data(), 0, fullscreenVertexBuffer->GetSize())) + return __LINE__; + + std::shared_ptr bloomSkipBlit = fullscreenPipelineInfo.pipelineLayout->AllocateShaderBinding(0); + std::shared_ptr finalBlitBinding = fullscreenPipelineInfo.pipelineLayout->AllocateShaderBinding(0); + + bool lightUpdate = true; + bool matUpdate = false; + + std::shared_ptr textureSampler = device->InstantiateTextureSampler({}); + + std::shared_ptr skyboxShaderBinding = skyboxPipelineLayout->AllocateShaderBinding(1); + skyboxShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + skyboxTexture.get(), + textureSampler.get() + } + } + }); + + std::shared_ptr gbufferShaderBinding = lightingPipelineInfo.pipelineLayout->AllocateShaderBinding(1); + + bool bloomEnabled = true; + bool forwardEnabled = true; + bool lightAnimation = true; + + std::size_t colorTexture; + std::size_t normalTexture; + std::size_t positionTexture; + std::size_t depthBuffer; + std::size_t backbuffer; + std::size_t bloomTextureA; + std::size_t bloomTextureB; + std::size_t lightOutput; + + Nz::BakedFrameGraph bakedGraph = [&] + { + Nz::PixelFormat depthStencilFormat = Nz::PixelFormat::Undefined; + for (Nz::PixelFormat candidate : { Nz::PixelFormat::Depth24Stencil8, Nz::PixelFormat::Depth32FStencil8, Nz::PixelFormat::Depth16Stencil8 }) + { + if (device->IsTextureFormatSupported(candidate, Nz::TextureUsage::DepthStencilAttachment)) + { + depthStencilFormat = candidate; + break; + } + } + + if (depthStencilFormat == Nz::PixelFormat::Undefined) + { + std::cerr << "no depth-stencil format found" << std::endl; + std::exit(__LINE__); + } + + Nz::FrameGraph graph; + + colorTexture = graph.AddAttachment({ + "Color", + Nz::PixelFormat::RGBA8 + }); + + normalTexture = graph.AddAttachment({ + "Normal", + Nz::PixelFormat::RGBA8 + }); + + positionTexture = graph.AddAttachment({ + "Position", + Nz::PixelFormat::RGBA32F + }); + + depthBuffer = graph.AddAttachment({ + "Depth buffer", + depthStencilFormat + }); + + lightOutput = graph.AddAttachment({ + "Light output", + Nz::PixelFormat::RGBA8 + }); + + backbuffer = graph.AddAttachment({ + "Backbuffer", + Nz::PixelFormat::RGBA8 + }); + + bloomTextureA = graph.AddAttachment({ + "Bloom texture A", + Nz::PixelFormat::RGBA8, + 10'000, + 10'000 + }); + + bloomTextureB = graph.AddAttachment({ + "Bloom texture B", + Nz::PixelFormat::RGBA8, + 10'000, + 10'000 + }); + + Nz::FramePass& gbufferPass = graph.AddPass("GBuffer"); + + std::size_t geometryAlbedo = gbufferPass.AddOutput(colorTexture); + gbufferPass.SetClearColor(geometryAlbedo, Nz::Color::Black); + + std::size_t geometryNormal = gbufferPass.AddOutput(normalTexture); + gbufferPass.SetClearColor(geometryNormal, Nz::Color::Black); + + std::size_t positionAttachment = gbufferPass.AddOutput(positionTexture); + gbufferPass.SetClearColor(positionAttachment, Nz::Color::Black); + + gbufferPass.SetDepthStencilClear(1.f, 0); + + gbufferPass.SetDepthStencilOutput(depthBuffer); + + gbufferPass.SetExecutionCallback([&] + { + return (matUpdate) ? Nz::FramePassExecution::UpdateAndExecute : Nz::FramePassExecution::Execute; + }); + + gbufferPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + + spaceshipModel.Draw(builder, modelInstance1); + spaceshipModel.Draw(builder, modelInstance2); + + // Plane + planeModel.Draw(builder, planeInstance); + }); + + Nz::FramePass& lightingPass = graph.AddPass("Lighting pass"); + lightingPass.SetExecutionCallback([&] + { + return (lightUpdate) ? Nz::FramePassExecution::UpdateAndExecute : Nz::FramePassExecution::Execute; + }); + + lightingPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + + //builder.BindVertexBuffer(0, vertexBuffer.get()); + builder.BindIndexBuffer(coneMeshGfx->GetIndexBuffer(0).get()); + builder.BindVertexBuffer(0, coneMeshGfx->GetVertexBuffer(0).get()); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + builder.BindShaderBinding(1, *gbufferShaderBinding); + + for (std::size_t i = 0; i < spotLights.size(); ++i) + { + builder.BindShaderBinding(2, *lightingShaderBindings[i]); + + builder.BindPipeline(*stencilPipeline); + builder.DrawIndexed(coneMeshGfx->GetIndexCount(0)); + + builder.BindPipeline(*lightingPipeline); + builder.DrawIndexed(coneMeshGfx->GetIndexCount(0)); + } + }); + + lightingPass.AddInput(colorTexture); + lightingPass.AddInput(normalTexture); + lightingPass.AddInput(positionTexture); + + lightingPass.SetClearColor(lightingPass.AddOutput(lightOutput), Nz::Color::Black); + lightingPass.SetDepthStencilInput(depthBuffer); + lightingPass.SetDepthStencilOutput(depthBuffer); + + Nz::FramePass& forwardPass = graph.AddPass("Forward pass"); + forwardPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + builder.BindShaderBinding(1, *skyboxShaderBinding); + + builder.BindIndexBuffer(cubeMeshGfx->GetIndexBuffer(0).get()); + builder.BindVertexBuffer(0, cubeMeshGfx->GetVertexBuffer(0).get()); + builder.BindPipeline(*skyboxPipeline); + + builder.DrawIndexed(static_cast(cubeMeshGfx->GetIndexCount(0))); + }); + forwardPass.SetExecutionCallback([&] + { + return (forwardEnabled) ? Nz::FramePassExecution::Execute : Nz::FramePassExecution::Skip; + }); + + forwardPass.AddInput(lightOutput); + forwardPass.AddOutput(lightOutput); + forwardPass.SetDepthStencilInput(depthBuffer); + forwardPass.SetDepthStencilOutput(depthBuffer); + + Nz::FramePass& bloomBrightPass = graph.AddPass("Bloom pass - extract bright pixels"); + bloomBrightPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth) / 10, int(offscreenHeight) / 10 }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth) / 10, int(offscreenHeight) / 10 }); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + builder.BindShaderBinding(1, *bloomBrightShaderBinding); + + builder.BindPipeline(*bloomBrightPipeline); + builder.BindVertexBuffer(0, fullscreenVertexBuffer.get()); + + builder.Draw(3); + }); + bloomBrightPass.SetExecutionCallback([&] + { + return (bloomEnabled) ? Nz::FramePassExecution::Execute : Nz::FramePassExecution::Skip; + }); + + bloomBrightPass.AddInput(lightOutput); + bloomBrightPass.AddOutput(bloomTextureA); + + Nz::FramePass& bloomBlurPass = graph.AddPass("Bloom pass - gaussian blur"); + bloomBlurPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth) / 10, int(offscreenHeight) / 10 }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth) / 10, int(offscreenHeight) / 10 }); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + builder.BindShaderBinding(1, *gaussianBlurShaderBinding); + builder.BindPipeline(*gaussianBlurPipeline); + builder.BindVertexBuffer(0, fullscreenVertexBuffer.get()); + + builder.Draw(3); + }); + bloomBlurPass.SetExecutionCallback([&] + { + return (bloomEnabled) ? Nz::FramePassExecution::Execute : Nz::FramePassExecution::Skip; + }); + + bloomBlurPass.AddInput(bloomTextureA); + bloomBlurPass.AddOutput(bloomTextureB); + + Nz::FramePass& bloomBlendPass = graph.AddPass("Bloom pass - blend"); + bloomBlendPass.SetCommandCallback([&](Nz::CommandBufferBuilder& builder) + { + builder.SetScissor(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(offscreenWidth), int(offscreenHeight) }); + + builder.BindShaderBinding(0, viewerInstance.GetShaderBinding()); + builder.BindShaderBinding(1, *bloomBlendShaderBinding); + builder.BindPipeline(*bloomBlendPipeline); + builder.BindVertexBuffer(0, fullscreenVertexBuffer.get()); + + builder.Draw(3); + }); + bloomBlendPass.SetExecutionCallback([&] + { + return (bloomEnabled) ? Nz::FramePassExecution::Execute : Nz::FramePassExecution::Skip; + }); + + bloomBlendPass.AddInput(lightOutput); + bloomBlendPass.AddInput(bloomTextureB); + bloomBlendPass.AddOutput(backbuffer); + + graph.SetBackbufferOutput(backbuffer); + + return graph.Bake(); + }(); + + bakedGraph.Resize(offscreenWidth, offscreenHeight); + + gbufferShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(colorTexture).get(), + textureSampler.get() + } + }, + { + 1, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(normalTexture).get(), + textureSampler.get() + } + }, + { + 2, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(positionTexture).get(), + textureSampler.get() + } + } + }); + + + for (std::size_t i = 0; i < MaxPointLight; ++i) + { + std::shared_ptr lightingShaderBinding = lightingPipelineInfo.pipelineLayout->AllocateShaderBinding(2); + lightingShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::UniformBufferBinding { + lightUbo.get(), + i * alignedSpotLightSize, spotLightOffsets.GetAlignedSize() + } + } + }); + + lightingShaderBindings.emplace_back(std::move(lightingShaderBinding)); + } + + bloomBrightShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(lightOutput).get(), + textureSampler.get() + } + } + }); + + gaussianBlurShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(bloomTextureA).get(), + textureSampler.get() + } + } + }); + + bloomBlendShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(lightOutput).get(), + textureSampler.get() + } + }, + { + 1, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(bloomTextureB).get(), + textureSampler.get() + } + } + }); + + bloomSkipBlit->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(lightOutput).get(), + textureSampler.get() + } + } + }); + + finalBlitBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + bakedGraph.GetAttachmentTexture(backbuffer).get(), + textureSampler.get() + } + } + }); + + + Nz::CommandBufferPtr drawCommandBuffer; + auto RebuildCommandBuffer = [&] + { + Nz::Vector2ui windowSize = window.GetSize(); + + drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) + { + Nz::Recti windowRenderRect(0, 0, window.GetSize().x, window.GetSize().y); + + builder.TextureBarrier(Nz::PipelineStage::ColorOutput, Nz::PipelineStage::FragmentShader, Nz::MemoryAccess::ColorWrite, Nz::MemoryAccess::ShaderRead, Nz::TextureLayout::ColorOutput, Nz::TextureLayout::ColorInput, *bakedGraph.GetAttachmentTexture(backbuffer)); + + builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); + { + builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), windowRenderRect); + { + builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + + builder.BindShaderBinding(0, *finalBlitBinding); + builder.BindPipeline(*fullscreenPipeline); + builder.BindVertexBuffer(0, fullscreenVertexBuffer.get()); + builder.Draw(3); + } + builder.EndRenderPass(); + } + builder.EndDebugRegion(); + }); + }; + RebuildCommandBuffer(); + + + Nz::Vector3f viewerPos = Nz::Vector3f::Backward() * 10.f + Nz::Vector3f::Up() * 3.f; + + Nz::EulerAnglesf camAngles(-30.f, 0.f, 0.f); + Nz::Quaternionf camQuat(camAngles); + + window.EnableEventPolling(true); + + Nz::Clock updateClock; + Nz::Clock secondClock; + unsigned int fps = 0; + + std::size_t totalFrameCount = 0; + + Nz::Mouse::SetRelativeMouseMode(true); + + float elapsedTime = 0.f; + Nz::UInt64 time = Nz::GetElapsedMicroseconds(); + + auto ComputeLightAnimationSpeed = [](const Nz::Vector3f& position) + { + return position.GetLength() / 15.f; + }; + + auto AnimateLightPosition = [](const Nz::Vector3f& position, float rotationSpeed, float elapsedTime) + { + rotationSpeed *= 45.f; + + return Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, elapsedTime * rotationSpeed, 0.f)) * position; + }; + + auto AnimateLightDirection = [](const Nz::Vector3f& direction, float rotationSpeed, float elapsedTime) + { + rotationSpeed *= 90.f; + + return Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, elapsedTime * rotationSpeed, 0.f)) * direction; + }; + + while (window.IsOpen()) + { + Nz::UInt64 now = Nz::GetElapsedMicroseconds(); + if (lightAnimation) + elapsedTime += (now - time) / 1'000'000.f; + time = now; + + Nz::WindowEvent event; + while (window.PollEvent(&event)) + { + switch (event.type) + { + case Nz::WindowEventType::Quit: + window.Close(); + break; + + case Nz::WindowEventType::MouseMoved: // La souris a bougé + { + // Gestion de la caméra free-fly (Rotation) + float sensitivity = 0.3f; // Sensibilité de la souris + + // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris + camAngles.yaw = camAngles.yaw - event.mouseMove.deltaX*sensitivity; + camAngles.yaw.Normalize(); + + // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles + camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f); + + camQuat = camAngles; + break; + } + + case Nz::WindowEventType::KeyPressed: + { + if (event.key.scancode == Nz::Keyboard::Scancode::Space) + { + float rotationSpeed = ComputeLightAnimationSpeed(viewerPos); + + auto& whiteLight = spotLights.emplace_back(); + whiteLight.radius = 5.f; + whiteLight.position = AnimateLightPosition(viewerPos, rotationSpeed, -elapsedTime); + whiteLight.direction = AnimateLightDirection(camQuat * Nz::Vector3f::Forward(), rotationSpeed, -elapsedTime); + + lightUpdate = true; + } + else if (event.key.virtualKey == Nz::Keyboard::VKey::F) + forwardEnabled = !forwardEnabled; + else if (event.key.virtualKey == Nz::Keyboard::VKey::A) + lightAnimation = !lightAnimation; + else if (event.key.virtualKey == Nz::Keyboard::VKey::B) + bloomEnabled = !bloomEnabled; + else if (event.key.virtualKey == Nz::Keyboard::VKey::E) + modelInstance1.UpdateWorldMatrix(Nz::Matrix4f::Transform(viewerPos, camQuat)); + + break; + } + + case Nz::WindowEventType::Resized: + { + Nz::Vector2ui windowSize = window.GetSize(); + viewerInstance.UpdateProjectionMatrix(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f)); + break; + } + + default: + break; + } + } + + if (updateClock.GetMilliseconds() > 1000 / 60) + { + float cameraSpeed = 2.f * updateClock.GetSeconds(); + updateClock.Restart(); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) + viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed; + + // Si la flèche du bas ou la touche S est pressée, on recule + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) + viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) + viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) + viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed; + + // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) + viewerPos += Nz::Vector3f::Up() * cameraSpeed; + + // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) + viewerPos += Nz::Vector3f::Down() * cameraSpeed; + + viewerInstance.UpdateViewMatrix(Nz::Matrix4f::ViewMatrix(viewerPos, camQuat)); + } + + Nz::RenderFrame frame = windowImpl->Acquire(); + if (!frame) + continue; + + if (frame.IsFramebufferInvalidated()) + { + frame.PushForRelease(std::move(drawCommandBuffer)); + RebuildCommandBuffer(); + } + + Nz::UploadPool& uploadPool = frame.GetUploadPool(); + + frame.Execute([&](Nz::CommandBufferBuilder& builder) + { + builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); + { + builder.PreTransferBarrier(); + + modelInstance1.UpdateBuffers(uploadPool, builder); + modelInstance2.UpdateBuffers(uploadPool, builder); + planeInstance.UpdateBuffers(uploadPool, builder); + + viewerInstance.UpdateBuffers(uploadPool, builder); + + if (!spotLights.empty() && (lightUpdate || lightAnimation)) + { + auto& lightDataAllocation = uploadPool.Allocate(alignedSpotLightSize * spotLights.size()); + Nz::UInt8* lightDataPtr = static_cast(lightDataAllocation.mappedPtr); + + for (const SpotLight& spotLight : spotLights) + { + float rotationSpeed = ComputeLightAnimationSpeed(spotLight.position); + + Nz::Vector3f position = AnimateLightPosition(spotLight.position, rotationSpeed, elapsedTime); + Nz::Vector3f direction = AnimateLightDirection(spotLight.direction, rotationSpeed, elapsedTime); + + Nz::AccessByOffset(lightDataPtr, colorOffset) = Nz::Vector3f(spotLight.color.r / 255.f, spotLight.color.g / 255.f, spotLight.color.b / 255.f); + Nz::AccessByOffset(lightDataPtr, positionOffset) = position; + Nz::AccessByOffset(lightDataPtr, directionOffset) = direction; + Nz::AccessByOffset(lightDataPtr, radiusOffset) = spotLight.radius; + Nz::AccessByOffset(lightDataPtr, invRadiusOffset) = 1.f / spotLight.radius; + Nz::AccessByOffset(lightDataPtr, innerAngleOffset) = spotLight.innerAngle.GetCos(); + Nz::AccessByOffset(lightDataPtr, outerAngleOffset) = spotLight.outerAngle.GetCos(); + + float baseRadius = spotLight.radius * spotLight.outerAngle.GetTan() * 1.1f; + Nz::Matrix4f transformMatrix = Nz::Matrix4f::Transform(position, Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), direction), Nz::Vector3f(baseRadius, baseRadius, spotLight.radius)); + Nz::AccessByOffset(lightDataPtr, transformMatrixOffset) = transformMatrix; + + lightDataPtr += alignedSpotLightSize; + } + + builder.CopyBuffer(lightDataAllocation, lightUbo.get()); + } + + matUpdate = spaceshipMat->Update(frame, builder) || matUpdate; + matUpdate = planeMat->Update(frame, builder) || matUpdate; + + builder.PostTransferBarrier(); + } + builder.EndDebugRegion(); + }, Nz::QueueType::Transfer); + + bakedGraph.Execute(frame); + frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); + + frame.Present(); + + window.Display(); + + matUpdate = false; + lightUpdate = false; + + // On incrémente le compteur de FPS improvisé + fps++; + totalFrameCount++; + + if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes + { + // Et on insère ces données dans le titre de la fenêtre + window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS"); + + /* + Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, + via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res". + Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier), + cela fonctionnera aussi comme ceci : "Chaîne de caractères". + */ + + // Et on réinitialise le compteur de FPS + fps = 0; + + // Et on relance l'horloge pour refaire ça dans une seconde + secondClock.Restart(); + } + } + + return EXIT_SUCCESS; +} diff --git a/examples/DeferredShading/xmake.lua b/examples/DeferredShading/xmake.lua new file mode 100644 index 000000000..5a2d9461b --- /dev/null +++ b/examples/DeferredShading/xmake.lua @@ -0,0 +1,5 @@ +target("DeferredShading") + set_group("Examples") + set_kind("binary") + add_deps("NazaraGraphics") + add_files("main.cpp") diff --git a/examples/DopplerEffect/build.lua b/examples/DopplerEffect/build.lua deleted file mode 100644 index 837f62af4..000000000 --- a/examples/DopplerEffect/build.lua +++ /dev/null @@ -1,14 +0,0 @@ -EXAMPLE.Name = "DopplerEffect" - -EXAMPLE.EnableConsole = true - -EXAMPLE.Files = { - "main.cpp" -} - -EXAMPLE.Libraries = { - "NazaraAudio", - "NazaraCore", - "NazaraPlatform", - "NazaraUtility" -} diff --git a/examples/DopplerEffect/main.cpp b/examples/DopplerEffect/main.cpp index 54a1169d0..8dfe7a4de 100644 --- a/examples/DopplerEffect/main.cpp +++ b/examples/DopplerEffect/main.cpp @@ -10,25 +10,24 @@ #include #include -#include // Thread::Sleep +#include #include #include #include +#include #include +#include int main() { - // NzKeyboard nécessite l'initialisation du module Utilitaire - Nz::Initializer audio; - if (!audio) - { - std::cout << "Failed to initialize audio module" << std::endl; - std::getchar(); - return 1; - } + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Modules audio; Nz::Sound sound; - if (!sound.LoadFromFile("resources/siren.wav")) + if (!sound.LoadFromFile(resourceDir / "siren.wav")) { std::cout << "Failed to load sound" << std::endl; std::getchar(); @@ -55,13 +54,13 @@ int main() // La boucle du programme (Pour déplacer le son) Nz::Clock clock; - while (sound.GetStatus() == Nz::SoundStatus_Playing) + while (sound.GetStatus() == Nz::SoundStatus::Playing) { // Comme le son se joue dans un thread séparé, on peut mettre en pause le principal régulièrement int sleepTime = int(1000/60 - clock.GetMilliseconds()); // 60 FPS if (sleepTime > 0) - Nz::Thread::Sleep(sleepTime); + std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); // On bouge la source du son en fonction du temps depuis chaque mise à jour Nz::Vector3f pos = sound.GetPosition() + sound.GetVelocity()*clock.GetSeconds(); diff --git a/examples/DopplerEffect/xmake.lua b/examples/DopplerEffect/xmake.lua new file mode 100644 index 000000000..42fd66ae2 --- /dev/null +++ b/examples/DopplerEffect/xmake.lua @@ -0,0 +1,5 @@ +target("DopplerEffect") + set_group("Examples") + set_kind("binary") + add_deps("NazaraAudio", "NazaraPlatform") + add_files("main.cpp") \ No newline at end of file diff --git a/examples/FirstScene/build.lua b/examples/FirstScene/build_disabled.lua similarity index 100% rename from examples/FirstScene/build.lua rename to examples/FirstScene/build_disabled.lua diff --git a/examples/FirstScene/main.cpp b/examples/FirstScene/main.cpp index 25a96ceca..b5dcac3c9 100644 --- a/examples/FirstScene/main.cpp +++ b/examples/FirstScene/main.cpp @@ -13,18 +13,16 @@ */ #include // Horloges -#include // Module de scripting #include // Module graphique #include // Module de rendu #include // Module utilitaire #include // Module utilitaire -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include // Petite fonction permettant de rendre le déplacement de la caméra moins ridige @@ -264,10 +262,6 @@ int main() application.EnableConsole(true); application.EnableFPSCounter(true); - Ndk::Application::ConsoleOverlay& consoleOverlay = application.GetConsoleOverlay(); - consoleOverlay.lua.PushGlobal("Spaceship", spaceship->CreateHandle()); - consoleOverlay.lua.PushGlobal("World", world->CreateHandle()); - //Gestion des Evenements Nz::EventHandler& eventHandler = window.GetEventHandler(); diff --git a/examples/GraphicsTest/main.cpp b/examples/GraphicsTest/main.cpp new file mode 100644 index 000000000..38f5330a4 --- /dev/null +++ b/examples/GraphicsTest/main.cpp @@ -0,0 +1,289 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Renderer::Config rendererConfig; + std::cout << "Run using Vulkan? (y/n)" << std::endl; + if (std::getchar() == 'y') + rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; + else + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + Nz::Modules nazara(rendererConfig); + + Nz::RenderWindow window; + + Nz::MeshParams meshParams; + meshParams.center = true; + meshParams.storage = Nz::DataStorage::Software; + meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, -90.f, 0.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f)); + meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_Normal_UV); + + std::shared_ptr 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__; + } + + std::shared_ptr spaceshipMesh = Nz::Mesh::LoadFromFile(resourceDir / "Spaceship/spaceship.obj", meshParams); + if (!spaceshipMesh) + { + NazaraError("Failed to load model"); + return __LINE__; + } + + std::shared_ptr gfxMesh = std::make_shared(*spaceshipMesh); + + // Texture + std::shared_ptr diffuseImage = Nz::Image::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png"); + if (!diffuseImage || !diffuseImage->Convert(Nz::PixelFormat::RGBA8_SRGB)) + { + NazaraError("Failed to load image"); + return __LINE__; + } + + Nz::TextureParams texParams; + texParams.renderDevice = device; + texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; + + std::shared_ptr material = std::make_shared(Nz::BasicMaterial::GetSettings()); + material->EnableDepthBuffer(true); + material->EnableFaceCulling(true); + + Nz::BasicMaterial basicMat(*material); + basicMat.EnableAlphaTest(false); + basicMat.SetAlphaMap(Nz::Texture::LoadFromFile(resourceDir / "alphatile.png", texParams)); + basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams)); + + Nz::Model model(std::move(gfxMesh)); + for (std::size_t i = 0; i < model.GetSubMeshCount(); ++i) + model.SetMaterial(i, material); + + Nz::Vector2ui windowSize = window.GetSize(); + + Nz::ViewerInstance viewerInstance; + viewerInstance.UpdateTargetSize(Nz::Vector2f(window.GetSize())); + viewerInstance.UpdateProjViewMatrices(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f), Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1)); + + Nz::WorldInstance modelInstance; + modelInstance.UpdateWorldMatrix(Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Left())); + + Nz::WorldInstance modelInstance2; + modelInstance2.UpdateWorldMatrix(Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Right())); + + Nz::RenderWindowImpl* windowImpl = window.GetImpl(); + std::shared_ptr commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); + + Nz::CommandBufferPtr drawCommandBuffer; + auto RebuildCommandBuffer = [&] + { + Nz::Vector2ui windowSize = window.GetSize(); + drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) + { + Nz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y); + + Nz::CommandBufferBuilder::ClearValues clearValues[2]; + clearValues[0].color = Nz::Color::Black; + clearValues[1].depth = 1.f; + clearValues[1].stencil = 0; + + builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); + { + builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] }); + { + builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.BindShaderBinding(Nz::Graphics::ViewerBindingSet, viewerInstance.GetShaderBinding()); + + for (Nz::WorldInstance& instance : { std::ref(modelInstance), std::ref(modelInstance2) }) + { + builder.BindShaderBinding(Nz::Graphics::WorldBindingSet, instance.GetShaderBinding()); + + for (std::size_t i = 0; i < model.GetSubMeshCount(); ++i) + { + builder.BindIndexBuffer(model.GetIndexBuffer(i).get()); + builder.BindVertexBuffer(0, model.GetVertexBuffer(i).get()); + builder.BindPipeline(*model.GetRenderPipeline(i)); + builder.BindShaderBinding(Nz::Graphics::MaterialBindingSet, model.GetMaterial(i)->GetShaderBinding()); + + builder.DrawIndexed(model.GetIndexCount(i)); + } + } + } + builder.EndRenderPass(); + } + builder.EndDebugRegion(); + }); + }; + + + Nz::Vector3f viewerPos = Nz::Vector3f::Zero(); + + Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); + Nz::Quaternionf camQuat(camAngles); + + window.EnableEventPolling(true); + + Nz::Clock updateClock; + Nz::Clock secondClock; + unsigned int fps = 0; + + Nz::Mouse::SetRelativeMouseMode(true); + + bool updateMat = false; + while (window.IsOpen()) + { + Nz::WindowEvent event; + while (window.PollEvent(&event)) + { + switch (event.type) + { + case Nz::WindowEventType::Quit: + window.Close(); + break; + + case Nz::WindowEventType::KeyPressed: + if (event.key.virtualKey == Nz::Keyboard::VKey::A) + { + basicMat.EnableAlphaTest(!basicMat.IsAlphaTestEnabled()); + updateMat = true; + } + + break; + + case Nz::WindowEventType::MouseMoved: // La souris a bougé + { + // Gestion de la caméra free-fly (Rotation) + float sensitivity = 0.3f; // Sensibilité de la souris + + // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris + camAngles.yaw = camAngles.yaw - event.mouseMove.deltaX * sensitivity; + camAngles.yaw.Normalize(); + + // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles + camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f); + + camQuat = camAngles; + break; + } + + case Nz::WindowEventType::Resized: + { + Nz::Vector2ui windowSize = window.GetSize(); + viewerInstance.UpdateProjectionMatrix(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f)); + viewerInstance.UpdateTargetSize(Nz::Vector2f(windowSize)); + break; + } + + default: + break; + } + } + + if (updateClock.GetMilliseconds() > 1000 / 60) + { + float cameraSpeed = 2.f * updateClock.GetSeconds(); + updateClock.Restart(); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) + viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed; + + // Si la flèche du bas ou la touche S est pressée, on recule + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) + viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) + viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) + viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed; + + // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) + viewerPos += Nz::Vector3f::Up() * cameraSpeed; + + // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) + viewerPos += Nz::Vector3f::Down() * cameraSpeed; + } + + Nz::RenderFrame frame = windowImpl->Acquire(); + if (!frame) + continue; + + Nz::UploadPool& uploadPool = frame.GetUploadPool(); + + viewerInstance.UpdateViewMatrix(Nz::Matrix4f::ViewMatrix(viewerPos, camAngles)); + + frame.Execute([&](Nz::CommandBufferBuilder& builder) + { + builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); + { + builder.PreTransferBarrier(); + + viewerInstance.UpdateBuffers(uploadPool, builder); + modelInstance.UpdateBuffers(uploadPool, builder); + modelInstance2.UpdateBuffers(uploadPool, builder); + + updateMat = material->Update(frame, builder) || updateMat; + + builder.PostTransferBarrier(); + } + builder.EndDebugRegion(); + }, Nz::QueueType::Transfer); + + if (updateMat || frame.IsFramebufferInvalidated()) + { + frame.PushForRelease(std::move(drawCommandBuffer)); + RebuildCommandBuffer(); + } + + frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); + + frame.Present(); + + window.Display(); + + // On incrémente le compteur de FPS improvisé + fps++; + + if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes + { + // Et on insère ces données dans le titre de la fenêtre + window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS"); + + /* + Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, + via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res". + Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier), + cela fonctionnera aussi comme ceci : "Chaîne de caractères". + */ + + // Et on réinitialise le compteur de FPS + fps = 0; + + // Et on relance l'horloge pour refaire ça dans une seconde + secondClock.Restart(); + } + } + + return EXIT_SUCCESS; +} diff --git a/examples/GraphicsTest/xmake.lua b/examples/GraphicsTest/xmake.lua new file mode 100644 index 000000000..f2c4d0741 --- /dev/null +++ b/examples/GraphicsTest/xmake.lua @@ -0,0 +1,5 @@ +target("GraphicsTest") + set_group("Examples") + set_kind("binary") + add_deps("NazaraGraphics") + add_files("main.cpp") \ No newline at end of file diff --git a/examples/HardwareInfo/main.cpp b/examples/HardwareInfo/main.cpp index 820f42a62..4173bf267 100644 --- a/examples/HardwareInfo/main.cpp +++ b/examples/HardwareInfo/main.cpp @@ -10,12 +10,11 @@ #include #include #include -#include #include #include #include -void printCap(std::ostream& o, const Nz::String& cap, bool b); +void printCap(std::ostream& o, const std::string& cap, bool b); int main() { @@ -58,46 +57,15 @@ int main() else oss << "Impossible de retrouver les informations du processeur" << std::endl; - oss << std::endl << "--Carte graphique--" << std::endl; - // La classe OpenGL nous donne accès à des informations sur la carte graphique - // Cependant celle-ci n'est accessible que si le projet est compilé avec NAZARA_RENDERER_OPENGL - // et que les répertoires d'inclusions donnent accès aux includes d'OpenGL (Cette démo utilisent ceux de Nazara) - Nz::Initializer openGL; - if (openGL) - { - // Nous récupérons ensuite la version d'OpenGL sous forme d'entier (ex: OpenGL 3.3 donnera 330) - unsigned int openglVersion = Nz::OpenGL::GetVersion(); - - // OpenGL nous donne accès à trois informations principales: - // 1) La chaîne d'identification du driver ("Renderer name") - // 2) La chaîne d'identification du concepteur ("Vendor name") - // 3) La version d'OpenGL - oss << "Identification: " << Nz::OpenGL::GetRendererName() << std::endl; - oss << "Concepteur: " << Nz::OpenGL::GetVendorName() << std::endl; - oss << "Version d'OpenGL: " << openglVersion/100 << '.' << openglVersion%100 << std::endl; - oss << std::endl; - - // Ainsi qu'un report des capacités de la carte graphique (avec le driver actuel) - oss << "Rapport des capacites: " << std::endl; // Pas d'accent car écriture dans un fichier (et on ne va pas s'embêter avec ça) - printCap(oss, "-Calculs 64bits", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_FP64)); - printCap(oss, "-Compression de textures (s3tc)", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_TextureCompression_s3tc)); - printCap(oss, "-Filtrage anisotrope", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_AnisotropicFilter)); - printCap(oss, "-Mode debug", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_DebugOutput)); - printCap(oss, "-Separate shader objects", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_SeparateShaderObjects)); - printCap(oss, "-Texture storage", Nz::OpenGL::IsSupported(Nz::OpenGLExtension_TextureStorage)); - } - else - oss << "Impossible de retrouver les informations de la carte graphique" << std::endl; - std::cout << "\r "; // On efface le message d'initialisation std::cout << '\r'; // Et on place déjà le caractère pour revenir sur la même ligne (Pour ne pas avoir un saut inutile) std::cout << oss.str() << std::endl; Nz::File reportFile("HardwareInfo.txt"); - if (reportFile.Open(Nz::OpenMode_Text | Nz::OpenMode_Truncate | Nz::OpenMode_WriteOnly)) + if (reportFile.Open(Nz::OpenMode::Text | Nz::OpenMode::Truncate | Nz::OpenMode::WriteOnly)) { - reportFile.Write(oss.str()); // Conversion implicite en Nz::String + reportFile.Write(oss.str()); // Conversion implicite en std::string reportFile.Close(); char accentAigu = static_cast(130); // C'est crade, mais ça marche chez 95% des Windowsiens @@ -111,7 +79,7 @@ int main() return 0; } -void printCap(std::ostream& o, const Nz::String& cap, bool b) +void printCap(std::ostream& o, const std::string& cap, bool b) { if (b) o << cap << ": Oui" << std::endl; diff --git a/examples/MeshInfos/main.cpp b/examples/MeshInfos/main.cpp index e7b3feaeb..782747e0d 100644 --- a/examples/MeshInfos/main.cpp +++ b/examples/MeshInfos/main.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include #include @@ -15,36 +15,28 @@ int main() { // Pour charger des ressources, il est impératif d'initialiser le module utilitaire - Nz::Initializer utility; - if (!utility) + Nz::Modules nazara; + /*if (!utility) { // Ça n'a pas fonctionné, le pourquoi se trouve dans le fichier NazaraLog.log std::cout << "Failed to initialize Nazara, see NazaraLog.log for further informations" << std::endl; std::getchar(); // On laise le temps de voir l'erreur return EXIT_FAILURE; - } + }*/ for (;;) { - Nz::Directory resourceDirectory("resources"); - if (!resourceDirectory.Open()) + std::vector models; + for (auto& p : std::filesystem::directory_iterator("resources")) { - std::cerr << "Failed to open resource directory" << std::endl; - std::getchar(); - return EXIT_FAILURE; - } + if (!p.is_regular_file()) + continue; - std::vector models; - while (resourceDirectory.NextResult()) - { - Nz::String path = resourceDirectory.GetResultName(); - Nz::String ext = path.SubStringFrom('.', -1, true); // Tout ce qui vient après le dernier '.' de la chaîne - if (Nz::MeshLoader::IsExtensionSupported(ext)) // L'extension est-elle supportée par le MeshLoader ? - models.push_back(path); + const std::filesystem::path& filePath = p.path(); + if (Nz::MeshLoader::IsExtensionSupported(filePath.extension().generic_u8string())) // L'extension est-elle supportée par le MeshLoader ? + models.push_back(filePath); } - resourceDirectory.Close(); - if (models.empty()) { std::cout << "No loadable mesh found in resource directory" << std::endl; @@ -71,7 +63,7 @@ int main() if (iChoice == 0) break; - Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(resourceDirectory.GetPath() + '/' + models[iChoice-1]); + Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(models[iChoice-1]); if (!mesh) { std::cout << "Failed to load mesh" << std::endl; @@ -123,8 +115,8 @@ int main() } } - Nz::String animationPath = mesh->GetAnimation(); - if (!animationPath.IsEmpty()) + std::filesystem::path animationPath = mesh->GetAnimation(); + if (!animationPath.empty()) { Nz::AnimationRef animation = Nz::Animation::LoadFromFile(animationPath); if (animation) @@ -174,7 +166,7 @@ int main() { const Nz::ParameterList& matData = mesh->GetMaterialData(i); - Nz::String data; + std::string data; if (!matData.GetStringParameter(Nz::MaterialData::FilePath, &data)) data = ""; diff --git a/examples/Particles/Common.cpp b/examples/Particles/Common.cpp index 0ed9096ef..690537d0f 100644 --- a/examples/Particles/Common.cpp +++ b/examples/Particles/Common.cpp @@ -1,8 +1,8 @@ #include "Common.hpp" #include #include -#include -#include +#include +#include ParticleDemo::ParticleDemo(const Nz::String& name, const ExampleShared& exampleShared) : m_shared(exampleShared), diff --git a/examples/Particles/Common.hpp b/examples/Particles/Common.hpp index 658b97419..3d672c5b3 100644 --- a/examples/Particles/Common.hpp +++ b/examples/Particles/Common.hpp @@ -7,10 +7,10 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include diff --git a/examples/Particles/LogoDemo.cpp b/examples/Particles/LogoDemo.cpp index f04ce43ad..23698cd66 100644 --- a/examples/Particles/LogoDemo.cpp +++ b/examples/Particles/LogoDemo.cpp @@ -2,8 +2,8 @@ #include #include #include -#include -#include +#include +#include #include namespace @@ -124,9 +124,9 @@ LogoExample::LogoExample(ExampleShared& sharedData) : ParticleDemo("Logo", sharedData) { Nz::ImageParams params; - params.loadFormat = Nz::PixelFormatType_RGBA8; + params.loadFormat = Nz::PixelFormat_RGBA8; - m_logo = Nz::Image::LoadFromFile("resources/Logo.png", params); + m_logo = Nz::Image::LoadFromFile("E:/Twitch/avatar_interested.png", params); if (!m_logo) NazaraError("Failed to load logo!"); diff --git a/examples/Particles/LogoDemo.hpp b/examples/Particles/LogoDemo.hpp index bd0536edf..bbf14e789 100644 --- a/examples/Particles/LogoDemo.hpp +++ b/examples/Particles/LogoDemo.hpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #include "Common.hpp" diff --git a/examples/Particles/SpacebattleDemo.cpp b/examples/Particles/SpacebattleDemo.cpp index 2ebc0969f..4b8dc12fd 100644 --- a/examples/Particles/SpacebattleDemo.cpp +++ b/examples/Particles/SpacebattleDemo.cpp @@ -4,8 +4,8 @@ #include #include #include -#include -#include +#include +#include namespace { @@ -294,7 +294,7 @@ ParticleDemo("Space battle", sharedData) } Nz::TextureRef skyboxCubemap = Nz::Texture::New(); - if (skyboxCubemap->Create(Nz::ImageType_Cubemap, Nz::PixelFormatType_RGBA8, 2048, 2048)) + if (skyboxCubemap->Create(Nz::ImageType_Cubemap, Nz::PixelFormat_RGBA8, 2048, 2048)) { skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveX, "resources/purple_nebula_skybox/purple_nebula_skybox_right1.png"); skyboxCubemap->LoadFaceFromFile(Nz::CubemapFace_PositiveY, "resources/purple_nebula_skybox/purple_nebula_skybox_top3.png"); diff --git a/examples/Particles/SpacebattleDemo.hpp b/examples/Particles/SpacebattleDemo.hpp index e0b928e19..b2aaa5c33 100644 --- a/examples/Particles/SpacebattleDemo.hpp +++ b/examples/Particles/SpacebattleDemo.hpp @@ -11,8 +11,8 @@ #include #include #include -#include -#include +#include +#include #include #include "Common.hpp" diff --git a/examples/Particles/build.lua b/examples/Particles/build_disabled.lua similarity index 100% rename from examples/Particles/build.lua rename to examples/Particles/build_disabled.lua diff --git a/examples/Particles/main.cpp b/examples/Particles/main.cpp index 4738c5eb1..5329a371d 100644 --- a/examples/Particles/main.cpp +++ b/examples/Particles/main.cpp @@ -1,16 +1,14 @@ #include #include #include -#include #include -#include #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include "LogoDemo.hpp" #include "SpacebattleDemo.hpp" #include @@ -38,6 +36,8 @@ int main() Nz::RenderWindow& window = app.AddWindow(mode, "Nazara demo - Particles", Nz::WindowStyle_Closable, targetParams); //Nz::RenderWindow& window = app.AddWindow(Nz::VideoMode(1920, 1080), "Nazara demo - Particles", Nz::WindowStyle_Fullscreen, targetParams); + app.EnableFPSCounter(true); + Ndk::World& world3D = app.AddWorld(); Ndk::World& world2D = app.AddWorld(); @@ -169,11 +169,11 @@ int main() case Nz::Keyboard::VKey::F5: { Nz::Image screenshot; - screenshot.Create(Nz::ImageType_2D, Nz::PixelFormatType_RGBA8, 1920, 1080); + screenshot.Create(Nz::ImageType_2D, Nz::PixelFormat_RGBA8, 1920, 1080); window.CopyToImage(&screenshot); static unsigned int counter = 1; - screenshot.SaveToFile("screenshot_" + Nz::String::Number(counter++) + ".png"); + screenshot.SaveToFile("screenshot_" + std::to_string(counter++) + ".png"); break; } diff --git a/examples/PhysicsDemo/main.cpp b/examples/PhysicsDemo/main.cpp new file mode 100644 index 000000000..96dca0bef --- /dev/null +++ b/examples/PhysicsDemo/main.cpp @@ -0,0 +1,410 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Renderer::Config rendererConfig; + std::cout << "Run using Vulkan? (y/n)" << std::endl; + if (std::getchar() != 'n') + rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; + else + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + Nz::Modules nazara(rendererConfig); + + Nz::RenderWindow window; + + Nz::MeshParams meshParams; + meshParams.center = true; + meshParams.storage = Nz::DataStorage::Software; + meshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 0.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f)); + meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_UV); + + std::shared_ptr 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__; + } + + std::shared_ptr spaceshipMesh = Nz::Mesh::LoadFromFile(resourceDir / "Spaceship/spaceship.obj", meshParams); + if (!spaceshipMesh) + { + NazaraError("Failed to load model"); + return __LINE__; + } + + std::shared_ptr gfxMesh = std::make_shared(*spaceshipMesh); + + // Texture + std::shared_ptr diffuseImage = Nz::Image::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png"); + if (!diffuseImage || !diffuseImage->Convert(Nz::PixelFormat::RGBA8_SRGB)) + { + NazaraError("Failed to load image"); + return __LINE__; + } + + Nz::TextureParams texParams; + texParams.renderDevice = device; + texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; + + std::shared_ptr material = std::make_shared(Nz::BasicMaterial::GetSettings()); + material->EnableDepthBuffer(true); + material->EnableFaceCulling(true); + + Nz::TextureSamplerInfo samplerInfo; + samplerInfo.anisotropyLevel = 8; + + Nz::BasicMaterial basicMat(*material); + basicMat.EnableAlphaTest(false); + basicMat.SetAlphaMap(Nz::Texture::LoadFromFile(resourceDir / "alphatile.png", texParams)); + basicMat.SetDiffuseMap(Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams)); + basicMat.SetDiffuseSampler(samplerInfo); + + std::shared_ptr model = std::make_shared(std::move(gfxMesh)); + for (std::size_t i = 0; i < model->GetSubMeshCount(); ++i) + model->SetMaterial(i, material); + + Nz::Vector2ui windowSize = window.GetSize(); + + Nz::ViewerInstance viewerInstance; + viewerInstance.UpdateTargetSize(Nz::Vector2f(window.GetSize())); + viewerInstance.UpdateProjViewMatrices(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f), Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1)); + + Nz::VertexMapper vertexMapper(*spaceshipMesh->GetSubMesh(0), Nz::BufferAccess::ReadOnly); + Nz::SparsePtr vertices = vertexMapper.GetComponentPtr(Nz::VertexComponent::Position); + + + entt::registry registry; + + Nz::Physics3DSystem physSytem(registry); + + + auto shipCollider = std::make_shared(vertices, vertexMapper.GetVertexCount(), 0.01f); + + std::shared_ptr colliderMat = std::make_shared(Nz::BasicMaterial::GetSettings()); + colliderMat->EnableDepthBuffer(true); + colliderMat->SetPrimitiveMode(Nz::PrimitiveMode::LineList); + + Nz::BasicMaterial colliderBasicMat(*colliderMat); + colliderBasicMat.SetDiffuseColor(Nz::Color::Green); + + std::shared_ptr colliderModel; + { + std::shared_ptr colliderMesh = Nz::Mesh::Build(shipCollider->GenerateMesh()); + std::shared_ptr colliderGraphicalMesh = std::make_shared(*colliderMesh); + + colliderModel = std::make_shared(colliderGraphicalMesh); + for (std::size_t i = 0; i < colliderModel->GetSubMeshCount(); ++i) + colliderModel->SetMaterial(i, colliderMat); + } + + entt::entity playerEntity = registry.create(); + Nz::Node headingNode; + { + auto& entityNode = registry.emplace(playerEntity); + entityNode.SetPosition(Nz::Vector3f(12.5f, 0.f, 25.f)); + + auto& entityGfx = registry.emplace(playerEntity); + entityGfx.AttachRenderable(model); + + auto& entityPhys = registry.emplace(playerEntity, physSytem.CreateRigidBody(shipCollider)); + entityPhys.SetMass(50.f); + entityPhys.SetAngularDamping(Nz::Vector3f::Zero()); + + headingNode.SetParent(entityNode); + headingNode.SetInheritRotation(false); + headingNode.SetRotation(entityNode.GetRotation()); + } + + + Nz::Node cameraNode; + cameraNode.SetParent(headingNode); + cameraNode.SetPosition(Nz::Vector3f::Backward() * 2.5f + Nz::Vector3f::Up() * 1.f); + + for (std::size_t x = 0; x < 1; ++x) + { + for (std::size_t y = 0; y < 1; ++y) + { + for (std::size_t z = 0; z < 10; ++z) + { + entt::entity entity = registry.create(); + auto& entityNode = registry.emplace(entity); + entityNode.SetPosition(Nz::Vector3f(x * 2.f, y * 1.5f, z * 2.f)); + + auto& entityGfx = registry.emplace(entity); + entityGfx.AttachRenderable(model); + + auto& entityPhys = registry.emplace(entity, physSytem.CreateRigidBody(shipCollider)); + entityPhys.SetMass(1.f); + entityPhys.SetAngularDamping(Nz::Vector3f::Zero()); + entityPhys.SetLinearDamping(0.f); + } + } + } + + + Nz::RenderWindowImpl* windowImpl = window.GetImpl(); + std::shared_ptr commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); + + Nz::CommandBufferPtr drawCommandBuffer; + auto RebuildCommandBuffer = [&] + { + Nz::Vector2ui windowSize = window.GetSize(); + drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) + { + Nz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y); + + Nz::CommandBufferBuilder::ClearValues clearValues[2]; + clearValues[0].color = Nz::Color(80, 80, 80); + clearValues[1].depth = 1.f; + clearValues[1].stencil = 0; + + builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); + { + builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] }); + { + builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.BindShaderBinding(Nz::Graphics::ViewerBindingSet, viewerInstance.GetShaderBinding()); + + auto view = registry.view(); + for (auto [entity, gfxComponent] : view.each()) + { + const Nz::WorldInstance& worldInstance = gfxComponent.GetWorldInstance(); + for (const auto& renderable : gfxComponent.GetRenderables()) + renderable->Draw(builder, worldInstance); + } + } + builder.EndRenderPass(); + } + builder.EndDebugRegion(); + }); + }; + + + Nz::Vector3f viewerPos = Nz::Vector3f::Zero(); + + Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); + Nz::Quaternionf camQuat(camAngles); + + window.EnableEventPolling(true); + + Nz::Clock updateClock; + Nz::Clock secondClock; + unsigned int fps = 0; + + Nz::Mouse::SetRelativeMouseMode(true); + + float elapsedTime = 0.f; + Nz::UInt64 time = Nz::GetElapsedMicroseconds(); + + Nz::PidController headingController(0.5f, 0.f, 0.05f); + Nz::PidController upController(1.f, 0.f, 0.1f); + + bool showColliders = false; + bool rebuildCommandBuffer = false; + while (window.IsOpen()) + { + Nz::UInt64 now = Nz::GetElapsedMicroseconds(); + elapsedTime = (now - time) / 1'000'000.f; + time = now; + + Nz::WindowEvent event; + while (window.PollEvent(&event)) + { + switch (event.type) + { + case Nz::WindowEventType::Quit: + window.Close(); + break; + + case Nz::WindowEventType::KeyPressed: + if (event.key.virtualKey == Nz::Keyboard::VKey::A) + { + basicMat.EnableAlphaTest(!basicMat.IsAlphaTestEnabled()); + rebuildCommandBuffer = true; + } + else if (event.key.virtualKey == Nz::Keyboard::VKey::B) + { + showColliders = !showColliders; + if (showColliders) + { + auto view = registry.view(); + for (auto [entity, gfxComponent] : view.each()) + gfxComponent.AttachRenderable(colliderModel); + } + else + { + auto view = registry.view(); + for (auto [entity, gfxComponent] : view.each()) + gfxComponent.DetachRenderable(colliderModel); + } + rebuildCommandBuffer = true; + } + + break; + + case Nz::WindowEventType::MouseMoved: + { + float sensitivity = 0.3f; + + camAngles.yaw = camAngles.yaw - event.mouseMove.deltaX * sensitivity; + camAngles.pitch = camAngles.pitch - event.mouseMove.deltaY * sensitivity; + + camAngles.Normalize(); + + camQuat = camAngles; + + headingNode.SetRotation(camQuat); + break; + } + + case Nz::WindowEventType::Resized: + { + Nz::Vector2ui windowSize = window.GetSize(); + viewerInstance.UpdateProjectionMatrix(Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f)); + viewerInstance.UpdateTargetSize(Nz::Vector2f(windowSize)); + break; + } + + default: + break; + } + } + + if (updateClock.GetMilliseconds() > 1000 / 60) + { + float updateTime = updateClock.Restart() / 1'000'000.f; + + float cameraSpeed = 20.f * updateTime; + + physSytem.Update(registry, 1000.f / 60.f); + + Nz::RigidBody3DComponent& playerShipBody = registry.get(playerEntity); + Nz::Quaternionf currentRotation = playerShipBody.GetRotation(); + + Nz::Vector3f desiredHeading = headingNode.GetForward(); + Nz::Vector3f currentHeading = currentRotation * Nz::Vector3f::Forward(); + Nz::Vector3f headingError = currentHeading.CrossProduct(desiredHeading); + + Nz::Vector3f desiredUp = headingNode.GetUp(); + Nz::Vector3f currentUp = currentRotation * Nz::Vector3f::Up(); + Nz::Vector3f upError = currentUp.CrossProduct(desiredUp); + + playerShipBody.AddTorque(headingController.Update(headingError, elapsedTime) * 10.f); + playerShipBody.AddTorque(upController.Update(upError, elapsedTime) * 10.f); + + float mass = playerShipBody.GetMass(); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) + playerShipBody.AddForce(Nz::Vector3f::Forward() * 2.5f * mass, Nz::CoordSys::Local); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) + playerShipBody.AddForce(Nz::Vector3f::Backward() * 2.5f * mass, Nz::CoordSys::Local); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) + playerShipBody.AddForce(Nz::Vector3f::Left() * 2.5f * mass, Nz::CoordSys::Local); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) + playerShipBody.AddForce(Nz::Vector3f::Right() * 2.5f * mass, Nz::CoordSys::Local); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) + playerShipBody.AddForce(Nz::Vector3f::Up() * 3.f * mass, Nz::CoordSys::Local); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) + playerShipBody.AddForce(Nz::Vector3f::Down() * 3.f * mass, Nz::CoordSys::Local); + } + + Nz::RenderFrame frame = windowImpl->Acquire(); + if (!frame) + continue; + + Nz::UploadPool& uploadPool = frame.GetUploadPool(); + + viewerInstance.UpdateViewMatrix(Nz::Matrix4f::ViewMatrix(cameraNode.GetPosition(Nz::CoordSys::Global), cameraNode.GetRotation(Nz::CoordSys::Global))); + + frame.Execute([&](Nz::CommandBufferBuilder& builder) + { + builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); + { + builder.PreTransferBarrier(); + + viewerInstance.UpdateBuffers(uploadPool, builder); + /* + modelInstance.UpdateBuffers(uploadPool, builder); + modelInstance2.UpdateBuffers(uploadPool, builder); + */ + + auto view = registry.view(); + for (auto [entity, gfxComponent, nodeComponent] : view.each()) + { + Nz::WorldInstance& worldInstance = gfxComponent.GetWorldInstance(); + worldInstance.UpdateWorldMatrix(nodeComponent.GetTransformMatrix()); + + worldInstance.UpdateBuffers(uploadPool, builder); + } + + if (material->Update(frame, builder)) + rebuildCommandBuffer = true; + + if (colliderMat->Update(frame, builder)) + rebuildCommandBuffer = true; + + builder.PostTransferBarrier(); + } + builder.EndDebugRegion(); + }, Nz::QueueType::Transfer); + + if (rebuildCommandBuffer || frame.IsFramebufferInvalidated()) + { + frame.PushForRelease(std::move(drawCommandBuffer)); + RebuildCommandBuffer(); + } + + frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); + + frame.Present(); + + window.Display(); + + rebuildCommandBuffer = false; + + fps++; + + if (secondClock.GetMilliseconds() >= 1000) + { + window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS"); + + fps = 0; + + secondClock.Restart(); + } + } + + registry.clear(); + + return EXIT_SUCCESS; +} diff --git a/examples/PhysicsDemo/xmake.lua b/examples/PhysicsDemo/xmake.lua new file mode 100644 index 000000000..65a6f99f7 --- /dev/null +++ b/examples/PhysicsDemo/xmake.lua @@ -0,0 +1,6 @@ +target("PhysicsDemo") + set_group("Examples") + set_kind("binary") + add_deps("NazaraGraphics", "NazaraPhysics3D") + add_packages("entt") + add_files("main.cpp") diff --git a/examples/PlayMusic/main.cpp b/examples/PlayMusic/main.cpp new file mode 100644 index 000000000..97c1048a7 --- /dev/null +++ b/examples/PlayMusic/main.cpp @@ -0,0 +1,42 @@ +/* +** PlayMusic - Example on playing a sound using streaming (doesn't load all the file in memory, only the played part) with Nz::Music +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Modules audio; + + Nz::SoundStreamParams streamParams; + streamParams.forceMono = false; + + Nz::Music music; + if (!music.OpenFromFile(resourceDir / "file_example_MP3_700KB.mp3", streamParams)) + { + std::cout << "Failed to load sound" << std::endl; + std::getchar(); + return EXIT_FAILURE; + } + + music.Play(); + + std::cout << "Playing sound..." << std::endl; + + while (music.IsPlaying()) + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + return EXIT_SUCCESS; +} diff --git a/examples/PlayMusic/xmake.lua b/examples/PlayMusic/xmake.lua new file mode 100644 index 000000000..32a81eb4c --- /dev/null +++ b/examples/PlayMusic/xmake.lua @@ -0,0 +1,5 @@ +target("PlayMusic") + set_group("Examples") + set_kind("binary") + add_deps("NazaraAudio") + add_files("main.cpp") diff --git a/examples/RenderTest/main.cpp b/examples/RenderTest/main.cpp new file mode 100644 index 000000000..f8da8f408 --- /dev/null +++ b/examples/RenderTest/main.cpp @@ -0,0 +1,429 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const char shaderSource[] = R"( + +option red: bool; + +[layout(std140)] +struct Data +{ + projectionMatrix: mat4, + worldMatrix: mat4, + viewMatrix: mat4 +} + +[set(0)] +external +{ + [binding(0)] viewerData: uniform, +} + +[set(1)] +external +{ + [binding(0)] tex: sampler2D +} + +struct VertIn +{ + [location(0)] position: vec3, + [location(1)] normal: vec3, + [location(2)] uv: vec2 +} + +struct VertOut +{ + [builtin(position)] position: vec4, + [location(0)] normal: vec3, + [location(1)] uv: vec2 +} + +struct FragOut +{ + [location(0)] color: vec4 +} + +[entry(frag)] +fn main(fragIn: VertOut) -> FragOut +{ + let lightDir = vec3(0.0, -0.707, 0.707); + let lightFactor = dot(fragIn.normal, lightDir); + + let fragOut: FragOut; + fragOut.color = lightFactor * tex.Sample(fragIn.uv) * select_opt(red, vec4(1.0, 0.0, 0.0, 1.0), vec4(1.0, 1.0, 1.0, 1.0)); + + return fragOut; +} + +[entry(vert)] +fn main(vertIn: VertIn) -> VertOut +{ + let vertOut: VertOut; + vertOut.position = viewerData.projectionMatrix * viewerData.viewMatrix * viewerData.worldMatrix * vec4(vertIn.position, 1.0); + vertOut.normal = vertIn.normal; + vertOut.uv = vertIn.uv; + + return vertOut; +} +)"; + +int main() +{ + std::filesystem::path resourceDir = "resources"; + if (!std::filesystem::is_directory(resourceDir) && std::filesystem::is_directory(".." / resourceDir)) + resourceDir = ".." / resourceDir; + + Nz::Renderer::Config rendererConfig; + std::cout << "Run using Vulkan? (y/n)" << std::endl; + if (std::getchar() == 'y') + rendererConfig.preferredAPI = Nz::RenderAPI::Vulkan; + else + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + Nz::Modules nazara(rendererConfig); + + Nz::RenderWindow window; + + 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)); + meshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout::XYZ_Normal_UV); + + std::shared_ptr device = Nz::Renderer::Instance()->InstanciateRenderDevice(0); + + std::string windowTitle = "Render Test"; + if (!window.Create(device, Nz::VideoMode(800, 600, 32), windowTitle)) + { + std::cout << "Failed to create Window" << std::endl; + return __LINE__; + } + + Nz::ShaderWriter::States states; + states.enabledOptions = 0; + states.optimize = true; + + auto fragVertShader = device->InstantiateShaderModule(Nz::ShaderStageType::Fragment | Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraShader, shaderSource, sizeof(shaderSource), states); + if (!fragVertShader) + { + std::cout << "Failed to instantiate shader" << std::endl; + return __LINE__; + } + + std::shared_ptr drfreak = Nz::Mesh::LoadFromFile(resourceDir / "Spaceship/spaceship.obj", meshParams); + if (!drfreak) + { + NazaraError("Failed to load model"); + return __LINE__; + } + + std::shared_ptr spaceshipMesh = std::static_pointer_cast(drfreak->GetSubMesh(0)); + + const std::shared_ptr& meshVB = spaceshipMesh->GetVertexBuffer(); + const std::shared_ptr& meshIB = spaceshipMesh->GetIndexBuffer(); + + // Index buffer + std::cout << "Index count: " << meshIB->GetIndexCount() << std::endl; + + // Vertex buffer + std::cout << "Vertex count: " << meshVB->GetVertexCount() << std::endl; + + // Texture + Nz::TextureParams texParams; + texParams.renderDevice = device; + texParams.loadFormat = Nz::PixelFormat::RGBA8_SRGB; + + std::shared_ptr texture = Nz::Texture::LoadFromFile(resourceDir / "Spaceship/Texture/diffuse.png", texParams); + std::shared_ptr textureSampler = device->InstantiateTextureSampler({}); + + struct + { + Nz::Matrix4f projectionMatrix; + Nz::Matrix4f modelMatrix; + Nz::Matrix4f viewMatrix; + } + ubo; + + Nz::Vector2ui windowSize = window.GetSize(); + ubo.projectionMatrix = Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f); + ubo.viewMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1); + ubo.modelMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2); + + Nz::UInt32 uniformSize = sizeof(ubo); + + Nz::RenderPipelineLayoutInfo pipelineLayoutInfo; + + auto& uboBinding = pipelineLayoutInfo.bindings.emplace_back(); + uboBinding.setIndex = 0; + uboBinding.bindingIndex = 0; + uboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex; + uboBinding.type = Nz::ShaderBindingType::UniformBuffer; + + std::shared_ptr basePipelineLayout = device->InstantiateRenderPipelineLayout(pipelineLayoutInfo); + + auto& textureBinding = pipelineLayoutInfo.bindings.emplace_back(); + textureBinding.setIndex = 1; + textureBinding.bindingIndex = 0; + textureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment; + textureBinding.type = Nz::ShaderBindingType::Texture; + + std::shared_ptr renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo)); + + Nz::ShaderBindingPtr viewerShaderBinding = basePipelineLayout->AllocateShaderBinding(0); + Nz::ShaderBindingPtr textureShaderBinding = renderPipelineLayout->AllocateShaderBinding(1); + + std::shared_ptr uniformBuffer = device->InstantiateBuffer(Nz::BufferType::Uniform); + if (!uniformBuffer->Initialize(uniformSize, Nz::BufferUsage::DeviceLocal | Nz::BufferUsage::Dynamic)) + { + NazaraError("Failed to create uniform buffer"); + return __LINE__; + } + + viewerShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::UniformBufferBinding { + uniformBuffer.get(), 0, uniformSize + } + } + }); + + textureShaderBinding->Update({ + { + 0, + Nz::ShaderBinding::TextureBinding { + texture.get(), textureSampler.get() + } + } + }); + + Nz::RenderPipelineInfo pipelineInfo; + pipelineInfo.pipelineLayout = renderPipelineLayout; + pipelineInfo.faceCulling = true; + + pipelineInfo.depthBuffer = true; + pipelineInfo.shaderModules.emplace_back(fragVertShader); + + auto& vertexBuffer = pipelineInfo.vertexBuffers.emplace_back(); + vertexBuffer.binding = 0; + vertexBuffer.declaration = meshVB->GetVertexDeclaration(); + + std::shared_ptr pipeline = device->InstantiateRenderPipeline(pipelineInfo); + + Nz::RenderDevice* renderDevice = window.GetRenderDevice().get(); + + Nz::RenderWindowImpl* windowImpl = window.GetImpl(); + std::shared_ptr commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics); + + Nz::RenderBuffer* renderBufferIB = static_cast(meshIB->GetBuffer()->GetImpl()); + Nz::RenderBuffer* renderBufferVB = static_cast(meshVB->GetBuffer()->GetImpl()); + + if (!renderBufferIB->Synchronize(renderDevice)) + { + NazaraError("Failed to synchronize render buffer"); + return __LINE__; + } + + if (!renderBufferVB->Synchronize(renderDevice)) + { + NazaraError("Failed to synchronize render buffer"); + return __LINE__; + } + + Nz::AbstractBuffer* indexBufferImpl = renderBufferIB->GetHardwareBuffer(renderDevice); + Nz::AbstractBuffer* vertexBufferImpl = renderBufferVB->GetHardwareBuffer(renderDevice); + + Nz::CommandBufferPtr drawCommandBuffer; + auto RebuildCommandBuffer = [&] + { + Nz::Vector2ui windowSize = window.GetSize(); + + drawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder) + { + Nz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y); + + Nz::CommandBufferBuilder::ClearValues clearValues[2]; + clearValues[0].color = Nz::Color::Black; + clearValues[1].depth = 1.f; + clearValues[1].stencil = 0; + + builder.BeginDebugRegion("Main window rendering", Nz::Color::Green); + { + builder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] }); + { + builder.BindIndexBuffer(indexBufferImpl); + builder.BindPipeline(*pipeline); + builder.BindVertexBuffer(0, vertexBufferImpl); + builder.BindShaderBinding(0, *viewerShaderBinding); + builder.BindShaderBinding(1, *textureShaderBinding); + + builder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + builder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) }); + + builder.DrawIndexed(meshIB->GetIndexCount()); + } + builder.EndRenderPass(); + } + builder.EndDebugRegion(); + }); + }; + RebuildCommandBuffer(); + + + Nz::Vector3f viewerPos = Nz::Vector3f::Zero(); + + Nz::EulerAnglesf camAngles(0.f, 0.f, 0.f); + Nz::Quaternionf camQuat(camAngles); + + window.EnableEventPolling(true); + + Nz::Clock updateClock; + Nz::Clock secondClock; + unsigned int fps = 0; + bool uboUpdate = true; + + Nz::Mouse::SetRelativeMouseMode(true); + + while (window.IsOpen()) + { + Nz::WindowEvent event; + while (window.PollEvent(&event)) + { + switch (event.type) + { + case Nz::WindowEventType::Quit: + window.Close(); + break; + + case Nz::WindowEventType::MouseMoved: // La souris a bougé + { + // Gestion de la caméra free-fly (Rotation) + float sensitivity = 0.3f; // Sensibilité de la souris + + // On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris + camAngles.yaw = camAngles.yaw - event.mouseMove.deltaX * sensitivity; + camAngles.yaw.Normalize(); + + // Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles + camAngles.pitch = Nz::Clamp(camAngles.pitch - event.mouseMove.deltaY*sensitivity, -89.f, 89.f); + + camQuat = camAngles; + + uboUpdate = true; + break; + } + + case Nz::WindowEventType::Resized: + { + Nz::Vector2ui windowSize = window.GetSize(); + ubo.projectionMatrix = Nz::Matrix4f::Perspective(Nz::DegreeAnglef(70.f), float(windowSize.x) / windowSize.y, 0.1f, 1000.f); + uboUpdate = true; + break; + } + + default: + break; + } + } + + if (updateClock.GetMilliseconds() > 1000 / 60) + { + float cameraSpeed = 2.f * updateClock.GetSeconds(); + updateClock.Restart(); + + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z)) + viewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed; + + // Si la flèche du bas ou la touche S est pressée, on recule + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S)) + viewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q)) + viewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed; + + // Etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D)) + viewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed; + + // Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation) + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift)) + viewerPos += Nz::Vector3f::Up() * cameraSpeed; + + // Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc... + if (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl)) + viewerPos += Nz::Vector3f::Down() * cameraSpeed; + + uboUpdate = true; + } + + Nz::RenderFrame frame = windowImpl->Acquire(); + if (!frame) + continue; + + if (frame.IsFramebufferInvalidated()) + { + frame.PushForRelease(std::move(drawCommandBuffer)); + RebuildCommandBuffer(); + } + + ubo.viewMatrix = Nz::Matrix4f::ViewMatrix(viewerPos, camAngles); + + if (uboUpdate) + { + auto& allocation = frame.GetUploadPool().Allocate(uniformSize); + + std::memcpy(allocation.mappedPtr, &ubo, sizeof(ubo)); + + frame.Execute([&](Nz::CommandBufferBuilder& builder) + { + builder.BeginDebugRegion("UBO Update", Nz::Color::Yellow); + { + builder.PreTransferBarrier(); + builder.CopyBuffer(allocation, uniformBuffer.get()); + builder.PostTransferBarrier(); + } + builder.EndDebugRegion(); + }, Nz::QueueType::Transfer); + + uboUpdate = false; + } + + frame.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics); + + frame.Present(); + + window.Display(); + + // On incrémente le compteur de FPS improvisé + fps++; + + if (secondClock.GetMilliseconds() >= 1000) // Toutes les secondes + { + // Et on insère ces données dans le titre de la fenêtre + window.SetTitle(windowTitle + " - " + Nz::NumberToString(fps) + " FPS"); + + /* + Note: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier, + via quelque chose de similaire à u8"Cha\u00CEne de caract\u00E8res". + Cependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier), + cela fonctionnera aussi comme ceci : "Chaîne de caractères". + */ + + // Et on réinitialise le compteur de FPS + fps = 0; + + // Et on relance l'horloge pour refaire ça dans une seconde + secondClock.Restart(); + } + } + + return EXIT_SUCCESS; +} diff --git a/examples/RenderTest/xmake.lua b/examples/RenderTest/xmake.lua new file mode 100644 index 000000000..0e11edc47 --- /dev/null +++ b/examples/RenderTest/xmake.lua @@ -0,0 +1,5 @@ +target("RenderTest") + set_group("Examples") + set_kind("binary") + add_deps("NazaraRenderer") + add_files("main.cpp") \ No newline at end of file diff --git a/examples/Std140Debug/main.cpp b/examples/Std140Debug/main.cpp new file mode 100644 index 000000000..4cbe0c1ed --- /dev/null +++ b/examples/Std140Debug/main.cpp @@ -0,0 +1,174 @@ +#include +#include +#include +#include +#include +#include +#include + +const char fragmentSource[] = R"( +#version 310 es + +#if GL_FRAGMENT_PRECISION_HIGH +precision highp float; +#else +precision mediump float; +#endif + +layout(binding = 3, std140) uniform LightParameters +{ + mat4 projectionMatrix; + mat4 invProjectionMatrix; + mat4 viewMatrix; + mat4 invViewMatrix; + mat4 viewProjMatrix; + mat4 invViewProjMatrix; + vec2 renderTargetSize; + vec2 invRenderTargetSize; + vec3 eyePosition; +}; + +void main() +{ +} +)"; + +const char vertexSource[] = R"( +#version 310 es + +void main() +{ + gl_Position = vec4(0.0, 0.0, 0.0, 1.0); +} +)"; + +template +std::vector SortIndexes(const std::vector& vec, Compare&& compare) +{ + std::vector p(vec.size()); + std::iota(p.begin(), p.end(), 0); + std::sort(p.begin(), p.end(), [&](std::size_t i, std::size_t j) { return compare(vec[i], vec[j]); }); + + return p; +} + +int main() +{ + Nz::Renderer::Config rendererConfig; + rendererConfig.preferredAPI = Nz::RenderAPI::OpenGL; + + Nz::Modules nazara(rendererConfig); + if (Nz::Renderer::Instance()->QueryAPI() != Nz::RenderAPI::OpenGL) + { + std::cout << "This program only works with OpenGL" << std::endl; + return EXIT_FAILURE; + } + + std::shared_ptr device = std::static_pointer_cast(Nz::Renderer::Instance()->InstanciateRenderDevice(0)); + + std::string err; + + // Fragment shader + Nz::GL::Shader fragmentShader; + if (!fragmentShader.Create(*device, GL_FRAGMENT_SHADER)) + { + std::cerr << "Failed to create fragment shader" << std::endl; + return EXIT_FAILURE; + } + + fragmentShader.SetSource(fragmentSource, sizeof(fragmentSource)); + fragmentShader.Compile(); + + if (!fragmentShader.GetCompilationStatus(&err)) + { + std::cerr << "Failed to compile fragment shader: " << err << std::endl; + return EXIT_FAILURE; + } + + // Vertex shader + Nz::GL::Shader vertexShader; + if (!vertexShader.Create(*device, GL_VERTEX_SHADER)) + { + std::cerr << "Failed to create vertex shader" << std::endl; + return EXIT_FAILURE; + } + + vertexShader.SetSource(vertexSource, sizeof(vertexSource)); + vertexShader.Compile(); + + if (!vertexShader.GetCompilationStatus(&err)) + { + std::cerr << "Failed to compile vertex shader: " << err << std::endl; + return EXIT_FAILURE; + } + + // Program + Nz::GL::Program program; + if (!program.Create(*device)) + { + std::cerr << "Failed to create program" << std::endl; + return EXIT_FAILURE; + } + + program.AttachShader(fragmentShader.GetObjectId()); + program.AttachShader(vertexShader.GetObjectId()); + program.Link(); + + if (!program.GetLinkStatus(&err)) + { + std::cerr << "Failed to link program: " << err << std::endl; + return EXIT_FAILURE; + } + + // Get infos + GLuint blockIndex = program.GetUniformBlockIndex("LightParameters"); + if (blockIndex == GL_INVALID_INDEX) + { + std::cerr << "Failed to find uniform block in program" << std::endl; + return EXIT_FAILURE; + } + + std::vector uniformIndices = program.GetActiveUniformBlockUniformIndices(blockIndex); + + std::vector offsets = program.GetActiveUniforms(uniformIndices.size(), reinterpret_cast(uniformIndices.data()), GL_UNIFORM_OFFSET); + + auto p = SortIndexes(offsets, std::less()); + + std::vector computedOffsets; + + Nz::FieldOffsets fieldOffsets(Nz::StructLayout::Std140); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddMatrix(Nz::StructFieldType::Float1, 4, 4, true)); + computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float2)); + computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float2)); + computedOffsets.push_back(fieldOffsets.AddField(Nz::StructFieldType::Float3)); + + + GLint dataSize; + program.GetActiveUniformBlock(blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize); + + if (fieldOffsets.GetAlignedSize() != dataSize) + std::cout << "size mismatch (computed " << fieldOffsets.GetAlignedSize() << ", reference has " << dataSize << ")" << std::endl;; + + if (computedOffsets.size() != uniformIndices.size()) + { + std::cout << "member count mismatch" << std::endl; + return EXIT_FAILURE; + } + + for (std::size_t i = 0; i < uniformIndices.size(); ++i) + { + GLint realOffset = offsets[p[i]]; + std::cout << program.GetActiveUniformName(uniformIndices[p[i]]) << ": " << realOffset; + if (realOffset != computedOffsets[i]) + std::cout << " ERR"; + + std::cout << std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/examples/Std140Debug/xmake.lua b/examples/Std140Debug/xmake.lua new file mode 100644 index 000000000..f72858562 --- /dev/null +++ b/examples/Std140Debug/xmake.lua @@ -0,0 +1,5 @@ +target("Std140Debug") + set_group("Examples") + set_kind("binary") + add_deps("NazaraOpenGLRenderer") + add_files("main.cpp") diff --git a/examples/Tut00/build.lua b/examples/Tut00/build_disabled.lua similarity index 92% rename from examples/Tut00/build.lua rename to examples/Tut00/build_disabled.lua index bdb125ab1..7d64037ff 100644 --- a/examples/Tut00/build.lua +++ b/examples/Tut00/build_disabled.lua @@ -10,9 +10,7 @@ EXAMPLE.Libraries = { "NazaraAudio", "NazaraCore", "NazaraGraphics", - "NazaraLua", "NazaraNetwork", - "NazaraNoise", "NazaraPhysics2D", "NazaraPhysics3D", "NazaraPlatform", diff --git a/examples/Tut00/main.cpp b/examples/Tut00/main.cpp index a1029eb99..5057bad12 100644 --- a/examples/Tut00/main.cpp +++ b/examples/Tut00/main.cpp @@ -1,14 +1,12 @@ -#include +#include #include #include -#include #include -#include #include #include #include #include -#include +#include #include int main(int argc, char* argv[]) @@ -18,6 +16,9 @@ int main(int argc, char* argv[]) Ndk::Application application(argc, argv); // Do what you want here + Nz::LuaInstance lua; + std::cout << lua.Execute("return {key = 42}") << std::endl; + std::cout << lua.DumpStack() << std::endl; return EXIT_SUCCESS; } diff --git a/examples/Tut01/build.lua b/examples/Tut01/build_disabled.lua similarity index 100% rename from examples/Tut01/build.lua rename to examples/Tut01/build_disabled.lua diff --git a/examples/Tut01/main.cpp b/examples/Tut01/main.cpp index 4570cec08..94834829c 100644 --- a/examples/Tut01/main.cpp +++ b/examples/Tut01/main.cpp @@ -3,10 +3,10 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include int main(int argc, char* argv[]) diff --git a/examples/Tut02/build.lua b/examples/Tut02/build_disabled.lua similarity index 100% rename from examples/Tut02/build.lua rename to examples/Tut02/build_disabled.lua diff --git a/examples/Tut02/main.cpp b/examples/Tut02/main.cpp index 54e92993f..cee826531 100644 --- a/examples/Tut02/main.cpp +++ b/examples/Tut02/main.cpp @@ -3,10 +3,10 @@ #include #include #include -#include -#include -#include -#include +#include +#include +#include +#include #include int main(int argc, char* argv[]) diff --git a/examples/bin/Shaders/PhongLighting/core.frag b/examples/bin/Shaders/PhongLighting/core.frag deleted file mode 100644 index f95d0eb04..000000000 --- a/examples/bin/Shaders/PhongLighting/core.frag +++ /dev/null @@ -1,488 +0,0 @@ -#if EARLY_FRAGMENT_TESTS && !ALPHA_TEST -layout(early_fragment_tests) in; -#endif - -// HACK UNTIL PROPER FIX -#if GLSL_VERSION < 400 - #undef SHADOW_MAPPING - #define SHADOW_MAPPING 0 -#endif -// HACK - -#define LIGHT_DIRECTIONAL 0 -#define LIGHT_POINT 1 -#define LIGHT_SPOT 2 - -/********************Entrant********************/ -in vec4 vColor; -in vec4 vLightSpacePos[3]; -in mat3 vLightToWorld; -in vec3 vNormal; -in vec2 vTexCoord; -in vec3 vViewDir; -in vec3 vWorldPos; - -/********************Sortant********************/ -out vec4 RenderTarget0; -out vec4 RenderTarget1; -out vec4 RenderTarget2; - -/********************Uniformes********************/ -struct Light -{ - int type; - vec4 color; - vec2 factors; - - vec4 parameters1; - vec4 parameters2; - vec2 parameters3; - bool shadowMapping; -}; - -// Lumières -uniform Light Lights[3]; -uniform samplerCube PointLightShadowMap[3]; -uniform sampler2D DirectionalSpotLightShadowMap[3]; - -// Matériau -uniform sampler2D MaterialAlphaMap; -uniform float MaterialAlphaThreshold; -uniform vec4 MaterialAmbient; -uniform vec4 MaterialDiffuse; -uniform sampler2D MaterialDiffuseMap; -uniform sampler2D MaterialEmissiveMap; -uniform sampler2D MaterialHeightMap; -uniform sampler2D MaterialNormalMap; -uniform float MaterialShininess; -uniform vec4 MaterialSpecular; -uniform sampler2D MaterialSpecularMap; - -// Autres -uniform float ParallaxBias = -0.03; -uniform float ParallaxScale = 0.02; -uniform vec2 InvTargetSize; -uniform vec3 EyePosition; -uniform samplerCube ReflectionMap; -uniform vec4 SceneAmbient; - -uniform mat4 WorldMatrix; - -uniform sampler2D TextureOverlay; - -/********************Fonctions********************/ - -#define kPI 3.1415926536 - -vec4 EncodeNormal(in vec3 normal) -{ - //return vec4(normal*0.5 + 0.5, 0.0); - return vec4(vec2(atan(normal.y, normal.x)/kPI, normal.z), 0.0, 0.0); -} - -float VectorToDepthValue(vec3 vec, float zNear, float zFar) -{ - vec3 absVec = abs(vec); - float localZ = max(absVec.x, max(absVec.y, absVec.z)); - - float normZ = ((zFar + zNear) * localZ - (2.0*zFar*zNear)) / ((zFar - zNear)*localZ); - return (normZ + 1.0) * 0.5; -} - -#if SHADOW_MAPPING -float CalculateDirectionalShadowFactor(int lightIndex) -{ - vec4 lightSpacePos = vLightSpacePos[lightIndex]; - return (texture(DirectionalSpotLightShadowMap[lightIndex], lightSpacePos.xy).x >= (lightSpacePos.z - 0.0005)) ? 1.0 : 0.0; -} - -float CalculatePointShadowFactor(int lightIndex, vec3 lightToWorld, float zNear, float zFar) -{ - return (texture(PointLightShadowMap[lightIndex], vec3(lightToWorld.x, -lightToWorld.y, -lightToWorld.z)).x >= VectorToDepthValue(lightToWorld, zNear, zFar)) ? 1.0 : 0.0; -} - -float CalculateSpotShadowFactor(int lightIndex, float lambert) -{ - vec4 lightSpacePos = vLightSpacePos[lightIndex]; - -#if 0 - float visibility = 1.0; - float bias = 0.005 * tan(acos(NoL)); - bias = clamp(bias, MinAllowedBias, MaxAllowedBias); - - float x,y; - for (y = -1.0; y <= 1.0; y+= 1.0) - for (x = -1.0; x <= 1.0; x+= 1.0) - visibility += (textureProj(DirectionalSpotLightShadowMap[lightIndex], lightSpacePos.xyw + vec3(x/1024.0 * lightSpacePos.w, y/1024.0 * lightSpacePos.w, 0.0)).x >= (lightSpacePos.z - 0.0005)/lightSpacePos.w) ? 1.0 : 0.0; - - visibility /= 9.0; - - return visibility; -#else - float bias = 0.005 * tan(acos(lambert)); - - return (textureProj(DirectionalSpotLightShadowMap[lightIndex], lightSpacePos.xyw).x >= (lightSpacePos.z - bias)/lightSpacePos.w) ? 1.0 : 0.0; -#endif -} -#endif - -void main() -{ - vec4 diffuseColor = MaterialDiffuse * vColor; - -#if AUTO_TEXCOORDS - vec2 texCoord = gl_FragCoord.xy * InvTargetSize; -#else - vec2 texCoord = vTexCoord; -#endif - -#if PARALLAX_MAPPING - float height = texture(MaterialHeightMap, texCoord).r; - float v = height*ParallaxScale + ParallaxBias; - - vec3 viewDir = normalize(vViewDir); - texCoord += v * viewDir.xy; -#endif - -#if DIFFUSE_MAPPING - diffuseColor *= texture(MaterialDiffuseMap, texCoord); -#endif - -#if FLAG_TEXTUREOVERLAY - diffuseColor *= texture(TextureOverlay, texCoord); -#endif - -#if FLAG_DEFERRED - #if ALPHA_TEST - // Inutile de faire de l'alpha-mapping sans alpha-test en Deferred (l'alpha n'est pas sauvegardé dans le G-Buffer) - #if ALPHA_MAPPING - diffuseColor.a *= texture(MaterialAlphaMap, texCoord).r; - #endif - - if (diffuseColor.a < MaterialAlphaThreshold) - discard; - #endif // ALPHA_TEST - - #if NORMAL_MAPPING - vec3 normal = normalize(vLightToWorld * (2.0 * vec3(texture(MaterialNormalMap, texCoord)) - 1.0)); - #else - vec3 normal = normalize(vNormal); - #endif // NORMAL_MAPPING - - vec3 specularColor = MaterialSpecular.rgb; - #if SPECULAR_MAPPING - specularColor *= texture(MaterialSpecularMap, texCoord).rgb; - #endif - - /* - Texture0: Diffuse Color + Specular - Texture1: Normal + Specular - Texture2: Encoded depth + Shininess - */ - RenderTarget0 = vec4(diffuseColor.rgb, dot(specularColor, vec3(0.3, 0.59, 0.11))); - RenderTarget1 = vec4(EncodeNormal(normal)); - RenderTarget2 = vec4(0.0, 0.0, 0.0, (MaterialShininess == 0.0) ? 0.0 : max(log2(MaterialShininess), 0.1)/10.5); // http://www.guerrilla-games.com/publications/dr_kz2_rsx_dev07.pdf -#else // FLAG_DEFERRED - #if ALPHA_MAPPING - diffuseColor.a *= texture(MaterialAlphaMap, texCoord).r; - #endif - - #if ALPHA_TEST - if (diffuseColor.a < MaterialAlphaThreshold) - discard; - #endif - - vec3 lightAmbient = vec3(0.0); - vec3 lightDiffuse = vec3(0.0); - vec3 lightSpecular = vec3(0.0); - - #if NORMAL_MAPPING - vec3 normal = normalize(vLightToWorld * (2.0 * vec3(texture(MaterialNormalMap, texCoord)) - 1.0)); - #else - vec3 normal = normalize(vNormal); - #endif - - if (MaterialShininess > 0.0) - { - vec3 eyeVec = normalize(EyePosition - vWorldPos); - - for (int i = 0; i < 3; ++i) - { - vec4 lightColor = Lights[i].color; - float lightAmbientFactor = Lights[i].factors.x; - float lightDiffuseFactor = Lights[i].factors.y; - - switch (Lights[i].type) - { - case LIGHT_DIRECTIONAL: - { - vec3 lightDir = -Lights[i].parameters1.xyz; - - // Ambient - lightAmbient += lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - float att = 1.0; - - float lambert = max(dot(normal, lightDir), 0.0); - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculateDirectionalShadowFactor(i); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Diffuse - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - - // Specular - vec3 reflection = reflect(-lightDir, normal); - float specularFactor = max(dot(reflection, eyeVec), 0.0); - specularFactor = pow(specularFactor, MaterialShininess); - - lightSpecular += att * specularFactor * lightColor.rgb; - break; - } - - case LIGHT_POINT: - { - vec3 lightPos = Lights[i].parameters1.xyz; - float lightAttenuation = Lights[i].parameters1.w; - float lightInvRadius = Lights[i].parameters2.w; - - vec3 worldToLight = lightPos - vWorldPos; - float lightDirLength = length(worldToLight); - vec3 lightDir = worldToLight / lightDirLength; // Normalisation - - float att = max(lightAttenuation - lightInvRadius * lightDirLength, 0.0); - - // Ambient - lightAmbient += att * lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculatePointShadowFactor(i, vWorldPos - lightPos, 0.1, 50.0); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Diffuse - float lambert = max(dot(normal, lightDir), 0.0); - - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - - // Specular - vec3 reflection = reflect(-lightDir, normal); - float specularFactor = max(dot(reflection, eyeVec), 0.0); - specularFactor = pow(specularFactor, MaterialShininess); - - lightSpecular += att * specularFactor * lightColor.rgb; - break; - } - - case LIGHT_SPOT: - { - vec3 lightPos = Lights[i].parameters1.xyz; - vec3 lightDir = Lights[i].parameters2.xyz; - float lightAttenuation = Lights[i].parameters1.w; - float lightInvRadius = Lights[i].parameters2.w; - float lightInnerAngle = Lights[i].parameters3.x; - float lightOuterAngle = Lights[i].parameters3.y; - - vec3 worldToLight = lightPos - vWorldPos; - float lightDistance = length(worldToLight); - worldToLight /= lightDistance; // Normalisation - - float att = max(lightAttenuation - lightInvRadius * lightDistance, 0.0); - - // Ambient - lightAmbient += att * lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - float lambert = max(dot(normal, worldToLight), 0.0); - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculateSpotShadowFactor(i, lambert); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Modification de l'atténuation pour gérer le spot - float curAngle = dot(lightDir, -worldToLight); - float innerMinusOuterAngle = lightInnerAngle - lightOuterAngle; - att *= max((curAngle - lightOuterAngle) / innerMinusOuterAngle, 0.0); - - // Diffuse - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - - // Specular - vec3 reflection = reflect(-worldToLight, normal); - float specularFactor = max(dot(reflection, eyeVec), 0.0); - specularFactor = pow(specularFactor, MaterialShininess); - - lightSpecular += att * specularFactor * lightColor.rgb; - break; - } - - default: - break; - } - } - } - else - { - for (int i = 0; i < 3; ++i) - { - vec4 lightColor = Lights[i].color; - float lightAmbientFactor = Lights[i].factors.x; - float lightDiffuseFactor = Lights[i].factors.y; - - switch (Lights[i].type) - { - case LIGHT_DIRECTIONAL: - { - vec3 lightDir = -Lights[i].parameters1.xyz; - - // Ambient - lightAmbient += lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - float att = 1.0; - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculateDirectionalShadowFactor(i); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Diffuse - float lambert = max(dot(normal, lightDir), 0.0); - - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - break; - } - - case LIGHT_POINT: - { - vec3 lightPos = Lights[i].parameters1.xyz; - float lightAttenuation = Lights[i].parameters1.w; - float lightInvRadius = Lights[i].parameters2.w; - - vec3 worldToLight = lightPos - vWorldPos; - float lightDirLength = length(worldToLight); - vec3 lightDir = worldToLight / lightDirLength; // Normalisation - - float att = max(lightAttenuation - lightInvRadius * lightDirLength, 0.0); - - // Ambient - lightAmbient += att * lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculatePointShadowFactor(i, vWorldPos - lightPos, 0.1, 50.0); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Diffuse - float lambert = max(dot(normal, lightDir), 0.0); - - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - break; - } - - case LIGHT_SPOT: - { - vec3 lightPos = Lights[i].parameters1.xyz; - vec3 lightDir = Lights[i].parameters2.xyz; - float lightAttenuation = Lights[i].parameters1.w; - float lightInvRadius = Lights[i].parameters2.w; - float lightInnerAngle = Lights[i].parameters3.x; - float lightOuterAngle = Lights[i].parameters3.y; - - vec3 worldToLight = lightPos - vWorldPos; - float lightDistance = length(worldToLight); - worldToLight /= lightDistance; // Normalisation - - float att = max(lightAttenuation - lightInvRadius * lightDistance, 0.0); - - // Ambient - lightAmbient += att * lightColor.rgb * lightAmbientFactor * (MaterialAmbient.rgb + SceneAmbient.rgb); - - float lambert = max(dot(normal, worldToLight), 0.0); - - #if SHADOW_MAPPING - if (Lights[i].shadowMapping) - { - float shadowFactor = CalculateSpotShadowFactor(i, lambert); - if (shadowFactor == 0.0) - break; - - att *= shadowFactor; - } - #endif - - // Modification de l'atténuation pour gérer le spot - float curAngle = dot(lightDir, -worldToLight); - float innerMinusOuterAngle = lightInnerAngle - lightOuterAngle; - att *= max((curAngle - lightOuterAngle) / innerMinusOuterAngle, 0.0); - - // Diffuse - lightDiffuse += att * lambert * lightColor.rgb * lightDiffuseFactor; - } - - default: - break; - } - } - } - - lightSpecular *= MaterialSpecular.rgb; - #if SPECULAR_MAPPING - lightSpecular *= texture(MaterialSpecularMap, texCoord).rgb; // Utiliser l'alpha de MaterialSpecular n'aurait aucun sens - #endif - - vec3 lightColor = (lightAmbient + lightDiffuse + lightSpecular); - - #if REFLECTION_MAPPING - vec3 eyeVec = normalize(vWorldPos - EyePosition); - - vec3 reflected = normalize(reflect(eyeVec, normal)); - //reflected = vec3(inverse(WorldMatrix) * vec4(reflected, 0.0)); - - lightColor *= texture(ReflectionMap, reflected).rgb; - #endif - - vec4 fragmentColor = vec4(lightColor, 1.0) * diffuseColor; - - #if EMISSIVE_MAPPING - float lightIntensity = dot(lightColor, vec3(0.3, 0.59, 0.11)); - - vec3 emissionColor = MaterialDiffuse.rgb * texture(MaterialEmissiveMap, texCoord).rgb; - RenderTarget0 = vec4(mix(fragmentColor.rgb, emissionColor, clamp(1.0 - 3.0*lightIntensity, 0.0, 1.0)), fragmentColor.a); - #else - RenderTarget0 = fragmentColor; - #endif // EMISSIVE_MAPPING -#endif // FLAG_DEFERRED -} - diff --git a/examples/bin/Shaders/PhongLighting/core.vert b/examples/bin/Shaders/PhongLighting/core.vert deleted file mode 100644 index 8943c5935..000000000 --- a/examples/bin/Shaders/PhongLighting/core.vert +++ /dev/null @@ -1,148 +0,0 @@ -/********************Entrant********************/ -#if FLAG_BILLBOARD -in vec3 InstanceData0; // center -in vec4 InstanceData1; // size | sin cos -in vec4 InstanceData2; // color -#else -in mat4 InstanceData0; -#endif - -in vec4 VertexColor; -in vec3 VertexPosition; -in vec3 VertexNormal; -in vec3 VertexTangent; -in vec2 VertexTexCoord; -in vec4 VertexUserdata0; - -/********************Sortant********************/ -out vec4 vColor; -out vec4 vLightSpacePos[3]; -out mat3 vLightToWorld; -out vec3 vNormal; -out vec2 vTexCoord; -out vec3 vViewDir; -out vec3 vWorldPos; - -/********************Uniformes********************/ -uniform vec3 EyePosition; -uniform mat4 InvViewMatrix; -uniform mat4 LightViewProjMatrix[3]; -uniform float VertexDepth; -uniform mat4 ViewMatrix; -uniform mat4 ViewProjMatrix; -uniform mat4 WorldMatrix; -uniform mat4 WorldViewProjMatrix; - -/********************Fonctions********************/ -void main() -{ -#if FLAG_VERTEXCOLOR - vec4 color = VertexColor; -#else - vec4 color = vec4(1.0); -#endif - - vec2 texCoords; - -#if FLAG_BILLBOARD - #if FLAG_INSTANCING - vec3 billboardCenter = InstanceData0; - vec2 billboardSize = InstanceData1.xy; - vec2 billboardSinCos = InstanceData1.zw; - vec4 billboardColor = InstanceData2; - - vec2 rotatedPosition; - rotatedPosition.x = VertexPosition.x*billboardSinCos.y - VertexPosition.y*billboardSinCos.x; - rotatedPosition.y = VertexPosition.y*billboardSinCos.y + VertexPosition.x*billboardSinCos.x; - rotatedPosition *= billboardSize; - - vec3 cameraRight = vec3(ViewMatrix[0][0], ViewMatrix[1][0], ViewMatrix[2][0]); - vec3 cameraUp = vec3(ViewMatrix[0][1], ViewMatrix[1][1], ViewMatrix[2][1]); - vec3 vertexPos = billboardCenter + cameraRight*rotatedPosition.x + cameraUp*rotatedPosition.y; - - gl_Position = ViewProjMatrix * vec4(vertexPos, 1.0); - color = billboardColor; - texCoords = VertexPosition.xy + 0.5; - #else - vec2 billboardCorner = VertexTexCoord - 0.5; - vec2 billboardSize = VertexUserdata0.xy; - vec2 billboardSinCos = VertexUserdata0.zw; - - vec2 rotatedPosition; - rotatedPosition.x = billboardCorner.x*billboardSinCos.y - billboardCorner.y*billboardSinCos.x; - rotatedPosition.y = billboardCorner.y*billboardSinCos.y + billboardCorner.x*billboardSinCos.x; - rotatedPosition *= billboardSize; - - vec3 cameraRight = vec3(ViewMatrix[0][0], ViewMatrix[1][0], ViewMatrix[2][0]); - vec3 cameraUp = vec3(ViewMatrix[0][1], ViewMatrix[1][1], ViewMatrix[2][1]); - vec3 vertexPos = VertexPosition + cameraRight*rotatedPosition.x + cameraUp*rotatedPosition.y; - - gl_Position = ViewProjMatrix * vec4(vertexPos, 1.0); - texCoords = VertexTexCoord; - #endif - texCoords.y = 1.0 - texCoords.y; -#else - #if FLAG_INSTANCING - #if TRANSFORM - gl_Position = ViewProjMatrix * InstanceData0 * vec4(VertexPosition, 1.0); - #else - #if UNIFORM_VERTEX_DEPTH - gl_Position = InstanceData0 * vec4(VertexPosition.xy, VertexDepth, 1.0); - #else - gl_Position = InstanceData0 * vec4(VertexPosition, 1.0); - #endif - #endif - #else - #if TRANSFORM - gl_Position = WorldViewProjMatrix * vec4(VertexPosition, 1.0); - #else - #if UNIFORM_VERTEX_DEPTH - gl_Position = vec4(VertexPosition.xy, VertexDepth, 1.0); - #else - gl_Position = vec4(VertexPosition, 1.0); - #endif - #endif - #endif - - texCoords = VertexTexCoord; -#endif - - vColor = color; - -#if FLAG_INSTANCING - mat3 rotationMatrix = mat3(InstanceData0); -#else - mat3 rotationMatrix = mat3(WorldMatrix); -#endif - -#if COMPUTE_TBNMATRIX - vec3 binormal = cross(VertexNormal, VertexTangent); - vLightToWorld[0] = normalize(rotationMatrix * VertexTangent); - vLightToWorld[1] = normalize(rotationMatrix * binormal); - vLightToWorld[2] = normalize(rotationMatrix * VertexNormal); -#else - vNormal = normalize(rotationMatrix * VertexNormal); -#endif - -#if SHADOW_MAPPING - for (int i = 0; i < 3; ++i) - vLightSpacePos[i] = LightViewProjMatrix[i] * WorldMatrix * vec4(VertexPosition, 1.0); -#endif - -#if TEXTURE_MAPPING - vTexCoord = VertexTexCoord; -#endif - -#if PARALLAX_MAPPING - vViewDir = EyePosition - VertexPosition; - vViewDir *= vLightToWorld; -#endif - -#if !FLAG_DEFERRED - #if FLAG_INSTANCING - vWorldPos = vec3(InstanceData0 * vec4(VertexPosition, 1.0)); - #else - vWorldPos = vec3(WorldMatrix * vec4(VertexPosition, 1.0)); - #endif -#endif -} diff --git a/include/Nazara/Audio/Algorithm.hpp b/include/Nazara/Audio/Algorithm.hpp index de8fac319..27d1e5394 100644 --- a/include/Nazara/Audio/Algorithm.hpp +++ b/include/Nazara/Audio/Algorithm.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -8,9 +8,11 @@ #define NAZARA_ALGORITHM_AUDIO_HPP #include +#include namespace Nz { + inline UInt32 GetChannelCount(AudioFormat format); template void MixToMono(T* input, T* output, UInt32 channelCount, UInt64 frameCount); } diff --git a/include/Nazara/Audio/Algorithm.inl b/include/Nazara/Audio/Algorithm.inl index a2b5c5fe5..858195ef6 100644 --- a/include/Nazara/Audio/Algorithm.inl +++ b/include/Nazara/Audio/Algorithm.inl @@ -1,12 +1,53 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp +#include #include #include namespace Nz { + /*! + * \ingroup audio + * \brief Get the number of channels occupied by an audio format + * \returns The number of channels occupied by an audio format (mono returns 1, stero returns 2, etc.) + * + * \param format A valid audio format + * + * \remark The format must be valid (using AudioFormat::Unknown will trigger an error) + */ + UInt32 GetChannelCount(AudioFormat format) + { + NazaraAssert(format != AudioFormat::Unknown, "invalid audio format"); + + switch (format) + { + case AudioFormat::Unknown: //< Just to make the compiler stop complaining + break; + + case AudioFormat::I16_Mono: + return 1; + + case AudioFormat::I16_Stereo: + return 2; + + case AudioFormat::I16_Quad: + return 4; + + case AudioFormat::I16_5_1: + return 6; + + case AudioFormat::I16_6_1: + return 7; + + case AudioFormat::I16_7_1: + return 8; + } + + return 0; + } + /*! * \ingroup audio * \brief Mixes channels in mono diff --git a/include/Nazara/Audio/Audio.hpp b/include/Nazara/Audio/Audio.hpp index 848202970..affab10a9 100644 --- a/include/Nazara/Audio/Audio.hpp +++ b/include/Nazara/Audio/Audio.hpp @@ -1,4 +1,4 @@ -// Copyright (C) 2017 Jérôme Leclercq +// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Audio module" // For conditions of distribution and use, see copyright notice in Config.hpp @@ -10,46 +10,61 @@ #include #include #include +#include +#include +#include #include #include namespace Nz { - class NAZARA_AUDIO_API Audio + class NAZARA_AUDIO_API Audio : public ModuleBase