diff --git a/Content/Documentation/ScriptingAPI-Documentation.md b/Content/Documentation/ScriptingAPI-Documentation.md index cbd927e9f..92e04a15a 100644 --- a/Content/Documentation/ScriptingAPI-Documentation.md +++ b/Content/Documentation/ScriptingAPI-Documentation.md @@ -43,6 +43,11 @@ This is a reference and explanation of Lua scripting features in Wicked Engine. 1. [RenderPath2D](#renderpath2d) 2. [RenderPath3D](#renderpath3d) 3. [LoadingScreen](#loadingscreen) + 12. [Primitives](#primitives) + 1. [Ray](#ray) + 2. [AABB](#aabb) + 3. [Sphere](#sphere) + 4. [Capsule](#capsule) 12. [Input](#input) ## Introduction and usage @@ -682,7 +687,7 @@ It inherits functions from RenderPath2D. - AddLoadingTask(string taskScript) - OnFinished(string taskScript) -### Intersects +### Primitives #### Ray A ray is defined by an origin Vector and a normalized direction Vector. It can be used to intersect with other primitives or the scene diff --git a/Content/Documentation/WickedEngine-Documentation.md b/Content/Documentation/WickedEngine-Documentation.md index 0709c76dc..63255be94 100644 --- a/Content/Documentation/WickedEngine-Documentation.md +++ b/Content/Documentation/WickedEngine-Documentation.md @@ -5,7 +5,7 @@ This is a reference for the C++ features of Wicked Engine ## Contents 1. [High Level Interface](#high-level-interface) - 1. [MainComponent](#maincomponent) + 1. [Application](#application) 2. [RenderPath](#renderpath) 3. [RenderPath2D](#renderpath2d) 4. [RenderPath3D](#renderpath3d) @@ -13,8 +13,8 @@ This is a reference for the C++ features of Wicked Engine 1.[Denoiser](#denoiser) 10. [LoadingScreen](#loadingscreen) 2. [System](#system) - 1. [wiECS (Entity-Component System)](#wiecs) - 2. [wiScene](#wiscene) + 1. [Entity-Component System](#entity-component-system) + 2. [Scene System](#scene-system) 1. [NameComponent](#namecomponent) 2. [LayerComponent](#layercomponent) 3. [TransformComponent](#transformcomponent) @@ -38,13 +38,13 @@ This is a reference for the C++ features of Wicked Engine 21. [InverseKinematicsComponent](#inversekinematicscomponent) 22. [SpringComponent](#springcomponent) 23. [Scene](#scene) - 3. [wiJobSystem](#wijobsystem) - 4. [wiInitializer](#wiinitializer) - 5. [wiPlatform](#wiplatform) - 6. [wiEvent](#wievent) - 7. [wiCanvas](#wicanvas) + 3. [Job System](#job-system) + 4. [Initializer](#initializer) + 5. [Platform](#platform) + 6. [EventHandler](#event-handler) + 7. [Canvas](#canvas) 3. [Graphics](#graphics) - 1. [wiGraphics](#wigraphics) + 1. [Graphics API](#graphics-api) 1. [GraphicsDevice](#wigraphicsdevice) 1. [Debug device](#debug-device) 2. [Creating resources](#creating-resources) @@ -69,7 +69,7 @@ This is a reference for the C++ features of Wicked Engine 2. [GraphicsDevice_DX11](#wigraphicsdevice_dx11) 3. [GraphicsDevice_DX12](#wigraphicsdevice_dx12) 4. [GraphicsDevice_Vulkan](#wigraphicsdevice_vulkan) - 2. [wiRenderer](#wirenderer) + 2. [Renderer](#renderer) 1. [DrawScene](#drawscene) 2. [DrawScene_Transparent](#drawscene_transparent) 3. [Tessellation](#tessellation) @@ -89,40 +89,38 @@ This is a reference for the C++ features of Wicked Engine 16. [Debug Draw](#debug-draw) 17. [Animation Skinning](#animation-skinning) 18. [Custom Shaders](#custom-shaders) - 3. [wiEnums](#wienums) - 4. [wiImage](#wiimage) - 5. [wiFont](#wifont) - 6. [wiEmittedParticle](#wiemittedparticle) - 7. [wiHairParticle](#wihairparticle) - 8. [wiOcean](#wiocean) - 9. [wiSprite](#wisprite) - 10. [wiSpriteFont](#wispritefont) - 11. [wiGPUSortLib](#wigpusortlib) - 12. [wiGPUBVH](#wigpubvh) + 3. [Enums](#enums) + 4. [Image Renderer](#image-renderer) + 5. [Font Renderer](#font-renderer) + 6. [Emitted Particle System](#emitted-particle-system) + 7. [Hair Particle System](#hair-particle-system) + 8. [Ocean](#ocean) + 9. [Sprite](#sprite) + 10. [SpriteFont](#spritefont) + 11. [GPUSortLib](#gpusortlib) + 12. [GPUBVH](#gpubvh) 4. [GUI](#gui) - 1. [wiGUI](#wigui) - 2. [wiWidget](#wiwidget) - 3. [wiButton](#wibutton) - 4. [wiLabel](#wilabel) - 5. [wiTextInputField](#witextinputfield) - 6. [wiSlider](#wislider) - 7. [wiCheckBox](#wicheckbox) - 8. [wiComboBox](#wicombobox) - 9. [wiWindow](#wiwindow) - 10. [wiColorPicker](#wicolorpicker) + 1. [GUI](#gui) + 2. [Widget](#widget) + 3. [Button](#button) + 4. [Label](#label) + 5. [TextInputField](#textinputfield) + 6. [Slider](#slider) + 7. [CheckBox](#checkbox) + 8. [ComboBox](#combobox) + 9. [Window](#window) + 10. [ColorPicker](#colorpicker) + 11. [TreeList](#treelist) 5. [Helpers](#helpers) - 1. [wiAllocators](#wiallocators) - 1. [LinearAllocator](#linearallocator) - 1. [ThreadSafeRingBuffer](#threadsaferingbuffer) - 2. [wiArchive](#wiarchive) - 3. [wiColor](#wicolor) - 5. [wiFadeManager](#wifademanager) - 6. [wiHelper](#wihelper) - 7. [wiIntersect](#wiintersect) + 2. [Archive](#archive) + 3. [Color](#color) + 5. [FadeManager](#fademanager) + 6. [Helper](#helper) + 7. [Primitive](#primitive) 1. [AABB](#aabb) - 2. [SPHERE](#sphere) - 2. [CAPSULE](#capsule) - 3. [RAY](#ray) + 2. [Sphere](#sphere) + 2. [Capsule](#capsule) + 3. [Ray](#ray) 4. [Frustum](#frustum) 5. [Hitbox2D](#hitbox2d) 8. [wiMath](#wimath) @@ -130,32 +128,28 @@ This is a reference for the C++ features of Wicked Engine 10. [wiRectPacker](#wirectpacker) 11. [wiResourceManager](#wiresourcemanager) 12. [wiSpinLock](#wispinlock) - 13. [wiStartupArguments](#wistartuparguments) + 13. [wiArguments](#wiarguments) 14. [wiTimer](#witimer) 6. [Input](#input) 7. [Audio](#audio) - 1. [wiAudio](#wiaudio) - 2. [Sound](#sound) - 3. [SoundInstance](#soundinstance) - 4. [SoundInstance3D](#soundinstance3d) - 5. [SUBMIX_TYPE](#submix_type) - 6. [REVERB_PRESET](#reverb_preset) + 1. [Sound](#sound) + 2. [SoundInstance](#soundinstance) + 3. [SoundInstance3D](#soundinstance3d) + 4. [SUBMIX_TYPE](#submix_type) + 5. [REVERB_PRESET](#reverb_preset) 8. [Physics](#physics) - 1. [wiPhysicsEngine](#wiphysicsengine) - 1. [Rigid Body Physics](#rigid-body-physics) - 2. [Soft Body Physics](#soft-body-physics) - 2. [wiPhysicsEngine_BULLET](#wiphysicsengine_bullet) + 1. [Rigid Body Physics](#rigid-body-physics) + 2. [Soft Body Physics](#soft-body-physics) 9. [Network](#network) - 1. [wiNetwork](#winetwork) 2. [Socket](#socket) 3. [Connection](#connection) 10. [Scripting](#scripting) - 1. [wiLua](#wilua) - 2. [wiLua_Globals](#wilua_globals) - 3. [wiLuna](#wiluna) + 1. [Lua](#lua) + 2. [Lua_Globals](#lua_globals) + 3. [Luna](#luna) 11. [Tools](#tools) - 1. [wiBacklog](#wibacklog) - 2. [wiProfiler](#wiprofiler) + 1. [Backlog](#backlog) + 2. [Profiler](#profiler) 12. [Shaders](#shaders) 1. [Interop](#interop) 1. [ConstantBufferMapping](#constantbuffermapping) @@ -168,14 +162,14 @@ This is a reference for the C++ features of Wicked Engine ## High Level Interface The high level interface consists of classes that allow for extending the engine with custom functionality. This is usually done by overriding the classes. -### MainComponent -[[Header]](../../WickedEngine/MainComponent.h) [[Cpp]](../../WickedEngine/MainComponent.cpp) +### Application +[[Header]](../../WickedEngine/wiApplication.h) [[Cpp]](../../WickedEngine/wiApplication.cpp) This is the main runtime component that has the Run() function. It should be included in the application entry point while calling Run() in an infinite loop.
The user should call the SetWindow() function to associate it with a window of the operating system. This window will be used to render to.
-The MainComponent has many uses that the user is not necessarily interested in. The most important part is that it manages the RenderPaths. There can be one active RenderPath at a time, which will be updated and rendered to the screen every frame. However, because a RenderPath is a highly customizable class, there is no limitation what can be done within the RenderPath, for example supporting multiple concurrent RenderPaths if required. RenderPaths can be switched wit ha Fade out screen easily. Loading Screen can be activated as an active Renderpath and it will load and switch to an other RenderPath if desired. A RenderPath can be simply activated with the MainComponent::ActivatePath() function.
-The MainComponent does the following every frame while it is running:
+The `Application` has many uses that the user is not necessarily interested in. The most important part is that it manages the RenderPaths. There can be one active RenderPath at a time, which will be updated and rendered to the screen every frame. However, because a RenderPath is a highly customizable class, there is no limitation what can be done within the RenderPath, for example supporting multiple concurrent RenderPaths if required. RenderPaths can be switched wit ha Fade out screen easily. Loading Screen can be activated as an active Renderpath and it will load and switch to an other RenderPath if desired. A RenderPath can be simply activated with the `Application::ActivatePath()` function.
+The `Application` does the following every frame while it is running:
1. FixedUpdate()
-Calls FixedUpdate for the active RenderPath and wakes up scripts that are waiting for fixedupdate(). The frequency off calls will be determined by MainComponent::setTargetFrameRate(float framespersecond). By default (parameter = 60), FixedUpdate will be called 60 times per second. +Calls FixedUpdate for the active RenderPath and wakes up scripts that are waiting for fixedupdate(). The frequency off calls will be determined by `Application::setTargetFrameRate(float framespersecond)`. By default (parameter = 60), FixedUpdate will be called 60 times per second. 2. Update(float deltatime)
Calls Update for the active RenderPath and wakes up scripts that are waiting for update() 3. Render()
@@ -184,13 +178,13 @@ Calls Render for the active RenderPath and wakes up scripts that are waiting for Calls Compose for the active RenderPath ### RenderPath -[[Header]](../../WickedEngine/RenderPath.h) -This is an empty base class that can be activated with a MainComponent. It calls its Start(), Update(), FixedUpdate(), Render(), Compose(), Stop() functions as needed. Override this to perform custom gameplay or rendering logic. The RenderPath inherits from [wiCanvas](#wicanvas), and the canvas properties will be set by the [MainComponent](#maincomponent) when the RenderPath was activated, and while the RenderPath is active.
+[[Header]](../../WickedEngine/wiRenderPath.h) +This is an empty base class that can be activated with a `Application`. It calls its Start(), Update(), FixedUpdate(), Render(), Compose(), Stop() functions as needed. Override this to perform custom gameplay or rendering logic. The RenderPath inherits from [wiCanvas](#wicanvas), and the canvas properties will be set by the [Application](#application) when the RenderPath was activated, and while the RenderPath is active.
The order in which the functions are executed every frame:
1. PreUpdate()
This will be called once per frame before any script that calls Update(). 2. FixedUpdate()
-This will be called in a manner that is deterministic, so logic will be running in the frequency that is specified with MainComponent::setTargetFrameRate(float framespersecond) +This will be called in a manner that is deterministic, so logic will be running in the frequency that is specified with `Application::setTargetFrameRate(float framespersecond)` 3. Update(float deltatime)
This will be called once per frame, and the elapsed time in seconds since the last Update() is provided as parameter 4. PostUpdate()
@@ -204,19 +198,19 @@ Apart from the functions that will be run every frame, the RenderPath has the fo 1. Load()
Intended for loading resources before the first time the RenderPath will be used. It will be callsed by [LoadingScreen](#loadingscreen) to load resources in the background. 2. Start()
-Start will always be called when a RenderPath is activated by the MainComponent +Start will always be called when a RenderPath is activated by the `Application` 3. Stop()
-Stop will be always called when the current RenderPath was the active one in MainComponent, but an other one was activated. +Stop will be always called when the current RenderPath was the active one in `Application`, but an other one was activated. ### RenderPath2D -[[Header]](../../WickedEngine/RenderPath2D.h) [[Cpp]](../../WickedEngine/RenderPath2D.cpp) +[[Header]](../../WickedEngine/wiRenderPath2D.h) [[Cpp]](../../WickedEngine/wiRenderPath2D.cpp) Capable of handling 2D rendering to offscreen buffer in Render() function, or just the screen in Compose() function. It has some functionality to render wiSprite and wiSpriteFont onto rendering layers and stenciling with 3D rendered scene. It has a [GUI](#gui) that is automatically updated and rendered if any elements have been added to it. ### RenderPath3D -[[Header]](../../WickedEngine/RenderPath3D.h) [[Cpp]](../../WickedEngine/RenderPath3D.cpp) +[[Header]](../../WickedEngine/wiRenderPath3D.h) [[Cpp]](../../WickedEngine/wiRenderPath3D.cpp) Base class for implementing 3D rendering paths. It also supports everything that the Renderpath2D does. -The post process chain is also implemented here. This means that the order of the post processes and the resources that they use are defined here, but the individual post process rendering on a lower level is implemented in the `wiRenderer` as core engine features. Read more about post process implementation in the [wiRenderer section](#post-processing). +The post process chain is also implemented here. This means that the order of the post processes and the resources that they use are defined here, but the individual post process rendering on a lower level is implemented in the `wi::renderer` as core engine features. Read more about post process implementation in the [wi::renderer section](#post-processing). The post process chain is implemented in `RenderPath3D::RenderPostprocessChain()` function and divided into multiple parts: - HDR
@@ -229,19 +223,19 @@ These are running in more specific locations, depending on the render path. For The HDR and LDR post process chain are using the "ping-ponging" technique, which means when the first post process consumes texture1 and produces texture2, then the following post process will consume texture2 and produce texture1, until all post processes are rendered. ### RenderPath3D_PathTracing -[[Header]](../../WickedEngine/RenderPath3D_PathTracing.h) [[Cpp]](../../WickedEngine/RenderPath3D_PathTracing.cpp) -Implements a compute shader based path tracing solution. In a static scene, the rendering will converge to ground truth. When something changes in the scene (something moves, ot material changes, etc...), the convergence will be restarted from the beginning. The raytracing is implemented in [wiRenderer](#wirenderer) and multiple [shaders](#shaders). The ray tracing is available on any GPU that supports compute shaders. +[[Header]](../../WickedEngine/wiRenderPath3D_PathTracing.h) [[Cpp]](../../WickedEngine/wiRenderPath3D_PathTracing.cpp) +Implements a compute shader based path tracing solution. In a static scene, the rendering will converge to ground truth. When something changes in the scene (something moves, ot material changes, etc...), the convergence will be restarted from the beginning. The raytracing is implemented in [wi::renderer](#wi::renderer) and multiple [shaders](#shaders). The ray tracing is available on any GPU that supports compute shaders. #### Denoiser To enable denoising for path traced images, you can use the [Open Image Denoise library](https://github.com/OpenImageDenoise/oidn). To enable this functionality, the engine will try to include the "OpenImageDenoise/oidn.hpp" file. If this file could be included, it will attampt to link with OpenImageDenoise.lib and tbb.lib. It is also required to provide the OpenImageDenoise.dll and tbb.dll near the exe to correctly launch the application after this. If you satisfy these steps, the denoiser will work automatically after the path tracer reached the target sample count. The final path traced image will be denoised and presented to the screen. ### LoadingScreen -[[Header]](../../WickedEngine/LoadingScreen.h) [[Cpp]](../../WickedEngine/LoadingScreen.cpp) +[[Header]](../../WickedEngine/wiLoadingScreen.h) [[Cpp]](../../WickedEngine/wiLoadingScreen.cpp) Render path that can be easily used for loading screen. It is able to load content or RenderPath in the background and switch to an other RenderPath onceit finished. ## System You can find out more about the Entity-Component system and other engine-level systems under ENGINE/System filter in the solution. -### wiECS +### Entity-Component System [[Header]](../../WickedEngine/wiECS.h) #### ComponentManager @@ -250,11 +244,11 @@ This is the core entity-component relationship handler class. The purpose of thi #### Entity Entity is a number, it can reference components through ComponentManager containers. An entity is always valid if it exists. It's not required that an entity has any components. An entity has a component, if there is a ComponentManager that has a component which is associated with the same entity. -### wiScene +### Scene System [[Header]](../../WickedEngine/wiScene.h) [[Cpp]](../../WickedEngine/wiScene.cpp) The logical scene representation using the Entity-Component System - GetScene
-Returns a global scene instance. The wiRenderer will use this scene instance to render the scene. The user can create multiple scenes as well, and merge those into the global scene so that those will be rendered as well. +Returns a global scene instance. The wi::renderer will use this scene instance to render the scene. The user can create multiple scenes as well, and merge those into the global scene so that those will be rendered as well. - LoadModel()
There are two flavours to this. One of them immediately loads into the global scene. The other loads into a custom scene, which is usefult to manage the contents separately. This function will return an Entity that represents the root transform of the scene - if the attached parameter was true, otherwise it will return INVALID_ENTITY and no root transform will be created. - Pick
@@ -376,11 +370,11 @@ An entity can have a `SpringComponent` to achieve a "jiggle" or "soft" animation #### Scene [[Header]](../../WickedEngine/wiScene.h) [[Cpp]](../../WickedEngine/wiScene.cpp) -A scene is a collection of component arrays. The scene is updating all the components in an efficient manner using the [job system](#wijobsystem). It can be serialized and saved/loaded from disk efficiently. +A scene is a collection of component arrays. The scene is updating all the components in an efficient manner using the [job system](#job-system). It can be serialized and saved/loaded from disk efficiently. - Update(float deltatime)
This function runs all the requied systems to update all components contained within the Scene. -### wiJobSystem +### Job System [[Header]](../../WickedEngine/wiJobSystem.h) [[Cpp]](../../WickedEngine/wiJobSystem.cpp) Manages the execution of concurrent tasks - context
@@ -392,11 +386,11 @@ This will schedule a task for execution on multiple parallel threads for a given - Wait
This function will block until all jobs have finished for a given workload. The current thread starts working on any work left to be finished. -### wiInitializer +### Initializer [[Header]](../../WickedEngine/wiInitializer.h) [[Cpp]](../../WickedEngine/wiInitializer.cpp) Initializes all engine systems either in a blocking or an asynchronous way. -### wiPlatform +### Platform [[Header]](../../WickedEngine/wiPlatform.h) You can get native platform specific handles here, such as window handle. - GetWindow
@@ -404,20 +398,20 @@ Returns the platform specific window handle - IsWindowActive
Returns true if the current window is the topmost one, false if it is not in focus -### wiEvent -[[Header]](../../WickedEngine/wiEvent.h) +### Event Handler +[[Header]](../../WickedEngine/wiEventHandler.h) The event system can be used to execute system-wide tasks. Any system can "subscribe" to events and any system can "fire" events. - Subscribe
The first parameter is the event ID. Core system events are negative numbers. The user can choose any positive number to create custom events. The second parameter is a function to be executed, with a userdata argument. The userdata argument can hold any custom data that the user desires. -The return value is a wiEvent::Handle type. When this is object is destroyed, the event is subscription for the function will be removed. +The return value is a `wi::eventhandler::Handle` type. When this is object is destroyed, the event is subscription for the function will be removed. Multiple functions can be subscribed to a single event ID. - FireEvent
The first argument is the event id, that says which events to invoke. The second argument will be passed to the subscribed event's userdata parameter. All events that are subsribed to the specified event id will run immediately at the time of the call of FireEvent. The order of execution among events is the order of which they were subscribed. -### wiCanvas +### Canvas [[Header]](../../WickedEngine/wiCanvas.h) The canvas specifies a DPI-aware drawing area. Use the GetLogical... functions to get parameters with DPI aware scale factors applied. Use the GetPhysical... functions to get the real pixel counts. @@ -425,7 +419,7 @@ The canvas specifies a DPI-aware drawing area. Use the GetLogical... functions t ## Graphics Everything related to rendering graphics will be discussed below -### wiGraphics +### Graphics API [[Header]](../../WickedEngine/wiGraphics.h) The graphics API wrappers @@ -705,12 +699,12 @@ The DirectX11 interface has been removed after version 0.56 [[Header]](../../WickedEngine/wiGraphicsDevice_DX12.h) [[Cpp]](../../WickedEngine/wiGraphicsDevice_DX12.cpp) DirectX12 implementation for rendering interface -#### wiGraphicsDevice_Vulkan +#### GraphicsDevice_Vulkan [[Header]](../../WickedEngine/wiGraphicsDevice_Vulkan.h) [[Cpp]](../../WickedEngine/wiGraphicsDevice_Vulkan.cpp) Vulkan implementation for rendering interface -### wiRenderer +### Renderer [[Header]](../../WickedEngine/wiRenderer.h) [[Cpp]](../../WickedEngine/wiRenderer.cpp) This is a collection of graphics technique implentations and functions to draw a scene, shadows, post processes and other things. It is also the manager of the GraphicsDevice instance, and provides other helper functions to load shaders from files on disk. @@ -731,15 +725,15 @@ The `flags` argument can contain various modifiers that determine what kind of o - `DRAWSCENE_OPAQUE`: Opaque object will be rendered - `DRAWSCENE_TRANSPARENT`: Transparent objects will be rendered. Objects will be sorted back-to front, for blending purposes -- `DRAWSCENE_OCCLUSIONCULLING`: Occluded objects won't be rendered. [Occlusion culling](#occlusion-culling) can be globally switched on/off using `wiRenderer::SetOcclusionCullingEnabled()` -- `DRAWSCENE_TESSELLATION`: Enable [tessellation](#tessellation) (if hardware supports it). [Tessellation](#tessellation) can be globally switched on/off using `wiRenderer::SetTessellationEnabled()` +- `DRAWSCENE_OCCLUSIONCULLING`: Occluded objects won't be rendered. [Occlusion culling](#occlusion-culling) can be globally switched on/off using `wi::renderer::SetOcclusionCullingEnabled()` +- `DRAWSCENE_TESSELLATION`: Enable [tessellation](#tessellation) (if hardware supports it). [Tessellation](#tessellation) can be globally switched on/off using `wi::renderer::SetTessellationEnabled()` - `DRAWSCENE_HAIRPARTICLE`: Draw hair particles #### Tessellation Tessellation can be used when rendering objects. Tessellation requires a GPU hardware feature and can enable displacement mapping on vertices or smoothing mesh silhouettes dynamically while rendering objects. Tessellation will be used when `tessellation` parameter to the [DrawScene](#drawscene) was set to `true` and the GPU supports the tessellation feature. Tessellation level can be specified per [MeshComponent](#meshcomponent)'s `tessellationFactor` parameter. Tessellation level will be modulated by distance from camera, so that tessellation factor will fade out on more distant objects. Greater tessellation factor means more detailed geometry will be generated. #### Occlusion Culling -Occlusion culling is a technique to determine which objects are within the camera, but are completely behind an other objects, such that they wouldn't be rendered. The depth buffer already does occlusion culling on the GPU, however, we would like to perform this earlier than submitting the mesh to the GPU for drawing, so essentially do the occlusion culling on CPU. A hybrid approach is used here, which uses the results from a previously rendered frame (that was rendered by GPU) to determine if an object will be visible in the current frame. For this, we first render the object into the previous frame's depth buffer, and use the previous frame's camera matrices, however, the current position of the object. In fact, we only render bounding boxes instead of objects, for performance reasons. Occlusion queries are used while rendering, and the CPU can read the results of the queries in a later frame. We keep track of how many frames the object was not visible, and if it was not visible for a certain amount, we omit it from rendering. If it suddenly becomes visible later, we immediately enable rendering it again. This technique means that results will lag behind for a few frames (latency between cpu and gpu and latency of using previous frame's depth buffer). These are implemented in the functions `wiRenderer::OcclusionCulling_Render()` and `wiRenderer::OcclusionCulling_Read()`. +Occlusion culling is a technique to determine which objects are within the camera, but are completely behind an other objects, such that they wouldn't be rendered. The depth buffer already does occlusion culling on the GPU, however, we would like to perform this earlier than submitting the mesh to the GPU for drawing, so essentially do the occlusion culling on CPU. A hybrid approach is used here, which uses the results from a previously rendered frame (that was rendered by GPU) to determine if an object will be visible in the current frame. For this, we first render the object into the previous frame's depth buffer, and use the previous frame's camera matrices, however, the current position of the object. In fact, we only render bounding boxes instead of objects, for performance reasons. Occlusion queries are used while rendering, and the CPU can read the results of the queries in a later frame. We keep track of how many frames the object was not visible, and if it was not visible for a certain amount, we omit it from rendering. If it suddenly becomes visible later, we immediately enable rendering it again. This technique means that results will lag behind for a few frames (latency between cpu and gpu and latency of using previous frame's depth buffer). These are implemented in the functions `wi::renderer::OcclusionCulling_Render()` and `wi::renderer::OcclusionCulling_Read()`. #### Shadow Maps The `DrawShadowmaps()` function will render shadow maps for each active dynamic light that are within the camera [frustum](#frustum). There are two types of shadow maps, 2D and Cube shadow maps. The maximum number of usable shadow maps are set up with calling `SetShadowProps2D()` or `SetShadowPropsCube()` functions, where the parameters will specify the maximum number of shadow maps and resolution. The shadow slots for each light must be already assigned, because this is a rendering function and is not allowed to modify the state of the [Scene](#scene) and [lights](#lightcomponent). The shadow slots will be set up in the [UpdatePerFrameData()](#updateperframedata) function that is called every frame by the `RenderPath3D`. @@ -752,26 +746,26 @@ Begin rendering the frame on GPU. This means that GPU compute jobs are kicked, s #### Ray tracing (hardware accelerated) -Hardware accelerated ray tracing API is now available, so a variety of renderer features are available using that. If the hardware support is available, the `Scene` will allocate a top level acceleration structure, and the meshes will allocate bottom level acceleration structures for themselves. Updating these is done by simply calling `wiRenderer::UpdateRaytracingAccelerationStructures(cmd)`. The updates will happen on the GPU timeline, so provide a [CommandList](#work-submission) as argument. The top level acceleration structure will be rebuilt from scratch. The bottom level acceleration structures will be rebuilt from scratch once, and then they will be updated (refitted). +Hardware accelerated ray tracing API is now available, so a variety of renderer features are available using that. If the hardware support is available, the `Scene` will allocate a top level acceleration structure, and the meshes will allocate bottom level acceleration structures for themselves. Updating these is done by simply calling `wi::renderer::UpdateRaytracingAccelerationStructures(cmd)`. The updates will happen on the GPU timeline, so provide a [CommandList](#work-submission) as argument. The top level acceleration structure will be rebuilt from scratch. The bottom level acceleration structures will be rebuilt from scratch once, and then they will be updated (refitted). After the acceleration structures are updated, ray tracing shaders can use it after binding to a shader resource slot. #### Ray tracing (legacy) -Ray tracing can be used in multiple ways to render the scene. The `RayTraceScene()` function will render the scene with the rays that are provided as the `RayBuffers` type argument. For example, to render the scene from the camera perspective, first create rays that originate from the camera and shoot towards the caera far plane for every pixel. The `GenerateScreenRayBuffers()` helper function implements this functionality, by expecting a [CameraComponent](#cameracomponent) argument and returns a `RayBuffers` structure. The result will be written to a texture that is provided as parameter. The texture must have been created with `UNORDERED_ACCESS` bind flags, because it will be written in compute shaders. The scene BVH structure must have been already built to use this, it can be accomplished by calling [wiRenderer::BuildSceneBVH()](#build-scene-bvh). The [RenderPath3D_Pathracing](#renderpath3d_pathtracing) uses this ray tracing functionality to render a path traced scene. +Ray tracing can be used in multiple ways to render the scene. The `RayTraceScene()` function will render the scene with the rays that are provided as the `RayBuffers` type argument. For example, to render the scene from the camera perspective, first create rays that originate from the camera and shoot towards the caera far plane for every pixel. The `GenerateScreenRayBuffers()` helper function implements this functionality, by expecting a [CameraComponent](#cameracomponent) argument and returns a `RayBuffers` structure. The result will be written to a texture that is provided as parameter. The texture must have been created with `UNORDERED_ACCESS` bind flags, because it will be written in compute shaders. The scene BVH structure must have been already built to use this, it can be accomplished by calling [wi::renderer::BuildSceneBVH()](#build-scene-bvh). The [RenderPath3D_Pathracing](#renderpath3d_pathtracing) uses this ray tracing functionality to render a path traced scene. Other than path tracing, the scene BVH can be rendered by using the `RayTraceSceneBVH` function. This will render the bounding box hierarchy to the screen as a heatmap. Blue colors mean that few boxes were hit per pixel, and with more bounding box hits the colors go to green, yellow, red, and finaly white. This is useful to determine how expensive a the scene is with regards to ray tracing performance. -The lightmap baking is also using ray tracing on the GPU to precompute static lighting for objects in the scene. [Objects](#objectcomponent) that contain lightmap atlas texture coordinate set can start lightmap rendering by setting `ObjectComponent::SetLightmapRenderRequest(true)`. Every object that have this flag set will have their lightmaps updated by performing ray traced rendering by the [wiRenderer](#wirenderer) internally. Lightmap texture coordinates can be generated by a separate tool, such as the Wicked Engine Editor application. Lightmaps will be rendered to a global lightmap atlas that can be used by all shaders to read static lighting data. The global lightmap atlas texture contains lightmaps from all objects inside the scene in a compact format for performance. Apart from that, each object contains its own lightmap in a full precision texture format that can be post-processed and saved to disc for later use. To denoise lightmaps, follow the same steps as the path tracer denoiser setup described in the [Denoiser](#denoiser) section. +The lightmap baking is also using ray tracing on the GPU to precompute static lighting for objects in the scene. [Objects](#objectcomponent) that contain lightmap atlas texture coordinate set can start lightmap rendering by setting `ObjectComponent::SetLightmapRenderRequest(true)`. Every object that have this flag set will have their lightmaps updated by performing ray traced rendering by the [wi::renderer](#wi::renderer) internally. Lightmap texture coordinates can be generated by a separate tool, such as the Wicked Engine Editor application. Lightmaps will be rendered to a global lightmap atlas that can be used by all shaders to read static lighting data. The global lightmap atlas texture contains lightmaps from all objects inside the scene in a compact format for performance. Apart from that, each object contains its own lightmap in a full precision texture format that can be post-processed and saved to disc for later use. To denoise lightmaps, follow the same steps as the path tracer denoiser setup described in the [Denoiser](#denoiser) section. #### Scene BVH -The scene BVH can be rebuilt from scratch using the `wiRenderer::BuildSceneBVH()` function. This will use the global scene to build the BVH hierarchy and global material atlases. The [ray tracing](#ray-tracing) features require the scene BVH to be built before using them. This is using the [wiGPUBVH](#wigpubvh) facility to build the BVH using compute shaders running on the GPU. +The scene BVH can be rebuilt from scratch using the `wi::renderer::BuildSceneBVH()` function. This will use the global scene to build the BVH hierarchy and global material atlases. The [ray tracing](#ray-tracing) features require the scene BVH to be built before using them. This is using the [wiGPUBVH](#wigpubvh) facility to build the BVH using compute shaders running on the GPU. #### Decals The [DecalComponents](#decalcomponent) in the scene can be rendered differently based on the rendering technique that is being used. The two main rendering techinques are forward and deferred rendering. Forward rendering is aimed at low bandwidth consumption, so the scene lighting is computed in one rendering pass, right when rendering the scene objects to the screen. In this case, all of the decals are also processed in the object rendering shaders automatically. In this case a decal atlas will need to be generated, because all decal textures must be available to sample in a single shader, but this is handled automatically inside the [UpdateRenderData](#updaterenderdata) function. -Deferred rendering techniques are outputting G-buffers, and compute lighting in a separate pass that is decoupled from the object rendering pass. Decals are rendered one by one on top of the albedo buffer using the function `wiRenderer::DrawDeferredDecals()`. All the lighting will be computed on top after the decals were rendered to the albedo in a separate render pass to complete the final scene. +Deferred rendering techniques are outputting G-buffers, and compute lighting in a separate pass that is decoupled from the object rendering pass. Decals are rendered one by one on top of the albedo buffer using the function `wi::renderer::DrawDeferredDecals()`. All the lighting will be computed on top after the decals were rendered to the albedo in a separate render pass to complete the final scene. #### Environment probes [EnvironmentProbeComponents](#environmentprobecomponent) can be placed into the scene and if they are tagged as invalid using the `EnvironmentProbeComponent::SetDirty(true)` flag, they will be rendered to a cubemap array that is accessible in all shaders. They will also be rendered in real time every frame if the `EnvironmentProbeComponent::SetRealTime(true)` flag is set. The cubemaps of these contain indirect specular information from a point source that can be used as approximate reflections for close by objects. @@ -779,7 +773,7 @@ The [DecalComponents](#decalcomponent) in the scene can be rendered differently The probes also must have [TransformComponent](#transformcomponent) associated to the same entity. This will be used to position the probes in the scene, but also to scale and rotate them. The scale/position/rotation defines an oriented bounding box (OBB) that will be used to perform parallax corrected environment mapping. This means that reflections inside the box volume will not appear as infinitely distant, but constrained inside the volume, to achieve more believable illusion. #### Post processing -There are several post processing effects implemented in the `wiRenderer`. They are all implemented in a single function with their name starting with Postprocess_, like for example: `wiRenderer::Postprocess_SSAO()`. They are aimed to be stateless functions, with their function signature clearly indicating input-output parameters and resources. +There are several post processing effects implemented in the `wi::renderer`. They are all implemented in a single function with their name starting with Postprocess_, like for example: `wi::renderer::Postprocess_SSAO()`. They are aimed to be stateless functions, with their function signature clearly indicating input-output parameters and resources. The chain/order of post processes is not implemented here, only the single effects themselves. The order of post proceses is more of a user responsibility, so it should be implemented in the [High Ievel Interface](#high-level-interface). For reference, a default post processchain is implemented in [RenderPath3D::RenderPostProcessChain()](#renderpath3d) function. @@ -788,22 +782,22 @@ Instanced rendering will be always used automatically when rendering objects. Th [ObjectComponents](#objectcomponent) can override [stencil](#stencil) settings for the [material](#materialcomponent). In case multiple [ObjectComponents](#objectcomponent) share the same mesh, but some are using different stencil overrides, those could be removed from the instanced batch, so there is some overhead to modifying stencil overrides for objects. -Tip: to find out more about how instancing is used to batch objects together, take a look at the `RenderMeshes()` function inside [wiRenderer.cpp](../WickedEngine/wiRenderer.cpp) +Tip: to find out more about how instancing is used to batch objects together, take a look at the `RenderMeshes()` function inside [wi::renderer.cpp](../WickedEngine/wi::renderer.cpp) #### Stencil If a depth stencil buffer is bound when using [DrawScene()](#drawscene), or [DrawScene_Transparent()](#drawscene_transparent), the stencil buffer will be written. The stencil is a 8-bit mask that can be used to achieve different kinds of screen space effects for different objects. [MaterialComponents](#materialcomponent) and [ObjectComponents](#objectcomponent) have the ability to set the stencil value that will be rendered. The 8-bit stencil value is separated into two parts: - The first 4 bits are reseved for engine-specific values, such as to separate skin, sky, common materials from each other. these values are contained in [wiEnums](#wienums) in the `STENCILREF` enum. - The last 4 bits are reserved for user stencil values. The application can decide what it wants to use these for. -Please use the `wiRenderer::CombineStencilrefs()` function to specify stencil masks in a future-proof way. +Please use the `wi::renderer::CombineStencilrefs()` function to specify stencil masks in a future-proof way. The [Pipeline States](#pipeline-states) have a `DepthStencilState` type member which will control how the stencil mask is used in the graphics pipeline for any custom rendering effect. The functionality is supposed to be equivalent and closely matching of what DirectX 11 provides, so for further information, refer to the [DirectX 11 documentation of Depth Stencil States](https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-depth-stencil). #### Loading Shaders -While the [GraphicsDevice is responsible of creating shaders and pipeline states](#pipeline-states-and-shaders), loading the shader files themselves are not handled by the graphics device. The `wiRenderer::LoadShader(ShaderStage::)` is a helper function that provides this feature. This is internally loading shaders from a common shader path, that is by default the "../WickedEngine/shaders" directory (relative to the application working directory), so the filename provided to this function must be relative to that path. Every system in the engine that loads shaders uses this function to load shaders from the same folder, which makes it very easy to reload shaders on demand with the `wiRenderer::ReloadShaders()` function. This is useful for when the developer modifies a shader and recompiles it, the engine can reload it while the application is running. The developer can modify the common shader path with the `wiRenderer::SetShaderPath()` to any path of preference. The developer is free to load shaders with a custom loader, from any path too, but the `wiRenderer::ReloadShaders()` functionality might not work in that case for those shaders. +While the [GraphicsDevice is responsible of creating shaders and pipeline states](#pipeline-states-and-shaders), loading the shader files themselves are not handled by the graphics device. The `wi::renderer::LoadShader(ShaderStage::)` is a helper function that provides this feature. This is internally loading shaders from a common shader path, that is by default the "../WickedEngine/shaders" directory (relative to the application working directory), so the filename provided to this function must be relative to that path. Every system in the engine that loads shaders uses this function to load shaders from the same folder, which makes it very easy to reload shaders on demand with the `wi::renderer::ReloadShaders()` function. This is useful for when the developer modifies a shader and recompiles it, the engine can reload it while the application is running. The developer can modify the common shader path with the `wi::renderer::SetShaderPath()` to any path of preference. The developer is free to load shaders with a custom loader, from any path too, but the `wi::renderer::ReloadShaders()` functionality might not work in that case for those shaders. #### Debug Draw -Debug geometry can be rendered by calling the `wiRenderer::DrawDebugWorld()` function and setting up debug geometries, or enabling debug features. The `DrawDebugWorld()` is already called by [RenderPath3D](#renderpath3d), so the developer can simply just worry about configure debug drawing features and add debug geometries and drawing will happen at the right place (if the developer decided to use [RenderPath3D](#renderpath3d) in their application). +Debug geometry can be rendered by calling the `wi::renderer::DrawDebugWorld()` function and setting up debug geometries, or enabling debug features. The `DrawDebugWorld()` is already called by [RenderPath3D](#renderpath3d), so the developer can simply just worry about configure debug drawing features and add debug geometries and drawing will happen at the right place (if the developer decided to use [RenderPath3D](#renderpath3d) in their application). The user provided debug geometry features at present are: - `DrawBox()`: provide a transformation matrix and color to render a wireframe box mesh with the desired transformation and color. The box will be only rendered for a single frame. @@ -822,19 +816,18 @@ Configuring other debug rendering functionality: - `SetToDrawDebugCameras()`: Cameras will be rendered as oriented boxes. #### Animation Skinning -[MeshComponents](#meshcomponent) that have their `armatureID` associated with an [ArmatureComponent](#armaturecomponent) will be skinned inside the `wiRenderer::UpdateRenderData()` function. This means that their vertex buffer will be animated with compute shaders, and the animated vertex buffer will be used throughout the rest of the frame. +[MeshComponents](#meshcomponent) that have their `armatureID` associated with an [ArmatureComponent](#armaturecomponent) will be skinned inside the `wi::renderer::UpdateRenderData()` function. This means that their vertex buffer will be animated with compute shaders, and the animated vertex buffer will be used throughout the rest of the frame. -If the [ArmatureComponent](#armaturecomponent) has less than `SKINNING_COMPUTE_THREADCOUNT` amount of bones, an optimized version of the skinning will be performed that uses shared memory. The user can disable this with the `wiRenderer::SetLDSSkinningEnabled()` function if the optimization proves to be worse on the target platform. #### Custom Shaders -Apart from the built in material shaders, the developer can create a library of custom shaders from the application side and assign them to materials. The `wiRenderer::RegisterCustomShader()` function is used to register a custom shader from the application. The function returns the ID of the custom shader that can be input to the `MaterialComponent::SetCustomShaderID()` function. +Apart from the built in material shaders, the developer can create a library of custom shaders from the application side and assign them to materials. The `wi::renderer::RegisterCustomShader()` function is used to register a custom shader from the application. The function returns the ID of the custom shader that can be input to the `MaterialComponent::SetCustomShaderID()` function. The custom shader is essentially the combination of a [Pipeline State Object](#pipeline-states-and-shaders) for each `RENDERPASS` and a `RENDERTYPE` flag that specifies whether it is to be drawn in a transparent or opaque, or other kind of pass within a `RENDERPASS`. The developer is responsible of creating a fully valid pipeline state to render a mesh. If a pipeline state is left as empty for a combination of `RENDERPASS` and `RENDERTYPE`, then the material will simply be skipped and not rendered. -### wiEnums +### Enums [[Header]](../../WickedEngine/wiEnums.h) -This is a collection of enum values used by the wiRenderer to identify graphics resources. Usually arrays of the same resource type are declared and the XYZENUM_COUNT values tell the length of the array. The other XYZENUM_VALUE represents a single element within that array. This makes the code easy to manage, for example: +This is a collection of enum values used by the wi::renderer to identify graphics resources. Usually arrays of the same resource type are declared and the XYZENUM_COUNT values tell the length of the array. The other XYZENUM_VALUE represents a single element within that array. This makes the code easy to manage, for example: ```cpp enum CBTYPE @@ -851,23 +844,23 @@ device->BindConstantBuffer(&buffers[CBTYPE_MESH], 0, cmd); // makes it easy to r This is widely used to make code straight forward and easy to add new objects, without needing to create additional declarations, except for the enum values. -### wiImage +### Image Renderer [[Header]](../../WickedEngine/wiImage.h) [[Cpp]](../../WickedEngine/wiImage.cpp) This can render images to the screen in a simple manner. You can draw an image like this: ```cpp -wiImage::SetCanvas(canvas, cmd); // setting the canvas area is required to set the drawing area and perform DPI scaling (the canvas will remain for the duration of the command list) -wiImage::Draw(myTexture, wiImageParams(10, 20, 256, 128), cmd); +wi::image::SetCanvas(canvas, cmd); // setting the canvas area is required to set the drawing area and perform DPI scaling (the canvas will remain for the duration of the command list) +wi::image::Draw(myTexture, wiImageParams(10, 20, 256, 128), cmd); ``` The example will draw a 2D texture image to the position (10, 20), with a size of 256 x 128 pixels to the current render pass. There are a lot of other parameters to customize the rendered image, for more information see wiImageParams structure. -- wiImageParams
+- wi::image::Params
Describe all parameters of how and where to draw the image on the screen. -### wiFont +### Font Renderer [[Header]](../../WickedEngine/wiFont.h) [[Cpp]](../../WickedEngine/wiFont.cpp) This can render fonts to the screen in a simple manner. You can render a font as simple as this: ```cpp -wiFont::SetCanvas(canvas, cmd); // setting the canvas area is required to set the drawing area and perform DPI scaling (the canvas will remain for the duration of the command list) -wiFont::Draw("write this!", wiFontParams(10, 20), cmd); +wi::font::SetCanvas(canvas, cmd); // setting the canvas area is required to set the drawing area and perform DPI scaling (the canvas will remain for the duration of the command list) +wi::font::Draw("write this!", wiFontParams(10, 20), cmd); ``` Which will write the text write this! to 10, 20 pixel position onto the screen. There are many other parameters to describe the font's position, size, color, etc. See the wiFontParams structure for more details. - wiFontParams
@@ -875,37 +868,37 @@ Describe all parameters of how and where to draw the font on the screen. The wiFont can load and render .ttf (TrueType) fonts. The default arial font style is embedded into the engine ([[arial.h]](../WickedEngine/Utility/arial.h) file). The developer can load additional fonts from files by using `wiFont::AddFontStyle()` functions. These can either load from a file, or take a provided byte data for the font. The `AddFontStyle()` will return an `int` that will indicate the font ID within the loaded font library. The `wiFontParams::style` can be set to the font ID to use a specific font that was previously loaded. If the developer added a font before wiFont::Initialize was called, then that will be the default font and the arial font will not be created. -### wiEmittedParticle +### Emitted Particle System [[Header]](../../WickedEngine/wiEmittedParticle.h) [[Cpp]](../../WickedEngine/wiEmittedParticle.cpp) GPU driven emitter particle system, used to draw large amount of camera facing quad billboards. Supports simulation with force fields and fluid simulation based on Smooth Particle Hydrodynamics computation. -### wiHairParticle +### Hair Particle System [[Header]](../../WickedEngine/wiHairParticle.h) [[Cpp]](../../WickedEngine/wiHairParticle.cpp) GPU driven particles that are attached to a mesh surface. It can be used to render vegetation. It participates in force fields simulation. -### wiOcean +### Ocean [[Header]](../../WickedEngine/wiOcean.h) [[Cpp]](../../WickedEngine/wiOcean.cpp) Ocean renderer using Fast Fourier Transforms simulation. The ocean surface is always rendered relative to the camera, like an infinitely large water body. -### wiSprite +### Sprite [[Header]](../../WickedEngine/wiSprite.h) [[Cpp]](../../WickedEngine/wiSprite.cpp) A helper facility to render and animate images. It uses the [wiImage](#wiimage) renderer internally - Anim
Several different simple animation utilities, like animated textures, wobbling, rotation, fade out, etc... -### wiSpriteFont +### SpriteFont [[Header]](../../WickedEngine/wiSprite.h) [[Cpp]](../../WickedEngine/wiSprite.cpp) A helper facility to render fonts. It uses the [wiFont](#wifont) renderer internally. It performs string conversion -### wiTextureHelper +### TextureHelper [[Header]](../../WickedEngine/wiTextureHelper.h) [[Cpp]](../../WickedEngine/wiTextureHelper.cpp) This is used to generate procedural textures, such as uniform colors, noise, etc... -### wiGPUSortLib +### GPUSortLib [[Header]](../../WickedEngine/wiGPUSortLib.h) [[Cpp]](../../WickedEngine/wiGPUSortLib.cpp) This is a GPU sorting facility using the Bitonic Sort algorithm. It can be used to sort an index list based on a list of floats as comparison keys entirely on the GPU. -### wiGPUBVH +### GPUBVH [[Header]](../../WickedEngine/wiGPUBVH.h) [[Cpp]](../../WickedEngine/wiGPUBVH.cpp) This facility can generate a BVH (Bounding Volume Hierarcy) on the GPU for a [Scene](#scene). The BVH structure can be used to perform efficient RAY-triangle intersections on the GPU, for example in ray tracing. This is not using the ray tracing API hardware acceleration, but implemented in compute, so it has wide hardware support. @@ -913,124 +906,103 @@ This facility can generate a BVH (Bounding Volume Hierarcy) on the GPU for a [Sc ## GUI The custom GUI, implemented with engine features -### wiGUI +### GUI [[Header]](../../WickedEngine/wiGUI.h) [[Cpp]](../../WickedEngine/wiGUI.cpp) The wiGUI is responsible to run a GUI interface and manage widgets. GUI Scaling: To ensure correct GUI scaling, GUI elements should be designed for the current window size. If they are placed inside `RenderPath2D::ResizeLayout()` function according to current screen size, it will ensure that GUI will be scaled on a Resolution or DPI change event, which is recommended. -### wiEventArgs -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +### EventArgs This will be sent to widget callbacks to provide event arguments in different formats ### wiWidget -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) The base widget interface can be extended with specific functionality. The GUI will store and process widgets by this interface. -#### wiButton -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### Button A simple clickable button. Supports the OnClick event callback. -#### wiLabel -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### Label A simple static text field. -#### wiTextInputField -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### TextInputField Supports text input when activated. Pressing Enter will accept the input and fire the OnInputAccepted callback. Pressing the Escape key while active will cancel the text input and restoe the previous state. There can be only one active text input field at a time. -#### wiSlider -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### Slider A slider, that can represent float or integer values. The slider also accepts text input to input number values. If the number input is outside of the slider's range, it will expand its range to support the newly assigned value. Upon changing the slider value, whether by text input or sliding, the OnSlide event callback will be fired. -#### wiCheckBox -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### CheckBox The checkbox is a two state item which can represent true/false state. The OnClick event callback will be fired upon changing the value (by clicking on it) -#### wiComboBox -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### ComboBox Supports item selection from a list of text. Can set the maximum number of visible items. If the list of items is greater than the max allowed visible items, then a vertical scrollbar will be presented to allow showing hidden items. Upon selection, the OnSelect event callback will be triggered. -#### wiWindow -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### Window A window widget is able to hold any number of other widgets. It can be moved across the screen, minimized and resized by the user. The window does not manage lifetime of attached widgets since 0.49.0! -#### wiColorPicker -[[Header]](../../WickedEngine/wiWidget.h) [[Cpp]](../../WickedEngine/wiWidget.cpp) +#### ColorPicker Supports picking a HSV (or HSL) color, displaying its RGB values. On selection, the OnColorChanged event callback will be fired and the user can read the new RGB value from the event argument. ## Helpers A collection of engine-level helper classes -### wiAllocators -[[Header]](../../WickedEngine/wiAllocators.h) - -#### LinearAllocator -[[Header]](../../WickedEngine/wiAllocators.h) -The linear allocator is used to allocate contiguous blocks of memory. The amount of maximum allocations is defined at creation time. Blocks then can be allocated from beginning to end until there is free space left. Blocks can be freed from the end until the allocator is not empty. This is not thread safe. - -#### ThreadSafeRingBuffer -[[Header]](../../WickedEngine/wiContainers.h) -This is a thread safe container that can hold elements of one certain data type at once. Elements are added to the end of container, and they are removed from the beginning. The container wraps around, so if the last element would be put after the last valid array index, then it will be put to the first instead (if the first array index is not occupied). - -### wiArchive +### Archive [[Header]](../../WickedEngine/wiArchive.h) [[Cpp]](../../WickedEngine/wiArchive.cpp) This is used for serializing binary data to disk or memory. An archive file always starts with the 64-bit version number that it was serialized with. An archive of greater version number than the current archive version of the engine can't be opened safely, so an error message will be shown if this happens. A certain archive version will not be forward compatible with the current engine version if the current archive version barrier number is greater than the archive's own version number. -### wiColor +### Color [[Header]](../../WickedEngine/wiColor.h) Utility to convert to/from float color data to 32-bit RGBA data (stored in a uint32_t as RGBA, where each channel is 8 bits) -### wiFadeManager +### FadeManager [[Header]](../../WickedEngine/wiFadeManager.h) [[Cpp]](../../WickedEngine/wiFadeManager.cpp) -Simple helper to manage a fadeout screen. Fadeout starts at transparent, then fades smoothly to an opaque color (such as black, in most cases), then a callback occurs which the user can handle with their own event. After that, the color will fade back to transperent. This is used by the [MainComponent](#maincomponent) to fade from one RenderPath to an other. +Simple helper to manage a fadeout screen. Fadeout starts at transparent, then fades smoothly to an opaque color (such as black, in most cases), then a callback occurs which the user can handle with their own event. After that, the color will fade back to transperent. This is used by the [Application](#application) to fade from one RenderPath to an other. -### wiHelper +### Helper [[Header]](../../WickedEngine/wiHelper.h) [[Cpp]](../../WickedEngine/wiHelper.cpp) Many helper utility functions, like screenshot, readfile, messagebox, splitpath, sleep, etc... -### wiIntersect -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +### Primitive +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) Primitives that can be intersected with each other #### AABB -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) Axis aligned bounding box. There are multiple ways to construct it, for example from min-max corners, or center and halfextent. -#### SPHERE -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +#### Sphere +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) Sphere with a center and radius. -#### CAPSULE -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +#### Capsule +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) It's like two spheres connected by a cylinder. Base and Tip are the two endpoints, radius is the cylinder's radius. -#### RAY -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +#### Ray +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) Line with a starting point (origin) and direction. The direction's reciprocal is precomputed to perform fast intersection of many primitives with one ray. #### Frustum -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) Six planes, most commonly used for checking if an intersectable primitive is inside a camera. #### Hitbox2D -[[Header]](../../WickedEngine/wiIntersect.h) [[Cpp]](../../WickedEngine/wiIntersect.cpp) +[[Header]](../../WickedEngine/wiPrimitive.h) [[Cpp]](../../WickedEngine/wiPrimitive.cpp) A rectangle, essentially an 2D AABB. -### wiMath +### Math [[Header]](../../WickedEngine/wiMath.h) [[Cpp]](../../WickedEngine/wiMath.cpp) Math related helper functions, like lerp, triangleArea, HueToRGB, etc... -### wiRandom +### Random [[Header]](../../WickedEngine/wiRandom.h) [[Cpp]](../../WickedEngine/wiRandom.cpp) Uniform random number generator with a good distribution. -### wiRectPacker +### RectPacker [[Header]](../../WickedEngine/wiRectPacker.h) [[Cpp]](../../WickedEngine/wiRectPacker.cpp) Provides the ability to pack multiple rectangles into a bigger rectangle, while taking up the least amount of space from the containing rectangle. -### wiResourceManager +### ResourceManager [[Header]](../../WickedEngine/wiResourceManager.h) [[Cpp]](../../WickedEngine/wiResourceManager.cpp) This can load images and sounds. It will hold on to resources until there is at least something that is referencing them, otherwise deletes them. One resource can have multiple owners, too. This is thread safe. @@ -1039,35 +1011,32 @@ This can load images and sounds. It will hold on to resources until there is at - `Clear()` : Clear all resources. This will clear the resource library, but resources that are still used somewhere will remain usable. The resource manager can support different modes that can be set with `SetMode(MODE param)` function: -- `MODE_DISCARD_FILEDATA_AFTER_LOAD` : this is the default behaviour. The resource will not hold on to file data, even if the user specified `IMPORT_RETAIN_FILEDATA` flag when loading the resource. This will result in the resource manager unable to serialize (save) itself. -- `MODE_ALLOW_RETAIN_FILEDATA` : this mode can be used to keep the file data buffers alive inside resources. This way the resource manager can be serialized (saved). Only the resources that still hold onto their file data will be serialized (saved). When loading a resource, the user can specify `IMPORT_RETAIN_FILEDATA` flag to keep the file data for a specific resource instead of discarding it. -- `MODE_ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING` : Keep all file data, but don't write them while serializing. This is useful to disable resource embedding temporarily without destroying file data buffers. +- `DISCARD_FILEDATA_AFTER_LOAD` : this is the default behaviour. The resource will not hold on to file data, even if the user specified `IMPORT_RETAIN_FILEDATA` flag when loading the resource. This will result in the resource manager unable to serialize (save) itself. +- `ALLOW_RETAIN_FILEDATA` : this mode can be used to keep the file data buffers alive inside resources. This way the resource manager can be serialized (saved). Only the resources that still hold onto their file data will be serialized (saved). When loading a resource, the user can specify `IMPORT_RETAIN_FILEDATA` flag to keep the file data for a specific resource instead of discarding it. +- `ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING` : Keep all file data, but don't write them while serializing. This is useful to disable resource embedding temporarily without destroying file data buffers. The resource manager can always be serialized in read mode. File data retention will be based on existing file import flags and the global resource manager mode. -### wiSpinLock +### SpinLock [[Header]](../../WickedEngine/wiSpinLock.h) [[Cpp]](../../WickedEngine/wiSpinLock.cpp) This can be used to guarantee exclusive access to a block in multithreaded race condition scenario instead of a mutex. The difference to a mutex that this doesn't let the thread to yield, but instead spin on an atomic flag until the spinlock can be locked. -### wiStartupArguments -[[Header]](../../WickedEngine/wiStartupArguments.h) [[Cpp]](../../WickedEngine/wiStartupArguments.cpp) +### Arguments +[[Header]](../../WickedEngine/wiArguments.h) [[Cpp]](../../WickedEngine/wiArguments.cpp) This is to store the startup parameters that were passed to the application from the operating system "command line". The user can query these arguments by name. -### wiTimer +### Timer [[Header]](../../WickedEngine/wiTimer.h) [[Cpp]](../../WickedEngine/wiTimer.cpp) High resolution stopwatch timer ## Input -The input interface - -### wiInput [[Header]](../../WickedEngine/wiInput.h) [[Cpp]](../../WickedEngine/wiInput.cpp) This is the high level input interface. Use this to read input devices in a platform-independent way. - Initialize
Creates all necessary resources, the engine initialization already does this via [wiInitializer](#wiinitializer), so the user probably doesn't have to worry about this. - Update
-This is called once per frame and necessary to process inputs. This is automatically called in [MainComponent](#maincomponent), so the user doesn't need to worry about it, unless they are reimplementing the high level interface for themselves. +This is called once per frame and necessary to process inputs. This is automatically called in [Application](#application), so the user doesn't need to worry about it, unless they are reimplementing the high level interface for themselves. - Down
Checks whether a button is currently held down. - Press
@@ -1109,21 +1078,19 @@ A touch contact point. Currently it is supported in UWP (Universal Windows Platf - GetTouches
Get a vector containing current Touch contact points -### wiXInput +### XInput [[Header]](../../WickedEngine/wiXInput.h) [[Cpp]](../../WickedEngine/wiXInput.cpp) Low level wrapper for XInput API (capable of handling Xbox controllers). This functionality is used by the more generic wiInput interface, so the user probably doesn't need to use this. -### wiRawInput +### RawInput [[Header]](../../WickedEngine/wiRawInput.h) [[Cpp]](../../WickedEngine/wiRawInput.cpp) Low level wrapper for RAWInput API (capable of handling human interface devices, such as mouse, keyboard, controllers). This functionality is used by the more generic wiInput interface, so the user probably doesn't need to use this. ## Audio -Handles audio playback and spatial audio. -### wiAudio [[Header]](../../WickedEngine/wiAudio.h) [[Cpp]](../../WickedEngine/wiAudio.cpp) -The namespace that is a collection of audio related functionality. It is currently implemented with XAudio2 +The namespace that is a collection of audio related functionality. - CreateSound - CreateSoundInstance - Play @@ -1179,10 +1146,9 @@ Can make different sounding 3D reverb effect globally ## Physics +[[Header]](../../WickedEngine/wiPhysics.h) [[Cpp]](../../WickedEngine/wiPhysics_Bullet.cpp) You can find the physics system related functionality under ENGINE/Physics filter in the solution. It uses the entity-component system to perform updating all physics components in the world. -### wiPhysicsEngine -[[Header]](../../WickedEngine/wiPhysicsEngine.h) [[Cpp]](../../WickedEngine/wiPhysicsEngine.cpp) - Initialize
This must be called before using the physics system, but it is automatically done by [wiInitializer](#wiinitializer) - IsEnabled
@@ -1220,13 +1186,8 @@ The pinned vertices can also be manipulated via skinning animation. If th Resetting a soft body can be accomplished by setting the `SoftBodyPhysicsComponent::FORCE_RESET` flag. This means that the next physics update will reset the soft body mesh to the initial pose. -### wiPhysicsEngine_Bullet -[[Header]](../../WickedEngine/wiPhysicsEngine_BULLET.h) [[Cpp]](../../WickedEngine/wiPhysicsEngine_BULLET.cpp) -Bullet physics engine implementation of the physics update system - ## Network -### wiNetwork [[Header]](../../WickedEngine/wiNetwork.h) [[Cpp]](../../WickedEngine/wiNetwork.cpp) Simple interface that provides UDP networking features. - Initialize @@ -1245,24 +1206,24 @@ An IP address and a port number that identifies the target of communication This is the place for the Lua scipt interface. For a complete reference about Lua scripting interface, please see the [ScriptingAPI-Documentation](ScriptingAPI-Documentation.md) ### LuaBindings The systems that are bound to Lua have the name of the system as their filename, postfixed by _BindLua. -### wiLua +### Lua [[Header]](../../WickedEngine/wiLua.h) [[Cpp]](../../WickedEngine/wiLua.cpp) The Lua scripting interface on the C++ side. This allows to execute lua commands from the C++ side and manipulate the lua stack, such as pushing values to lua and getting values from lua, among other things. -### wiLua_Globals +### Lua_Globals [[Header]](../../WickedEngine/wiLua_Globals.h) Hardcoded lua script in text format. This will be always executed and provides some commonly used helper functionality for lua scripts. -### wiLuna +### Luna [[Header]](../../WickedEngine/wiLuna.h) Helper to allow bind engine classes from C++ to Lua ## Tools This is the place for tools that use engine-level systems -### wiBackLog -[[Header]](../../WickedEngine/wiBacklog.h) [[Cpp]](../../WickedEngine/wiBackLog.cpp) +### Backlog +[[Header]](../../WickedEngine/wiBacklog.h) [[Cpp]](../../WickedEngine/wiBacklog.cpp) Used to log any messages by any system, from any thread. It can draw itself to the screen. It can execute Lua scripts. -If there was a `wiBackLog::LogLevel::Error` or higher severity message posted on the backlog, the contents of the log will be saved to the temporary user directory as wiBackLog.txt. -### wiProfiler +If there was a `wii:backlog::LogLevel::Error` or higher severity message posted on the backlog, the contents of the log will be saved to the temporary user directory as wiBacklog.txt. +### Profiler [[Header]](../../WickedEngine/wiProfiler.h) [[Cpp]](../../WickedEngine/wiProfiler.cpp) Used to time specific ranges in execution. Support CPU and GPU timing. Can write the result to the screen as simple text at this time. diff --git a/Content/scripts/character_controller_tps.lua b/Content/scripts/character_controller_tps.lua index 456757bed..007f32448 100644 --- a/Content/scripts/character_controller_tps.lua +++ b/Content/scripts/character_controller_tps.lua @@ -405,10 +405,10 @@ runProcess(function() -- We will override the render path so we can invoke the script from Editor and controls won't collide with editor scripts -- Also save the active component that we can restore when ESCAPE is pressed - local prevPath = main.GetActivePath() + local prevPath = application.GetActivePath() local path = RenderPath3D() path.SetLightShaftsEnabled(true) - main.SetActivePath(path) + application.SetActivePath(path) local font = SpriteFont("This script is showcasing how to perform scene collision with raycasts for character and camera.\nControls:\n#####################\n\nWASD/arrows/left analog stick: walk\nSHIFT/right shoulder button: movement speed\nSPACE/gamepad X/gamepad button 2: Jump\nRight Mouse Button/Right thumbstick: rotate camera\nScoll middle mouse/Left-Right triggers: adjust camera distance\nESCAPE key: quit\nR: reload script"); font.SetSize(14) @@ -433,14 +433,14 @@ runProcess(function() -- so if you loaded this script from the editor, you can go back to the editor with ESC backlog_post("EXIT") killProcesses() - main.SetActivePath(prevPath) + application.SetActivePath(prevPath) return end if(input.Press(string.byte('R'))) then -- reload script backlog_post("RELOAD") killProcesses() - main.SetActivePath(prevPath) + application.SetActivePath(prevPath) dofile("character_controller_tps.lua") return end diff --git a/Content/scripts/fighting_game.lua b/Content/scripts/fighting_game.lua index 4f4e35be1..c0ca67e46 100644 --- a/Content/scripts/fighting_game.lua +++ b/Content/scripts/fighting_game.lua @@ -1305,7 +1305,7 @@ local function Character(face, skin_color, shirt_color, hair_color, shoe_color) -- HP bar, etc. sprites: - local renderPath = main.GetActivePath() + local renderPath = application.GetActivePath() self.sprite_hpbar_background = Sprite("hp_bar.png") local fx = self.sprite_hpbar_background.GetParams() @@ -1903,14 +1903,14 @@ runProcess(function() -- We lock the framerate to 60 FPS, so if frame rate goes below, game will play slower -- -- There is also the possibility to implement game logic in fixed_update() instead, but that is not common for fighting games - main.SetTargetFrameRate(60) - main.SetFrameRateLock(true) + application.SetTargetFrameRate(60) + application.SetFrameRateLock(true) -- We will override the render path so we can invoke the script from Editor and controls won't collide with editor scripts -- Also save the active component that we can restore when ESCAPE is pressed - local prevPath = main.GetActivePath() + local prevPath = application.GetActivePath() local path = RenderPath3D() - main.SetActivePath(path) + application.SetActivePath(path) local help_text = "" help_text = help_text .. "Wicked Engine Fighting game sample script\n" @@ -2026,14 +2026,14 @@ runProcess(function() -- so if you loaded this script from the editor, you can go back to the editor with ESC backlog_post("EXIT") killProcesses() - main.SetActivePath(prevPath) + application.SetActivePath(prevPath) return end if(input.Press(string.byte('R'))) then -- reload script backlog_post("RELOAD") killProcesses() - main.SetActivePath(prevPath) + application.SetActivePath(prevPath) dofile("fighting_game.lua") return end diff --git a/Editor/AnimationWindow.cpp b/Editor/AnimationWindow.cpp index 27d0ad65b..eca464286 100644 --- a/Editor/AnimationWindow.cpp +++ b/Editor/AnimationWindow.cpp @@ -2,12 +2,12 @@ #include "AnimationWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void AnimationWindow::Create(EditorComponent* editor) { - wiWindow::Create("Animation Window"); + wi::gui::Window::Create("Animation Window"); SetSize(XMFLOAT2(520, 140)); float x = 140; @@ -20,8 +20,8 @@ void AnimationWindow::Create(EditorComponent* editor) animationsComboBox.SetSize(XMFLOAT2(300, hei)); animationsComboBox.SetPos(XMFLOAT2(x, y += step)); animationsComboBox.SetEnabled(false); - animationsComboBox.OnSelect([&](wiEventArgs args) { - entity = wiScene::GetScene().animations.GetEntity(args.iValue); + animationsComboBox.OnSelect([&](wi::gui::EventArgs args) { + entity = wi::scene::GetScene().animations.GetEntity(args.iValue); }); animationsComboBox.SetTooltip("Choose an animation clip..."); AddWidget(&animationsComboBox); @@ -30,8 +30,8 @@ void AnimationWindow::Create(EditorComponent* editor) loopedCheckBox.SetTooltip("Toggle animation looping behaviour."); loopedCheckBox.SetSize(XMFLOAT2(hei, hei)); loopedCheckBox.SetPos(XMFLOAT2(150, y += step)); - loopedCheckBox.OnClick([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + loopedCheckBox.OnClick([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { animation->SetLooped(args.bValue); @@ -43,8 +43,8 @@ void AnimationWindow::Create(EditorComponent* editor) playButton.SetTooltip("Play/Pause animation."); playButton.SetSize(XMFLOAT2(100, hei)); playButton.SetPos(XMFLOAT2(200, y)); - playButton.OnClick([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + playButton.OnClick([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { if (animation->IsPlaying()) @@ -64,8 +64,8 @@ void AnimationWindow::Create(EditorComponent* editor) stopButton.SetTooltip("Stop animation."); stopButton.SetSize(XMFLOAT2(100, hei)); stopButton.SetPos(XMFLOAT2(310, y)); - stopButton.OnClick([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + stopButton.OnClick([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { animation->Stop(); @@ -76,8 +76,8 @@ void AnimationWindow::Create(EditorComponent* editor) timerSlider.Create(0, 1, 0, 100000, "Timer: "); timerSlider.SetSize(XMFLOAT2(250, hei)); timerSlider.SetPos(XMFLOAT2(x, y += step)); - timerSlider.OnSlide([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + timerSlider.OnSlide([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { animation->timer = args.fValue; @@ -90,8 +90,8 @@ void AnimationWindow::Create(EditorComponent* editor) amountSlider.Create(0, 1, 0, 100000, "Amount: "); amountSlider.SetSize(XMFLOAT2(250, hei)); amountSlider.SetPos(XMFLOAT2(x, y += step)); - amountSlider.OnSlide([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + amountSlider.OnSlide([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { animation->amount = args.fValue; @@ -104,8 +104,8 @@ void AnimationWindow::Create(EditorComponent* editor) speedSlider.Create(0, 4, 1, 100000, "Speed: "); speedSlider.SetSize(XMFLOAT2(250, hei)); speedSlider.SetPos(XMFLOAT2(x, y += step)); - speedSlider.OnSlide([&](wiEventArgs args) { - AnimationComponent* animation = wiScene::GetScene().animations.GetComponent(entity); + speedSlider.OnSlide([&](wi::gui::EventArgs args) { + AnimationComponent* animation = wi::scene::GetScene().animations.GetComponent(entity); if (animation != nullptr) { animation->speed = args.fValue; @@ -126,7 +126,7 @@ void AnimationWindow::Update() { animationsComboBox.ClearItems(); - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); if (!scene.animations.Contains(entity)) { @@ -169,7 +169,7 @@ void AnimationWindow::Update() if (animation.IsPlaying()) { playButton.SetText("Pause"); - animation.amount = wiMath::Lerp(animation.amount, 1, 0.1f); + animation.amount = wi::math::Lerp(animation.amount, 1, 0.1f); } else { diff --git a/Editor/AnimationWindow.h b/Editor/AnimationWindow.h index d431be363..e3425d59c 100644 --- a/Editor/AnimationWindow.h +++ b/Editor/AnimationWindow.h @@ -3,20 +3,20 @@ class EditorComponent; -class AnimationWindow : public wiWindow +class AnimationWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity = wiECS::INVALID_ENTITY; + wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY; - wiComboBox animationsComboBox; - wiCheckBox loopedCheckBox; - wiButton playButton; - wiButton stopButton; - wiSlider timerSlider; - wiSlider amountSlider; - wiSlider speedSlider; + wi::gui::ComboBox animationsComboBox; + wi::gui::CheckBox loopedCheckBox; + wi::gui::Button playButton; + wi::gui::Button stopButton; + wi::gui::Slider timerSlider; + wi::gui::Slider amountSlider; + wi::gui::Slider speedSlider; void Update(); }; diff --git a/Editor/App_Windows.cpp b/Editor/App_Windows.cpp index 43177b3c4..69aff6f99 100644 --- a/Editor/App_Windows.cpp +++ b/Editor/App_Windows.cpp @@ -167,15 +167,15 @@ protected: if (c == '\b') { - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); } else { - if (wiBackLog::isActive()) - wiBackLog::input(c); - wiTextInputField::AddInput(c); + if (wi::backlog::isActive()) + wi::backlog::input(c); + wi::gui::TextInputField::AddInput(c); } } diff --git a/Editor/CameraWindow.cpp b/Editor/CameraWindow.cpp index 1449cba5b..446d56478 100644 --- a/Editor/CameraWindow.cpp +++ b/Editor/CameraWindow.cpp @@ -2,16 +2,16 @@ #include "CameraWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void CameraWindow::ResetCam() { move = {}; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + CameraComponent& camera = wi::scene::GetCamera(); float width = camera.width; float height = camera.height; camera = CameraComponent(); @@ -30,8 +30,8 @@ void CameraWindow::ResetCam() void CameraWindow::Create(EditorComponent* editor) { - wiWindow::Create("Camera Window"); - camera_transform.MatrixTransform(wiScene::GetCamera().GetInvView()); + wi::gui::Window::Create("Camera Window"); + camera_transform.MatrixTransform(wi::scene::GetCamera().GetInvView()); camera_transform.UpdateTransform(); SetSize(XMFLOAT2(380, 360)); @@ -45,10 +45,10 @@ void CameraWindow::Create(EditorComponent* editor) farPlaneSlider.SetTooltip("Controls the camera's far clip plane, geometry farther than this will be clipped."); farPlaneSlider.SetSize(XMFLOAT2(100, hei)); farPlaneSlider.SetPos(XMFLOAT2(x, y += step)); - farPlaneSlider.SetValue(wiScene::GetCamera().zFarP); - farPlaneSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + farPlaneSlider.SetValue(wi::scene::GetCamera().zFarP); + farPlaneSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.zFarP = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -59,10 +59,10 @@ void CameraWindow::Create(EditorComponent* editor) nearPlaneSlider.SetTooltip("Controls the camera's near clip plane, geometry closer than this will be clipped."); nearPlaneSlider.SetSize(XMFLOAT2(100, hei)); nearPlaneSlider.SetPos(XMFLOAT2(x, y += step)); - nearPlaneSlider.SetValue(wiScene::GetCamera().zNearP); - nearPlaneSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + nearPlaneSlider.SetValue(wi::scene::GetCamera().zNearP); + nearPlaneSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.zNearP = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -73,9 +73,9 @@ void CameraWindow::Create(EditorComponent* editor) fovSlider.SetTooltip("Controls the camera's top-down field of view (in degrees)"); fovSlider.SetSize(XMFLOAT2(100, hei)); fovSlider.SetPos(XMFLOAT2(x, y += step)); - fovSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + fovSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.fov = args.fValue / 180.f * XM_PI; camera.UpdateCamera(); camera.SetDirty(); @@ -86,9 +86,9 @@ void CameraWindow::Create(EditorComponent* editor) focalLengthSlider.SetTooltip("Controls the depth of field effect's focus distance"); focalLengthSlider.SetSize(XMFLOAT2(100, hei)); focalLengthSlider.SetPos(XMFLOAT2(x, y += step)); - focalLengthSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + focalLengthSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.focal_length = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -99,9 +99,9 @@ void CameraWindow::Create(EditorComponent* editor) apertureSizeSlider.SetTooltip("Controls the depth of field effect's strength"); apertureSizeSlider.SetSize(XMFLOAT2(100, hei)); apertureSizeSlider.SetPos(XMFLOAT2(x, y += step)); - apertureSizeSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + apertureSizeSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.aperture_size = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -112,9 +112,9 @@ void CameraWindow::Create(EditorComponent* editor) apertureShapeXSlider.SetTooltip("Controls the depth of field effect's bokeh shape"); apertureShapeXSlider.SetSize(XMFLOAT2(100, hei)); apertureShapeXSlider.SetPos(XMFLOAT2(x, y += step)); - apertureShapeXSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + apertureShapeXSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.aperture_shape.x = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -125,9 +125,9 @@ void CameraWindow::Create(EditorComponent* editor) apertureShapeYSlider.SetTooltip("Controls the depth of field effect's bokeh shape"); apertureShapeYSlider.SetSize(XMFLOAT2(100, hei)); apertureShapeYSlider.SetPos(XMFLOAT2(x, y += step)); - apertureShapeYSlider.OnSlide([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + apertureShapeYSlider.OnSlide([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); camera.aperture_shape.y = args.fValue; camera.UpdateCamera(); camera.SetDirty(); @@ -152,7 +152,7 @@ void CameraWindow::Create(EditorComponent* editor) resetButton.Create("Reset Camera"); resetButton.SetSize(XMFLOAT2(140, hei)); resetButton.SetPos(XMFLOAT2(x, y += step)); - resetButton.OnClick([&](wiEventArgs args) { + resetButton.OnClick([&](wi::gui::EventArgs args) { ResetCam(); }); AddWidget(&resetButton); @@ -169,11 +169,11 @@ void CameraWindow::Create(EditorComponent* editor) proxyButton.SetTooltip("Copy the current camera and place a proxy of it in the world."); proxyButton.SetSize(XMFLOAT2(140, hei)); proxyButton.SetPos(XMFLOAT2(x, y += step * 2)); - proxyButton.OnClick([=](wiEventArgs args) { + proxyButton.OnClick([=](wi::gui::EventArgs args) { - const CameraComponent& camera = wiScene::GetCamera(); + const CameraComponent& camera = wi::scene::GetCamera(); - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); static int camcounter = 0; Entity entity = scene.Entity_CreateCamera("cam" + std::to_string(camcounter), camera.width, camera.height, camera.zNearP, camera.zFarP, camera.fov); @@ -216,7 +216,7 @@ void CameraWindow::SetEntity(Entity entity) { proxy = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); if (scene.cameras.GetComponent(entity) != nullptr) { @@ -233,7 +233,7 @@ void CameraWindow::SetEntity(Entity entity) void CameraWindow::Update() { - CameraComponent& camera = wiScene::GetCamera(); + CameraComponent& camera = wi::scene::GetCamera(); farPlaneSlider.SetValue(camera.zFarP); nearPlaneSlider.SetValue(camera.zNearP); diff --git a/Editor/CameraWindow.h b/Editor/CameraWindow.h index 2f30627b8..b80ef7f9f 100644 --- a/Editor/CameraWindow.h +++ b/Editor/CameraWindow.h @@ -3,38 +3,38 @@ class EditorComponent; -class CameraWindow : public wiWindow +class CameraWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); void ResetCam(); - wiECS::Entity proxy = wiECS::INVALID_ENTITY; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity proxy = wi::ecs::INVALID_ENTITY; + void SetEntity(wi::ecs::Entity entity); void Update(); XMFLOAT3 move = {}; - wiScene::TransformComponent camera_transform; - wiScene::TransformComponent camera_target; + wi::scene::TransformComponent camera_transform; + wi::scene::TransformComponent camera_target; - wiSlider farPlaneSlider; - wiSlider nearPlaneSlider; - wiSlider fovSlider; - wiSlider focalLengthSlider; - wiSlider apertureSizeSlider; - wiSlider apertureShapeXSlider; - wiSlider apertureShapeYSlider; - wiSlider movespeedSlider; - wiSlider rotationspeedSlider; - wiSlider accelerationSlider; - wiButton resetButton; - wiCheckBox fpsCheckBox; + wi::gui::Slider farPlaneSlider; + wi::gui::Slider nearPlaneSlider; + wi::gui::Slider fovSlider; + wi::gui::Slider focalLengthSlider; + wi::gui::Slider apertureSizeSlider; + wi::gui::Slider apertureShapeXSlider; + wi::gui::Slider apertureShapeYSlider; + wi::gui::Slider movespeedSlider; + wi::gui::Slider rotationspeedSlider; + wi::gui::Slider accelerationSlider; + wi::gui::Button resetButton; + wi::gui::CheckBox fpsCheckBox; - wiButton proxyButton; - wiCheckBox followCheckBox; - wiSlider followSlider; + wi::gui::Button proxyButton; + wi::gui::CheckBox followCheckBox; + wi::gui::Slider followSlider; }; diff --git a/Editor/DecalWindow.cpp b/Editor/DecalWindow.cpp index 17b9a6eb0..2e691aa4a 100644 --- a/Editor/DecalWindow.cpp +++ b/Editor/DecalWindow.cpp @@ -2,13 +2,13 @@ #include "DecalWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void DecalWindow::Create(EditorComponent* editor) { - wiWindow::Create("Decal Window"); + wi::gui::Window::Create("Decal Window"); SetSize(XMFLOAT2(400, 200)); float x = 200; @@ -29,15 +29,15 @@ void DecalWindow::Create(EditorComponent* editor) infoLabel.SetText("Selecting decals will select the according material. Set decal properties (texture, color, etc.) in the Material window."); infoLabel.SetSize(XMFLOAT2(400 - 20, 100)); infoLabel.SetPos(XMFLOAT2(10, y)); - infoLabel.SetColor(wiColor::Transparent()); + infoLabel.SetColor(wi::Color::Transparent()); AddWidget(&infoLabel); y += infoLabel.GetScale().y - step + 5; decalNameField.Create("Decal Name"); decalNameField.SetPos(XMFLOAT2(10, y+=step)); decalNameField.SetSize(XMFLOAT2(300, hei)); - decalNameField.OnInputAccepted([=](wiEventArgs args) { - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + decalNameField.OnInputAccepted([=](wi::gui::EventArgs args) { + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name != nullptr) { *name = args.sValue; @@ -57,7 +57,7 @@ void DecalWindow::SetEntity(Entity entity) { this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); const DecalComponent* decal = scene.decals.GetComponent(entity); if (decal != nullptr) diff --git a/Editor/DecalWindow.h b/Editor/DecalWindow.h index 6b421b971..97d42a803 100644 --- a/Editor/DecalWindow.h +++ b/Editor/DecalWindow.h @@ -3,16 +3,16 @@ class EditorComponent; -class DecalWindow : public wiWindow +class DecalWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiCheckBox placementCheckBox; - wiLabel infoLabel; - wiTextInputField decalNameField; + wi::gui::CheckBox placementCheckBox; + wi::gui::Label infoLabel; + wi::gui::TextInputField decalNameField; }; diff --git a/Editor/Editor.cpp b/Editor/Editor.cpp index 22785aa94..f2f911e81 100644 --- a/Editor/Editor.cpp +++ b/Editor/Editor.cpp @@ -11,11 +11,11 @@ #include #include -using namespace wiGraphics; -using namespace wiRectPacker; -using namespace wiScene; -using namespace wiECS; - +using namespace wi::graphics; +using namespace wi::primitive; +using namespace wi::rectpacker; +using namespace wi::scene; +using namespace wi::ecs; #ifdef PLATFORM_UWP #include @@ -61,7 +61,7 @@ winrt::fire_and_forget uwp_copy_assets() // scripts: { - wiHelper::StringConvert(rootdir + "scripts\\", wstr); + wi::helper::StringConvert(rootdir + "scripts\\", wstr); auto src = co_await StorageFolder::GetFolderFromPathAsync(wstr.c_str()); if (src) { @@ -75,7 +75,7 @@ winrt::fire_and_forget uwp_copy_assets() // models: { - wiHelper::StringConvert(rootdir + "models\\", wstr); + wi::helper::StringConvert(rootdir + "models\\", wstr); auto src = co_await StorageFolder::GetFolderFromPathAsync(wstr.c_str()); if (src) { @@ -89,7 +89,7 @@ winrt::fire_and_forget uwp_copy_assets() // Documentation: { - wiHelper::StringConvert(rootdir + "Documentation\\", wstr); + wi::helper::StringConvert(rootdir + "Documentation\\", wstr); auto src = co_await StorageFolder::GetFolderFromPathAsync(wstr.c_str()); if (src) { @@ -105,10 +105,10 @@ winrt::fire_and_forget uwp_copy_assets() void Editor::Initialize() { - MainComponent::Initialize(); + Application::Initialize(); // With this mode, file data for resources will be kept around. This allows serializing embedded resource data inside scenes - wiResourceManager::SetMode(wiResourceManager::MODE_ALLOW_RETAIN_FILEDATA); + wi::resourcemanager::SetMode(wi::resourcemanager::Mode::ALLOW_RETAIN_FILEDATA); infoDisplay.active = true; infoDisplay.watermark = true; @@ -118,7 +118,7 @@ void Editor::Initialize() infoDisplay.colorspace = true; infoDisplay.heap_allocation_counter = true; - wiRenderer::SetOcclusionCullingEnabled(true); + wi::renderer::SetOcclusionCullingEnabled(true); loader.Load(); @@ -132,17 +132,16 @@ void Editor::Initialize() void EditorLoadingScreen::Load() { - font = wiSpriteFont("Loading...", wiFontParams(0, 0, 36, - WIFALIGN_CENTER, WIFALIGN_CENTER)); + font = wi::SpriteFont("Loading...", wi::font::Params(0, 0, 36, wi::font::WIFALIGN_CENTER, wi::font::WIFALIGN_CENTER)); AddFont(&font); - sprite = wiSprite("images/logo_small.png"); + sprite = wi::Sprite("images/logo_small.png"); sprite.anim.opa = 1; sprite.anim.repeatable = true; sprite.params.siz = XMFLOAT2(128, 128); sprite.params.pivot = XMFLOAT2(0.5f, 1.0f); - sprite.params.quality = QUALITY_LINEAR; - sprite.params.blendFlag = BLENDMODE_ALPHA; + sprite.params.quality = wi::image::QUALITY_LINEAR; + sprite.params.blendFlag = wi::enums::BLENDMODE_ALPHA; AddSprite(&sprite); LoadingScreen::Load(); @@ -151,7 +150,7 @@ void EditorLoadingScreen::Update(float dt) { font.params.posX = GetLogicalWidth()*0.5f; font.params.posY = GetLogicalHeight()*0.5f; - sprite.params.pos = XMFLOAT3(GetLogicalWidth()*0.5f, GetLogicalHeight()*0.5f - font.textHeight(), 0); + sprite.params.pos = XMFLOAT3(GetLogicalWidth()*0.5f, GetLogicalHeight()*0.5f - font.TextHeight(), 0); LoadingScreen::Update(dt); } @@ -162,12 +161,12 @@ void EditorComponent::ChangeRenderPath(RENDERPATH path) switch (path) { case EditorComponent::RENDERPATH_DEFAULT: - renderPath = std::make_unique(); + renderPath = std::make_unique(); pathTraceTargetSlider.SetVisible(false); pathTraceStatisticsLabel.SetVisible(false); break; case EditorComponent::RENDERPATH_PATHTRACING: - renderPath = std::make_unique(); + renderPath = std::make_unique(); pathTraceTargetSlider.SetVisible(true); pathTraceStatisticsLabel.SetVisible(true); break; @@ -180,7 +179,7 @@ void EditorComponent::ChangeRenderPath(RENDERPATH path) renderPath->Load(); - wiGUI& gui = GetGUI(); + wi::gui::GUI& gui = GetGUI(); // Destroy and recreate renderer and postprocess windows: @@ -202,7 +201,7 @@ void EditorComponent::ResizeBuffers() init(main->canvas); RenderPath2D::ResizeBuffers(); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); renderPath->init(*this); renderPath->ResizeBuffers(); @@ -416,18 +415,18 @@ void EditorComponent::Load() uwp_copy_assets(); #endif // PLATFORM_UWP - wiJobSystem::context ctx; - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { pointLightTex = wiResourceManager::Load("images/pointlight.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { spotLightTex = wiResourceManager::Load("images/spotlight.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { dirLightTex = wiResourceManager::Load("images/directional_light.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { areaLightTex = wiResourceManager::Load("images/arealight.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { decalTex = wiResourceManager::Load("images/decal.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { forceFieldTex = wiResourceManager::Load("images/forcefield.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { emitterTex = wiResourceManager::Load("images/emitter.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { hairTex = wiResourceManager::Load("images/hair.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { cameraTex = wiResourceManager::Load("images/camera.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { armatureTex = wiResourceManager::Load("images/armature.dds"); }); - wiJobSystem::Execute(ctx, [this](wiJobArgs args) { soundTex = wiResourceManager::Load("images/sound.dds"); }); + wi::jobsystem::context ctx; + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { pointLightTex = wi::resourcemanager::Load("images/pointlight.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { spotLightTex = wi::resourcemanager::Load("images/spotlight.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { dirLightTex = wi::resourcemanager::Load("images/directional_light.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { areaLightTex = wi::resourcemanager::Load("images/arealight.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { decalTex = wi::resourcemanager::Load("images/decal.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { forceFieldTex = wi::resourcemanager::Load("images/forcefield.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { emitterTex = wi::resourcemanager::Load("images/emitter.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { hairTex = wi::resourcemanager::Load("images/hair.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { cameraTex = wi::resourcemanager::Load("images/camera.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { armatureTex = wi::resourcemanager::Load("images/armature.dds"); }); + wi::jobsystem::Execute(ctx, [this](wi::jobsystem::JobArgs args) { soundTex = wi::resourcemanager::Load("images/sound.dds"); }); // wait for ctx is at the end of this function! translator.Create(); @@ -437,189 +436,189 @@ void EditorComponent::Load() rendererWnd_Toggle.Create("Renderer"); rendererWnd_Toggle.SetTooltip("Renderer settings window"); - rendererWnd_Toggle.OnClick([&](wiEventArgs args) { + rendererWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { rendererWnd.SetVisible(!rendererWnd.IsVisible()); }); GetGUI().AddWidget(&rendererWnd_Toggle); postprocessWnd_Toggle.Create("PostProcess"); postprocessWnd_Toggle.SetTooltip("Postprocess settings window"); - postprocessWnd_Toggle.OnClick([&](wiEventArgs args) { + postprocessWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { postprocessWnd.SetVisible(!postprocessWnd.IsVisible()); }); GetGUI().AddWidget(&postprocessWnd_Toggle); paintToolWnd_Toggle.Create("Paint Tool"); paintToolWnd_Toggle.SetTooltip("Paint tool window"); - paintToolWnd_Toggle.OnClick([&](wiEventArgs args) { + paintToolWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { paintToolWnd.SetVisible(!paintToolWnd.IsVisible()); }); GetGUI().AddWidget(&paintToolWnd_Toggle); /////////////////////// - wiColor option_color_idle = wiColor(255, 145, 145, 100); - wiColor option_color_focus = wiColor(255, 197, 193, 200); + wi::Color option_color_idle = wi::Color(255, 145, 145, 100); + wi::Color option_color_focus = wi::Color(255, 197, 193, 200); weatherWnd_Toggle.Create("Weather"); - weatherWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - weatherWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + weatherWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + weatherWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); weatherWnd_Toggle.SetTooltip("Weather settings window"); - weatherWnd_Toggle.OnClick([&](wiEventArgs args) { + weatherWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { weatherWnd.SetVisible(!weatherWnd.IsVisible()); }); GetGUI().AddWidget(&weatherWnd_Toggle); objectWnd_Toggle.Create("Object"); - objectWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - objectWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + objectWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + objectWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); objectWnd_Toggle.SetTooltip("Object settings window"); - objectWnd_Toggle.OnClick([&](wiEventArgs args) { + objectWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { objectWnd.SetVisible(!objectWnd.IsVisible()); }); GetGUI().AddWidget(&objectWnd_Toggle); meshWnd_Toggle.Create("Mesh"); - meshWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - meshWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + meshWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + meshWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); meshWnd_Toggle.SetTooltip("Mesh settings window"); - meshWnd_Toggle.OnClick([&](wiEventArgs args) { + meshWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { meshWnd.SetVisible(!meshWnd.IsVisible()); }); GetGUI().AddWidget(&meshWnd_Toggle); materialWnd_Toggle.Create("Material"); - materialWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - materialWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + materialWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + materialWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); materialWnd_Toggle.SetTooltip("Material settings window"); - materialWnd_Toggle.OnClick([&](wiEventArgs args) { + materialWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { materialWnd.SetVisible(!materialWnd.IsVisible()); }); GetGUI().AddWidget(&materialWnd_Toggle); cameraWnd_Toggle.Create("Camera"); - cameraWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - cameraWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + cameraWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + cameraWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); cameraWnd_Toggle.SetTooltip("Camera settings window"); - cameraWnd_Toggle.OnClick([&](wiEventArgs args) { + cameraWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { cameraWnd.SetVisible(!cameraWnd.IsVisible()); }); GetGUI().AddWidget(&cameraWnd_Toggle); envProbeWnd_Toggle.Create("EnvProbe"); - envProbeWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - envProbeWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + envProbeWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + envProbeWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); envProbeWnd_Toggle.SetTooltip("Environment probe settings window"); - envProbeWnd_Toggle.OnClick([&](wiEventArgs args) { + envProbeWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { envProbeWnd.SetVisible(!envProbeWnd.IsVisible()); }); GetGUI().AddWidget(&envProbeWnd_Toggle); decalWnd_Toggle.Create("Decal"); - decalWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - decalWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + decalWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + decalWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); decalWnd_Toggle.SetTooltip("Decal settings window"); - decalWnd_Toggle.OnClick([&](wiEventArgs args) { + decalWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { decalWnd.SetVisible(!decalWnd.IsVisible()); }); GetGUI().AddWidget(&decalWnd_Toggle); soundWnd_Toggle.Create("Sound"); - soundWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - soundWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + soundWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + soundWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); soundWnd_Toggle.SetTooltip("Sound settings window"); - soundWnd_Toggle.OnClick([&](wiEventArgs args) { + soundWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { soundWnd.SetVisible(!soundWnd.IsVisible()); }); GetGUI().AddWidget(&soundWnd_Toggle); lightWnd_Toggle.Create("Light"); - lightWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - lightWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + lightWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + lightWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); lightWnd_Toggle.SetTooltip("Light settings window"); - lightWnd_Toggle.OnClick([&](wiEventArgs args) { + lightWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { lightWnd.SetVisible(!lightWnd.IsVisible()); }); GetGUI().AddWidget(&lightWnd_Toggle); animWnd_Toggle.Create("Animation"); - animWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - animWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + animWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + animWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); animWnd_Toggle.SetTooltip("Animation inspector window"); - animWnd_Toggle.OnClick([&](wiEventArgs args) { + animWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { animWnd.SetVisible(!animWnd.IsVisible()); }); GetGUI().AddWidget(&animWnd_Toggle); emitterWnd_Toggle.Create("Emitter"); - emitterWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - emitterWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + emitterWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + emitterWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); emitterWnd_Toggle.SetTooltip("Emitter Particle System properties"); - emitterWnd_Toggle.OnClick([&](wiEventArgs args) { + emitterWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { emitterWnd.SetVisible(!emitterWnd.IsVisible()); }); GetGUI().AddWidget(&emitterWnd_Toggle); hairWnd_Toggle.Create("HairParticle"); - hairWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - hairWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + hairWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + hairWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); hairWnd_Toggle.SetTooltip("Hair Particle System properties"); - hairWnd_Toggle.OnClick([&](wiEventArgs args) { + hairWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { hairWnd.SetVisible(!hairWnd.IsVisible()); }); GetGUI().AddWidget(&hairWnd_Toggle); forceFieldWnd_Toggle.Create("ForceField"); - forceFieldWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - forceFieldWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + forceFieldWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + forceFieldWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); forceFieldWnd_Toggle.SetTooltip("Force Field properties"); - forceFieldWnd_Toggle.OnClick([&](wiEventArgs args) { + forceFieldWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { forceFieldWnd.SetVisible(!forceFieldWnd.IsVisible()); }); GetGUI().AddWidget(&forceFieldWnd_Toggle); springWnd_Toggle.Create("Spring"); - springWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - springWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + springWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + springWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); springWnd_Toggle.SetTooltip("Spring properties"); - springWnd_Toggle.OnClick([&](wiEventArgs args) { + springWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { springWnd.SetVisible(!springWnd.IsVisible()); }); GetGUI().AddWidget(&springWnd_Toggle); ikWnd_Toggle.Create("IK"); - ikWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - ikWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + ikWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + ikWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); ikWnd_Toggle.SetTooltip("Inverse Kinematics properties"); - ikWnd_Toggle.OnClick([&](wiEventArgs args) { + ikWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { ikWnd.SetVisible(!ikWnd.IsVisible()); }); GetGUI().AddWidget(&ikWnd_Toggle); transformWnd_Toggle.Create("Transform"); - transformWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - transformWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + transformWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + transformWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); transformWnd_Toggle.SetTooltip("Transform properties"); - transformWnd_Toggle.OnClick([&](wiEventArgs args) { + transformWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { transformWnd.SetVisible(!transformWnd.IsVisible()); }); GetGUI().AddWidget(&transformWnd_Toggle); layerWnd_Toggle.Create("Layer"); - layerWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - layerWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + layerWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + layerWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); layerWnd_Toggle.SetTooltip("Layer Component"); - layerWnd_Toggle.OnClick([&](wiEventArgs args) { + layerWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { layerWnd.SetVisible(!layerWnd.IsVisible()); }); GetGUI().AddWidget(&layerWnd_Toggle); nameWnd_Toggle.Create("Name"); - nameWnd_Toggle.SetColor(option_color_idle, wiWidget::IDLE); - nameWnd_Toggle.SetColor(option_color_focus, wiWidget::FOCUS); + nameWnd_Toggle.SetColor(option_color_idle, wi::gui::IDLE); + nameWnd_Toggle.SetColor(option_color_focus, wi::gui::FOCUS); nameWnd_Toggle.SetTooltip("Name Component"); - nameWnd_Toggle.OnClick([&](wiEventArgs args) { + nameWnd_Toggle.OnClick([&](wi::gui::EventArgs args) { nameWnd.SetVisible(!nameWnd.IsVisible()); }); GetGUI().AddWidget(&nameWnd_Toggle); @@ -630,7 +629,7 @@ void EditorComponent::Load() translatorCheckBox.Create("Translator: "); translatorCheckBox.SetTooltip("Enable the translator tool"); - translatorCheckBox.OnClick([&](wiEventArgs args) { + translatorCheckBox.OnClick([&](wi::gui::EventArgs args) { translator.enabled = args.bValue; }); GetGUI().AddWidget(&translatorCheckBox); @@ -640,7 +639,7 @@ void EditorComponent::Load() isTranslatorCheckBox.Create("T: "); { isScalatorCheckBox.SetTooltip("Scale"); - isScalatorCheckBox.OnClick([&](wiEventArgs args) { + isScalatorCheckBox.OnClick([&](wi::gui::EventArgs args) { translator.isScalator = args.bValue; translator.isTranslator = false; translator.isRotator = false; @@ -651,7 +650,7 @@ void EditorComponent::Load() GetGUI().AddWidget(&isScalatorCheckBox); isRotatorCheckBox.SetTooltip("Rotate"); - isRotatorCheckBox.OnClick([&](wiEventArgs args) { + isRotatorCheckBox.OnClick([&](wi::gui::EventArgs args) { translator.isRotator = args.bValue; translator.isScalator = false; translator.isTranslator = false; @@ -662,7 +661,7 @@ void EditorComponent::Load() GetGUI().AddWidget(&isRotatorCheckBox); isTranslatorCheckBox.SetTooltip("Translate"); - isTranslatorCheckBox.OnClick([&](wiEventArgs args) { + isTranslatorCheckBox.OnClick([&](wi::gui::EventArgs args) { translator.isTranslator = args.bValue; translator.isScalator = false; translator.isRotator = false; @@ -676,14 +675,14 @@ void EditorComponent::Load() saveButton.Create("Save"); saveButton.SetTooltip("Save the current scene"); - saveButton.SetColor(wiColor(0, 198, 101, 180), wiWidget::WIDGETSTATE::IDLE); - saveButton.SetColor(wiColor(0, 255, 140, 255), wiWidget::WIDGETSTATE::FOCUS); - saveButton.OnClick([&](wiEventArgs args) { + saveButton.SetColor(wi::Color(0, 198, 101, 180), wi::gui::WIDGETSTATE::IDLE); + saveButton.SetColor(wi::Color(0, 255, 140, 255), wi::gui::WIDGETSTATE::FOCUS); + saveButton.OnClick([&](wi::gui::EventArgs args) { const bool dump_to_header = saveModeComboBox.GetSelected() == 2; - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::SAVE; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::SAVE; if (dump_to_header) { params.description = "C++ header (.h)"; @@ -694,29 +693,29 @@ void EditorComponent::Load() params.description = "Wicked Scene (.wiscene)"; params.extensions.push_back("wiscene"); } - wiHelper::FileDialog(params, [=](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { - std::string filename = wiHelper::ReplaceExtension(fileName, params.extensions.front()); - wiArchive archive = dump_to_header ? wiArchive() : wiArchive(filename, false); + wi::helper::FileDialog(params, [=](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + std::string filename = wi::helper::ReplaceExtension(fileName, params.extensions.front()); + wi::Archive archive = dump_to_header ? wi::Archive() : wi::Archive(filename, false); if (archive.IsOpen()) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - wiResourceManager::MODE embed_mode = (wiResourceManager::MODE)saveModeComboBox.GetItemUserData(saveModeComboBox.GetSelected()); - wiResourceManager::SetMode(embed_mode); + wi::resourcemanager::Mode embed_mode = (wi::resourcemanager::Mode)saveModeComboBox.GetItemUserData(saveModeComboBox.GetSelected()); + wi::resourcemanager::SetMode(embed_mode); scene.Serialize(archive); if (dump_to_header) { - archive.SaveHeaderFile(filename, wiHelper::RemoveExtension(wiHelper::GetFileNameFromPath(filename))); + archive.SaveHeaderFile(filename, wi::helper::RemoveExtension(wi::helper::GetFileNameFromPath(filename))); } ResetHistory(); } else { - wiHelper::messageBox("Could not create " + fileName + "!"); + wi::helper::messageBox("Could not create " + fileName + "!"); } }); }); @@ -726,78 +725,78 @@ void EditorComponent::Load() modelButton.Create("Load Model"); modelButton.SetTooltip("Load a scene / import model into the editor..."); - modelButton.SetColor(wiColor(0, 89, 255, 180), wiWidget::WIDGETSTATE::IDLE); - modelButton.SetColor(wiColor(112, 155, 255, 255), wiWidget::WIDGETSTATE::FOCUS); - modelButton.OnClick([&](wiEventArgs args) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + modelButton.SetColor(wi::Color(0, 89, 255, 180), wi::gui::WIDGETSTATE::IDLE); + modelButton.SetColor(wi::Color(112, 155, 255, 255), wi::gui::WIDGETSTATE::FOCUS); + modelButton.OnClick([&](wi::gui::EventArgs args) { + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Model formats (.wiscene, .obj, .gltf, .glb)"; params.extensions.push_back("wiscene"); params.extensions.push_back("obj"); params.extensions.push_back("gltf"); params.extensions.push_back("glb"); - wiHelper::FileDialog(params, [&](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + wi::helper::FileDialog(params, [&](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { - size_t camera_count_prev = wiScene::GetScene().cameras.GetCount(); + size_t camera_count_prev = wi::scene::GetScene().cameras.GetCount(); - main->loader.addLoadingFunction([=](wiJobArgs args) { - std::string extension = wiHelper::toUpper(wiHelper::GetExtensionFromFileName(fileName)); + main->loader.addLoadingFunction([=](wi::jobsystem::JobArgs args) { + std::string extension = wi::helper::toUpper(wi::helper::GetExtensionFromFileName(fileName)); if (!extension.compare("WISCENE")) // engine-serialized { - wiScene::LoadModel(fileName); + wi::scene::LoadModel(fileName); } else if (!extension.compare("OBJ")) // wavefront-obj { Scene scene; ImportModel_OBJ(fileName, scene); - wiScene::GetScene().Merge(scene); + wi::scene::GetScene().Merge(scene); } else if (!extension.compare("GLTF")) // text-based gltf { Scene scene; ImportModel_GLTF(fileName, scene); - wiScene::GetScene().Merge(scene); + wi::scene::GetScene().Merge(scene); } else if (!extension.compare("GLB")) // binary gltf { Scene scene; ImportModel_GLTF(fileName, scene); - wiScene::GetScene().Merge(scene); + wi::scene::GetScene().Merge(scene); } }); main->loader.onFinished([=] { // Detect when the new scene contains a new camera, and snap the camera onto it: - size_t camera_count = wiScene::GetScene().cameras.GetCount(); + size_t camera_count = wi::scene::GetScene().cameras.GetCount(); if (camera_count > 0 && camera_count > camera_count_prev) { - Entity entity = wiScene::GetScene().cameras.GetEntity(camera_count_prev); + Entity entity = wi::scene::GetScene().cameras.GetEntity(camera_count_prev); if (entity != INVALID_ENTITY) { - TransformComponent* camera_transform = wiScene::GetScene().transforms.GetComponent(entity); + TransformComponent* camera_transform = wi::scene::GetScene().transforms.GetComponent(entity); if (camera_transform != nullptr) { cameraWnd.camera_transform = *camera_transform; } - CameraComponent* cam = wiScene::GetScene().cameras.GetComponent(entity); + CameraComponent* cam = wi::scene::GetScene().cameras.GetComponent(entity); if (cam != nullptr) { - wiScene::GetCamera() = *cam; + wi::scene::GetCamera() = *cam; // camera aspect should be always for the current screen - wiScene::GetCamera().width = (float)renderPath->GetInternalResolution().x; - wiScene::GetCamera().height = (float)renderPath->GetInternalResolution().y; + wi::scene::GetCamera().width = (float)renderPath->GetInternalResolution().x; + wi::scene::GetCamera().height = (float)renderPath->GetInternalResolution().y; } } } - main->ActivatePath(this, 0.2f, wiColor::Black()); + main->ActivatePath(this, 0.2f, wi::Color::Black()); weatherWnd.Update(); RefreshSceneGraphView(); }); - main->ActivatePath(&main->loader, 0.2f, wiColor::Black()); + main->ActivatePath(&main->loader, 0.2f, wi::Color::Black()); ResetHistory(); }); }); @@ -807,16 +806,16 @@ void EditorComponent::Load() scriptButton.Create("Load Script"); scriptButton.SetTooltip("Load a Lua script..."); - scriptButton.SetColor(wiColor(255, 33, 140, 180), wiWidget::WIDGETSTATE::IDLE); - scriptButton.SetColor(wiColor(255, 100, 140, 255), wiWidget::WIDGETSTATE::FOCUS); - scriptButton.OnClick([&](wiEventArgs args) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + scriptButton.SetColor(wi::Color(255, 33, 140, 180), wi::gui::WIDGETSTATE::IDLE); + scriptButton.SetColor(wi::Color(255, 100, 140, 255), wi::gui::WIDGETSTATE::FOCUS); + scriptButton.OnClick([&](wi::gui::EventArgs args) { + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Lua script"; params.extensions.push_back("lua"); - wiHelper::FileDialog(params, [](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { - wiLua::RunFile(fileName); + wi::helper::FileDialog(params, [](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + wi::lua::RunFile(fileName); }); }); }); @@ -825,11 +824,11 @@ void EditorComponent::Load() clearButton.Create("Clear World"); clearButton.SetTooltip("Delete every model from the scene"); - clearButton.SetColor(wiColor(255, 173, 43, 180), wiWidget::WIDGETSTATE::IDLE); - clearButton.SetColor(wiColor(255, 235, 173, 255), wiWidget::WIDGETSTATE::FOCUS); - clearButton.OnClick([&](wiEventArgs args) { + clearButton.SetColor(wi::Color(255, 173, 43, 180), wi::gui::WIDGETSTATE::IDLE); + clearButton.SetColor(wi::Color(255, 235, 173, 255), wi::gui::WIDGETSTATE::FOCUS); + clearButton.OnClick([&](wi::gui::EventArgs args) { translator.selected.clear(); - wiRenderer::ClearWorld(wiScene::GetScene()); + wi::renderer::ClearWorld(wi::scene::GetScene()); objectWnd.SetEntity(INVALID_ENTITY); meshWnd.SetEntity(INVALID_ENTITY, -1); lightWnd.SetEntity(INVALID_ENTITY); @@ -855,9 +854,9 @@ void EditorComponent::Load() helpButton.Create("?"); helpButton.SetTooltip("Help"); - helpButton.SetColor(wiColor(34, 158, 214, 180), wiWidget::WIDGETSTATE::IDLE); - helpButton.SetColor(wiColor(113, 183, 214, 255), wiWidget::WIDGETSTATE::FOCUS); - helpButton.OnClick([&](wiEventArgs args) { + helpButton.SetColor(wi::Color(34, 158, 214, 180), wi::gui::WIDGETSTATE::IDLE); + helpButton.SetColor(wi::Color(113, 183, 214, 255), wi::gui::WIDGETSTATE::FOCUS); + helpButton.OnClick([&](wi::gui::EventArgs args) { helpLabel.SetVisible(!helpLabel.IsVisible()); }); GetGUI().AddWidget(&helpButton); @@ -899,69 +898,69 @@ void EditorComponent::Load() exitButton.Create("X"); exitButton.SetTooltip("Exit"); - exitButton.SetColor(wiColor(190, 0, 0, 180), wiWidget::WIDGETSTATE::IDLE); - exitButton.SetColor(wiColor(255, 0, 0, 255), wiWidget::WIDGETSTATE::FOCUS); - exitButton.OnClick([this](wiEventArgs args) { - wiPlatform::Exit(); + exitButton.SetColor(wi::Color(190, 0, 0, 180), wi::gui::WIDGETSTATE::IDLE); + exitButton.SetColor(wi::Color(255, 0, 0, 255), wi::gui::WIDGETSTATE::FOCUS); + exitButton.OnClick([this](wi::gui::EventArgs args) { + wi::platform::Exit(); }); GetGUI().AddWidget(&exitButton); profilerEnabledCheckBox.Create("Profiler Enabled: "); profilerEnabledCheckBox.SetTooltip("Toggle Profiler On/Off"); - profilerEnabledCheckBox.OnClick([&](wiEventArgs args) { - wiProfiler::SetEnabled(args.bValue); + profilerEnabledCheckBox.OnClick([&](wi::gui::EventArgs args) { + wi::profiler::SetEnabled(args.bValue); }); - profilerEnabledCheckBox.SetCheck(wiProfiler::IsEnabled()); + profilerEnabledCheckBox.SetCheck(wi::profiler::IsEnabled()); GetGUI().AddWidget(&profilerEnabledCheckBox); physicsEnabledCheckBox.Create("Physics Simulation: "); physicsEnabledCheckBox.SetTooltip("Toggle Physics Simulation On/Off"); - physicsEnabledCheckBox.OnClick([&](wiEventArgs args) { - wiPhysicsEngine::SetSimulationEnabled(args.bValue); + physicsEnabledCheckBox.OnClick([&](wi::gui::EventArgs args) { + wi::physics::SetSimulationEnabled(args.bValue); }); - physicsEnabledCheckBox.SetCheck(wiPhysicsEngine::IsSimulationEnabled()); + physicsEnabledCheckBox.SetCheck(wi::physics::IsSimulationEnabled()); GetGUI().AddWidget(&physicsEnabledCheckBox); cinemaModeCheckBox.Create("Cinema Mode: "); cinemaModeCheckBox.SetTooltip("Toggle Cinema Mode (All HUD disabled). Press ESC to exit."); - cinemaModeCheckBox.OnClick([&](wiEventArgs args) { + cinemaModeCheckBox.OnClick([&](wi::gui::EventArgs args) { if (renderPath != nullptr) { renderPath->GetGUI().SetVisible(false); } GetGUI().SetVisible(false); - wiProfiler::SetEnabled(false); + wi::profiler::SetEnabled(false); main->infoDisplay.active = false; }); GetGUI().AddWidget(&cinemaModeCheckBox); sceneGraphView.Create("Scene graph view"); - sceneGraphView.OnSelect([this](wiEventArgs args) { + sceneGraphView.OnSelect([this](wi::gui::EventArgs args) { translator.selected.clear(); for (int i = 0; i < sceneGraphView.GetItemCount(); ++i) { - const wiTreeList::Item& item = sceneGraphView.GetItem(i); + const wi::gui::TreeList::Item& item = sceneGraphView.GetItem(i); if (item.selected) { - wiScene::PickResult pick; + wi::scene::PickResult pick; pick.entity = (Entity)item.userdata; AddSelected(pick); } } }); - sceneGraphView.SetColor(wiColor(100, 100, 100, 100), wiWidget::IDLE); + sceneGraphView.SetColor(wi::Color(100, 100, 100, 100), wi::gui::IDLE); GetGUI().AddWidget(&sceneGraphView); renderPathComboBox.Create("Render Path: "); renderPathComboBox.AddItem("Default"); renderPathComboBox.AddItem("Path Tracing"); - renderPathComboBox.OnSelect([&](wiEventArgs args) { + renderPathComboBox.OnSelect([&](wi::gui::EventArgs args) { ChangeRenderPath((RENDERPATH)args.iValue); }); renderPathComboBox.SetSelected(RENDERPATH_DEFAULT); @@ -971,12 +970,12 @@ void EditorComponent::Load() saveModeComboBox.Create("Save Mode: "); - saveModeComboBox.SetColor(wiColor(0, 198, 101, 180), wiWidget::WIDGETSTATE::IDLE); - saveModeComboBox.SetColor(wiColor(0, 255, 140, 255), wiWidget::WIDGETSTATE::FOCUS); - saveModeComboBox.AddItem("Embed resources", wiResourceManager::MODE_ALLOW_RETAIN_FILEDATA); - saveModeComboBox.AddItem("No embedding", wiResourceManager::MODE_ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING); - saveModeComboBox.AddItem("Dump to header", wiResourceManager::MODE_ALLOW_RETAIN_FILEDATA); - saveModeComboBox.SetTooltip("Choose whether to embed resources (textures, sounds...) in the scene file when saving, or keep them as separate files.\nThe Dump to header option will use embedding and create a C++ header file with byte data of the scene to be used with wiArchive serialization."); + saveModeComboBox.SetColor(wi::Color(0, 198, 101, 180), wi::gui::WIDGETSTATE::IDLE); + saveModeComboBox.SetColor(wi::Color(0, 255, 140, 255), wi::gui::WIDGETSTATE::FOCUS); + saveModeComboBox.AddItem("Embed resources", (uint64_t)wi::resourcemanager::Mode::ALLOW_RETAIN_FILEDATA); + saveModeComboBox.AddItem("No embedding", (uint64_t)wi::resourcemanager::Mode::ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING); + saveModeComboBox.AddItem("Dump to header", (uint64_t)wi::resourcemanager::Mode::ALLOW_RETAIN_FILEDATA); + saveModeComboBox.SetTooltip("Choose whether to embed resources (textures, sounds...) in the scene file when saving, or keep them as separate files.\nThe Dump to header option will use embedding and create a C++ header file with byte data of the scene to be used with wi::Archive serialization."); GetGUI().AddWidget(&saveModeComboBox); @@ -1010,7 +1009,7 @@ void EditorComponent::Load() layerWnd.Create(this); nameWnd.Create(this); - wiGUI& gui = GetGUI(); + wi::gui::GUI& gui = GetGUI(); gui.AddWidget(&materialWnd); gui.AddWidget(&weatherWnd); gui.AddWidget(&objectWnd); @@ -1033,7 +1032,7 @@ void EditorComponent::Load() cameraWnd.ResetCam(); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); RenderPath2D::Load(); } @@ -1055,10 +1054,10 @@ void EditorComponent::FixedUpdate() } void EditorComponent::Update(float dt) { - wiProfiler::range_id profrange = wiProfiler::BeginRangeCPU("Editor Update"); + wi::profiler::range_id profrange = wi::profiler::BeginRangeCPU("Editor Update"); - Scene& scene = wiScene::GetScene(); - CameraComponent& camera = wiScene::GetCamera(); + Scene& scene = wi::scene::GetScene(); + CameraComponent& camera = wi::scene::GetCamera(); cameraWnd.Update(); animWnd.Update(); @@ -1068,7 +1067,7 @@ void EditorComponent::Update(float dt) selectionOutlineTimer += dt; bool clear_selected = false; - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_ESCAPE)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_ESCAPE)) { if (cinemaModeCheckBox.GetCheck()) { @@ -1089,19 +1088,19 @@ void EditorComponent::Update(float dt) } // Camera control: - XMFLOAT4 currentMouse = wiInput::GetPointer(); - if (!wiBackLog::isActive() && !GetGUI().HasFocus()) + XMFLOAT4 currentMouse = wi::input::GetPointer(); + if (!wi::backlog::isActive() && !GetGUI().HasFocus()) { static XMFLOAT4 originalMouse = XMFLOAT4(0, 0, 0, 0); static bool camControlStart = true; if (camControlStart) { - originalMouse = wiInput::GetPointer(); + originalMouse = wi::input::GetPointer(); } float xDif = 0, yDif = 0; - if (wiInput::Down(wiInput::MOUSE_BUTTON_MIDDLE)) + if (wi::input::Down(wi::input::MOUSE_BUTTON_MIDDLE)) { camControlStart = false; #if 0 @@ -1110,41 +1109,41 @@ void EditorComponent::Update(float dt) yDif = currentMouse.y - originalMouse.y; #else // Mouse delta from hardware read: - xDif = wiInput::GetMouseState().delta_position.x; - yDif = wiInput::GetMouseState().delta_position.y; + xDif = wi::input::GetMouseState().delta_position.x; + yDif = wi::input::GetMouseState().delta_position.y; #endif xDif = 0.1f * xDif * (1.0f / 60.0f); yDif = 0.1f * yDif * (1.0f / 60.0f); - wiInput::SetPointer(originalMouse); - wiInput::HidePointer(true); + wi::input::SetPointer(originalMouse); + wi::input::HidePointer(true); } else { camControlStart = true; - wiInput::HidePointer(false); + wi::input::HidePointer(false); } const float buttonrotSpeed = 2.0f * dt; - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LEFT)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LEFT)) { xDif -= buttonrotSpeed; } - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_RIGHT)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_RIGHT)) { xDif += buttonrotSpeed; } - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_UP)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_UP)) { yDif -= buttonrotSpeed; } - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_DOWN)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_DOWN)) { yDif += buttonrotSpeed; } - const XMFLOAT4 leftStick = wiInput::GetAnalog(wiInput::GAMEPAD_ANALOG_THUMBSTICK_L, 0); - const XMFLOAT4 rightStick = wiInput::GetAnalog(wiInput::GAMEPAD_ANALOG_THUMBSTICK_R, 0); - const XMFLOAT4 rightTrigger = wiInput::GetAnalog(wiInput::GAMEPAD_ANALOG_TRIGGER_R, 0); + const XMFLOAT4 leftStick = wi::input::GetAnalog(wi::input::GAMEPAD_ANALOG_THUMBSTICK_L, 0); + const XMFLOAT4 rightStick = wi::input::GetAnalog(wi::input::GAMEPAD_ANALOG_THUMBSTICK_R, 0); + const XMFLOAT4 rightTrigger = wi::input::GetAnalog(wi::input::GAMEPAD_ANALOG_TRIGGER_R, 0); const float jostickrotspeed = 0.05f; xDif += rightStick.x * jostickrotspeed; @@ -1159,19 +1158,19 @@ void EditorComponent::Update(float dt) // FPS Camera const float clampedDT = std::min(dt, 0.1f); // if dt > 100 millisec, don't allow the camera to jump too far... - const float speed = ((wiInput::Down(wiInput::KEYBOARD_BUTTON_LSHIFT) ? 10.0f : 1.0f) + rightTrigger.x * 10.0f) * cameraWnd.movespeedSlider.GetValue() * clampedDT; + const float speed = ((wi::input::Down(wi::input::KEYBOARD_BUTTON_LSHIFT) ? 10.0f : 1.0f) + rightTrigger.x * 10.0f) * cameraWnd.movespeedSlider.GetValue() * clampedDT; XMVECTOR move = XMLoadFloat3(&cameraWnd.move); XMVECTOR moveNew = XMVectorSet(leftStick.x, 0, leftStick.y, 0); - if (!wiInput::Down(wiInput::KEYBOARD_BUTTON_LCONTROL)) + if (!wi::input::Down(wi::input::KEYBOARD_BUTTON_LCONTROL)) { // Only move camera if control not pressed - if (wiInput::Down((wiInput::BUTTON)'A') || wiInput::Down(wiInput::GAMEPAD_BUTTON_LEFT)) { moveNew += XMVectorSet(-1, 0, 0, 0); } - if (wiInput::Down((wiInput::BUTTON)'D') || wiInput::Down(wiInput::GAMEPAD_BUTTON_RIGHT)) { moveNew += XMVectorSet(1, 0, 0, 0); } - if (wiInput::Down((wiInput::BUTTON)'W') || wiInput::Down(wiInput::GAMEPAD_BUTTON_UP)) { moveNew += XMVectorSet(0, 0, 1, 0); } - if (wiInput::Down((wiInput::BUTTON)'S') || wiInput::Down(wiInput::GAMEPAD_BUTTON_DOWN)) { moveNew += XMVectorSet(0, 0, -1, 0); } - if (wiInput::Down((wiInput::BUTTON)'E') || wiInput::Down(wiInput::GAMEPAD_BUTTON_2)) { moveNew += XMVectorSet(0, 1, 0, 0); } - if (wiInput::Down((wiInput::BUTTON)'Q') || wiInput::Down(wiInput::GAMEPAD_BUTTON_1)) { moveNew += XMVectorSet(0, -1, 0, 0); } + if (wi::input::Down((wi::input::BUTTON)'A') || wi::input::Down(wi::input::GAMEPAD_BUTTON_LEFT)) { moveNew += XMVectorSet(-1, 0, 0, 0); } + if (wi::input::Down((wi::input::BUTTON)'D') || wi::input::Down(wi::input::GAMEPAD_BUTTON_RIGHT)) { moveNew += XMVectorSet(1, 0, 0, 0); } + if (wi::input::Down((wi::input::BUTTON)'W') || wi::input::Down(wi::input::GAMEPAD_BUTTON_UP)) { moveNew += XMVectorSet(0, 0, 1, 0); } + if (wi::input::Down((wi::input::BUTTON)'S') || wi::input::Down(wi::input::GAMEPAD_BUTTON_DOWN)) { moveNew += XMVectorSet(0, 0, -1, 0); } + if (wi::input::Down((wi::input::BUTTON)'E') || wi::input::Down(wi::input::GAMEPAD_BUTTON_2)) { moveNew += XMVectorSet(0, 1, 0, 0); } + if (wi::input::Down((wi::input::BUTTON)'Q') || wi::input::Down(wi::input::GAMEPAD_BUTTON_1)) { moveNew += XMVectorSet(0, -1, 0, 0); } moveNew += XMVector3Normalize(moveNew); } moveNew *= speed; @@ -1202,14 +1201,14 @@ void EditorComponent::Update(float dt) { // Orbital Camera - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LSHIFT)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LSHIFT)) { XMVECTOR V = XMVectorAdd(camera.GetRight() * xDif, camera.GetUp() * yDif) * 10; XMFLOAT3 vec; XMStoreFloat3(&vec, V); cameraWnd.camera_target.Translate(vec); } - else if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LCONTROL) || currentMouse.z != 0.0f) + else if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LCONTROL) || currentMouse.z != 0.0f) { cameraWnd.camera_transform.Translate(XMFLOAT3(0, 0, yDif * 4 + currentMouse.z)); cameraWnd.camera_transform.translation_local.z = std::min(0.0f, cameraWnd.camera_transform.translation_local.z); @@ -1227,9 +1226,9 @@ void EditorComponent::Update(float dt) // Begin picking: unsigned int pickMask = rendererWnd.GetPickType(); - RAY pickRay = wiRenderer::GetPickRay((long)currentMouse.x, (long)currentMouse.y, *this); + Ray pickRay = wi::renderer::GetPickRay((long)currentMouse.x, (long)currentMouse.y, *this); { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); if (pickMask & PICK_LIGHT) { @@ -1240,9 +1239,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1257,9 +1256,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1274,9 +1273,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1291,9 +1290,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1308,9 +1307,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1323,12 +1322,12 @@ void EditorComponent::Update(float dt) Entity entity = scene.probes.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - if (SPHERE(transform.GetPosition(), 1).intersects(pickRay)) + if (Sphere(transform.GetPosition(), 1).intersects(pickRay)) { - float dis = wiMath::Distance(transform.GetPosition(), pickRay.origin); + float dis = wi::math::Distance(transform.GetPosition(), pickRay.origin); if (dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1345,9 +1344,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1362,9 +1361,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1379,9 +1378,9 @@ void EditorComponent::Update(float dt) XMVECTOR disV = XMVector3LinePointDistance(XMLoadFloat3(&pickRay.origin), XMLoadFloat3(&pickRay.origin) + XMLoadFloat3(&pickRay.direction), transform.GetPositionV()); float dis = XMVectorGetX(disV); - if (dis > 0.01f && dis < wiMath::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) + if (dis > 0.01f && dis < wi::math::Distance(transform.GetPosition(), pickRay.origin) * 0.05f && dis < hovered.distance) { - hovered = wiScene::PickResult(); + hovered = wi::scene::PickResult(); hovered.entity = entity; hovered.distance = dis; } @@ -1392,12 +1391,12 @@ void EditorComponent::Update(float dt) { // Object picking only when mouse button down, because it can be slow with high polycount if ( - wiInput::Down(wiInput::MOUSE_BUTTON_LEFT) || - wiInput::Down(wiInput::MOUSE_BUTTON_RIGHT) || + wi::input::Down(wi::input::MOUSE_BUTTON_LEFT) || + wi::input::Down(wi::input::MOUSE_BUTTON_RIGHT) || paintToolWnd.GetMode() != PaintToolWindow::MODE_DISABLED ) { - hovered = wiScene::Pick(pickRay, pickMask); + hovered = wi::scene::Pick(pickRay, pickMask); } } } @@ -1411,15 +1410,15 @@ void EditorComponent::Update(float dt) const ObjectComponent* object = scene.objects.GetComponent(hovered.entity); if (object != nullptr) { - if (translator.selected.empty() && object->GetRenderTypes() & RENDERTYPE_WATER) + if (translator.selected.empty() && object->GetRenderTypes() & wi::enums::RENDERTYPE_WATER) { - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) { // if water, then put a water ripple onto it: scene.PutWaterRipple("images/ripple.png", hovered.position); } } - else if (decalWnd.placementCheckBox.GetCheck() && wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) + else if (decalWnd.placementCheckBox.GetCheck() && wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) { // if not water or softbody, put a decal on it: static int decalselector = 0; @@ -1440,10 +1439,10 @@ void EditorComponent::Update(float dt) // Select... static bool selectAll = false; - if (wiInput::Press(wiInput::MOUSE_BUTTON_RIGHT) || selectAll || clear_selected) + if (wi::input::Press(wi::input::MOUSE_BUTTON_RIGHT) || selectAll || clear_selected) { - wiArchive& archive = AdvanceHistory(); + wi::Archive& archive = AdvanceHistory(); archive << HISTORYOP_SELECTION; // record PREVIOUS selection state... archive << translator.selected.size(); @@ -1470,7 +1469,7 @@ void EditorComponent::Update(float dt) // Parented objects won't be attached, but only the parents instead. Otherwise it would cause "double translation" continue; } - wiScene::PickResult picked; + wi::scene::PickResult picked; picked.entity = entity; AddSelected(picked); } @@ -1479,12 +1478,12 @@ void EditorComponent::Update(float dt) { // Add the hovered item to the selection: - if (!translator.selected.empty() && wiInput::Down(wiInput::KEYBOARD_BUTTON_LSHIFT)) + if (!translator.selected.empty() && wi::input::Down(wi::input::KEYBOARD_BUTTON_LSHIFT)) { // Union selection: - wi::vector saved = translator.selected; + wi::vector saved = translator.selected; translator.selected.clear(); - for (const wiScene::PickResult& picked : saved) + for (const wi::scene::PickResult& picked : saved) { AddSelected(picked); } @@ -1523,15 +1522,15 @@ void EditorComponent::Update(float dt) } // Control operations... - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LCONTROL)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LCONTROL)) { // Select All - if (wiInput::Press((wiInput::BUTTON)'A')) + if (wi::input::Press((wi::input::BUTTON)'A')) { selectAll = true; } // Copy - if (wiInput::Press((wiInput::BUTTON)'C')) + if (wi::input::Press((wi::input::BUTTON)'C')) { auto prevSel = translator.selected; @@ -1543,7 +1542,7 @@ void EditorComponent::Update(float dt) } } // Paste - if (wiInput::Press((wiInput::BUTTON)'V')) + if (wi::input::Press((wi::input::BUTTON)'V')) { auto prevSel = translator.selected; translator.selected.clear(); @@ -1553,7 +1552,7 @@ void EditorComponent::Update(float dt) clipboard >> count; for (size_t i = 0; i < count; ++i) { - wiScene::PickResult picked; + wi::scene::PickResult picked; picked.entity = scene.Entity_Serialize(clipboard); AddSelected(picked); } @@ -1561,13 +1560,13 @@ void EditorComponent::Update(float dt) RefreshSceneGraphView(); } // Duplicate Instances - if (wiInput::Press((wiInput::BUTTON)'D')) + if (wi::input::Press((wi::input::BUTTON)'D')) { auto prevSel = translator.selected; translator.selected.clear(); for (auto& x : prevSel) { - wiScene::PickResult picked; + wi::scene::PickResult picked; picked.entity = scene.Entity_Duplicate(x.entity); AddSelected(picked); } @@ -1575,7 +1574,7 @@ void EditorComponent::Update(float dt) RefreshSceneGraphView(); } // Put Instances - if (clipboard.IsOpen() && hovered.subsetIndex >= 0 && wiInput::Down(wiInput::KEYBOARD_BUTTON_LSHIFT) && wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) + if (clipboard.IsOpen() && hovered.subsetIndex >= 0 && wi::input::Down(wi::input::KEYBOARD_BUTTON_LSHIFT) && wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) { clipboard.SetReadModeAndResetPos(true); size_t count; @@ -1595,14 +1594,14 @@ void EditorComponent::Update(float dt) RefreshSceneGraphView(); } // Undo - if (wiInput::Press((wiInput::BUTTON)'Z')) + if (wi::input::Press((wi::input::BUTTON)'Z')) { ConsumeHistoryOperation(true); RefreshSceneGraphView(); } // Redo - if (wiInput::Press((wiInput::BUTTON)'Y')) + if (wi::input::Press((wi::input::BUTTON)'Y')) { ConsumeHistoryOperation(false); @@ -1614,9 +1613,9 @@ void EditorComponent::Update(float dt) // Delete - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_DELETE)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_DELETE)) { - wiArchive& archive = AdvanceHistory(); + wi::Archive& archive = AdvanceHistory(); archive << HISTORYOP_DELETE; archive << translator.selected.size(); @@ -1661,7 +1660,7 @@ void EditorComponent::Update(float dt) } else { - const wiScene::PickResult& picked = translator.selected.back(); + const wi::scene::PickResult& picked = translator.selected.back(); assert(picked.entity != INVALID_ENTITY); objectWnd.SetEntity(picked.entity); @@ -1746,7 +1745,7 @@ void EditorComponent::Update(float dt) if (translator.IsDragEnded()) { - wiArchive& archive = AdvanceHistory(); + wi::Archive& archive = AdvanceHistory(); archive << HISTORYOP_TRANSLATOR; archive << translator.GetDragDeltaMatrix(); } @@ -1768,7 +1767,7 @@ void EditorComponent::Update(float dt) camera.TransformCamera(cameraWnd.camera_transform); camera.UpdateCamera(); - RenderPath3D_PathTracing* pathtracer = dynamic_cast(renderPath.get()); + wi::RenderPath3D_PathTracing* pathtracer = dynamic_cast(renderPath.get()); if (pathtracer != nullptr) { pathtracer->setTargetSampleCount((int)pathTraceTargetSlider.GetValue()); @@ -1790,7 +1789,7 @@ void EditorComponent::Update(float dt) pathTraceStatisticsLabel.SetText(ss); } - wiProfiler::EndRange(profrange); + wi::profiler::EndRange(profrange); RenderPath2D::Update(dt); @@ -1805,7 +1804,7 @@ void EditorComponent::PostUpdate() } void EditorComponent::Render() const { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); // Hovered item boxes: if (!cinemaModeCheckBox.GetCheck()) @@ -1819,7 +1818,7 @@ void EditorComponent::Render() const XMFLOAT4X4 hoverBox; XMStoreFloat4x4(&hoverBox, aabb.getAsBoxMatrix()); - wiRenderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0.5f, 0.5f)); + wi::renderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0.5f, 0.5f)); } const LightComponent* light = scene.lights.GetComponent(hovered.entity); @@ -1829,13 +1828,13 @@ void EditorComponent::Render() const XMFLOAT4X4 hoverBox; XMStoreFloat4x4(&hoverBox, aabb.getAsBoxMatrix()); - wiRenderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0, 0.5f)); + wi::renderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0, 0.5f)); } const DecalComponent* decal = scene.decals.GetComponent(hovered.entity); if (decal != nullptr) { - wiRenderer::DrawBox(decal->world, XMFLOAT4(0.5f, 0, 0.5f, 0.5f)); + wi::renderer::DrawBox(decal->world, XMFLOAT4(0.5f, 0, 0.5f, 0.5f)); } const EnvironmentProbeComponent* probe = scene.probes.GetComponent(hovered.entity); @@ -1845,15 +1844,15 @@ void EditorComponent::Render() const XMFLOAT4X4 hoverBox; XMStoreFloat4x4(&hoverBox, aabb.getAsBoxMatrix()); - wiRenderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0.5f, 0.5f)); + wi::renderer::DrawBox(hoverBox, XMFLOAT4(0.5f, 0.5f, 0.5f, 0.5f)); } - const wiHairParticle* hair = scene.hairs.GetComponent(hovered.entity); + const wi::HairParticleSystem* hair = scene.hairs.GetComponent(hovered.entity); if (hair != nullptr) { XMFLOAT4X4 hoverBox; XMStoreFloat4x4(&hoverBox, hair->aabb.getAsBoxMatrix()); - wiRenderer::DrawBox(hoverBox, XMFLOAT4(0, 0.5f, 0, 0.5f)); + wi::renderer::DrawBox(hoverBox, XMFLOAT4(0, 0.5f, 0, 0.5f)); } } @@ -1863,11 +1862,11 @@ void EditorComponent::Render() const for (size_t i = 0; i < scene.springs.GetCount(); ++i) { const SpringComponent& spring = scene.springs[i]; - wiRenderer::RenderablePoint point; + wi::renderer::RenderablePoint point; point.position = spring.center_of_mass; point.size = 0.05f; point.color = XMFLOAT4(1, 1, 0, 1); - wiRenderer::DrawPoint(point); + wi::renderer::DrawPoint(point); } } } @@ -1905,7 +1904,7 @@ void EditorComponent::Render() const // also display decal OBB: XMFLOAT4X4 selectionBox; selectionBox = decal->world; - wiRenderer::DrawBox(selectionBox, XMFLOAT4(1, 0, 1, 1)); + wi::renderer::DrawBox(selectionBox, XMFLOAT4(1, 0, 1, 1)); } const EnvironmentProbeComponent* probe = scene.probes.GetComponent(picked.entity); @@ -1915,7 +1914,7 @@ void EditorComponent::Render() const selectedAABB = AABB::Merge(selectedAABB, aabb); } - const wiHairParticle* hair = scene.hairs.GetComponent(picked.entity); + const wi::HairParticleSystem* hair = scene.hairs.GetComponent(picked.entity); if (hair != nullptr) { selectedAABB = AABB::Merge(selectedAABB, hair->aabb); @@ -1926,7 +1925,7 @@ void EditorComponent::Render() const XMFLOAT4X4 selectionBox; XMStoreFloat4x4(&selectionBox, selectedAABB.getAsBoxMatrix()); - wiRenderer::DrawBox(selectionBox, XMFLOAT4(1, 1, 1, 1)); + wi::renderer::DrawBox(selectionBox, XMFLOAT4(1, 1, 1, 1)); } paintToolWnd.DrawBrush(); @@ -1936,7 +1935,7 @@ void EditorComponent::Render() const // Selection outline: if(renderPath->GetDepthStencil() != nullptr && !translator.selected.empty()) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); CommandList cmd = device->BeginCommandList(); device->EventBegin("Editor - Selection Outline Mask", cmd); @@ -1946,13 +1945,13 @@ void EditorComponent::Render() const vp.height = (float)rt_selectionOutline[0].GetDesc().height; device->BindViewports(1, &vp, cmd); - wiImageParams fx; + wi::image::Params fx; fx.enableFullScreen(); - fx.stencilComp = STENCILMODE::STENCILMODE_EQUAL; + fx.stencilComp = wi::image::STENCILMODE::STENCILMODE_EQUAL; // We will specify the stencil ref in user-space, don't care about engine stencil refs here: // Otherwise would need to take into account engine ref and draw multiple permutations of stencil refs. - fx.stencilRefMode = STENCILREFMODE_USER; + fx.stencilRefMode = wi::image::STENCILREFMODE_USER; // Materials outline: { @@ -1960,7 +1959,7 @@ void EditorComponent::Render() const // Draw solid blocks of selected materials fx.stencilRef = EDITORSTENCILREF_HIGHLIGHT_MATERIAL; - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); device->RenderPassEnd(cmd); } @@ -1971,7 +1970,7 @@ void EditorComponent::Render() const // Draw solid blocks of selected objects fx.stencilRef = EDITORSTENCILREF_HIGHLIGHT_OBJECT; - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); device->RenderPassEnd(cmd); } @@ -1995,27 +1994,27 @@ void EditorComponent::Compose(CommandList cmd) const const float selectionColorIntensity = std::sin(selectionOutlineTimer * XM_2PI * 0.8f) * 0.5f + 0.5f; if (renderPath->GetDepthStencil() != nullptr && !translator.selected.empty()) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("Editor - Selection Outline", cmd); - wiRenderer::BindCommonResources(cmd); - float opacity = wiMath::Lerp(0.4f, 1.0f, selectionColorIntensity); + wi::renderer::BindCommonResources(cmd); + float opacity = wi::math::Lerp(0.4f, 1.0f, selectionColorIntensity); XMFLOAT4 col = selectionColor2; col.w *= opacity; - wiRenderer::Postprocess_Outline(rt_selectionOutline[0], cmd, 0.1f, 1, col); + wi::renderer::Postprocess_Outline(rt_selectionOutline[0], cmd, 0.1f, 1, col); col = selectionColor; col.w *= opacity; - wiRenderer::Postprocess_Outline(rt_selectionOutline[1], cmd, 0.1f, 1, col); + wi::renderer::Postprocess_Outline(rt_selectionOutline[1], cmd, 0.1f, 1, col); device->EventEnd(cmd); } - const CameraComponent& camera = wiScene::GetCamera(); + const CameraComponent& camera = wi::scene::GetCamera(); - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - const wiColor inactiveEntityColor = wiColor::fromFloat4(XMFLOAT4(1, 1, 1, 0.5f)); - const wiColor hoveredEntityColor = wiColor::fromFloat4(XMFLOAT4(1, 1, 1, 1)); - const XMFLOAT4 glow = wiMath::Lerp(wiMath::Lerp(XMFLOAT4(1, 1, 1, 1), selectionColor, 0.4f), selectionColor, selectionColorIntensity); - const wiColor selectedEntityColor = wiColor::fromFloat4(glow); + const wi::Color inactiveEntityColor = wi::Color::fromFloat4(XMFLOAT4(1, 1, 1, 0.5f)); + const wi::Color hoveredEntityColor = wi::Color::fromFloat4(XMFLOAT4(1, 1, 1, 1)); + const XMFLOAT4 glow = wi::math::Lerp(wi::math::Lerp(XMFLOAT4(1, 1, 1, 1), selectionColor, 0.4f), selectionColor, selectionColorIntensity); + const wi::Color selectedEntityColor = wi::Color::fromFloat4(glow); // remove camera jittering CameraComponent cam = *renderPath->camera; @@ -2025,7 +2024,7 @@ void EditorComponent::Compose(CommandList cmd) const const XMMATRIX R = XMLoadFloat3x3(&cam.rotationMatrix); - wiImageParams fx; + wi::image::Params fx; fx.customRotation = &R; fx.customProjection = &VP; @@ -2037,7 +2036,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.lights.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2060,16 +2059,16 @@ void EditorComponent::Compose(CommandList cmd) const switch (light.GetType()) { case LightComponent::POINT: - wiImage::Draw(&pointLightTex->texture, fx, cmd); + wi::image::Draw(&pointLightTex.GetTexture(), fx, cmd); break; case LightComponent::SPOT: - wiImage::Draw(&spotLightTex->texture, fx, cmd); + wi::image::Draw(&spotLightTex.GetTexture(), fx, cmd); break; case LightComponent::DIRECTIONAL: - wiImage::Draw(&dirLightTex->texture, fx, cmd); + wi::image::Draw(&dirLightTex.GetTexture(), fx, cmd); break; default: - wiImage::Draw(&areaLightTex->texture, fx, cmd); + wi::image::Draw(&areaLightTex.GetTexture(), fx, cmd); break; } } @@ -2083,7 +2082,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.decals.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2104,7 +2103,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&decalTex->texture, fx, cmd); + wi::image::Draw(&decalTex.GetTexture(), fx, cmd); } } @@ -2116,7 +2115,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.forces.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2137,7 +2136,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&forceFieldTex->texture, fx, cmd); + wi::image::Draw(&forceFieldTex.GetTexture(), fx, cmd); } } @@ -2149,7 +2148,7 @@ void EditorComponent::Compose(CommandList cmd) const const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2170,7 +2169,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&cameraTex->texture, fx, cmd); + wi::image::Draw(&cameraTex.GetTexture(), fx, cmd); } } @@ -2181,7 +2180,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.armatures.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2202,7 +2201,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&armatureTex->texture, fx, cmd); + wi::image::Draw(&armatureTex.GetTexture(), fx, cmd); } } @@ -2213,7 +2212,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.emitters.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2234,7 +2233,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&emitterTex->texture, fx, cmd); + wi::image::Draw(&emitterTex.GetTexture(), fx, cmd); } } @@ -2245,7 +2244,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.hairs.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2266,7 +2265,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&hairTex->texture, fx, cmd); + wi::image::Draw(&hairTex.GetTexture(), fx, cmd); } } @@ -2277,7 +2276,7 @@ void EditorComponent::Compose(CommandList cmd) const Entity entity = scene.sounds.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); - float dist = wiMath::Distance(transform.GetPosition(), camera.Eye) * 0.08f; + float dist = wi::math::Distance(transform.GetPosition(), camera.Eye) * 0.08f; fx.pos = transform.GetPosition(); fx.siz = XMFLOAT2(dist, dist); @@ -2298,7 +2297,7 @@ void EditorComponent::Compose(CommandList cmd) const } - wiImage::Draw(&soundTex->texture, fx, cmd); + wi::image::Draw(&soundTex.GetTexture(), fx, cmd); } } @@ -2311,15 +2310,15 @@ void EditorComponent::Compose(CommandList cmd) const RenderPath2D::Compose(cmd); } -void EditorComponent::PushToSceneGraphView(wiECS::Entity entity, int level) +void EditorComponent::PushToSceneGraphView(wi::ecs::Entity entity, int level) { if (scenegraphview_added_items.count(entity) != 0) { return; } - const Scene& scene = wiScene::GetScene(); + const Scene& scene = wi::scene::GetScene(); - wiTreeList::Item item; + wi::gui::TreeList::Item item; item.level = level; item.userdata = entity; item.selected = IsSelected(entity); @@ -2340,11 +2339,11 @@ void EditorComponent::PushToSceneGraphView(wiECS::Entity entity, int level) } void EditorComponent::RefreshSceneGraphView() { - const Scene& scene = wiScene::GetScene(); + const Scene& scene = wi::scene::GetScene(); for (int i = 0; i < sceneGraphView.GetItemCount(); ++i) { - const wiTreeList::Item& item = sceneGraphView.GetItem(i); + const wi::gui::TreeList::Item& item = sceneGraphView.GetItem(i); if (item.open) { scenegraphview_opened_items.insert((Entity)item.userdata); @@ -2374,7 +2373,7 @@ void EditorComponent::RefreshSceneGraphView() continue; } - wiTreeList::Item item; + wi::gui::TreeList::Item item; item.userdata = entity; item.selected = IsSelected(entity); item.open = scenegraphview_opened_items.count(entity) != 0; @@ -2394,7 +2393,7 @@ void EditorComponent::RefreshSceneGraphView() continue; } - wiTreeList::Item item; + wi::gui::TreeList::Item item; item.userdata = entity; item.selected = IsSelected(entity); item.open = scenegraphview_opened_items.count(entity) != 0; @@ -2415,7 +2414,7 @@ void EditorComponent::ClearSelected() } void EditorComponent::AddSelected(Entity entity) { - wiScene::PickResult res; + wi::scene::PickResult res; res.entity = entity; AddSelected(res); } @@ -2456,7 +2455,7 @@ void EditorComponent::ResetHistory() historyPos = -1; history.clear(); } -wiArchive& EditorComponent::AdvanceHistory() +wi::Archive& EditorComponent::AdvanceHistory() { historyPos++; @@ -2479,9 +2478,9 @@ void EditorComponent::ConsumeHistoryOperation(bool undo) historyPos++; } - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - wiArchive& archive = history[historyPos]; + wi::Archive& archive = history[historyPos]; archive.SetReadModeAndResetPos(true); int temp; @@ -2538,12 +2537,12 @@ void EditorComponent::ConsumeHistoryOperation(bool undo) { // Read selections states from archive: - wi::vector selectedBEFORE; + wi::vector selectedBEFORE; size_t selectionCountBEFORE; archive >> selectionCountBEFORE; for (size_t i = 0; i < selectionCountBEFORE; ++i) { - wiScene::PickResult sel; + wi::scene::PickResult sel; archive >> sel.entity; archive >> sel.position; archive >> sel.normal; @@ -2553,12 +2552,12 @@ void EditorComponent::ConsumeHistoryOperation(bool undo) selectedBEFORE.push_back(sel); } - wi::vector selectedAFTER; + wi::vector selectedAFTER; size_t selectionCountAFTER; archive >> selectionCountAFTER; for (size_t i = 0; i < selectionCountAFTER; ++i) { - wiScene::PickResult sel; + wi::scene::PickResult sel; archive >> sel.entity; archive >> sel.position; archive >> sel.normal; diff --git a/Editor/Editor.h b/Editor/Editor.h index d0a5e719b..19be5e553 100644 --- a/Editor/Editor.h +++ b/Editor/Editor.h @@ -24,21 +24,21 @@ #include "LayerWindow.h" #include "NameWindow.h" -class EditorLoadingScreen : public LoadingScreen +class EditorLoadingScreen : public wi::LoadingScreen { private: - wiSprite sprite; - wiSpriteFont font; + wi::Sprite sprite; + wi::SpriteFont font; public: void Load() override; void Update(float dt) override; }; class Editor; -class EditorComponent : public RenderPath2D +class EditorComponent : public wi::RenderPath2D { private: - std::shared_ptr pointLightTex, spotLightTex, dirLightTex, areaLightTex, decalTex, forceFieldTex, emitterTex, hairTex, cameraTex, armatureTex, soundTex; + wi::Resource pointLightTex, spotLightTex, dirLightTex, areaLightTex, decalTex, forceFieldTex, emitterTex, hairTex, cameraTex, armatureTex, soundTex; public: MaterialWindow materialWnd; PostprocessWindow postprocessWnd; @@ -64,61 +64,61 @@ public: Editor* main = nullptr; - wiButton rendererWnd_Toggle; - wiButton postprocessWnd_Toggle; - wiButton paintToolWnd_Toggle; - wiButton weatherWnd_Toggle; - wiButton objectWnd_Toggle; - wiButton meshWnd_Toggle; - wiButton materialWnd_Toggle; - wiButton cameraWnd_Toggle; - wiButton envProbeWnd_Toggle; - wiButton decalWnd_Toggle; - wiButton soundWnd_Toggle; - wiButton lightWnd_Toggle; - wiButton animWnd_Toggle; - wiButton emitterWnd_Toggle; - wiButton hairWnd_Toggle; - wiButton forceFieldWnd_Toggle; - wiButton springWnd_Toggle; - wiButton ikWnd_Toggle; - wiButton transformWnd_Toggle; - wiButton layerWnd_Toggle; - wiButton nameWnd_Toggle; - wiCheckBox translatorCheckBox; - wiCheckBox isScalatorCheckBox; - wiCheckBox isRotatorCheckBox; - wiCheckBox isTranslatorCheckBox; - wiButton saveButton; - wiComboBox saveModeComboBox; - wiButton modelButton; - wiButton scriptButton; - wiButton clearButton; - wiButton helpButton; - wiButton exitButton; - wiCheckBox profilerEnabledCheckBox; - wiCheckBox physicsEnabledCheckBox; - wiCheckBox cinemaModeCheckBox; - wiComboBox renderPathComboBox; - wiLabel helpLabel; + wi::gui::Button rendererWnd_Toggle; + wi::gui::Button postprocessWnd_Toggle; + wi::gui::Button paintToolWnd_Toggle; + wi::gui::Button weatherWnd_Toggle; + wi::gui::Button objectWnd_Toggle; + wi::gui::Button meshWnd_Toggle; + wi::gui::Button materialWnd_Toggle; + wi::gui::Button cameraWnd_Toggle; + wi::gui::Button envProbeWnd_Toggle; + wi::gui::Button decalWnd_Toggle; + wi::gui::Button soundWnd_Toggle; + wi::gui::Button lightWnd_Toggle; + wi::gui::Button animWnd_Toggle; + wi::gui::Button emitterWnd_Toggle; + wi::gui::Button hairWnd_Toggle; + wi::gui::Button forceFieldWnd_Toggle; + wi::gui::Button springWnd_Toggle; + wi::gui::Button ikWnd_Toggle; + wi::gui::Button transformWnd_Toggle; + wi::gui::Button layerWnd_Toggle; + wi::gui::Button nameWnd_Toggle; + wi::gui::CheckBox translatorCheckBox; + wi::gui::CheckBox isScalatorCheckBox; + wi::gui::CheckBox isRotatorCheckBox; + wi::gui::CheckBox isTranslatorCheckBox; + wi::gui::Button saveButton; + wi::gui::ComboBox saveModeComboBox; + wi::gui::Button modelButton; + wi::gui::Button scriptButton; + wi::gui::Button clearButton; + wi::gui::Button helpButton; + wi::gui::Button exitButton; + wi::gui::CheckBox profilerEnabledCheckBox; + wi::gui::CheckBox physicsEnabledCheckBox; + wi::gui::CheckBox cinemaModeCheckBox; + wi::gui::ComboBox renderPathComboBox; + wi::gui::Label helpLabel; - wiTreeList sceneGraphView; - wi::unordered_set scenegraphview_added_items; - wi::unordered_set scenegraphview_opened_items; - void PushToSceneGraphView(wiECS::Entity entity, int level); + wi::gui::TreeList sceneGraphView; + wi::unordered_set scenegraphview_added_items; + wi::unordered_set scenegraphview_opened_items; + void PushToSceneGraphView(wi::ecs::Entity entity, int level); void RefreshSceneGraphView(); - wiSlider pathTraceTargetSlider; - wiLabel pathTraceStatisticsLabel; + wi::gui::Slider pathTraceTargetSlider; + wi::gui::Label pathTraceStatisticsLabel; - std::unique_ptr renderPath; + std::unique_ptr renderPath; enum RENDERPATH { RENDERPATH_DEFAULT, RENDERPATH_PATHTRACING, }; void ChangeRenderPath(RENDERPATH path); - const wiGraphics::Texture* GetGUIBlurredBackground() const override { return renderPath->GetGUIBlurredBackground(); } + const wi::graphics::Texture* GetGUIBlurredBackground() const override { return renderPath->GetGUIBlurredBackground(); } void ResizeBuffers() override; void ResizeLayout() override; @@ -129,7 +129,7 @@ public: void Update(float dt) override; void PostUpdate() override; void Render() const override; - void Compose(wiGraphics::CommandList cmd) const override; + void Compose(wi::graphics::CommandList cmd) const override; enum EDITORSTENCILREF @@ -139,26 +139,26 @@ public: EDITORSTENCILREF_HIGHLIGHT_MATERIAL = 0x02, EDITORSTENCILREF_LAST = 0x0F, }; - wiGraphics::Texture rt_selectionOutline_MSAA; - wiGraphics::Texture rt_selectionOutline[2]; - wiGraphics::RenderPass renderpass_selectionOutline[2]; + wi::graphics::Texture rt_selectionOutline_MSAA; + wi::graphics::Texture rt_selectionOutline[2]; + wi::graphics::RenderPass renderpass_selectionOutline[2]; float selectionOutlineTimer = 0; const XMFLOAT4 selectionColor = XMFLOAT4(1, 0.6f, 0, 1); const XMFLOAT4 selectionColor2 = XMFLOAT4(0, 1, 0.6f, 0.35f); Translator translator; - wiScene::PickResult hovered; + wi::scene::PickResult hovered; void ClearSelected(); - void AddSelected(wiECS::Entity entity); - void AddSelected(const wiScene::PickResult& picked); - bool IsSelected(wiECS::Entity entity) const; + void AddSelected(wi::ecs::Entity entity); + void AddSelected(const wi::scene::PickResult& picked); + bool IsSelected(wi::ecs::Entity entity) const; - wiArchive clipboard; + wi::Archive clipboard; - wi::vector history; + wi::vector history; int historyPos = -1; enum HistoryOperationType { @@ -170,11 +170,11 @@ public: }; void ResetHistory(); - wiArchive& AdvanceHistory(); + wi::Archive& AdvanceHistory(); void ConsumeHistoryOperation(bool undo); }; -class Editor : public MainComponent +class Editor : public wi::Application { public: EditorComponent renderComponent; diff --git a/Editor/EmitterWindow.cpp b/Editor/EmitterWindow.cpp index 92f00f5d4..30daf7795 100644 --- a/Editor/EmitterWindow.cpp +++ b/Editor/EmitterWindow.cpp @@ -4,12 +4,12 @@ #include -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void EmitterWindow::Create(EditorComponent* editor) { - wiWindow::Create("Emitter Window"); + wi::gui::Window::Create("Emitter Window"); SetSize(XMFLOAT2(680, 700)); float x = 200; @@ -21,8 +21,8 @@ void EmitterWindow::Create(EditorComponent* editor) emitterNameField.Create("EmitterName"); emitterNameField.SetPos(XMFLOAT2(x, y += step)); emitterNameField.SetSize(XMFLOAT2(300, itemheight)); - emitterNameField.OnInputAccepted([=](wiEventArgs args) { - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + emitterNameField.OnInputAccepted([=](wi::gui::EventArgs args) { + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name != nullptr) { *name = args.sValue; @@ -35,8 +35,8 @@ void EmitterWindow::Create(EditorComponent* editor) addButton.Create("Add Emitter"); addButton.SetPos(XMFLOAT2(x, y += step)); addButton.SetSize(XMFLOAT2(150, itemheight)); - addButton.OnClick([=](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + addButton.OnClick([=](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); Entity entity = scene.Entity_CreateEmitter("editorEmitter"); editor->ClearSelected(); editor->AddSelected(entity); @@ -49,7 +49,7 @@ void EmitterWindow::Create(EditorComponent* editor) restartButton.Create("Restart Emitter"); restartButton.SetPos(XMFLOAT2(x + 160, y)); restartButton.SetSize(XMFLOAT2(150, itemheight)); - restartButton.OnClick([&](wiEventArgs args) { + restartButton.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -63,7 +63,7 @@ void EmitterWindow::Create(EditorComponent* editor) meshComboBox.SetSize(XMFLOAT2(300, itemheight)); meshComboBox.SetPos(XMFLOAT2(x, y += step)); meshComboBox.SetEnabled(false); - meshComboBox.OnSelect([&](wiEventArgs args) { + meshComboBox.OnSelect([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -73,7 +73,7 @@ void EmitterWindow::Create(EditorComponent* editor) } else { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); emitter->meshID = scene.meshes.GetEntity(args.iValue - 1); } } @@ -88,11 +88,11 @@ void EmitterWindow::Create(EditorComponent* editor) shaderTypeComboBox.AddItem("SOFT + DISTORTION"); shaderTypeComboBox.AddItem("SIMPLEST"); shaderTypeComboBox.AddItem("SOFT + LIGHTING"); - shaderTypeComboBox.OnSelect([&](wiEventArgs args) { + shaderTypeComboBox.OnSelect([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { - emitter->shaderType = (wiEmittedParticle::PARTICLESHADERTYPE)args.iValue; + emitter->shaderType = (wi::EmittedParticleSystem::PARTICLESHADERTYPE)args.iValue; } }); shaderTypeComboBox.SetEnabled(false); @@ -103,7 +103,7 @@ void EmitterWindow::Create(EditorComponent* editor) sortCheckBox.Create("Sorting Enabled: "); sortCheckBox.SetPos(XMFLOAT2(x, y += step)); sortCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - sortCheckBox.OnClick([&](wiEventArgs args) { + sortCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -118,7 +118,7 @@ void EmitterWindow::Create(EditorComponent* editor) depthCollisionsCheckBox.Create("Depth Buffer Collisions Enabled: "); depthCollisionsCheckBox.SetPos(XMFLOAT2(x + 250, y)); depthCollisionsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - depthCollisionsCheckBox.OnClick([&](wiEventArgs args) { + depthCollisionsCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -133,7 +133,7 @@ void EmitterWindow::Create(EditorComponent* editor) sphCheckBox.Create("SPH - FluidSim: "); sphCheckBox.SetPos(XMFLOAT2(x + 400, y)); sphCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - sphCheckBox.OnClick([&](wiEventArgs args) { + sphCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -148,7 +148,7 @@ void EmitterWindow::Create(EditorComponent* editor) pauseCheckBox.Create("PAUSE: "); pauseCheckBox.SetPos(XMFLOAT2(x, y += step)); pauseCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - pauseCheckBox.OnClick([&](wiEventArgs args) { + pauseCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -163,7 +163,7 @@ void EmitterWindow::Create(EditorComponent* editor) debugCheckBox.Create("DEBUG: "); debugCheckBox.SetPos(XMFLOAT2(x + 120, y)); debugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - debugCheckBox.OnClick([&](wiEventArgs args) { + debugCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -178,7 +178,7 @@ void EmitterWindow::Create(EditorComponent* editor) volumeCheckBox.Create("Volume: "); volumeCheckBox.SetPos(XMFLOAT2(x + 250, y)); volumeCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - volumeCheckBox.OnClick([&](wiEventArgs args) { + volumeCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -193,7 +193,7 @@ void EmitterWindow::Create(EditorComponent* editor) frameBlendingCheckBox.Create("Frame Blending: "); frameBlendingCheckBox.SetPos(XMFLOAT2(x + 400, y)); frameBlendingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - frameBlendingCheckBox.OnClick([&](wiEventArgs args) { + frameBlendingCheckBox.OnClick([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -220,7 +220,7 @@ void EmitterWindow::Create(EditorComponent* editor) frameRateInput.SetText(""); frameRateInput.SetTooltip("Enter a value to enable looping sprite sheet animation (frames per second). Set 0 for animation along paritcle lifetime."); frameRateInput.SetDescription("Frame Rate: "); - frameRateInput.OnInputAccepted([this](wiEventArgs args) { + frameRateInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -235,7 +235,7 @@ void EmitterWindow::Create(EditorComponent* editor) framesXInput.SetText(""); framesXInput.SetTooltip("How many horizontal frames there are in the spritesheet."); framesXInput.SetDescription("Frames X: "); - framesXInput.OnInputAccepted([this](wiEventArgs args) { + framesXInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -250,7 +250,7 @@ void EmitterWindow::Create(EditorComponent* editor) framesYInput.SetText(""); framesYInput.SetTooltip("How many vertical frames there are in the spritesheet."); framesYInput.SetDescription("Frames Y: "); - framesYInput.OnInputAccepted([this](wiEventArgs args) { + framesYInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -265,7 +265,7 @@ void EmitterWindow::Create(EditorComponent* editor) frameCountInput.SetText(""); frameCountInput.SetTooltip("Enter a value to enable the random sprite sheet frame selection's max frame number."); frameCountInput.SetDescription("Frame Count: "); - frameCountInput.OnInputAccepted([this](wiEventArgs args) { + frameCountInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -280,7 +280,7 @@ void EmitterWindow::Create(EditorComponent* editor) frameStartInput.SetText(""); frameStartInput.SetTooltip("Specifies the starting frame of the animation."); frameStartInput.SetDescription("Start Frame: "); - frameStartInput.OnInputAccepted([this](wiEventArgs args) { + frameStartInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -298,7 +298,7 @@ void EmitterWindow::Create(EditorComponent* editor) VelocityXInput.SetTooltip("Vector X component"); VelocityXInput.SetPos(XMFLOAT2(x, y += step)); VelocityXInput.SetSize(XMFLOAT2(38, itemheight)); - VelocityXInput.OnInputAccepted([&](wiEventArgs args) { + VelocityXInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -312,7 +312,7 @@ void EmitterWindow::Create(EditorComponent* editor) VelocityYInput.SetTooltip("Vector Y component"); VelocityYInput.SetPos(XMFLOAT2(x + 40, y)); VelocityYInput.SetSize(XMFLOAT2(38, itemheight)); - VelocityYInput.OnInputAccepted([&](wiEventArgs args) { + VelocityYInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -326,7 +326,7 @@ void EmitterWindow::Create(EditorComponent* editor) VelocityZInput.SetTooltip("Vector Z component"); VelocityZInput.SetPos(XMFLOAT2(x + 80, y)); VelocityZInput.SetSize(XMFLOAT2(38, itemheight)); - VelocityZInput.OnInputAccepted([&](wiEventArgs args) { + VelocityZInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -343,7 +343,7 @@ void EmitterWindow::Create(EditorComponent* editor) GravityXInput.SetTooltip("Vector X component"); GravityXInput.SetPos(XMFLOAT2(x + 200, y)); GravityXInput.SetSize(XMFLOAT2(38, itemheight)); - GravityXInput.OnInputAccepted([&](wiEventArgs args) { + GravityXInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -357,7 +357,7 @@ void EmitterWindow::Create(EditorComponent* editor) GravityYInput.SetTooltip("Vector Y component"); GravityYInput.SetPos(XMFLOAT2(x + 240, y)); GravityYInput.SetSize(XMFLOAT2(38, itemheight)); - GravityYInput.OnInputAccepted([&](wiEventArgs args) { + GravityYInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -371,7 +371,7 @@ void EmitterWindow::Create(EditorComponent* editor) GravityZInput.SetTooltip("Vector Z component"); GravityZInput.SetPos(XMFLOAT2(x + 280, y)); GravityZInput.SetSize(XMFLOAT2(38, itemheight)); - GravityZInput.OnInputAccepted([&](wiEventArgs args) { + GravityZInput.OnInputAccepted([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -383,7 +383,7 @@ void EmitterWindow::Create(EditorComponent* editor) maxParticlesSlider.Create(100.0f, 1000000.0f, 10000, 100000, "Max particle count: "); maxParticlesSlider.SetSize(XMFLOAT2(360, itemheight)); maxParticlesSlider.SetPos(XMFLOAT2(x, y += step)); - maxParticlesSlider.OnSlide([&](wiEventArgs args) { + maxParticlesSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -397,7 +397,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitCountSlider.Create(0.0f, 10000.0f, 1.0f, 100000, "Emit count per sec: "); emitCountSlider.SetSize(XMFLOAT2(360, itemheight)); emitCountSlider.SetPos(XMFLOAT2(x, y += step)); - emitCountSlider.OnSlide([&](wiEventArgs args) { + emitCountSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -411,7 +411,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitSizeSlider.Create(0.01f, 10.0f, 1.0f, 100000, "Size: "); emitSizeSlider.SetSize(XMFLOAT2(360, itemheight)); emitSizeSlider.SetPos(XMFLOAT2(x, y += step)); - emitSizeSlider.OnSlide([&](wiEventArgs args) { + emitSizeSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -425,7 +425,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitRotationSlider.Create(0.0f, 1.0f, 0.0f, 100000, "Rotation: "); emitRotationSlider.SetSize(XMFLOAT2(360, itemheight)); emitRotationSlider.SetPos(XMFLOAT2(x, y += step)); - emitRotationSlider.OnSlide([&](wiEventArgs args) { + emitRotationSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -439,7 +439,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitNormalSlider.Create(0.0f, 100.0f, 1.0f, 100000, "Normal factor: "); emitNormalSlider.SetSize(XMFLOAT2(360, itemheight)); emitNormalSlider.SetPos(XMFLOAT2(x, y += step)); - emitNormalSlider.OnSlide([&](wiEventArgs args) { + emitNormalSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -453,7 +453,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitScalingSlider.Create(0.0f, 100.0f, 1.0f, 100000, "Scaling: "); emitScalingSlider.SetSize(XMFLOAT2(360, itemheight)); emitScalingSlider.SetPos(XMFLOAT2(x, y += step)); - emitScalingSlider.OnSlide([&](wiEventArgs args) { + emitScalingSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -467,7 +467,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitLifeSlider.Create(0.0f, 100.0f, 1.0f, 10000, "Life span: "); emitLifeSlider.SetSize(XMFLOAT2(360, itemheight)); emitLifeSlider.SetPos(XMFLOAT2(x, y += step)); - emitLifeSlider.OnSlide([&](wiEventArgs args) { + emitLifeSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -481,7 +481,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitRandomnessSlider.Create(0.0f, 1.0f, 1.0f, 100000, "Randomness: "); emitRandomnessSlider.SetSize(XMFLOAT2(360, itemheight)); emitRandomnessSlider.SetPos(XMFLOAT2(x, y += step)); - emitRandomnessSlider.OnSlide([&](wiEventArgs args) { + emitRandomnessSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -495,7 +495,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitLifeRandomnessSlider.Create(0.0f, 2.0f, 0.0f, 100000, "Life randomness: "); emitLifeRandomnessSlider.SetSize(XMFLOAT2(360, itemheight)); emitLifeRandomnessSlider.SetPos(XMFLOAT2(x, y += step)); - emitLifeRandomnessSlider.OnSlide([&](wiEventArgs args) { + emitLifeRandomnessSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -509,7 +509,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitColorRandomnessSlider.Create(0.0f, 2.0f, 0.0f, 100000, "Color randomness: "); emitColorRandomnessSlider.SetSize(XMFLOAT2(360, itemheight)); emitColorRandomnessSlider.SetPos(XMFLOAT2(x, y += step)); - emitColorRandomnessSlider.OnSlide([&](wiEventArgs args) { + emitColorRandomnessSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -523,7 +523,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitMotionBlurSlider.Create(0.0f, 1.0f, 1.0f, 100000, "Motion blur: "); emitMotionBlurSlider.SetSize(XMFLOAT2(360, itemheight)); emitMotionBlurSlider.SetPos(XMFLOAT2(x, y += step)); - emitMotionBlurSlider.OnSlide([&](wiEventArgs args) { + emitMotionBlurSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -537,7 +537,7 @@ void EmitterWindow::Create(EditorComponent* editor) emitMassSlider.Create(0.1f, 100.0f, 1.0f, 100000, "Mass: "); emitMassSlider.SetSize(XMFLOAT2(360, itemheight)); emitMassSlider.SetPos(XMFLOAT2(x, y += step)); - emitMassSlider.OnSlide([&](wiEventArgs args) { + emitMassSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -553,7 +553,7 @@ void EmitterWindow::Create(EditorComponent* editor) timestepSlider.Create(-1, 0.016f, -1, 100000, "Timestep: "); timestepSlider.SetSize(XMFLOAT2(360, itemheight)); timestepSlider.SetPos(XMFLOAT2(x, y += step)); - timestepSlider.OnSlide([&](wiEventArgs args) { + timestepSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -569,7 +569,7 @@ void EmitterWindow::Create(EditorComponent* editor) dragSlider.Create(-1, 0.016f, -1, 100000, "Drag: "); dragSlider.SetSize(XMFLOAT2(360, itemheight)); dragSlider.SetPos(XMFLOAT2(x, y += step)); - dragSlider.OnSlide([&](wiEventArgs args) { + dragSlider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -587,7 +587,7 @@ void EmitterWindow::Create(EditorComponent* editor) sph_h_Slider.Create(0.1f, 100.0f, 1.0f, 100000, "SPH Smoothing Radius (h): "); sph_h_Slider.SetSize(XMFLOAT2(360, itemheight)); sph_h_Slider.SetPos(XMFLOAT2(x, y += step)); - sph_h_Slider.OnSlide([&](wiEventArgs args) { + sph_h_Slider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -601,7 +601,7 @@ void EmitterWindow::Create(EditorComponent* editor) sph_K_Slider.Create(0.1f, 100.0f, 1.0f, 100000, "SPH Pressure Constant (K): "); sph_K_Slider.SetSize(XMFLOAT2(360, itemheight)); sph_K_Slider.SetPos(XMFLOAT2(x, y += step)); - sph_K_Slider.OnSlide([&](wiEventArgs args) { + sph_K_Slider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -615,7 +615,7 @@ void EmitterWindow::Create(EditorComponent* editor) sph_p0_Slider.Create(0.1f, 100.0f, 1.0f, 100000, "SPH Reference Density (p0): "); sph_p0_Slider.SetSize(XMFLOAT2(360, itemheight)); sph_p0_Slider.SetPos(XMFLOAT2(x, y += step)); - sph_p0_Slider.OnSlide([&](wiEventArgs args) { + sph_p0_Slider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -629,7 +629,7 @@ void EmitterWindow::Create(EditorComponent* editor) sph_e_Slider.Create(0.1f, 100.0f, 1.0f, 100000, "SPH Viscosity (e): "); sph_e_Slider.SetSize(XMFLOAT2(360, itemheight)); sph_e_Slider.SetPos(XMFLOAT2(x, y += step)); - sph_e_Slider.OnSlide([&](wiEventArgs args) { + sph_e_Slider.OnSlide([&](wi::gui::EventArgs args) { auto emitter = GetEmitter(); if (emitter != nullptr) { @@ -715,15 +715,15 @@ void EmitterWindow::SetEntity(Entity entity) } -wiEmittedParticle* EmitterWindow::GetEmitter() +wi::EmittedParticleSystem* EmitterWindow::GetEmitter() { if (entity == INVALID_ENTITY) { return nullptr; } - Scene& scene = wiScene::GetScene(); - wiEmittedParticle* emitter = scene.emitters.GetComponent(entity); + Scene& scene = wi::scene::GetScene(); + wi::EmittedParticleSystem* emitter = scene.emitters.GetComponent(entity); return emitter; } @@ -736,7 +736,7 @@ void EmitterWindow::UpdateData() return; } - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); meshComboBox.ClearItems(); meshComboBox.AddItem("NO MESH"); diff --git a/Editor/EmitterWindow.h b/Editor/EmitterWindow.h index 580eb8202..0c8218aeb 100644 --- a/Editor/EmitterWindow.h +++ b/Editor/EmitterWindow.h @@ -5,62 +5,62 @@ class EditorComponent; class MaterialWindow; -class EmitterWindow : public wiWindow +class EmitterWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); void UpdateData(); - wiScene::wiEmittedParticle* GetEmitter(); + wi::EmittedParticleSystem* GetEmitter(); - wiTextInputField emitterNameField; - wiButton addButton; - wiButton restartButton; - wiComboBox meshComboBox; - wiComboBox shaderTypeComboBox; - wiLabel infoLabel; - wiSlider maxParticlesSlider; - wiCheckBox sortCheckBox; - wiCheckBox depthCollisionsCheckBox; - wiCheckBox sphCheckBox; - wiCheckBox pauseCheckBox; - wiCheckBox debugCheckBox; - wiCheckBox volumeCheckBox; - wiCheckBox frameBlendingCheckBox; - wiSlider emitCountSlider; - wiSlider emitSizeSlider; - wiSlider emitRotationSlider; - wiSlider emitNormalSlider; - wiSlider emitScalingSlider; - wiSlider emitLifeSlider; - wiSlider emitRandomnessSlider; - wiSlider emitLifeRandomnessSlider; - wiSlider emitColorRandomnessSlider; - wiSlider emitMotionBlurSlider; - wiSlider emitMassSlider; - wiSlider timestepSlider; - wiSlider dragSlider; - wiTextInputField VelocityXInput; - wiTextInputField VelocityYInput; - wiTextInputField VelocityZInput; - wiTextInputField GravityXInput; - wiTextInputField GravityYInput; - wiTextInputField GravityZInput; + wi::gui::TextInputField emitterNameField; + wi::gui::Button addButton; + wi::gui::Button restartButton; + wi::gui::ComboBox meshComboBox; + wi::gui::ComboBox shaderTypeComboBox; + wi::gui::Label infoLabel; + wi::gui::Slider maxParticlesSlider; + wi::gui::CheckBox sortCheckBox; + wi::gui::CheckBox depthCollisionsCheckBox; + wi::gui::CheckBox sphCheckBox; + wi::gui::CheckBox pauseCheckBox; + wi::gui::CheckBox debugCheckBox; + wi::gui::CheckBox volumeCheckBox; + wi::gui::CheckBox frameBlendingCheckBox; + wi::gui::Slider emitCountSlider; + wi::gui::Slider emitSizeSlider; + wi::gui::Slider emitRotationSlider; + wi::gui::Slider emitNormalSlider; + wi::gui::Slider emitScalingSlider; + wi::gui::Slider emitLifeSlider; + wi::gui::Slider emitRandomnessSlider; + wi::gui::Slider emitLifeRandomnessSlider; + wi::gui::Slider emitColorRandomnessSlider; + wi::gui::Slider emitMotionBlurSlider; + wi::gui::Slider emitMassSlider; + wi::gui::Slider timestepSlider; + wi::gui::Slider dragSlider; + wi::gui::TextInputField VelocityXInput; + wi::gui::TextInputField VelocityYInput; + wi::gui::TextInputField VelocityZInput; + wi::gui::TextInputField GravityXInput; + wi::gui::TextInputField GravityYInput; + wi::gui::TextInputField GravityZInput; - wiSlider sph_h_Slider; - wiSlider sph_K_Slider; - wiSlider sph_p0_Slider; - wiSlider sph_e_Slider; + wi::gui::Slider sph_h_Slider; + wi::gui::Slider sph_K_Slider; + wi::gui::Slider sph_p0_Slider; + wi::gui::Slider sph_e_Slider; - wiTextInputField frameRateInput; - wiTextInputField framesXInput; - wiTextInputField framesYInput; - wiTextInputField frameCountInput; - wiTextInputField frameStartInput; + wi::gui::TextInputField frameRateInput; + wi::gui::TextInputField framesXInput; + wi::gui::TextInputField framesYInput; + wi::gui::TextInputField frameCountInput; + wi::gui::TextInputField frameStartInput; }; diff --git a/Editor/EnvProbeWindow.cpp b/Editor/EnvProbeWindow.cpp index 3759354bf..53ffeb355 100644 --- a/Editor/EnvProbeWindow.cpp +++ b/Editor/EnvProbeWindow.cpp @@ -2,12 +2,12 @@ #include "EnvProbeWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void EnvProbeWindow::Create(EditorComponent* editor) { - wiWindow::Create("Environment Probe Window"); + wi::gui::Window::Create("Environment Probe Window"); SetSize(XMFLOAT2(300, 200)); float x = 100, y = 5, step = 35; @@ -15,8 +15,8 @@ void EnvProbeWindow::Create(EditorComponent* editor) realTimeCheckBox.Create("RealTime: "); realTimeCheckBox.SetPos(XMFLOAT2(x, y += step)); realTimeCheckBox.SetEnabled(false); - realTimeCheckBox.OnClick([&](wiEventArgs args) { - EnvironmentProbeComponent* probe = wiScene::GetScene().probes.GetComponent(entity); + realTimeCheckBox.OnClick([&](wi::gui::EventArgs args) { + EnvironmentProbeComponent* probe = wi::scene::GetScene().probes.GetComponent(entity); if (probe != nullptr) { probe->SetRealTime(args.bValue); @@ -27,10 +27,10 @@ void EnvProbeWindow::Create(EditorComponent* editor) generateButton.Create("Put"); generateButton.SetPos(XMFLOAT2(x, y += step)); - generateButton.OnClick([=](wiEventArgs args) { + generateButton.OnClick([=](wi::gui::EventArgs args) { XMFLOAT3 pos; - XMStoreFloat3(&pos, XMVectorAdd(wiScene::GetCamera().GetEye(), wiScene::GetCamera().GetAt() * 4)); - Entity entity = wiScene::GetScene().Entity_CreateEnvironmentProbe("editorProbe", pos); + XMStoreFloat3(&pos, XMVectorAdd(wi::scene::GetCamera().GetEye(), wi::scene::GetCamera().GetAt() * 4)); + Entity entity = wi::scene::GetScene().Entity_CreateEnvironmentProbe("editorProbe", pos); editor->ClearSelected(); editor->AddSelected(entity); editor->RefreshSceneGraphView(); @@ -41,8 +41,8 @@ void EnvProbeWindow::Create(EditorComponent* editor) refreshButton.Create("Refresh"); refreshButton.SetPos(XMFLOAT2(x, y += step)); refreshButton.SetEnabled(false); - refreshButton.OnClick([&](wiEventArgs args) { - EnvironmentProbeComponent* probe = wiScene::GetScene().probes.GetComponent(entity); + refreshButton.OnClick([&](wi::gui::EventArgs args) { + EnvironmentProbeComponent* probe = wi::scene::GetScene().probes.GetComponent(entity); if (probe != nullptr) { probe->SetDirty(); @@ -53,8 +53,8 @@ void EnvProbeWindow::Create(EditorComponent* editor) refreshAllButton.Create("Refresh All"); refreshAllButton.SetPos(XMFLOAT2(x, y += step)); refreshAllButton.SetEnabled(true); - refreshAllButton.OnClick([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + refreshAllButton.OnClick([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); for (size_t i = 0; i < scene.probes.GetCount(); ++i) { EnvironmentProbeComponent& probe = scene.probes[i]; @@ -76,7 +76,7 @@ void EnvProbeWindow::SetEntity(Entity entity) { this->entity = entity; - const EnvironmentProbeComponent* probe = wiScene::GetScene().probes.GetComponent(entity); + const EnvironmentProbeComponent* probe = wi::scene::GetScene().probes.GetComponent(entity); if (probe == nullptr) { diff --git a/Editor/EnvProbeWindow.h b/Editor/EnvProbeWindow.h index aa2b44313..627314997 100644 --- a/Editor/EnvProbeWindow.h +++ b/Editor/EnvProbeWindow.h @@ -3,17 +3,17 @@ class EditorComponent; -class EnvProbeWindow : public wiWindow +class EnvProbeWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiCheckBox realTimeCheckBox; - wiButton generateButton; - wiButton refreshButton; - wiButton refreshAllButton; + wi::gui::CheckBox realTimeCheckBox; + wi::gui::Button generateButton; + wi::gui::Button refreshButton; + wi::gui::Button refreshAllButton; }; diff --git a/Editor/ForceFieldWindow.cpp b/Editor/ForceFieldWindow.cpp index 3bc4ec05f..1488edb2c 100644 --- a/Editor/ForceFieldWindow.cpp +++ b/Editor/ForceFieldWindow.cpp @@ -2,13 +2,13 @@ #include "ForceFieldWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void ForceFieldWindow::Create(EditorComponent* editor) { - wiWindow::Create("Force Field Window"); + wi::gui::Window::Create("Force Field Window"); SetSize(XMFLOAT2(420, 120)); float x = 150; @@ -19,9 +19,9 @@ void ForceFieldWindow::Create(EditorComponent* editor) addButton.Create("Add Force Field"); addButton.SetSize(XMFLOAT2(150, hei)); addButton.SetPos(XMFLOAT2(x, y += step)); - addButton.OnClick([=](wiEventArgs args) { - Entity entity = wiScene::GetScene().Entity_CreateForce("editorForce"); - ForceFieldComponent* force = wiScene::GetScene().forces.GetComponent(entity); + addButton.OnClick([=](wi::gui::EventArgs args) { + Entity entity = wi::scene::GetScene().Entity_CreateForce("editorForce"); + ForceFieldComponent* force = wi::scene::GetScene().forces.GetComponent(entity); if (force != nullptr) { switch (typeComboBox.GetSelected()) @@ -53,8 +53,8 @@ void ForceFieldWindow::Create(EditorComponent* editor) typeComboBox.Create("Force Field type: "); typeComboBox.SetPos(XMFLOAT2(x, y += step)); typeComboBox.SetSize(XMFLOAT2(200, hei)); - typeComboBox.OnSelect([&](wiEventArgs args) { - ForceFieldComponent* force = wiScene::GetScene().forces.GetComponent(entity); + typeComboBox.OnSelect([&](wi::gui::EventArgs args) { + ForceFieldComponent* force = wi::scene::GetScene().forces.GetComponent(entity); if (force != nullptr && args.iValue >= 0) { switch (args.iValue) @@ -81,8 +81,8 @@ void ForceFieldWindow::Create(EditorComponent* editor) gravitySlider.Create(-10, 10, 0, 100000, "Gravity: "); gravitySlider.SetSize(XMFLOAT2(200, hei)); gravitySlider.SetPos(XMFLOAT2(x, y += step)); - gravitySlider.OnSlide([&](wiEventArgs args) { - ForceFieldComponent* force = wiScene::GetScene().forces.GetComponent(entity); + gravitySlider.OnSlide([&](wi::gui::EventArgs args) { + ForceFieldComponent* force = wi::scene::GetScene().forces.GetComponent(entity); if (force != nullptr) { force->gravity = args.fValue; @@ -96,8 +96,8 @@ void ForceFieldWindow::Create(EditorComponent* editor) rangeSlider.Create(0.0f, 100.0f, 10, 100000, "Range: "); rangeSlider.SetSize(XMFLOAT2(200, hei)); rangeSlider.SetPos(XMFLOAT2(x, y += step)); - rangeSlider.OnSlide([&](wiEventArgs args) { - ForceFieldComponent* force = wiScene::GetScene().forces.GetComponent(entity); + rangeSlider.OnSlide([&](wi::gui::EventArgs args) { + ForceFieldComponent* force = wi::scene::GetScene().forces.GetComponent(entity); if (force != nullptr) { force->range_local = args.fValue; @@ -119,7 +119,7 @@ void ForceFieldWindow::SetEntity(Entity entity) { this->entity = entity; - const ForceFieldComponent* force = wiScene::GetScene().forces.GetComponent(entity); + const ForceFieldComponent* force = wi::scene::GetScene().forces.GetComponent(entity); if (force != nullptr) { diff --git a/Editor/ForceFieldWindow.h b/Editor/ForceFieldWindow.h index 06491e967..ac9d326a6 100644 --- a/Editor/ForceFieldWindow.h +++ b/Editor/ForceFieldWindow.h @@ -3,17 +3,17 @@ class EditorComponent; -class ForceFieldWindow : public wiWindow +class ForceFieldWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiComboBox typeComboBox; - wiSlider gravitySlider; - wiSlider rangeSlider; - wiButton addButton; + wi::gui::ComboBox typeComboBox; + wi::gui::Slider gravitySlider; + wi::gui::Slider rangeSlider; + wi::gui::Button addButton; }; diff --git a/Editor/HairParticleWindow.cpp b/Editor/HairParticleWindow.cpp index 255bc9ed9..b787a08da 100644 --- a/Editor/HairParticleWindow.cpp +++ b/Editor/HairParticleWindow.cpp @@ -2,12 +2,12 @@ #include "HairParticleWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void HairParticleWindow::Create(EditorComponent* editor) { - wiWindow::Create("Hair Particle System Window"); + wi::gui::Window::Create("Hair Particle System Window"); SetSize(XMFLOAT2(600, 260)); float x = 160; @@ -19,8 +19,8 @@ void HairParticleWindow::Create(EditorComponent* editor) addButton.Create("Add Hair Particle System"); addButton.SetPos(XMFLOAT2(x, y += step)); addButton.SetSize(XMFLOAT2(200, hei)); - addButton.OnClick([=](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + addButton.OnClick([=](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); Entity entity = scene.Entity_CreateHair("editorHair"); editor->ClearSelected(); editor->AddSelected(entity); @@ -34,7 +34,7 @@ void HairParticleWindow::Create(EditorComponent* editor) meshComboBox.SetSize(XMFLOAT2(300, hei)); meshComboBox.SetPos(XMFLOAT2(x, y += step)); meshComboBox.SetEnabled(false); - meshComboBox.OnSelect([&](wiEventArgs args) { + meshComboBox.OnSelect([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -44,7 +44,7 @@ void HairParticleWindow::Create(EditorComponent* editor) } else { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); hair->meshID = scene.meshes.GetEntity(args.iValue - 1); } } @@ -55,7 +55,7 @@ void HairParticleWindow::Create(EditorComponent* editor) countSlider.Create(0, 100000, 1000, 100000, "Strand Count: "); countSlider.SetSize(XMFLOAT2(360, hei)); countSlider.SetPos(XMFLOAT2(x, y += step)); - countSlider.OnSlide([&](wiEventArgs args) { + countSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -69,7 +69,7 @@ void HairParticleWindow::Create(EditorComponent* editor) lengthSlider.Create(0, 4, 1, 100000, "Particle Length: "); lengthSlider.SetSize(XMFLOAT2(360, hei)); lengthSlider.SetPos(XMFLOAT2(x, y += step)); - lengthSlider.OnSlide([&](wiEventArgs args) { + lengthSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -83,7 +83,7 @@ void HairParticleWindow::Create(EditorComponent* editor) stiffnessSlider.Create(0, 20, 5, 100000, "Particle Stiffness: "); stiffnessSlider.SetSize(XMFLOAT2(360, hei)); stiffnessSlider.SetPos(XMFLOAT2(x, y += step)); - stiffnessSlider.OnSlide([&](wiEventArgs args) { + stiffnessSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -97,7 +97,7 @@ void HairParticleWindow::Create(EditorComponent* editor) randomnessSlider.Create(0, 1, 0.2f, 100000, "Particle Randomness: "); randomnessSlider.SetSize(XMFLOAT2(360, hei)); randomnessSlider.SetPos(XMFLOAT2(x, y += step)); - randomnessSlider.OnSlide([&](wiEventArgs args) { + randomnessSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -111,7 +111,7 @@ void HairParticleWindow::Create(EditorComponent* editor) segmentcountSlider.Create(1, 10, 1, 9, "Segment Count: "); segmentcountSlider.SetSize(XMFLOAT2(360, hei)); segmentcountSlider.SetPos(XMFLOAT2(x, y += step)); - segmentcountSlider.OnSlide([&](wiEventArgs args) { + segmentcountSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -125,7 +125,7 @@ void HairParticleWindow::Create(EditorComponent* editor) randomSeedSlider.Create(1, 12345, 1, 12344, "Random seed: "); randomSeedSlider.SetSize(XMFLOAT2(360, hei)); randomSeedSlider.SetPos(XMFLOAT2(x, y += step)); - randomSeedSlider.OnSlide([&](wiEventArgs args) { + randomSeedSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -139,7 +139,7 @@ void HairParticleWindow::Create(EditorComponent* editor) viewDistanceSlider.Create(0, 1000, 100, 10000, "View distance: "); viewDistanceSlider.SetSize(XMFLOAT2(360, hei)); viewDistanceSlider.SetPos(XMFLOAT2(x, y += step)); - viewDistanceSlider.OnSlide([&](wiEventArgs args) { + viewDistanceSlider.OnSlide([&](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -156,7 +156,7 @@ void HairParticleWindow::Create(EditorComponent* editor) framesXInput.SetText(""); framesXInput.SetTooltip("How many horizontal frames there are in the spritesheet."); framesXInput.SetDescription("Frames X: "); - framesXInput.OnInputAccepted([this](wiEventArgs args) { + framesXInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -171,7 +171,7 @@ void HairParticleWindow::Create(EditorComponent* editor) framesYInput.SetText(""); framesYInput.SetTooltip("How many vertical frames there are in the spritesheet."); framesYInput.SetDescription("Frames Y: "); - framesYInput.OnInputAccepted([this](wiEventArgs args) { + framesYInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -188,7 +188,7 @@ void HairParticleWindow::Create(EditorComponent* editor) frameCountInput.SetText(""); frameCountInput.SetTooltip("Enter a value to enable the random sprite sheet frame selection's max frame number."); frameCountInput.SetDescription("Frame Count: "); - frameCountInput.OnInputAccepted([this](wiEventArgs args) { + frameCountInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -203,7 +203,7 @@ void HairParticleWindow::Create(EditorComponent* editor) frameStartInput.SetText(""); frameStartInput.SetTooltip("Specifies the first frame of the sheet that can be used."); frameStartInput.SetDescription("First Frame: "); - frameStartInput.OnInputAccepted([this](wiEventArgs args) { + frameStartInput.OnInputAccepted([this](wi::gui::EventArgs args) { auto hair = GetHair(); if (hair != nullptr) { @@ -251,15 +251,15 @@ void HairParticleWindow::SetEntity(Entity entity) addButton.SetEnabled(true); } -wiHairParticle* HairParticleWindow::GetHair() +wi::HairParticleSystem* HairParticleWindow::GetHair() { if (entity == INVALID_ENTITY) { return nullptr; } - Scene& scene = wiScene::GetScene(); - wiHairParticle* hair = scene.hairs.GetComponent(entity); + Scene& scene = wi::scene::GetScene(); + wi::HairParticleSystem* hair = scene.hairs.GetComponent(entity); return hair; } @@ -272,7 +272,7 @@ void HairParticleWindow::UpdateData() return; } - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); meshComboBox.ClearItems(); meshComboBox.AddItem("NO MESH"); diff --git a/Editor/HairParticleWindow.h b/Editor/HairParticleWindow.h index dc12a70e9..a972fd223 100644 --- a/Editor/HairParticleWindow.h +++ b/Editor/HairParticleWindow.h @@ -5,31 +5,31 @@ class EditorComponent; class MaterialWindow; -class HairParticleWindow : public wiWindow +class HairParticleWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); void UpdateData(); - wiScene::wiHairParticle* GetHair(); + wi::HairParticleSystem* GetHair(); - wiButton addButton; - wiComboBox meshComboBox; - wiSlider lengthSlider; - wiSlider stiffnessSlider; - wiSlider randomnessSlider; - wiSlider countSlider; - wiSlider segmentcountSlider; - wiSlider randomSeedSlider; - wiSlider viewDistanceSlider; - wiTextInputField framesXInput; - wiTextInputField framesYInput; - wiTextInputField frameCountInput; - wiTextInputField frameStartInput; + wi::gui::Button addButton; + wi::gui::ComboBox meshComboBox; + wi::gui::Slider lengthSlider; + wi::gui::Slider stiffnessSlider; + wi::gui::Slider randomnessSlider; + wi::gui::Slider countSlider; + wi::gui::Slider segmentcountSlider; + wi::gui::Slider randomSeedSlider; + wi::gui::Slider viewDistanceSlider; + wi::gui::TextInputField framesXInput; + wi::gui::TextInputField framesYInput; + wi::gui::TextInputField frameCountInput; + wi::gui::TextInputField frameStartInput; }; diff --git a/Editor/IKWindow.cpp b/Editor/IKWindow.cpp index d51bbde65..9c58f3d9f 100644 --- a/Editor/IKWindow.cpp +++ b/Editor/IKWindow.cpp @@ -2,13 +2,13 @@ #include "IKWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void IKWindow::Create(EditorComponent* editor) { - wiWindow::Create("Inverse Kinematics (IK) Window"); + wi::gui::Window::Create("Inverse Kinematics (IK) Window"); SetSize(XMFLOAT2(400, 150)); float x = 120; @@ -27,8 +27,8 @@ void IKWindow::Create(EditorComponent* editor) targetCombo.SetSize(XMFLOAT2(siz, hei)); targetCombo.SetPos(XMFLOAT2(x, y += step)); targetCombo.SetEnabled(false); - targetCombo.OnSelect([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + targetCombo.OnSelect([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity); if (ik != nullptr) { @@ -49,8 +49,8 @@ void IKWindow::Create(EditorComponent* editor) disabledCheckBox.SetTooltip("Disable simulation."); disabledCheckBox.SetPos(XMFLOAT2(x, y += step)); disabledCheckBox.SetSize(XMFLOAT2(hei, hei)); - disabledCheckBox.OnClick([=](wiEventArgs args) { - wiScene::GetScene().inverse_kinematics.GetComponent(entity)->SetDisabled(args.bValue); + disabledCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().inverse_kinematics.GetComponent(entity)->SetDisabled(args.bValue); }); AddWidget(&disabledCheckBox); @@ -58,8 +58,8 @@ void IKWindow::Create(EditorComponent* editor) chainLengthSlider.SetTooltip("How far the hierarchy chain is simulated backwards from this entity"); chainLengthSlider.SetPos(XMFLOAT2(x, y += step)); chainLengthSlider.SetSize(XMFLOAT2(siz, hei)); - chainLengthSlider.OnSlide([&](wiEventArgs args) { - wiScene::GetScene().inverse_kinematics.GetComponent(entity)->chain_length = args.iValue; + chainLengthSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::scene::GetScene().inverse_kinematics.GetComponent(entity)->chain_length = args.iValue; }); AddWidget(&chainLengthSlider); @@ -67,8 +67,8 @@ void IKWindow::Create(EditorComponent* editor) iterationCountSlider.SetTooltip("How many iterations to compute the inverse kinematics for. Higher values are slower but more accurate."); iterationCountSlider.SetPos(XMFLOAT2(x, y += step)); iterationCountSlider.SetSize(XMFLOAT2(siz, hei)); - iterationCountSlider.OnSlide([&](wiEventArgs args) { - wiScene::GetScene().inverse_kinematics.GetComponent(entity)->iteration_count = args.iValue; + iterationCountSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::scene::GetScene().inverse_kinematics.GetComponent(entity)->iteration_count = args.iValue; }); AddWidget(&iterationCountSlider); @@ -82,7 +82,7 @@ void IKWindow::SetEntity(Entity entity) { this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); const InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity); if (ik != nullptr) @@ -112,7 +112,7 @@ void IKWindow::SetEntity(Entity entity) SetEnabled(false); } - const TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + const TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { createButton.SetEnabled(true); @@ -120,16 +120,16 @@ void IKWindow::SetEntity(Entity entity) if (ik == nullptr) { createButton.SetText("Create"); - createButton.OnClick([=](wiEventArgs args) { - wiScene::GetScene().inverse_kinematics.Create(entity).chain_length = 1; + createButton.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().inverse_kinematics.Create(entity).chain_length = 1; SetEntity(entity); }); } else { createButton.SetText("Remove"); - createButton.OnClick([=](wiEventArgs args) { - wiScene::GetScene().inverse_kinematics.Remove_KeepSorted(entity); + createButton.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().inverse_kinematics.Remove_KeepSorted(entity); SetEntity(entity); }); } diff --git a/Editor/IKWindow.h b/Editor/IKWindow.h index 5ae99cef0..dfd71acc1 100644 --- a/Editor/IKWindow.h +++ b/Editor/IKWindow.h @@ -3,18 +3,18 @@ class EditorComponent; -class IKWindow : public wiWindow +class IKWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiButton createButton; - wiComboBox targetCombo; - wiCheckBox disabledCheckBox; - wiSlider chainLengthSlider; - wiSlider iterationCountSlider; + wi::gui::Button createButton; + wi::gui::ComboBox targetCombo; + wi::gui::CheckBox disabledCheckBox; + wi::gui::Slider chainLengthSlider; + wi::gui::Slider iterationCountSlider; }; diff --git a/Editor/LayerWindow.cpp b/Editor/LayerWindow.cpp index f25bf244e..462dfe185 100644 --- a/Editor/LayerWindow.cpp +++ b/Editor/LayerWindow.cpp @@ -2,13 +2,13 @@ #include "LayerWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void LayerWindow::Create(EditorComponent* editor) { - wiWindow::Create("Layer Window"); + wi::gui::Window::Create("Layer Window"); SetSize(XMFLOAT2(410, 160)); float x = 30; @@ -21,12 +21,12 @@ void LayerWindow::Create(EditorComponent* editor) layers[i].Create(""); layers[i].SetText(std::to_string(i) + ": "); layers[i].SetPos(XMFLOAT2(x + (i % 8) * 50, y + (i / 8 + 1) * step)); - layers[i].OnClick([=](wiEventArgs args) { + layers[i].OnClick([=](wi::gui::EventArgs args) { - LayerComponent* layer = wiScene::GetScene().layers.GetComponent(entity); + LayerComponent* layer = wi::scene::GetScene().layers.GetComponent(entity); if (layer == nullptr) { - layer = &wiScene::GetScene().layers.Create(entity); + layer = &wi::scene::GetScene().layers.Create(entity); } if (args.bValue) @@ -46,11 +46,11 @@ void LayerWindow::Create(EditorComponent* editor) enableAllButton.Create("Enable ALL"); enableAllButton.SetPos(XMFLOAT2(x, y)); - enableAllButton.OnClick([this](wiEventArgs args) { - LayerComponent* layer = wiScene::GetScene().layers.GetComponent(entity); + enableAllButton.OnClick([this](wi::gui::EventArgs args) { + LayerComponent* layer = wi::scene::GetScene().layers.GetComponent(entity); if (layer == nullptr) { - layer = &wiScene::GetScene().layers.Create(entity); + layer = &wi::scene::GetScene().layers.Create(entity); } if (layer == nullptr) return; @@ -60,11 +60,11 @@ void LayerWindow::Create(EditorComponent* editor) enableNoneButton.Create("Enable NONE"); enableNoneButton.SetPos(XMFLOAT2(x + 120, y)); - enableNoneButton.OnClick([this](wiEventArgs args) { - LayerComponent* layer = wiScene::GetScene().layers.GetComponent(entity); + enableNoneButton.OnClick([this](wi::gui::EventArgs args) { + LayerComponent* layer = wi::scene::GetScene().layers.GetComponent(entity); if (layer == nullptr) { - layer = &wiScene::GetScene().layers.Create(entity); + layer = &wi::scene::GetScene().layers.Create(entity); } if (layer == nullptr) return; @@ -86,7 +86,7 @@ void LayerWindow::SetEntity(Entity entity) { SetEnabled(true); - LayerComponent* layer = wiScene::GetScene().layers.GetComponent(entity); + LayerComponent* layer = wi::scene::GetScene().layers.GetComponent(entity); if (layer == nullptr) { for (uint32_t i = 0; i < 32; ++i) @@ -101,13 +101,13 @@ void LayerWindow::SetEntity(Entity entity) layers[i].SetCheck(layer->GetLayerMask() & 1 << i); } - HierarchyComponent* hier = wiScene::GetScene().hierarchy.GetComponent(entity); + HierarchyComponent* hier = wi::scene::GetScene().hierarchy.GetComponent(entity); if (hier != nullptr) { hier->layerMask_bind = layer->layerMask; } - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetDirty(); diff --git a/Editor/LayerWindow.h b/Editor/LayerWindow.h index 97d009316..23ed7ce24 100644 --- a/Editor/LayerWindow.h +++ b/Editor/LayerWindow.h @@ -3,16 +3,16 @@ class EditorComponent; -class LayerWindow : public wiWindow +class LayerWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiCheckBox layers[32]; - wiButton enableAllButton; - wiButton enableNoneButton; + wi::gui::CheckBox layers[32]; + wi::gui::Button enableAllButton; + wi::gui::Button enableNoneButton; }; diff --git a/Editor/LightWindow.cpp b/Editor/LightWindow.cpp index cb49b053e..0995c8bc8 100644 --- a/Editor/LightWindow.cpp +++ b/Editor/LightWindow.cpp @@ -4,14 +4,14 @@ #include -using namespace wiECS; -using namespace wiGraphics; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::graphics; +using namespace wi::scene; void LightWindow::Create(EditorComponent* editor) { - wiWindow::Create("Light Window"); + wi::gui::Window::Create("Light Window"); SetSize(XMFLOAT2(650, 500)); float x = 450; @@ -22,8 +22,8 @@ void LightWindow::Create(EditorComponent* editor) energySlider.Create(0.1f, 64, 0, 100000, "Energy: "); energySlider.SetSize(XMFLOAT2(100, hei)); energySlider.SetPos(XMFLOAT2(x, y += step)); - energySlider.OnSlide([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + energySlider.OnSlide([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->energy = args.fValue; @@ -36,8 +36,8 @@ void LightWindow::Create(EditorComponent* editor) rangeSlider.Create(1, 1000, 0, 100000, "Range: "); rangeSlider.SetSize(XMFLOAT2(100, hei)); rangeSlider.SetPos(XMFLOAT2(x, y += step)); - rangeSlider.OnSlide([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + rangeSlider.OnSlide([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->range_local = args.fValue; @@ -50,8 +50,8 @@ void LightWindow::Create(EditorComponent* editor) //radiusSlider.Create(0.01f, 10, 0, 100000, "Radius: "); //radiusSlider.SetSize(XMFLOAT2(100, hei)); //radiusSlider.SetPos(XMFLOAT2(x, y += step)); - //radiusSlider.OnSlide([&](wiEventArgs args) { - // LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + //radiusSlider.OnSlide([&](wi::gui::EventArgs args) { + // LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); // if (light != nullptr) // { // light->radius = args.fValue; @@ -64,8 +64,8 @@ void LightWindow::Create(EditorComponent* editor) //widthSlider.Create(1, 10, 0, 100000, "Width: "); //widthSlider.SetSize(XMFLOAT2(100, hei)); //widthSlider.SetPos(XMFLOAT2(x, y += step)); - //widthSlider.OnSlide([&](wiEventArgs args) { - // LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + //widthSlider.OnSlide([&](wi::gui::EventArgs args) { + // LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); // if (light != nullptr) // { // light->width = args.fValue; @@ -78,8 +78,8 @@ void LightWindow::Create(EditorComponent* editor) //heightSlider.Create(1, 10, 0, 100000, "Height: "); //heightSlider.SetSize(XMFLOAT2(100, hei)); //heightSlider.SetPos(XMFLOAT2(x, y += step)); - //heightSlider.OnSlide([&](wiEventArgs args) { - // LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + //heightSlider.OnSlide([&](wi::gui::EventArgs args) { + // LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); // if (light != nullptr) // { // light->height = args.fValue; @@ -92,8 +92,8 @@ void LightWindow::Create(EditorComponent* editor) fovSlider.Create(0.1f, XM_PI - 0.01f, 0, 100000, "FOV: "); fovSlider.SetSize(XMFLOAT2(100, hei)); fovSlider.SetPos(XMFLOAT2(x, y += step)); - fovSlider.OnSlide([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + fovSlider.OnSlide([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->fov = args.fValue; @@ -106,8 +106,8 @@ void LightWindow::Create(EditorComponent* editor) shadowCheckBox.Create("Shadow: "); shadowCheckBox.SetSize(XMFLOAT2(hei, hei)); shadowCheckBox.SetPos(XMFLOAT2(x, y += step)); - shadowCheckBox.OnClick([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + shadowCheckBox.OnClick([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->SetCastShadow(args.bValue); @@ -120,8 +120,8 @@ void LightWindow::Create(EditorComponent* editor) volumetricsCheckBox.Create("Volumetric: "); volumetricsCheckBox.SetSize(XMFLOAT2(hei, hei)); volumetricsCheckBox.SetPos(XMFLOAT2(x, y += step)); - volumetricsCheckBox.OnClick([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + volumetricsCheckBox.OnClick([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->SetVolumetricsEnabled(args.bValue); @@ -134,8 +134,8 @@ void LightWindow::Create(EditorComponent* editor) haloCheckBox.Create("Visualizer: "); haloCheckBox.SetSize(XMFLOAT2(hei, hei)); haloCheckBox.SetPos(XMFLOAT2(x, y += step)); - haloCheckBox.OnClick([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + haloCheckBox.OnClick([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->SetVisualizerEnabled(args.bValue); @@ -148,8 +148,8 @@ void LightWindow::Create(EditorComponent* editor) staticCheckBox.Create("Static: "); staticCheckBox.SetSize(XMFLOAT2(hei, hei)); staticCheckBox.SetPos(XMFLOAT2(x, y += step)); - staticCheckBox.OnClick([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + staticCheckBox.OnClick([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->SetStatic(args.bValue); @@ -162,9 +162,9 @@ void LightWindow::Create(EditorComponent* editor) addLightButton.Create("Add Light"); addLightButton.SetPos(XMFLOAT2(x, y += step)); addLightButton.SetSize(XMFLOAT2(150, hei)); - addLightButton.OnClick([=](wiEventArgs args) { - Entity entity = wiScene::GetScene().Entity_CreateLight("editorLight", XMFLOAT3(0, 3, 0), XMFLOAT3(1, 1, 1), 2, 60); - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + addLightButton.OnClick([=](wi::gui::EventArgs args) { + Entity entity = wi::scene::GetScene().Entity_CreateLight("editorLight", XMFLOAT3(0, 3, 0), XMFLOAT3(1, 1, 1), 2, 60); + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->type = (LightComponent::LightType)typeSelectorComboBox.GetSelected(); @@ -186,8 +186,8 @@ void LightWindow::Create(EditorComponent* editor) colorPicker.SetPos(XMFLOAT2(10, 30)); colorPicker.SetVisible(true); colorPicker.SetEnabled(false); - colorPicker.OnColorChanged([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + colorPicker.OnColorChanged([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { light->color = args.color.toFloat3(); @@ -198,8 +198,8 @@ void LightWindow::Create(EditorComponent* editor) typeSelectorComboBox.Create("Type: "); typeSelectorComboBox.SetSize(XMFLOAT2(150, hei)); typeSelectorComboBox.SetPos(XMFLOAT2(x, y += step)); - typeSelectorComboBox.OnSelect([&](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + typeSelectorComboBox.OnSelect([&](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr && args.iValue >= 0) { light->SetType((LightComponent::LightType)args.iValue); @@ -236,8 +236,8 @@ void LightWindow::Create(EditorComponent* editor) lensflare_Button[i].SetTooltip("Load a lensflare texture to this slot"); lensflare_Button[i].SetPos(XMFLOAT2(x, y += step)); lensflare_Button[i].SetSize(XMFLOAT2(260, hei)); - lensflare_Button[i].OnClick([=](wiEventArgs args) { - LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + lensflare_Button[i].OnClick([=](wi::gui::EventArgs args) { + LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light == nullptr) return; @@ -247,23 +247,23 @@ void LightWindow::Create(EditorComponent* editor) light->lensFlareNames.resize(i + 1); } - if (light->lensFlareRimTextures[i] != nullptr) + if (light->lensFlareRimTextures[i].IsValid()) { light->lensFlareNames[i] = ""; - light->lensFlareRimTextures[i] = nullptr; + light->lensFlareRimTextures[i] = {}; lensflare_Button[i].SetText(""); } else { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Texture"; - params.extensions = wiResourceManager::GetSupportedImageExtensions(); - wiHelper::FileDialog(params, [this, light, i](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { - light->lensFlareRimTextures[i] = wiResourceManager::Load(fileName, wiResourceManager::IMPORT_RETAIN_FILEDATA); + params.extensions = wi::resourcemanager::GetSupportedImageExtensions(); + wi::helper::FileDialog(params, [this, light, i](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + light->lensFlareRimTextures[i] = wi::resourcemanager::Load(fileName, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); light->lensFlareNames[i] = fileName; - lensflare_Button[i].SetText(wiHelper::GetFileNameFromPath(fileName)); + lensflare_Button[i].SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } @@ -282,7 +282,7 @@ void LightWindow::SetEntity(Entity entity) { this->entity = entity; - const LightComponent* light = wiScene::GetScene().lights.GetComponent(entity); + const LightComponent* light = wi::scene::GetScene().lights.GetComponent(entity); if (light != nullptr) { @@ -302,16 +302,16 @@ void LightWindow::SetEntity(Entity entity) staticCheckBox.SetEnabled(true); staticCheckBox.SetCheck(light->IsStatic()); colorPicker.SetEnabled(true); - colorPicker.SetPickColor(wiColor::fromFloat3(light->color)); + colorPicker.SetPickColor(wi::Color::fromFloat3(light->color)); typeSelectorComboBox.SetSelected((int)light->GetType()); SetLightType(light->GetType()); for (size_t i = 0; i < arraysize(lensflare_Button); ++i) { - if (light->lensFlareRimTextures.size() > i && light->lensFlareRimTextures[i] && !light->lensFlareNames[i].empty()) + if (light->lensFlareRimTextures.size() > i && light->lensFlareRimTextures[i].IsValid() && !light->lensFlareNames[i].empty()) { - lensflare_Button[i].SetText(wiHelper::GetFileNameFromPath(light->lensFlareNames[i])); + lensflare_Button[i].SetText(wi::helper::GetFileNameFromPath(light->lensFlareNames[i])); } else { diff --git a/Editor/LightWindow.h b/Editor/LightWindow.h index a0d1e2b8b..f3b4b612f 100644 --- a/Editor/LightWindow.h +++ b/Editor/LightWindow.h @@ -3,31 +3,31 @@ class EditorComponent; -class LightWindow : public wiWindow +class LightWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - void SetLightType(wiScene::LightComponent::LightType type); + void SetLightType(wi::scene::LightComponent::LightType type); - wiSlider energySlider; - wiSlider rangeSlider; - wiSlider radiusSlider; - wiSlider widthSlider; - wiSlider heightSlider; - wiSlider fovSlider; - wiCheckBox shadowCheckBox; - wiCheckBox haloCheckBox; - wiCheckBox volumetricsCheckBox; - wiCheckBox staticCheckBox; - wiButton addLightButton; - wiColorPicker colorPicker; - wiComboBox typeSelectorComboBox; + wi::gui::Slider energySlider; + wi::gui::Slider rangeSlider; + wi::gui::Slider radiusSlider; + wi::gui::Slider widthSlider; + wi::gui::Slider heightSlider; + wi::gui::Slider fovSlider; + wi::gui::CheckBox shadowCheckBox; + wi::gui::CheckBox haloCheckBox; + wi::gui::CheckBox volumetricsCheckBox; + wi::gui::CheckBox staticCheckBox; + wi::gui::Button addLightButton; + wi::gui::ColorPicker colorPicker; + wi::gui::ComboBox typeSelectorComboBox; - wiLabel lensflare_Label; - wiButton lensflare_Button[7]; + wi::gui::Label lensflare_Label; + wi::gui::Button lensflare_Button[7]; }; diff --git a/Editor/MaterialWindow.cpp b/Editor/MaterialWindow.cpp index 8491ea309..17f5d9063 100644 --- a/Editor/MaterialWindow.cpp +++ b/Editor/MaterialWindow.cpp @@ -2,13 +2,13 @@ #include "MaterialWindow.h" #include "Editor.h" -using namespace wiGraphics; -using namespace wiECS; -using namespace wiScene; +using namespace wi::graphics; +using namespace wi::ecs; +using namespace wi::scene; void MaterialWindow::Create(EditorComponent* editor) { - wiWindow::Create("Material Window"); + wi::gui::Window::Create("Material Window"); SetSize(XMFLOAT2(720, 620)); float x = 670, y = 0; @@ -19,8 +19,8 @@ void MaterialWindow::Create(EditorComponent* editor) shadowReceiveCheckBox.SetTooltip("Receives shadow or not?"); shadowReceiveCheckBox.SetPos(XMFLOAT2(540, y += step)); shadowReceiveCheckBox.SetSize(XMFLOAT2(hei, hei)); - shadowReceiveCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + shadowReceiveCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetReceiveShadow(args.bValue); }); @@ -30,8 +30,8 @@ void MaterialWindow::Create(EditorComponent* editor) shadowCasterCheckBox.SetTooltip("The subset will contribute to the scene shadows if enabled."); shadowCasterCheckBox.SetPos(XMFLOAT2(670, y)); shadowCasterCheckBox.SetSize(XMFLOAT2(hei, hei)); - shadowCasterCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + shadowCasterCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetCastShadow(args.bValue); }); @@ -41,8 +41,8 @@ void MaterialWindow::Create(EditorComponent* editor) useVertexColorsCheckBox.SetTooltip("Enable if you want to render the mesh with vertex colors (must have appropriate vertex buffer)"); useVertexColorsCheckBox.SetPos(XMFLOAT2(670, y += step)); useVertexColorsCheckBox.SetSize(XMFLOAT2(hei, hei)); - useVertexColorsCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + useVertexColorsCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetUseVertexColors(args.bValue); }); @@ -52,8 +52,8 @@ void MaterialWindow::Create(EditorComponent* editor) specularGlossinessCheckBox.SetTooltip("If enabled, surface map will be viewed like it contains specular color (RGB) and smoothness (A)"); specularGlossinessCheckBox.SetPos(XMFLOAT2(670, y += step)); specularGlossinessCheckBox.SetSize(XMFLOAT2(hei, hei)); - specularGlossinessCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + specularGlossinessCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetUseSpecularGlossinessWorkflow(args.bValue); SetEntity(entity); @@ -64,8 +64,8 @@ void MaterialWindow::Create(EditorComponent* editor) occlusionPrimaryCheckBox.SetTooltip("If enabled, surface map's RED channel will be used as occlusion map"); occlusionPrimaryCheckBox.SetPos(XMFLOAT2(670, y += step)); occlusionPrimaryCheckBox.SetSize(XMFLOAT2(hei, hei)); - occlusionPrimaryCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + occlusionPrimaryCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetOcclusionEnabled_Primary(args.bValue); }); @@ -75,8 +75,8 @@ void MaterialWindow::Create(EditorComponent* editor) occlusionSecondaryCheckBox.SetTooltip("If enabled, occlusion map's RED channel will be used as occlusion map"); occlusionSecondaryCheckBox.SetPos(XMFLOAT2(670, y += step)); occlusionSecondaryCheckBox.SetSize(XMFLOAT2(hei, hei)); - occlusionSecondaryCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + occlusionSecondaryCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetOcclusionEnabled_Secondary(args.bValue); }); @@ -86,8 +86,8 @@ void MaterialWindow::Create(EditorComponent* editor) windCheckBox.SetTooltip("If enabled, vertex wind weights will affect how much wind offset affects the subset."); windCheckBox.SetPos(XMFLOAT2(670, y += step)); windCheckBox.SetSize(XMFLOAT2(hei, hei)); - windCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + windCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetUseWind(args.bValue); }); @@ -97,8 +97,8 @@ void MaterialWindow::Create(EditorComponent* editor) doubleSidedCheckBox.SetTooltip("Decide whether to render both sides of the material (It's also possible to set this behaviour per mesh)."); doubleSidedCheckBox.SetPos(XMFLOAT2(540, y)); doubleSidedCheckBox.SetSize(XMFLOAT2(hei, hei)); - doubleSidedCheckBox.OnClick([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + doubleSidedCheckBox.OnClick([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetDoubleSided(args.bValue); }); @@ -111,11 +111,11 @@ void MaterialWindow::Create(EditorComponent* editor) shaderTypeComboBox.Create("Shader: "); - shaderTypeComboBox.SetTooltip("Select a shader for this material. \nCustom shaders (*) will also show up here (see wiRenderer:RegisterCustomShader() for more info.)\nNote that custom shaders (*) can't select between blend modes, as they are created with an explicit blend mode."); + shaderTypeComboBox.SetTooltip("Select a shader for this material. \nCustom shaders (*) will also show up here (see wi::renderer:RegisterCustomShader() for more info.)\nNote that custom shaders (*) can't select between blend modes, as they are created with an explicit blend mode."); shaderTypeComboBox.SetPos(XMFLOAT2(x, y += step)); shaderTypeComboBox.SetSize(XMFLOAT2(wid, hei)); - shaderTypeComboBox.OnSelect([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + shaderTypeComboBox.OnSelect([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { if (args.iValue >= MaterialComponent::SHADERTYPE_COUNT) @@ -141,7 +141,7 @@ void MaterialWindow::Create(EditorComponent* editor) shaderTypeComboBox.AddItem("Water", MaterialComponent::SHADERTYPE_WATER); shaderTypeComboBox.AddItem("Cartoon", MaterialComponent::SHADERTYPE_CARTOON); shaderTypeComboBox.AddItem("Unlit", MaterialComponent::SHADERTYPE_UNLIT); - for (auto& x : wiRenderer::GetCustomShaders()) + for (auto& x : wi::renderer::GetCustomShaders()) { shaderTypeComboBox.AddItem("*" + x.name); } @@ -152,11 +152,11 @@ void MaterialWindow::Create(EditorComponent* editor) blendModeComboBox.Create("Blend mode: "); blendModeComboBox.SetPos(XMFLOAT2(x, y += step)); blendModeComboBox.SetSize(XMFLOAT2(wid, hei)); - blendModeComboBox.OnSelect([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + blendModeComboBox.OnSelect([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr && args.iValue >= 0) { - material->userBlendMode = (BLENDMODE)args.iValue; + material->userBlendMode = (wi::enums::BLENDMODE)args.iValue; } }); blendModeComboBox.AddItem("Opaque"); @@ -172,8 +172,8 @@ void MaterialWindow::Create(EditorComponent* editor) shadingRateComboBox.SetTooltip("Select shading rate for this material. \nSelecting larger shading rate will decrease rendering quality of this material, \nbut increases performance.\nRequires hardware support for variable shading rate"); shadingRateComboBox.SetPos(XMFLOAT2(x, y += step)); shadingRateComboBox.SetSize(XMFLOAT2(wid, hei)); - shadingRateComboBox.OnSelect([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + shadingRateComboBox.OnSelect([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->shadingRate = (ShadingRate)args.iValue; @@ -200,8 +200,8 @@ void MaterialWindow::Create(EditorComponent* editor) normalMapSlider.SetTooltip("How much the normal map should distort the face normals (bumpiness)."); normalMapSlider.SetSize(XMFLOAT2(wid, hei)); normalMapSlider.SetPos(XMFLOAT2(x, y += step)); - normalMapSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + normalMapSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetNormalMapStrength(args.fValue); }); @@ -211,8 +211,8 @@ void MaterialWindow::Create(EditorComponent* editor) roughnessSlider.SetTooltip("Adjust the surface roughness. Rough surfaces are less shiny, more matte."); roughnessSlider.SetSize(XMFLOAT2(wid, hei)); roughnessSlider.SetPos(XMFLOAT2(x, y += step)); - roughnessSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + roughnessSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetRoughness(args.fValue); }); @@ -222,8 +222,8 @@ void MaterialWindow::Create(EditorComponent* editor) reflectanceSlider.SetTooltip("Adjust the surface [non-metal] reflectivity (also called specularFactor).\nNote: this is not available in specular-glossiness workflow"); reflectanceSlider.SetSize(XMFLOAT2(wid, hei)); reflectanceSlider.SetPos(XMFLOAT2(x, y += step)); - reflectanceSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + reflectanceSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetReflectance(args.fValue); }); @@ -233,8 +233,8 @@ void MaterialWindow::Create(EditorComponent* editor) metalnessSlider.SetTooltip("The more metal-like the surface is, the more the its color will contribute to the reflection color.\nNote: this is not available in specular-glossiness workflow"); metalnessSlider.SetSize(XMFLOAT2(wid, hei)); metalnessSlider.SetPos(XMFLOAT2(x, y += step)); - metalnessSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + metalnessSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetMetalness(args.fValue); }); @@ -244,8 +244,8 @@ void MaterialWindow::Create(EditorComponent* editor) alphaRefSlider.SetTooltip("Adjust the alpha cutoff threshold. Alpha cutout can affect performance"); alphaRefSlider.SetSize(XMFLOAT2(wid, hei)); alphaRefSlider.SetPos(XMFLOAT2(x, y += step)); - alphaRefSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + alphaRefSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetAlphaRef(args.fValue); }); @@ -255,8 +255,8 @@ void MaterialWindow::Create(EditorComponent* editor) emissiveSlider.SetTooltip("Adjust the light emission of the surface. The color of the light emitted is that of the color of the material."); emissiveSlider.SetSize(XMFLOAT2(wid, hei)); emissiveSlider.SetPos(XMFLOAT2(x, y += step)); - emissiveSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + emissiveSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetEmissiveStrength(args.fValue); }); @@ -266,8 +266,8 @@ void MaterialWindow::Create(EditorComponent* editor) transmissionSlider.SetTooltip("Adjust the transmissiveness. More transmissiveness means more diffuse light is transmitted instead of absorbed."); transmissionSlider.SetSize(XMFLOAT2(wid, hei)); transmissionSlider.SetPos(XMFLOAT2(x, y += step)); - transmissionSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + transmissionSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetTransmissionAmount(args.fValue); }); @@ -277,8 +277,8 @@ void MaterialWindow::Create(EditorComponent* editor) refractionSlider.SetTooltip("Adjust the refraction amount for transmissive materials."); refractionSlider.SetSize(XMFLOAT2(wid, hei)); refractionSlider.SetPos(XMFLOAT2(x, y += step)); - refractionSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + refractionSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetRefractionAmount(args.fValue); }); @@ -288,8 +288,8 @@ void MaterialWindow::Create(EditorComponent* editor) pomSlider.SetTooltip("Adjust how much the bump map should modulate the surface parallax effect. \nOnly works with PBR + Parallax shader."); pomSlider.SetSize(XMFLOAT2(wid, hei)); pomSlider.SetPos(XMFLOAT2(x, y += step)); - pomSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + pomSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetParallaxOcclusionMapping(args.fValue); }); @@ -299,8 +299,8 @@ void MaterialWindow::Create(EditorComponent* editor) displacementMappingSlider.SetTooltip("Adjust how much the bump map should modulate the geometry when using tessellation."); displacementMappingSlider.SetSize(XMFLOAT2(wid, hei)); displacementMappingSlider.SetPos(XMFLOAT2(x, y += step)); - displacementMappingSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + displacementMappingSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetDisplacementMapping(args.fValue); }); @@ -310,8 +310,8 @@ void MaterialWindow::Create(EditorComponent* editor) subsurfaceScatteringSlider.SetTooltip("Subsurface scattering amount. \nYou can also adjust the subsurface color by selecting it in the color picker"); subsurfaceScatteringSlider.SetSize(XMFLOAT2(wid, hei)); subsurfaceScatteringSlider.SetPos(XMFLOAT2(x, y += step)); - subsurfaceScatteringSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + subsurfaceScatteringSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) material->SetSubsurfaceScatteringAmount(args.fValue); }); @@ -321,8 +321,8 @@ void MaterialWindow::Create(EditorComponent* editor) texAnimFrameRateSlider.SetTooltip("Adjust the texture animation frame rate (frames per second). Any value above 0 will make the material dynamic."); texAnimFrameRateSlider.SetSize(XMFLOAT2(wid, hei)); texAnimFrameRateSlider.SetPos(XMFLOAT2(x, y += step)); - texAnimFrameRateSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + texAnimFrameRateSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->texAnimFrameRate = args.fValue; @@ -334,8 +334,8 @@ void MaterialWindow::Create(EditorComponent* editor) texAnimDirectionSliderU.SetTooltip("Adjust the texture animation speed along the U direction in texture space."); texAnimDirectionSliderU.SetSize(XMFLOAT2(wid, hei)); texAnimDirectionSliderU.SetPos(XMFLOAT2(x, y += step)); - texAnimDirectionSliderU.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + texAnimDirectionSliderU.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->texAnimDirection.x = args.fValue; @@ -347,8 +347,8 @@ void MaterialWindow::Create(EditorComponent* editor) texAnimDirectionSliderV.SetTooltip("Adjust the texture animation speed along the V direction in texture space."); texAnimDirectionSliderV.SetSize(XMFLOAT2(wid, hei)); texAnimDirectionSliderV.SetPos(XMFLOAT2(x, y += step)); - texAnimDirectionSliderV.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + texAnimDirectionSliderV.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->texAnimDirection.y = args.fValue; @@ -360,8 +360,8 @@ void MaterialWindow::Create(EditorComponent* editor) texMulSliderX.SetTooltip("Adjust the texture mapping size."); texMulSliderX.SetSize(XMFLOAT2(wid, hei)); texMulSliderX.SetPos(XMFLOAT2(x, y += step)); - texMulSliderX.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + texMulSliderX.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetDirty(); @@ -374,8 +374,8 @@ void MaterialWindow::Create(EditorComponent* editor) texMulSliderY.SetTooltip("Adjust the texture mapping size."); texMulSliderY.SetSize(XMFLOAT2(wid, hei)); texMulSliderY.SetPos(XMFLOAT2(x, y += step)); - texMulSliderY.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + texMulSliderY.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetDirty(); @@ -389,8 +389,8 @@ void MaterialWindow::Create(EditorComponent* editor) sheenRoughnessSlider.SetTooltip("This affects roughness of sheen layer for cloth shading."); sheenRoughnessSlider.SetSize(XMFLOAT2(wid, hei)); sheenRoughnessSlider.SetPos(XMFLOAT2(x, y += step)); - sheenRoughnessSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + sheenRoughnessSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetSheenRoughness(args.fValue); @@ -402,8 +402,8 @@ void MaterialWindow::Create(EditorComponent* editor) clearcoatSlider.SetTooltip("This affects clearcoat layer blending."); clearcoatSlider.SetSize(XMFLOAT2(wid, hei)); clearcoatSlider.SetPos(XMFLOAT2(x, y += step)); - clearcoatSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + clearcoatSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetClearcoatFactor(args.fValue); @@ -415,8 +415,8 @@ void MaterialWindow::Create(EditorComponent* editor) clearcoatRoughnessSlider.SetTooltip("This affects roughness of clear coat layer."); clearcoatRoughnessSlider.SetSize(XMFLOAT2(wid, hei)); clearcoatRoughnessSlider.SetPos(XMFLOAT2(x, y += step)); - clearcoatRoughnessSlider.OnSlide([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + clearcoatRoughnessSlider.OnSlide([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { material->SetClearcoatRoughness(args.fValue); @@ -435,8 +435,8 @@ void MaterialWindow::Create(EditorComponent* editor) materialNameField.SetTooltip("Set a name for the material..."); materialNameField.SetPos(XMFLOAT2(10, y += step)); materialNameField.SetSize(XMFLOAT2(300, hei)); - materialNameField.OnInputAccepted([=](wiEventArgs args) { - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + materialNameField.OnInputAccepted([=](wi::gui::EventArgs args) { + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name != nullptr) { *name = args.sValue; @@ -449,8 +449,8 @@ void MaterialWindow::Create(EditorComponent* editor) newMaterialButton.Create("New Material"); newMaterialButton.SetPos(XMFLOAT2(10 + 5 + 300, y)); newMaterialButton.SetSize(XMFLOAT2(100, hei)); - newMaterialButton.OnClick([=](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + newMaterialButton.OnClick([=](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); Entity entity = scene.Entity_CreateMaterial("editorMaterial"); editor->ClearSelected(); editor->AddSelected(entity); @@ -474,8 +474,8 @@ void MaterialWindow::Create(EditorComponent* editor) colorPicker.SetPos(XMFLOAT2(10, y += step)); colorPicker.SetVisible(true); colorPicker.SetEnabled(true); - colorPicker.OnColorChanged([&](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + colorPicker.OnColorChanged([&](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { switch (colorComboBox.GetSelected()) @@ -559,7 +559,7 @@ void MaterialWindow::Create(EditorComponent* editor) break; } } - textureSlotComboBox.OnSelect([this](wiEventArgs args) + textureSlotComboBox.OnSelect([this](wi::gui::EventArgs args) { switch (args.iValue) @@ -607,7 +607,7 @@ void MaterialWindow::Create(EditorComponent* editor) break; } - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material == nullptr) return; textureSlotButton.SetImage(material->textures[args.iValue].resource); @@ -620,36 +620,36 @@ void MaterialWindow::Create(EditorComponent* editor) textureSlotButton.Create(""); textureSlotButton.SetSize(XMFLOAT2(180, 180)); textureSlotButton.SetPos(XMFLOAT2(textureSlotComboBox.GetPosition().x + textureSlotComboBox.GetScale().x - textureSlotButton.GetScale().x, y += step)); - textureSlotButton.sprites[wiWidget::IDLE].params.color = wiColor::White(); - textureSlotButton.sprites[wiWidget::FOCUS].params.color = wiColor::Gray(); - textureSlotButton.sprites[wiWidget::ACTIVE].params.color = wiColor::White(); - textureSlotButton.sprites[wiWidget::DEACTIVATING].params.color = wiColor::Gray(); - textureSlotButton.OnClick([this](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + textureSlotButton.sprites[wi::gui::IDLE].params.color = wi::Color::White(); + textureSlotButton.sprites[wi::gui::FOCUS].params.color = wi::Color::Gray(); + textureSlotButton.sprites[wi::gui::ACTIVE].params.color = wi::Color::White(); + textureSlotButton.sprites[wi::gui::DEACTIVATING].params.color = wi::Color::Gray(); + textureSlotButton.OnClick([this](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material == nullptr) return; int slot = textureSlotComboBox.GetSelected(); - if (material->textures[slot].resource != nullptr) + if (material->textures[slot].resource.IsValid()) { - material->textures[slot].resource = nullptr; + material->textures[slot].resource = {}; material->textures[slot].name = ""; material->SetDirty(); textureSlotLabel.SetText(""); } else { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Texture"; - params.extensions = wiResourceManager::GetSupportedImageExtensions(); - wiHelper::FileDialog(params, [this, material, slot](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { - material->textures[slot].resource = wiResourceManager::Load(fileName, wiResourceManager::IMPORT_RETAIN_FILEDATA); + params.extensions = wi::resourcemanager::GetSupportedImageExtensions(); + wi::helper::FileDialog(params, [this, material, slot](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + material->textures[slot].resource = wi::resourcemanager::Load(fileName, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); material->textures[slot].name = fileName; material->SetDirty(); - textureSlotLabel.SetText(wiHelper::GetFileNameFromPath(fileName)); + textureSlotLabel.SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } @@ -668,8 +668,8 @@ void MaterialWindow::Create(EditorComponent* editor) textureSlotUvsetField.SetTooltip("uv set number"); textureSlotUvsetField.SetPos(XMFLOAT2(x + textureSlotLabel.GetScale().x + 2, y)); textureSlotUvsetField.SetSize(XMFLOAT2(hei, hei)); - textureSlotUvsetField.OnInputAccepted([this](wiEventArgs args) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(entity); + textureSlotUvsetField.OnInputAccepted([this](wi::gui::EventArgs args) { + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(entity); if (material != nullptr) { int slot = textureSlotComboBox.GetSelected(); @@ -691,7 +691,7 @@ void MaterialWindow::SetEntity(Entity entity) { this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); MaterialComponent* material = scene.materials.GetComponent(entity); if (material != nullptr) @@ -743,19 +743,19 @@ void MaterialWindow::SetEntity(Entity entity) { default: case 0: - colorPicker.SetPickColor(wiColor::fromFloat4(material->baseColor)); + colorPicker.SetPickColor(wi::Color::fromFloat4(material->baseColor)); break; case 1: - colorPicker.SetPickColor(wiColor::fromFloat4(material->specularColor)); + colorPicker.SetPickColor(wi::Color::fromFloat4(material->specularColor)); break; case 2: - colorPicker.SetPickColor(wiColor::fromFloat3(XMFLOAT3(material->emissiveColor.x, material->emissiveColor.y, material->emissiveColor.z))); + colorPicker.SetPickColor(wi::Color::fromFloat3(XMFLOAT3(material->emissiveColor.x, material->emissiveColor.y, material->emissiveColor.z))); break; case 3: - colorPicker.SetPickColor(wiColor::fromFloat3(XMFLOAT3(material->subsurfaceScattering.x, material->subsurfaceScattering.y, material->subsurfaceScattering.z))); + colorPicker.SetPickColor(wi::Color::fromFloat3(XMFLOAT3(material->subsurfaceScattering.x, material->subsurfaceScattering.y, material->subsurfaceScattering.z))); break; case 4: - colorPicker.SetPickColor(wiColor::fromFloat3(XMFLOAT3(material->sheenColor.x, material->sheenColor.y, material->sheenColor.z))); + colorPicker.SetPickColor(wi::Color::fromFloat3(XMFLOAT3(material->sheenColor.x, material->sheenColor.y, material->sheenColor.z))); break; } @@ -798,7 +798,7 @@ void MaterialWindow::SetEntity(Entity entity) clearcoatSlider.SetValue(material->clearcoat); clearcoatRoughnessSlider.SetValue(material->clearcoatRoughness); - shadingRateComboBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::VARIABLE_RATE_SHADING)); + shadingRateComboBox.SetEnabled(wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::VARIABLE_RATE_SHADING)); if (material->IsUsingSpecularGlossinessWorkflow()) { @@ -808,7 +808,7 @@ void MaterialWindow::SetEntity(Entity entity) int slot = textureSlotComboBox.GetSelected(); textureSlotButton.SetImage(material->textures[slot].resource); - textureSlotLabel.SetText(wiHelper::GetFileNameFromPath(material->textures[slot].name)); + textureSlotLabel.SetText(wi::helper::GetFileNameFromPath(material->textures[slot].name)); textureSlotUvsetField.SetText(std::to_string(material->textures[slot].uvset)); } else @@ -818,7 +818,7 @@ void MaterialWindow::SetEntity(Entity entity) colorComboBox.SetEnabled(false); colorPicker.SetEnabled(false); - textureSlotButton.SetImage(nullptr); + textureSlotButton.SetImage(wi::Resource()); textureSlotLabel.SetText(""); textureSlotUvsetField.SetText(""); } diff --git a/Editor/MaterialWindow.h b/Editor/MaterialWindow.h index aa7d0ad77..34dc1fcb3 100644 --- a/Editor/MaterialWindow.h +++ b/Editor/MaterialWindow.h @@ -3,53 +3,53 @@ class EditorComponent; -class MaterialWindow : public wiWindow +class MaterialWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiTextInputField materialNameField; - wiButton newMaterialButton; - wiCheckBox shadowReceiveCheckBox; - wiCheckBox shadowCasterCheckBox; - wiCheckBox useVertexColorsCheckBox; - wiCheckBox specularGlossinessCheckBox; - wiCheckBox occlusionPrimaryCheckBox; - wiCheckBox occlusionSecondaryCheckBox; - wiCheckBox windCheckBox; - wiCheckBox doubleSidedCheckBox; - wiSlider normalMapSlider; - wiSlider roughnessSlider; - wiSlider reflectanceSlider; - wiSlider metalnessSlider; - wiSlider emissiveSlider; - wiSlider transmissionSlider; - wiSlider refractionSlider; - wiSlider pomSlider; - wiSlider displacementMappingSlider; - wiSlider subsurfaceScatteringSlider; - wiSlider texAnimFrameRateSlider; - wiSlider texAnimDirectionSliderU; - wiSlider texAnimDirectionSliderV; - wiSlider texMulSliderX; - wiSlider texMulSliderY; - wiSlider alphaRefSlider; - wiComboBox shaderTypeComboBox; - wiComboBox blendModeComboBox; - wiComboBox shadingRateComboBox; - wiSlider sheenRoughnessSlider; - wiSlider clearcoatSlider; - wiSlider clearcoatRoughnessSlider; + wi::gui::TextInputField materialNameField; + wi::gui::Button newMaterialButton; + wi::gui::CheckBox shadowReceiveCheckBox; + wi::gui::CheckBox shadowCasterCheckBox; + wi::gui::CheckBox useVertexColorsCheckBox; + wi::gui::CheckBox specularGlossinessCheckBox; + wi::gui::CheckBox occlusionPrimaryCheckBox; + wi::gui::CheckBox occlusionSecondaryCheckBox; + wi::gui::CheckBox windCheckBox; + wi::gui::CheckBox doubleSidedCheckBox; + wi::gui::Slider normalMapSlider; + wi::gui::Slider roughnessSlider; + wi::gui::Slider reflectanceSlider; + wi::gui::Slider metalnessSlider; + wi::gui::Slider emissiveSlider; + wi::gui::Slider transmissionSlider; + wi::gui::Slider refractionSlider; + wi::gui::Slider pomSlider; + wi::gui::Slider displacementMappingSlider; + wi::gui::Slider subsurfaceScatteringSlider; + wi::gui::Slider texAnimFrameRateSlider; + wi::gui::Slider texAnimDirectionSliderU; + wi::gui::Slider texAnimDirectionSliderV; + wi::gui::Slider texMulSliderX; + wi::gui::Slider texMulSliderY; + wi::gui::Slider alphaRefSlider; + wi::gui::ComboBox shaderTypeComboBox; + wi::gui::ComboBox blendModeComboBox; + wi::gui::ComboBox shadingRateComboBox; + wi::gui::Slider sheenRoughnessSlider; + wi::gui::Slider clearcoatSlider; + wi::gui::Slider clearcoatRoughnessSlider; - wiComboBox colorComboBox; - wiColorPicker colorPicker; + wi::gui::ComboBox colorComboBox; + wi::gui::ColorPicker colorPicker; - wiComboBox textureSlotComboBox; - wiButton textureSlotButton; - wiLabel textureSlotLabel; - wiTextInputField textureSlotUvsetField; + wi::gui::ComboBox textureSlotComboBox; + wi::gui::Button textureSlotButton; + wi::gui::Label textureSlotLabel; + wi::gui::TextInputField textureSlotUvsetField; }; diff --git a/Editor/MeshWindow.cpp b/Editor/MeshWindow.cpp index 38c48d97d..444ddbabe 100644 --- a/Editor/MeshWindow.cpp +++ b/Editor/MeshWindow.cpp @@ -8,15 +8,15 @@ #include -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; -struct TerraGen : public wiWindow +struct TerraGen : public wi::gui::Window { - wiSlider dimXSlider; - wiSlider dimYSlider; - wiSlider dimZSlider; - wiButton heightmapButton; + wi::gui::Slider dimXSlider; + wi::gui::Slider dimYSlider; + wi::gui::Slider dimZSlider; + wi::gui::Button heightmapButton; // heightmap texture: unsigned char* rgb = nullptr; @@ -25,7 +25,7 @@ struct TerraGen : public wiWindow TerraGen() { - wiWindow::Create("TerraGen"); + wi::gui::Window::Create("TerraGen"); SetSize(XMFLOAT2(260, 130)); float xx = 20; @@ -76,7 +76,7 @@ struct TerraGen : public wiWindow void MeshWindow::Create(EditorComponent* editor) { - wiWindow::Create("Mesh Window"); + wi::gui::Window::Create("Mesh Window"); SetSize(XMFLOAT2(580, 580)); float x = 150; @@ -87,7 +87,7 @@ void MeshWindow::Create(EditorComponent* editor) meshInfoLabel.Create("Mesh Info"); meshInfoLabel.SetPos(XMFLOAT2(x - 50, y += step)); meshInfoLabel.SetSize(XMFLOAT2(450, 190)); - meshInfoLabel.SetColor(wiColor::Transparent()); + meshInfoLabel.SetColor(wi::Color::Transparent()); AddWidget(&meshInfoLabel); // Left side: @@ -97,8 +97,8 @@ void MeshWindow::Create(EditorComponent* editor) subsetComboBox.SetSize(XMFLOAT2(40, hei)); subsetComboBox.SetPos(XMFLOAT2(x, y += step)); subsetComboBox.SetEnabled(false); - subsetComboBox.OnSelect([=](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + subsetComboBox.OnSelect([=](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); MeshComponent* mesh = scene.meshes.GetComponent(entity); if (mesh != nullptr) { @@ -116,20 +116,20 @@ void MeshWindow::Create(EditorComponent* editor) terrainCheckBox.SetTooltip("If enabled, the mesh will use multiple materials and blend between them based on vertex colors."); terrainCheckBox.SetSize(XMFLOAT2(hei, hei)); terrainCheckBox.SetPos(XMFLOAT2(x, y += step)); - terrainCheckBox.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + terrainCheckBox.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->SetTerrain(args.bValue); if (args.bValue && mesh->vertex_colors.empty()) { mesh->vertex_colors.resize(mesh->vertex_positions.size()); - std::fill(mesh->vertex_colors.begin(), mesh->vertex_colors.end(), wiColor::Red().rgba); // fill red (meaning only blend base material) + std::fill(mesh->vertex_colors.begin(), mesh->vertex_colors.end(), wi::Color::Red().rgba); // fill red (meaning only blend base material) mesh->CreateRenderData(); for (auto& subset : mesh->subsets) { - MaterialComponent* material = wiScene::GetScene().materials.GetComponent(subset.materialID); + MaterialComponent* material = wi::scene::GetScene().materials.GetComponent(subset.materialID); if (material != nullptr) { material->SetUseVertexColors(true); @@ -145,8 +145,8 @@ void MeshWindow::Create(EditorComponent* editor) doubleSidedCheckBox.SetTooltip("If enabled, the inside of the mesh will be visible."); doubleSidedCheckBox.SetSize(XMFLOAT2(hei, hei)); doubleSidedCheckBox.SetPos(XMFLOAT2(x, y += step)); - doubleSidedCheckBox.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + doubleSidedCheckBox.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->SetDoubleSided(args.bValue); @@ -158,9 +158,9 @@ void MeshWindow::Create(EditorComponent* editor) softbodyCheckBox.SetTooltip("Enable soft body simulation. Tip: Use the Paint Tool to control vertex pinning."); softbodyCheckBox.SetSize(XMFLOAT2(hei, hei)); softbodyCheckBox.SetPos(XMFLOAT2(x, y += step)); - softbodyCheckBox.OnClick([&](wiEventArgs args) { + softbodyCheckBox.OnClick([&](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); SoftBodyPhysicsComponent* physicscomponent = scene.softbodies.GetComponent(entity); if (args.bValue) @@ -188,8 +188,8 @@ void MeshWindow::Create(EditorComponent* editor) massSlider.SetTooltip("Set the mass amount for the physics engine."); massSlider.SetSize(XMFLOAT2(100, hei)); massSlider.SetPos(XMFLOAT2(x, y += step)); - massSlider.OnSlide([&](wiEventArgs args) { - SoftBodyPhysicsComponent* physicscomponent = wiScene::GetScene().softbodies.GetComponent(entity); + massSlider.OnSlide([&](wi::gui::EventArgs args) { + SoftBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().softbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->mass = args.fValue; @@ -201,8 +201,8 @@ void MeshWindow::Create(EditorComponent* editor) frictionSlider.SetTooltip("Set the friction amount for the physics engine."); frictionSlider.SetSize(XMFLOAT2(100, hei)); frictionSlider.SetPos(XMFLOAT2(x, y += step)); - frictionSlider.OnSlide([&](wiEventArgs args) { - SoftBodyPhysicsComponent* physicscomponent = wiScene::GetScene().softbodies.GetComponent(entity); + frictionSlider.OnSlide([&](wi::gui::EventArgs args) { + SoftBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().softbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->friction = args.fValue; @@ -214,8 +214,8 @@ void MeshWindow::Create(EditorComponent* editor) restitutionSlider.SetTooltip("Set the restitution amount for the physics engine."); restitutionSlider.SetSize(XMFLOAT2(100, hei)); restitutionSlider.SetPos(XMFLOAT2(x, y += step)); - restitutionSlider.OnSlide([&](wiEventArgs args) { - SoftBodyPhysicsComponent* physicscomponent = wiScene::GetScene().softbodies.GetComponent(entity); + restitutionSlider.OnSlide([&](wi::gui::EventArgs args) { + SoftBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().softbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->restitution = args.fValue; @@ -227,8 +227,8 @@ void MeshWindow::Create(EditorComponent* editor) impostorCreateButton.SetTooltip("Create an impostor image of the mesh. The mesh will be replaced by this image when far away, to render faster."); impostorCreateButton.SetSize(XMFLOAT2(240, hei)); impostorCreateButton.SetPos(XMFLOAT2(x - 50, y += step)); - impostorCreateButton.OnClick([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + impostorCreateButton.OnClick([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); ImpostorComponent* impostor = scene.impostors.GetComponent(entity); if (impostor == nullptr) { @@ -247,8 +247,8 @@ void MeshWindow::Create(EditorComponent* editor) impostorDistanceSlider.SetTooltip("Assign the distance where the mesh geometry should be switched to the impostor image."); impostorDistanceSlider.SetSize(XMFLOAT2(100, hei)); impostorDistanceSlider.SetPos(XMFLOAT2(x, y += step)); - impostorDistanceSlider.OnSlide([&](wiEventArgs args) { - ImpostorComponent* impostor = wiScene::GetScene().impostors.GetComponent(entity); + impostorDistanceSlider.OnSlide([&](wi::gui::EventArgs args) { + ImpostorComponent* impostor = wi::scene::GetScene().impostors.GetComponent(entity); if (impostor != nullptr) { impostor->swapInDistance = args.fValue; @@ -260,8 +260,8 @@ void MeshWindow::Create(EditorComponent* editor) tessellationFactorSlider.SetTooltip("Set the dynamic tessellation amount. Tessellation should be enabled in the Renderer window and your GPU must support it!"); tessellationFactorSlider.SetSize(XMFLOAT2(100, hei)); tessellationFactorSlider.SetPos(XMFLOAT2(x, y += step)); - tessellationFactorSlider.OnSlide([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + tessellationFactorSlider.OnSlide([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->tessellationFactor = args.fValue; @@ -273,8 +273,8 @@ void MeshWindow::Create(EditorComponent* editor) flipCullingButton.SetTooltip("Flip faces to reverse triangle culling order."); flipCullingButton.SetSize(XMFLOAT2(240, hei)); flipCullingButton.SetPos(XMFLOAT2(x - 50, y += step)); - flipCullingButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + flipCullingButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->FlipCulling(); @@ -287,8 +287,8 @@ void MeshWindow::Create(EditorComponent* editor) flipNormalsButton.SetTooltip("Flip surface normals."); flipNormalsButton.SetSize(XMFLOAT2(240, hei)); flipNormalsButton.SetPos(XMFLOAT2(x - 50, y += step)); - flipNormalsButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + flipNormalsButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->FlipNormals(); @@ -301,8 +301,8 @@ void MeshWindow::Create(EditorComponent* editor) computeNormalsSmoothButton.SetTooltip("Compute surface normals of the mesh. Resulting normals will be unique per vertex. This can reduce vertex count, but is slow."); computeNormalsSmoothButton.SetSize(XMFLOAT2(240, hei)); computeNormalsSmoothButton.SetPos(XMFLOAT2(x - 50, y += step)); - computeNormalsSmoothButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + computeNormalsSmoothButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->ComputeNormals(MeshComponent::COMPUTE_NORMALS_SMOOTH); @@ -315,8 +315,8 @@ void MeshWindow::Create(EditorComponent* editor) computeNormalsHardButton.SetTooltip("Compute surface normals of the mesh. Resulting normals will be unique per face. This can increase vertex count."); computeNormalsHardButton.SetSize(XMFLOAT2(240, hei)); computeNormalsHardButton.SetPos(XMFLOAT2(x - 50, y += step)); - computeNormalsHardButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + computeNormalsHardButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->ComputeNormals(MeshComponent::COMPUTE_NORMALS_HARD); @@ -329,8 +329,8 @@ void MeshWindow::Create(EditorComponent* editor) recenterButton.SetTooltip("Recenter mesh to AABB center."); recenterButton.SetSize(XMFLOAT2(240, hei)); recenterButton.SetPos(XMFLOAT2(x - 50, y += step)); - recenterButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + recenterButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->Recenter(); @@ -343,8 +343,8 @@ void MeshWindow::Create(EditorComponent* editor) recenterToBottomButton.SetTooltip("Recenter mesh to AABB bottom."); recenterToBottomButton.SetSize(XMFLOAT2(240, hei)); recenterToBottomButton.SetPos(XMFLOAT2(x - 50, y += step)); - recenterToBottomButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + recenterToBottomButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { mesh->RecenterToBottom(); @@ -357,8 +357,8 @@ void MeshWindow::Create(EditorComponent* editor) optimizeButton.SetTooltip("Run the meshoptimizer library."); optimizeButton.SetSize(XMFLOAT2(240, hei)); optimizeButton.SetPos(XMFLOAT2(x - 50, y += step)); - optimizeButton.OnClick([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + optimizeButton.OnClick([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { // https://github.com/zeux/meshoptimizer#vertex-cache-optimization @@ -387,8 +387,8 @@ void MeshWindow::Create(EditorComponent* editor) subsetMaterialComboBox.SetSize(XMFLOAT2(200, hei)); subsetMaterialComboBox.SetPos(XMFLOAT2(x + 180, y += step)); subsetMaterialComboBox.SetEnabled(false); - subsetMaterialComboBox.OnSelect([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + subsetMaterialComboBox.OnSelect([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); MeshComponent* mesh = scene.meshes.GetComponent(entity); if (mesh != nullptr && subset >= 0 && subset < mesh->subsets.size()) { @@ -411,8 +411,8 @@ void MeshWindow::Create(EditorComponent* editor) terrainMat1Combo.SetSize(XMFLOAT2(200, hei)); terrainMat1Combo.SetPos(XMFLOAT2(x + 180, y += step)); terrainMat1Combo.SetEnabled(false); - terrainMat1Combo.OnSelect([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + terrainMat1Combo.OnSelect([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { if (args.iValue == 0) @@ -421,7 +421,7 @@ void MeshWindow::Create(EditorComponent* editor) } else { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); mesh->terrain_material1 = scene.materials.GetEntity(args.iValue - 1); } } @@ -433,8 +433,8 @@ void MeshWindow::Create(EditorComponent* editor) terrainMat2Combo.SetSize(XMFLOAT2(200, hei)); terrainMat2Combo.SetPos(XMFLOAT2(x + 180, y += step)); terrainMat2Combo.SetEnabled(false); - terrainMat2Combo.OnSelect([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + terrainMat2Combo.OnSelect([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { if (args.iValue == 0) @@ -443,7 +443,7 @@ void MeshWindow::Create(EditorComponent* editor) } else { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); mesh->terrain_material2 = scene.materials.GetEntity(args.iValue - 1); } } @@ -455,8 +455,8 @@ void MeshWindow::Create(EditorComponent* editor) terrainMat3Combo.SetSize(XMFLOAT2(200, hei)); terrainMat3Combo.SetPos(XMFLOAT2(x + 180, y += step)); terrainMat3Combo.SetEnabled(false); - terrainMat3Combo.OnSelect([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + terrainMat3Combo.OnSelect([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr) { if (args.iValue == 0) @@ -465,7 +465,7 @@ void MeshWindow::Create(EditorComponent* editor) } else { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); mesh->terrain_material3 = scene.materials.GetEntity(args.iValue - 1); } } @@ -477,7 +477,7 @@ void MeshWindow::Create(EditorComponent* editor) terrainGenButton.SetTooltip("Generate terrain meshes."); terrainGenButton.SetSize(XMFLOAT2(200, hei)); terrainGenButton.SetPos(XMFLOAT2(x + 180, y += step)); - terrainGenButton.OnClick([=](wiEventArgs args) { + terrainGenButton.OnClick([=](wi::gui::EventArgs args) { terragen.Cleanup(); terragen.SetVisible(true); @@ -490,7 +490,7 @@ void MeshWindow::Create(EditorComponent* editor) terrainGenButton.translation.y) ); - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); Entity entity = scene.Entity_CreateObject("editorTerrain"); ObjectComponent& object = *scene.objects.GetComponent(entity); object.meshID = scene.Entity_CreateMesh("terrainMesh"); @@ -519,7 +519,7 @@ void MeshWindow::Create(EditorComponent* editor) mesh->vertex_positions[index] = XMFLOAT3((float)i - (float)width * 0.5f, 0, (float)j - (float)height * 0.5f); if (rgb != nullptr) mesh->vertex_positions[index].y = ((float)rgb[index * channelCount] - 127.0f) * heightmap_scale; - mesh->vertex_colors[index] = wiColor::Red().rgba; + mesh->vertex_colors[index] = wi::Color::Red().rgba; XMFLOAT2 uv = XMFLOAT2((float)i / (float)width, (float)j / (float)height); mesh->vertex_uvset_0[index] = uv; mesh->vertex_uvset_1[index] = uv; @@ -553,7 +553,7 @@ void MeshWindow::Create(EditorComponent* editor) generate_mesh(128, 128); editor->ClearSelected(); - wiScene::PickResult pick; + wi::scene::PickResult pick; pick.entity = entity; pick.subsetIndex = 0; editor->AddSelected(pick); @@ -563,28 +563,28 @@ void MeshWindow::Create(EditorComponent* editor) - terragen.dimXSlider.OnSlide([=](wiEventArgs args) { + terragen.dimXSlider.OnSlide([=](wi::gui::EventArgs args) { terragen.width = (int)terragen.dimXSlider.GetValue(); terragen.height = (int)terragen.dimZSlider.GetValue(); generate_mesh(terragen.width, terragen.height); }); - terragen.dimZSlider.OnSlide([=](wiEventArgs args) { + terragen.dimZSlider.OnSlide([=](wi::gui::EventArgs args) { terragen.width = (int)terragen.dimXSlider.GetValue(); terragen.height = (int)terragen.dimZSlider.GetValue(); generate_mesh(terragen.width, terragen.height); }); - terragen.dimYSlider.OnSlide([=](wiEventArgs args) { + terragen.dimYSlider.OnSlide([=](wi::gui::EventArgs args) { generate_mesh(terragen.width, terragen.height, terragen.rgb, terragen.channelCount, args.fValue); }); - terragen.heightmapButton.OnClick([=](wiEventArgs args) { + terragen.heightmapButton.OnClick([=](wi::gui::EventArgs args) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Texture"; - params.extensions = wiResourceManager::GetSupportedImageExtensions(); - wiHelper::FileDialog(params, [=](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + params.extensions = wi::resourcemanager::GetSupportedImageExtensions(); + wi::helper::FileDialog(params, [=](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { if (terragen.rgb != nullptr) { stbi_image_free(terragen.rgb); @@ -606,8 +606,8 @@ void MeshWindow::Create(EditorComponent* editor) morphTargetCombo.Create("Morph Target:"); morphTargetCombo.SetSize(XMFLOAT2(100, hei)); morphTargetCombo.SetPos(XMFLOAT2(x + 280, y += step)); - morphTargetCombo.OnSelect([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + morphTargetCombo.OnSelect([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr && args.iValue < (int)mesh->targets.size()) { morphTargetSlider.SetValue(mesh->targets[args.iValue].weight); @@ -620,8 +620,8 @@ void MeshWindow::Create(EditorComponent* editor) morphTargetSlider.SetTooltip("Set the weight for morph target"); morphTargetSlider.SetSize(XMFLOAT2(100, hei)); morphTargetSlider.SetPos(XMFLOAT2(x + 280, y += step)); - morphTargetSlider.OnSlide([&](wiEventArgs args) { - MeshComponent* mesh = wiScene::GetScene().meshes.GetComponent(entity); + morphTargetSlider.OnSlide([&](wi::gui::EventArgs args) { + MeshComponent* mesh = wi::scene::GetScene().meshes.GetComponent(entity); if (mesh != nullptr && morphTargetCombo.GetSelected() < (int)mesh->targets.size()) { mesh->targets[morphTargetCombo.GetSelected()].weight = args.fValue; @@ -643,7 +643,7 @@ void MeshWindow::SetEntity(Entity entity, int subset) this->entity = entity; this->subset = subset; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); const MeshComponent* mesh = scene.meshes.GetComponent(entity); @@ -735,7 +735,7 @@ void MeshWindow::SetEntity(Entity entity, int subset) softbodyCheckBox.SetCheck(false); - SoftBodyPhysicsComponent* physicscomponent = wiScene::GetScene().softbodies.GetComponent(entity); + SoftBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().softbodies.GetComponent(entity); if (physicscomponent != nullptr) { softbodyCheckBox.SetCheck(true); diff --git a/Editor/MeshWindow.h b/Editor/MeshWindow.h index 0e9a58e23..4d2b52830 100644 --- a/Editor/MeshWindow.h +++ b/Editor/MeshWindow.h @@ -3,41 +3,41 @@ class EditorComponent; -class MeshWindow : public wiWindow +class MeshWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; + wi::ecs::Entity entity; int subset = -1; - void SetEntity(wiECS::Entity entity, int subset); + void SetEntity(wi::ecs::Entity entity, int subset); - wiLabel meshInfoLabel; - wiComboBox subsetComboBox; - wiComboBox subsetMaterialComboBox; - wiCheckBox doubleSidedCheckBox; - wiCheckBox softbodyCheckBox; - wiSlider massSlider; - wiSlider frictionSlider; - wiSlider restitutionSlider; - wiButton impostorCreateButton; - wiSlider impostorDistanceSlider; - wiSlider tessellationFactorSlider; - wiButton flipCullingButton; - wiButton flipNormalsButton; - wiButton computeNormalsSmoothButton; - wiButton computeNormalsHardButton; - wiButton recenterButton; - wiButton recenterToBottomButton; - wiButton optimizeButton; + wi::gui::Label meshInfoLabel; + wi::gui::ComboBox subsetComboBox; + wi::gui::ComboBox subsetMaterialComboBox; + wi::gui::CheckBox doubleSidedCheckBox; + wi::gui::CheckBox softbodyCheckBox; + wi::gui::Slider massSlider; + wi::gui::Slider frictionSlider; + wi::gui::Slider restitutionSlider; + wi::gui::Button impostorCreateButton; + wi::gui::Slider impostorDistanceSlider; + wi::gui::Slider tessellationFactorSlider; + wi::gui::Button flipCullingButton; + wi::gui::Button flipNormalsButton; + wi::gui::Button computeNormalsSmoothButton; + wi::gui::Button computeNormalsHardButton; + wi::gui::Button recenterButton; + wi::gui::Button recenterToBottomButton; + wi::gui::Button optimizeButton; - wiCheckBox terrainCheckBox; - wiComboBox terrainMat1Combo; - wiComboBox terrainMat2Combo; - wiComboBox terrainMat3Combo; - wiButton terrainGenButton; + wi::gui::CheckBox terrainCheckBox; + wi::gui::ComboBox terrainMat1Combo; + wi::gui::ComboBox terrainMat2Combo; + wi::gui::ComboBox terrainMat3Combo; + wi::gui::Button terrainGenButton; - wiComboBox morphTargetCombo; - wiSlider morphTargetSlider; + wi::gui::ComboBox morphTargetCombo; + wi::gui::Slider morphTargetSlider; }; diff --git a/Editor/ModelImporter.h b/Editor/ModelImporter.h index 8ebdba870..591f0e173 100644 --- a/Editor/ModelImporter.h +++ b/Editor/ModelImporter.h @@ -1,11 +1,11 @@ #pragma once #include -namespace wiScene +namespace wi::scene { struct Scene; } -void ImportModel_OBJ(const std::string& fileName, wiScene::Scene& scene); -void ImportModel_GLTF(const std::string& fileName, wiScene::Scene& scene); +void ImportModel_OBJ(const std::string& fileName, wi::scene::Scene& scene); +void ImportModel_GLTF(const std::string& fileName, wi::scene::Scene& scene); diff --git a/Editor/ModelImporter_GLTF.cpp b/Editor/ModelImporter_GLTF.cpp index 29f8fd9c3..a96d526b5 100644 --- a/Editor/ModelImporter_GLTF.cpp +++ b/Editor/ModelImporter_GLTF.cpp @@ -15,9 +15,9 @@ #define TINYGLTF_NO_STB_IMAGE_WRITE #include "tiny_gltf.h" -using namespace wiGraphics; -using namespace wiScene; -using namespace wiECS; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::ecs; // Transform the data from glTF space to engine-space: @@ -28,7 +28,7 @@ namespace tinygltf { bool FileExists(const std::string& abs_filename, void*) { - return wiHelper::FileExists(abs_filename); + return wi::helper::FileExists(abs_filename); } std::string ExpandFilePath(const std::string& filepath, void*) { @@ -81,12 +81,12 @@ namespace tinygltf bool ReadWholeFile(wi::vector* out, std::string* err, const std::string& filepath, void*) { - return wiHelper::FileRead(filepath, *out); + return wi::helper::FileRead(filepath, *out); } bool WriteWholeFile(std::string* err, const std::string& filepath, const std::vector& contents, void*) { - return wiHelper::FileWrite(filepath, contents.data(), contents.size()); + return wi::helper::FileWrite(filepath, contents.data(), contents.size()); } bool LoadImageData(Image *image, const int image_idx, std::string *err, @@ -101,28 +101,28 @@ namespace tinygltf std::string ss; do { ss.clear(); - ss += "gltfimport_" + std::to_string(wiRandom::getRandom(std::numeric_limits::max())) + ".png"; - } while (wiResourceManager::Contains(ss)); // this is to avoid overwriting an existing imported image + ss += "gltfimport_" + std::to_string(wi::random::GetRandom(std::numeric_limits::max())) + ".png"; + } while (wi::resourcemanager::Contains(ss)); // this is to avoid overwriting an existing imported image image->uri = ss; } - auto resource = wiResourceManager::Load( + auto resource = wi::resourcemanager::Load( image->uri, - wiResourceManager::IMPORT_RETAIN_FILEDATA, + wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA, (const uint8_t*)bytes, (size_t)size ); - if (resource == nullptr) + if (!resource.IsValid()) { return false; } - image->width = resource->texture.desc.width; - image->height = resource->texture.desc.height; + image->width = resource.GetTexture().desc.width; + image->height = resource.GetTexture().desc.height; image->component = 4; - wiResourceManager::ResourceSerializer* seri = (wiResourceManager::ResourceSerializer*)userdata; + wi::resourcemanager::ResourceSerializer* seri = (wi::resourcemanager::ResourceSerializer*)userdata; seri->resources.push_back(resource); return true; @@ -190,7 +190,7 @@ void LoadNode(int nodeIndex, Entity parent, LoaderState& state) node.name = "cam" + std::to_string(camID++); } - entity = scene.Entity_CreateCamera(node.name, wiScene::GetCamera().width, wiScene::GetCamera().height, 0.1f, 800); + entity = scene.Entity_CreateCamera(node.name, wi::scene::GetCamera().width, wi::scene::GetCamera().height, 0.1f, 800); } if (entity == INVALID_ENTITY) @@ -254,9 +254,9 @@ void LoadNode(int nodeIndex, Entity parent, LoaderState& state) void ImportModel_GLTF(const std::string& fileName, Scene& scene) { - std::string directory = wiHelper::GetDirectoryFromPath(fileName); - std::string name = wiHelper::GetFileNameFromPath(fileName); - std::string extension = wiHelper::toUpper(wiHelper::GetExtensionFromFileName(name)); + std::string directory = wi::helper::GetDirectoryFromPath(fileName); + std::string name = wi::helper::GetFileNameFromPath(fileName); + std::string extension = wi::helper::toUpper(wi::helper::GetExtensionFromFileName(name)); tinygltf::TinyGLTF loader; @@ -271,7 +271,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) callbacks.ExpandFilePath = tinygltf::ExpandFilePath; loader.SetFsCallbacks(callbacks); - wiResourceManager::ResourceSerializer seri; // keep this alive to not delete loaded images while importing gltf + wi::resourcemanager::ResourceSerializer seri; // keep this alive to not delete loaded images while importing gltf loader.SetImageLoader(tinygltf::LoadImageData, &seri); loader.SetImageWriter(tinygltf::WriteImageData, nullptr); @@ -279,7 +279,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) state.scene = &scene; wi::vector filedata; - ret = wiHelper::FileRead(fileName, filedata); + ret = wi::helper::FileRead(fileName, filedata); if (ret) { @@ -304,7 +304,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) } if (!ret) { - wiHelper::messageBox(err, "GLTF error!"); + wi::helper::messageBox(err, "GLTF error!"); } Entity rootEntity = CreateEntity(); @@ -349,7 +349,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::BASECOLORMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::BASECOLORMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::BASECOLORMAP].name = img.uri; material.textures[MaterialComponent::BASECOLORMAP].uvset = baseColorTexture->second.TextureTexCoord(); } @@ -362,7 +362,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::NORMALMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::NORMALMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::NORMALMAP].name = img.uri; material.textures[MaterialComponent::NORMALMAP].uvset = normalTexture->second.TextureTexCoord(); } @@ -375,7 +375,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SURFACEMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SURFACEMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SURFACEMAP].name = img.uri; material.textures[MaterialComponent::SURFACEMAP].uvset = metallicRoughnessTexture->second.TextureTexCoord(); } @@ -388,7 +388,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::EMISSIVEMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::EMISSIVEMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::EMISSIVEMAP].name = img.uri; material.textures[MaterialComponent::EMISSIVEMAP].uvset = emissiveTexture->second.TextureTexCoord(); } @@ -401,7 +401,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::OCCLUSIONMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::OCCLUSIONMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::OCCLUSIONMAP].name = img.uri; material.textures[MaterialComponent::OCCLUSIONMAP].uvset = occlusionTexture->second.TextureTexCoord(); material.SetOcclusionEnabled_Secondary(true); @@ -437,7 +437,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) { if (alphaMode->second.string_value.compare("BLEND") == 0) { - material.userBlendMode = BLENDMODE_ALPHA; + material.userBlendMode = wi::enums::BLENDMODE_ALPHA; } } @@ -469,7 +469,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::TRANSMISSIONMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::TRANSMISSIONMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::TRANSMISSIONMAP].name = img.uri; material.textures[MaterialComponent::TRANSMISSIONMAP].uvset = (uint32_t)ext_transmission->second.Get("transmissionTexture").Get("texCoord").Get(); } @@ -493,7 +493,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::BASECOLORMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::BASECOLORMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::BASECOLORMAP].name = img.uri; material.textures[MaterialComponent::BASECOLORMAP].uvset = (uint32_t)specularGlossinessWorkflow->second.Get("diffuseTexture").Get("texCoord").Get(); } @@ -507,7 +507,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SURFACEMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SURFACEMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SURFACEMAP].name = img.uri; material.textures[MaterialComponent::SURFACEMAP].uvset = (uint32_t)specularGlossinessWorkflow->second.Get("specularGlossinessTexture").Get("texCoord").Get(); } @@ -561,7 +561,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SHEENCOLORMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SHEENCOLORMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SHEENCOLORMAP].name = img.uri; material.textures[MaterialComponent::SHEENCOLORMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -581,7 +581,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SHEENROUGHNESSMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SHEENROUGHNESSMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SHEENROUGHNESSMAP].name = img.uri; material.textures[MaterialComponent::SHEENROUGHNESSMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -617,7 +617,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::CLEARCOATMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::CLEARCOATMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::CLEARCOATMAP].name = img.uri; material.textures[MaterialComponent::CLEARCOATMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -637,7 +637,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::CLEARCOATROUGHNESSMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::CLEARCOATROUGHNESSMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::CLEARCOATROUGHNESSMAP].name = img.uri; material.textures[MaterialComponent::CLEARCOATROUGHNESSMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -652,7 +652,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::CLEARCOATNORMALMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::CLEARCOATNORMALMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::CLEARCOATNORMALMAP].name = img.uri; material.textures[MaterialComponent::CLEARCOATNORMALMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -686,7 +686,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) } if (ext_specular->second.Has("specularTexture")) { - if (material.textures[MaterialComponent::SURFACEMAP].resource == nullptr) + if (!material.textures[MaterialComponent::SURFACEMAP].resource.IsValid()) { auto& param = ext_specular->second.Get("specularTexture"); int index = param.Get("index").Get(); @@ -697,11 +697,11 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SURFACEMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SURFACEMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SURFACEMAP].name = img.uri; material.textures[MaterialComponent::SURFACEMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } - else if (material.textures[MaterialComponent::SPECULARMAP].resource == nullptr) + else if (!material.textures[MaterialComponent::SPECULARMAP].resource.IsValid()) { auto& param = ext_specular->second.Get("specularTexture"); int index = param.Get("index").Get(); @@ -712,13 +712,13 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SPECULARMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SPECULARMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SPECULARMAP].name = img.uri; material.textures[MaterialComponent::SPECULARMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } else { - wiBackLog::post("[KHR_materials_specular warning] specularTexture must be either in surfaceMap.a or specularColorTexture.a! specularTexture discarded!", wiBackLog::LogLevel::Warning); + wi::backlog::post("[KHR_materials_specular warning] specularTexture must be either in surfaceMap.a or specularColorTexture.a! specularTexture discarded!", wi::backlog::LogLevel::Warning); } } if (ext_specular->second.Has("specularColorTexture")) @@ -732,7 +732,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) img_source = tex.extensions["KHR_texture_basisu"].Get("source").Get(); } auto& img = state.gltfModel.images[img_source]; - material.textures[MaterialComponent::SPECULARMAP].resource = wiResourceManager::Load(img.uri); + material.textures[MaterialComponent::SPECULARMAP].resource = wi::resourcemanager::Load(img.uri); material.textures[MaterialComponent::SPECULARMAP].name = img.uri; material.textures[MaterialComponent::SPECULARMAP].uvset = (uint32_t)param.Get("texCoord").Get(); } @@ -955,7 +955,7 @@ void ImportModel_GLTF(const std::string& fileName, Scene& scene) for (size_t i = 0; i < vertexCount; ++i) { const XMFLOAT4& color = *(XMFLOAT4*)((size_t)data + i * stride); - uint32_t rgba = wiMath::CompressColor(color); + uint32_t rgba = wi::math::CompressColor(color); mesh.vertex_colors[vertexOffset + i] = rgba; } diff --git a/Editor/ModelImporter_OBJ.cpp b/Editor/ModelImporter_OBJ.cpp index 24f9edd5b..209dc5f23 100644 --- a/Editor/ModelImporter_OBJ.cpp +++ b/Editor/ModelImporter_OBJ.cpp @@ -9,9 +9,9 @@ #include #include -using namespace wiGraphics; -using namespace wiScene; -using namespace wiECS; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::ecs; struct membuf : std::streambuf { @@ -40,7 +40,7 @@ public: } wi::vector filedata; - if (!wiHelper::FileRead(filepath, filedata)) + if (!wi::helper::FileRead(filepath, filedata)) { std::string ss; ss += "WARN: Material file [ " + filepath + " ] not found.\n"; @@ -74,8 +74,8 @@ static const bool transform_to_LH = true; void ImportModel_OBJ(const std::string& fileName, Scene& scene) { - std::string directory = wiHelper::GetDirectoryFromPath(fileName); - std::string name = wiHelper::GetFileNameFromPath(fileName); + std::string directory = wi::helper::GetDirectoryFromPath(fileName); + std::string name = wi::helper::GetFileNameFromPath(fileName); tinyobj::attrib_t obj_attrib; wi::vector obj_shapes; @@ -83,7 +83,7 @@ void ImportModel_OBJ(const std::string& fileName, Scene& scene) std::string obj_errors; wi::vector filedata; - bool success = wiHelper::FileRead(fileName, filedata); + bool success = wi::helper::FileRead(fileName, filedata); if (success) { @@ -99,7 +99,7 @@ void ImportModel_OBJ(const std::string& fileName, Scene& scene) if (!obj_errors.empty()) { - wiBackLog::post(obj_errors, wiBackLog::LogLevel::Error); + wi::backlog::post(obj_errors, wi::backlog::LogLevel::Error); } if (success) @@ -232,10 +232,10 @@ void ImportModel_OBJ(const std::string& fileName, Scene& scene) // eliminate duplicate vertices by means of hashing: size_t vertexHash = 0; - wiHelper::hash_combine(vertexHash, index.vertex_index); - wiHelper::hash_combine(vertexHash, index.normal_index); - wiHelper::hash_combine(vertexHash, index.texcoord_index); - wiHelper::hash_combine(vertexHash, materialIndex); + wi::helper::hash_combine(vertexHash, index.vertex_index); + wi::helper::hash_combine(vertexHash, index.normal_index); + wi::helper::hash_combine(vertexHash, index.texcoord_index); + wi::helper::hash_combine(vertexHash, materialIndex); if (uniqueVertices.count(vertexHash) == 0) { @@ -254,6 +254,6 @@ void ImportModel_OBJ(const std::string& fileName, Scene& scene) } else { - wiHelper::messageBox("OBJ import failed! Check backlog for errors!", "Error!"); + wi::helper::messageBox("OBJ import failed! Check backlog for errors!", "Error!"); } } diff --git a/Editor/NameWindow.cpp b/Editor/NameWindow.cpp index ed439b281..27e1105dd 100644 --- a/Editor/NameWindow.cpp +++ b/Editor/NameWindow.cpp @@ -2,13 +2,13 @@ #include "NameWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void NameWindow::Create(EditorComponent* editor) { - wiWindow::Create("Name Window"); + wi::gui::Window::Create("Name Window"); SetSize(XMFLOAT2(360, 80)); float x = 60; @@ -21,11 +21,11 @@ void NameWindow::Create(EditorComponent* editor) nameInput.SetDescription("Name: "); nameInput.SetPos(XMFLOAT2(x, y += step)); nameInput.SetSize(XMFLOAT2(siz, hei)); - nameInput.OnInputAccepted([=](wiEventArgs args) { - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + nameInput.OnInputAccepted([=](wi::gui::EventArgs args) { + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name == nullptr) { - name = &wiScene::GetScene().names.Create(entity); + name = &wi::scene::GetScene().names.Create(entity); } name->name = args.sValue; @@ -47,7 +47,7 @@ void NameWindow::SetEntity(Entity entity) { SetEnabled(true); - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name != nullptr) { nameInput.SetValue(name->name); diff --git a/Editor/NameWindow.h b/Editor/NameWindow.h index 14e3ba035..2935dbeb0 100644 --- a/Editor/NameWindow.h +++ b/Editor/NameWindow.h @@ -3,14 +3,14 @@ class EditorComponent; -class NameWindow : public wiWindow +class NameWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiTextInputField nameInput; + wi::gui::TextInputField nameInput; }; diff --git a/Editor/ObjectWindow.cpp b/Editor/ObjectWindow.cpp index dabb1f8a2..145943f15 100644 --- a/Editor/ObjectWindow.cpp +++ b/Editor/ObjectWindow.cpp @@ -7,8 +7,8 @@ #include -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; static void SetPixel(uint8_t *dest, int destWidth, int x, int y, const uint8_t *color) @@ -90,7 +90,7 @@ static Atlas_Dim GenerateMeshAtlas(MeshComponent& meshcomponent, uint32_t resolu mesh.indexFormat = xatlas::IndexFormat::UInt32; xatlas::AddMeshError::Enum error = xatlas::AddMesh(atlas, mesh); if (error != xatlas::AddMeshError::Success) { - wiHelper::messageBox(xatlas::StringForEnum(error), "Adding mesh to xatlas failed!"); + wi::helper::messageBox(xatlas::StringForEnum(error), "Adding mesh to xatlas failed!"); return dim; } } @@ -260,7 +260,7 @@ void ObjectWindow::Create(EditorComponent* editor) { this->editor = editor; - wiWindow::Create("Object Window"); + wi::gui::Window::Create("Object Window"); SetSize(XMFLOAT2(660, 500)); float x = 200; @@ -279,8 +279,8 @@ void ObjectWindow::Create(EditorComponent* editor) renderableCheckBox.SetSize(XMFLOAT2(hei, hei)); renderableCheckBox.SetPos(XMFLOAT2(x, y += step)); renderableCheckBox.SetCheck(true); - renderableCheckBox.OnClick([&](wiEventArgs args) { - ObjectComponent* object = wiScene::GetScene().objects.GetComponent(entity); + renderableCheckBox.OnClick([&](wi::gui::EventArgs args) { + ObjectComponent* object = wi::scene::GetScene().objects.GetComponent(entity); if (object != nullptr) { object->SetRenderable(args.bValue); @@ -293,8 +293,8 @@ void ObjectWindow::Create(EditorComponent* editor) shadowCheckBox.SetSize(XMFLOAT2(hei, hei)); shadowCheckBox.SetPos(XMFLOAT2(x, y += step)); shadowCheckBox.SetCheck(true); - shadowCheckBox.OnClick([&](wiEventArgs args) { - ObjectComponent* object = wiScene::GetScene().objects.GetComponent(entity); + shadowCheckBox.OnClick([&](wi::gui::EventArgs args) { + ObjectComponent* object = wi::scene::GetScene().objects.GetComponent(entity); if (object != nullptr) { object->SetCastShadow(args.bValue); @@ -306,8 +306,8 @@ void ObjectWindow::Create(EditorComponent* editor) ditherSlider.SetTooltip("Adjust transparency of the object. Opaque materials will use dithered transparency in this case!"); ditherSlider.SetSize(XMFLOAT2(100, hei)); ditherSlider.SetPos(XMFLOAT2(x, y += step)); - ditherSlider.OnSlide([&](wiEventArgs args) { - ObjectComponent* object = wiScene::GetScene().objects.GetComponent(entity); + ditherSlider.OnSlide([&](wi::gui::EventArgs args) { + ObjectComponent* object = wi::scene::GetScene().objects.GetComponent(entity); if (object != nullptr) { object->color.w = 1 - args.fValue; @@ -319,8 +319,8 @@ void ObjectWindow::Create(EditorComponent* editor) cascadeMaskSlider.SetTooltip("How many shadow cascades to skip when rendering this object into shadow maps? (0: skip none, it will be in all cascades, 1: skip first (biggest cascade), ...etc..."); cascadeMaskSlider.SetSize(XMFLOAT2(100, hei)); cascadeMaskSlider.SetPos(XMFLOAT2(x, y += step)); - cascadeMaskSlider.OnSlide([&](wiEventArgs args) { - ObjectComponent* object = wiScene::GetScene().objects.GetComponent(entity); + cascadeMaskSlider.OnSlide([&](wi::gui::EventArgs args) { + ObjectComponent* object = wi::scene::GetScene().objects.GetComponent(entity); if (object != nullptr) { object->cascadeMask = (uint32_t)args.iValue; @@ -346,12 +346,12 @@ void ObjectWindow::Create(EditorComponent* editor) collisionShapeComboBox.AddItem("Capsule"); collisionShapeComboBox.AddItem("Convex Hull"); collisionShapeComboBox.AddItem("Triangle Mesh"); - collisionShapeComboBox.OnSelect([&](wiEventArgs args) + collisionShapeComboBox.OnSelect([&](wi::gui::EventArgs args) { if (entity == INVALID_ENTITY) return; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); RigidBodyPhysicsComponent* physicscomponent = scene.rigidbodies.GetComponent(entity); if (args.iValue == 0) @@ -451,8 +451,8 @@ void ObjectWindow::Create(EditorComponent* editor) XSlider.Create(0, 10, 1, 100000, "X: "); XSlider.SetSize(XMFLOAT2(100, hei)); XSlider.SetPos(XMFLOAT2(x, y += step)); - XSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + XSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { switch (physicscomponent->shape) @@ -476,8 +476,8 @@ void ObjectWindow::Create(EditorComponent* editor) YSlider.Create(0, 10, 1, 100000, "Y: "); YSlider.SetSize(XMFLOAT2(100, hei)); YSlider.SetPos(XMFLOAT2(x, y += step)); - YSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + YSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { switch (physicscomponent->shape) @@ -498,8 +498,8 @@ void ObjectWindow::Create(EditorComponent* editor) ZSlider.Create(0, 10, 1, 100000, "Z: "); ZSlider.SetSize(XMFLOAT2(100, hei)); ZSlider.SetPos(XMFLOAT2(x, y += step)); - ZSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + ZSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { switch (physicscomponent->shape) @@ -518,8 +518,8 @@ void ObjectWindow::Create(EditorComponent* editor) massSlider.SetTooltip("Set the mass amount for the physics engine."); massSlider.SetSize(XMFLOAT2(100, hei)); massSlider.SetPos(XMFLOAT2(x, y += step)); - massSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + massSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->mass = args.fValue; @@ -531,8 +531,8 @@ void ObjectWindow::Create(EditorComponent* editor) frictionSlider.SetTooltip("Set the friction amount for the physics engine."); frictionSlider.SetSize(XMFLOAT2(100, hei)); frictionSlider.SetPos(XMFLOAT2(x, y += step)); - frictionSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + frictionSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->friction = args.fValue; @@ -544,8 +544,8 @@ void ObjectWindow::Create(EditorComponent* editor) restitutionSlider.SetTooltip("Set the restitution amount for the physics engine."); restitutionSlider.SetSize(XMFLOAT2(100, hei)); restitutionSlider.SetPos(XMFLOAT2(x, y += step)); - restitutionSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + restitutionSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->restitution = args.fValue; @@ -557,8 +557,8 @@ void ObjectWindow::Create(EditorComponent* editor) lineardampingSlider.SetTooltip("Set the linear damping amount for the physics engine."); lineardampingSlider.SetSize(XMFLOAT2(100, hei)); lineardampingSlider.SetPos(XMFLOAT2(x, y += step)); - lineardampingSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + lineardampingSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->damping_linear = args.fValue; @@ -570,8 +570,8 @@ void ObjectWindow::Create(EditorComponent* editor) angulardampingSlider.SetTooltip("Set the mass amount for the physics engine."); angulardampingSlider.SetSize(XMFLOAT2(100, hei)); angulardampingSlider.SetPos(XMFLOAT2(x, y += step)); - angulardampingSlider.OnSlide([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + angulardampingSlider.OnSlide([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->damping_angular = args.fValue; @@ -584,8 +584,8 @@ void ObjectWindow::Create(EditorComponent* editor) kinematicCheckBox.SetSize(XMFLOAT2(hei, hei)); kinematicCheckBox.SetPos(XMFLOAT2(x, y += step)); kinematicCheckBox.SetCheck(false); - kinematicCheckBox.OnClick([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + kinematicCheckBox.OnClick([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->SetKinematic(args.bValue); @@ -598,8 +598,8 @@ void ObjectWindow::Create(EditorComponent* editor) disabledeactivationCheckBox.SetSize(XMFLOAT2(hei, hei)); disabledeactivationCheckBox.SetPos(XMFLOAT2(x, y += step)); disabledeactivationCheckBox.SetCheck(false); - disabledeactivationCheckBox.OnClick([&](wiEventArgs args) { - RigidBodyPhysicsComponent* physicscomponent = wiScene::GetScene().rigidbodies.GetComponent(entity); + disabledeactivationCheckBox.OnClick([&](wi::gui::EventArgs args) { + RigidBodyPhysicsComponent* physicscomponent = wi::scene::GetScene().rigidbodies.GetComponent(entity); if (physicscomponent != nullptr) { physicscomponent->SetDisableDeactivation(args.bValue); @@ -615,10 +615,10 @@ void ObjectWindow::Create(EditorComponent* editor) lightmapResolutionSlider.SetTooltip("Set the approximate resolution for this object's lightmap. This will be packed into the larger global lightmap later."); lightmapResolutionSlider.SetSize(XMFLOAT2(100, hei)); lightmapResolutionSlider.SetPos(XMFLOAT2(x, y += step)); - lightmapResolutionSlider.OnSlide([&](wiEventArgs args) { + lightmapResolutionSlider.OnSlide([&](wi::gui::EventArgs args) { // unfortunately, we must be pow2 with full float lightmap format, otherwise it could be unlimited (but accumulation blending would suffer then) // or at least for me, downloading the lightmap was glitching out when non-pow 2 and RGBA32_FLOAT format - lightmapResolutionSlider.SetValue(float(wiMath::GetNextPowerOfTwo(uint32_t(args.fValue)))); + lightmapResolutionSlider.SetValue(float(wi::math::GetNextPowerOfTwo(uint32_t(args.fValue)))); }); AddWidget(&lightmapResolutionSlider); @@ -636,9 +636,9 @@ void ObjectWindow::Create(EditorComponent* editor) generateLightmapButton.SetTooltip("Render the lightmap for only this object. It will automatically combined with the global lightmap."); generateLightmapButton.SetPos(XMFLOAT2(x, y)); generateLightmapButton.SetSize(XMFLOAT2(140, hei)); - generateLightmapButton.OnClick([&](wiEventArgs args) { + generateLightmapButton.OnClick([&](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); enum UV_GEN_TYPE { @@ -668,7 +668,7 @@ void ObjectWindow::Create(EditorComponent* editor) } - wiJobSystem::context ctx; + wi::jobsystem::context ctx; for (auto& it : gen_meshes) { @@ -685,12 +685,12 @@ void ObjectWindow::Create(EditorComponent* editor) } else if (gen_type == UV_GEN_GENERATE_ATLAS) { - wiJobSystem::Execute(ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { it.second = GenerateMeshAtlas(mesh, (uint32_t)lightmapResolutionSlider.GetValue()); }); } } - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); for (auto& x : gen_objects) { @@ -717,9 +717,9 @@ void ObjectWindow::Create(EditorComponent* editor) stopLightmapGenButton.SetTooltip("Stop the lightmap rendering and save the lightmap."); stopLightmapGenButton.SetPos(XMFLOAT2(x, y += step)); stopLightmapGenButton.SetSize(XMFLOAT2(140, hei)); - stopLightmapGenButton.OnClick([&](wiEventArgs args) { + stopLightmapGenButton.OnClick([&](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); for (auto& x : this->editor->translator.selected) { @@ -738,9 +738,9 @@ void ObjectWindow::Create(EditorComponent* editor) clearLightmapButton.SetTooltip("Clear the lightmap from this object."); clearLightmapButton.SetPos(XMFLOAT2(x, y += step)); clearLightmapButton.SetSize(XMFLOAT2(140, hei)); - clearLightmapButton.OnClick([&](wiEventArgs args) { + clearLightmapButton.OnClick([&](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); for (auto& x : this->editor->translator.selected) { @@ -768,8 +768,8 @@ void ObjectWindow::Create(EditorComponent* editor) colorPicker.SetPos(XMFLOAT2(350, y += step)); colorPicker.SetVisible(true); colorPicker.SetEnabled(true); - colorPicker.OnColorChanged([&](wiEventArgs args) { - ObjectComponent* object = wiScene::GetScene().objects.GetComponent(entity); + colorPicker.OnColorChanged([&](wi::gui::EventArgs args) { + ObjectComponent* object = wi::scene::GetScene().objects.GetComponent(entity); if (object != nullptr) { switch (colorComboBox.GetSelected()) @@ -804,7 +804,7 @@ void ObjectWindow::SetEntity(Entity entity) this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); const ObjectComponent* object = scene.objects.GetComponent(entity); @@ -824,10 +824,10 @@ void ObjectWindow::SetEntity(Entity entity) { default: case 0: - colorPicker.SetPickColor(wiColor::fromFloat4(object->color)); + colorPicker.SetPickColor(wi::Color::fromFloat4(object->color)); break; case 1: - colorPicker.SetPickColor(wiColor::fromFloat4(object->emissiveColor)); + colorPicker.SetPickColor(wi::Color::fromFloat4(object->emissiveColor)); break; } diff --git a/Editor/ObjectWindow.h b/Editor/ObjectWindow.h index 68ff19d73..206798e74 100644 --- a/Editor/ObjectWindow.h +++ b/Editor/ObjectWindow.h @@ -3,41 +3,41 @@ class EditorComponent; -class ObjectWindow : public wiWindow +class ObjectWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); EditorComponent* editor; - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiLabel nameLabel; - wiCheckBox renderableCheckBox; - wiCheckBox shadowCheckBox; - wiSlider ditherSlider; - wiSlider cascadeMaskSlider; + wi::gui::Label nameLabel; + wi::gui::CheckBox renderableCheckBox; + wi::gui::CheckBox shadowCheckBox; + wi::gui::Slider ditherSlider; + wi::gui::Slider cascadeMaskSlider; - wiComboBox colorComboBox; - wiColorPicker colorPicker; + wi::gui::ComboBox colorComboBox; + wi::gui::ColorPicker colorPicker; - wiLabel physicsLabel; - wiComboBox collisionShapeComboBox; - wiSlider XSlider; - wiSlider YSlider; - wiSlider ZSlider; - wiSlider massSlider; - wiSlider frictionSlider; - wiSlider restitutionSlider; - wiSlider lineardampingSlider; - wiSlider angulardampingSlider; - wiCheckBox disabledeactivationCheckBox; - wiCheckBox kinematicCheckBox; + wi::gui::Label physicsLabel; + wi::gui::ComboBox collisionShapeComboBox; + wi::gui::Slider XSlider; + wi::gui::Slider YSlider; + wi::gui::Slider ZSlider; + wi::gui::Slider massSlider; + wi::gui::Slider frictionSlider; + wi::gui::Slider restitutionSlider; + wi::gui::Slider lineardampingSlider; + wi::gui::Slider angulardampingSlider; + wi::gui::CheckBox disabledeactivationCheckBox; + wi::gui::CheckBox kinematicCheckBox; - wiSlider lightmapResolutionSlider; - wiComboBox lightmapSourceUVSetComboBox; - wiButton generateLightmapButton; - wiButton stopLightmapGenButton; - wiButton clearLightmapButton; + wi::gui::Slider lightmapResolutionSlider; + wi::gui::ComboBox lightmapSourceUVSetComboBox; + wi::gui::Button generateLightmapButton; + wi::gui::Button stopLightmapGenButton; + wi::gui::Button clearLightmapButton; }; diff --git a/Editor/PaintToolWindow.cpp b/Editor/PaintToolWindow.cpp index 00ca9ccf3..a3250052c 100644 --- a/Editor/PaintToolWindow.cpp +++ b/Editor/PaintToolWindow.cpp @@ -5,15 +5,15 @@ #include -using namespace wiECS; -using namespace wiScene; -using namespace wiGraphics; +using namespace wi::ecs; +using namespace wi::scene; +using namespace wi::graphics; void PaintToolWindow::Create(EditorComponent* editor) { this->editor = editor; - wiWindow::Create("Paint Tool Window"); + wi::gui::Window::Create("Paint Tool Window"); SetSize(XMFLOAT2(400, 600)); float x = 100; @@ -37,7 +37,7 @@ void PaintToolWindow::Create(EditorComponent* editor) modeComboBox.AddItem("Hairparticle - Length (Alpha)"); modeComboBox.AddItem("Wind weight (Alpha)"); modeComboBox.SetSelected(0); - modeComboBox.OnSelect([&](wiEventArgs args) { + modeComboBox.OnSelect([&](wi::gui::EventArgs args) { textureSlotComboBox.SetEnabled(false); saveTextureButton.SetEnabled(false); switch (args.iValue) @@ -86,7 +86,7 @@ void PaintToolWindow::Create(EditorComponent* editor) infoLabel.Create("Paint Tool is disabled."); infoLabel.SetSize(XMFLOAT2(400 - 20, 100)); infoLabel.SetPos(XMFLOAT2(10, y)); - infoLabel.SetColor(wiColor::Transparent()); + infoLabel.SetColor(wi::Color::Transparent()); AddWidget(&infoLabel); y += infoLabel.GetScale().y - step + 5; @@ -159,9 +159,9 @@ void PaintToolWindow::Create(EditorComponent* editor) saveTextureButton.SetSize(XMFLOAT2(200, hei)); saveTextureButton.SetPos(XMFLOAT2(x, y += step)); saveTextureButton.SetEnabled(false); - saveTextureButton.OnClick([this] (wiEventArgs args) { + saveTextureButton.OnClick([this] (wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); ObjectComponent* object = scene.objects.GetComponent(entity); if (object == nullptr || object->meshID == INVALID_ENTITY) return; @@ -179,13 +179,13 @@ void PaintToolWindow::Create(EditorComponent* editor) uint64_t sel = textureSlotComboBox.GetItemUserData(textureSlotComboBox.GetSelected()); wi::vector texturefiledata; - if (wiHelper::saveTextureToMemoryFile(editTexture, "PNG", texturefiledata)) + if (wi::helper::saveTextureToMemoryFile(editTexture, "PNG", texturefiledata)) { - material->textures[sel].resource->filedata = texturefiledata; + material->textures[sel].resource.SetFileData(texturefiledata); } else { - wiHelper::messageBox("Saving texture failed! :("); + wi::helper::messageBox("Saving texture failed! :("); } }); @@ -208,21 +208,21 @@ void PaintToolWindow::Update(float dt) XMFLOAT2 posNew; posNew.x = editor->GetLogicalWidth() * 0.5f; posNew.y = editor->GetLogicalHeight() * 0.5f; - if (editor->GetGUI().HasFocus() || wiBackLog::isActive() || entity == INVALID_ENTITY) + if (editor->GetGUI().HasFocus() || wi::backlog::isActive() || entity == INVALID_ENTITY) { pos = posNew; return; } - const bool pointer_down = wiInput::Down(wiInput::MOUSE_BUTTON_LEFT); + const bool pointer_down = wi::input::Down(wi::input::MOUSE_BUTTON_LEFT); if (!pointer_down) { stroke_dist = FLT_MAX; } - auto pointer = wiInput::GetPointer(); + auto pointer = wi::input::GetPointer(); posNew = XMFLOAT2(pointer.x, pointer.y); - stroke_dist += wiMath::Distance(pos, posNew); + stroke_dist += wi::math::Distance(pos, posNew); const float pressure = pressureCheckBox.GetCheck() ? pointer.w : 1.0f; const float spacing = spacingSlider.GetValue(); @@ -241,13 +241,13 @@ void PaintToolWindow::Update(float dt) const float pressure_radius = radius * pressure; const float amount = amountSlider.GetValue(); const float falloff = falloffSlider.GetValue(); - const wiColor color = colorPicker.GetPickColor(); + const wi::Color color = colorPicker.GetPickColor(); const XMFLOAT4 color_float = color.toFloat4(); const bool backfaces = backfaceCheckBox.GetCheck(); const bool wireframe = wireCheckBox.GetCheck(); - Scene& scene = wiScene::GetScene(); - const CameraComponent& camera = wiScene::GetCamera(); + Scene& scene = wi::scene::GetScene(); + const CameraComponent& camera = wi::scene::GetCamera(); const XMVECTOR C = XMLoadFloat2(&pos); const XMMATRIX VP = camera.GetViewProjection(); const XMVECTOR MUL = XMVectorSet(0.5f, -0.5f, 1, 1); @@ -259,7 +259,7 @@ void PaintToolWindow::Update(float dt) { case MODE_TEXTURE: { - const wiScene::PickResult& intersect = editor->hovered; + const wi::scene::PickResult& intersect = editor->hovered; if (intersect.entity != entity) break; @@ -296,7 +296,7 @@ void PaintToolWindow::Update(float dt) if (painting) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); CommandList cmd = device->BeginCommandList(); RecordHistory(true, cmd); @@ -304,10 +304,10 @@ void PaintToolWindow::Update(float dt) // Need to requery this because RecordHistory might swap textures on material: editTexture = GetEditTextureSlot(*material, &uvset); - device->BindComputeShader(wiRenderer::GetShader(CSTYPE_PAINT_TEXTURE), cmd); + device->BindComputeShader(wi::renderer::GetShader(wi::enums::CSTYPE_PAINT_TEXTURE), cmd); - wiRenderer::BindCommonResources(cmd); - device->BindResource(wiTextureHelper::getWhite(), 0, cmd); + wi::renderer::BindCommonResources(cmd); + device->BindResource(wi::texturehelper::getWhite(), 0, cmd); device->BindUAV(&editTexture, 0, cmd); PaintTextureCB cb; @@ -328,10 +328,10 @@ void PaintToolWindow::Update(float dt) device->Barrier(barriers, arraysize(barriers), cmd); - wiRenderer::GenerateMipChain(editTexture, wiRenderer::MIPGENFILTER::MIPGENFILTER_LINEAR, cmd); + wi::renderer::GenerateMipChain(editTexture, wi::renderer::MIPGENFILTER::MIPGENFILTER_LINEAR, cmd); } - wiRenderer::PaintRadius paintrad; + wi::renderer::PaintRadius paintrad; paintrad.objectEntity = entity; paintrad.subset = subset; paintrad.radius = radius; @@ -339,7 +339,7 @@ void PaintToolWindow::Update(float dt) paintrad.uvset = uvset; paintrad.dimensions.x = desc.width; paintrad.dimensions.y = desc.height; - wiRenderer::DrawPaintRadius(paintrad); + wi::renderer::DrawPaintRadius(paintrad); } break; @@ -404,7 +404,7 @@ void PaintToolWindow::Update(float dt) if (mesh->vertex_colors.empty()) { mesh->vertex_colors.resize(mesh->vertex_positions.size()); - std::fill(mesh->vertex_colors.begin(), mesh->vertex_colors.end(), wiColor::White().rgba); // fill white + std::fill(mesh->vertex_colors.begin(), mesh->vertex_colors.end(), wi::Color::White().rgba); // fill white rebuild = true; } break; @@ -430,7 +430,7 @@ void PaintToolWindow::Update(float dt) } else { - P = wiScene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); + P = wi::scene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); } P = XMVector3Transform(P, W); N = XMVector3Normalize(XMVector3TransformNormal(N, W)); @@ -457,15 +457,15 @@ void PaintToolWindow::Update(float dt) { case MODE_VERTEXCOLOR: { - wiColor vcol = mesh->vertex_colors[j]; - vcol = wiColor::lerp(vcol, color, affection); + wi::Color vcol = mesh->vertex_colors[j]; + vcol = wi::Color::lerp(vcol, color, affection); mesh->vertex_colors[j] = vcol.rgba; } break; case MODE_WIND: { - wiColor vcol = wiColor(0, 0, 0, mesh->vertex_windweights[j]); - vcol = wiColor::lerp(vcol, color, affection); + wi::Color vcol = wi::Color(0, 0, 0, mesh->vertex_windweights[j]); + vcol = wi::Color::lerp(vcol, color, affection); mesh->vertex_windweights[j] = vcol.getA(); } break; @@ -487,20 +487,20 @@ void PaintToolWindow::Update(float dt) continue; const XMVECTOR P[arraysize(triangle)] = { - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wiScene::SkinVertex(*mesh, *armature, triangle[0]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wiScene::SkinVertex(*mesh, *armature, triangle[1]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wiScene::SkinVertex(*mesh, *armature, triangle[2]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[0]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[1]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[2]), W), }; - wiRenderer::RenderableTriangle tri; + wi::renderer::RenderableTriangle tri; XMStoreFloat3(&tri.positionA, P[0]); XMStoreFloat3(&tri.positionB, P[1]); XMStoreFloat3(&tri.positionC, P[2]); if (mode == MODE_WIND) { - tri.colorA = wiColor(mesh->vertex_windweights[triangle[0]], 0, 0, 255); - tri.colorB = wiColor(mesh->vertex_windweights[triangle[1]], 0, 0, 255); - tri.colorC = wiColor(mesh->vertex_windweights[triangle[2]], 0, 0, 255); + tri.colorA = wi::Color(mesh->vertex_windweights[triangle[0]], 0, 0, 255); + tri.colorB = wi::Color(mesh->vertex_windweights[triangle[1]], 0, 0, 255); + tri.colorC = wi::Color(mesh->vertex_windweights[triangle[2]], 0, 0, 255); } else { @@ -508,7 +508,7 @@ void PaintToolWindow::Update(float dt) tri.colorB.w = 0.8f; tri.colorC.w = 0.8f; } - wiRenderer::DrawTriangle(tri, true); + wi::renderer::DrawTriangle(tri, true); } } @@ -561,7 +561,7 @@ void PaintToolWindow::Update(float dt) } else { - P = wiScene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); + P = wi::scene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); } P = XMVector3Transform(P, W); N = XMVector3Normalize(XMVector3TransformNormal(N, W)); @@ -616,19 +616,19 @@ void PaintToolWindow::Update(float dt) mesh->indices[j + 2], }; const XMVECTOR P[arraysize(triangle)] = { - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wiScene::SkinVertex(*mesh, *armature, triangle[0]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wiScene::SkinVertex(*mesh, *armature, triangle[1]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wiScene::SkinVertex(*mesh, *armature, triangle[2]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[0]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[1]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[2]), W), }; - wiRenderer::RenderableTriangle tri; + wi::renderer::RenderableTriangle tri; XMStoreFloat3(&tri.positionA, P[0]); XMStoreFloat3(&tri.positionB, P[1]); XMStoreFloat3(&tri.positionC, P[2]); tri.colorA.w = 0.8f; tri.colorB.w = 0.8f; tri.colorC.w = 0.8f; - wiRenderer::DrawTriangle(tri, true); + wi::renderer::DrawTriangle(tri, true); } } @@ -655,7 +655,7 @@ void PaintToolWindow::Update(float dt) break; // Painting: - if (pointer_moved && wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) + if (pointer_moved && wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) { size_t j = 0; for (auto& ind : softbody->physicsToGraphicsVertexMapping) @@ -688,7 +688,7 @@ void PaintToolWindow::Update(float dt) const float weight0 = softbody->weights[physicsIndex0]; const float weight1 = softbody->weights[physicsIndex1]; const float weight2 = softbody->weights[physicsIndex2]; - wiRenderer::RenderableTriangle tri; + wi::renderer::RenderableTriangle tri; if (softbody->vertex_positions_simulation.empty()) { XMStoreFloat3(&tri.positionA, XMVector3Transform(XMLoadFloat3(&mesh->vertex_positions[graphicsIndex0]), W)); @@ -715,12 +715,12 @@ void PaintToolWindow::Update(float dt) tri.colorC = XMFLOAT4(1, 1, 1, 1); if (wireframe) { - wiRenderer::DrawTriangle(tri, true); + wi::renderer::DrawTriangle(tri, true); } if (weight0 == 0 && weight1 == 0 && weight2 == 0) { tri.colorA = tri.colorB = tri.colorC = XMFLOAT4(1, 0, 0, 0.8f); - wiRenderer::DrawTriangle(tri); + wi::renderer::DrawTriangle(tri); } } } @@ -730,7 +730,7 @@ void PaintToolWindow::Update(float dt) case MODE_HAIRPARTICLE_REMOVE_TRIANGLE: case MODE_HAIRPARTICLE_LENGTH: { - wiHairParticle* hair = scene.hairs.GetComponent(entity); + wi::HairParticleSystem* hair = scene.hairs.GetComponent(entity); if (hair == nullptr || hair->meshID == INVALID_ENTITY) break; @@ -758,7 +758,7 @@ void PaintToolWindow::Update(float dt) } else { - P = wiScene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); + P = wi::scene::SkinVertex(*mesh, *armature, (uint32_t)j, &N); } P = XMVector3Transform(P, W); N = XMVector3Normalize(XMVector3TransformNormal(N, W)); @@ -787,14 +787,14 @@ void PaintToolWindow::Update(float dt) if (hair->vertex_lengths[j] > 0) // don't change distribution { const float affection = amount * std::pow(1.0f - (dist / pressure_radius), falloff); - hair->vertex_lengths[j] = wiMath::Lerp(hair->vertex_lengths[j], color_float.w, affection); + hair->vertex_lengths[j] = wi::math::Lerp(hair->vertex_lengths[j], color_float.w, affection); // don't let it "remove" the vertex by keeping its length above zero: // (because if removed, distribution also changes which might be distracting) - hair->vertex_lengths[j] = wiMath::Clamp(hair->vertex_lengths[j], 1.0f / 255.0f, 1.0f); + hair->vertex_lengths[j] = wi::math::Clamp(hair->vertex_lengths[j], 1.0f / 255.0f, 1.0f); } break; } - hair->_flags |= wiHairParticle::REBUILD_BUFFERS; + hair->_flags |= wi::HairParticleSystem::REBUILD_BUFFERS; } } } @@ -809,16 +809,16 @@ void PaintToolWindow::Update(float dt) mesh->indices[j + 2], }; const XMVECTOR P[arraysize(triangle)] = { - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wiScene::SkinVertex(*mesh, *armature, triangle[0]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wiScene::SkinVertex(*mesh, *armature, triangle[1]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wiScene::SkinVertex(*mesh, *armature, triangle[2]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[0]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[1]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[2]), W), }; - wiRenderer::RenderableTriangle tri; + wi::renderer::RenderableTriangle tri; XMStoreFloat3(&tri.positionA, P[0]); XMStoreFloat3(&tri.positionB, P[1]); XMStoreFloat3(&tri.positionC, P[2]); - wiRenderer::DrawTriangle(tri, true); + wi::renderer::DrawTriangle(tri, true); } for (size_t j = 0; j < hair->indices.size() && wireframe; j += 3) @@ -829,17 +829,17 @@ void PaintToolWindow::Update(float dt) hair->indices[j + 2], }; const XMVECTOR P[arraysize(triangle)] = { - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wiScene::SkinVertex(*mesh, *armature, triangle[0]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wiScene::SkinVertex(*mesh, *armature, triangle[1]), W), - XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wiScene::SkinVertex(*mesh, *armature, triangle[2]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[0]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[0]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[1]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[1]), W), + XMVector3Transform(armature == nullptr ? XMLoadFloat3(&mesh->vertex_positions[triangle[2]]) : wi::scene::SkinVertex(*mesh, *armature, triangle[2]), W), }; - wiRenderer::RenderableTriangle tri; + wi::renderer::RenderableTriangle tri; XMStoreFloat3(&tri.positionA, P[0]); XMStoreFloat3(&tri.positionB, P[1]); XMStoreFloat3(&tri.positionC, P[2]); tri.colorA = tri.colorB = tri.colorC = XMFLOAT4(1, 0, 1, 0.9f); - wiRenderer::DrawTriangle(tri, false); + wi::renderer::DrawTriangle(tri, false); } } } @@ -850,7 +850,7 @@ void PaintToolWindow::Update(float dt) void PaintToolWindow::DrawBrush() const { const MODE mode = GetMode(); - if (mode == MODE_DISABLED || mode == MODE_TEXTURE || entity == INVALID_ENTITY || wiBackLog::isActive()) + if (mode == MODE_DISABLED || mode == MODE_TEXTURE || entity == INVALID_ENTITY || wi::backlog::isActive()) return; const int segmentcount = 36; @@ -860,13 +860,13 @@ void PaintToolWindow::DrawBrush() const { const float angle0 = rot + (float)i / (float)segmentcount * XM_2PI; const float angle1 = rot + (float)(i + 1) / (float)segmentcount * XM_2PI; - wiRenderer::RenderableLine2D line; + wi::renderer::RenderableLine2D line; line.start.x = pos.x + sinf(angle0) * radius; line.start.y = pos.y + cosf(angle0) * radius; line.end.x = pos.x + sinf(angle1) * radius; line.end.y = pos.y + cosf(angle1) * radius; line.color_end = line.color_start = i%2 == 0 ? XMFLOAT4(0, 0, 0, 0.8f): XMFLOAT4(1,1,1,1); - wiRenderer::DrawLine(line); + wi::renderer::DrawLine(line); } } @@ -875,7 +875,7 @@ PaintToolWindow::MODE PaintToolWindow::GetMode() const { return (MODE)modeComboBox.GetSelected(); } -void PaintToolWindow::SetEntity(wiECS::Entity value, int subsetindex) +void PaintToolWindow::SetEntity(wi::ecs::Entity value, int subsetindex) { entity = value; subset = subsetindex; @@ -901,14 +901,14 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) // Start history recording (undo) currentHistory = &editor->AdvanceHistory(); - wiArchive& archive = *currentHistory; + wi::Archive& archive = *currentHistory; archive << EditorComponent::HISTORYOP_PAINTTOOL; archive << (uint32_t)GetMode(); archive << entity; } else { - if (!history_needs_recording_end || wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) + if (!history_needs_recording_end || wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) return; history_needs_recording_end = false; history_needs_recording_start = false; @@ -916,8 +916,8 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) // End history recording (redo) } - wiArchive& archive = *currentHistory; - Scene& scene = wiScene::GetScene(); + wi::Archive& archive = *currentHistory; + Scene& scene = wi::scene::GetScene(); switch (GetMode()) { @@ -950,7 +950,7 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) if (start) { // Make a copy of texture to edit and replace material resource: - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); Texture newTex; TextureDesc desc = editTexture.GetDesc(); desc.format = Format::R8G8B8A8_UNORM; // force format to one that is writable by GPU @@ -963,8 +963,8 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) subresource_index = device->CreateSubresource(&newTex, SubresourceType::UAV, 0, 1, i, 1); assert(subresource_index == i); } - assert(cmd != wiGraphics::INVALID_COMMANDLIST); - wiRenderer::CopyTexture2D(newTex, -1, 0, 0, editTexture, 0, cmd); + assert(cmd != wi::graphics::INVALID_COMMANDLIST); + wi::renderer::CopyTexture2D(newTex, -1, 0, 0, editTexture, 0, cmd); ReplaceEditTextureSlot(*material, newTex); } @@ -1029,7 +1029,7 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) case PaintToolWindow::MODE_HAIRPARTICLE_REMOVE_TRIANGLE: case PaintToolWindow::MODE_HAIRPARTICLE_LENGTH: { - wiHairParticle* hair = scene.hairs.GetComponent(entity); + wi::HairParticleSystem* hair = scene.hairs.GetComponent(entity); if (hair == nullptr) break; @@ -1041,7 +1041,7 @@ void PaintToolWindow::RecordHistory(bool start, CommandList cmd) break; } } -void PaintToolWindow::ConsumeHistoryOperation(wiArchive& archive, bool undo) +void PaintToolWindow::ConsumeHistoryOperation(wi::Archive& archive, bool undo) { MODE historymode; archive >> (uint32_t&)historymode; @@ -1049,7 +1049,7 @@ void PaintToolWindow::ConsumeHistoryOperation(wiArchive& archive, bool undo) modeComboBox.SetSelected(historymode); - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); switch (historymode) { @@ -1208,13 +1208,13 @@ void PaintToolWindow::ConsumeHistoryOperation(wiArchive& archive, bool undo) case PaintToolWindow::MODE_HAIRPARTICLE_REMOVE_TRIANGLE: case PaintToolWindow::MODE_HAIRPARTICLE_LENGTH: { - wiHairParticle* hair = scene.hairs.GetComponent(entity); + wi::HairParticleSystem* hair = scene.hairs.GetComponent(entity); if (hair == nullptr) break; - wiHairParticle undo_hair; + wi::HairParticleSystem undo_hair; archive >> undo_hair.vertex_lengths; - wiHairParticle redo_hair; + wi::HairParticleSystem redo_hair; archive >> redo_hair.vertex_lengths; if (undo) @@ -1226,7 +1226,7 @@ void PaintToolWindow::ConsumeHistoryOperation(wiArchive& archive, bool undo) hair->vertex_lengths = redo_hair.vertex_lengths; } - hair->_flags |= wiHairParticle::REBUILD_BUFFERS; + hair->_flags |= wi::HairParticleSystem::REBUILD_BUFFERS; } break; default: @@ -1237,17 +1237,17 @@ void PaintToolWindow::ConsumeHistoryOperation(wiArchive& archive, bool undo) Texture PaintToolWindow::GetEditTextureSlot(const MaterialComponent& material, int* uvset) { uint64_t sel = textureSlotComboBox.GetItemUserData(textureSlotComboBox.GetSelected()); - if (material.textures[sel].resource == nullptr) + if (!material.textures[sel].resource.IsValid()) { return Texture(); } if (uvset) *uvset = material.textures[sel].uvset; - return material.textures[sel].resource->texture; + return material.textures[sel].resource.GetTexture(); } -void PaintToolWindow::ReplaceEditTextureSlot(wiScene::MaterialComponent& material, const Texture& texture) +void PaintToolWindow::ReplaceEditTextureSlot(wi::scene::MaterialComponent& material, const Texture& texture) { uint64_t sel = textureSlotComboBox.GetItemUserData(textureSlotComboBox.GetSelected()); - material.textures[sel].resource->texture = texture; + material.textures[sel].resource.SetTexture(texture); material.SetDirty(); } diff --git a/Editor/PaintToolWindow.h b/Editor/PaintToolWindow.h index 4708a97e4..a51302298 100644 --- a/Editor/PaintToolWindow.h +++ b/Editor/PaintToolWindow.h @@ -3,35 +3,35 @@ class EditorComponent; -class PaintToolWindow : public wiWindow +class PaintToolWindow : public wi::gui::Window { float rot = 0; float stroke_dist = 0; bool history_needs_recording_start = false; bool history_needs_recording_end = false; size_t history_textureIndex = 0; - wi::vector history_textures; // we'd like to keep history textures in GPU memory to avoid GPU readback - wiGraphics::Texture GetEditTextureSlot(const wiScene::MaterialComponent& material, int* uvset = nullptr); - void ReplaceEditTextureSlot(wiScene::MaterialComponent& material, const wiGraphics::Texture& texture); + wi::vector history_textures; // we'd like to keep history textures in GPU memory to avoid GPU readback + wi::graphics::Texture GetEditTextureSlot(const wi::scene::MaterialComponent& material, int* uvset = nullptr); + void ReplaceEditTextureSlot(wi::scene::MaterialComponent& material, const wi::graphics::Texture& texture); public: void Create(EditorComponent* editor); EditorComponent* editor = nullptr; - wiECS::Entity entity = wiECS::INVALID_ENTITY; + wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY; int subset = -1; - wiComboBox modeComboBox; - wiLabel infoLabel; - wiSlider radiusSlider; - wiSlider amountSlider; - wiSlider falloffSlider; - wiSlider spacingSlider; - wiCheckBox backfaceCheckBox; - wiCheckBox wireCheckBox; - wiCheckBox pressureCheckBox; - wiColorPicker colorPicker; - wiComboBox textureSlotComboBox; - wiButton saveTextureButton; + wi::gui::ComboBox modeComboBox; + wi::gui::Label infoLabel; + wi::gui::Slider radiusSlider; + wi::gui::Slider amountSlider; + wi::gui::Slider falloffSlider; + wi::gui::Slider spacingSlider; + wi::gui::CheckBox backfaceCheckBox; + wi::gui::CheckBox wireCheckBox; + wi::gui::CheckBox pressureCheckBox; + wi::gui::ColorPicker colorPicker; + wi::gui::ComboBox textureSlotComboBox; + wi::gui::Button saveTextureButton; void Update(float dt); void DrawBrush() const; @@ -53,9 +53,9 @@ public: MODE_WIND, }; MODE GetMode() const; - void SetEntity(wiECS::Entity value, int subsetindex = -1); + void SetEntity(wi::ecs::Entity value, int subsetindex = -1); - wiArchive* currentHistory = nullptr; - void RecordHistory(bool start, wiGraphics::CommandList cmd = wiGraphics::INVALID_COMMANDLIST); - void ConsumeHistoryOperation(wiArchive& archive, bool undo); + wi::Archive* currentHistory = nullptr; + void RecordHistory(bool start, wi::graphics::CommandList cmd = wi::graphics::INVALID_COMMANDLIST); + void ConsumeHistoryOperation(wi::Archive& archive, bool undo); }; diff --git a/Editor/PostprocessWindow.cpp b/Editor/PostprocessWindow.cpp index 2717f34c2..33575c8e6 100644 --- a/Editor/PostprocessWindow.cpp +++ b/Editor/PostprocessWindow.cpp @@ -4,12 +4,11 @@ #include -using namespace wiGraphics; - +using namespace wi::graphics; void PostprocessWindow::Create(EditorComponent* editor) { - wiWindow::Create("PostProcess Window"); + wi::gui::Window::Create("PostProcess Window"); SetSize(XMFLOAT2(420, 500)); float x = 150; @@ -23,7 +22,7 @@ void PostprocessWindow::Create(EditorComponent* editor) exposureSlider.SetSize(XMFLOAT2(100, hei)); exposureSlider.SetPos(XMFLOAT2(x, y += step)); exposureSlider.SetValue(editor->renderPath->getExposure()); - exposureSlider.OnSlide([=](wiEventArgs args) { + exposureSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setExposure(args.fValue); }); AddWidget(&exposureSlider); @@ -34,7 +33,7 @@ void PostprocessWindow::Create(EditorComponent* editor) lensFlareCheckBox.SetSize(XMFLOAT2(hei, hei)); lensFlareCheckBox.SetPos(XMFLOAT2(x, y += step)); lensFlareCheckBox.SetCheck(editor->renderPath->getLensFlareEnabled()); - lensFlareCheckBox.OnClick([=](wiEventArgs args) { + lensFlareCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setLensFlareEnabled(args.bValue); }); AddWidget(&lensFlareCheckBox); @@ -45,7 +44,7 @@ void PostprocessWindow::Create(EditorComponent* editor) lightShaftsCheckBox.SetSize(XMFLOAT2(hei, hei)); lightShaftsCheckBox.SetPos(XMFLOAT2(x, y += step)); lightShaftsCheckBox.SetCheck(editor->renderPath->getLightShaftsEnabled()); - lightShaftsCheckBox.OnClick([=](wiEventArgs args) { + lightShaftsCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setLightShaftsEnabled(args.bValue); }); AddWidget(&lightShaftsCheckBox); @@ -59,23 +58,23 @@ void PostprocessWindow::Create(EditorComponent* editor) aoComboBox.AddItem("SSAO"); aoComboBox.AddItem("HBAO"); aoComboBox.AddItem("MSAO"); - if (wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + if (wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { aoComboBox.AddItem("RTAO"); } aoComboBox.SetSelected(editor->renderPath->getAO()); - aoComboBox.OnSelect([=](wiEventArgs args) { - editor->renderPath->setAO((RenderPath3D::AO)args.iValue); + aoComboBox.OnSelect([=](wi::gui::EventArgs args) { + editor->renderPath->setAO((wi::RenderPath3D::AO)args.iValue); switch (editor->renderPath->getAO()) { - case RenderPath3D::AO_SSAO: + case wi::RenderPath3D::AO_SSAO: aoRangeSlider.SetEnabled(true); aoRangeSlider.SetValue(2.0f); aoSampleCountSlider.SetEnabled(true); aoSampleCountSlider.SetValue(9.0f); break; - case RenderPath3D::AO_RTAO: + case wi::RenderPath3D::AO_RTAO: aoRangeSlider.SetEnabled(true); aoRangeSlider.SetValue(10.0f); aoSampleCountSlider.SetEnabled(false); @@ -96,7 +95,7 @@ void PostprocessWindow::Create(EditorComponent* editor) aoPowerSlider.SetSize(XMFLOAT2(100, hei)); aoPowerSlider.SetPos(XMFLOAT2(x + 100, y += step)); aoPowerSlider.SetValue((float)editor->renderPath->getAOPower()); - aoPowerSlider.OnSlide([=](wiEventArgs args) { + aoPowerSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setAOPower(args.fValue); }); AddWidget(&aoPowerSlider); @@ -106,7 +105,7 @@ void PostprocessWindow::Create(EditorComponent* editor) aoRangeSlider.SetSize(XMFLOAT2(100, hei)); aoRangeSlider.SetPos(XMFLOAT2(x + 100, y += step)); aoRangeSlider.SetValue((float)editor->renderPath->getAOPower()); - aoRangeSlider.OnSlide([=](wiEventArgs args) { + aoRangeSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setAORange(args.fValue); }); AddWidget(&aoRangeSlider); @@ -116,7 +115,7 @@ void PostprocessWindow::Create(EditorComponent* editor) aoSampleCountSlider.SetSize(XMFLOAT2(100, hei)); aoSampleCountSlider.SetPos(XMFLOAT2(x + 100, y += step)); aoSampleCountSlider.SetValue((float)editor->renderPath->getAOPower()); - aoSampleCountSlider.OnSlide([=](wiEventArgs args) { + aoSampleCountSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setAOSampleCount(args.iValue); }); AddWidget(&aoSampleCountSlider); @@ -127,7 +126,7 @@ void PostprocessWindow::Create(EditorComponent* editor) ssrCheckBox.SetSize(XMFLOAT2(hei, hei)); ssrCheckBox.SetPos(XMFLOAT2(x, y += step)); ssrCheckBox.SetCheck(editor->renderPath->getSSREnabled()); - ssrCheckBox.OnClick([=](wiEventArgs args) { + ssrCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setSSREnabled(args.bValue); }); AddWidget(&ssrCheckBox); @@ -138,19 +137,19 @@ void PostprocessWindow::Create(EditorComponent* editor) raytracedReflectionsCheckBox.SetSize(XMFLOAT2(hei, hei)); raytracedReflectionsCheckBox.SetPos(XMFLOAT2(x + 200, y)); raytracedReflectionsCheckBox.SetCheck(editor->renderPath->getRaytracedReflectionEnabled()); - raytracedReflectionsCheckBox.OnClick([=](wiEventArgs args) { + raytracedReflectionsCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setRaytracedReflectionsEnabled(args.bValue); }); AddWidget(&raytracedReflectionsCheckBox); - raytracedReflectionsCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::RAYTRACING)); + raytracedReflectionsCheckBox.SetEnabled(wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::RAYTRACING)); screenSpaceShadowsCheckBox.Create("SS Shadows: "); screenSpaceShadowsCheckBox.SetTooltip("Enable screen space contact shadows. This can add small shadows details to shadow maps in screen space."); screenSpaceShadowsCheckBox.SetSize(XMFLOAT2(hei, hei)); screenSpaceShadowsCheckBox.SetPos(XMFLOAT2(x, y += step)); - screenSpaceShadowsCheckBox.SetCheck(wiRenderer::GetScreenSpaceShadowsEnabled()); - screenSpaceShadowsCheckBox.OnClick([=](wiEventArgs args) { - wiRenderer::SetScreenSpaceShadowsEnabled(args.bValue); + screenSpaceShadowsCheckBox.SetCheck(wi::renderer::GetScreenSpaceShadowsEnabled()); + screenSpaceShadowsCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::renderer::SetScreenSpaceShadowsEnabled(args.bValue); }); AddWidget(&screenSpaceShadowsCheckBox); @@ -159,7 +158,7 @@ void PostprocessWindow::Create(EditorComponent* editor) screenSpaceShadowsRangeSlider.SetSize(XMFLOAT2(100, hei)); screenSpaceShadowsRangeSlider.SetPos(XMFLOAT2(x + 100, y)); screenSpaceShadowsRangeSlider.SetValue((float)editor->renderPath->getScreenSpaceShadowRange()); - screenSpaceShadowsRangeSlider.OnSlide([=](wiEventArgs args) { + screenSpaceShadowsRangeSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setScreenSpaceShadowRange(args.fValue); }); AddWidget(&screenSpaceShadowsRangeSlider); @@ -169,7 +168,7 @@ void PostprocessWindow::Create(EditorComponent* editor) screenSpaceShadowsStepCountSlider.SetSize(XMFLOAT2(100, hei)); screenSpaceShadowsStepCountSlider.SetPos(XMFLOAT2(x + 100, y += step)); screenSpaceShadowsStepCountSlider.SetValue((float)editor->renderPath->getScreenSpaceShadowSampleCount()); - screenSpaceShadowsStepCountSlider.OnSlide([=](wiEventArgs args) { + screenSpaceShadowsStepCountSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setScreenSpaceShadowSampleCount(args.iValue); }); AddWidget(&screenSpaceShadowsStepCountSlider); @@ -179,7 +178,7 @@ void PostprocessWindow::Create(EditorComponent* editor) eyeAdaptionCheckBox.SetSize(XMFLOAT2(hei, hei)); eyeAdaptionCheckBox.SetPos(XMFLOAT2(x, y += step)); eyeAdaptionCheckBox.SetCheck(editor->renderPath->getEyeAdaptionEnabled()); - eyeAdaptionCheckBox.OnClick([=](wiEventArgs args) { + eyeAdaptionCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setEyeAdaptionEnabled(args.bValue); }); AddWidget(&eyeAdaptionCheckBox); @@ -189,7 +188,7 @@ void PostprocessWindow::Create(EditorComponent* editor) eyeAdaptionKeySlider.SetSize(XMFLOAT2(100, hei)); eyeAdaptionKeySlider.SetPos(XMFLOAT2(x + 100, y)); eyeAdaptionKeySlider.SetValue(editor->renderPath->getEyeAdaptionKey()); - eyeAdaptionKeySlider.OnSlide([=](wiEventArgs args) { + eyeAdaptionKeySlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setEyeAdaptionKey(args.fValue); }); AddWidget(&eyeAdaptionKeySlider); @@ -199,7 +198,7 @@ void PostprocessWindow::Create(EditorComponent* editor) eyeAdaptionRateSlider.SetSize(XMFLOAT2(100, hei)); eyeAdaptionRateSlider.SetPos(XMFLOAT2(x + 100, y += step)); eyeAdaptionRateSlider.SetValue(editor->renderPath->getEyeAdaptionRate()); - eyeAdaptionRateSlider.OnSlide([=](wiEventArgs args) { + eyeAdaptionRateSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setEyeAdaptionRate(args.fValue); }); AddWidget(&eyeAdaptionRateSlider); @@ -210,7 +209,7 @@ void PostprocessWindow::Create(EditorComponent* editor) motionBlurCheckBox.SetSize(XMFLOAT2(hei, hei)); motionBlurCheckBox.SetPos(XMFLOAT2(x, y += step)); motionBlurCheckBox.SetCheck(editor->renderPath->getMotionBlurEnabled()); - motionBlurCheckBox.OnClick([=](wiEventArgs args) { + motionBlurCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setMotionBlurEnabled(args.bValue); }); AddWidget(&motionBlurCheckBox); @@ -221,7 +220,7 @@ void PostprocessWindow::Create(EditorComponent* editor) motionBlurStrengthSlider.SetSize(XMFLOAT2(100, hei)); motionBlurStrengthSlider.SetPos(XMFLOAT2(x + 100, y)); motionBlurStrengthSlider.SetValue(editor->renderPath->getMotionBlurStrength()); - motionBlurStrengthSlider.OnSlide([=](wiEventArgs args) { + motionBlurStrengthSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setMotionBlurStrength(args.fValue); }); AddWidget(&motionBlurStrengthSlider); @@ -232,7 +231,7 @@ void PostprocessWindow::Create(EditorComponent* editor) depthOfFieldCheckBox.SetSize(XMFLOAT2(hei, hei)); depthOfFieldCheckBox.SetPos(XMFLOAT2(x, y += step)); depthOfFieldCheckBox.SetCheck(editor->renderPath->getDepthOfFieldEnabled()); - depthOfFieldCheckBox.OnClick([=](wiEventArgs args) { + depthOfFieldCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setDepthOfFieldEnabled(args.bValue); }); AddWidget(&depthOfFieldCheckBox); @@ -243,7 +242,7 @@ void PostprocessWindow::Create(EditorComponent* editor) depthOfFieldScaleSlider.SetSize(XMFLOAT2(100, hei)); depthOfFieldScaleSlider.SetPos(XMFLOAT2(x + 100, y)); depthOfFieldScaleSlider.SetValue(editor->renderPath->getDepthOfFieldStrength()); - depthOfFieldScaleSlider.OnSlide([=](wiEventArgs args) { + depthOfFieldScaleSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setDepthOfFieldStrength(args.fValue); }); AddWidget(&depthOfFieldScaleSlider); @@ -254,7 +253,7 @@ void PostprocessWindow::Create(EditorComponent* editor) bloomCheckBox.SetSize(XMFLOAT2(hei, hei)); bloomCheckBox.SetPos(XMFLOAT2(x, y += step)); bloomCheckBox.SetCheck(editor->renderPath->getBloomEnabled()); - bloomCheckBox.OnClick([=](wiEventArgs args) { + bloomCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setBloomEnabled(args.bValue); }); AddWidget(&bloomCheckBox); @@ -264,7 +263,7 @@ void PostprocessWindow::Create(EditorComponent* editor) bloomStrengthSlider.SetSize(XMFLOAT2(100, hei)); bloomStrengthSlider.SetPos(XMFLOAT2(x + 100, y)); bloomStrengthSlider.SetValue(editor->renderPath->getBloomThreshold()); - bloomStrengthSlider.OnSlide([=](wiEventArgs args) { + bloomStrengthSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setBloomThreshold(args.fValue); }); AddWidget(&bloomStrengthSlider); @@ -275,7 +274,7 @@ void PostprocessWindow::Create(EditorComponent* editor) fxaaCheckBox.SetSize(XMFLOAT2(hei, hei)); fxaaCheckBox.SetPos(XMFLOAT2(x, y += step)); fxaaCheckBox.SetCheck(editor->renderPath->getFXAAEnabled()); - fxaaCheckBox.OnClick([=](wiEventArgs args) { + fxaaCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setFXAAEnabled(args.bValue); }); AddWidget(&fxaaCheckBox); @@ -285,7 +284,7 @@ void PostprocessWindow::Create(EditorComponent* editor) colorGradingCheckBox.SetSize(XMFLOAT2(hei, hei)); colorGradingCheckBox.SetPos(XMFLOAT2(x, y += step)); colorGradingCheckBox.SetCheck(editor->renderPath->getColorGradingEnabled()); - colorGradingCheckBox.OnClick([=](wiEventArgs args) { + colorGradingCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setColorGradingEnabled(args.bValue); }); AddWidget(&colorGradingCheckBox); @@ -295,7 +294,7 @@ void PostprocessWindow::Create(EditorComponent* editor) ditherCheckBox.SetSize(XMFLOAT2(hei, hei)); ditherCheckBox.SetPos(XMFLOAT2(x, y += step)); ditherCheckBox.SetCheck(editor->renderPath->getDitherEnabled()); - ditherCheckBox.OnClick([=](wiEventArgs args) { + ditherCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setDitherEnabled(args.bValue); }); AddWidget(&ditherCheckBox); @@ -306,7 +305,7 @@ void PostprocessWindow::Create(EditorComponent* editor) sharpenFilterCheckBox.SetSize(XMFLOAT2(hei, hei)); sharpenFilterCheckBox.SetPos(XMFLOAT2(x, y += step)); sharpenFilterCheckBox.SetCheck(editor->renderPath->getSharpenFilterEnabled()); - sharpenFilterCheckBox.OnClick([=](wiEventArgs args) { + sharpenFilterCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setSharpenFilterEnabled(args.bValue); }); AddWidget(&sharpenFilterCheckBox); @@ -317,7 +316,7 @@ void PostprocessWindow::Create(EditorComponent* editor) sharpenFilterAmountSlider.SetSize(XMFLOAT2(100, hei)); sharpenFilterAmountSlider.SetPos(XMFLOAT2(x + 100, y)); sharpenFilterAmountSlider.SetValue(editor->renderPath->getSharpenFilterAmount()); - sharpenFilterAmountSlider.OnSlide([=](wiEventArgs args) { + sharpenFilterAmountSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setSharpenFilterAmount(args.fValue); }); AddWidget(&sharpenFilterAmountSlider); @@ -327,7 +326,7 @@ void PostprocessWindow::Create(EditorComponent* editor) outlineCheckBox.SetSize(XMFLOAT2(hei, hei)); outlineCheckBox.SetPos(XMFLOAT2(x, y += step)); outlineCheckBox.SetCheck(editor->renderPath->getOutlineEnabled()); - outlineCheckBox.OnClick([=](wiEventArgs args) { + outlineCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setOutlineEnabled(args.bValue); }); AddWidget(&outlineCheckBox); @@ -337,7 +336,7 @@ void PostprocessWindow::Create(EditorComponent* editor) outlineThresholdSlider.SetSize(XMFLOAT2(100, hei)); outlineThresholdSlider.SetPos(XMFLOAT2(x + 100, y)); outlineThresholdSlider.SetValue(editor->renderPath->getOutlineThreshold()); - outlineThresholdSlider.OnSlide([=](wiEventArgs args) { + outlineThresholdSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setOutlineThreshold(args.fValue); }); AddWidget(&outlineThresholdSlider); @@ -347,7 +346,7 @@ void PostprocessWindow::Create(EditorComponent* editor) outlineThicknessSlider.SetSize(XMFLOAT2(100, hei)); outlineThicknessSlider.SetPos(XMFLOAT2(x + 100, y += step)); outlineThicknessSlider.SetValue(editor->renderPath->getOutlineThickness()); - outlineThicknessSlider.OnSlide([=](wiEventArgs args) { + outlineThicknessSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setOutlineThickness(args.fValue); }); AddWidget(&outlineThicknessSlider); @@ -357,7 +356,7 @@ void PostprocessWindow::Create(EditorComponent* editor) chromaticaberrationCheckBox.SetSize(XMFLOAT2(hei, hei)); chromaticaberrationCheckBox.SetPos(XMFLOAT2(x, y += step)); chromaticaberrationCheckBox.SetCheck(editor->renderPath->getOutlineEnabled()); - chromaticaberrationCheckBox.OnClick([=](wiEventArgs args) { + chromaticaberrationCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setChromaticAberrationEnabled(args.bValue); }); AddWidget(&chromaticaberrationCheckBox); @@ -367,7 +366,7 @@ void PostprocessWindow::Create(EditorComponent* editor) chromaticaberrationSlider.SetSize(XMFLOAT2(100, hei)); chromaticaberrationSlider.SetPos(XMFLOAT2(x + 100, y)); chromaticaberrationSlider.SetValue(editor->renderPath->getChromaticAberrationAmount()); - chromaticaberrationSlider.OnSlide([=](wiEventArgs args) { + chromaticaberrationSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setChromaticAberrationAmount(args.fValue); }); AddWidget(&chromaticaberrationSlider); @@ -377,7 +376,7 @@ void PostprocessWindow::Create(EditorComponent* editor) fsrCheckBox.SetSize(XMFLOAT2(hei, hei)); fsrCheckBox.SetPos(XMFLOAT2(x, y += step)); fsrCheckBox.SetCheck(editor->renderPath->getFSREnabled()); - fsrCheckBox.OnClick([=](wiEventArgs args) { + fsrCheckBox.OnClick([=](wi::gui::EventArgs args) { editor->renderPath->setFSREnabled(args.bValue); }); AddWidget(&fsrCheckBox); @@ -387,7 +386,7 @@ void PostprocessWindow::Create(EditorComponent* editor) fsrSlider.SetSize(XMFLOAT2(100, hei)); fsrSlider.SetPos(XMFLOAT2(x + 100, y)); fsrSlider.SetValue(editor->renderPath->getFSRSharpness()); - fsrSlider.OnSlide([=](wiEventArgs args) { + fsrSlider.OnSlide([=](wi::gui::EventArgs args) { editor->renderPath->setFSRSharpness(args.fValue); }); AddWidget(&fsrSlider); diff --git a/Editor/PostprocessWindow.h b/Editor/PostprocessWindow.h index 4f4c5012f..cccad26ff 100644 --- a/Editor/PostprocessWindow.h +++ b/Editor/PostprocessWindow.h @@ -3,44 +3,44 @@ class EditorComponent; -class PostprocessWindow : public wiWindow +class PostprocessWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiSlider exposureSlider; - wiCheckBox lensFlareCheckBox; - wiCheckBox lightShaftsCheckBox; - wiComboBox aoComboBox; - wiSlider aoPowerSlider; - wiSlider aoRangeSlider; - wiSlider aoSampleCountSlider; - wiCheckBox ssrCheckBox; - wiCheckBox raytracedReflectionsCheckBox; - wiCheckBox screenSpaceShadowsCheckBox; - wiSlider screenSpaceShadowsStepCountSlider; - wiSlider screenSpaceShadowsRangeSlider; - wiCheckBox eyeAdaptionCheckBox; - wiSlider eyeAdaptionKeySlider; - wiSlider eyeAdaptionRateSlider; - wiCheckBox motionBlurCheckBox; - wiSlider motionBlurStrengthSlider; - wiCheckBox depthOfFieldCheckBox; - wiSlider depthOfFieldScaleSlider; - wiCheckBox bloomCheckBox; - wiSlider bloomStrengthSlider; - wiCheckBox fxaaCheckBox; - wiCheckBox colorGradingCheckBox; - wiCheckBox ditherCheckBox; - wiCheckBox sharpenFilterCheckBox; - wiSlider sharpenFilterAmountSlider; - wiCheckBox outlineCheckBox; - wiSlider outlineThresholdSlider; - wiSlider outlineThicknessSlider; - wiCheckBox chromaticaberrationCheckBox; - wiSlider chromaticaberrationSlider; - wiCheckBox fsrCheckBox; - wiSlider fsrSlider; + wi::gui::Slider exposureSlider; + wi::gui::CheckBox lensFlareCheckBox; + wi::gui::CheckBox lightShaftsCheckBox; + wi::gui::ComboBox aoComboBox; + wi::gui::Slider aoPowerSlider; + wi::gui::Slider aoRangeSlider; + wi::gui::Slider aoSampleCountSlider; + wi::gui::CheckBox ssrCheckBox; + wi::gui::CheckBox raytracedReflectionsCheckBox; + wi::gui::CheckBox screenSpaceShadowsCheckBox; + wi::gui::Slider screenSpaceShadowsStepCountSlider; + wi::gui::Slider screenSpaceShadowsRangeSlider; + wi::gui::CheckBox eyeAdaptionCheckBox; + wi::gui::Slider eyeAdaptionKeySlider; + wi::gui::Slider eyeAdaptionRateSlider; + wi::gui::CheckBox motionBlurCheckBox; + wi::gui::Slider motionBlurStrengthSlider; + wi::gui::CheckBox depthOfFieldCheckBox; + wi::gui::Slider depthOfFieldScaleSlider; + wi::gui::CheckBox bloomCheckBox; + wi::gui::Slider bloomStrengthSlider; + wi::gui::CheckBox fxaaCheckBox; + wi::gui::CheckBox colorGradingCheckBox; + wi::gui::CheckBox ditherCheckBox; + wi::gui::CheckBox sharpenFilterCheckBox; + wi::gui::Slider sharpenFilterAmountSlider; + wi::gui::CheckBox outlineCheckBox; + wi::gui::Slider outlineThresholdSlider; + wi::gui::Slider outlineThicknessSlider; + wi::gui::CheckBox chromaticaberrationCheckBox; + wi::gui::Slider chromaticaberrationSlider; + wi::gui::CheckBox fsrCheckBox; + wi::gui::Slider fsrSlider; }; diff --git a/Editor/RendererWindow.cpp b/Editor/RendererWindow.cpp index ef6c8bef1..333720484 100644 --- a/Editor/RendererWindow.cpp +++ b/Editor/RendererWindow.cpp @@ -1,17 +1,14 @@ #include "stdafx.h" #include "RendererWindow.h" -#include "RenderPath3D.h" #include "Editor.h" -#include "wiPhysicsEngine.h" - void RendererWindow::Create(EditorComponent* editor) { - wiWindow::Create("Renderer Window"); + wi::gui::Window::Create("Renderer Window"); - wiRenderer::SetToDrawDebugEnvProbes(true); - wiRenderer::SetToDrawGridHelper(true); - wiRenderer::SetToDrawDebugCameras(true); + wi::renderer::SetToDrawDebugEnvProbes(true); + wi::renderer::SetToDrawGridHelper(true); + wi::renderer::SetToDrawDebugCameras(true); SetSize(XMFLOAT2(580, 550)); @@ -23,8 +20,8 @@ void RendererWindow::Create(EditorComponent* editor) vsyncCheckBox.SetPos(XMFLOAT2(x, y += step)); vsyncCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); vsyncCheckBox.SetCheck(editor->main->swapChain.desc.vsync); - vsyncCheckBox.OnClick([=](wiEventArgs args) { - wiEvent::SetVSync(args.bValue); + vsyncCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::eventhandler::SetVSync(args.bValue); }); AddWidget(&vsyncCheckBox); @@ -40,10 +37,10 @@ void RendererWindow::Create(EditorComponent* editor) occlusionCullingCheckBox.SetScriptTip("SetOcclusionCullingEnabled(bool enabled)"); occlusionCullingCheckBox.SetPos(XMFLOAT2(x, y += step)); occlusionCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - occlusionCullingCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetOcclusionCullingEnabled(args.bValue); + occlusionCullingCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetOcclusionCullingEnabled(args.bValue); }); - occlusionCullingCheckBox.SetCheck(wiRenderer::GetOcclusionCullingEnabled()); + occlusionCullingCheckBox.SetCheck(wi::renderer::GetOcclusionCullingEnabled()); AddWidget(&occlusionCullingCheckBox); resolutionScaleSlider.Create(0.25f, 2.0f, 1.0f, 7.0f, "Resolution Scale: "); @@ -51,7 +48,7 @@ void RendererWindow::Create(EditorComponent* editor) resolutionScaleSlider.SetSize(XMFLOAT2(100, itemheight)); resolutionScaleSlider.SetPos(XMFLOAT2(x, y += step)); resolutionScaleSlider.SetValue(editor->resolutionScale); - resolutionScaleSlider.OnSlide([editor](wiEventArgs args) { + resolutionScaleSlider.OnSlide([editor](wi::gui::EventArgs args) { if (editor->resolutionScale != args.fValue) { editor->renderPath->resolutionScale = args.fValue; @@ -65,69 +62,69 @@ void RendererWindow::Create(EditorComponent* editor) surfelGICheckBox.SetTooltip("Surfel GI is a raytraced diffuse GI using raytracing and surface cache."); surfelGICheckBox.SetPos(XMFLOAT2(x, y += step)); surfelGICheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - surfelGICheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetSurfelGIEnabled(args.bValue); + surfelGICheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetSurfelGIEnabled(args.bValue); }); - surfelGICheckBox.SetCheck(wiRenderer::GetSurfelGIEnabled()); + surfelGICheckBox.SetCheck(wi::renderer::GetSurfelGIEnabled()); AddWidget(&surfelGICheckBox); surfelGIDebugCheckBox.Create("DEBUG: "); surfelGIDebugCheckBox.SetTooltip("Toggle Surfel GI visualization."); surfelGIDebugCheckBox.SetPos(XMFLOAT2(x + 122, y)); surfelGIDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - surfelGIDebugCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetSurfelGIDebugEnabled(args.bValue); + surfelGIDebugCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetSurfelGIDebugEnabled(args.bValue); }); - surfelGIDebugCheckBox.SetCheck(wiRenderer::GetSurfelGIDebugEnabled()); + surfelGIDebugCheckBox.SetCheck(wi::renderer::GetSurfelGIDebugEnabled()); AddWidget(&surfelGIDebugCheckBox); voxelRadianceCheckBox.Create("Voxel GI: "); voxelRadianceCheckBox.SetTooltip("Toggle voxel Global Illumination computation."); voxelRadianceCheckBox.SetPos(XMFLOAT2(x, y += step)); voxelRadianceCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - voxelRadianceCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetVoxelRadianceEnabled(args.bValue); + voxelRadianceCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceEnabled(args.bValue); }); - voxelRadianceCheckBox.SetCheck(wiRenderer::GetVoxelRadianceEnabled()); + voxelRadianceCheckBox.SetCheck(wi::renderer::GetVoxelRadianceEnabled()); AddWidget(&voxelRadianceCheckBox); voxelRadianceDebugCheckBox.Create("DEBUG: "); voxelRadianceDebugCheckBox.SetTooltip("Toggle Voxel GI visualization."); voxelRadianceDebugCheckBox.SetPos(XMFLOAT2(x + 122, y)); voxelRadianceDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - voxelRadianceDebugCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawVoxelHelper(args.bValue); + voxelRadianceDebugCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawVoxelHelper(args.bValue); }); - voxelRadianceDebugCheckBox.SetCheck(wiRenderer::GetToDrawVoxelHelper()); + voxelRadianceDebugCheckBox.SetCheck(wi::renderer::GetToDrawVoxelHelper()); AddWidget(&voxelRadianceDebugCheckBox); voxelRadianceSecondaryBounceCheckBox.Create("Secondary Light Bounce: "); voxelRadianceSecondaryBounceCheckBox.SetTooltip("Toggle secondary light bounce computation for Voxel GI."); voxelRadianceSecondaryBounceCheckBox.SetPos(XMFLOAT2(x, y += step)); voxelRadianceSecondaryBounceCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - voxelRadianceSecondaryBounceCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetVoxelRadianceSecondaryBounceEnabled(args.bValue); + voxelRadianceSecondaryBounceCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceSecondaryBounceEnabled(args.bValue); }); - voxelRadianceSecondaryBounceCheckBox.SetCheck(wiRenderer::GetVoxelRadianceSecondaryBounceEnabled()); + voxelRadianceSecondaryBounceCheckBox.SetCheck(wi::renderer::GetVoxelRadianceSecondaryBounceEnabled()); AddWidget(&voxelRadianceSecondaryBounceCheckBox); voxelRadianceReflectionsCheckBox.Create("Reflections: "); voxelRadianceReflectionsCheckBox.SetTooltip("Toggle specular reflections computation for Voxel GI."); voxelRadianceReflectionsCheckBox.SetPos(XMFLOAT2(x + 122, y)); voxelRadianceReflectionsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - voxelRadianceReflectionsCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetVoxelRadianceReflectionsEnabled(args.bValue); + voxelRadianceReflectionsCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceReflectionsEnabled(args.bValue); }); - voxelRadianceReflectionsCheckBox.SetCheck(wiRenderer::GetVoxelRadianceReflectionsEnabled()); + voxelRadianceReflectionsCheckBox.SetCheck(wi::renderer::GetVoxelRadianceReflectionsEnabled()); AddWidget(&voxelRadianceReflectionsCheckBox); voxelRadianceVoxelSizeSlider.Create(0.25, 2, 1, 7, "Voxel GI Voxel Size: "); voxelRadianceVoxelSizeSlider.SetTooltip("Adjust the voxel size for Voxel GI calculations."); voxelRadianceVoxelSizeSlider.SetSize(XMFLOAT2(100, itemheight)); voxelRadianceVoxelSizeSlider.SetPos(XMFLOAT2(x, y += step)); - voxelRadianceVoxelSizeSlider.SetValue(wiRenderer::GetVoxelRadianceVoxelSize()); - voxelRadianceVoxelSizeSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetVoxelRadianceVoxelSize(args.fValue); + voxelRadianceVoxelSizeSlider.SetValue(wi::renderer::GetVoxelRadianceVoxelSize()); + voxelRadianceVoxelSizeSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceVoxelSize(args.fValue); }); AddWidget(&voxelRadianceVoxelSizeSlider); @@ -135,9 +132,9 @@ void RendererWindow::Create(EditorComponent* editor) voxelRadianceConeTracingSlider.SetTooltip("Adjust the number of cones sampled in the radiance gathering phase."); voxelRadianceConeTracingSlider.SetSize(XMFLOAT2(100, itemheight)); voxelRadianceConeTracingSlider.SetPos(XMFLOAT2(x, y += step)); - voxelRadianceConeTracingSlider.SetValue((float)wiRenderer::GetVoxelRadianceNumCones()); - voxelRadianceConeTracingSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetVoxelRadianceNumCones(args.iValue); + voxelRadianceConeTracingSlider.SetValue((float)wi::renderer::GetVoxelRadianceNumCones()); + voxelRadianceConeTracingSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceNumCones(args.iValue); }); AddWidget(&voxelRadianceConeTracingSlider); @@ -145,9 +142,9 @@ void RendererWindow::Create(EditorComponent* editor) voxelRadianceRayStepSizeSlider.SetTooltip("Adjust the precision of ray marching for cone tracing step. Lower values = more precision but slower performance."); voxelRadianceRayStepSizeSlider.SetSize(XMFLOAT2(100, itemheight)); voxelRadianceRayStepSizeSlider.SetPos(XMFLOAT2(x, y += step)); - voxelRadianceRayStepSizeSlider.SetValue(wiRenderer::GetVoxelRadianceRayStepSize()); - voxelRadianceRayStepSizeSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetVoxelRadianceRayStepSize(args.fValue); + voxelRadianceRayStepSizeSlider.SetValue(wi::renderer::GetVoxelRadianceRayStepSize()); + voxelRadianceRayStepSizeSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceRayStepSize(args.fValue); }); AddWidget(&voxelRadianceRayStepSizeSlider); @@ -155,9 +152,9 @@ void RendererWindow::Create(EditorComponent* editor) voxelRadianceMaxDistanceSlider.SetTooltip("Adjust max raymarching distance for voxel GI."); voxelRadianceMaxDistanceSlider.SetSize(XMFLOAT2(100, itemheight)); voxelRadianceMaxDistanceSlider.SetPos(XMFLOAT2(x, y += step)); - voxelRadianceMaxDistanceSlider.SetValue(wiRenderer::GetVoxelRadianceMaxDistance()); - voxelRadianceMaxDistanceSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetVoxelRadianceMaxDistance(args.fValue); + voxelRadianceMaxDistanceSlider.SetValue(wi::renderer::GetVoxelRadianceMaxDistance()); + voxelRadianceMaxDistanceSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetVoxelRadianceMaxDistance(args.fValue); }); AddWidget(&voxelRadianceMaxDistanceSlider); @@ -165,73 +162,73 @@ void RendererWindow::Create(EditorComponent* editor) wireFrameCheckBox.SetTooltip("Visualize the scene as a wireframe"); wireFrameCheckBox.SetPos(XMFLOAT2(x, y += step)); wireFrameCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - wireFrameCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetWireRender(args.bValue); + wireFrameCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetWireRender(args.bValue); }); - wireFrameCheckBox.SetCheck(wiRenderer::IsWireRender()); + wireFrameCheckBox.SetCheck(wi::renderer::IsWireRender()); AddWidget(&wireFrameCheckBox); variableRateShadingClassificationCheckBox.Create("VRS Classification: "); variableRateShadingClassificationCheckBox.SetTooltip("Enable classification of variable rate shading on the screen. Less important parts will be shaded with lesser resolution.\nRequires Tier2 support for variable shading rate"); variableRateShadingClassificationCheckBox.SetPos(XMFLOAT2(x, y += step)); variableRateShadingClassificationCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - variableRateShadingClassificationCheckBox.OnClick([editor](wiEventArgs args) { - wiRenderer::SetVariableRateShadingClassification(args.bValue); + variableRateShadingClassificationCheckBox.OnClick([editor](wi::gui::EventArgs args) { + wi::renderer::SetVariableRateShadingClassification(args.bValue); editor->ResizeBuffers(); }); - variableRateShadingClassificationCheckBox.SetCheck(wiRenderer::GetVariableRateShadingClassification()); + variableRateShadingClassificationCheckBox.SetCheck(wi::renderer::GetVariableRateShadingClassification()); AddWidget(&variableRateShadingClassificationCheckBox); - variableRateShadingClassificationCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)); + variableRateShadingClassificationCheckBox.SetEnabled(wi::graphics::GetDevice()->CheckCapability(wi::graphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)); variableRateShadingClassificationDebugCheckBox.Create("DEBUG: "); variableRateShadingClassificationDebugCheckBox.SetTooltip("Toggle visualization of variable rate shading classification feature"); variableRateShadingClassificationDebugCheckBox.SetPos(XMFLOAT2(x + 122, y)); variableRateShadingClassificationDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - variableRateShadingClassificationDebugCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetVariableRateShadingClassificationDebug(args.bValue); + variableRateShadingClassificationDebugCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetVariableRateShadingClassificationDebug(args.bValue); }); - variableRateShadingClassificationDebugCheckBox.SetCheck(wiRenderer::GetVariableRateShadingClassificationDebug()); + variableRateShadingClassificationDebugCheckBox.SetCheck(wi::renderer::GetVariableRateShadingClassificationDebug()); AddWidget(&variableRateShadingClassificationDebugCheckBox); - variableRateShadingClassificationDebugCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)); + variableRateShadingClassificationDebugCheckBox.SetEnabled(wi::graphics::GetDevice()->CheckCapability(wi::graphics::GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)); advancedLightCullingCheckBox.Create("2.5D Light Culling: "); advancedLightCullingCheckBox.SetTooltip("Enable a more aggressive light culling approach which can result in slower culling but faster rendering (Tiled renderer only)"); advancedLightCullingCheckBox.SetPos(XMFLOAT2(x, y += step)); advancedLightCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - advancedLightCullingCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetAdvancedLightCulling(args.bValue); + advancedLightCullingCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetAdvancedLightCulling(args.bValue); }); - advancedLightCullingCheckBox.SetCheck(wiRenderer::GetAdvancedLightCulling()); + advancedLightCullingCheckBox.SetCheck(wi::renderer::GetAdvancedLightCulling()); AddWidget(&advancedLightCullingCheckBox); debugLightCullingCheckBox.Create("DEBUG: "); debugLightCullingCheckBox.SetTooltip("Toggle visualization of the screen space light culling heatmap grid (Tiled renderer only)"); debugLightCullingCheckBox.SetPos(XMFLOAT2(x + 122, y)); debugLightCullingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - debugLightCullingCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetDebugLightCulling(args.bValue); + debugLightCullingCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetDebugLightCulling(args.bValue); }); - debugLightCullingCheckBox.SetCheck(wiRenderer::GetDebugLightCulling()); + debugLightCullingCheckBox.SetCheck(wi::renderer::GetDebugLightCulling()); AddWidget(&debugLightCullingCheckBox); tessellationCheckBox.Create("Tessellation Enabled: "); tessellationCheckBox.SetTooltip("Enable tessellation feature. You also need to specify a tessellation factor for individual objects."); tessellationCheckBox.SetPos(XMFLOAT2(x, y += step)); tessellationCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - tessellationCheckBox.OnClick([=](wiEventArgs args) { - wiRenderer::SetTessellationEnabled(args.bValue); + tessellationCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::renderer::SetTessellationEnabled(args.bValue); }); - tessellationCheckBox.SetCheck(wiRenderer::GetTessellationEnabled()); + tessellationCheckBox.SetCheck(wi::renderer::GetTessellationEnabled()); AddWidget(&tessellationCheckBox); - tessellationCheckBox.SetEnabled(wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::TESSELLATION)); + tessellationCheckBox.SetEnabled(wi::graphics::GetDevice()->CheckCapability(wi::graphics::GraphicsDeviceCapability::TESSELLATION)); speedMultiplierSlider.Create(0, 4, 1, 100000, "Speed: "); speedMultiplierSlider.SetTooltip("Adjust the global speed (time multiplier)"); speedMultiplierSlider.SetSize(XMFLOAT2(100, itemheight)); speedMultiplierSlider.SetPos(XMFLOAT2(x, y += step)); - speedMultiplierSlider.SetValue(wiRenderer::GetGameSpeed()); - speedMultiplierSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetGameSpeed(args.fValue); + speedMultiplierSlider.SetValue(wi::renderer::GetGameSpeed()); + speedMultiplierSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetGameSpeed(args.fValue); }); AddWidget(&speedMultiplierSlider); @@ -239,9 +236,9 @@ void RendererWindow::Create(EditorComponent* editor) transparentShadowsCheckBox.SetTooltip("Enables color tinted shadows and refraction caustics effects for transparent objects and water."); transparentShadowsCheckBox.SetPos(XMFLOAT2(x, y += step)); transparentShadowsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - transparentShadowsCheckBox.SetCheck(wiRenderer::GetTransparentShadowsEnabled()); - transparentShadowsCheckBox.OnClick([=](wiEventArgs args) { - wiRenderer::SetTransparentShadowsEnabled(args.bValue); + transparentShadowsCheckBox.SetCheck(wi::renderer::GetTransparentShadowsEnabled()); + transparentShadowsCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::renderer::SetTransparentShadowsEnabled(args.bValue); }); AddWidget(&transparentShadowsCheckBox); @@ -249,20 +246,20 @@ void RendererWindow::Create(EditorComponent* editor) shadowTypeComboBox.SetSize(XMFLOAT2(100, itemheight)); shadowTypeComboBox.SetPos(XMFLOAT2(x, y += step)); shadowTypeComboBox.AddItem("Shadowmaps"); - if (wiGraphics::GetDevice()->CheckCapability(wiGraphics::GraphicsDeviceCapability::RAYTRACING)) + if (wi::graphics::GetDevice()->CheckCapability(wi::graphics::GraphicsDeviceCapability::RAYTRACING)) { shadowTypeComboBox.AddItem("Ray traced"); } - shadowTypeComboBox.OnSelect([&](wiEventArgs args) { + shadowTypeComboBox.OnSelect([&](wi::gui::EventArgs args) { switch (args.iValue) { default: case 0: - wiRenderer::SetRaytracedShadowsEnabled(false); + wi::renderer::SetRaytracedShadowsEnabled(false); break; case 1: - wiRenderer::SetRaytracedShadowsEnabled(true); + wi::renderer::SetRaytracedShadowsEnabled(true); break; } }); @@ -280,30 +277,30 @@ void RendererWindow::Create(EditorComponent* editor) shadowProps2DComboBox.AddItem("1024"); shadowProps2DComboBox.AddItem("2048"); shadowProps2DComboBox.AddItem("4096"); - shadowProps2DComboBox.OnSelect([&](wiEventArgs args) { + shadowProps2DComboBox.OnSelect([&](wi::gui::EventArgs args) { switch (args.iValue) { case 0: - wiRenderer::SetShadowProps2D(0, -1); + wi::renderer::SetShadowProps2D(0, -1); break; case 1: - wiRenderer::SetShadowProps2D(128, -1); + wi::renderer::SetShadowProps2D(128, -1); break; case 2: - wiRenderer::SetShadowProps2D(256, -1); + wi::renderer::SetShadowProps2D(256, -1); break; case 3: - wiRenderer::SetShadowProps2D(512, -1); + wi::renderer::SetShadowProps2D(512, -1); break; case 4: - wiRenderer::SetShadowProps2D(1024, -1); + wi::renderer::SetShadowProps2D(1024, -1); break; case 5: - wiRenderer::SetShadowProps2D(2048, -1); + wi::renderer::SetShadowProps2D(2048, -1); break; case 6: - wiRenderer::SetShadowProps2D(4096, -1); + wi::renderer::SetShadowProps2D(4096, -1); break; default: break; @@ -324,29 +321,29 @@ void RendererWindow::Create(EditorComponent* editor) shadowPropsCubeComboBox.AddItem("1024"); shadowPropsCubeComboBox.AddItem("2048"); shadowPropsCubeComboBox.AddItem("4096"); - shadowPropsCubeComboBox.OnSelect([&](wiEventArgs args) { + shadowPropsCubeComboBox.OnSelect([&](wi::gui::EventArgs args) { switch (args.iValue) { case 0: - wiRenderer::SetShadowPropsCube(0, -1); + wi::renderer::SetShadowPropsCube(0, -1); break; case 1: - wiRenderer::SetShadowPropsCube(128, -1); + wi::renderer::SetShadowPropsCube(128, -1); break; case 2: - wiRenderer::SetShadowPropsCube(256, -1); + wi::renderer::SetShadowPropsCube(256, -1); break; case 3: - wiRenderer::SetShadowPropsCube(512, -1); + wi::renderer::SetShadowPropsCube(512, -1); break; case 4: - wiRenderer::SetShadowPropsCube(1024, -1); + wi::renderer::SetShadowPropsCube(1024, -1); break; case 5: - wiRenderer::SetShadowPropsCube(2048, -1); + wi::renderer::SetShadowPropsCube(2048, -1); break; case 6: - wiRenderer::SetShadowPropsCube(4096, -1); + wi::renderer::SetShadowPropsCube(4096, -1); break; default: break; @@ -364,7 +361,7 @@ void RendererWindow::Create(EditorComponent* editor) MSAAComboBox.AddItem("2"); MSAAComboBox.AddItem("4"); MSAAComboBox.AddItem("8"); - MSAAComboBox.OnSelect([=](wiEventArgs args) { + MSAAComboBox.OnSelect([=](wi::gui::EventArgs args) { switch (args.iValue) { case 0: @@ -392,10 +389,10 @@ void RendererWindow::Create(EditorComponent* editor) temporalAACheckBox.SetTooltip("Toggle Temporal Anti Aliasing. It is a supersampling techique which is performed across multiple frames."); temporalAACheckBox.SetPos(XMFLOAT2(x, y += step)); temporalAACheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - temporalAACheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetTemporalAAEnabled(args.bValue); + temporalAACheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetTemporalAAEnabled(args.bValue); }); - temporalAACheckBox.SetCheck(wiRenderer::GetTemporalAAEnabled()); + temporalAACheckBox.SetCheck(wi::renderer::GetTemporalAAEnabled()); AddWidget(&temporalAACheckBox); temporalAADebugCheckBox.Create("DEBUGJitter: "); @@ -403,10 +400,10 @@ void RendererWindow::Create(EditorComponent* editor) temporalAADebugCheckBox.SetTooltip("Disable blending of frame history. Camera Subpixel jitter will be visible."); temporalAADebugCheckBox.SetPos(XMFLOAT2(x + 122, y)); temporalAADebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - temporalAADebugCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetTemporalAADebugEnabled(args.bValue); + temporalAADebugCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetTemporalAADebugEnabled(args.bValue); }); - temporalAADebugCheckBox.SetCheck(wiRenderer::GetTemporalAADebugEnabled()); + temporalAADebugCheckBox.SetCheck(wi::renderer::GetTemporalAADebugEnabled()); AddWidget(&temporalAADebugCheckBox); textureQualityComboBox.Create("Texture Quality: "); @@ -416,28 +413,28 @@ void RendererWindow::Create(EditorComponent* editor) textureQualityComboBox.AddItem("Bilinear"); textureQualityComboBox.AddItem("Trilinear"); textureQualityComboBox.AddItem("Anisotropic"); - textureQualityComboBox.OnSelect([&](wiEventArgs args) { - wiGraphics::SamplerDesc desc = wiRenderer::GetSampler(SAMPLER_OBJECTSHADER)->GetDesc(); + textureQualityComboBox.OnSelect([&](wi::gui::EventArgs args) { + wi::graphics::SamplerDesc desc = wi::renderer::GetSampler(wi::enums::SAMPLER_OBJECTSHADER)->GetDesc(); switch (args.iValue) { case 0: - desc.filter = wiGraphics::Filter::MIN_MAG_MIP_POINT; + desc.filter = wi::graphics::Filter::MIN_MAG_MIP_POINT; break; case 1: - desc.filter = wiGraphics::Filter::MIN_MAG_LINEAR_MIP_POINT; + desc.filter = wi::graphics::Filter::MIN_MAG_LINEAR_MIP_POINT; break; case 2: - desc.filter = wiGraphics::Filter::MIN_MAG_MIP_LINEAR; + desc.filter = wi::graphics::Filter::MIN_MAG_MIP_LINEAR; break; case 3: - desc.filter = wiGraphics::Filter::ANISOTROPIC; + desc.filter = wi::graphics::Filter::ANISOTROPIC; break; default: break; } - wiRenderer::ModifyObjectSampler(desc); + wi::renderer::ModifyObjectSampler(desc); }); textureQualityComboBox.SetSelected(3); @@ -448,10 +445,10 @@ void RendererWindow::Create(EditorComponent* editor) mipLodBiasSlider.SetTooltip("Bias the rendered mip map level of the material textures."); mipLodBiasSlider.SetSize(XMFLOAT2(100, itemheight)); mipLodBiasSlider.SetPos(XMFLOAT2(x, y += step)); - mipLodBiasSlider.OnSlide([&](wiEventArgs args) { - wiGraphics::SamplerDesc desc = wiRenderer::GetSampler(SAMPLER_OBJECTSHADER)->GetDesc(); - desc.mip_lod_bias = wiMath::Clamp(args.fValue, -15.9f, 15.9f); - wiRenderer::ModifyObjectSampler(desc); + mipLodBiasSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::graphics::SamplerDesc desc = wi::renderer::GetSampler(wi::enums::SAMPLER_OBJECTSHADER)->GetDesc(); + desc.mip_lod_bias = wi::math::Clamp(args.fValue, -15.9f, 15.9f); + wi::renderer::ModifyObjectSampler(desc); }); AddWidget(&mipLodBiasSlider); @@ -459,9 +456,9 @@ void RendererWindow::Create(EditorComponent* editor) raytraceBounceCountSlider.SetTooltip("How many light bounces to compute when doing ray tracing."); raytraceBounceCountSlider.SetSize(XMFLOAT2(100, itemheight)); raytraceBounceCountSlider.SetPos(XMFLOAT2(x, y += step)); - raytraceBounceCountSlider.SetValue((float)wiRenderer::GetRaytraceBounceCount()); - raytraceBounceCountSlider.OnSlide([&](wiEventArgs args) { - wiRenderer::SetRaytraceBounceCount((uint32_t)args.iValue); + raytraceBounceCountSlider.SetValue((float)wi::renderer::GetRaytraceBounceCount()); + raytraceBounceCountSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::renderer::SetRaytraceBounceCount((uint32_t)args.iValue); }); AddWidget(&raytraceBounceCountSlider); @@ -474,10 +471,10 @@ void RendererWindow::Create(EditorComponent* editor) physicsDebugCheckBox.SetTooltip("Visualize the physics world"); physicsDebugCheckBox.SetPos(XMFLOAT2(x, y += step)); physicsDebugCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - physicsDebugCheckBox.OnClick([](wiEventArgs args) { - wiPhysicsEngine::SetDebugDrawEnabled(args.bValue); + physicsDebugCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::physics::SetDebugDrawEnabled(args.bValue); }); - physicsDebugCheckBox.SetCheck(wiPhysicsEngine::IsDebugDrawEnabled()); + physicsDebugCheckBox.SetCheck(wi::physics::IsDebugDrawEnabled()); AddWidget(&physicsDebugCheckBox); partitionBoxesCheckBox.Create("SPTree visualizer: "); @@ -485,10 +482,10 @@ void RendererWindow::Create(EditorComponent* editor) partitionBoxesCheckBox.SetScriptTip("SetDebugPartitionTreeEnabled(bool enabled)"); partitionBoxesCheckBox.SetPos(XMFLOAT2(x, y += step)); partitionBoxesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - partitionBoxesCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugPartitionTree(args.bValue); + partitionBoxesCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugPartitionTree(args.bValue); }); - partitionBoxesCheckBox.SetCheck(wiRenderer::GetToDrawDebugPartitionTree()); + partitionBoxesCheckBox.SetCheck(wi::renderer::GetToDrawDebugPartitionTree()); AddWidget(&partitionBoxesCheckBox); boneLinesCheckBox.Create("Bone line visualizer: "); @@ -496,10 +493,10 @@ void RendererWindow::Create(EditorComponent* editor) boneLinesCheckBox.SetScriptTip("SetDebugBonesEnabled(bool enabled)"); boneLinesCheckBox.SetPos(XMFLOAT2(x, y += step)); boneLinesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - boneLinesCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugBoneLines(args.bValue); + boneLinesCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugBoneLines(args.bValue); }); - boneLinesCheckBox.SetCheck(wiRenderer::GetToDrawDebugBoneLines()); + boneLinesCheckBox.SetCheck(wi::renderer::GetToDrawDebugBoneLines()); AddWidget(&boneLinesCheckBox); debugEmittersCheckBox.Create("Emitter visualizer: "); @@ -507,10 +504,10 @@ void RendererWindow::Create(EditorComponent* editor) debugEmittersCheckBox.SetScriptTip("SetDebugEmittersEnabled(bool enabled)"); debugEmittersCheckBox.SetPos(XMFLOAT2(x, y += step)); debugEmittersCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - debugEmittersCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugEmitters(args.bValue); + debugEmittersCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugEmitters(args.bValue); }); - debugEmittersCheckBox.SetCheck(wiRenderer::GetToDrawDebugEmitters()); + debugEmittersCheckBox.SetCheck(wi::renderer::GetToDrawDebugEmitters()); AddWidget(&debugEmittersCheckBox); debugForceFieldsCheckBox.Create("Force Field visualizer: "); @@ -518,50 +515,50 @@ void RendererWindow::Create(EditorComponent* editor) debugForceFieldsCheckBox.SetScriptTip("SetDebugForceFieldsEnabled(bool enabled)"); debugForceFieldsCheckBox.SetPos(XMFLOAT2(x, y += step)); debugForceFieldsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - debugForceFieldsCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugForceFields(args.bValue); + debugForceFieldsCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugForceFields(args.bValue); }); - debugForceFieldsCheckBox.SetCheck(wiRenderer::GetToDrawDebugForceFields()); + debugForceFieldsCheckBox.SetCheck(wi::renderer::GetToDrawDebugForceFields()); AddWidget(&debugForceFieldsCheckBox); debugRaytraceBVHCheckBox.Create("Raytrace BVH visualizer: "); debugRaytraceBVHCheckBox.SetTooltip("Visualize scene BVH if raytracing is enabled"); debugRaytraceBVHCheckBox.SetPos(XMFLOAT2(x, y += step)); debugRaytraceBVHCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - debugRaytraceBVHCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetRaytraceDebugBVHVisualizerEnabled(args.bValue); + debugRaytraceBVHCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetRaytraceDebugBVHVisualizerEnabled(args.bValue); }); - debugRaytraceBVHCheckBox.SetCheck(wiRenderer::GetRaytraceDebugBVHVisualizerEnabled()); + debugRaytraceBVHCheckBox.SetCheck(wi::renderer::GetRaytraceDebugBVHVisualizerEnabled()); AddWidget(&debugRaytraceBVHCheckBox); envProbesCheckBox.Create("Env probe visualizer: "); envProbesCheckBox.SetTooltip("Toggle visualization of environment probes as reflective spheres"); envProbesCheckBox.SetPos(XMFLOAT2(x, y += step)); envProbesCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - envProbesCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugEnvProbes(args.bValue); + envProbesCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugEnvProbes(args.bValue); }); - envProbesCheckBox.SetCheck(wiRenderer::GetToDrawDebugEnvProbes()); + envProbesCheckBox.SetCheck(wi::renderer::GetToDrawDebugEnvProbes()); AddWidget(&envProbesCheckBox); cameraVisCheckBox.Create("Camera Proxy visualizer: "); cameraVisCheckBox.SetTooltip("Toggle visualization of camera proxies in the scene"); cameraVisCheckBox.SetPos(XMFLOAT2(x, y += step)); cameraVisCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - cameraVisCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawDebugCameras(args.bValue); + cameraVisCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawDebugCameras(args.bValue); }); - cameraVisCheckBox.SetCheck(wiRenderer::GetToDrawDebugCameras()); + cameraVisCheckBox.SetCheck(wi::renderer::GetToDrawDebugCameras()); AddWidget(&cameraVisCheckBox); gridHelperCheckBox.Create("Grid helper: "); gridHelperCheckBox.SetTooltip("Toggle showing of unit visualizer grid in the world origin"); gridHelperCheckBox.SetPos(XMFLOAT2(x, y += step)); gridHelperCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - gridHelperCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetToDrawGridHelper(args.bValue); + gridHelperCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetToDrawGridHelper(args.bValue); }); - gridHelperCheckBox.SetCheck(wiRenderer::GetToDrawGridHelper()); + gridHelperCheckBox.SetCheck(wi::renderer::GetToDrawGridHelper()); AddWidget(&gridHelperCheckBox); @@ -641,10 +638,10 @@ void RendererWindow::Create(EditorComponent* editor) freezeCullingCameraCheckBox.SetTooltip("Freeze culling camera update. Scene culling will not be updated with the view"); freezeCullingCameraCheckBox.SetPos(XMFLOAT2(x, y += step * 2)); freezeCullingCameraCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - freezeCullingCameraCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetFreezeCullingCameraEnabled(args.bValue); + freezeCullingCameraCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetFreezeCullingCameraEnabled(args.bValue); }); - freezeCullingCameraCheckBox.SetCheck(wiRenderer::GetFreezeCullingCameraEnabled()); + freezeCullingCameraCheckBox.SetCheck(wi::renderer::GetFreezeCullingCameraEnabled()); AddWidget(&freezeCullingCameraCheckBox); @@ -653,10 +650,10 @@ void RendererWindow::Create(EditorComponent* editor) disableAlbedoMapsCheckBox.SetTooltip("Disables albedo maps on objects for easier lighting debugging"); disableAlbedoMapsCheckBox.SetPos(XMFLOAT2(x, y += step)); disableAlbedoMapsCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - disableAlbedoMapsCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetDisableAlbedoMaps(args.bValue); + disableAlbedoMapsCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetDisableAlbedoMaps(args.bValue); }); - disableAlbedoMapsCheckBox.SetCheck(wiRenderer::IsDisableAlbedoMaps()); + disableAlbedoMapsCheckBox.SetCheck(wi::renderer::IsDisableAlbedoMaps()); AddWidget(&disableAlbedoMapsCheckBox); @@ -664,10 +661,10 @@ void RendererWindow::Create(EditorComponent* editor) forceDiffuseLightingCheckBox.SetTooltip("Sets every surface fully diffuse, with zero specularity"); forceDiffuseLightingCheckBox.SetPos(XMFLOAT2(x, y += step)); forceDiffuseLightingCheckBox.SetSize(XMFLOAT2(itemheight, itemheight)); - forceDiffuseLightingCheckBox.OnClick([](wiEventArgs args) { - wiRenderer::SetForceDiffuseLighting(args.bValue); + forceDiffuseLightingCheckBox.OnClick([](wi::gui::EventArgs args) { + wi::renderer::SetForceDiffuseLighting(args.bValue); }); - forceDiffuseLightingCheckBox.SetCheck(wiRenderer::IsForceDiffuseLighting()); + forceDiffuseLightingCheckBox.SetCheck(wi::renderer::IsForceDiffuseLighting()); AddWidget(&forceDiffuseLightingCheckBox); @@ -723,24 +720,24 @@ uint32_t RendererWindow::GetPickType() const return pickType; } -void RendererWindow::UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain) +void RendererWindow::UpdateSwapChainFormats(wi::graphics::SwapChain* swapChain) { swapchainComboBox.OnSelect(nullptr); swapchainComboBox.ClearItems(); - swapchainComboBox.AddItem("SDR 8bit", static_cast(wiGraphics::Format::R8G8B8A8_UNORM)); - swapchainComboBox.AddItem("SDR 10bit", static_cast(wiGraphics::Format::R10G10B10A2_UNORM)); - if (wiGraphics::GetDevice()->IsSwapChainSupportsHDR(swapChain)) + swapchainComboBox.AddItem("SDR 8bit", static_cast(wi::graphics::Format::R8G8B8A8_UNORM)); + swapchainComboBox.AddItem("SDR 10bit", static_cast(wi::graphics::Format::R10G10B10A2_UNORM)); + if (wi::graphics::GetDevice()->IsSwapChainSupportsHDR(swapChain)) { - swapchainComboBox.AddItem("HDR 10bit", static_cast(wiGraphics::Format::R10G10B10A2_UNORM)); - swapchainComboBox.AddItem("HDR 16bit", static_cast(wiGraphics::Format::R16G16B16A16_FLOAT)); + swapchainComboBox.AddItem("HDR 10bit", static_cast(wi::graphics::Format::R10G10B10A2_UNORM)); + swapchainComboBox.AddItem("HDR 16bit", static_cast(wi::graphics::Format::R16G16B16A16_FLOAT)); switch (swapChain->desc.format) { default: - case wiGraphics::Format::R8G8B8A8_UNORM: + case wi::graphics::Format::R8G8B8A8_UNORM: swapchainComboBox.SetSelected(0); break; - case wiGraphics::Format::R10G10B10A2_UNORM: + case wi::graphics::Format::R10G10B10A2_UNORM: if (swapChain->desc.allow_hdr) { swapchainComboBox.SetSelected(2); @@ -750,7 +747,7 @@ void RendererWindow::UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain) swapchainComboBox.SetSelected(1); } break; - case wiGraphics::Format::R16G16B16A16_FLOAT: + case wi::graphics::Format::R16G16B16A16_FLOAT: swapchainComboBox.SetSelected(4); break; } @@ -760,21 +757,21 @@ void RendererWindow::UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain) switch (swapChain->desc.format) { default: - case wiGraphics::Format::R8G8B8A8_UNORM: + case wi::graphics::Format::R8G8B8A8_UNORM: swapchainComboBox.SetSelected(0); break; - case wiGraphics::Format::R10G10B10A2_UNORM: + case wi::graphics::Format::R10G10B10A2_UNORM: swapchainComboBox.SetSelected(1); break; - case wiGraphics::Format::R16G16B16A16_FLOAT: + case wi::graphics::Format::R16G16B16A16_FLOAT: swapchainComboBox.SetSelected(1); break; } } - swapchainComboBox.OnSelect([=](wiEventArgs args) { + swapchainComboBox.OnSelect([=](wi::gui::EventArgs args) { - swapChain->desc.format = (wiGraphics::Format)args.userdata; + swapChain->desc.format = (wi::graphics::Format)args.userdata; switch (args.iValue) { default: @@ -788,7 +785,7 @@ void RendererWindow::UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain) break; } - bool success = wiGraphics::GetDevice()->CreateSwapChain(&swapChain->desc, nullptr, swapChain); + bool success = wi::graphics::GetDevice()->CreateSwapChain(&swapChain->desc, nullptr, swapChain); assert(success); }); } diff --git a/Editor/RendererWindow.h b/Editor/RendererWindow.h index aa631543e..e933792d0 100644 --- a/Editor/RendererWindow.h +++ b/Editor/RendererWindow.h @@ -6,7 +6,7 @@ class EditorComponent; enum PICKTYPE { PICK_VOID = 0, - PICK_OBJECT = RENDERTYPE_OPAQUE | RENDERTYPE_TRANSPARENT | RENDERTYPE_WATER, + PICK_OBJECT = wi::enums::RENDERTYPE_ALL, PICK_LIGHT = 8, PICK_DECAL = 16, PICK_ENVPROBE = 32, @@ -18,68 +18,68 @@ enum PICKTYPE PICK_SOUND = 2048, }; -class RendererWindow : public wiWindow +class RendererWindow : public wi::gui::Window { public: void Create(EditorComponent* editorcomponent); - wiCheckBox vsyncCheckBox; - wiComboBox swapchainComboBox; - wiCheckBox occlusionCullingCheckBox; - wiSlider resolutionScaleSlider; - wiCheckBox surfelGICheckBox; - wiCheckBox surfelGIDebugCheckBox; - wiCheckBox voxelRadianceCheckBox; - wiCheckBox voxelRadianceDebugCheckBox; - wiCheckBox voxelRadianceSecondaryBounceCheckBox; - wiCheckBox voxelRadianceReflectionsCheckBox; - wiSlider voxelRadianceVoxelSizeSlider; - wiSlider voxelRadianceConeTracingSlider; - wiSlider voxelRadianceRayStepSizeSlider; - wiSlider voxelRadianceMaxDistanceSlider; - wiCheckBox physicsDebugCheckBox; - wiCheckBox partitionBoxesCheckBox; - wiCheckBox boneLinesCheckBox; - wiCheckBox debugEmittersCheckBox; - wiCheckBox debugForceFieldsCheckBox; - wiCheckBox debugRaytraceBVHCheckBox; - wiCheckBox wireFrameCheckBox; - wiCheckBox variableRateShadingClassificationCheckBox; - wiCheckBox variableRateShadingClassificationDebugCheckBox; - wiCheckBox advancedLightCullingCheckBox; - wiCheckBox debugLightCullingCheckBox; - wiCheckBox tessellationCheckBox; - wiCheckBox envProbesCheckBox; - wiCheckBox gridHelperCheckBox; - wiCheckBox cameraVisCheckBox; - wiCheckBox pickTypeObjectCheckBox; - wiCheckBox pickTypeEnvProbeCheckBox; - wiCheckBox pickTypeLightCheckBox; - wiCheckBox pickTypeDecalCheckBox; - wiCheckBox pickTypeForceFieldCheckBox; - wiCheckBox pickTypeEmitterCheckBox; - wiCheckBox pickTypeHairCheckBox; - wiCheckBox pickTypeCameraCheckBox; - wiCheckBox pickTypeArmatureCheckBox; - wiCheckBox pickTypeSoundCheckBox; - wiSlider speedMultiplierSlider; - wiCheckBox transparentShadowsCheckBox; - wiComboBox shadowTypeComboBox; - wiComboBox shadowProps2DComboBox; - wiComboBox shadowPropsCubeComboBox; - wiComboBox MSAAComboBox; - wiCheckBox temporalAACheckBox; - wiCheckBox temporalAADebugCheckBox; - wiComboBox textureQualityComboBox; - wiSlider mipLodBiasSlider; - wiSlider raytraceBounceCountSlider; + wi::gui::CheckBox vsyncCheckBox; + wi::gui::ComboBox swapchainComboBox; + wi::gui::CheckBox occlusionCullingCheckBox; + wi::gui::Slider resolutionScaleSlider; + wi::gui::CheckBox surfelGICheckBox; + wi::gui::CheckBox surfelGIDebugCheckBox; + wi::gui::CheckBox voxelRadianceCheckBox; + wi::gui::CheckBox voxelRadianceDebugCheckBox; + wi::gui::CheckBox voxelRadianceSecondaryBounceCheckBox; + wi::gui::CheckBox voxelRadianceReflectionsCheckBox; + wi::gui::Slider voxelRadianceVoxelSizeSlider; + wi::gui::Slider voxelRadianceConeTracingSlider; + wi::gui::Slider voxelRadianceRayStepSizeSlider; + wi::gui::Slider voxelRadianceMaxDistanceSlider; + wi::gui::CheckBox physicsDebugCheckBox; + wi::gui::CheckBox partitionBoxesCheckBox; + wi::gui::CheckBox boneLinesCheckBox; + wi::gui::CheckBox debugEmittersCheckBox; + wi::gui::CheckBox debugForceFieldsCheckBox; + wi::gui::CheckBox debugRaytraceBVHCheckBox; + wi::gui::CheckBox wireFrameCheckBox; + wi::gui::CheckBox variableRateShadingClassificationCheckBox; + wi::gui::CheckBox variableRateShadingClassificationDebugCheckBox; + wi::gui::CheckBox advancedLightCullingCheckBox; + wi::gui::CheckBox debugLightCullingCheckBox; + wi::gui::CheckBox tessellationCheckBox; + wi::gui::CheckBox envProbesCheckBox; + wi::gui::CheckBox gridHelperCheckBox; + wi::gui::CheckBox cameraVisCheckBox; + wi::gui::CheckBox pickTypeObjectCheckBox; + wi::gui::CheckBox pickTypeEnvProbeCheckBox; + wi::gui::CheckBox pickTypeLightCheckBox; + wi::gui::CheckBox pickTypeDecalCheckBox; + wi::gui::CheckBox pickTypeForceFieldCheckBox; + wi::gui::CheckBox pickTypeEmitterCheckBox; + wi::gui::CheckBox pickTypeHairCheckBox; + wi::gui::CheckBox pickTypeCameraCheckBox; + wi::gui::CheckBox pickTypeArmatureCheckBox; + wi::gui::CheckBox pickTypeSoundCheckBox; + wi::gui::Slider speedMultiplierSlider; + wi::gui::CheckBox transparentShadowsCheckBox; + wi::gui::ComboBox shadowTypeComboBox; + wi::gui::ComboBox shadowProps2DComboBox; + wi::gui::ComboBox shadowPropsCubeComboBox; + wi::gui::ComboBox MSAAComboBox; + wi::gui::CheckBox temporalAACheckBox; + wi::gui::CheckBox temporalAADebugCheckBox; + wi::gui::ComboBox textureQualityComboBox; + wi::gui::Slider mipLodBiasSlider; + wi::gui::Slider raytraceBounceCountSlider; - wiCheckBox freezeCullingCameraCheckBox; - wiCheckBox disableAlbedoMapsCheckBox; - wiCheckBox forceDiffuseLightingCheckBox; + wi::gui::CheckBox freezeCullingCameraCheckBox; + wi::gui::CheckBox disableAlbedoMapsCheckBox; + wi::gui::CheckBox forceDiffuseLightingCheckBox; uint32_t GetPickType() const; - void UpdateSwapChainFormats(wiGraphics::SwapChain* swapChain); + void UpdateSwapChainFormats(wi::graphics::SwapChain* swapChain); }; diff --git a/Editor/SoundWindow.cpp b/Editor/SoundWindow.cpp index 244f73db2..c3708bf1e 100644 --- a/Editor/SoundWindow.cpp +++ b/Editor/SoundWindow.cpp @@ -3,13 +3,13 @@ #include "wiAudio.h" #include "Editor.h" -using namespace wiGraphics; -using namespace wiECS; -using namespace wiScene; +using namespace wi::graphics; +using namespace wi::ecs; +using namespace wi::scene; void SoundWindow::Create(EditorComponent* editor) { - wiWindow::Create("Sound Window"); + wi::gui::Window::Create("Sound Window"); SetSize(XMFLOAT2(440, 220)); float x = 20; @@ -20,8 +20,8 @@ void SoundWindow::Create(EditorComponent* editor) reverbComboBox.Create("Reverb: "); reverbComboBox.SetPos(XMFLOAT2(x + 80, y += step)); reverbComboBox.SetSize(XMFLOAT2(180, hei)); - reverbComboBox.OnSelect([&](wiEventArgs args) { - wiAudio::SetReverb((wiAudio::REVERB_PRESET)args.iValue); + reverbComboBox.OnSelect([&](wi::gui::EventArgs args) { + wi::audio::SetReverb((wi::audio::REVERB_PRESET)args.iValue); }); reverbComboBox.AddItem("DEFAULT"); reverbComboBox.AddItem("GENERIC"); @@ -62,13 +62,13 @@ void SoundWindow::Create(EditorComponent* editor) addButton.SetTooltip("Add a sound file to the scene."); addButton.SetPos(XMFLOAT2(x, y += step)); addButton.SetSize(XMFLOAT2(80, hei)); - addButton.OnClick([=](wiEventArgs args) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + addButton.OnClick([=](wi::gui::EventArgs args) { + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Sound"; - params.extensions = wiResourceManager::GetSupportedSoundExtensions(); - wiHelper::FileDialog(params, [=](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + params.extensions = wi::resourcemanager::GetSupportedSoundExtensions(); + wi::helper::FileDialog(params, [=](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { Entity entity = GetScene().Entity_CreateSound("editorSound", fileName); editor->ClearSelected(); editor->AddSelected(entity); @@ -88,11 +88,11 @@ void SoundWindow::Create(EditorComponent* editor) nameField.SetTooltip("Enter a sound name to identify this entity..."); nameField.SetPos(XMFLOAT2(x, y += step)); nameField.SetSize(XMFLOAT2(300, hei)); - nameField.OnInputAccepted([=](wiEventArgs args) { - NameComponent* name = wiScene::GetScene().names.GetComponent(entity); + nameField.OnInputAccepted([=](wi::gui::EventArgs args) { + NameComponent* name = wi::scene::GetScene().names.GetComponent(entity); if (name == nullptr) { - name = &wiScene::GetScene().names.Create(entity); + name = &wi::scene::GetScene().names.Create(entity); } *name = args.sValue; @@ -105,7 +105,7 @@ void SoundWindow::Create(EditorComponent* editor) playstopButton.SetTooltip("Play/Stop selected sound instance."); playstopButton.SetPos(XMFLOAT2(x, y += step)); playstopButton.SetSize(XMFLOAT2(80, hei)); - playstopButton.OnClick([&](wiEventArgs args) { + playstopButton.OnClick([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { @@ -128,7 +128,7 @@ void SoundWindow::Create(EditorComponent* editor) loopedCheckbox.SetTooltip("Enable looping for the selected sound instance."); loopedCheckbox.SetPos(XMFLOAT2(x + 150, y)); loopedCheckbox.SetSize(XMFLOAT2(hei, hei)); - loopedCheckbox.OnClick([&](wiEventArgs args) { + loopedCheckbox.OnClick([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { @@ -142,12 +142,12 @@ void SoundWindow::Create(EditorComponent* editor) reverbCheckbox.SetTooltip("Enable/disable reverb."); reverbCheckbox.SetPos(XMFLOAT2(x + 240, y)); reverbCheckbox.SetSize(XMFLOAT2(hei, hei)); - reverbCheckbox.OnClick([&](wiEventArgs args) { + reverbCheckbox.OnClick([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { sound->soundinstance.SetEnableReverb(args.bValue); - wiAudio::CreateSoundInstance(&sound->soundResource->sound, &sound->soundinstance); + wi::audio::CreateSoundInstance(&sound->soundResource.GetSound(), &sound->soundinstance); } }); AddWidget(&reverbCheckbox); @@ -157,12 +157,12 @@ void SoundWindow::Create(EditorComponent* editor) disable3dCheckbox.SetTooltip("Sounds in the scene are 3D spatial by default. Select this to disable 3D effect."); disable3dCheckbox.SetPos(XMFLOAT2(x + 300, y)); disable3dCheckbox.SetSize(XMFLOAT2(hei, hei)); - disable3dCheckbox.OnClick([&](wiEventArgs args) { + disable3dCheckbox.OnClick([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { sound->SetDisable3D(args.bValue); - wiAudio::CreateSoundInstance(&sound->soundResource->sound, &sound->soundinstance); + wi::audio::CreateSoundInstance(&sound->soundResource.GetSound(), &sound->soundinstance); } }); AddWidget(&disable3dCheckbox); @@ -172,7 +172,7 @@ void SoundWindow::Create(EditorComponent* editor) volumeSlider.SetTooltip("Set volume level for the selected sound instance."); volumeSlider.SetPos(XMFLOAT2(x + 60, y += step)); volumeSlider.SetSize(XMFLOAT2(240, hei)); - volumeSlider.OnSlide([&](wiEventArgs args) { + volumeSlider.OnSlide([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { @@ -185,12 +185,12 @@ void SoundWindow::Create(EditorComponent* editor) submixComboBox.Create("Submix: "); submixComboBox.SetPos(XMFLOAT2(x + 80, y += step)); submixComboBox.SetSize(XMFLOAT2(180, hei)); - submixComboBox.OnSelect([&](wiEventArgs args) { + submixComboBox.OnSelect([&](wi::gui::EventArgs args) { SoundComponent* sound = GetScene().sounds.GetComponent(entity); if (sound != nullptr) { - sound->soundinstance.type = (wiAudio::SUBMIX_TYPE)args.iValue; - wiAudio::CreateSoundInstance(&sound->soundResource->sound, &sound->soundinstance); + sound->soundinstance.type = (wi::audio::SUBMIX_TYPE)args.iValue; + wi::audio::CreateSoundInstance(&sound->soundResource.GetSound(), &sound->soundinstance); } }); submixComboBox.AddItem("SOUNDEFFECT"); @@ -213,7 +213,7 @@ void SoundWindow::SetEntity(Entity entity) { this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); SoundComponent* sound = scene.sounds.GetComponent(entity); NameComponent* name = scene.names.GetComponent(entity); diff --git a/Editor/SoundWindow.h b/Editor/SoundWindow.h index c0f89bc3e..326d3fcd9 100644 --- a/Editor/SoundWindow.h +++ b/Editor/SoundWindow.h @@ -3,22 +3,22 @@ class EditorComponent; -class SoundWindow : public wiWindow +class SoundWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity = wiECS::INVALID_ENTITY; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY; + void SetEntity(wi::ecs::Entity entity); - wiComboBox reverbComboBox; - wiButton addButton; - wiLabel filenameLabel; - wiTextInputField nameField; - wiButton playstopButton; - wiCheckBox loopedCheckbox; - wiCheckBox reverbCheckbox; - wiCheckBox disable3dCheckbox; - wiSlider volumeSlider; - wiComboBox submixComboBox; + wi::gui::ComboBox reverbComboBox; + wi::gui::Button addButton; + wi::gui::Label filenameLabel; + wi::gui::TextInputField nameField; + wi::gui::Button playstopButton; + wi::gui::CheckBox loopedCheckbox; + wi::gui::CheckBox reverbCheckbox; + wi::gui::CheckBox disable3dCheckbox; + wi::gui::Slider volumeSlider; + wi::gui::ComboBox submixComboBox; }; diff --git a/Editor/SpringWindow.cpp b/Editor/SpringWindow.cpp index d9c331c38..ba44ca7db 100644 --- a/Editor/SpringWindow.cpp +++ b/Editor/SpringWindow.cpp @@ -2,13 +2,13 @@ #include "SpringWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void SpringWindow::Create(EditorComponent* editor) { - wiWindow::Create("Spring Window"); + wi::gui::Window::Create("Spring Window"); SetSize(XMFLOAT2(460, 200)); float x = 150; @@ -33,8 +33,8 @@ void SpringWindow::Create(EditorComponent* editor) disabledCheckBox.SetTooltip("Disable simulation."); disabledCheckBox.SetPos(XMFLOAT2(x, y += step)); disabledCheckBox.SetSize(XMFLOAT2(hei, hei)); - disabledCheckBox.OnClick([=](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->SetDisabled(args.bValue); + disabledCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->SetDisabled(args.bValue); }); AddWidget(&disabledCheckBox); @@ -42,8 +42,8 @@ void SpringWindow::Create(EditorComponent* editor) stretchCheckBox.SetTooltip("Stretch means that length from parent transform won't be preserved."); stretchCheckBox.SetPos(XMFLOAT2(x, y += step)); stretchCheckBox.SetSize(XMFLOAT2(hei, hei)); - stretchCheckBox.OnClick([=](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->SetStretchEnabled(args.bValue); + stretchCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->SetStretchEnabled(args.bValue); }); AddWidget(&stretchCheckBox); @@ -51,8 +51,8 @@ void SpringWindow::Create(EditorComponent* editor) gravityCheckBox.SetTooltip("Whether global gravity should affect the spring"); gravityCheckBox.SetPos(XMFLOAT2(x, y += step)); gravityCheckBox.SetSize(XMFLOAT2(hei, hei)); - gravityCheckBox.OnClick([=](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->SetGravityEnabled(args.bValue); + gravityCheckBox.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->SetGravityEnabled(args.bValue); }); AddWidget(&gravityCheckBox); @@ -60,8 +60,8 @@ void SpringWindow::Create(EditorComponent* editor) stiffnessSlider.SetTooltip("The stiffness affects how strongly the spring tries to orient itself to rest pose (higher values increase the jiggliness)"); stiffnessSlider.SetPos(XMFLOAT2(x, y += step)); stiffnessSlider.SetSize(XMFLOAT2(siz, hei)); - stiffnessSlider.OnSlide([&](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->stiffness = args.fValue; + stiffnessSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->stiffness = args.fValue; }); AddWidget(&stiffnessSlider); @@ -69,8 +69,8 @@ void SpringWindow::Create(EditorComponent* editor) dampingSlider.SetTooltip("The damping affects how fast energy is lost (higher values make the spring come to rest faster)"); dampingSlider.SetPos(XMFLOAT2(x, y += step)); dampingSlider.SetSize(XMFLOAT2(siz, hei)); - dampingSlider.OnSlide([&](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->damping = args.fValue; + dampingSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->damping = args.fValue; }); AddWidget(&dampingSlider); @@ -78,8 +78,8 @@ void SpringWindow::Create(EditorComponent* editor) windSlider.SetTooltip("How much the global wind effect affects the spring"); windSlider.SetPos(XMFLOAT2(x, y += step)); windSlider.SetSize(XMFLOAT2(siz, hei)); - windSlider.OnSlide([&](wiEventArgs args) { - wiScene::GetScene().springs.GetComponent(entity)->wind_affection = args.fValue; + windSlider.OnSlide([&](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.GetComponent(entity)->wind_affection = args.fValue; }); AddWidget(&windSlider); @@ -93,7 +93,7 @@ void SpringWindow::SetEntity(Entity entity) { this->entity = entity; - const SpringComponent* spring = wiScene::GetScene().springs.GetComponent(entity); + const SpringComponent* spring = wi::scene::GetScene().springs.GetComponent(entity); if (spring != nullptr) { @@ -111,7 +111,7 @@ void SpringWindow::SetEntity(Entity entity) SetEnabled(false); } - const TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + const TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { createButton.SetEnabled(true); @@ -119,16 +119,16 @@ void SpringWindow::SetEntity(Entity entity) if (spring == nullptr) { createButton.SetText("Create"); - createButton.OnClick([=](wiEventArgs args) { - wiScene::GetScene().springs.Create(entity); + createButton.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.Create(entity); SetEntity(entity); }); } else { createButton.SetText("Remove"); - createButton.OnClick([=](wiEventArgs args) { - wiScene::GetScene().springs.Remove_KeepSorted(entity); + createButton.OnClick([=](wi::gui::EventArgs args) { + wi::scene::GetScene().springs.Remove_KeepSorted(entity); SetEntity(entity); }); } diff --git a/Editor/SpringWindow.h b/Editor/SpringWindow.h index 53ffa5dab..d1a40efec 100644 --- a/Editor/SpringWindow.h +++ b/Editor/SpringWindow.h @@ -3,21 +3,21 @@ class EditorComponent; -class SpringWindow : public wiWindow +class SpringWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiButton createButton; - wiCheckBox debugCheckBox; - wiCheckBox disabledCheckBox; - wiCheckBox stretchCheckBox; - wiCheckBox gravityCheckBox; - wiSlider stiffnessSlider; - wiSlider dampingSlider; - wiSlider windSlider; + wi::gui::Button createButton; + wi::gui::CheckBox debugCheckBox; + wi::gui::CheckBox disabledCheckBox; + wi::gui::CheckBox stretchCheckBox; + wi::gui::CheckBox gravityCheckBox; + wi::gui::Slider stiffnessSlider; + wi::gui::Slider dampingSlider; + wi::gui::Slider windSlider; }; diff --git a/Editor/TransformWindow.cpp b/Editor/TransformWindow.cpp index 339439e26..11ca17744 100644 --- a/Editor/TransformWindow.cpp +++ b/Editor/TransformWindow.cpp @@ -2,13 +2,13 @@ #include "TransformWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void TransformWindow::Create(EditorComponent* editor) { - wiWindow::Create("Transform Window"); + wi::gui::Window::Create("Transform Window"); SetSize(XMFLOAT2(460, 180)); float x = 100; @@ -21,9 +21,9 @@ void TransformWindow::Create(EditorComponent* editor) createButton.SetTooltip("Create a new entity with only a trasform component"); createButton.SetPos(XMFLOAT2(x, y += step)); createButton.SetSize(XMFLOAT2(350, hei)); - createButton.OnClick([=](wiEventArgs args) { + createButton.OnClick([=](wi::gui::EventArgs args) { Entity entity = CreateEntity(); - wiScene::GetScene().transforms.Create(entity); + wi::scene::GetScene().transforms.Create(entity); editor->ClearSelected(); editor->AddSelected(entity); editor->RefreshSceneGraphView(); @@ -35,8 +35,8 @@ void TransformWindow::Create(EditorComponent* editor) parentCombo.SetSize(XMFLOAT2(330, hei)); parentCombo.SetPos(XMFLOAT2(x, y += step)); parentCombo.SetEnabled(false); - parentCombo.OnSelect([&](wiEventArgs args) { - Scene& scene = wiScene::GetScene(); + parentCombo.OnSelect([&](wi::gui::EventArgs args) { + Scene& scene = wi::scene::GetScene(); scene.Component_Detach(entity); @@ -54,8 +54,8 @@ void TransformWindow::Create(EditorComponent* editor) txInput.SetDescription("Translation X: "); txInput.SetPos(XMFLOAT2(x, y += step)); txInput.SetSize(XMFLOAT2(siz, hei)); - txInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + txInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->translation_local.x = args.fValue; @@ -69,8 +69,8 @@ void TransformWindow::Create(EditorComponent* editor) tyInput.SetDescription("Translation Y: "); tyInput.SetPos(XMFLOAT2(x, y += step)); tyInput.SetSize(XMFLOAT2(siz, hei)); - tyInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + tyInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->translation_local.y = args.fValue; @@ -84,8 +84,8 @@ void TransformWindow::Create(EditorComponent* editor) tzInput.SetDescription("Translation Z: "); tzInput.SetPos(XMFLOAT2(x, y += step)); tzInput.SetSize(XMFLOAT2(siz, hei)); - tzInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + tzInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->translation_local.z = args.fValue; @@ -105,8 +105,8 @@ void TransformWindow::Create(EditorComponent* editor) rxInput.SetDescription("Rotation X: "); rxInput.SetPos(XMFLOAT2(x, y += step)); rxInput.SetSize(XMFLOAT2(siz, hei)); - rxInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + rxInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->rotation_local.x = args.fValue; @@ -120,8 +120,8 @@ void TransformWindow::Create(EditorComponent* editor) ryInput.SetDescription("Rotation Y: "); ryInput.SetPos(XMFLOAT2(x, y += step)); ryInput.SetSize(XMFLOAT2(siz, hei)); - ryInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + ryInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->rotation_local.y = args.fValue; @@ -135,8 +135,8 @@ void TransformWindow::Create(EditorComponent* editor) rzInput.SetDescription("Rotation Z: "); rzInput.SetPos(XMFLOAT2(x, y += step)); rzInput.SetSize(XMFLOAT2(siz, hei)); - rzInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + rzInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->rotation_local.z = args.fValue; @@ -150,8 +150,8 @@ void TransformWindow::Create(EditorComponent* editor) rwInput.SetDescription("Rotation W: "); rwInput.SetPos(XMFLOAT2(x, y += step)); rwInput.SetSize(XMFLOAT2(siz, hei)); - rwInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + rwInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->rotation_local.w = args.fValue; @@ -172,8 +172,8 @@ void TransformWindow::Create(EditorComponent* editor) sxInput.SetDescription("Scale X: "); sxInput.SetPos(XMFLOAT2(x, y += step)); sxInput.SetSize(XMFLOAT2(siz, hei)); - sxInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + sxInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->scale_local.x = args.fValue; @@ -187,8 +187,8 @@ void TransformWindow::Create(EditorComponent* editor) syInput.SetDescription("Scale Y: "); syInput.SetPos(XMFLOAT2(x, y += step)); syInput.SetSize(XMFLOAT2(siz, hei)); - syInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + syInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->scale_local.y = args.fValue; @@ -202,8 +202,8 @@ void TransformWindow::Create(EditorComponent* editor) szInput.SetDescription("Scale Z: "); szInput.SetPos(XMFLOAT2(x, y += step)); szInput.SetSize(XMFLOAT2(siz, hei)); - szInput.OnInputAccepted([&](wiEventArgs args) { - TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); + szInput.OnInputAccepted([&](wi::gui::EventArgs args) { + TransformComponent* transform = wi::scene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { transform->scale_local.z = args.fValue; @@ -222,7 +222,7 @@ void TransformWindow::SetEntity(Entity entity) { this->entity = entity; - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); const TransformComponent* transform = scene.transforms.GetComponent(entity); if (transform != nullptr) diff --git a/Editor/TransformWindow.h b/Editor/TransformWindow.h index 489e4a788..ad6885270 100644 --- a/Editor/TransformWindow.h +++ b/Editor/TransformWindow.h @@ -3,29 +3,29 @@ class EditorComponent; -class TransformWindow : public wiWindow +class TransformWindow : public wi::gui::Window { public: void Create(EditorComponent* editor); - wiECS::Entity entity; - void SetEntity(wiECS::Entity entity); + wi::ecs::Entity entity; + void SetEntity(wi::ecs::Entity entity); - wiButton createButton; + wi::gui::Button createButton; - wiComboBox parentCombo; + wi::gui::ComboBox parentCombo; - wiTextInputField txInput; - wiTextInputField tyInput; - wiTextInputField tzInput; + wi::gui::TextInputField txInput; + wi::gui::TextInputField tyInput; + wi::gui::TextInputField tzInput; - wiTextInputField rxInput; - wiTextInputField ryInput; - wiTextInputField rzInput; - wiTextInputField rwInput; + wi::gui::TextInputField rxInput; + wi::gui::TextInputField ryInput; + wi::gui::TextInputField rzInput; + wi::gui::TextInputField rwInput; - wiTextInputField sxInput; - wiTextInputField syInput; - wiTextInputField szInput; + wi::gui::TextInputField sxInput; + wi::gui::TextInputField syInput; + wi::gui::TextInputField szInput; }; diff --git a/Editor/Translator.cpp b/Editor/Translator.cpp index f305fef5d..bff1ed5f9 100644 --- a/Editor/Translator.cpp +++ b/Editor/Translator.cpp @@ -4,11 +4,12 @@ #include "wiInput.h" #include "wiMath.h" #include "shaders/ShaderInterop_Renderer.h" -#include "wiEvent.h" +#include "wiEventHandler.h" -using namespace wiGraphics; -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; +using namespace wi::graphics; +using namespace wi::primitive; PipelineState pso_solidpart; PipelineState pso_wirepart; @@ -24,17 +25,17 @@ namespace Translator_Internal { void LoadShaders() { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); { PipelineStateDesc desc; - desc.vs = wiRenderer::GetShader(VSTYPE_VERTEXCOLOR); - desc.ps = wiRenderer::GetShader(PSTYPE_VERTEXCOLOR); - desc.il = wiRenderer::GetInputLayout(ILTYPE_VERTEXCOLOR); - desc.dss = wiRenderer::GetDepthStencilState(DSSTYPE_DEPTHDISABLED); - desc.rs = wiRenderer::GetRasterizerState(RSTYPE_DOUBLESIDED); - desc.bs = wiRenderer::GetBlendState(BSTYPE_ADDITIVE); + desc.vs = wi::renderer::GetShader(wi::enums::VSTYPE_VERTEXCOLOR); + desc.ps = wi::renderer::GetShader(wi::enums::PSTYPE_VERTEXCOLOR); + desc.il = wi::renderer::GetInputLayout(wi::enums::ILTYPE_VERTEXCOLOR); + desc.dss = wi::renderer::GetDepthStencilState(wi::enums::DSSTYPE_DEPTHDISABLED); + desc.rs = wi::renderer::GetRasterizerState(wi::enums::RSTYPE_DOUBLESIDED); + desc.bs = wi::renderer::GetBlendState(wi::enums::BSTYPE_ADDITIVE); desc.pt = PrimitiveTopology::TRIANGLELIST; device->CreatePipelineState(&desc, &pso_solidpart); @@ -43,12 +44,12 @@ namespace Translator_Internal { PipelineStateDesc desc; - desc.vs = wiRenderer::GetShader(VSTYPE_VERTEXCOLOR); - desc.ps = wiRenderer::GetShader(PSTYPE_VERTEXCOLOR); - desc.il = wiRenderer::GetInputLayout(ILTYPE_VERTEXCOLOR); - desc.dss = wiRenderer::GetDepthStencilState(DSSTYPE_DEPTHDISABLED); - desc.rs = wiRenderer::GetRasterizerState(RSTYPE_WIRE_DOUBLESIDED_SMOOTH); - desc.bs = wiRenderer::GetBlendState(BSTYPE_TRANSPARENT); + desc.vs = wi::renderer::GetShader(wi::enums::VSTYPE_VERTEXCOLOR); + desc.ps = wi::renderer::GetShader(wi::enums::PSTYPE_VERTEXCOLOR); + desc.il = wi::renderer::GetInputLayout(wi::enums::ILTYPE_VERTEXCOLOR); + desc.dss = wi::renderer::GetDepthStencilState(wi::enums::DSSTYPE_DEPTHDISABLED); + desc.rs = wi::renderer::GetRasterizerState(wi::enums::RSTYPE_WIRE_DOUBLESIDED_SMOOTH); + desc.bs = wi::renderer::GetBlendState(wi::enums::BSTYPE_TRANSPARENT); desc.pt = PrimitiveTopology::LINELIST; device->CreatePipelineState(&desc, &pso_wirepart); @@ -58,7 +59,7 @@ namespace Translator_Internal void Translator::Create() { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); if (!vertexBuffer_Axis.IsValid()) { @@ -155,7 +156,7 @@ void Translator::Create() } } -void Translator::Update(const wiCanvas& canvas) +void Translator::Update(const wi::Canvas& canvas) { if (selected.empty()) { @@ -165,8 +166,8 @@ void Translator::Update(const wiCanvas& canvas) dragStarted = false; dragEnded = false; - XMFLOAT4 pointer = wiInput::GetPointer(); - const CameraComponent& cam = wiScene::GetCamera(); + XMFLOAT4 pointer = wi::input::GetPointer(); + const CameraComponent& cam = wi::scene::GetCamera(); XMVECTOR pos = transform.GetPositionV(); if (enabled) @@ -180,9 +181,9 @@ void Translator::Update(const wiCanvas& canvas) XMMATRIX W = XMMatrixIdentity(); XMFLOAT3 p = transform.GetPosition(); - dist = wiMath::Distance(p, cam.Eye) * 0.05f; + dist = wi::math::Distance(p, cam.Eye) * 0.05f; - RAY ray = wiRenderer::GetPickRay((long)pointer.x, (long)pointer.y, canvas); + Ray ray = wi::renderer::GetPickRay((long)pointer.x, (long)pointer.y, canvas); XMVECTOR x, y, z, xy, xz, yz; @@ -267,12 +268,12 @@ void Translator::Update(const wiCanvas& canvas) } } - if (dragging || (state != TRANSLATOR_IDLE && wiInput::Press(wiInput::MOUSE_BUTTON_LEFT))) + if (dragging || (state != TRANSLATOR_IDLE && wi::input::Press(wi::input::MOUSE_BUTTON_LEFT))) { if (!dragging) { dragStarted = true; - dragDeltaMatrix = IDENTITYMATRIX; + dragDeltaMatrix = wi::math::IDENTITY_MATRIX; } XMVECTOR plane, planeNormal; @@ -313,12 +314,12 @@ void Translator::Update(const wiCanvas& canvas) } plane = XMPlaneFromPointNormal(pos, XMVector3Normalize(planeNormal)); - RAY ray = wiRenderer::GetPickRay((long)pointer.x, (long)pointer.y, canvas); + Ray ray = wi::renderer::GetPickRay((long)pointer.x, (long)pointer.y, canvas); XMVECTOR rayOrigin = XMLoadFloat3(&ray.origin); XMVECTOR rayDir = XMLoadFloat3(&ray.direction); XMVECTOR intersection = XMPlaneIntersectLine(plane, rayOrigin, rayOrigin + rayDir*cam.zFarP); - ray = wiRenderer::GetPickRay((long)prevPointer.x, (long)prevPointer.y, canvas); + ray = wi::renderer::GetPickRay((long)prevPointer.x, (long)prevPointer.y, canvas); rayOrigin = XMLoadFloat3(&ray.origin); rayDir = XMLoadFloat3(&ray.direction); XMVECTOR intersectionPrev = XMPlaneIntersectLine(plane, rayOrigin, rayOrigin + rayDir*cam.zFarP); @@ -327,22 +328,22 @@ void Translator::Update(const wiCanvas& canvas) if (state == TRANSLATOR_X) { XMVECTOR A = pos, B = pos + XMVectorSet(1, 0, 0, 0); - XMVECTOR P = wiMath::GetClosestPointToLine(A, B, intersection); - XMVECTOR PPrev = wiMath::GetClosestPointToLine(A, B, intersectionPrev); + XMVECTOR P = wi::math::GetClosestPointToLine(A, B, intersection); + XMVECTOR PPrev = wi::math::GetClosestPointToLine(A, B, intersectionPrev); deltaV = P - PPrev; } else if (state == TRANSLATOR_Y) { XMVECTOR A = pos, B = pos + XMVectorSet(0, 1, 0, 0); - XMVECTOR P = wiMath::GetClosestPointToLine(A, B, intersection); - XMVECTOR PPrev = wiMath::GetClosestPointToLine(A, B, intersectionPrev); + XMVECTOR P = wi::math::GetClosestPointToLine(A, B, intersection); + XMVECTOR PPrev = wi::math::GetClosestPointToLine(A, B, intersectionPrev); deltaV = P - PPrev; } else if (state == TRANSLATOR_Z) { XMVECTOR A = pos, B = pos + XMVectorSet(0, 0, 1, 0); - XMVECTOR P = wiMath::GetClosestPointToLine(A, B, intersection); - XMVECTOR PPrev = wiMath::GetClosestPointToLine(A, B, intersectionPrev); + XMVECTOR P = wi::math::GetClosestPointToLine(A, B, intersection); + XMVECTOR PPrev = wi::math::GetClosestPointToLine(A, B, intersectionPrev); deltaV = P - PPrev; } else @@ -389,7 +390,7 @@ void Translator::Update(const wiCanvas& canvas) dragging = true; } - if (!wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) + if (!wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) { if (dragging) { @@ -423,13 +424,13 @@ void Translator::Draw(const CameraComponent& camera, CommandList cmd) const if (!shaders_loaded) { shaders_loaded = true; - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { Translator_Internal::LoadShaders(); }); + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { Translator_Internal::LoadShaders(); }); Translator_Internal::LoadShaders(); } - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("Editor - Translator", cmd); @@ -523,7 +524,7 @@ void Translator::Draw(const CameraComponent& camera, CommandList cmd) const void Translator::PreTranslate() { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); // Find the center of all the entities that are selected: XMVECTOR centerV = XMVectorSet(0, 0, 0, 0); @@ -567,7 +568,7 @@ void Translator::PreTranslate() } void Translator::PostTranslate() { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); for (auto& x : selected) { diff --git a/Editor/Translator.h b/Editor/Translator.h index 76fea0515..45e23dbb8 100644 --- a/Editor/Translator.h +++ b/Editor/Translator.h @@ -7,23 +7,23 @@ class Translator { private: XMFLOAT4 prevPointer = XMFLOAT4(0, 0, 0, 0); - XMFLOAT4X4 dragDeltaMatrix = IDENTITYMATRIX; + XMFLOAT4X4 dragDeltaMatrix = wi::math::IDENTITY_MATRIX; bool dragging = false; bool dragStarted = false; bool dragEnded = false; public: void Create(); - void Update(const wiCanvas& canvas); - void Draw(const wiScene::CameraComponent& camera, wiGraphics::CommandList cmd) const; + void Update(const wi::Canvas& canvas); + void Draw(const wi::scene::CameraComponent& camera, wi::graphics::CommandList cmd) const; // Attach selection to translator temporarily void PreTranslate(); // Apply translator to selection void PostTranslate(); - wiScene::TransformComponent transform; - wi::vector selected; + wi::scene::TransformComponent transform; + wi::vector selected; bool enabled = false; diff --git a/Editor/WeatherWindow.cpp b/Editor/WeatherWindow.cpp index 8458b1e2c..bdd538f79 100644 --- a/Editor/WeatherWindow.cpp +++ b/Editor/WeatherWindow.cpp @@ -2,13 +2,13 @@ #include "WeatherWindow.h" #include "Editor.h" -using namespace wiECS; -using namespace wiScene; -using namespace wiGraphics; +using namespace wi::ecs; +using namespace wi::scene; +using namespace wi::graphics; void WeatherWindow::Create(EditorComponent* editor) { - wiWindow::Create("Weather Window"); + wi::gui::Window::Create("Weather Window"); SetSize(XMFLOAT2(660, 610)); float x = 180; @@ -20,7 +20,7 @@ void WeatherWindow::Create(EditorComponent* editor) heightFogCheckBox.Create("Height fog: "); heightFogCheckBox.SetSize(XMFLOAT2(hei, hei)); heightFogCheckBox.SetPos(XMFLOAT2(x + 100, y += step)); - heightFogCheckBox.OnClick([&](wiEventArgs args) { + heightFogCheckBox.OnClick([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.SetHeightFog(args.bValue); }); @@ -29,7 +29,7 @@ void WeatherWindow::Create(EditorComponent* editor) fogStartSlider.Create(0, 5000, 0, 100000, "Fog Start: "); fogStartSlider.SetSize(XMFLOAT2(100, hei)); fogStartSlider.SetPos(XMFLOAT2(x, y += step)); - fogStartSlider.OnSlide([&](wiEventArgs args) { + fogStartSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().fogStart = args.fValue; }); AddWidget(&fogStartSlider); @@ -37,7 +37,7 @@ void WeatherWindow::Create(EditorComponent* editor) fogEndSlider.Create(1, 5000, 1000, 10000, "Fog End: "); fogEndSlider.SetSize(XMFLOAT2(100, hei)); fogEndSlider.SetPos(XMFLOAT2(x, y += step)); - fogEndSlider.OnSlide([&](wiEventArgs args) { + fogEndSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().fogEnd = args.fValue; }); AddWidget(&fogEndSlider); @@ -45,7 +45,7 @@ void WeatherWindow::Create(EditorComponent* editor) fogHeightStartSlider.Create(-100, 100, 1, 10000, "Fog Height Start: "); fogHeightStartSlider.SetSize(XMFLOAT2(100, hei)); fogHeightStartSlider.SetPos(XMFLOAT2(x, y += step)); - fogHeightStartSlider.OnSlide([&](wiEventArgs args) { + fogHeightStartSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().fogHeightStart = args.fValue; }); AddWidget(&fogHeightStartSlider); @@ -53,7 +53,7 @@ void WeatherWindow::Create(EditorComponent* editor) fogHeightEndSlider.Create(-100, 100, 3, 10000, "Fog Height End: "); fogHeightEndSlider.SetSize(XMFLOAT2(100, hei)); fogHeightEndSlider.SetPos(XMFLOAT2(x, y += step)); - fogHeightEndSlider.OnSlide([&](wiEventArgs args) { + fogHeightEndSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().fogHeightEnd = args.fValue; }); AddWidget(&fogHeightEndSlider); @@ -61,7 +61,7 @@ void WeatherWindow::Create(EditorComponent* editor) fogHeightSkySlider.Create(0, 1, 0, 10000, "Fog Height Sky: "); fogHeightSkySlider.SetSize(XMFLOAT2(100, hei)); fogHeightSkySlider.SetPos(XMFLOAT2(x, y += step)); - fogHeightSkySlider.OnSlide([&](wiEventArgs args) { + fogHeightSkySlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().fogHeightSky = args.fValue; }); AddWidget(&fogHeightSkySlider); @@ -69,7 +69,7 @@ void WeatherWindow::Create(EditorComponent* editor) cloudinessSlider.Create(0, 1, 0.0f, 10000, "Cloudiness: "); cloudinessSlider.SetSize(XMFLOAT2(100, hei)); cloudinessSlider.SetPos(XMFLOAT2(x, y += step)); - cloudinessSlider.OnSlide([&](wiEventArgs args) { + cloudinessSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().cloudiness = args.fValue; }); AddWidget(&cloudinessSlider); @@ -77,7 +77,7 @@ void WeatherWindow::Create(EditorComponent* editor) cloudScaleSlider.Create(0.00005f, 0.001f, 0.0005f, 10000, "Cloud Scale: "); cloudScaleSlider.SetSize(XMFLOAT2(100, hei)); cloudScaleSlider.SetPos(XMFLOAT2(x, y += step)); - cloudScaleSlider.OnSlide([&](wiEventArgs args) { + cloudScaleSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().cloudScale = args.fValue; }); AddWidget(&cloudScaleSlider); @@ -85,7 +85,7 @@ void WeatherWindow::Create(EditorComponent* editor) cloudSpeedSlider.Create(0.001f, 0.2f, 0.1f, 10000, "Cloud Speed: "); cloudSpeedSlider.SetSize(XMFLOAT2(100, hei)); cloudSpeedSlider.SetPos(XMFLOAT2(x, y += step)); - cloudSpeedSlider.OnSlide([&](wiEventArgs args) { + cloudSpeedSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().cloudSpeed = args.fValue; }); AddWidget(&cloudSpeedSlider); @@ -93,7 +93,7 @@ void WeatherWindow::Create(EditorComponent* editor) windSpeedSlider.Create(0.0f, 4.0f, 1.0f, 10000, "Wind Speed: "); windSpeedSlider.SetSize(XMFLOAT2(100, hei)); windSpeedSlider.SetPos(XMFLOAT2(x, y += step)); - windSpeedSlider.OnSlide([&](wiEventArgs args) { + windSpeedSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().windSpeed = args.fValue; }); AddWidget(&windSpeedSlider); @@ -101,7 +101,7 @@ void WeatherWindow::Create(EditorComponent* editor) windMagnitudeSlider.Create(0.0f, 0.2f, 0.0f, 10000, "Wind Magnitude: "); windMagnitudeSlider.SetSize(XMFLOAT2(100, hei)); windMagnitudeSlider.SetPos(XMFLOAT2(x, y += step)); - windMagnitudeSlider.OnSlide([&](wiEventArgs args) { + windMagnitudeSlider.OnSlide([&](wi::gui::EventArgs args) { UpdateWind(); }); AddWidget(&windMagnitudeSlider); @@ -109,7 +109,7 @@ void WeatherWindow::Create(EditorComponent* editor) windDirectionSlider.Create(0, 1, 0, 10000, "Wind Direction: "); windDirectionSlider.SetSize(XMFLOAT2(100, hei)); windDirectionSlider.SetPos(XMFLOAT2(x, y += step)); - windDirectionSlider.OnSlide([&](wiEventArgs args) { + windDirectionSlider.OnSlide([&](wi::gui::EventArgs args) { UpdateWind(); }); AddWidget(&windDirectionSlider); @@ -117,7 +117,7 @@ void WeatherWindow::Create(EditorComponent* editor) windWaveSizeSlider.Create(0, 1, 0, 10000, "Wind Wave Size: "); windWaveSizeSlider.SetSize(XMFLOAT2(100, hei)); windWaveSizeSlider.SetPos(XMFLOAT2(x, y += step)); - windWaveSizeSlider.OnSlide([&](wiEventArgs args) { + windWaveSizeSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().windWaveSize = args.fValue; }); AddWidget(&windWaveSizeSlider); @@ -125,7 +125,7 @@ void WeatherWindow::Create(EditorComponent* editor) windRandomnessSlider.Create(0, 10, 5, 10000, "Wind Randomness: "); windRandomnessSlider.SetSize(XMFLOAT2(100, hei)); windRandomnessSlider.SetPos(XMFLOAT2(x, y += step)); - windRandomnessSlider.OnSlide([&](wiEventArgs args) { + windRandomnessSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().windRandomness = args.fValue; }); AddWidget(&windRandomnessSlider); @@ -133,7 +133,7 @@ void WeatherWindow::Create(EditorComponent* editor) skyExposureSlider.Create(0, 4, 1, 10000, "Sky Exposure: "); skyExposureSlider.SetSize(XMFLOAT2(100, hei)); skyExposureSlider.SetPos(XMFLOAT2(x, y += step)); - skyExposureSlider.OnSlide([&](wiEventArgs args) { + skyExposureSlider.OnSlide([&](wi::gui::EventArgs args) { GetWeather().skyExposure = args.fValue; }); AddWidget(&skyExposureSlider); @@ -142,7 +142,7 @@ void WeatherWindow::Create(EditorComponent* editor) simpleskyCheckBox.SetTooltip("Simple sky will simply blend horizon and zenith color from bottom to top."); simpleskyCheckBox.SetSize(XMFLOAT2(hei, hei)); simpleskyCheckBox.SetPos(XMFLOAT2(x, y += step)); - simpleskyCheckBox.OnClick([&](wiEventArgs args) { + simpleskyCheckBox.OnClick([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.SetSimpleSky(args.bValue); if (args.bValue) @@ -156,7 +156,7 @@ void WeatherWindow::Create(EditorComponent* editor) realisticskyCheckBox.SetTooltip("Physically based sky rendering model."); realisticskyCheckBox.SetSize(XMFLOAT2(hei, hei)); realisticskyCheckBox.SetPos(XMFLOAT2(x + 120, y)); - realisticskyCheckBox.OnClick([&](wiEventArgs args) { + realisticskyCheckBox.OnClick([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.SetRealisticSky(args.bValue); if (args.bValue) @@ -170,27 +170,27 @@ void WeatherWindow::Create(EditorComponent* editor) skyButton.SetTooltip("Load a skybox cubemap texture..."); skyButton.SetSize(XMFLOAT2(240, hei)); skyButton.SetPos(XMFLOAT2(x-100, y += step)); - skyButton.OnClick([=](wiEventArgs args) { + skyButton.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); - if (weather.skyMap == nullptr) + if (!weather.skyMap.IsValid()) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Cubemap texture"; params.extensions.push_back("dds"); - wiHelper::FileDialog(params, [=](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + wi::helper::FileDialog(params, [=](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { auto& weather = GetWeather(); weather.skyMapName = fileName; - weather.skyMap = wiResourceManager::Load(fileName, wiResourceManager::IMPORT_RETAIN_FILEDATA); - skyButton.SetText(wiHelper::GetFileNameFromPath(fileName)); + weather.skyMap = wi::resourcemanager::Load(fileName, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); + skyButton.SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } else { - weather.skyMap.reset(); + weather.skyMap = {}; weather.skyMapName.clear(); skyButton.SetText("Load Sky"); } @@ -205,27 +205,27 @@ void WeatherWindow::Create(EditorComponent* editor) colorgradingButton.SetTooltip("Load a color grading lookup texture. It must be a 256x16 RGBA image!"); colorgradingButton.SetSize(XMFLOAT2(240, hei)); colorgradingButton.SetPos(XMFLOAT2(x - 100, y += step)); - colorgradingButton.OnClick([=](wiEventArgs args) { + colorgradingButton.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); - if (weather.colorGradingMap == nullptr) + if (!weather.colorGradingMap.IsValid()) { - wiHelper::FileDialogParams params; - params.type = wiHelper::FileDialogParams::OPEN; + wi::helper::FileDialogParams params; + params.type = wi::helper::FileDialogParams::OPEN; params.description = "Texture"; - params.extensions = wiResourceManager::GetSupportedImageExtensions(); - wiHelper::FileDialog(params, [=](std::string fileName) { - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + params.extensions = wi::resourcemanager::GetSupportedImageExtensions(); + wi::helper::FileDialog(params, [=](std::string fileName) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { auto& weather = GetWeather(); weather.colorGradingMapName = fileName; - weather.colorGradingMap = wiResourceManager::Load(fileName, wiResourceManager::IMPORT_COLORGRADINGLUT | wiResourceManager::IMPORT_RETAIN_FILEDATA); - colorgradingButton.SetText(wiHelper::GetFileNameFromPath(fileName)); + weather.colorGradingMap = wi::resourcemanager::Load(fileName, wi::resourcemanager::Flags::IMPORT_COLORGRADINGLUT | wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); + colorgradingButton.SetText(wi::helper::GetFileNameFromPath(fileName)); }); }); } else { - weather.colorGradingMap.reset(); + weather.colorGradingMap = {}; weather.colorGradingMapName.clear(); colorgradingButton.SetText("Load Color Grading LUT"); } @@ -239,7 +239,7 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_enabledCheckBox.Create("Ocean simulation enabled: "); ocean_enabledCheckBox.SetSize(XMFLOAT2(hei, hei)); ocean_enabledCheckBox.SetPos(XMFLOAT2(x + 100, y += step)); - ocean_enabledCheckBox.OnClick([&](wiEventArgs args) { + ocean_enabledCheckBox.OnClick([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.SetOceanEnabled(args.bValue); if (!weather.IsOceanEnabled()) @@ -253,9 +253,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_patchSizeSlider.Create(1, 1000, 1000, 100000, "Patch size: "); ocean_patchSizeSlider.SetSize(XMFLOAT2(100, hei)); ocean_patchSizeSlider.SetPos(XMFLOAT2(x, y += step)); - ocean_patchSizeSlider.SetValue(wiScene::GetScene().weather.oceanParameters.patch_length); + ocean_patchSizeSlider.SetValue(wi::scene::GetScene().weather.oceanParameters.patch_length); ocean_patchSizeSlider.SetTooltip("Adjust water tiling patch size"); - ocean_patchSizeSlider.OnSlide([&](wiEventArgs args) { + ocean_patchSizeSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.patch_length = args.fValue; GetScene().ocean = {}; @@ -265,9 +265,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_waveAmplitudeSlider.Create(0, 1000, 1000, 100000, "Wave amplitude: "); ocean_waveAmplitudeSlider.SetSize(XMFLOAT2(100, hei)); ocean_waveAmplitudeSlider.SetPos(XMFLOAT2(x, y += step)); - ocean_waveAmplitudeSlider.SetValue(wiScene::GetScene().weather.oceanParameters.wave_amplitude); + ocean_waveAmplitudeSlider.SetValue(wi::scene::GetScene().weather.oceanParameters.wave_amplitude); ocean_waveAmplitudeSlider.SetTooltip("Adjust wave size"); - ocean_waveAmplitudeSlider.OnSlide([&](wiEventArgs args) { + ocean_waveAmplitudeSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.wave_amplitude = args.fValue; GetScene().ocean = {}; @@ -277,9 +277,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_choppyScaleSlider.Create(0, 10, 1000, 100000, "Choppiness: "); ocean_choppyScaleSlider.SetSize(XMFLOAT2(100, hei)); ocean_choppyScaleSlider.SetPos(XMFLOAT2(x, y += step)); - ocean_choppyScaleSlider.SetValue(wiScene::GetScene().weather.oceanParameters.choppy_scale); + ocean_choppyScaleSlider.SetValue(wi::scene::GetScene().weather.oceanParameters.choppy_scale); ocean_choppyScaleSlider.SetTooltip("Adjust wave choppiness"); - ocean_choppyScaleSlider.OnSlide([&](wiEventArgs args) { + ocean_choppyScaleSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.choppy_scale = args.fValue; }); @@ -288,9 +288,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_windDependencySlider.Create(0, 1, 1000, 100000, "Wind dependency: "); ocean_windDependencySlider.SetSize(XMFLOAT2(100, hei)); ocean_windDependencySlider.SetPos(XMFLOAT2(x, y += step)); - ocean_windDependencySlider.SetValue(wiScene::GetScene().weather.oceanParameters.wind_dependency); + ocean_windDependencySlider.SetValue(wi::scene::GetScene().weather.oceanParameters.wind_dependency); ocean_windDependencySlider.SetTooltip("Adjust wind contribution"); - ocean_windDependencySlider.OnSlide([&](wiEventArgs args) { + ocean_windDependencySlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.wind_dependency = args.fValue; GetScene().ocean = {}; @@ -300,9 +300,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_timeScaleSlider.Create(0, 4, 1000, 100000, "Time scale: "); ocean_timeScaleSlider.SetSize(XMFLOAT2(100, hei)); ocean_timeScaleSlider.SetPos(XMFLOAT2(x, y += step)); - ocean_timeScaleSlider.SetValue(wiScene::GetScene().weather.oceanParameters.time_scale); + ocean_timeScaleSlider.SetValue(wi::scene::GetScene().weather.oceanParameters.time_scale); ocean_timeScaleSlider.SetTooltip("Adjust simulation speed"); - ocean_timeScaleSlider.OnSlide([&](wiEventArgs args) { + ocean_timeScaleSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.time_scale = args.fValue; }); @@ -313,7 +313,7 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_heightSlider.SetPos(XMFLOAT2(x, y += step)); ocean_heightSlider.SetValue(0); ocean_heightSlider.SetTooltip("Adjust water level"); - ocean_heightSlider.OnSlide([&](wiEventArgs args) { + ocean_heightSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.waterHeight = args.fValue; }); @@ -324,7 +324,7 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_detailSlider.SetPos(XMFLOAT2(x, y += step)); ocean_detailSlider.SetValue(4); ocean_detailSlider.SetTooltip("Adjust surface tessellation resolution. High values can decrease performance."); - ocean_detailSlider.OnSlide([&](wiEventArgs args) { + ocean_detailSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.surfaceDetail = (uint32_t)args.iValue; }); @@ -335,7 +335,7 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_toleranceSlider.SetPos(XMFLOAT2(x, y += step)); ocean_toleranceSlider.SetValue(2); ocean_toleranceSlider.SetTooltip("Big waves can introduce glitches on screen borders, this can fix that but surface detail will decrease."); - ocean_toleranceSlider.OnSlide([&](wiEventArgs args) { + ocean_toleranceSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.oceanParameters.surfaceDisplacementTolerance = args.fValue; }); @@ -346,9 +346,9 @@ void WeatherWindow::Create(EditorComponent* editor) ocean_resetButton.SetTooltip("Reset ocean to default values."); ocean_resetButton.SetSize(XMFLOAT2(240, hei)); ocean_resetButton.SetPos(XMFLOAT2(x - 100, y += step)); - ocean_resetButton.OnClick([=](wiEventArgs args) { + ocean_resetButton.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); - weather.oceanParameters = wiOcean::OceanParameters(); + weather.oceanParameters = wi::Ocean::OceanParameters(); GetScene().ocean = {}; }); AddWidget(&ocean_resetButton); @@ -382,7 +382,7 @@ void WeatherWindow::Create(EditorComponent* editor) colorPicker.SetPos(XMFLOAT2(x, y += step)); colorPicker.SetVisible(false); colorPicker.SetEnabled(true); - colorPicker.OnColorChanged([&](wiEventArgs args) { + colorPicker.OnColorChanged([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); switch (colorComboBox.GetSelected()) { @@ -413,7 +413,7 @@ void WeatherWindow::Create(EditorComponent* editor) volumetricCloudsCheckBox.SetTooltip("Enable volumetric cloud rendering, which is separate from the simple cloud parameters."); volumetricCloudsCheckBox.SetSize(XMFLOAT2(hei, hei)); volumetricCloudsCheckBox.SetPos(XMFLOAT2(x + 280, y += step)); - volumetricCloudsCheckBox.OnClick([&](wiEventArgs args) { + volumetricCloudsCheckBox.OnClick([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.SetVolumetricClouds(args.bValue); }); @@ -422,7 +422,7 @@ void WeatherWindow::Create(EditorComponent* editor) coverageAmountSlider.Create(0, 10, 0, 1000, "Coverage amount: "); coverageAmountSlider.SetSize(XMFLOAT2(100, hei)); coverageAmountSlider.SetPos(XMFLOAT2(x + 150, y += step)); - coverageAmountSlider.OnSlide([&](wiEventArgs args) { + coverageAmountSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.volumetricCloudParameters.CoverageAmount = args.fValue; }); @@ -431,7 +431,7 @@ void WeatherWindow::Create(EditorComponent* editor) coverageMinimumSlider.Create(1, 2, 1, 1000, "Coverage minimmum: "); coverageMinimumSlider.SetSize(XMFLOAT2(100, hei)); coverageMinimumSlider.SetPos(XMFLOAT2(x + 150, y += step)); - coverageMinimumSlider.OnSlide([&](wiEventArgs args) { + coverageMinimumSlider.OnSlide([&](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.volumetricCloudParameters.CoverageMinimum = args.fValue; }); @@ -442,9 +442,9 @@ void WeatherWindow::Create(EditorComponent* editor) preset0Button.SetTooltip("Apply this weather preset to the world."); preset0Button.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); preset0Button.SetPos(XMFLOAT2(x, y += step)); - preset0Button.OnClick([=](wiEventArgs args) { + preset0Button.OnClick([=](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); scene.weathers.Clear(); scene.weather = WeatherComponent(); @@ -457,7 +457,7 @@ void WeatherWindow::Create(EditorComponent* editor) preset1Button.SetTooltip("Apply this weather preset to the world."); preset1Button.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); preset1Button.SetPos(XMFLOAT2(x, y += step)); - preset1Button.OnClick([=](wiEventArgs args) { + preset1Button.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.ambient = XMFLOAT3(33.0f / 255.0f, 47.0f / 255.0f, 127.0f / 255.0f); @@ -477,7 +477,7 @@ void WeatherWindow::Create(EditorComponent* editor) preset2Button.SetTooltip("Apply this weather preset to the world."); preset2Button.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); preset2Button.SetPos(XMFLOAT2(x, y += step)); - preset2Button.OnClick([=](wiEventArgs args) { + preset2Button.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.ambient = XMFLOAT3(86.0f / 255.0f, 29.0f / 255.0f, 29.0f / 255.0f); @@ -497,7 +497,7 @@ void WeatherWindow::Create(EditorComponent* editor) preset3Button.SetTooltip("Apply this weather preset to the world."); preset3Button.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); preset3Button.SetPos(XMFLOAT2(x, y += step)); - preset3Button.OnClick([=](wiEventArgs args) { + preset3Button.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.ambient = XMFLOAT3(0.1f, 0.1f, 0.1f); @@ -517,7 +517,7 @@ void WeatherWindow::Create(EditorComponent* editor) preset4Button.SetTooltip("Apply this weather preset to the world."); preset4Button.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); preset4Button.SetPos(XMFLOAT2(x, y += step)); - preset4Button.OnClick([=](wiEventArgs args) { + preset4Button.OnClick([=](wi::gui::EventArgs args) { auto& weather = GetWeather(); weather.ambient = XMFLOAT3(12.0f / 255.0f, 21.0f / 255.0f, 77.0f / 255.0f); @@ -538,9 +538,9 @@ void WeatherWindow::Create(EditorComponent* editor) eliminateCoarseCascadesButton.SetTooltip("Eliminate the coarse cascade mask for every object in the scene."); eliminateCoarseCascadesButton.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); eliminateCoarseCascadesButton.SetPos(XMFLOAT2(x, y += step * 2)); - eliminateCoarseCascadesButton.OnClick([=](wiEventArgs args) { + eliminateCoarseCascadesButton.OnClick([=](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); for (size_t i = 0; i < scene.objects.GetCount(); ++i) { scene.objects[i].cascadeMask = 1; @@ -554,11 +554,11 @@ void WeatherWindow::Create(EditorComponent* editor) ktxConvButton.SetTooltip("All material textures in the scene will be cinverted to KTX2 format.\nTHIS MIGHT TAKE LONG, SO GET YOURSELF A COFFEE OR TEA!"); ktxConvButton.SetSize(XMFLOAT2(colorPicker.GetScale().x, hei)); ktxConvButton.SetPos(XMFLOAT2(x, y += step)); - ktxConvButton.OnClick([=](wiEventArgs args) { + ktxConvButton.OnClick([=](wi::gui::EventArgs args) { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); - wi::unordered_map> conv; + wi::unordered_map conv; for (uint32_t i = 0; i < scene.materials.GetCount(); ++i) { MaterialComponent& material = scene.materials[i]; @@ -566,29 +566,31 @@ void WeatherWindow::Create(EditorComponent* editor) { if (x.GetGPUResource() == nullptr) continue; - if (wiHelper::GetExtensionFromFileName(x.name).compare("KTX2")) + if (wi::helper::GetExtensionFromFileName(x.name).compare("KTX2")) { - x.name = wiHelper::ReplaceExtension(x.name, "KTX2"); + x.name = wi::helper::ReplaceExtension(x.name, "KTX2"); conv[x.name] = x.resource; } } } - wiJobSystem::context ctx; + wi::jobsystem::context ctx; for (auto& x : conv) { - if (wiHelper::saveTextureToMemory(x.second->texture, x.second->filedata)) + std::vector filedata; + if (wi::helper::saveTextureToMemory(x.second.GetTexture(), filedata)) { - wiJobSystem::Execute(ctx, [&](wiJobArgs args) { + x.second.SetFileData(std::move(filedata)); + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { wi::vector filedata_ktx2; - if (wiHelper::saveTextureToMemoryFile(x.second->filedata, x.second->texture.desc, "KTX2", filedata_ktx2)) + if (wi::helper::saveTextureToMemoryFile(x.second.GetFileData(), x.second.GetTexture().desc, "KTX2", filedata_ktx2)) { - x.second = wiResourceManager::Load(x.first, wiResourceManager::IMPORT_RETAIN_FILEDATA, filedata_ktx2.data(), filedata_ktx2.size()); + x.second = wi::resourcemanager::Load(x.first, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA, filedata_ktx2.data(), filedata_ktx2.size()); } }); } } - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); for (uint32_t i = 0; i < scene.materials.GetCount(); ++i) { @@ -608,19 +610,19 @@ void WeatherWindow::Create(EditorComponent* editor) void WeatherWindow::Update() { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); if (scene.weathers.GetCount() > 0) { auto& weather = scene.weathers[0]; if (!weather.skyMapName.empty()) { - skyButton.SetText(wiHelper::GetFileNameFromPath(weather.skyMapName)); + skyButton.SetText(wi::helper::GetFileNameFromPath(weather.skyMapName)); } if (!weather.colorGradingMapName.empty()) { - colorgradingButton.SetText(wiHelper::GetFileNameFromPath(weather.colorGradingMapName)); + colorgradingButton.SetText(wi::helper::GetFileNameFromPath(weather.colorGradingMapName)); } heightFogCheckBox.SetCheck(weather.IsHeightFog()); @@ -642,19 +644,19 @@ void WeatherWindow::Update() { default: case 0: - colorPicker.SetPickColor(wiColor::fromFloat3(weather.ambient)); + colorPicker.SetPickColor(wi::Color::fromFloat3(weather.ambient)); break; case 1: - colorPicker.SetPickColor(wiColor::fromFloat3(weather.horizon)); + colorPicker.SetPickColor(wi::Color::fromFloat3(weather.horizon)); break; case 2: - colorPicker.SetPickColor(wiColor::fromFloat3(weather.zenith)); + colorPicker.SetPickColor(wi::Color::fromFloat3(weather.zenith)); break; case 3: - colorPicker.SetPickColor(wiColor::fromFloat4(weather.oceanParameters.waterColor)); + colorPicker.SetPickColor(wi::Color::fromFloat4(weather.oceanParameters.waterColor)); break; case 4: - colorPicker.SetPickColor(wiColor::fromFloat3(weather.volumetricCloudParameters.Albedo)); + colorPicker.SetPickColor(wi::Color::fromFloat3(weather.volumetricCloudParameters.Albedo)); break; } @@ -679,7 +681,7 @@ void WeatherWindow::Update() WeatherComponent& WeatherWindow::GetWeather() const { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); if (scene.weathers.GetCount() == 0) { scene.weathers.Create(CreateEntity()); @@ -689,7 +691,7 @@ WeatherComponent& WeatherWindow::GetWeather() const void WeatherWindow::InvalidateProbes() const { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); // Also, we invalidate all environment probes to reflect the sky changes. for (size_t i = 0; i < scene.probes.GetCount(); ++i) diff --git a/Editor/WeatherWindow.h b/Editor/WeatherWindow.h index 3fc3a6e55..42b31c39a 100644 --- a/Editor/WeatherWindow.h +++ b/Editor/WeatherWindow.h @@ -3,7 +3,7 @@ class EditorComponent; -class WeatherWindow : public wiWindow +class WeatherWindow : public wi::gui::Window { void UpdateWind(); public: @@ -11,55 +11,55 @@ public: void Update(); - wiScene::WeatherComponent& GetWeather() const; + wi::scene::WeatherComponent& GetWeather() const; void InvalidateProbes() const; - wiCheckBox heightFogCheckBox; - wiSlider fogStartSlider; - wiSlider fogEndSlider; - wiSlider fogHeightStartSlider; - wiSlider fogHeightEndSlider; - wiSlider fogHeightSkySlider; - wiSlider cloudinessSlider; - wiSlider cloudScaleSlider; - wiSlider cloudSpeedSlider; - wiSlider windSpeedSlider; - wiSlider windMagnitudeSlider; - wiSlider windDirectionSlider; - wiSlider windWaveSizeSlider; - wiSlider windRandomnessSlider; - wiSlider skyExposureSlider; - wiCheckBox simpleskyCheckBox; - wiCheckBox realisticskyCheckBox; - wiButton skyButton; - wiButton colorgradingButton; + wi::gui::CheckBox heightFogCheckBox; + wi::gui::Slider fogStartSlider; + wi::gui::Slider fogEndSlider; + wi::gui::Slider fogHeightStartSlider; + wi::gui::Slider fogHeightEndSlider; + wi::gui::Slider fogHeightSkySlider; + wi::gui::Slider cloudinessSlider; + wi::gui::Slider cloudScaleSlider; + wi::gui::Slider cloudSpeedSlider; + wi::gui::Slider windSpeedSlider; + wi::gui::Slider windMagnitudeSlider; + wi::gui::Slider windDirectionSlider; + wi::gui::Slider windWaveSizeSlider; + wi::gui::Slider windRandomnessSlider; + wi::gui::Slider skyExposureSlider; + wi::gui::CheckBox simpleskyCheckBox; + wi::gui::CheckBox realisticskyCheckBox; + wi::gui::Button skyButton; + wi::gui::Button colorgradingButton; // ocean params: - wiCheckBox ocean_enabledCheckBox; - wiSlider ocean_patchSizeSlider; - wiSlider ocean_waveAmplitudeSlider; - wiSlider ocean_choppyScaleSlider; - wiSlider ocean_windDependencySlider; - wiSlider ocean_timeScaleSlider; - wiSlider ocean_heightSlider; - wiSlider ocean_detailSlider; - wiSlider ocean_toleranceSlider; - wiButton ocean_resetButton; + wi::gui::CheckBox ocean_enabledCheckBox; + wi::gui::Slider ocean_patchSizeSlider; + wi::gui::Slider ocean_waveAmplitudeSlider; + wi::gui::Slider ocean_choppyScaleSlider; + wi::gui::Slider ocean_windDependencySlider; + wi::gui::Slider ocean_timeScaleSlider; + wi::gui::Slider ocean_heightSlider; + wi::gui::Slider ocean_detailSlider; + wi::gui::Slider ocean_toleranceSlider; + wi::gui::Button ocean_resetButton; - wiComboBox colorComboBox; - wiColorPicker colorPicker; + wi::gui::ComboBox colorComboBox; + wi::gui::ColorPicker colorPicker; // volumetric clouds: - wiCheckBox volumetricCloudsCheckBox; - wiSlider coverageAmountSlider; - wiSlider coverageMinimumSlider; + wi::gui::CheckBox volumetricCloudsCheckBox; + wi::gui::Slider coverageAmountSlider; + wi::gui::Slider coverageMinimumSlider; - wiButton preset0Button; - wiButton preset1Button; - wiButton preset2Button; - wiButton preset3Button; - wiButton preset4Button; - wiButton eliminateCoarseCascadesButton; - wiButton ktxConvButton; + wi::gui::Button preset0Button; + wi::gui::Button preset1Button; + wi::gui::Button preset2Button; + wi::gui::Button preset3Button; + wi::gui::Button preset4Button; + wi::gui::Button eliminateCoarseCascadesButton; + wi::gui::Button ktxConvButton; }; diff --git a/Editor/main_SDL2.cpp b/Editor/main_SDL2.cpp index 09df13dec..22b0f6d29 100644 --- a/Editor/main_SDL2.cpp +++ b/Editor/main_SDL2.cpp @@ -111,20 +111,20 @@ int sdl_loop(Editor &editor) break; case SDL_WINDOWEVENT_FOCUS_GAINED: editor.is_window_active = true; - if (wiShaderCompiler::GetRegisteredShaderCount() > 0) + if (wi::shadercompiler::GetRegisteredShaderCount() > 0) { std::thread([] { - wiBackLog::post("[Shader check] Started checking " + std::to_string(wiShaderCompiler::GetRegisteredShaderCount()) + " registered shaders for changes..."); - if (wiShaderCompiler::CheckRegisteredShadersOutdated()) + wi::backlog::post("[Shader check] Started checking " + std::to_string(wi::shadercompiler::GetRegisteredShaderCount()) + " registered shaders for changes..."); + if (wi::shadercompiler::CheckRegisteredShadersOutdated()) { - wiBackLog::post("[Shader check] Changes detected, initiating reload..."); - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [](uint64_t userdata) { - wiRenderer::ReloadShaders(); + wi::backlog::post("[Shader check] Changes detected, initiating reload..."); + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [](uint64_t userdata) { + wi::renderer::ReloadShaders(); }); } else { - wiBackLog::post("[Shader check] All up to date"); + wi::backlog::post("[Shader check] All up to date"); } }).detach(); } @@ -146,15 +146,15 @@ int sdl_loop(Editor &editor) { if(c == 127) { - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); } else if (c != -1) { - if (wiBackLog::isActive()) - wiBackLog::input(c); - wiTextInputField::AddInput(c); + if (wi::backlog::isActive()) + wi::backlog::input(c); + wi::gui::TextInputField::AddInput(c); } } cbuf = c; @@ -193,7 +193,7 @@ int main(int argc, char *argv[]) { Editor editor; - wiStartupArguments::Parse(argc, argv); + wi::arguments::Parse(argc, argv); sdl2::sdlsystem_ptr_t system = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING | SDL_INIT_EVENTS); if (!system) { diff --git a/Editor/main_Windows.cpp b/Editor/main_Windows.cpp index 44bc47cbb..a99ef48d4 100644 --- a/Editor/main_Windows.cpp +++ b/Editor/main_Windows.cpp @@ -39,7 +39,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, BOOL dpi_success = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); assert(dpi_success); - wiStartupArguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... + wi::arguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); @@ -211,7 +211,7 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { case PRINTSCREEN: { - wiHelper::screenshot(editor.swapChain); + wi::helper::screenshot(editor.swapChain); } break; default: @@ -222,46 +222,46 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) switch (wParam) { case VK_BACK: - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); break; case VK_RETURN: break; default: { const char c = (const char)(TCHAR)wParam; - if (wiBackLog::isActive()) + if (wi::backlog::isActive()) { - wiBackLog::input(c); + wi::backlog::input(c); } - wiTextInputField::AddInput(c); + wi::gui::TextInputField::AddInput(c); } break; } break; case WM_INPUT: - wiRawInput::ParseMessage((void*)lParam); + wi::input::rawinput::ParseMessage((void*)lParam); break; case WM_KILLFOCUS: editor.is_window_active = false; break; case WM_SETFOCUS: editor.is_window_active = true; - if (wiShaderCompiler::GetRegisteredShaderCount() > 0) + if (wi::shadercompiler::GetRegisteredShaderCount() > 0) { std::thread([] { - wiBackLog::post("[Shader check] Started checking " + std::to_string(wiShaderCompiler::GetRegisteredShaderCount()) + " registered shaders for changes..."); - if (wiShaderCompiler::CheckRegisteredShadersOutdated()) + wi::backlog::post("[Shader check] Started checking " + std::to_string(wi::shadercompiler::GetRegisteredShaderCount()) + " registered shaders for changes..."); + if (wi::shadercompiler::CheckRegisteredShadersOutdated()) { - wiBackLog::post("[Shader check] Changes detected, initiating reload..."); - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [](uint64_t userdata) { - wiRenderer::ReloadShaders(); + wi::backlog::post("[Shader check] Changes detected, initiating reload..."); + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [](uint64_t userdata) { + wi::renderer::ReloadShaders(); }); } else { - wiBackLog::post("[Shader check] All up to date"); + wi::backlog::post("[Shader check] All up to date"); } }).detach(); } diff --git a/Example_ImGui/Example_ImGui.cpp b/Example_ImGui/Example_ImGui.cpp index 0b62e37a0..180ffd142 100644 --- a/Example_ImGui/Example_ImGui.cpp +++ b/Example_ImGui/Example_ImGui.cpp @@ -13,9 +13,9 @@ #include #include -using namespace wiECS; -using namespace wiGraphics; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; +using namespace wi::graphics; Shader imguiVS; Shader imguiPS; @@ -57,7 +57,7 @@ bool ImGui_Impl_CreateDeviceObjects() textureData.row_pitch = width * GetFormatStride(textureDesc.format); textureData.slice_pitch = textureData.row_pitch * height; - wiGraphics::GetDevice()->CreateTexture(&textureDesc, &textureData, &fontTexture); + wi::graphics::GetDevice()->CreateTexture(&textureDesc, &textureData, &fontTexture); // Store our identifier io.Fonts->SetTexID((ImTextureID)&fontTexture); @@ -74,11 +74,11 @@ bool ImGui_Impl_CreateDeviceObjects() desc.vs = &imguiVS; desc.ps = &imguiPS; desc.il = &imguiInputLayout; - desc.dss = wiRenderer::GetDepthStencilState(DSSTYPE_DEPTHREAD); - desc.rs = wiRenderer::GetRasterizerState(RSTYPE_DOUBLESIDED); - desc.bs = wiRenderer::GetBlendState(BSTYPE_TRANSPARENT); + desc.dss = wi::renderer::GetDepthStencilState(wi::enums::DSSTYPE_DEPTHREAD); + desc.rs = wi::renderer::GetRasterizerState(wi::enums::RSTYPE_DOUBLESIDED); + desc.bs = wi::renderer::GetBlendState(wi::enums::BSTYPE_TRANSPARENT); desc.pt = PrimitiveTopology::TRIANGLELIST; - wiGraphics::GetDevice()->CreatePipelineState(&desc, &imguiPSO); + wi::graphics::GetDevice()->CreatePipelineState(&desc, &imguiPSO); return true; } @@ -99,15 +99,15 @@ void Example_ImGui::Initialize() { // Compile shaders { - wiShaderCompiler::Initialize(); + wi::shadercompiler::Initialize(); - auto shaderPath = wiRenderer::GetShaderSourcePath(); - wiRenderer::SetShaderSourcePath(wiHelper::GetCurrentPath() + "/"); + auto shaderPath = wi::renderer::GetShaderSourcePath(); + wi::renderer::SetShaderSourcePath(wi::helper::GetCurrentPath() + "/"); - wiRenderer::LoadShader(ShaderStage::VS, imguiVS, "ImGuiVS.cso"); - wiRenderer::LoadShader(ShaderStage::PS, imguiPS, "ImGuiPS.cso"); + wi::renderer::LoadShader(ShaderStage::VS, imguiVS, "ImGuiVS.cso"); + wi::renderer::LoadShader(ShaderStage::PS, imguiPS, "ImGuiPS.cso"); - wiRenderer::SetShaderSourcePath(shaderPath); + wi::renderer::SetShaderSourcePath(shaderPath); } // Setup Dear ImGui context @@ -135,7 +135,7 @@ void Example_ImGui::Initialize() io.BackendRendererName = "Wicked"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. - MainComponent::Initialize(); + Application::Initialize(); infoDisplay.active = true; infoDisplay.watermark = true; @@ -149,9 +149,9 @@ void Example_ImGui::Initialize() ActivatePath(&renderer); } -void Example_ImGui::Compose(wiGraphics::CommandList cmd) +void Example_ImGui::Compose(wi::graphics::CommandList cmd) { - MainComponent::Compose(cmd); + Application::Compose(cmd); // Rendering ImGui::Render(); @@ -171,7 +171,7 @@ void Example_ImGui::Compose(wiGraphics::CommandList cmd) auto* bd = ImGui_Impl_GetBackendData(); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); // Get memory for vertex and index buffers const uint64_t vbSize = sizeof(ImDrawVert) * drawData->TotalVtxCount; @@ -321,30 +321,30 @@ void Example_ImGuiRenderer::Load() label.Create("Label1"); label.SetText("Wicked Engine ImGui integration"); - label.font.params.h_align = WIFALIGN_CENTER; + label.font.params.h_align = wi::font::WIFALIGN_CENTER; label.SetSize(XMFLOAT2(240, 20)); GetGUI().AddWidget(&label); // Reset all state that tests might have modified: - wiEvent::SetVSync(true); - wiRenderer::SetToDrawGridHelper(false); - wiRenderer::SetTemporalAAEnabled(true); - wiRenderer::ClearWorld(wiScene::GetScene()); - wiScene::GetScene().weather = WeatherComponent(); + wi::eventhandler::SetVSync(true); + wi::renderer::SetToDrawGridHelper(false); + wi::renderer::SetTemporalAAEnabled(true); + wi::renderer::ClearWorld(wi::scene::GetScene()); + wi::scene::GetScene().weather = WeatherComponent(); this->ClearSprites(); this->ClearFonts(); - if (wiLua::GetLuaState() != nullptr) { - wiLua::KillProcesses(); + if (wi::lua::GetLuaState() != nullptr) { + wi::lua::KillProcesses(); } // Reset camera position: TransformComponent transform; transform.Translate(XMFLOAT3(0, 2.f, -4.5f)); transform.UpdateTransform(); - wiScene::GetCamera().TransformCamera(transform); + wi::scene::GetCamera().TransformCamera(transform); // Load model. - wiScene::LoadModel("../Content/models/teapot.wiscene"); + wi::scene::LoadModel("../Content/models/teapot.wiscene"); RenderPath3D::Load(); } @@ -408,23 +408,23 @@ void Example_ImGuiRenderer::Update(float dt) ImGui::End(); } - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); // teapot_material Base Base_mesh Top Top_mesh editorLight - wiECS::Entity e_teapot_base = scene.Entity_FindByName("Base"); - wiECS::Entity e_teapot_top = scene.Entity_FindByName("Top"); - assert(e_teapot_base != wiECS::INVALID_ENTITY); - assert(e_teapot_top != wiECS::INVALID_ENTITY); + wi::ecs::Entity e_teapot_base = scene.Entity_FindByName("Base"); + wi::ecs::Entity e_teapot_top = scene.Entity_FindByName("Top"); + assert(e_teapot_base != wi::ecs::INVALID_ENTITY); + assert(e_teapot_top != wi::ecs::INVALID_ENTITY); TransformComponent* transform_base = scene.transforms.GetComponent(e_teapot_base); TransformComponent* transform_top = scene.transforms.GetComponent(e_teapot_top); assert(transform_base != nullptr); assert(transform_top != nullptr); float rotation = dt; - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LEFT)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LEFT)) { transform_base->Rotate(XMVectorSet(0, rotation, 0, 1)); transform_top->Rotate(XMVectorSet(0, rotation, 0, 1)); } - else if (wiInput::Down(wiInput::KEYBOARD_BUTTON_RIGHT)) + else if (wi::input::Down(wi::input::KEYBOARD_BUTTON_RIGHT)) { transform_base->Rotate(XMVectorSet(0, -rotation, 0, 1)); transform_top->Rotate(XMVectorSet(0, -rotation, 0, 1)); diff --git a/Example_ImGui/Example_ImGui.h b/Example_ImGui/Example_ImGui.h index ac92da8bc..4a7ec26f1 100644 --- a/Example_ImGui/Example_ImGui.h +++ b/Example_ImGui/Example_ImGui.h @@ -2,9 +2,9 @@ #include "WickedEngine.h" -class Example_ImGuiRenderer : public RenderPath3D +class Example_ImGuiRenderer : public wi::RenderPath3D { - wiLabel label; + wi::gui::Label label; public: void Load() override; void Update(float dt) override; @@ -12,13 +12,13 @@ public: void Render() const override; }; -class Example_ImGui : public MainComponent +class Example_ImGui : public wi::Application { Example_ImGuiRenderer renderer; public: ~Example_ImGui() override; void Initialize() override; - void Compose(wiGraphics::CommandList cmd) override; + void Compose(wi::graphics::CommandList cmd) override; }; diff --git a/Example_ImGui/main_SDL2.cpp b/Example_ImGui/main_SDL2.cpp index b859d9928..b7f4c621a 100644 --- a/Example_ImGui/main_SDL2.cpp +++ b/Example_ImGui/main_SDL2.cpp @@ -50,7 +50,7 @@ int main(int argc, char *argv[]) Example_ImGui exampleImGui; // TODO: Place code here. - wiStartupArguments::Parse(argc, argv); + wi::arguments::Parse(argc, argv); sdl2::sdlsystem_ptr_t system = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING | SDL_INIT_EVENTS); if (!system) { diff --git a/Example_ImGui/main_Windows.cpp b/Example_ImGui/main_Windows.cpp index 482bfdcf5..beefdf0f8 100644 --- a/Example_ImGui/main_Windows.cpp +++ b/Example_ImGui/main_Windows.cpp @@ -33,7 +33,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, BOOL dpi_success = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); assert(dpi_success); - wiStartupArguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... + wi::arguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); @@ -169,26 +169,26 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) switch (wParam) { case VK_BACK: - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); break; case VK_RETURN: break; default: { const char c = (const char)(TCHAR)wParam; - if (wiBackLog::isActive()) + if (wi::backlog::isActive()) { - wiBackLog::input(c); + wi::backlog::input(c); } - wiTextInputField::AddInput(c); + wi::gui::TextInputField::AddInput(c); } break; } break; case WM_INPUT: - wiRawInput::ParseMessage((void*)lParam); + wi::input::rawinput::ParseMessage((void*)lParam); break; case WM_KILLFOCUS: example_imgui.is_window_active = false; diff --git a/README.md b/README.md index 1aeb2b83b..477c2f78c 100644 --- a/README.md +++ b/README.md @@ -84,55 +84,55 @@ If you have questions or stuck, please use the `linux` communication channel on // Include engine headers: #include "WickedEngine.h" -// Declare main component once per application: -MainComponent main; +// Create the Wicked Engine application: +wi::Application application; // Assign window that you will render to: -main.SetWindow(hWnd); +application.SetWindow(hWnd); // Run the application: while(true) { - main.Run(); + application.Run(); } ``` #### Basics (C++): ```cpp -RenderPath3D myGame; // Declare a game screen component, aka "RenderPath" (you could also override its Update(), Render() etc. functions). -main.ActivatePath(&myGame); // Register your game to the application. It will call Start(), Update(), Render(), etc. from now on... +wi::RenderPath3D myGame; // Declare a game screen component, aka "RenderPath" (you could also override its Update(), Render() etc. functions). +application.ActivatePath(&myGame); // Register your game to the application. It will call Start(), Update(), Render(), etc. from now on... -wiScene::LoadModel("myModel.wiscene"); // Simply load a model into the current global scene -wiScene::GetScene(); // Get the current global scene +wi::scene::LoadModel("myModel.wiscene"); // Simply load a model into the current global scene +wi::scene::GetScene(); // Get the current global scene -wiScene::Scene scene2; // create a separate scene -wiScene::LoadModel(scene2, "myModel2.wiscene"); // Load model into a separate scene -wiScene::GetScene().Merge(scene2); // Combine separate scene with global scene +wi::scene::Scene scene2; // create a separate scene +wi::scene::LoadModel(scene2, "myModel2.wiscene"); // Load model into a separate scene +wi::scene::GetScene().Merge(scene2); // Combine separate scene with global scene myGame.setFXAAEnabled(true); // You can enable post process effects this way... -RenderPath2D myMenuScreen; // This is an other render path, but now a simple 2D one. It can only render 2D graphics by default (like a menu for example) -main.ActivatePath(&myMenuScreen); // activate the menu, the previous path (myGame) will be stopped +wi::RenderPath2D myMenuScreen; // This is an other render path, but now a simple 2D one. It can only render 2D graphics by default (like a menu for example) +application.ActivatePath(&myMenuScreen); // activate the menu, the previous path (myGame) will be stopped -wiSprite mySprite("image.png"); // There are many utilities, such as a "sprite" helper class +wi::Sprite mySprite("image.png"); // There are many utilities, such as a "sprite" helper class myMenuScreen.AddSprite(&mySprite); // The 2D render path is ready to handle sprite and font rendering for you -wiAudio::Sound mySound; -wiAudio::CreateSound("explosion.wav", &mySound); // Loads a sound file -wiAudio::SoundInstance mySoundInstance; -wiAudio::CreateSoundInstance(&mySound, &mySoundInstance); // Instances the sound file, it can be played now -wiAudio::Play(&mySoundInstance); // Play the sound instance -wiAudio::SetVolume(0.6, &mySoundInstance); // Set the volume of this soundinstance -wiAudio::SetVolume(0.2); // Set the master volume +wi::audio::Sound mySound; +wi::audio::CreateSound("explosion.wav", &mySound); // Loads a sound file +wi::audio::SoundInstance mySoundInstance; +wi::audio::CreateSoundInstance(&mySound, &mySoundInstance); // Instances the sound file, it can be played now +wi::audio::Play(&mySoundInstance); // Play the sound instance +wi::audio::SetVolume(0.6, &mySoundInstance); // Set the volume of this soundinstance +wi::audio::SetVolume(0.2); // Set the master volume -if (wiInput::Press(wiInput::KEYBOARD_BUTTON_SPACE)) { wiAudio::Stop(&mySoundInstance); } // You can check if a button is pressed or not (this only triggers once) -if (wiInput::Down(wiInput::KEYBOARD_BUTTON_SPACE)) { wiAudio::Play(&mySoundInstance); } // You can check if a button is pushed down or not (this triggers repeatedly) +if (wi::input::Press(wi::input::KEYBOARD_BUTTON_SPACE)) { wi::audio::Stop(&mySoundInstance); } // You can check if a button is pressed or not (this only triggers once) +if (wi::input::Down(wi::input::KEYBOARD_BUTTON_SPACE)) { wi::audio::Play(&mySoundInstance); } // You can check if a button is pushed down or not (this triggers repeatedly) ``` #### Scripting (LUA): ```lua --- Set a rendering path for the application main component +-- Set a rendering path for the application path = RenderPath3D; -main.SetActivePath(path); -- "main" is created automatically +application.SetActivePath(path); -- "application" is created automatically by wi::Application -- Load a model entity into the global scene: entity = LoadModel("myModel.wiscene"); @@ -152,9 +152,9 @@ transform = scene.Component_GetTransform(entity); transform.Translate(Vector(2, 0, 0)); -- Print any WickedEngine class information to the backlog: -getprops(main); -- prints the main component methods -getprops(scene); -- prints the Scene class methods -getprops(path); -- prints the deferred render path methods +getprops(application); -- prints the application methods +getprops(scene); -- prints the Scene class methods +getprops(path); -- prints the deferred render path methods -- Play a sound: sound = Sound() diff --git a/Template_UWP/Main.cpp b/Template_UWP/Main.cpp index 530e013e3..616f0c75f 100644 --- a/Template_UWP/Main.cpp +++ b/Template_UWP/Main.cpp @@ -45,10 +45,10 @@ public: CoreApplication::Resuming({ this, &ViewProvider::OnResuming }); - main.infoDisplay.active = true; - main.infoDisplay.watermark = true; - main.infoDisplay.resolution = true; - main.infoDisplay.fpsinfo = true; + application.infoDisplay.active = true; + application.infoDisplay.watermark = true; + application.infoDisplay.resolution = true; + application.infoDisplay.fpsinfo = true; } void Uninitialize() noexcept @@ -87,7 +87,7 @@ public: m_logicalWidth = window.Bounds().Width; m_logicalHeight = window.Bounds().Height; - main.SetWindow(&window); + application.SetWindow(&window); } void Load(winrt::hstring const &) noexcept @@ -100,7 +100,7 @@ public: { if (m_visible) { - main.Run(); + application.Run(); CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); } @@ -134,7 +134,7 @@ protected: void OnWindowSizeChanged(CoreWindow const & sender, WindowSizeChangedEventArgs const & /*args*/) { - main.SetWindow(&sender); + application.SetWindow(&sender); } void OnVisibilityChanged(CoreWindow const & /*sender*/, VisibilityChangedEventArgs const & args) @@ -166,15 +166,15 @@ protected: if (c == '\b') { - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); } else { - if (wiBackLog::isActive()) - wiBackLog::input(c); - wiTextInputField::AddInput(c); + if (wi::backlog::isActive()) + wi::backlog::input(c); + wi::gui::TextInputField::AddInput(c); } } @@ -182,7 +182,7 @@ protected: void OnDpiChanged(DisplayInformation const & sender, IInspectable const & /*args*/) { - main.SetWindow(&CoreWindow::GetForCurrentThread()); + application.SetWindow(&CoreWindow::GetForCurrentThread()); } void OnDisplayContentsInvalidated(DisplayInformation const & /*sender*/, IInspectable const & /*args*/) @@ -195,7 +195,7 @@ private: float m_DPI = 96; float m_logicalWidth = 800; float m_logicalHeight = 600; - MainComponent main; + wi::Application application; inline int ConvertDipsToPixels(float dips) const noexcept { diff --git a/Template_Windows/main.cpp b/Template_Windows/main.cpp index fe06ed7b3..98a99d372 100644 --- a/Template_Windows/main.cpp +++ b/Template_Windows/main.cpp @@ -10,7 +10,7 @@ HINSTANCE hInst; // current instance WCHAR szTitle[MAX_LOADSTRING]; // The title bar text WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name -MainComponent main; // Wicked Engine Main Runtime Component +wi::Application application; // Wicked Engine Application // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); @@ -31,7 +31,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, BOOL dpi_success = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); assert(dpi_success); - wiStartupArguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... + wi::arguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); @@ -47,10 +47,10 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TEMPLATEWINDOWS)); // just show some basic info: - main.infoDisplay.active = true; - main.infoDisplay.watermark = true; - main.infoDisplay.resolution = true; - main.infoDisplay.fpsinfo = true; + application.infoDisplay.active = true; + application.infoDisplay.watermark = true; + application.infoDisplay.resolution = true; + application.infoDisplay.fpsinfo = true; MSG msg = { 0 }; while (msg.message != WM_QUIT) @@ -61,7 +61,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, } else { - main.Run(); // run the update - render loop (mandatory) + application.Run(); // run the update - render loop (mandatory) } } @@ -123,7 +123,7 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) UpdateWindow(hWnd); - main.SetWindow(hWnd); // assign window handle (mandatory) + application.SetWindow(hWnd); // assign window handle (mandatory) return TRUE; @@ -162,36 +162,36 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) break; case WM_SIZE: case WM_DPICHANGED: - if (main.is_window_active) - main.SetWindow(hWnd); + if (application.is_window_active) + application.SetWindow(hWnd); break; case WM_CHAR: switch (wParam) { case VK_BACK: - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); break; case VK_RETURN: break; default: { const char c = (const char)(TCHAR)wParam; - if (wiBackLog::isActive()) + if (wi::backlog::isActive()) { - wiBackLog::input(c); + wi::backlog::input(c); } - wiTextInputField::AddInput(c); + wi::gui::TextInputField::AddInput(c); } break; } break; case WM_KILLFOCUS: - main.is_window_active = false; + application.is_window_active = false; break; case WM_SETFOCUS: - main.is_window_active = true; + application.is_window_active = true; break; case WM_PAINT: { diff --git a/Tests/Tests.cpp b/Tests/Tests.cpp index 7371633ed..07f175c8d 100644 --- a/Tests/Tests.cpp +++ b/Tests/Tests.cpp @@ -6,12 +6,12 @@ #include #include -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; void Tests::Initialize() { - MainComponent::Initialize(); + wi::Application::Initialize(); infoDisplay.active = true; infoDisplay.watermark = true; @@ -41,37 +41,37 @@ void TestsRenderer::Load() label.Create("Label1"); label.SetText("Wicked Engine Test Framework"); - label.font.params.h_align = WIFALIGN_CENTER; + label.font.params.h_align = wi::font::WIFALIGN_CENTER; label.SetSize(XMFLOAT2(240,20)); GetGUI().AddWidget(&label); - static wiAudio::Sound sound; - static wiAudio::SoundInstance soundinstance; + static wi::audio::Sound sound; + static wi::audio::SoundInstance soundinstance; - static wiButton audioTest; + static wi::gui::Button audioTest; audioTest.Create("AudioTest"); audioTest.SetText("Play Test Audio"); audioTest.SetSize(XMFLOAT2(200, 20)); audioTest.SetPos(XMFLOAT2(10, 140)); - audioTest.SetColor(wiColor(255, 205, 43, 200), wiWidget::WIDGETSTATE::IDLE); - audioTest.SetColor(wiColor(255, 235, 173, 255), wiWidget::WIDGETSTATE::FOCUS); - audioTest.OnClick([&](wiEventArgs args) { + audioTest.SetColor(wi::Color(255, 205, 43, 200), wi::gui::IDLE); + audioTest.SetColor(wi::Color(255, 235, 173, 255), wi::gui::FOCUS); + audioTest.OnClick([&](wi::gui::EventArgs args) { static bool playing = false; if (!sound.IsValid()) { - wiAudio::CreateSound("sound/music.wav", &sound); - wiAudio::CreateSoundInstance(&sound, &soundinstance); + wi::audio::CreateSound("sound/music.wav", &sound); + wi::audio::CreateSoundInstance(&sound, &soundinstance); } if (playing) { - wiAudio::Stop(&soundinstance); + wi::audio::Stop(&soundinstance); audioTest.SetText("Play Test Audio"); } else { - wiAudio::Play(&soundinstance); + wi::audio::Play(&soundinstance); audioTest.SetText("Stop Test Audio"); } @@ -80,17 +80,17 @@ void TestsRenderer::Load() GetGUI().AddWidget(&audioTest); - static wiSlider volume; + static wi::gui::Slider volume; volume.Create(0, 100, 50, 100, "Volume"); volume.SetText("Volume: "); volume.SetSize(XMFLOAT2(100, 20)); volume.SetPos(XMFLOAT2(65, 170)); - volume.sprites_knob[wiWidget::WIDGETSTATE::IDLE].params.color = wiColor(255, 205, 43, 200); - volume.sprites_knob[wiWidget::WIDGETSTATE::FOCUS].params.color = wiColor(255, 235, 173, 255); - volume.sprites[wiWidget::WIDGETSTATE::IDLE].params.color = wiMath::Lerp(wiColor::Transparent(), volume.sprites_knob[wiWidget::WIDGETSTATE::IDLE].params.color, 0.5f); - volume.sprites[wiWidget::WIDGETSTATE::FOCUS].params.color = wiMath::Lerp(wiColor::Transparent(), volume.sprites_knob[wiWidget::WIDGETSTATE::FOCUS].params.color, 0.5f); - volume.OnSlide([](wiEventArgs args) { - wiAudio::SetVolume(args.fValue / 100.0f, &soundinstance); + volume.sprites_knob[wi::gui::IDLE].params.color = wi::Color(255, 205, 43, 200); + volume.sprites_knob[wi::gui::FOCUS].params.color = wi::Color(255, 235, 173, 255); + volume.sprites[wi::gui::IDLE].params.color = wi::math::Lerp(wi::Color::Transparent(), volume.sprites_knob[wi::gui::WIDGETSTATE::IDLE].params.color, 0.5f); + volume.sprites[wi::gui::FOCUS].params.color = wi::math::Lerp(wi::Color::Transparent(), volume.sprites_knob[wi::gui::WIDGETSTATE::FOCUS].params.color, 0.5f); + volume.OnSlide([](wi::gui::EventArgs args) { + wi::audio::SetVolume(args.fValue / 100.0f, &soundinstance); }); GetGUI().AddWidget(&volume); @@ -99,8 +99,8 @@ void TestsRenderer::Load() testSelector.SetText("Demo: "); testSelector.SetSize(XMFLOAT2(140, 20)); testSelector.SetPos(XMFLOAT2(50, 200)); - testSelector.SetColor(wiColor(255, 205, 43, 200), wiWidget::WIDGETSTATE::IDLE); - testSelector.SetColor(wiColor(255, 235, 173, 255), wiWidget::WIDGETSTATE::FOCUS); + testSelector.SetColor(wi::Color(255, 205, 43, 200), wi::gui::IDLE); + testSelector.SetColor(wi::Color(255, 235, 173, 255), wi::gui::FOCUS); testSelector.AddItem("HelloWorld"); testSelector.AddItem("Model"); testSelector.AddItem("EmittedParticle 1"); @@ -122,25 +122,25 @@ void TestsRenderer::Load() testSelector.AddItem("65k Instances"); testSelector.AddItem("unordered_map perf"); testSelector.SetMaxVisibleItemCount(10); - testSelector.OnSelect([=](wiEventArgs args) { + testSelector.OnSelect([=](wi::gui::EventArgs args) { // Reset all state that tests might have modified: - wiEvent::SetVSync(true); - wiRenderer::SetToDrawGridHelper(false); - wiRenderer::SetTemporalAAEnabled(false); - wiRenderer::ClearWorld(wiScene::GetScene()); - wiScene::GetScene().weather = WeatherComponent(); + wi::eventhandler::SetVSync(true); + wi::renderer::SetToDrawGridHelper(false); + wi::renderer::SetTemporalAAEnabled(false); + wi::renderer::ClearWorld(wi::scene::GetScene()); + wi::scene::GetScene().weather = WeatherComponent(); this->ClearSprites(); this->ClearFonts(); - if (wiLua::GetLuaState() != nullptr) { - wiLua::KillProcesses(); + if (wi::lua::GetLuaState() != nullptr) { + wi::lua::KillProcesses(); } // Reset camera position: TransformComponent transform; transform.Translate(XMFLOAT3(0, 2.f, -4.5f)); transform.UpdateTransform(); - wiScene::GetCamera().TransformCamera(transform); + wi::scene::GetCamera().TransformCamera(transform); float screenW = GetLogicalWidth(); float screenH = GetLogicalHeight(); @@ -154,8 +154,8 @@ void TestsRenderer::Load() // The second texture is a static image of "hello world" written on it // Then add some animations to the sprite to get a nice wobbly and color changing effect. // You can learn more in the Sprite test in RunSpriteTest() function - static wiSprite sprite; - sprite = wiSprite("images/movingtex.png", "images/HelloWorld.png"); + static wi::Sprite sprite; + sprite = wi::Sprite("images/movingtex.png", "images/HelloWorld.png"); sprite.params.pos = XMFLOAT3(screenW / 2, screenH / 2, 0); sprite.params.siz = XMFLOAT2(200, 100); sprite.params.pivot = XMFLOAT2(0.5f, 0.5f); @@ -167,36 +167,36 @@ void TestsRenderer::Load() break; } case 1: - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/teapot.wiscene"); + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/teapot.wiscene"); break; case 2: - wiScene::LoadModel("../Content/models/emitter_smoke.wiscene"); + wi::scene::LoadModel("../Content/models/emitter_smoke.wiscene"); break; case 3: - wiScene::LoadModel("../Content/models/emitter_skinned.wiscene"); + wi::scene::LoadModel("../Content/models/emitter_skinned.wiscene"); break; case 4: - wiScene::LoadModel("../Content/models/hairparticle_torus.wiscene", XMMatrixTranslation(0, 1, 0)); + wi::scene::LoadModel("../Content/models/hairparticle_torus.wiscene", XMMatrixTranslation(0, 1, 0)); break; case 5: - wiRenderer::SetToDrawGridHelper(true); - wiLua::RunFile("test_script.lua"); + wi::renderer::SetToDrawGridHelper(true); + wi::lua::RunFile("test_script.lua"); break; case 6: - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/water_test.wiscene", XMMatrixTranslation(0, 1, 0)); + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/water_test.wiscene", XMMatrixTranslation(0, 1, 0)); break; case 7: - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/shadows_test.wiscene", XMMatrixTranslation(0, 1, 0)); + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/shadows_test.wiscene", XMMatrixTranslation(0, 1, 0)); break; case 8: - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/physics_test.wiscene"); + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/physics_test.wiscene"); break; case 9: - wiScene::LoadModel("../Content/models/cloth_test.wiscene", XMMatrixTranslation(0, 3, 4)); + wi::scene::LoadModel("../Content/models/cloth_test.wiscene", XMMatrixTranslation(0, 3, 4)); break; case 10: RunJobSystemTest(); @@ -205,34 +205,34 @@ void TestsRenderer::Load() RunFontTest(); break; case 12: - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/volumetric_test.wiscene", XMMatrixTranslation(0, 0, 4)); + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/volumetric_test.wiscene", XMMatrixTranslation(0, 0, 4)); break; case 13: RunSpriteTest(); break; case 14: - wiEvent::SetVSync(false); // turn off vsync if we can to accelerate the baking - wiRenderer::SetTemporalAAEnabled(true); - wiScene::LoadModel("../Content/models/lightmap_bake_test.wiscene", XMMatrixTranslation(0, 0, 4)); + wi::eventhandler::SetVSync(false); // turn off vsync if we can to accelerate the baking + wi::renderer::SetTemporalAAEnabled(true); + wi::scene::LoadModel("../Content/models/lightmap_bake_test.wiscene", XMMatrixTranslation(0, 0, 4)); break; case 15: RunNetworkTest(); break; case 16: { - static wiSpriteFont font("This test plays a vibration on the first controller's left motor (if device supports it) \n and changes the LED to a random color (if device supports it)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_CENTER; + static wi::SpriteFont font("This test plays a vibration on the first controller's left motor (if device supports it) \n and changes the LED to a random color (if device supports it)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_CENTER; font.params.size = 20; font.params.posX = screenW / 2; font.params.posY = screenH / 2; AddFont(&font); - wiInput::ControllerFeedback feedback; - feedback.led_color.rgba = wiRandom::getRandom(0xFFFFFF); + wi::input::ControllerFeedback feedback; + feedback.led_color.rgba = wi::random::GetRandom(0xFFFFFF); feedback.vibration_left = 0.9f; - wiInput::SetControllerFeedback(feedback, 0); + wi::input::SetControllerFeedback(feedback, 0); } break; case 17: @@ -265,15 +265,15 @@ void TestsRenderer::Load() weather.zenith = XMFLOAT3(0.42f, 0.42f, 0.42f); weather.cloudiness = 0.75f; - wiScene::GetScene().Merge(scene); // add lodaded scene to global scene + wi::scene::GetScene().Merge(scene); // add lodaded scene to global scene } break; case 18: { - wiScene::LoadModel("../Content/models/cube.wiscene"); - wiProfiler::SetEnabled(true); - Scene& scene = wiScene::GetScene(); + wi::scene::LoadModel("../Content/models/cube.wiscene"); + wi::profiler::SetEnabled(true); + Scene& scene = wi::scene::GetScene(); scene.Entity_CreateLight("testlight", XMFLOAT3(0, 2, -4), XMFLOAT3(1, 1, 1), 4, 10); Entity cubeentity = scene.Entity_FindByName("Cube"); const float scale = 0.06f; @@ -315,23 +315,23 @@ void TestsRenderer::Update(float dt) { case 1: { - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); // teapot_material Base Base_mesh Top Top_mesh editorLight - wiECS::Entity e_teapot_base = scene.Entity_FindByName("Base"); - wiECS::Entity e_teapot_top = scene.Entity_FindByName("Top"); - assert(e_teapot_base != wiECS::INVALID_ENTITY); - assert(e_teapot_top != wiECS::INVALID_ENTITY); + wi::ecs::Entity e_teapot_base = scene.Entity_FindByName("Base"); + wi::ecs::Entity e_teapot_top = scene.Entity_FindByName("Top"); + assert(e_teapot_base != wi::ecs::INVALID_ENTITY); + assert(e_teapot_top != wi::ecs::INVALID_ENTITY); TransformComponent* transform_base = scene.transforms.GetComponent(e_teapot_base); TransformComponent* transform_top = scene.transforms.GetComponent(e_teapot_top); assert(transform_base != nullptr); assert(transform_top != nullptr); float rotation = dt; - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_LEFT)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_LEFT)) { transform_base->Rotate(XMVectorSet(0,rotation,0,1)); transform_top->Rotate(XMVectorSet(0,rotation,0,1)); } - else if (wiInput::Down(wiInput::KEYBOARD_BUTTON_RIGHT)) + else if (wi::input::Down(wi::input::KEYBOARD_BUTTON_RIGHT)) { transform_base->Rotate(XMVectorSet(0,-rotation,0,1)); transform_top->Rotate(XMVectorSet(0,-rotation,0,1)); @@ -343,12 +343,12 @@ void TestsRenderer::Update(float dt) if (ik_entity != INVALID_ENTITY) { // Inverse kinematics test: - Scene& scene = wiScene::GetScene(); + Scene& scene = wi::scene::GetScene(); InverseKinematicsComponent& ik = *scene.inverse_kinematics.GetComponent(ik_entity); TransformComponent& target = *scene.transforms.GetComponent(ik.target); // place ik target on a plane intersected by mouse ray: - RAY ray = wiRenderer::GetPickRay((long)wiInput::GetPointer().x, (long)wiInput::GetPointer().y, *this); + wi::primitive::Ray ray = wi::renderer::GetPickRay((long)wi::input::GetPointer().x, (long)wi::input::GetPointer().y, *this); XMVECTOR plane = XMVectorSet(0, 0, 1, 0.2f); XMVECTOR I = XMPlaneIntersectLine(plane, XMLoadFloat3(&ray.origin), XMLoadFloat3(&ray.origin) + XMLoadFloat3(&ray.direction) * 10000); target.ClearTransform(); @@ -358,26 +358,26 @@ void TestsRenderer::Update(float dt) target.UpdateTransform(); // draw debug ik target position: - wiRenderer::RenderablePoint pp; + wi::renderer::RenderablePoint pp; pp.position = target.GetPosition(); pp.color = XMFLOAT4(0, 1, 1, 1); pp.size = 0.2f; - wiRenderer::DrawPoint(pp); + wi::renderer::DrawPoint(pp); pp.position = scene.transforms.GetComponent(ik_entity)->GetPosition(); pp.color = XMFLOAT4(1, 0, 0, 1); pp.size = 0.1f; - wiRenderer::DrawPoint(pp); + wi::renderer::DrawPoint(pp); } } break; case 18: { - static wiTimer timer; + static wi::Timer timer; float sec = (float)timer.elapsed_seconds(); - wiJobSystem::context ctx; - wiJobSystem::Dispatch(ctx, (uint32_t)scene->transforms.GetCount(), 1024, [&](wiJobArgs args) { + wi::jobsystem::context ctx; + wi::jobsystem::Dispatch(ctx, (uint32_t)scene->transforms.GetCount(), 1024, [&](wi::jobsystem::JobArgs args) { TransformComponent& transform = scene->transforms[args.jobIndex]; XMStoreFloat4x4( &transform.world, @@ -385,12 +385,12 @@ void TestsRenderer::Update(float dt) ); }); scene->materials[0].SetEmissiveColor(XMFLOAT4(1, 1, 1, 1)); - wiJobSystem::Dispatch(ctx, (uint32_t)scene->objects.GetCount(), 1024, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)scene->objects.GetCount(), 1024, [&](wi::jobsystem::JobArgs args) { ObjectComponent& object = scene->objects[args.jobIndex]; float f = std::pow(std::sin(-sec * 2 + 4 * (float)args.jobIndex / (float)scene->objects.GetCount()) * 0.5f + 0.5f, 32.0f); object.emissiveColor = XMFLOAT4(0, 0.25f, 1, f * 3); }); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); } break; @@ -401,10 +401,10 @@ void TestsRenderer::Update(float dt) void TestsRenderer::RunJobSystemTest() { - wiTimer timer; + wi::Timer timer; // This is created to be able to wait on the workload independently from other workload: - wiJobSystem::context ctx; + wi::jobsystem::context ctx; // This will simulate going over a big dataset first in a simple loop, then with the Job System and compare timings uint32_t itemCount = 1000000; @@ -412,37 +412,37 @@ void TestsRenderer::RunJobSystemTest() ss += "Job System performance test:\n"; ss += "You can find out more in Tests.cpp, RunJobSystemTest() function.\n\n"; - ss += "wiJobSystem was created with " + std::to_string(wiJobSystem::GetThreadCount()) + " worker threads.\n\n"; + ss += "wi::jobsystem was created with " + std::to_string(wi::jobsystem::GetThreadCount()) + " worker threads.\n\n"; ss += "1) Execute() test:\n"; // Serial test { timer.record(); - wiHelper::Spin(100); - wiHelper::Spin(100); - wiHelper::Spin(100); - wiHelper::Spin(100); + wi::helper::Spin(100); + wi::helper::Spin(100); + wi::helper::Spin(100); + wi::helper::Spin(100); double time = timer.elapsed(); ss += "Serial took " + std::to_string(time) + " milliseconds\n"; } // Execute test { timer.record(); - wiJobSystem::Execute(ctx, [](wiJobArgs args){ wiHelper::Spin(100); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args){ wiHelper::Spin(100); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args){ wiHelper::Spin(100); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args){ wiHelper::Spin(100); }); - wiJobSystem::Wait(ctx); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args){ wi::helper::Spin(100); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args){ wi::helper::Spin(100); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args){ wi::helper::Spin(100); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args){ wi::helper::Spin(100); }); + wi::jobsystem::Wait(ctx); double time = timer.elapsed(); - ss += "wiJobSystem::Execute() took " + std::to_string(time) + " milliseconds\n"; + ss += "wi::jobsystem::Execute() took " + std::to_string(time) + " milliseconds\n"; } ss += "\n2) Dispatch() test:\n"; // Simple loop test: { - wi::vector dataSet(itemCount); + wi::vector dataSet(itemCount); timer.record(); for (uint32_t i = 0; i < itemCount; ++i) { @@ -454,39 +454,39 @@ void TestsRenderer::RunJobSystemTest() // Dispatch test: { - wi::vector dataSet(itemCount); + wi::vector dataSet(itemCount); timer.record(); - wiJobSystem::Dispatch(ctx, itemCount, 1000, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, itemCount, 1000, [&](wi::jobsystem::JobArgs args) { dataSet[args.jobIndex].UpdateCamera(); }); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); double time = timer.elapsed(); - ss += "wiJobSystem::Dispatch() took " + std::to_string(time) + " milliseconds\n"; + ss += "wi::jobsystem::Dispatch() took " + std::to_string(time) + " milliseconds\n"; } - static wiSpriteFont font; - font = wiSpriteFont(ss); + static wi::SpriteFont font; + font = wi::SpriteFont(ss); font.params.posX = GetLogicalWidth() / 2; font.params.posY = GetLogicalHeight() / 2; - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_CENTER; + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_CENTER; font.params.size = 24; this->AddFont(&font); } void TestsRenderer::RunFontTest() { - static wiSpriteFont font; - static wiSpriteFont font_upscaled; + static wi::SpriteFont font; + static wi::SpriteFont font_upscaled; - font.SetText("This is Arial, size 32 wiFont"); - font_upscaled.SetText("This is Arial, size 14 wiFont, but upscaled to 32"); + font.SetText("This is Arial, size 32 wi::font"); + font_upscaled.SetText("This is Arial, size 14 wi::font, but upscaled to 32"); font.params.posX = GetLogicalWidth() / 2.0f; font.params.posY = GetLogicalHeight() / 6.0f; font.params.size = 32; font_upscaled.params = font.params; - font_upscaled.params.posY += font.textHeight(); + font_upscaled.params.posY += font.TextHeight(); font.params.style = 0; // 0 = default font font_upscaled.params.style = 0; // 0 = default font @@ -496,20 +496,20 @@ void TestsRenderer::RunFontTest() AddFont(&font); AddFont(&font_upscaled); - static wiSpriteFont font_aligned; + static wi::SpriteFont font_aligned; font_aligned = font; - font_aligned.params.posY += font.textHeight() * 2; + font_aligned.params.posY += font.TextHeight() * 2; font_aligned.params.size = 38; - font_aligned.params.shadowColor = wiColor::Red(); - font_aligned.params.h_align = WIFALIGN_CENTER; + font_aligned.params.shadowColor = wi::Color::Red(); + font_aligned.params.h_align = wi::font::WIFALIGN_CENTER; font_aligned.SetText("Center aligned, red shadow, bigger"); AddFont(&font_aligned); - static wiSpriteFont font_aligned2; + static wi::SpriteFont font_aligned2; font_aligned2 = font_aligned; - font_aligned2.params.posY += font_aligned.textHeight(); - font_aligned2.params.shadowColor = wiColor::Purple(); - font_aligned2.params.h_align = WIFALIGN_RIGHT; + font_aligned2.params.posY += font_aligned.TextHeight(); + font_aligned2.params.shadowColor = wi::Color::Purple(); + font_aligned2.params.h_align = wi::font::WIFALIGN_RIGHT; font_aligned2.SetText("Right aligned, purple shadow"); AddFont(&font_aligned2); @@ -524,23 +524,23 @@ void TestsRenderer::RunFontTest() ss += s + "\t"; } } - static wiSpriteFont font_japanese; + static wi::SpriteFont font_japanese; font_japanese = font_aligned2; - font_japanese.params.posY += font_aligned2.textHeight(); - font_japanese.params.style = wiFont::AddFontStyle("yumin.ttf"); - font_japanese.params.shadowColor = wiColor::Transparent(); - font_japanese.params.h_align = WIFALIGN_CENTER; + font_japanese.params.posY += font_aligned2.TextHeight(); + font_japanese.params.style = wi::font::AddFontStyle("yumin.ttf"); + font_japanese.params.shadowColor = wi::Color::Transparent(); + font_japanese.params.h_align = wi::font::WIFALIGN_CENTER; font_japanese.params.size = 34; font_japanese.SetText(ss); AddFont(&font_japanese); - static wiSpriteFont font_colored; - font_colored.params.color = wiColor::Cyan(); - font_colored.params.h_align = WIFALIGN_CENTER; - font_colored.params.v_align = WIFALIGN_TOP; + static wi::SpriteFont font_colored; + font_colored.params.color = wi::Color::Cyan(); + font_colored.params.h_align = wi::font::WIFALIGN_CENTER; + font_colored.params.v_align = wi::font::WIFALIGN_TOP; font_colored.params.size = 26; font_colored.params.posX = GetLogicalWidth() / 2; - font_colored.params.posY = font_japanese.params.posY + font_japanese.textHeight(); + font_colored.params.posY = font_japanese.params.posY + font_japanese.TextHeight(); font_colored.SetText("Colored font"); AddFont(&font_colored); } @@ -550,17 +550,17 @@ void TestsRenderer::RunSpriteTest() const float screenW = GetLogicalWidth(); const float screenH = GetLogicalHeight(); const XMFLOAT3 startPos = XMFLOAT3(screenW * 0.3f, screenH * 0.2f, 0); - wiImageParams params; + wi::image::Params params; params.pos = startPos; params.siz = XMFLOAT2(128, 128); params.pivot = XMFLOAT2(0.5f, 0.5f); - params.quality = QUALITY_LINEAR; - params.sampleFlag = SAMPLEMODE_CLAMP; - params.blendFlag = BLENDMODE_ALPHA; + params.quality = wi::image::QUALITY_LINEAR; + params.sampleFlag = wi::image::SAMPLEMODE_CLAMP; + params.blendFlag = wi::enums::BLENDMODE_ALPHA; // Info: { - static wiSpriteFont font("For more information, please see \nTests.cpp, RunSpriteTest() function."); + static wi::SpriteFont font("For more information, please see \nTests.cpp, RunSpriteTest() function."); font.params.posX = 10; font.params.posY = screenH / 2; AddFont(&font); @@ -568,13 +568,13 @@ void TestsRenderer::RunSpriteTest() // Simple sprite, no animation: { - static wiSprite sprite("../Content/logo_small.png"); + static wi::Sprite sprite("../Content/logo_small.png"); sprite.params = params; AddSprite(&sprite); - static wiSpriteFont font("No animation: "); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("No animation: "); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -584,16 +584,16 @@ void TestsRenderer::RunSpriteTest() // Simple sprite, fade animation: { - static wiSprite sprite("../Content/logo_small.png"); + static wi::Sprite sprite("../Content/logo_small.png"); sprite.params = params; - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.fad = 1.2f; // (you can also do opacity animation with sprite.anim.opa) sprite.anim.repeatable = true; AddSprite(&sprite); - static wiSpriteFont font("Fade animation: "); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("Fade animation: "); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -603,16 +603,16 @@ void TestsRenderer::RunSpriteTest() // Simple sprite, wobble animation: { - static wiSprite sprite("../Content/logo_small.png"); + static wi::Sprite sprite("../Content/logo_small.png"); sprite.params = params; - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.wobbleAnim.amount = XMFLOAT2(0.11f, 0.18f); sprite.anim.wobbleAnim.speed = 1.4f; AddSprite(&sprite); - static wiSpriteFont font("Wobble animation: "); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("Wobble animation: "); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -622,16 +622,16 @@ void TestsRenderer::RunSpriteTest() // Simple sprite, rotate animation: { - static wiSprite sprite("../Content/logo_small.png"); + static wi::Sprite sprite("../Content/logo_small.png"); sprite.params = params; - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.rot = 2.8f; sprite.anim.repeatable = true; AddSprite(&sprite); - static wiSpriteFont font("Rotate animation: "); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("Rotate animation: "); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -641,20 +641,20 @@ void TestsRenderer::RunSpriteTest() // Simple sprite, movingtex: { - static wiSprite sprite("images/movingtex.png", "../Content/logo_small.png"); // first param is the texture we will display (and also scroll here). Second param is a mask texture + static wi::Sprite sprite("images/movingtex.png", "../Content/logo_small.png"); // first param is the texture we will display (and also scroll here). Second param is a mask texture // Don't overwrite all params for this, because we want to keep the mask... sprite.params.pos = params.pos; sprite.params.siz = params.siz; sprite.params.pivot = params.pivot; sprite.params.color = XMFLOAT4(2, 2, 2, 1); // increase brightness a bit - sprite.params.sampleFlag = SAMPLEMODE_MIRROR; // texcoords will be scrolled out of bounds, so set up a wrap mode other than clamp + sprite.params.sampleFlag = wi::image::SAMPLEMODE_MIRROR; // texcoords will be scrolled out of bounds, so set up a wrap mode other than clamp sprite.anim.movingTexAnim.speedX = 0; sprite.anim.movingTexAnim.speedY = 2; // scroll the texture vertically. This value is pixels/second. So because our texture here is 1x2 pixels, just scroll it once fully per second with a value of 2 AddSprite(&sprite); - static wiSpriteFont font("MovingTex + mask: "); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("MovingTex + mask: "); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -668,13 +668,13 @@ void TestsRenderer::RunSpriteTest() // Spritesheet, no anim: { - static wiSprite sprite("images/spritesheet_grid.png"); + static wi::Sprite sprite("images/spritesheet_grid.png"); sprite.params = params; // nothing extra, just display the full spritesheet AddSprite(&sprite); - static wiSpriteFont font("Spritesheet: \n(without animation)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("Spritesheet: \n(without animation)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -684,18 +684,18 @@ void TestsRenderer::RunSpriteTest() // Spritesheet, single line: { - static wiSprite sprite("images/spritesheet_grid.png"); + static wi::Sprite sprite("images/spritesheet_grid.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 128, 128)); // drawrect cutout for a 0,0,128,128 pixel rect, this is also the first frame of animation - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.repeatable = true; // enable looping sprite.anim.drawRectAnim.frameRate = 3; // 3 FPS, to be easily readable sprite.anim.drawRectAnim.frameCount = 4; // animate only a single line horizontally AddSprite(&sprite); - static wiSpriteFont font("single line anim: \n(4 frames)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("single line anim: \n(4 frames)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -705,19 +705,19 @@ void TestsRenderer::RunSpriteTest() // Spritesheet, single vertical line: { - static wiSprite sprite("images/spritesheet_grid.png"); + static wi::Sprite sprite("images/spritesheet_grid.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 128, 128)); // drawrect cutout for a 0,0,128,128 pixel rect, this is also the first frame of animation - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.repeatable = true; // enable looping sprite.anim.drawRectAnim.frameRate = 3; // 3 FPS, to be easily readable sprite.anim.drawRectAnim.frameCount = 4; // again, specify 4 total frames to loop... sprite.anim.drawRectAnim.horizontalFrameCount = 1; // ...but this time, limit the horizontal frame count. This way, we can get it to only animate vertically AddSprite(&sprite); - static wiSpriteFont font("single line: \n(4 vertical frames)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("single line: \n(4 vertical frames)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -727,19 +727,19 @@ void TestsRenderer::RunSpriteTest() // Spritesheet, multiline: { - static wiSprite sprite("images/spritesheet_grid.png"); + static wi::Sprite sprite("images/spritesheet_grid.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 128, 128)); // drawrect cutout for a 0,0,128,128 pixel rect, this is also the first frame of animation - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.repeatable = true; // enable looping sprite.anim.drawRectAnim.frameRate = 3; // 3 FPS, to be easily readable sprite.anim.drawRectAnim.frameCount = 16; // all frames sprite.anim.drawRectAnim.horizontalFrameCount = 4; // all horizontal frames AddSprite(&sprite); - static wiSpriteFont font("multiline: \n(all 16 frames)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("multiline: \n(all 16 frames)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -749,19 +749,19 @@ void TestsRenderer::RunSpriteTest() // Spritesheet, multiline, irregular: { - static wiSprite sprite("images/spritesheet_grid.png"); + static wi::Sprite sprite("images/spritesheet_grid.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 128, 128)); // drawrect cutout for a 0,0,128,128 pixel rect, this is also the first frame of animation - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.repeatable = true; // enable looping sprite.anim.drawRectAnim.frameRate = 3; // 3 FPS, to be easily readable sprite.anim.drawRectAnim.frameCount = 14; // NOT all frames, which makes it irregular, so the last line will not contain all horizontal frames sprite.anim.drawRectAnim.horizontalFrameCount = 4; // all horizontal frames AddSprite(&sprite); - static wiSpriteFont font("irregular multiline: \n(14 frames)"); - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("irregular multiline: \n(14 frames)"); + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -776,18 +776,18 @@ void TestsRenderer::RunSpriteTest() // And the nice ones: { - static wiSprite sprite("images/fire_001.png"); + static wi::Sprite sprite("images/fire_001.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 192, 192)); // set the draw rect (texture cutout). This will also be the first frame of the animation - sprite.anim = wiSprite::Anim(); // reset animation state + sprite.anim = wi::Sprite::Anim(); // reset animation state sprite.anim.drawRectAnim.frameCount = 20; // set the total frame count of the animation sprite.anim.drawRectAnim.horizontalFrameCount = 5; // this is a multiline spritesheet, so also set how many maximum frames there are in a line sprite.anim.drawRectAnim.frameRate = 40; // animation frames per second sprite.anim.repeatable = true; // looping AddSprite(&sprite); - static wiSpriteFont font("For the following spritesheets, credits belong to: https://mrbubblewand.wordpress.com/download/"); - font.params.v_align = WIFALIGN_BOTTOM; + static wi::SpriteFont font("For the following spritesheets, credits belong to: https://mrbubblewand.wordpress.com/download/"); + font.params.v_align = wi::font::WIFALIGN_BOTTOM; font.params.posX = sprite.params.pos.x - sprite.params.siz.x * 0.5f; font.params.posY = sprite.params.pos.y - sprite.params.siz.y * 0.5f; AddFont(&font); @@ -796,10 +796,10 @@ void TestsRenderer::RunSpriteTest() } { - static wiSprite sprite("images/wind_002.png"); + static wi::Sprite sprite("images/wind_002.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 192, 192)); - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.drawRectAnim.frameCount = 30; sprite.anim.drawRectAnim.horizontalFrameCount = 5; sprite.anim.drawRectAnim.frameRate = 30; @@ -810,10 +810,10 @@ void TestsRenderer::RunSpriteTest() } { - static wiSprite sprite("images/water_003.png"); + static wi::Sprite sprite("images/water_003.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 192, 192)); - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.drawRectAnim.frameCount = 50; sprite.anim.drawRectAnim.horizontalFrameCount = 5; sprite.anim.drawRectAnim.frameRate = 27; @@ -824,10 +824,10 @@ void TestsRenderer::RunSpriteTest() } { - static wiSprite sprite("images/earth_001.png"); + static wi::Sprite sprite("images/earth_001.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 192, 192)); - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.drawRectAnim.frameCount = 20; sprite.anim.drawRectAnim.horizontalFrameCount = 5; sprite.anim.drawRectAnim.frameRate = 27; @@ -838,10 +838,10 @@ void TestsRenderer::RunSpriteTest() } { - static wiSprite sprite("images/special_001.png"); + static wi::Sprite sprite("images/special_001.png"); sprite.params = params; sprite.params.enableDrawRect(XMFLOAT4(0, 0, 192, 192)); - sprite.anim = wiSprite::Anim(); + sprite.anim = wi::Sprite::Anim(); sprite.anim.drawRectAnim.frameCount = 40; sprite.anim.drawRectAnim.horizontalFrameCount = 5; sprite.anim.drawRectAnim.frameRate = 27; @@ -854,53 +854,53 @@ void TestsRenderer::RunSpriteTest() } void TestsRenderer::RunNetworkTest() { - static wiSpriteFont font; + static wi::SpriteFont font; - wiNetwork::Connection connection; + wi::network::Connection connection; connection.ipaddress = { 127,0,0,1 }; // localhost connection.port = 12345; // just any random port really std::thread sender([&] { // Create sender socket: - wiNetwork::Socket sock; - wiNetwork::CreateSocket(&sock); + wi::network::Socket sock; + wi::network::CreateSocket(&sock); // Create a text message: const char message[] = "Hi, this is a text message sent over the network!\nYou can find out more in Tests.cpp, RunNetworkTest() function."; const size_t message_size = sizeof(message); // First, send the text message size: - wiNetwork::Send(&sock, &connection, &message_size, sizeof(message_size)); + wi::network::Send(&sock, &connection, &message_size, sizeof(message_size)); // Then send the actual text message: - wiNetwork::Send(&sock, &connection, message, message_size); + wi::network::Send(&sock, &connection, message, message_size); }); std::thread receiver([&] { // Create receiver socket: - wiNetwork::Socket sock; - wiNetwork::CreateSocket(&sock); + wi::network::Socket sock; + wi::network::CreateSocket(&sock); // Listen on the port which the sender uses: - wiNetwork::ListenPort(&sock, connection.port); + wi::network::ListenPort(&sock, connection.port); // We can check for incoming messages with CanReceive(). A timeout value can be specified in microseconds // to let the function block for some time, otherwise it returns imediately - // It is not necessary to use this, but the wiNetwork::Receive() will block until there is a message - if (wiNetwork::CanReceive(&sock, 1000000)) + // It is not necessary to use this, but the wi::network::Receive() will block until there is a message + if (wi::network::CanReceive(&sock, 1000000)) { // We know that we want a text message in this simple example, but we don't know the size. // We also know that the sender sends the text size before the actual text, so first we will receive the text size: size_t message_size; - wiNetwork::Connection sender_connection; // this will be filled out with the sender's address - wiNetwork::Receive(&sock, &sender_connection, &message_size, sizeof(message_size)); + wi::network::Connection sender_connection; // this will be filled out with the sender's address + wi::network::Receive(&sock, &sender_connection, &message_size, sizeof(message_size)); - if (wiNetwork::CanReceive(&sock, 1000000)) + if (wi::network::CanReceive(&sock, 1000000)) { // Once we know the text message length, we can receive the message itself: char* message = new char[message_size]; // allocate text buffer - wiNetwork::Receive(&sock, &sender_connection, message, message_size); + wi::network::Receive(&sock, &sender_connection, message, message_size); // Write the message to the screen: font.SetText(message); @@ -925,14 +925,14 @@ void TestsRenderer::RunNetworkTest() font.params.posX = GetLogicalWidth() / 2; font.params.posY = GetLogicalHeight() / 2; - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_CENTER; + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_CENTER; font.params.size = 24; AddFont(&font); } void TestsRenderer::RunUnorderedMapTest() { - wiTimer timer; + wi::Timer timer; const size_t elements = 1000000; #define shuffle(i) (i * 345734667877) % 98787546343 @@ -973,12 +973,12 @@ void TestsRenderer::RunUnorderedMapTest() ss += "wi::unordered_map access: " + std::to_string(timer.elapsed_milliseconds()) + " ms"; } - static wiSpriteFont font; - font = wiSpriteFont(ss); + static wi::SpriteFont font; + font = wi::SpriteFont(ss); font.params.posX = GetLogicalWidth() / 2; font.params.posY = GetLogicalHeight() / 2; - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_CENTER; + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_CENTER; font.params.size = 24; this->AddFont(&font); } diff --git a/Tests/Tests.h b/Tests/Tests.h index 61f1abe1a..dda7f9008 100644 --- a/Tests/Tests.h +++ b/Tests/Tests.h @@ -2,11 +2,11 @@ #include "WickedEngine.h" -class TestsRenderer : public RenderPath3D +class TestsRenderer : public wi::RenderPath3D { - wiLabel label; - wiComboBox testSelector; - wiECS::Entity ik_entity = wiECS::INVALID_ENTITY; + wi::gui::Label label; + wi::gui::ComboBox testSelector; + wi::ecs::Entity ik_entity = wi::ecs::INVALID_ENTITY; public: void Load() override; void Update(float dt) override; @@ -19,7 +19,7 @@ public: void RunUnorderedMapTest(); }; -class Tests : public MainComponent +class Tests : public wi::Application { TestsRenderer renderer; public: diff --git a/Tests/main_SDL2.cpp b/Tests/main_SDL2.cpp index 43c7fb6ca..49807e44b 100644 --- a/Tests/main_SDL2.cpp +++ b/Tests/main_SDL2.cpp @@ -53,7 +53,7 @@ int main(int argc, char *argv[]) Tests tests; // TODO: Place code here. - wiStartupArguments::Parse(argc, argv); + wi::arguments::Parse(argc, argv); sdl2::sdlsystem_ptr_t system = sdl2::make_sdlsystem(SDL_INIT_EVERYTHING | SDL_INIT_EVENTS); if (!system) { diff --git a/Tests/main_Windows.cpp b/Tests/main_Windows.cpp index 23feb29d8..508b7d62c 100644 --- a/Tests/main_Windows.cpp +++ b/Tests/main_Windows.cpp @@ -31,7 +31,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE hInstance, BOOL dpi_success = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); assert(dpi_success); - wiStartupArguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... + wi::arguments::Parse(lpCmdLine); // if you wish to use command line arguments, here is a good place to parse them... // Initialize global strings LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); @@ -162,26 +162,26 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) switch (wParam) { case VK_BACK: - if (wiBackLog::isActive()) - wiBackLog::deletefromInput(); - wiTextInputField::DeleteFromInput(); + if (wi::backlog::isActive()) + wi::backlog::deletefromInput(); + wi::gui::TextInputField::DeleteFromInput(); break; case VK_RETURN: break; default: { const char c = (const char)(TCHAR)wParam; - if (wiBackLog::isActive()) + if (wi::backlog::isActive()) { - wiBackLog::input(c); + wi::backlog::input(c); } - wiTextInputField::AddInput(c); + wi::gui::TextInputField::AddInput(c); } break; } break; case WM_INPUT: - wiRawInput::ParseMessage((void*)lParam); + wi::input::rawinput::ParseMessage((void*)lParam); break; case WM_KILLFOCUS: tests.is_window_active = false; diff --git a/WickedEngine/ArchiveVersionHistory.txt b/WickedEngine/ArchiveVersionHistory.txt index 1fcf52d03..655300f99 100644 --- a/WickedEngine/ArchiveVersionHistory.txt +++ b/WickedEngine/ArchiveVersionHistory.txt @@ -1,6 +1,6 @@ -This file contains changelog of wiArchive versions +This file contains changelog of wi::Archive versions -73: wiArchive no longer saves null terminator for strings +73: wi::Archive no longer saves null terminator for strings 72: Scene::Entity_Serialize() recursive serialization 71: serialized WeatherComponent::fogHeightStart and fogHeightEnd 70: serialized VolumetricCloudParameters @@ -10,7 +10,7 @@ This file contains changelog of wiArchive versions 66: serialized WeatherComponent::atmosphereParameters and skyExposure 65: serialized CameraComponent focal_length, aperture_size and aperture_shape 64: serialized per-emitter gravity, velocity, drag and random_color -63: serialized wiResourceManager embedded resources +63: serialized wi::resource_manager embedded resources 62: serialized WeatherComponent::colorGradingMapName property 61: serialized sheen and clearcoat material properties 60: serializer ObjectComponent::emissiveColor diff --git a/WickedEngine/CMakeLists.txt b/WickedEngine/CMakeLists.txt index 3da0ddfa1..79a259116 100644 --- a/WickedEngine/CMakeLists.txt +++ b/WickedEngine/CMakeLists.txt @@ -34,27 +34,26 @@ add_subdirectory(LUA) add_subdirectory(Utility) add_library(${TARGET_NAME} STATIC - LoadingScreen.cpp - LoadingScreen_BindLua.cpp - MainComponent.cpp - MainComponent_BindLua.cpp - Matrix_BindLua.cpp - RenderPath_BindLua.cpp - RenderPath2D.cpp - RenderPath2D_BindLua.cpp - RenderPath3D.cpp - RenderPath3D_BindLua.cpp - RenderPath3D_PathTracing.cpp - SpriteAnim_BindLua.cpp - Texture_BindLua.cpp - Vector_BindLua.cpp + wiLoadingScreen.cpp + wiLoadingScreen_BindLua.cpp + wiApplication.cpp + wiApplication_BindLua.cpp + wiRenderPath_BindLua.cpp + wiRenderPath2D.cpp + wiRenderPath2D_BindLua.cpp + wiRenderPath3D.cpp + wiRenderPath3D_BindLua.cpp + wiRenderPath3D_PathTracing.cpp + wiSpriteAnim_BindLua.cpp + wiTexture_BindLua.cpp + wiMath_BindLua.cpp wiArchive.cpp wiAudio.cpp wiAudio_BindLua.cpp - wiBackLog.cpp - wiBackLog_BindLua.cpp + wiBacklog.cpp + wiBacklog_BindLua.cpp wiEmittedParticle.cpp - wiEvent.cpp + wiEventHandler.cpp wiFadeManager.cpp wiFFTGenerator.cpp wiFont.cpp @@ -70,8 +69,8 @@ add_library(${TARGET_NAME} STATIC wiInitializer.cpp wiInput.cpp wiInput_BindLua.cpp - wiIntersect.cpp - wiIntersect_BindLua.cpp + wiPrimitive.cpp + wiPrimitive_BindLua.cpp wiJobSystem.cpp wiLua.cpp wiMath.cpp @@ -80,7 +79,7 @@ add_library(${TARGET_NAME} STATIC wiNetwork_Windows.cpp wiNetwork_UWP.cpp wiOcean.cpp - wiPhysicsEngine_Bullet.cpp + wiPhysics_Bullet.cpp wiProfiler.cpp wiRandom.cpp wiRawInput.cpp @@ -96,10 +95,9 @@ add_library(${TARGET_NAME} STATIC wiSprite_BindLua.cpp wiSpriteFont.cpp wiSpriteFont_BindLua.cpp - wiStartupArguments.cpp + wiArguments.cpp wiTextureHelper.cpp wiVersion.cpp - wiWidget.cpp wiXInput.cpp wiShaderCompiler.cpp ) diff --git a/WickedEngine/CommonInclude.h b/WickedEngine/CommonInclude.h index 91cfb15c8..67db9d04e 100644 --- a/WickedEngine/CommonInclude.h +++ b/WickedEngine/CommonInclude.h @@ -52,6 +52,14 @@ constexpr typename std::enable_if::enable, E&>::type return lhs; } template +constexpr typename std::enable_if::enable, E>::type operator~(E rhs) +{ + typedef typename std::underlying_type::type underlying; + rhs = static_cast( + ~static_cast(rhs)); + return rhs; +} +template constexpr bool has_flag(E lhs, E rhs) { return (lhs & rhs) == rhs; diff --git a/WickedEngine/LoadingScreen.cpp b/WickedEngine/LoadingScreen.cpp deleted file mode 100644 index 1e1152192..000000000 --- a/WickedEngine/LoadingScreen.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "LoadingScreen.h" -#include "MainComponent.h" - -#include - -bool LoadingScreen::isActive() -{ - return wiJobSystem::IsBusy(ctx); -} - -void LoadingScreen::addLoadingFunction(std::function loadingFunction) -{ - if (loadingFunction != nullptr) - { - tasks.push_back(loadingFunction); - } -} - -void LoadingScreen::addLoadingComponent(RenderPath* component, MainComponent* main, float fadeSeconds, wiColor fadeColor) -{ - addLoadingFunction([=](wiJobArgs args) { - component->Load(); - }); - onFinished([=] { - main->ActivatePath(component, fadeSeconds, fadeColor); - }); -} - -void LoadingScreen::onFinished(std::function finishFunction) -{ - if (finishFunction != nullptr) - finish = finishFunction; -} - -void LoadingScreen::Start() -{ - for (auto& x : tasks) - { - wiJobSystem::Execute(ctx, x); - } - std::thread([this]() { - wiJobSystem::Wait(ctx); - finish(); - }).detach(); - - RenderPath2D::Start(); -} - -void LoadingScreen::Stop() -{ - tasks.clear(); - finish = nullptr; - - RenderPath2D::Stop(); -} - diff --git a/WickedEngine/LoadingScreen.h b/WickedEngine/LoadingScreen.h deleted file mode 100644 index 08a6b5c5b..000000000 --- a/WickedEngine/LoadingScreen.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -#include "RenderPath2D.h" -#include "wiColor.h" -#include "wiJobSystem.h" -#include "wiVector.h" - -#include - -class MainComponent; - -class LoadingScreen : - public RenderPath2D -{ -private: - wiJobSystem::context ctx; - wi::vector> tasks; - std::function finish; -public: - - //Add a loading task which should be executed - //use std::bind( YourFunctionPointer ) - void addLoadingFunction(std::function loadingFunction); - //Helper for loading a whole renderable component - void addLoadingComponent(RenderPath* component, MainComponent* main, float fadeSeconds = 0, wiColor fadeColor = wiColor(0, 0, 0, 255)); - //Set a function that should be called when the loading finishes - //use std::bind( YourFunctionPointer ) - void onFinished(std::function finishFunction); - //See if the loading is currently running - bool isActive(); - - //Start Executing the tasks and mark the loading as active - virtual void Start() override; - //Clear all tasks - virtual void Stop() override; -}; - diff --git a/WickedEngine/LoadingScreen_BindLua.cpp b/WickedEngine/LoadingScreen_BindLua.cpp deleted file mode 100644 index 60f37ee12..000000000 --- a/WickedEngine/LoadingScreen_BindLua.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include "LoadingScreen_BindLua.h" - -const char LoadingScreen_BindLua::className[] = "LoadingScreen"; - -Luna::FunctionType LoadingScreen_BindLua::methods[] = { - lunamethod(RenderPath2D_BindLua, AddSprite), - lunamethod(RenderPath2D_BindLua, AddFont), - lunamethod(RenderPath2D_BindLua, RemoveSprite), - lunamethod(RenderPath2D_BindLua, RemoveFont), - lunamethod(RenderPath2D_BindLua, ClearSprites), - lunamethod(RenderPath2D_BindLua, ClearFonts), - lunamethod(RenderPath2D_BindLua, GetSpriteOrder), - lunamethod(RenderPath2D_BindLua, GetFontOrder), - lunamethod(RenderPath2D_BindLua, AddLayer), - lunamethod(RenderPath2D_BindLua, GetLayers), - lunamethod(RenderPath2D_BindLua, SetLayerOrder), - lunamethod(RenderPath2D_BindLua, SetSpriteOrder), - lunamethod(RenderPath2D_BindLua, SetFontOrder), - - lunamethod(RenderPath_BindLua, GetLayerMask), - lunamethod(RenderPath_BindLua, SetLayerMask), - - lunamethod(LoadingScreen_BindLua, AddLoadingTask), - lunamethod(LoadingScreen_BindLua, OnFinished), - { NULL, NULL } -}; -Luna::PropertyType LoadingScreen_BindLua::properties[] = { - { NULL, NULL } -}; - -int LoadingScreen_BindLua::AddLoadingTask(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - std::string task = wiLua::SGetString(L, 1); - LoadingScreen* loading = dynamic_cast(component); - if (loading != nullptr) - { - loading->addLoadingFunction([=](wiJobArgs args) { - wiLua::RunText(task); - }); - } - else - wiLua::SError(L, "AddLoader(string taskScript) component is not a LoadingScreen!"); - } - else - wiLua::SError(L, "AddLoader(string taskScript) not enough arguments!"); - return 0; -} -int LoadingScreen_BindLua::OnFinished(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - std::string task = wiLua::SGetString(L, 1); - LoadingScreen* loading = dynamic_cast(component); - if (loading != nullptr) - { - loading->onFinished([=] { - wiLua::RunText(task); - }); - } - else - wiLua::SError(L, "OnFinished(string taskScript) component is not a LoadingScreen!"); - } - else - wiLua::SError(L, "OnFinished(string taskScript) not enough arguments!"); - return 0; -} - -void LoadingScreen_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} diff --git a/WickedEngine/LoadingScreen_BindLua.h b/WickedEngine/LoadingScreen_BindLua.h deleted file mode 100644 index a11aece1d..000000000 --- a/WickedEngine/LoadingScreen_BindLua.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "LoadingScreen.h" -#include "RenderPath2D_BindLua.h" - -class LoadingScreen_BindLua : public RenderPath2D_BindLua -{ -private: - LoadingScreen loadingscreen; -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - LoadingScreen_BindLua(LoadingScreen* component) - { - this->component = component; - } - LoadingScreen_BindLua(lua_State* L) - { - this->component = &loadingscreen; - } - - int AddLoadingTask(lua_State* L); - int OnFinished(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/MainComponent.cpp b/WickedEngine/MainComponent.cpp deleted file mode 100644 index 9d6511fe0..000000000 --- a/WickedEngine/MainComponent.cpp +++ /dev/null @@ -1,531 +0,0 @@ -#include "MainComponent.h" -#include "RenderPath.h" -#include "wiRenderer.h" -#include "wiHelper.h" -#include "wiTimer.h" -#include "wiInput.h" -#include "wiBackLog.h" -#include "MainComponent_BindLua.h" -#include "wiVersion.h" -#include "wiEnums.h" -#include "wiTextureHelper.h" -#include "wiProfiler.h" -#include "wiInitializer.h" -#include "wiStartupArguments.h" -#include "wiFont.h" -#include "wiImage.h" -#include "wiEvent.h" - -#include "wiGraphicsDevice_DX12.h" -#include "wiGraphicsDevice_Vulkan.h" - -#include -#include -#include -#include -#include - -std::atomic number_of_heap_allocations{ 0 }; -std::atomic size_of_heap_allocations{ 0 }; - -using namespace wiGraphics; - -void MainComponent::Initialize() -{ - if (initialized) - { - return; - } - initialized = true; - - wiInitializer::InitializeComponentsAsync(); -} - -void MainComponent::ActivatePath(RenderPath* component, float fadeSeconds, wiColor fadeColor) -{ - if (component != nullptr) - { - component->init(canvas); - } - - // Fade manager will activate on fadeout - fadeManager.Clear(); - fadeManager.Start(fadeSeconds, fadeColor, [this, component]() { - - if (GetActivePath() != nullptr) - { - GetActivePath()->Stop(); - } - - if (component != nullptr) - { - component->Start(); - } - activePath = component; - }); - - fadeManager.Update(0); // If user calls ActivatePath without fadeout, it will be instant -} - -void MainComponent::Run() -{ - - if (!initialized) - { - // Initialize in a lazy way, so the user application doesn't have to call this explicitly - Initialize(); - initialized = true; - } - if (!wiInitializer::IsInitializeFinished()) - { - // Until engine is not loaded, present initialization screen... - CommandList cmd = graphicsDevice->BeginCommandList(); - graphicsDevice->RenderPassBegin(&swapChain, cmd); - wiImage::SetCanvas(canvas, cmd); - wiFont::SetCanvas(canvas, cmd); - Viewport viewport; - viewport.width = (float)swapChain.desc.width; - viewport.height = (float)swapChain.desc.height; - graphicsDevice->BindViewports(1, &viewport, cmd); - wiFontParams params; - params.posX = 5.f; - params.posY = 5.f; - std::string text = wiBackLog::getText(); - float textheight = wiFont::textHeight(text, params); - float screenheight = canvas.GetLogicalHeight(); - if (textheight > screenheight) - { - params.posY = screenheight - textheight; - } - wiFont::Draw(text, params, cmd); - graphicsDevice->RenderPassEnd(cmd); - graphicsDevice->SubmitCommandLists(); - return; - } - - static bool startup_script = false; - if (!startup_script) - { - startup_script = true; - wiLua::RegisterObject(MainComponent_BindLua::className, "main", new MainComponent_BindLua(this)); - wiLua::RunFile("startup.lua"); - } - - if (!is_window_active) - { - // If the application is not active, disable Update loops: - deltaTimeAccumulator = 0; - return; - } - - wiProfiler::BeginFrame(); - - deltaTime = float(std::max(0.0, timer.elapsed() / 1000.0)); - timer.record(); - - // Wake up the events that need to be executed on the main thread, in thread safe manner: - wiEvent::FireEvent(SYSTEM_EVENT_THREAD_SAFE_POINT, 0); - - const float dt = framerate_lock ? (1.0f / targetFrameRate) : deltaTime; - - fadeManager.Update(dt); - - ColorSpace colorspace = graphicsDevice->GetSwapChainColorSpace(&swapChain); - - if (GetActivePath() != nullptr) - { - GetActivePath()->colorspace = colorspace; - GetActivePath()->init(canvas); - GetActivePath()->PreUpdate(); - } - - // Fixed time update: - auto range = wiProfiler::BeginRangeCPU("Fixed Update"); - { - if (frameskip) - { - deltaTimeAccumulator += dt; - if (deltaTimeAccumulator > 10) - { - // application probably lost control, fixed update would take too long - deltaTimeAccumulator = 0; - } - - const float targetFrameRateInv = 1.0f / targetFrameRate; - while (deltaTimeAccumulator >= targetFrameRateInv) - { - FixedUpdate(); - deltaTimeAccumulator -= targetFrameRateInv; - } - } - else - { - FixedUpdate(); - } - } - wiProfiler::EndRange(range); // Fixed Update - - // Variable-timed update: - Update(dt); - - Render(); - - wiInput::Update(window); - - // Begin final compositing: - CommandList cmd = graphicsDevice->BeginCommandList(); - wiImage::SetCanvas(canvas, cmd); - wiFont::SetCanvas(canvas, cmd); - Viewport viewport; - viewport.width = (float)swapChain.desc.width; - viewport.height = (float)swapChain.desc.height; - graphicsDevice->BindViewports(1, &viewport, cmd); - - bool colorspace_conversion_required = colorspace == ColorSpace::HDR10_ST2084; - if (colorspace_conversion_required) - { - // In HDR10, we perform the compositing in a custom linear color space render target - graphicsDevice->RenderPassBegin(&renderpass, cmd); - } - else - { - // If swapchain is SRGB or Linear HDR, it can be used for blending - // - If it is SRGB, the render path will ensure tonemapping to SDR - // - If it is Linear HDR, we can blend trivially in linear space - graphicsDevice->RenderPassBegin(&swapChain, cmd); - } - Compose(cmd); - graphicsDevice->RenderPassEnd(cmd); - - if (colorspace_conversion_required) - { - // In HDR10, we perform a final mapping from linear to HDR10, into the swapchain - graphicsDevice->RenderPassBegin(&swapChain, cmd); - wiImageParams fx; - fx.enableFullScreen(); - fx.enableHDR10OutputMapping(); - wiImage::Draw(&rendertarget, fx, cmd); - graphicsDevice->RenderPassEnd(cmd); - } - - wiProfiler::EndFrame(cmd); - graphicsDevice->SubmitCommandLists(); -} - -void MainComponent::Update(float dt) -{ - auto range = wiProfiler::BeginRangeCPU("Update"); - - wiLua::SetDeltaTime(double(dt)); - wiLua::Update(); - - wiBackLog::Update(canvas, dt); - - if (GetActivePath() != nullptr) - { - GetActivePath()->Update(dt); - GetActivePath()->PostUpdate(); - } - - wiProfiler::EndRange(range); // Update -} - -void MainComponent::FixedUpdate() -{ - wiLua::FixedUpdate(); - - if (GetActivePath() != nullptr) - { - GetActivePath()->FixedUpdate(); - } -} - -void MainComponent::Render() -{ - auto range = wiProfiler::BeginRangeCPU("Render"); - - wiLua::Render(); - - if (GetActivePath() != nullptr) - { - GetActivePath()->Render(); - } - - wiProfiler::EndRange(range); // Render -} - -void MainComponent::Compose(CommandList cmd) -{ - auto range = wiProfiler::BeginRangeCPU("Compose"); - - if (GetActivePath() != nullptr) - { - GetActivePath()->Compose(cmd); - } - - if (fadeManager.IsActive()) - { - // display fade rect - static wiImageParams fx; - fx.siz.x = canvas.GetLogicalWidth(); - fx.siz.y = canvas.GetLogicalHeight(); - fx.opacity = fadeManager.opacity; - wiImage::Draw(wiTextureHelper::getColor(fadeManager.color), fx, cmd); - } - - // Draw the information display - if (infoDisplay.active) - { - infodisplay_str.clear(); - if (infoDisplay.watermark) - { - infodisplay_str += "Wicked Engine "; - infodisplay_str += wiVersion::GetVersionString(); - infodisplay_str += " "; - -#if defined(_ARM) - infodisplay_str += "[ARM]"; -#elif defined(_WIN64) - infodisplay_str += "[64-bit]"; -#elif defined(_WIN32) - infodisplay_str += "[32-bit]"; -#endif - -#ifdef PLATFORM_UWP - infodisplay_str += "[UWP]"; -#endif - -#ifdef WICKEDENGINE_BUILD_DX12 - if (dynamic_cast(graphicsDevice.get())) - { - infodisplay_str += "[DX12]"; - } -#endif -#ifdef WICKEDENGINE_BUILD_VULKAN - if (dynamic_cast(graphicsDevice.get())) - { - infodisplay_str += "[Vulkan]"; - } -#endif - -#ifdef _DEBUG - infodisplay_str += "[DEBUG]"; -#endif - if (graphicsDevice->IsDebugDevice()) - { - infodisplay_str += "[debugdevice]"; - } - infodisplay_str += "\n"; - } - if (infoDisplay.resolution) - { - infodisplay_str += "Resolution: " + std::to_string(canvas.GetPhysicalWidth()) + " x " + std::to_string(canvas.GetPhysicalHeight()) + " (" + std::to_string(int(canvas.GetDPI())) + " dpi)\n"; - } - if (infoDisplay.logical_size) - { - infodisplay_str += "Logical Size: " + std::to_string(int(canvas.GetLogicalWidth())) + " x " + std::to_string(int(canvas.GetLogicalHeight())) + "\n"; - } - if (infoDisplay.colorspace) - { - infodisplay_str += "Color Space: "; - ColorSpace colorSpace = graphicsDevice->GetSwapChainColorSpace(&swapChain); - switch (colorSpace) - { - default: - case wiGraphics::ColorSpace::SRGB: - infodisplay_str += "sRGB"; - break; - case wiGraphics::ColorSpace::HDR10_ST2084: - infodisplay_str += "ST.2084 (HDR10)"; - break; - case wiGraphics::ColorSpace::HDR_LINEAR: - infodisplay_str += "Linear (HDR)"; - break; - } - infodisplay_str += "\n"; - } - if (infoDisplay.fpsinfo) - { - deltatimes[fps_avg_counter++ % arraysize(deltatimes)] = deltaTime; - float displaydeltatime = deltaTime; - if (fps_avg_counter > arraysize(deltatimes)) - { - float avg_time = 0; - for (int i = 0; i < arraysize(deltatimes); ++i) - { - avg_time += deltatimes[i]; - } - displaydeltatime = avg_time / arraysize(deltatimes); - } - - infodisplay_str += std::to_string(int(std::round(1.0f / displaydeltatime))) + " FPS\n"; - } - if (infoDisplay.heap_allocation_counter) - { - infodisplay_str += "Heap allocations per frame: " + std::to_string(number_of_heap_allocations.load()) + " (" + std::to_string(size_of_heap_allocations.load()) + " bytes)\n"; - number_of_heap_allocations.store(0); - size_of_heap_allocations.store(0); - } - if (infoDisplay.pipeline_count) - { - infodisplay_str += "Graphics pipelines active: " + std::to_string(graphicsDevice->GetActivePipelineCount()) + "\n"; - } - -#ifdef _DEBUG - infodisplay_str += "Warning: This is a [DEBUG] build, performance will be slow!\n"; -#endif - if (graphicsDevice->IsDebugDevice()) - { - infodisplay_str += "Warning: Graphics is in [debugdevice] mode, performance will be slow!\n"; - } - - wiFont::Draw(infodisplay_str, wiFontParams(4, 4, infoDisplay.size, WIFALIGN_LEFT, WIFALIGN_TOP, wiColor(255,255,255,255), wiColor(0,0,0,255)), cmd); - - if (infoDisplay.colorgrading_helper) - { - wiImage::Draw(wiTextureHelper::getColorGradeDefault(), wiImageParams(0, 0, 256.0f / canvas.GetDPIScaling(), 16.0f / canvas.GetDPIScaling()), cmd); - } - } - - wiProfiler::DrawData(canvas, 4, 120, cmd); - - wiBackLog::Draw(canvas, cmd); - - wiProfiler::EndRange(range); // Compose -} - -void MainComponent::SetWindow(wiPlatform::window_type window, bool fullscreen) -{ - this->window = window; - - // User can also create a graphics device if custom logic is desired, but they must do before this function! - if (graphicsDevice == nullptr) - { - bool debugdevice = wiStartupArguments::HasArgument("debugdevice"); - bool gpuvalidation = wiStartupArguments::HasArgument("gpuvalidation"); - - bool use_dx12 = wiStartupArguments::HasArgument("dx12"); - bool use_vulkan = wiStartupArguments::HasArgument("vulkan"); - -#ifndef WICKEDENGINE_BUILD_DX12 - if (use_dx12) { - wiHelper::messageBox("The engine was built without DX12 support!", "Error"); - use_dx12 = false; - } -#endif -#ifndef WICKEDENGINE_BUILD_VULKAN - if (use_vulkan) { - wiHelper::messageBox("The engine was built without Vulkan support!", "Error"); - use_vulkan = false; - } -#endif - - if (!use_dx12 && !use_vulkan) - { -#if defined(WICKEDENGINE_BUILD_DX12) - use_dx12 = true; -#elif defined(WICKEDENGINE_BUILD_VULKAN) - use_vulkan = true; -#else - wiBackLog::post("No rendering backend is enabled! Please enable at least one so we can use it as default", wiBackLog::LogLevel::Error); - assert(false); -#endif - } - assert(use_dx12 || use_vulkan); - - if (use_vulkan) - { -#ifdef WICKEDENGINE_BUILD_VULKAN - wiRenderer::SetShaderPath(wiRenderer::GetShaderPath() + "spirv/"); - graphicsDevice = std::make_unique(window, debugdevice); -#endif - } - else if (use_dx12) - { -#ifdef WICKEDENGINE_BUILD_DX12 - wiRenderer::SetShaderPath(wiRenderer::GetShaderPath() + "hlsl6/"); - graphicsDevice = std::make_unique(debugdevice, gpuvalidation); -#endif - } - } - wiGraphics::GetDevice() = graphicsDevice.get(); - wiRenderer::InitializeCommonSamplers(); - - canvas.init(window); - - SwapChainDesc desc; - if (swapChain.IsValid()) - { - // it will only resize, but keep format and other settings - desc = swapChain.desc; - } - else - { - // initialize for the first time - desc.buffer_count = 3; - desc.format = Format::R10G10B10A2_UNORM; - } - desc.width = canvas.GetPhysicalWidth(); - desc.height = canvas.GetPhysicalHeight(); - desc.allow_hdr = allow_hdr; - bool success = graphicsDevice->CreateSwapChain(&desc, window, &swapChain); - assert(success); - - swapChainVsyncChangeEvent = wiEvent::Subscribe(SYSTEM_EVENT_SET_VSYNC, [this](uint64_t userdata) { - SwapChainDesc desc = swapChain.desc; - desc.vsync = userdata != 0; - bool success = graphicsDevice->CreateSwapChain(&desc, nullptr, &swapChain); - assert(success); - }); - - if (graphicsDevice->GetSwapChainColorSpace(&swapChain) == ColorSpace::HDR10_ST2084) - { - TextureDesc desc; - desc.width = swapChain.desc.width; - desc.height = swapChain.desc.height; - desc.format = Format::R11G11B10_FLOAT; - desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; - bool success = graphicsDevice->CreateTexture(&desc, nullptr, &rendertarget); - assert(success); - graphicsDevice->SetName(&rendertarget, "MainComponent::rendertarget"); - - RenderPassDesc renderpassdesc; - renderpassdesc.attachments.push_back(RenderPassAttachment::RenderTarget(&rendertarget, RenderPassAttachment::LoadOp::CLEAR)); - success = graphicsDevice->CreateRenderPass(&renderpassdesc, &renderpass); - assert(success); - } -} - - -// Heap alloc replacements are used to count heap allocations: -// It is good practice to reduce the amount of heap allocations that happen during the frame, -// so keep an eye on the info display of the engine while MainComponent::InfoDisplayer::heap_allocation_counter is enabled - -void* operator new(std::size_t size) { - number_of_heap_allocations.fetch_add(1); - size_of_heap_allocations.fetch_add(size); - void* p = malloc(size); - if (!p) throw std::bad_alloc(); - return p; -} -void* operator new[](std::size_t size) { - number_of_heap_allocations.fetch_add(1); - size_of_heap_allocations.fetch_add(size); - void* p = malloc(size); - if (!p) throw std::bad_alloc(); - return p; -} -void* operator new[](std::size_t size, const std::nothrow_t&) throw() { - number_of_heap_allocations.fetch_add(1); - size_of_heap_allocations.fetch_add(size); - return malloc(size); -} -void* operator new(std::size_t size, const std::nothrow_t&) throw() { - number_of_heap_allocations.fetch_add(1); - size_of_heap_allocations.fetch_add(size); - return malloc(size); -} -void operator delete(void* ptr) throw() { free(ptr); } -void operator delete (void* ptr, const std::nothrow_t&) throw() { free(ptr); } -void operator delete[](void* ptr) throw() { free(ptr); } -void operator delete[](void* ptr, const std::nothrow_t&) throw() { free(ptr); } diff --git a/WickedEngine/MainComponent.h b/WickedEngine/MainComponent.h deleted file mode 100644 index fc07d58ad..000000000 --- a/WickedEngine/MainComponent.h +++ /dev/null @@ -1,116 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiPlatform.h" -#include "wiResourceManager.h" -#include "wiColor.h" -#include "wiFadeManager.h" -#include "wiGraphics.h" -#include "wiEvent.h" -#include "wiCanvas.h" - -#include -#include - -class RenderPath; - -class MainComponent -{ -protected: - std::unique_ptr graphicsDevice; - wiEvent::Handle swapChainVsyncChangeEvent; - - RenderPath* activePath = nullptr; - float targetFrameRate = 60; - bool frameskip = true; - bool framerate_lock = false; - bool initialized = false; - - wiFadeManager fadeManager; - - float deltaTime = 0; - float deltaTimeAccumulator = 0; - wiTimer timer; - - float deltatimes[20] = {}; - int fps_avg_counter = 0; - - // These are used when HDR10 color space is active: - // Because we want to blend in linear color space, but HDR10 is non-linear - wiGraphics::Texture rendertarget; - wiGraphics::RenderPass renderpass; - - std::string infodisplay_str; - -public: - virtual ~MainComponent() = default; - - bool is_window_active = true; - bool allow_hdr = true; - wiGraphics::SwapChain swapChain; - wiCanvas canvas; - wiPlatform::window_type window; - - // Runs the main engine loop - void Run(); - - // This will activate a RenderPath as the active one, so it will run its Update, FixedUpdate, Render and Compose functions - // You can set a fade time and fade screen color so that switching components will happen when the screen is faded out. Then it will fade back to the new component - void ActivatePath(RenderPath* component, float fadeSeconds = 0, wiColor fadeColor = wiColor(0,0,0,255)); - inline RenderPath* GetActivePath(){ return activePath; } - - // Set the desired target framerate for the FixedUpdate() loop (default = 60) - void setTargetFrameRate(float value) { targetFrameRate = value; } - // Get the desired target framerate for the FixedUpdate() loop - float getTargetFrameRate() const { return targetFrameRate; } - // Set the desired behaviour of the FixedUpdate() loop (default = true) - // enabled : the FixedUpdate() loop will run at targetFrameRate frequency - // disabled : the FixedUpdate() loop will run every frame only once. - void setFrameSkip(bool enabled) { frameskip = enabled; } - void setFrameRateLock(bool enabled) { framerate_lock = enabled; } - - // This is where the critical initializations happen (before any rendering or anything else) - virtual void Initialize(); - // This is where application-wide updates get executed once per frame. - // RenderPath::Update is also called from here for the active component - virtual void Update(float dt); - // This is where application-wide updates get executed in a fixed timestep based manner. - // RenderPath::FixedUpdate is also called from here for the active component - virtual void FixedUpdate(); - // This is where application-wide rendering happens to offscreen buffers. - // RenderPath::Render is also called from here for the active component - virtual void Render(); - // This is where the application will render to the screen (backbuffer). It must render to the provided command list. - virtual void Compose(wiGraphics::CommandList cmd); - - // You need to call this before calling Run() or Initialize() if you want to render - void SetWindow(wiPlatform::window_type, bool fullscreen = false); - - - struct InfoDisplayer - { - // activate the whole display - bool active = false; - // display engine version number - bool watermark = true; - // display framerate - bool fpsinfo = false; - // display resolution info - bool resolution = false; - // window's size in logical (DPI scaled) units - bool logical_size = false; - // HDR status and color space - bool colorspace = false; - // display number of heap allocations per frame - bool heap_allocation_counter = false; - // display the active graphics pipeline count - bool pipeline_count = false; - // text size - int size = 16; - // display default color grading helper texture in top left corner of the screen - bool colorgrading_helper = false; - }; - // display all-time engine information text - InfoDisplayer infoDisplay; - -}; - diff --git a/WickedEngine/MainComponent_BindLua.cpp b/WickedEngine/MainComponent_BindLua.cpp deleted file mode 100644 index dc27291dd..000000000 --- a/WickedEngine/MainComponent_BindLua.cpp +++ /dev/null @@ -1,412 +0,0 @@ -#include "MainComponent_BindLua.h" -#include "RenderPath_BindLua.h" -#include "RenderPath3D_BindLua.h" -#include "RenderPath2D_BindLua.h" -#include "LoadingScreen_BindLua.h" -#include "wiProfiler.h" - -const char MainComponent_BindLua::className[] = "MainComponent"; - -Luna::FunctionType MainComponent_BindLua::methods[] = { - lunamethod(MainComponent_BindLua, GetActivePath), - lunamethod(MainComponent_BindLua, SetActivePath), - lunamethod(MainComponent_BindLua, SetFrameSkip), - lunamethod(MainComponent_BindLua, SetTargetFrameRate), - lunamethod(MainComponent_BindLua, SetFrameRateLock), - lunamethod(MainComponent_BindLua, SetInfoDisplay), - lunamethod(MainComponent_BindLua, SetWatermarkDisplay), - lunamethod(MainComponent_BindLua, SetFPSDisplay), - lunamethod(MainComponent_BindLua, SetResolutionDisplay), - lunamethod(MainComponent_BindLua, SetLogicalSizeDisplay), - lunamethod(MainComponent_BindLua, SetPipelineCountDisplay), - lunamethod(MainComponent_BindLua, SetHeapAllocationCountDisplay), - lunamethod(MainComponent_BindLua, GetCanvas), - { NULL, NULL } -}; -Luna::PropertyType MainComponent_BindLua::properties[] = { - { NULL, NULL } -}; - -MainComponent_BindLua::MainComponent_BindLua(MainComponent* component) :component(component) -{ -} - -MainComponent_BindLua::MainComponent_BindLua(lua_State *L) -{ - component = nullptr; -} - -int MainComponent_BindLua::GetActivePath(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "GetActivePath() component is empty!"); - return 0; - } - - //return 3d component if the active one is of that type - RenderPath3D* comp3D = dynamic_cast(component->GetActivePath()); - if (comp3D != nullptr) - { - Luna::push(L, new RenderPath3D_BindLua(comp3D)); - return 1; - } - - //return loading component if the active one is of that type - LoadingScreen* compLoad = dynamic_cast(component->GetActivePath()); - if (compLoad != nullptr) - { - Luna::push(L, new LoadingScreen_BindLua(compLoad)); - return 1; - } - - //return 2d component if the active one is of that type - RenderPath2D* comp2D = dynamic_cast(component->GetActivePath()); - if (comp2D != nullptr) - { - Luna::push(L, new RenderPath2D_BindLua(comp2D)); - return 1; - } - - //return component if the active one is of that type - RenderPath* comp = dynamic_cast(component->GetActivePath()); - if (comp != nullptr) - { - Luna::push(L, new RenderPath_BindLua(comp)); - return 1; - } - - wiLua::SError(L, "GetActivePath() Warning: type of active component not registered!"); - return 0; -} -int MainComponent_BindLua::SetActivePath(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetActivePath(RenderPath component) component is empty!"); - return 0; - } - - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - float fadeSeconds = 0; - wiColor fadeColor = wiColor(0, 0, 0, 255); - if (argc > 1) - { - fadeSeconds = wiLua::SGetFloat(L, 2); - if (argc > 2) - { - fadeColor.setR((uint8_t)wiLua::SGetInt(L, 3)); - if (argc > 3) - { - fadeColor.setG((uint8_t)wiLua::SGetInt(L, 4)); - if (argc > 4) - { - fadeColor.setB((uint8_t)wiLua::SGetInt(L, 5)); - } - } - } - } - - RenderPath3D_BindLua* comp3D = Luna::lightcheck(L, 1); - if (comp3D != nullptr) - { - component->ActivatePath(comp3D->component, fadeSeconds, fadeColor); - return 0; - } - - LoadingScreen_BindLua* compLoad = Luna::lightcheck(L, 1); - if (compLoad != nullptr) - { - component->ActivatePath(compLoad->component, fadeSeconds, fadeColor); - return 0; - } - - RenderPath2D_BindLua* comp2D = Luna::lightcheck(L, 1); - if (comp2D != nullptr) - { - component->ActivatePath(comp2D->component, fadeSeconds, fadeColor); - return 0; - } - - RenderPath_BindLua* comp = Luna::lightcheck(L, 1); - if (comp != nullptr) - { - component->ActivatePath(comp->component, fadeSeconds, fadeColor); - return 0; - } - } - else - { - wiLua::SError(L, "SetActivePath(RenderPath component, opt int fadeFrames,fadeColorR,fadeColorG,fadeColorB) not enought arguments!"); - return 0; - } - return 0; -} -int MainComponent_BindLua::SetFrameSkip(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetFrameSkip(bool enabled) component is empty!"); - return 0; - } - - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->setFrameSkip(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetFrameSkip(bool enabled) not enought arguments!"); - return 0; -} -int MainComponent_BindLua::SetTargetFrameRate(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetTargetFrameRate(float value) component is empty!"); - return 0; - } - - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->setTargetFrameRate(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetTargetFrameRate(float value) not enought arguments!"); - return 0; -} -int MainComponent_BindLua::SetFrameRateLock(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetFrameRateLock(bool enabled) component is empty!"); - return 0; - } - - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->setFrameRateLock(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetFrameRateLock(bool enabled) not enought arguments!"); - return 0; -} -int MainComponent_BindLua::SetInfoDisplay(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetInfoDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.active = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetInfoDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetWatermarkDisplay(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetWatermarkDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.watermark = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetWatermarkDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetFPSDisplay(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetFPSDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.fpsinfo = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetFPSDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetResolutionDisplay(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetResolutionDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.resolution = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetResolutionDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetLogicalSizeDisplay(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetLogicalSizeDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.logical_size = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetLogicalSizeDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetPipelineCountDisplay(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetPipelineCountDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.pipeline_count = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetPipelineCountDisplay(bool active) not enough arguments!"); - return 0; -} -int MainComponent_BindLua::SetHeapAllocationCountDisplay(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetHeapAllocationCountDisplay() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - component->infoDisplay.heap_allocation_counter = wiLua::SGetBool(L, 1); - } - else - wiLua::SError(L, "SetHeapAllocationCountDisplay(bool active) not enough arguments!"); - return 0; -} - -int MainComponent_BindLua::GetCanvas(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "GetCanvas() component is empty!"); - return 0; - } - Luna::push(L, new Canvas_BindLua(component->canvas)); - return 1; -} - - -int SetProfilerEnabled(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiProfiler::SetEnabled(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetProfilerEnabled(bool active) not enough arguments!"); - - return 0; -} - -void MainComponent_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - - wiLua::RegisterFunc("SetProfilerEnabled", SetProfilerEnabled); - } -} - - - - - - - - - - -const char Canvas_BindLua::className[] = "Canvas"; - -Luna::FunctionType Canvas_BindLua::methods[] = { - lunamethod(Canvas_BindLua, GetDPI), - lunamethod(Canvas_BindLua, GetDPIScaling), - lunamethod(Canvas_BindLua, GetPhysicalWidth), - lunamethod(Canvas_BindLua, GetPhysicalHeight), - lunamethod(Canvas_BindLua, GetLogicalWidth), - lunamethod(Canvas_BindLua, GetLogicalHeight), - { NULL, NULL } -}; -Luna::PropertyType Canvas_BindLua::properties[] = { - { NULL, NULL } -}; - - -int Canvas_BindLua::GetDPI(lua_State* L) -{ - wiLua::SSetFloat(L, canvas.GetDPI()); - return 1; -} -int Canvas_BindLua::GetDPIScaling(lua_State* L) -{ - wiLua::SSetFloat(L, canvas.GetDPIScaling()); - return 1; -} -int Canvas_BindLua::GetPhysicalWidth(lua_State* L) -{ - wiLua::SSetInt(L, canvas.GetPhysicalWidth()); - return 1; -} -int Canvas_BindLua::GetPhysicalHeight(lua_State* L) -{ - wiLua::SSetInt(L, canvas.GetPhysicalHeight()); - return 1; -} -int Canvas_BindLua::GetLogicalWidth(lua_State* L) -{ - wiLua::SSetFloat(L, canvas.GetLogicalWidth()); - return 1; -} -int Canvas_BindLua::GetLogicalHeight(lua_State* L) -{ - wiLua::SSetFloat(L, canvas.GetLogicalHeight()); - return 1; -} - -void Canvas_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} diff --git a/WickedEngine/MainComponent_BindLua.h b/WickedEngine/MainComponent_BindLua.h deleted file mode 100644 index a64f862a2..000000000 --- a/WickedEngine/MainComponent_BindLua.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "MainComponent.h" - -class Canvas_BindLua -{ -public: - wiCanvas canvas; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - Canvas_BindLua(const wiCanvas& canvas) : canvas(canvas) {} - Canvas_BindLua(lua_State* L) {} - - int GetDPI(lua_State* L); - int GetDPIScaling(lua_State* L); - int GetPhysicalWidth(lua_State* L); - int GetPhysicalHeight(lua_State* L); - int GetLogicalWidth(lua_State* L); - int GetLogicalHeight(lua_State* L); - - static void Bind(); -}; - -class MainComponent_BindLua -{ -private: - MainComponent* component = nullptr; -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - MainComponent_BindLua(MainComponent* component = nullptr); - MainComponent_BindLua(lua_State *L); - - int GetActivePath(lua_State *L); - int SetActivePath(lua_State *L); - int SetFrameSkip(lua_State *L); - int SetTargetFrameRate(lua_State *L); - int SetFrameRateLock(lua_State *L); - int SetInfoDisplay(lua_State *L); - int SetWatermarkDisplay(lua_State *L); - int SetFPSDisplay(lua_State *L); - int SetResolutionDisplay(lua_State* L); - int SetLogicalSizeDisplay(lua_State *L); - int SetPipelineCountDisplay(lua_State* L); - int SetHeapAllocationCountDisplay(lua_State* L); - - int GetCanvas(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/Matrix_BindLua.cpp b/WickedEngine/Matrix_BindLua.cpp deleted file mode 100644 index 1e9e5fb4f..000000000 --- a/WickedEngine/Matrix_BindLua.cpp +++ /dev/null @@ -1,323 +0,0 @@ -#include "Matrix_BindLua.h" -#include "Vector_BindLua.h" - -using namespace DirectX; - - -const char Matrix_BindLua::className[] = "Matrix"; - -Luna::FunctionType Matrix_BindLua::methods[] = { - lunamethod(Matrix_BindLua, GetRow), - lunamethod(Matrix_BindLua, Translation), - lunamethod(Matrix_BindLua, Rotation), - lunamethod(Matrix_BindLua, RotationX), - lunamethod(Matrix_BindLua, RotationY), - lunamethod(Matrix_BindLua, RotationZ), - lunamethod(Matrix_BindLua, RotationQuaternion), - lunamethod(Matrix_BindLua, Scale), - lunamethod(Matrix_BindLua, LookTo), - lunamethod(Matrix_BindLua, LookAt), - - lunamethod(Matrix_BindLua, Add), - lunamethod(Matrix_BindLua, Multiply), - lunamethod(Matrix_BindLua, Transpose), - lunamethod(Matrix_BindLua, Inverse), - { NULL, NULL } -}; -Luna::PropertyType Matrix_BindLua::properties[] = { - { NULL, NULL } -}; - -Matrix_BindLua::Matrix_BindLua() -{ - std::memcpy(this, &IDENTITYMATRIX, sizeof(IDENTITYMATRIX)); -} -Matrix_BindLua::Matrix_BindLua(const XMFLOAT4X4& matrix) -{ - std::memcpy(this, &matrix, sizeof(matrix)); -} -Matrix_BindLua::Matrix_BindLua(const XMMATRIX& matrix) -{ - XMStoreFloat4x4(this, matrix); -} -Matrix_BindLua::Matrix_BindLua(lua_State* L) -{ - std::memcpy(this, &IDENTITYMATRIX, sizeof(IDENTITYMATRIX)); - - int argc = wiLua::SGetArgCount(L); - - // fill out all the four rows of the matrix - for (int i = 0; i < 4; ++i) - { - float x = 0.f, y = 0.f, z = 0.f, w = 0.f; - if (argc > i * 4) - { - x = wiLua::SGetFloat(L, i * 4 + 1); - if (argc > i * 4 + 1) - { - y = wiLua::SGetFloat(L, i * 4 + 2); - if (argc > i * 4 + 2) - { - z = wiLua::SGetFloat(L, i * 4 + 3); - if (argc > i * 4 + 3) - { - w = wiLua::SGetFloat(L, i * 4 + 4); - } - } - } - } - this->m[i][0] = x; - this->m[i][1] = x; - this->m[i][2] = x; - this->m[i][3] = x; - } - -} - -int Matrix_BindLua::GetRow(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - int row = 0; - if (argc > 1) - { - row = wiLua::SGetInt(L, 2); - if (row < 0 || row > 3) - row = 0; - } - XMFLOAT4 r = XMFLOAT4(m[row][0], m[row][1], m[row][2], m[row][3]); - Luna::push(L, new Vector_BindLua(r)); - return 1; -} - - - -int Matrix_BindLua::Translation(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - mat = XMMatrixTranslationFromVector(XMLoadFloat4(vector)); - } - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::Rotation(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - mat = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat4(vector)); - } - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::RotationX(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - mat = XMMatrixRotationX(wiLua::SGetFloat(L, 1)); - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::RotationY(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - mat = XMMatrixRotationY(wiLua::SGetFloat(L, 1)); - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::RotationZ(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - mat = XMMatrixRotationZ(wiLua::SGetFloat(L, 1)); - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::RotationQuaternion(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - mat = XMMatrixRotationQuaternion(XMLoadFloat4(vector)); - } - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::Scale(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - XMMATRIX mat = XMMatrixIdentity(); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - mat = XMMatrixScalingFromVector(XMLoadFloat4(vector)); - } - } - Luna::push(L, new Matrix_BindLua(mat)); - return 1; -} - -int Matrix_BindLua::LookTo(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* pos = Luna::lightcheck(L, 1); - Vector_BindLua* dir = Luna::lightcheck(L, 2); - if (pos != nullptr && dir != nullptr) - { - XMVECTOR Up; - if (argc > 3) - { - Vector_BindLua* up = Luna::lightcheck(L, 3); - Up = XMLoadFloat4(up); - } - else - Up = XMVectorSet(0, 1, 0, 0); - Luna::push(L, new Matrix_BindLua(XMMatrixLookToLH(XMLoadFloat4(pos), XMLoadFloat4(dir), Up))); - } - else - wiLua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) argument is not a Vector!"); - } - else - wiLua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) not enough arguments!"); - return 1; -} - -int Matrix_BindLua::LookAt(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* pos = Luna::lightcheck(L, 1); - Vector_BindLua* dir = Luna::lightcheck(L, 2); - if (dir != nullptr) - { - XMVECTOR Up; - if (argc > 3) - { - Vector_BindLua* up = Luna::lightcheck(L, 3); - Up = XMLoadFloat4(up); - } - else - Up = XMVectorSet(0, 1, 0, 0); - Luna::push(L, new Matrix_BindLua(XMMatrixLookAtLH(XMLoadFloat4(pos), XMLoadFloat4(dir), Up))); - } - else - wiLua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) argument is not a Vector!"); - } - else - wiLua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) not enough arguments!"); - return 1; -} - -int Matrix_BindLua::Multiply(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Matrix_BindLua* m1 = Luna::lightcheck(L, 1); - Matrix_BindLua* m2 = Luna::lightcheck(L, 2); - if (m1 && m2) - { - Luna::push(L, new Matrix_BindLua(XMMatrixMultiply(XMLoadFloat4x4(m1), XMLoadFloat4x4(m2)))); - return 1; - } - } - wiLua::SError(L, "Multiply(Matrix m1,m2) not enough arguments!"); - return 0; -} -int Matrix_BindLua::Add(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Matrix_BindLua* m1 = Luna::lightcheck(L, 1); - Matrix_BindLua* m2 = Luna::lightcheck(L, 2); - if (m1 && m2) - { - Luna::push(L, new Matrix_BindLua(XMLoadFloat4x4(m1) + XMLoadFloat4x4(m2))); - return 1; - } - } - wiLua::SError(L, "Add(Matrix m1,m2) not enough arguments!"); - return 0; -} -int Matrix_BindLua::Transpose(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Matrix_BindLua* m1 = Luna::lightcheck(L, 1); - if (m1) - { - Luna::push(L, new Matrix_BindLua(XMMatrixTranspose(XMLoadFloat4x4(m1)))); - return 1; - } - } - wiLua::SError(L, "Transpose(Matrix m) not enough arguments!"); - return 0; -} -int Matrix_BindLua::Inverse(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Matrix_BindLua* m1 = Luna::lightcheck(L, 1); - if (m1) - { - XMVECTOR det; - Luna::push(L, new Matrix_BindLua(XMMatrixInverse(&det, XMLoadFloat4x4(m1)))); - wiLua::SSetFloat(L, XMVectorGetX(det)); - return 2; - } - } - wiLua::SError(L, "Inverse(Matrix m) not enough arguments!"); - return 0; -} - - -void Matrix_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - wiLua::RunText("matrix = Matrix()"); - } -} diff --git a/WickedEngine/Matrix_BindLua.h b/WickedEngine/Matrix_BindLua.h deleted file mode 100644 index 0952d8032..000000000 --- a/WickedEngine/Matrix_BindLua.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiLua.h" -#include "wiLuna.h" -#include "wiMath.h" - -class Matrix_BindLua : public XMFLOAT4X4 -{ -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - Matrix_BindLua(); - Matrix_BindLua(const XMMATRIX& matrix); - Matrix_BindLua(const XMFLOAT4X4& matrix); - Matrix_BindLua(lua_State* L); - - int GetRow(lua_State* L); - - int Translation(lua_State* L); - int Rotation(lua_State* L); - int RotationX(lua_State* L); - int RotationY(lua_State* L); - int RotationZ(lua_State* L); - int RotationQuaternion(lua_State* L); - int Scale(lua_State* L); - int LookTo(lua_State* L); - int LookAt(lua_State* L); - - int Multiply(lua_State* L); - int Add(lua_State* L); - int Transpose(lua_State* L); - int Inverse(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/RenderPath.h b/WickedEngine/RenderPath.h deleted file mode 100644 index 9901fb318..000000000 --- a/WickedEngine/RenderPath.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiGraphicsDevice.h" -#include "wiCanvas.h" - -class RenderPath : public wiCanvas -{ -private: - uint32_t layerMask = 0xFFFFFFFF; - -public: - virtual ~RenderPath() = default; - - // load resources in background (for example behind loading screen) - virtual void Load() {} - // called when RenderPath gets activated - virtual void Start() {} - // called when RenderPath gets deactivated (for example when switching to an other RenderPath) - virtual void Stop() {} - // executed before Update() - virtual void PreUpdate() {} - // update with fixed frequency - virtual void FixedUpdate() {} - // update once per frame - // dt : elapsed time since last call in seconds - virtual void Update(float dt) {} - // executed after Update() - virtual void PostUpdate() {} - // Render to layers, rendertargets, etc - // This will be rendered offscreen - virtual void Render() const {} - // Compose the rendered layers (for example blend the layers together as Images) - // This will be rendered to the backbuffer - virtual void Compose(wiGraphics::CommandList cmd) const {} - - inline uint32_t getLayerMask() const { return layerMask; } - inline void setlayerMask(uint32_t value) { layerMask = value; } - - wiGraphics::ColorSpace colorspace = wiGraphics::ColorSpace::SRGB; -}; - diff --git a/WickedEngine/RenderPath2D.cpp b/WickedEngine/RenderPath2D.cpp deleted file mode 100644 index e3a6df56b..000000000 --- a/WickedEngine/RenderPath2D.cpp +++ /dev/null @@ -1,550 +0,0 @@ -#include "RenderPath2D.h" -#include "wiResourceManager.h" -#include "wiSprite.h" -#include "wiSpriteFont.h" -#include "wiRenderer.h" - -using namespace wiGraphics; - - -void RenderPath2D::ResizeBuffers() -{ - current_buffersize = GetInternalResolution(); - current_layoutscale = 0; // invalidate layout - - GraphicsDevice* device = wiGraphics::GetDevice(); - - const Texture* dsv = GetDepthStencil(); - if(dsv != nullptr && (resolutionScale != 1.0f || dsv->GetDesc().sample_count > 1)) - { - TextureDesc desc = GetDepthStencil()->GetDesc(); - desc.layout = ResourceState::SHADER_RESOURCE; - desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; - desc.format = Format::R8G8B8A8_UNORM; - device->CreateTexture(&desc, nullptr, &rtStenciled); - device->SetName(&rtStenciled, "rtStenciled"); - - if (desc.sample_count > 1) - { - desc.sample_count = 1; - device->CreateTexture(&desc, nullptr, &rtStenciled_resolved); - device->SetName(&rtStenciled_resolved, "rtStenciled_resolved"); - } - } - else - { - rtStenciled = Texture(); // this will be deleted here - } - - { - TextureDesc desc; - desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; - desc.format = Format::R8G8B8A8_UNORM; - desc.width = GetPhysicalWidth(); - desc.height = GetPhysicalHeight(); - device->CreateTexture(&desc, nullptr, &rtFinal); - device->SetName(&rtFinal, "rtFinal"); - } - - if (rtStenciled.IsValid()) - { - RenderPassDesc desc; - desc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtStenciled, RenderPassAttachment::LoadOp::CLEAR)); - desc.attachments.push_back( - RenderPassAttachment::DepthStencil( - dsv, - RenderPassAttachment::LoadOp::LOAD, - RenderPassAttachment::StoreOp::STORE, - ResourceState::DEPTHSTENCIL_READONLY, - ResourceState::DEPTHSTENCIL_READONLY, - ResourceState::DEPTHSTENCIL_READONLY - ) - ); - - if (rtStenciled.GetDesc().sample_count > 1) - { - desc.attachments.push_back(RenderPassAttachment::Resolve(&rtStenciled_resolved)); - } - - device->CreateRenderPass(&desc, &renderpass_stenciled); - - dsv = nullptr; - } - { - RenderPassDesc desc; - desc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtFinal, RenderPassAttachment::LoadOp::CLEAR)); - - if(dsv != nullptr && !rtStenciled.IsValid()) - { - desc.attachments.push_back( - RenderPassAttachment::DepthStencil( - dsv, - RenderPassAttachment::LoadOp::LOAD, - RenderPassAttachment::StoreOp::STORE, - ResourceState::DEPTHSTENCIL_READONLY, - ResourceState::DEPTHSTENCIL_READONLY, - ResourceState::DEPTHSTENCIL_READONLY - ) - ); - } - - device->CreateRenderPass(&desc, &renderpass_final); - } - -} -void RenderPath2D::ResizeLayout() -{ - current_layoutscale = GetDPIScaling(); -} - -void RenderPath2D::Update(float dt) -{ - XMUINT2 internalResolution = GetInternalResolution(); - - if (current_buffersize.x != internalResolution.x || current_buffersize.y != internalResolution.y) - { - ResizeBuffers(); - } - if (current_layoutscale != GetDPIScaling()) - { - ResizeLayout(); - } - - GetGUI().Update(*this, dt); - - for (auto& x : layers) - { - for (auto& y : x.items) - { - switch (y.type) - { - default: - case RenderItem2D::SPRITE: - if (y.sprite != nullptr) - { - y.sprite->Update(dt); - } - break; - case RenderItem2D::FONT: - if (y.font != nullptr) - { - y.font->Update(dt); - } - break; - } - } - } - - if (colorspace != ColorSpace::SRGB && (rtLinearColorSpace.desc.width != rtFinal.desc.width || rtLinearColorSpace.desc.height != rtFinal.desc.height)) - { - TextureDesc desc = rtFinal.desc; - desc.format = Format::R16G16B16A16_FLOAT; - bool success = wiGraphics::GetDevice()->CreateTexture(&desc, nullptr, &rtLinearColorSpace); - assert(success); - wiGraphics::GetDevice()->SetName(&rtLinearColorSpace, "rtLinearColorSpace"); - - RenderPassDesc renderpassdesc; - renderpassdesc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtLinearColorSpace, RenderPassAttachment::LoadOp::CLEAR)); - success = wiGraphics::GetDevice()->CreateRenderPass(&renderpassdesc, &renderpass_linearize); - assert(success); - } - - RenderPath::Update(dt); -} -void RenderPath2D::FixedUpdate() -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - switch (y.type) - { - default: - case RenderItem2D::SPRITE: - if (y.sprite != nullptr) - { - y.sprite->FixedUpdate(); - } - break; - case RenderItem2D::FONT: - if (y.font != nullptr) - { - y.font->FixedUpdate(); - } - break; - } - } - } - - RenderPath::FixedUpdate(); -} -void RenderPath2D::Render() const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - CommandList cmd = device->BeginCommandList(); - wiImage::SetCanvas(*this, cmd); - wiFont::SetCanvas(*this, cmd); - - wiRenderer::ProcessDeferredMipGenRequests(cmd); - - if (GetGUIBlurredBackground() != nullptr) - { - wiImage::SetBackground(*GetGUIBlurredBackground(), cmd); - } - - // Special care for internal resolution, because stencil buffer is of internal resolution, - // so we might need to render stencil sprites to separate render target that matches internal resolution! - if (rtStenciled.IsValid()) - { - device->RenderPassBegin(&renderpass_stenciled, cmd); - - Viewport vp; - vp.width = (float)rtStenciled.GetDesc().width; - vp.height = (float)rtStenciled.GetDesc().height; - device->BindViewports(1, &vp, cmd); - - device->EventBegin("STENCIL Sprite Layers", cmd); - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::SPRITE && - y.sprite != nullptr && - y.sprite->params.stencilComp != STENCILMODE_DISABLED) - { - y.sprite->Draw(cmd); - } - } - } - device->EventEnd(cmd); - - device->RenderPassEnd(cmd); - } - - device->RenderPassBegin(&renderpass_final, cmd); - - Viewport vp; - vp.width = (float)rtFinal.GetDesc().width; - vp.height = (float)rtFinal.GetDesc().height; - device->BindViewports(1, &vp, cmd); - - if (GetDepthStencil() != nullptr) - { - if (rtStenciled.IsValid()) - { - device->EventBegin("Copy STENCIL Sprite Layers", cmd); - wiImageParams fx; - fx.enableFullScreen(); - if (rtStenciled.GetDesc().sample_count > 1) - { - wiImage::Draw(&rtStenciled_resolved, fx, cmd); - } - else - { - wiImage::Draw(&rtStenciled, fx, cmd); - } - device->EventEnd(cmd); - } - else - { - device->EventBegin("STENCIL Sprite Layers", cmd); - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::SPRITE && - y.sprite != nullptr && - y.sprite->params.stencilComp != STENCILMODE_DISABLED) - { - y.sprite->Draw(cmd); - } - } - } - device->EventEnd(cmd); - } - } - - device->EventBegin("Sprite Layers", cmd); - for (auto& x : layers) - { - for (auto& y : x.items) - { - switch (y.type) - { - default: - case RenderItem2D::SPRITE: - if (y.sprite != nullptr && y.sprite->params.stencilComp == STENCILMODE_DISABLED) - { - y.sprite->Draw(cmd); - } - break; - case RenderItem2D::FONT: - if (y.font != nullptr) - { - y.font->Draw(cmd); - } - break; - } - } - } - device->EventEnd(cmd); - - GetGUI().Render(*this, cmd); - - device->RenderPassEnd(cmd); - - if (colorspace != ColorSpace::SRGB) - { - // Convert the regular SRGB result of the render path to linear space for HDR compositing: - device->RenderPassBegin(&renderpass_linearize, cmd); - wiImageParams fx; - fx.enableFullScreen(); - fx.enableLinearOutputMapping(hdr_scaling); - wiImage::Draw(&rtFinal, fx, cmd); - device->RenderPassEnd(cmd); - render_result = rtLinearColorSpace; - } - else - { - render_result = rtFinal; - } - - RenderPath::Render(); -} -void RenderPath2D::Compose(CommandList cmd) const -{ - wiImageParams fx; - fx.enableFullScreen(); - fx.blendFlag = BLENDMODE_PREMULTIPLIED; - wiImage::Draw(&render_result, fx, cmd); - - RenderPath::Compose(cmd); -} - - -void RenderPath2D::AddSprite(wiSprite* sprite, const std::string& layer) -{ - for (auto& x : layers) - { - if (!x.name.compare(layer)) - { - x.items.push_back(RenderItem2D()); - x.items.back().type = RenderItem2D::SPRITE; - x.items.back().sprite = sprite; - } - } - SortLayers(); -} -void RenderPath2D::RemoveSprite(wiSprite* sprite) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::SPRITE && y.sprite == sprite) - { - y.sprite = nullptr; - } - } - } - CleanLayers(); -} -void RenderPath2D::ClearSprites() -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::SPRITE) - { - y.sprite = nullptr; - } - } - } - CleanLayers(); -} -int RenderPath2D::GetSpriteOrder(wiSprite* sprite) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.sprite == sprite) - { - return y.order; - } - } - } - return 0; -} - -void RenderPath2D::AddFont(wiSpriteFont* font, const std::string& layer) -{ - for (auto& x : layers) - { - if (!x.name.compare(layer)) - { - x.items.push_back(RenderItem2D()); - x.items.back().type = RenderItem2D::FONT; - x.items.back().font = font; - } - } - SortLayers(); -} -void RenderPath2D::RemoveFont(wiSpriteFont* font) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::FONT && y.font == font) - { - y.font = nullptr; - } - } - } - CleanLayers(); -} -void RenderPath2D::ClearFonts() -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::FONT) - { - y.font = nullptr; - } - } - } - CleanLayers(); -} -int RenderPath2D::GetFontOrder(wiSpriteFont* font) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.font == font) - { - return y.order; - } - } - } - return 0; -} - - -void RenderPath2D::AddLayer(const std::string& name) -{ - for (auto& x : layers) - { - if (!x.name.compare(name)) - return; - } - RenderLayer2D layer; - layer.name = name; - layer.order = (int)layers.size(); - layers.push_back(layer); - layers.back().items.clear(); -} -void RenderPath2D::SetLayerOrder(const std::string& name, int order) -{ - for (auto& x : layers) - { - if (!x.name.compare(name)) - { - x.order = order; - break; - } - } - SortLayers(); -} -void RenderPath2D::SetSpriteOrder(wiSprite* sprite, int order) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::SPRITE && y.sprite == sprite) - { - y.order = order; - } - } - } - SortLayers(); -} -void RenderPath2D::SetFontOrder(wiSpriteFont* font, int order) -{ - for (auto& x : layers) - { - for (auto& y : x.items) - { - if (y.type == RenderItem2D::FONT && y.font == font) - { - y.order = order; - } - } - } - SortLayers(); -} -void RenderPath2D::SortLayers() -{ - if (layers.empty()) - { - return; - } - - for (size_t i = 0; i < layers.size() - 1; ++i) - { - for (size_t j = i + 1; j < layers.size(); ++j) - { - if (layers[i].order > layers[j].order) - { - RenderLayer2D swap = layers[i]; - layers[i] = layers[j]; - layers[j] = swap; - } - } - } - for (auto& x : layers) - { - if (x.items.empty()) - { - continue; - } - for (size_t i = 0; i < x.items.size() - 1; ++i) - { - for (size_t j = i + 1; j < x.items.size(); ++j) - { - if (x.items[i].order > x.items[j].order) - { - RenderItem2D swap = x.items[i]; - x.items[i] = x.items[j]; - x.items[j] = swap; - } - } - } - } -} - -void RenderPath2D::CleanLayers() -{ - for (auto& x : layers) - { - if (x.items.empty()) - { - continue; - } - wi::vector itemsToRetain(0); - for (auto& y : x.items) - { - if (y.sprite != nullptr || y.font!=nullptr) - { - itemsToRetain.push_back(y); - } - } - x.items.clear(); - x.items = itemsToRetain; - } -} diff --git a/WickedEngine/RenderPath2D.h b/WickedEngine/RenderPath2D.h deleted file mode 100644 index 728dd82ec..000000000 --- a/WickedEngine/RenderPath2D.h +++ /dev/null @@ -1,103 +0,0 @@ -#pragma once -#include "RenderPath.h" -#include "wiGUI.h" -#include "wiVector.h" - -#include - -class wiSprite; -class wiSpriteFont; - -struct RenderItem2D -{ - enum TYPE - { - SPRITE, - FONT, - } type = SPRITE; - union - { - wiSprite* sprite = nullptr; - wiSpriteFont* font; - }; - int order = 0; -}; -struct RenderLayer2D -{ - wi::vector items; - std::string name; - int order = 0; -}; - -class RenderPath2D : - public RenderPath -{ -private: - wiGraphics::Texture rtStenciled; - wiGraphics::Texture rtStenciled_resolved; - wiGraphics::Texture rtFinal; - - wiGraphics::RenderPass renderpass_stenciled; - wiGraphics::RenderPass renderpass_final; - - wiGraphics::Texture rtLinearColorSpace; - wiGraphics::RenderPass renderpass_linearize; - - wiGUI GUI; - - XMUINT2 current_buffersize{}; - float current_layoutscale{}; - - mutable wiGraphics::Texture render_result = rtFinal; - - float hdr_scaling = 9.0f; - -public: - // create resolution dependent resources, such as render targets - virtual void ResizeBuffers(); - // update DPI dependent elements, such as GUI elements, sprites - virtual void ResizeLayout(); - - void Update(float dt) override; - void FixedUpdate() override; - void Render() const override; - void Compose(wiGraphics::CommandList cmd) const override; - - const wiGraphics::Texture& GetRenderResult() const { return render_result; } - virtual const wiGraphics::Texture* GetDepthStencil() const { return nullptr; } - virtual const wiGraphics::Texture* GetGUIBlurredBackground() const { return nullptr; } - - void AddSprite(wiSprite* sprite, const std::string& layer = ""); - void RemoveSprite(wiSprite* sprite); - void ClearSprites(); - int GetSpriteOrder(wiSprite* sprite); - - void AddFont(wiSpriteFont* font, const std::string& layer = ""); - void RemoveFont(wiSpriteFont* font); - void ClearFonts(); - int GetFontOrder(wiSpriteFont* font); - - wi::vector layers{ 1 }; - void AddLayer(const std::string& name); - void SetLayerOrder(const std::string& name, int order); - void SetSpriteOrder(wiSprite* sprite, int order); - void SetFontOrder(wiSpriteFont* font, int order); - void SortLayers(); - void CleanLayers(); - - const wiGUI& GetGUI() const { return GUI; } - wiGUI& GetGUI() { return GUI; } - - float resolutionScale = 1.0f; - XMUINT2 GetInternalResolution() const - { - return XMUINT2( - uint32_t((float)GetPhysicalWidth() * resolutionScale), - uint32_t((float)GetPhysicalHeight() * resolutionScale) - ); - } - - float GetHDRScaling() const { return hdr_scaling; } - void SetHDRScaling(float value) { hdr_scaling = value; } -}; - diff --git a/WickedEngine/RenderPath2D_BindLua.cpp b/WickedEngine/RenderPath2D_BindLua.cpp deleted file mode 100644 index 4508043ca..000000000 --- a/WickedEngine/RenderPath2D_BindLua.cpp +++ /dev/null @@ -1,423 +0,0 @@ -#include "RenderPath2D_BindLua.h" -#include "wiSprite_BindLua.h" -#include "wiSpriteFont_BindLua.h" - -#include - -const char RenderPath2D_BindLua::className[] = "RenderPath2D"; - -Luna::FunctionType RenderPath2D_BindLua::methods[] = { - lunamethod(RenderPath2D_BindLua, AddSprite), - lunamethod(RenderPath2D_BindLua, AddFont), - lunamethod(RenderPath2D_BindLua, RemoveSprite), - lunamethod(RenderPath2D_BindLua, RemoveFont), - lunamethod(RenderPath2D_BindLua, ClearSprites), - lunamethod(RenderPath2D_BindLua, ClearFonts), - lunamethod(RenderPath2D_BindLua, GetSpriteOrder), - lunamethod(RenderPath2D_BindLua, GetFontOrder), - lunamethod(RenderPath2D_BindLua, AddLayer), - lunamethod(RenderPath2D_BindLua, GetLayers), - lunamethod(RenderPath2D_BindLua, SetLayerOrder), - lunamethod(RenderPath2D_BindLua, SetSpriteOrder), - lunamethod(RenderPath2D_BindLua, SetFontOrder), - lunamethod(RenderPath_BindLua, GetLayerMask), - lunamethod(RenderPath_BindLua, SetLayerMask), - { NULL, NULL } -}; -Luna::PropertyType RenderPath2D_BindLua::properties[] = { - { NULL, NULL } -}; - -int RenderPath2D_BindLua::AddSprite(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "AddSprite() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSprite_BindLua* sprite = Luna::lightcheck(L, 1); - if (sprite != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - if(argc>1) - ccomp->AddSprite(&sprite->sprite, wiLua::SGetString(L,2)); - else - ccomp->AddSprite(&sprite->sprite); - } - else - { - wiLua::SError(L, "AddSprite(Sprite sprite, opt string layer) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "AddSprite(Sprite sprite, opt string layer) argument is not a Sprite!"); - } - else - { - wiLua::SError(L, "AddSprite(Sprite sprite, opt string layer) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::AddFont(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "AddFont() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSpriteFont_BindLua* font = Luna::lightcheck(L, 1); - if (font != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - if (argc > 1) - ccomp->AddFont(&font->font, wiLua::SGetString(L, 2)); - else - ccomp->AddFont(&font->font); - } - else - { - wiLua::SError(L, "AddFont(Font font, opt string layer) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "AddFont(Font font, opt string layer) argument is not a Font!"); - } - else - { - wiLua::SError(L, "AddFont(Font font, opt string layer) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::RemoveSprite(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "RemoveSprite() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSprite_BindLua* sprite = Luna::lightcheck(L, 1); - if (sprite != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->RemoveSprite(&sprite->sprite); - } - else - { - wiLua::SError(L, "RemoveSprite(Sprite sprite) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "RemoveSprite(Sprite sprite) argument is not a Sprite!"); - } - else - { - wiLua::SError(L, "RemoveSprite(Sprite sprite) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::RemoveFont(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "RemoveFont() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSpriteFont_BindLua* font = Luna::lightcheck(L, 1); - if (font != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->RemoveFont(&font->font); - } - else - { - wiLua::SError(L, "RemoveFont(Font font) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "RemoveFont(Font font) argument is not a Font!"); - } - else - { - wiLua::SError(L, "RemoveFont(Font font) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::ClearSprites(lua_State *L) -{ - if (component == nullptr) - { - wiLua::SError(L, "ClearSprites() component is empty!"); - return 0; - } - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->ClearSprites(); - } - else - { - wiLua::SError(L, "ClearSprites() not a RenderPath2D!"); - } - return 0; -} -int RenderPath2D_BindLua::ClearFonts(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "ClearFonts() component is empty!"); - return 0; - } - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->ClearFonts(); - } - else - { - wiLua::SError(L, "ClearFonts() not a RenderPath2D!"); - } - return 0; -} -int RenderPath2D_BindLua::GetSpriteOrder(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "GetSpriteOrder() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSprite_BindLua* sprite = Luna::lightcheck(L, 1); - if (sprite != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - wiLua::SSetInt(L, ccomp->GetSpriteOrder(&sprite->sprite)); - return 1; - } - else - { - wiLua::SError(L, "GetSpriteOrder(Sprite sprite) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "GetSpriteOrder(Sprite sprite) argument is not a Sprite!"); - } - else - { - wiLua::SError(L, "GetSpriteOrder(Sprite sprite) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::GetFontOrder(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "GetFontOrder() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSpriteFont_BindLua* font = Luna::lightcheck(L, 1); - if (font != nullptr) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - wiLua::SSetInt(L, ccomp->GetFontOrder(&font->font)); - return 1; - } - else - { - wiLua::SError(L, "GetFontOrder(Font font) not a RenderPath2D!"); - } - } - else - wiLua::SError(L, "GetFontOrder(Font font) argument is not a Sprite!"); - } - else - { - wiLua::SError(L, "GetFontOrder(Font font) not enough arguments!"); - } - return 0; -} - -int RenderPath2D_BindLua::AddLayer(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "AddLayer() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->AddLayer(wiLua::SGetString(L, 1)); - } - else - { - wiLua::SError(L, "AddLayer(string name) not a RenderPath2D!"); - } - } - else - { - wiLua::SError(L, "AddLayer(string name) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::GetLayers(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "GetLayers() component is empty!"); - return 0; - } - - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - std::string ss; - for (auto& x : ccomp->layers) - { - ss += x.name + "\n"; - } - wiLua::SSetString(L, ss); - return 1; - } - else - { - wiLua::SError(L, "GetLayers() not a RenderPath2D!"); - } - - return 0; -} -int RenderPath2D_BindLua::SetLayerOrder(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetLayerOrder() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - ccomp->SetLayerOrder(wiLua::SGetString(L, 1),wiLua::SGetInt(L,2)); - } - else - { - wiLua::SError(L, "SetLayerOrder(string name, int order) not a RenderPath2D!"); - } - } - else - { - wiLua::SError(L, "SetLayerOrder(string name, int order) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::SetSpriteOrder(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetSpriteOrder() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - wiSprite_BindLua* sprite = Luna::lightcheck(L, 1); - if (sprite != nullptr) - { - ccomp->SetSpriteOrder(&sprite->sprite, wiLua::SGetInt(L, 2)); - } - else - { - wiLua::SError(L, "SetSpriteOrder(Sprite sprite, int order) argument is not a Sprite!"); - } - } - else - { - wiLua::SError(L, "SetSpriteOrder(Sprite sprite, int order) not a RenderPath2D!"); - } - } - else - { - wiLua::SError(L, "SetSpriteOrder(Sprite sprite, int order) not enough arguments!"); - } - return 0; -} -int RenderPath2D_BindLua::SetFontOrder(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetFontOrder() component is empty!"); - return 0; - } - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - RenderPath2D* ccomp = dynamic_cast(component); - if (ccomp != nullptr) - { - wiSpriteFont_BindLua* font = Luna::lightcheck(L, 1); - if (font != nullptr) - { - ccomp->SetFontOrder(&font->font, wiLua::SGetInt(L, 2)); - } - else - { - wiLua::SError(L, "SetFontOrder(Font font, int order) argument is not a Font!"); - } - } - else - { - wiLua::SError(L, "SetFontOrder(Font font, int order) not a RenderPath2D!"); - } - } - else - { - wiLua::SError(L, "SetFontOrder(Font font, int order) not enough arguments!"); - } - return 0; -} - -void RenderPath2D_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} diff --git a/WickedEngine/RenderPath2D_BindLua.h b/WickedEngine/RenderPath2D_BindLua.h deleted file mode 100644 index 8462c8539..000000000 --- a/WickedEngine/RenderPath2D_BindLua.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "RenderPath2D.h" -#include "RenderPath_BindLua.h" - -class RenderPath2D_BindLua : public RenderPath_BindLua -{ -private: - RenderPath2D renderpath; -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - RenderPath2D_BindLua() = default; - RenderPath2D_BindLua(RenderPath2D* component) - { - this->component = component; - } - RenderPath2D_BindLua(lua_State* L) - { - this->component = &renderpath; - } - - int AddSprite(lua_State *L); - int AddFont(lua_State* L); - int RemoveSprite(lua_State *L); - int RemoveFont(lua_State* L); - int ClearSprites(lua_State *L); - int ClearFonts(lua_State* L); - int GetSpriteOrder(lua_State* L); - int GetFontOrder(lua_State* L); - - int AddLayer(lua_State* L); - int GetLayers(lua_State* L); - int SetLayerOrder(lua_State* L); - int SetSpriteOrder(lua_State* L); - int SetFontOrder(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/RenderPath3D.h b/WickedEngine/RenderPath3D.h deleted file mode 100644 index f86a2e4d3..000000000 --- a/WickedEngine/RenderPath3D.h +++ /dev/null @@ -1,249 +0,0 @@ -#pragma once -#include "RenderPath2D.h" -#include "wiRenderer.h" -#include "wiGraphicsDevice.h" -#include "wiResourceManager.h" -#include "wiScene.h" - -#include - -class RenderPath3D : - public RenderPath2D -{ -public: - enum AO - { - AO_DISABLED, // no ambient occlusion - AO_SSAO, // simple brute force screen space ambient occlusion - AO_HBAO, // horizon based screen space ambient occlusion - AO_MSAO, // multi scale screen space ambient occlusion - AO_RTAO, // ray traced ambient occlusion - // Don't alter order! (bound to lua manually) - }; -private: - float exposure = 1.0f; - float bloomThreshold = 1.0f; - float motionBlurStrength = 100.0f; - float dofStrength = 10.0f; - float sharpenFilterAmount = 0.28f; - float outlineThreshold = 0.2f; - float outlineThickness = 1.0f; - XMFLOAT4 outlineColor = XMFLOAT4(0, 0, 0, 1); - float aoRange = 1.0f; - uint32_t aoSampleCount = 16; - float aoPower = 1.0f; - float chromaticAberrationAmount = 2.0f; - uint32_t screenSpaceShadowSampleCount = 16; - float screenSpaceShadowRange = 1; - float eyeadaptionKey = 0.115f; - float eyeadaptionRate = 1; - float fsrSharpness = 1.0f; - - AO ao = AO_DISABLED; - bool fxaaEnabled = false; - bool ssrEnabled = false; - bool raytracedReflectionsEnabled = false; - bool reflectionsEnabled = true; - bool shadowsEnabled = true; - bool bloomEnabled = true; - bool colorGradingEnabled = true; - bool volumeLightsEnabled = true; - bool lightShaftsEnabled = false; - bool lensFlareEnabled = true; - bool motionBlurEnabled = false; - bool depthOfFieldEnabled = true; - bool eyeAdaptionEnabled = false; - bool sharpenFilterEnabled = false; - bool outlineEnabled = false; - bool chromaticAberrationEnabled = false; - bool ditherEnabled = true; - bool occlusionCullingEnabled = true; - bool sceneUpdateEnabled = true; - bool fsrEnabled = true; - - uint32_t msaaSampleCount = 1; - -public: - wiGraphics::Texture rtMain; - wiGraphics::Texture rtMain_render; // can be MSAA - wiGraphics::Texture rtGbuffer[GBUFFER_COUNT]; - wiGraphics::Texture rtPrimitiveID_render; // can be MSAA - wiGraphics::Texture rtReflection; // contains the scene rendered for planar reflections - wiGraphics::Texture rtSSR; // standard screen-space reflection results - wiGraphics::Texture rtSceneCopy; // contains the rendered scene that can be fed into transparent pass for distortion effect - wiGraphics::Texture rtSceneCopy_tmp; // temporary for gaussian mipchain - wiGraphics::Texture rtWaterRipple; // water ripple sprite normal maps are rendered into this - wiGraphics::Texture rtParticleDistortion; // contains distortive particles - wiGraphics::Texture rtParticleDistortion_Resolved; // contains distortive particles - wiGraphics::Texture rtVolumetricLights[2]; // contains the volumetric light results - wiGraphics::Texture rtTemporalAA[2]; // temporal AA history buffer - wiGraphics::Texture rtBloom; // contains the bright parts of the image + mipchain - wiGraphics::Texture rtBloom_tmp; // temporary for bloom downsampling - wiGraphics::Texture rtAO; // full res AO - wiGraphics::Texture rtShadow; // raytraced shadows mask - wiGraphics::Texture rtSun[2]; // 0: sun render target used for lightshafts (can be MSAA), 1: radial blurred lightshafts - wiGraphics::Texture rtSun_resolved; // sun render target, but the resolved version if MSAA is enabled - wiGraphics::Texture rtGUIBlurredBackground[3]; // downsampled, gaussian blurred scene for GUI - wiGraphics::Texture rtShadingRate; // UINT8 shading rate per tile - wiGraphics::Texture rtFSR[2]; // FSR upscaling result (full resolution LDR) - - wiGraphics::Texture rtPostprocess; // ping-pong with main scene RT in post-process chain - - wiGraphics::Texture depthBuffer_Main; // used for depth-testing, can be MSAA - wiGraphics::Texture depthBuffer_Copy; // used for shader resource, single sample - wiGraphics::Texture depthBuffer_Copy1; // used for disocclusion check - wiGraphics::Texture depthBuffer_Reflection; // used for reflection, single sample - wiGraphics::Texture rtLinearDepth; // linear depth result + mipchain (max filter) - - wiGraphics::RenderPass renderpass_depthprepass; - wiGraphics::RenderPass renderpass_main; - wiGraphics::RenderPass renderpass_transparent; - wiGraphics::RenderPass renderpass_reflection_depthprepass; - wiGraphics::RenderPass renderpass_reflection; - wiGraphics::RenderPass renderpass_downsamplescene; - wiGraphics::RenderPass renderpass_lightshafts; - wiGraphics::RenderPass renderpass_volumetriclight; - wiGraphics::RenderPass renderpass_particledistortion; - wiGraphics::RenderPass renderpass_waterripples; - - wiGraphics::Texture debugUAV; // debug UAV can be used by some shaders... - wiRenderer::TiledLightResources tiledLightResources; - wiRenderer::TiledLightResources tiledLightResources_planarReflection; - wiRenderer::LuminanceResources luminanceResources; - wiRenderer::SSAOResources ssaoResources; - wiRenderer::MSAOResources msaoResources; - wiRenderer::RTAOResources rtaoResources; - wiRenderer::RTReflectionResources rtreflectionResources; - wiRenderer::SSRResources ssrResources; - wiRenderer::RTShadowResources rtshadowResources; - wiRenderer::ScreenSpaceShadowResources screenspaceshadowResources; - wiRenderer::DepthOfFieldResources depthoffieldResources; - wiRenderer::MotionBlurResources motionblurResources; - wiRenderer::VolumetricCloudResources volumetriccloudResources; - wiRenderer::VolumetricCloudResources volumetriccloudResources_reflection; - wiRenderer::BloomResources bloomResources; - wiRenderer::SurfelGIResources surfelGIResources; - - mutable const wiGraphics::Texture* lastPostprocessRT = &rtPostprocess; - // Post-processes are ping-ponged, this function helps to obtain the last postprocess render target that was written - const wiGraphics::Texture* GetLastPostprocessRT() const - { - return lastPostprocessRT; - } - - virtual void RenderAO(wiGraphics::CommandList cmd) const; - virtual void RenderSSR(wiGraphics::CommandList cmd) const; - virtual void RenderOutline(wiGraphics::CommandList cmd) const; - virtual void RenderLightShafts(wiGraphics::CommandList cmd) const; - virtual void RenderVolumetrics(wiGraphics::CommandList cmd) const; - virtual void RenderSceneMIPChain(wiGraphics::CommandList cmd) const; - virtual void RenderTransparents(wiGraphics::CommandList cmd) const; - virtual void RenderPostprocessChain(wiGraphics::CommandList cmd) const; - - void ResizeBuffers() override; - - wiScene::CameraComponent* camera = &wiScene::GetCamera(); - wiScene::CameraComponent camera_previous; - wiScene::CameraComponent camera_reflection; - wiScene::CameraComponent camera_reflection_previous; - - wiScene::Scene* scene = &wiScene::GetScene(); - wiRenderer::Visibility visibility_main; - wiRenderer::Visibility visibility_reflection; - - FrameCB frameCB = {}; - - const wiGraphics::Texture* GetDepthStencil() const override { return &depthBuffer_Main; } - const wiGraphics::Texture* GetGUIBlurredBackground() const override { return &rtGUIBlurredBackground[2]; } - - constexpr float getExposure() const { return exposure; } - constexpr float getBloomThreshold() const { return bloomThreshold; } - constexpr float getMotionBlurStrength() const { return motionBlurStrength; } - constexpr float getDepthOfFieldStrength() const { return dofStrength; } - constexpr float getSharpenFilterAmount() const { return sharpenFilterAmount; } - constexpr float getOutlineThreshold() const { return outlineThreshold; } - constexpr float getOutlineThickness() const { return outlineThickness; } - constexpr XMFLOAT4 getOutlineColor() const { return outlineColor; } - constexpr float getAORange() const { return aoRange; } - constexpr uint32_t getAOSampleCount() const { return aoSampleCount; } - constexpr float getAOPower() const { return aoPower; } - constexpr float getChromaticAberrationAmount() const { return chromaticAberrationAmount; } - constexpr uint32_t getScreenSpaceShadowSampleCount() const { return screenSpaceShadowSampleCount; } - constexpr float getScreenSpaceShadowRange() const { return screenSpaceShadowRange; } - constexpr float getEyeAdaptionKey() const { return eyeadaptionKey; } - constexpr float getEyeAdaptionRate() const { return eyeadaptionRate; } - constexpr float getFSRSharpness() const { return fsrSharpness; } - - constexpr bool getAOEnabled() const { return ao != AO_DISABLED; } - constexpr AO getAO() const { return ao; } - constexpr bool getSSREnabled() const { return ssrEnabled; } - constexpr bool getRaytracedReflectionEnabled() const { return raytracedReflectionsEnabled; } - constexpr bool getShadowsEnabled() const { return shadowsEnabled; } - constexpr bool getReflectionsEnabled() const { return reflectionsEnabled; } - constexpr bool getFXAAEnabled() const { return fxaaEnabled; } - constexpr bool getBloomEnabled() const { return bloomEnabled; } - constexpr bool getColorGradingEnabled() const { return colorGradingEnabled; } - constexpr bool getVolumeLightsEnabled() const { return volumeLightsEnabled; } - constexpr bool getLightShaftsEnabled() const { return lightShaftsEnabled; } - constexpr bool getLensFlareEnabled() const { return lensFlareEnabled; } - constexpr bool getMotionBlurEnabled() const { return motionBlurEnabled; } - constexpr bool getDepthOfFieldEnabled() const { return depthOfFieldEnabled; } - constexpr bool getEyeAdaptionEnabled() const { return eyeAdaptionEnabled; } - constexpr bool getSharpenFilterEnabled() const { return sharpenFilterEnabled && getSharpenFilterAmount() > 0; } - constexpr bool getOutlineEnabled() const { return outlineEnabled; } - constexpr bool getChromaticAberrationEnabled() const { return chromaticAberrationEnabled; } - constexpr bool getDitherEnabled() const { return ditherEnabled; } - constexpr bool getOcclusionCullingEnabled() const { return occlusionCullingEnabled; } - constexpr bool getSceneUpdateEnabled() const { return sceneUpdateEnabled; } - constexpr bool getFSREnabled() const { return fsrEnabled; } - - constexpr uint32_t getMSAASampleCount() const { return msaaSampleCount; } - - constexpr void setExposure(float value) { exposure = value; } - constexpr void setBloomThreshold(float value){ bloomThreshold = value; } - constexpr void setMotionBlurStrength(float value) { motionBlurStrength = value; } - constexpr void setDepthOfFieldStrength(float value) { dofStrength = value; } - constexpr void setSharpenFilterAmount(float value) { sharpenFilterAmount = value; } - constexpr void setOutlineThreshold(float value) { outlineThreshold = value; } - constexpr void setOutlineThickness(float value) { outlineThickness = value; } - constexpr void setOutlineColor(const XMFLOAT4& value) { outlineColor = value; } - constexpr void setAORange(float value) { aoRange = value; } - constexpr void setAOSampleCount(uint32_t value) { aoSampleCount = value; } - constexpr void setAOPower(float value) { aoPower = value; } - constexpr void setChromaticAberrationAmount(float value) { chromaticAberrationAmount = value; } - constexpr void setScreenSpaceShadowSampleCount(uint32_t value) { screenSpaceShadowSampleCount = value; } - constexpr void setScreenSpaceShadowRange(float value) { screenSpaceShadowRange = value; } - constexpr void setEyeAdaptionKey(float value) { eyeadaptionKey = value; } - constexpr void setEyeAdaptionRate(float value) { eyeadaptionRate = value; } - constexpr void setFSRSharpness(float value) { fsrSharpness = value; } - - void setAO(AO value); - void setSSREnabled(bool value); - void setRaytracedReflectionsEnabled(bool value); - constexpr void setShadowsEnabled(bool value){ shadowsEnabled = value; } - constexpr void setReflectionsEnabled(bool value){ reflectionsEnabled = value; } - constexpr void setFXAAEnabled(bool value){ fxaaEnabled = value; } - constexpr void setBloomEnabled(bool value){ bloomEnabled = value; } - constexpr void setColorGradingEnabled(bool value){ colorGradingEnabled = value; } - constexpr void setVolumeLightsEnabled(bool value){ volumeLightsEnabled = value; } - constexpr void setLightShaftsEnabled(bool value){ lightShaftsEnabled = value; } - constexpr void setLensFlareEnabled(bool value){ lensFlareEnabled = value; } - constexpr void setMotionBlurEnabled(bool value){ motionBlurEnabled = value; } - constexpr void setDepthOfFieldEnabled(bool value){ depthOfFieldEnabled = value; } - constexpr void setEyeAdaptionEnabled(bool value) { eyeAdaptionEnabled = value; } - constexpr void setSharpenFilterEnabled(bool value) { sharpenFilterEnabled = value; } - constexpr void setOutlineEnabled(bool value) { outlineEnabled = value; } - constexpr void setChromaticAberrationEnabled(bool value) { chromaticAberrationEnabled = value; } - constexpr void setDitherEnabled(bool value) { ditherEnabled = value; } - constexpr void setOcclusionCullingEnabled(bool value) { occlusionCullingEnabled = value; } - constexpr void setSceneUpdateEnabled(bool value) { sceneUpdateEnabled = value; } - void setFSREnabled(bool value); - - virtual void setMSAASampleCount(uint32_t value) { msaaSampleCount = value; } - - void PreUpdate() override; - void Update(float dt) override; - void Render() const override; - void Compose(wiGraphics::CommandList cmd) const override; -}; - diff --git a/WickedEngine/RenderPath3D_BindLua.cpp b/WickedEngine/RenderPath3D_BindLua.cpp deleted file mode 100644 index 74d4c5b87..000000000 --- a/WickedEngine/RenderPath3D_BindLua.cpp +++ /dev/null @@ -1,379 +0,0 @@ -#include "RenderPath3D_BindLua.h" -#include "Texture_BindLua.h" - -const char RenderPath3D_BindLua::className[] = "RenderPath3D"; - -Luna::FunctionType RenderPath3D_BindLua::methods[] = { - lunamethod(RenderPath2D_BindLua, AddSprite), - lunamethod(RenderPath2D_BindLua, AddFont), - lunamethod(RenderPath2D_BindLua, RemoveSprite), - lunamethod(RenderPath2D_BindLua, RemoveFont), - lunamethod(RenderPath2D_BindLua, ClearSprites), - lunamethod(RenderPath2D_BindLua, ClearFonts), - lunamethod(RenderPath2D_BindLua, GetSpriteOrder), - lunamethod(RenderPath2D_BindLua, GetFontOrder), - - lunamethod(RenderPath2D_BindLua, AddLayer), - lunamethod(RenderPath2D_BindLua, GetLayers), - lunamethod(RenderPath2D_BindLua, SetLayerOrder), - lunamethod(RenderPath2D_BindLua, SetSpriteOrder), - lunamethod(RenderPath2D_BindLua, SetFontOrder), - - lunamethod(RenderPath_BindLua, GetLayerMask), - lunamethod(RenderPath_BindLua, SetLayerMask), - - lunamethod(RenderPath3D_BindLua, SetAO), - lunamethod(RenderPath3D_BindLua, SetSSREnabled), - lunamethod(RenderPath3D_BindLua, SetRaytracedReflectionsEnabled), - lunamethod(RenderPath3D_BindLua, SetShadowsEnabled), - lunamethod(RenderPath3D_BindLua, SetReflectionsEnabled), - lunamethod(RenderPath3D_BindLua, SetFXAAEnabled), - lunamethod(RenderPath3D_BindLua, SetBloomEnabled), - lunamethod(RenderPath3D_BindLua, SetBloomThreshold), - lunamethod(RenderPath3D_BindLua, SetColorGradingEnabled), - lunamethod(RenderPath3D_BindLua, SetVolumeLightsEnabled), - lunamethod(RenderPath3D_BindLua, SetLightShaftsEnabled), - lunamethod(RenderPath3D_BindLua, SetLensFlareEnabled), - lunamethod(RenderPath3D_BindLua, SetMotionBlurEnabled), - lunamethod(RenderPath3D_BindLua, SetDitherEnabled), - lunamethod(RenderPath3D_BindLua, SetDepthOfFieldEnabled), - lunamethod(RenderPath3D_BindLua, SetEyeAdaptionEnabled), - lunamethod(RenderPath3D_BindLua, SetMSAASampleCount), - lunamethod(RenderPath3D_BindLua, SetSharpenFilterEnabled), - lunamethod(RenderPath3D_BindLua, SetSharpenFilterAmount), - lunamethod(RenderPath3D_BindLua, SetExposure), - lunamethod(RenderPath3D_BindLua, SetMotionBlurStrength), - lunamethod(RenderPath3D_BindLua, SetDepthOfFieldStrength), - { NULL, NULL } -}; -Luna::PropertyType RenderPath3D_BindLua::properties[] = { - { NULL, NULL } -}; - - -int RenderPath3D_BindLua::SetAO(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetAO(AO value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - int value = wiLua::SGetInt(L, 1); - RenderPath3D::AO ao = (RenderPath3D::AO)value; - ((RenderPath3D*)component)->setAO(ao); - } - else - wiLua::SError(L, "SetAO(AO value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetSSREnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetSSREnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setSSREnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetSSREnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetRaytracedReflectionsEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetRaytracedReflectionsEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setRaytracedReflectionsEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetRaytracedReflectionsEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetShadowsEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetShadowsEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setShadowsEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetShadowsEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetReflectionsEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetShadowsEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setReflectionsEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetShadowsEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetFXAAEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetFXAAEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setFXAAEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetFXAAEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetBloomEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetBloomEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setBloomEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetBloomEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetBloomThreshold(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetBloomThreshold(float value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setBloomThreshold(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetBloomThreshold(float value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetColorGradingEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetColorGradingEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setColorGradingEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetColorGradingEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetVolumeLightsEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetVolumeLightsEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setVolumeLightsEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetVolumeLightsEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetLightShaftsEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetLightShaftsEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setLightShaftsEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetLightShaftsEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetLensFlareEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetLensFlareEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setLensFlareEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetLensFlareEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetMotionBlurEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetMotionBlurEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setMotionBlurEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetMotionBlurEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetDitherEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetDitherEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - ((RenderPath3D*)component)->setDitherEnabled(wiLua::SGetBool(L, 1)); - else - wiLua::SError(L, "SetDitherEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetDepthOfFieldEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetDepthOfFieldEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setDepthOfFieldEnabled(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetDepthOfFieldEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetEyeAdaptionEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetEyeAdaptionEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setEyeAdaptionEnabled(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetEyeAdaptionEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetMSAASampleCount(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetMSAASampleCount(int value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setMSAASampleCount((uint32_t)wiLua::SGetInt(L, 1)); - } - else - wiLua::SError(L, "SetMSAASampleCount(int value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetSharpenFilterEnabled(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetSharpenFilterEnabled(bool value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setSharpenFilterEnabled(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "SetSharpenFilterEnabled(bool value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetSharpenFilterAmount(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetSharpenFilterAmount(float value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setSharpenFilterAmount(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetSharpenFilterAmount(float value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetExposure(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetExposure(float value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setExposure(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetExposure(float value) not enough arguments!"); - return 0; -} - - -int RenderPath3D_BindLua::SetMotionBlurStrength(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetMotionBlurStrength(float value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setMotionBlurStrength(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetMotionBlurStrength(float value) not enough arguments!"); - return 0; -} -int RenderPath3D_BindLua::SetDepthOfFieldStrength(lua_State* L) -{ - if (component == nullptr) - { - wiLua::SError(L, "SetDepthOfFieldStrength(float value) component is null!"); - return 0; - } - if (wiLua::SGetArgCount(L) > 0) - { - ((RenderPath3D*)component)->setDepthOfFieldStrength(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "SetDepthOfFieldStrength(float value) not enough arguments!"); - return 0; -} - -void RenderPath3D_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - - wiLua::RunText("AO_DISABLED = 0"); - wiLua::RunText("AO_SSAO = 1"); - wiLua::RunText("AO_HBAO = 2"); - wiLua::RunText("AO_MSAO = 3"); - wiLua::RunText("AO_RTAO = 4"); - } -} diff --git a/WickedEngine/RenderPath3D_BindLua.h b/WickedEngine/RenderPath3D_BindLua.h deleted file mode 100644 index f1a4e97ba..000000000 --- a/WickedEngine/RenderPath3D_BindLua.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "RenderPath3D.h" -#include "RenderPath2D_BindLua.h" - -class RenderPath3D_BindLua : public RenderPath2D_BindLua -{ -private: - RenderPath3D renderpath; -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - RenderPath3D_BindLua() = default; - RenderPath3D_BindLua(RenderPath3D* component) - { - this->component = component; - } - RenderPath3D_BindLua(lua_State* L) - { - this->component = &renderpath; - } - - int SetAO(lua_State* L); - int SetSSREnabled(lua_State* L); - int SetRaytracedReflectionsEnabled(lua_State* L); - int SetShadowsEnabled(lua_State* L); - int SetReflectionsEnabled(lua_State* L); - int SetFXAAEnabled(lua_State* L); - int SetBloomEnabled(lua_State* L); - int SetBloomThreshold(lua_State* L); - int SetColorGradingEnabled(lua_State* L); - int SetVolumeLightsEnabled(lua_State* L); - int SetLightShaftsEnabled(lua_State* L); - int SetLensFlareEnabled(lua_State* L); - int SetMotionBlurEnabled(lua_State* L); - int SetDitherEnabled(lua_State* L); - int SetDepthOfFieldEnabled(lua_State* L); - int SetEyeAdaptionEnabled(lua_State* L); - int SetMSAASampleCount(lua_State* L); - int SetSharpenFilterEnabled(lua_State* L); - int SetSharpenFilterAmount(lua_State* L); - int SetExposure(lua_State* L); - int SetMotionBlurStrength(lua_State* L); - int SetDepthOfFieldStrength(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/RenderPath3D_PathTracing.cpp b/WickedEngine/RenderPath3D_PathTracing.cpp deleted file mode 100644 index 477524468..000000000 --- a/WickedEngine/RenderPath3D_PathTracing.cpp +++ /dev/null @@ -1,406 +0,0 @@ -#include "RenderPath3D_PathTracing.h" -#include "wiRenderer.h" -#include "wiImage.h" -#include "wiHelper.h" -#include "wiTextureHelper.h" -#include "wiSprite.h" -#include "wiProfiler.h" -#include "wiScene.h" -#include "wiBackLog.h" - -#if __has_include("OpenImageDenoise/oidn.hpp") -#define OPEN_IMAGE_DENOISE -#include "OpenImageDenoise/oidn.hpp" -#pragma comment(lib,"OpenImageDenoise.lib") -#pragma comment(lib,"tbb.lib") -// Also provide OpenImageDenoise.dll and tbb.dll near the exe! -bool DenoiserCallback(void* userPtr, double n) -{ - auto renderpath = (RenderPath3D_PathTracing*)userPtr; - if (renderpath->getProgress() < 1) - { - renderpath->denoiserProgress = 0; - return false; - } - renderpath->denoiserProgress = (float)n; - return true; -} -bool RenderPath3D_PathTracing::isDenoiserAvailable() const { return true; } -#else -bool RenderPath3D_PathTracing::isDenoiserAvailable() const { return false; } -#endif - - -using namespace wiGraphics; -using namespace wiScene; - - -void RenderPath3D_PathTracing::ResizeBuffers() -{ - RenderPath2D::ResizeBuffers(); // we don't need to use any buffers from RenderPath3D, so skip those - - GraphicsDevice* device = wiGraphics::GetDevice(); - - XMUINT2 internalResolution = GetInternalResolution(); - - { - TextureDesc desc; - desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE | BindFlag::RENDER_TARGET; - desc.format = Format::R32G32B32A32_FLOAT; - desc.width = internalResolution.x; - desc.height = internalResolution.y; - device->CreateTexture(&desc, nullptr, &traceResult); - device->SetName(&traceResult, "traceResult"); - -#ifdef OPEN_IMAGE_DENOISE - desc.bind_flags = BindFlag::UNORDERED_ACCESS; - desc.layout = ResourceState::UNORDERED_ACCESS; - device->CreateTexture(&desc, nullptr, &denoiserAlbedo); - device->SetName(&denoiserAlbedo, "denoiserAlbedo"); - device->CreateTexture(&desc, nullptr, &denoiserNormal); - device->SetName(&denoiserNormal, "denoiserNormal"); -#endif // OPEN_IMAGE_DENOISE - } - { - TextureDesc desc; - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.format = Format::R11G11B10_FLOAT; - desc.width = internalResolution.x; - desc.height = internalResolution.y; - device->CreateTexture(&desc, nullptr, &rtPostprocess); - device->SetName(&rtPostprocess, "rtPostprocess"); - - - desc.width /= 4; - desc.height /= 4; - desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE; - device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[0]); - device->SetName(&rtGUIBlurredBackground[0], "rtGUIBlurredBackground[0]"); - - desc.width /= 4; - desc.height /= 4; - device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[1]); - device->SetName(&rtGUIBlurredBackground[1], "rtGUIBlurredBackground[1]"); - device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[2]); - device->SetName(&rtGUIBlurredBackground[2], "rtGUIBlurredBackground[2]"); - } - - { - RenderPassDesc desc; - desc.attachments.push_back(RenderPassAttachment::RenderTarget(&traceResult, RenderPassAttachment::LoadOp::CLEAR)); - - device->CreateRenderPass(&desc, &renderpass_debugbvh); - } - - wiRenderer::CreateLuminanceResources(luminanceResources, internalResolution); - wiRenderer::CreateBloomResources(bloomResources, internalResolution); - - // also reset accumulation buffer state: - sam = -1; -} - -void RenderPath3D_PathTracing::Update(float dt) -{ - setOcclusionCullingEnabled(false); - - if (camera->IsDirty()) - { - camera->SetDirty(false); - sam = -1; - } - else - { - for (size_t i = 0; i < scene->transforms.GetCount(); ++i) - { - const TransformComponent& transform = scene->transforms[i]; - - if (transform.IsDirty()) - { - sam = -1; - break; - } - } - - if (sam >= 0) - { - for (size_t i = 0; i < scene->materials.GetCount(); ++i) - { - const MaterialComponent& material = scene->materials[i]; - - if (material.IsDirty()) - { - sam = -1; - break; - } - } - } - } - sam++; - - if (sam > target) - { - sam = target; - } - if (target < sam) - { - resetProgress(); - } - - scene->SetAccelerationStructureUpdateRequested(sam == 0); - setSceneUpdateEnabled(sam == 0); - - RenderPath3D::Update(dt); - - -#ifdef OPEN_IMAGE_DENOISE - if (sam == target) - { - if (!denoiserResult.IsValid() && !wiJobSystem::IsBusy(denoiserContext)) - { - //wiHelper::saveTextureToFile(denoiserAlbedo, "C:/PROJECTS/WickedEngine/Editor/_albedo.png"); - //wiHelper::saveTextureToFile(denoiserNormal, "C:/PROJECTS/WickedEngine/Editor/_normal.png"); - - texturedata_src.clear(); - texturedata_dst.clear(); - texturedata_albedo.clear(); - texturedata_normal.clear(); - - if (wiHelper::saveTextureToMemory(traceResult, texturedata_src)) - { - wiHelper::saveTextureToMemory(denoiserAlbedo, texturedata_albedo); - wiHelper::saveTextureToMemory(denoiserNormal, texturedata_normal); - - texturedata_dst.resize(texturedata_src.size()); - - wiJobSystem::Execute(denoiserContext, [&](wiJobArgs args) { - - size_t width = (size_t)traceResult.desc.width; - size_t height = (size_t)traceResult.desc.height; - { - // https://github.com/OpenImageDenoise/oidn#c11-api-example - - // Create an Intel Open Image Denoise device - static oidn::DeviceRef device = oidn::newDevice(); - static bool init = false; - if (!init) - { - device.commit(); - init = true; - } - - // Create a denoising filter - oidn::FilterRef filter = device.newFilter("RT"); // generic ray tracing filter - filter.setImage("color", texturedata_src.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); - if (!texturedata_albedo.empty()) - { - filter.setImage("albedo", texturedata_albedo.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); // optional - } - if (!texturedata_normal.empty()) - { - filter.setImage("normal", texturedata_normal.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); // optional - } - filter.setImage("output", texturedata_dst.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); - filter.set("hdr", true); // image is HDR - //filter.set("cleanAux", true); - filter.commit(); - - denoiserProgress = 0; - filter.setProgressMonitorFunction(DenoiserCallback, this); - - // Filter the image - filter.execute(); - - // Check for errors - const char* errorMessage; - auto error = device.getError(errorMessage); - if (error != oidn::Error::None && error != oidn::Error::Cancelled) - { - wiBackLog::post(std::string("[OpenImageDenoise error] ") + errorMessage); - } - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - - TextureDesc desc; - desc.width = (uint32_t)width; - desc.height = (uint32_t)height; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - desc.format = Format::R32G32B32A32_FLOAT; - - SubresourceData initdata; - initdata.data_ptr = texturedata_dst.data(); - initdata.row_pitch = uint32_t(sizeof(XMFLOAT4) * width); - device->CreateTexture(&desc, &initdata, &denoiserResult); - - }); - } - } - } - else - { - denoiserResult = Texture(); - denoiserProgress = 0; - } -#endif // OPEN_IMAGE_DENOISE -} - -void RenderPath3D_PathTracing::Render() const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - wiJobSystem::context ctx; - - if (sam < target) - { - // Setup: - CommandList cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { - - wiRenderer::BindCameraCB( - *camera, - camera_previous, - camera_reflection, - cmd - ); - wiRenderer::UpdateRenderData(visibility_main, frameCB, cmd); - wiRenderer::UpdateRenderDataAsync(visibility_main, frameCB, cmd); - - if (scene->IsAccelerationStructureUpdateRequested()) - { - wiRenderer::UpdateRaytracingAccelerationStructures(*scene, cmd); - } - }); - - // Main scene: - cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { - - GraphicsDevice* device = wiGraphics::GetDevice(); - - wiRenderer::BindCameraCB( - *camera, - *camera, - *camera, - cmd - ); - wiRenderer::BindCommonResources(cmd); - - if (wiRenderer::GetRaytraceDebugBVHVisualizerEnabled()) - { - device->RenderPassBegin(&renderpass_debugbvh, cmd); - - Viewport vp; - vp.width = (float)traceResult.GetDesc().width; - vp.height = (float)traceResult.GetDesc().height; - device->BindViewports(1, &vp, cmd); - - wiRenderer::RayTraceSceneBVH(*scene, cmd); - - device->RenderPassEnd(cmd); - } - else - { - auto range = wiProfiler::BeginRangeGPU("Traced Scene", cmd); - - wiRenderer::RayTraceScene( - *scene, - traceResult, - sam, - cmd, - denoiserAlbedo.IsValid() ? &denoiserAlbedo : nullptr, - denoiserNormal.IsValid() ? &denoiserNormal : nullptr - ); - - - wiProfiler::EndRange(range); // Traced Scene - } - - }); - } - - // Tonemap etc: - CommandList cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { - - GraphicsDevice* device = wiGraphics::GetDevice(); - - wiRenderer::BindCameraCB( - *camera, - *camera, - *camera, - cmd - ); - wiRenderer::BindCommonResources(cmd); - - Texture srcTex = denoiserResult.IsValid() && !wiJobSystem::IsBusy(denoiserContext) ? denoiserResult : traceResult; - - if (getEyeAdaptionEnabled()) - { - wiRenderer::ComputeLuminance( - luminanceResources, - srcTex, - cmd, - getEyeAdaptionRate(), - getEyeAdaptionKey() - ); - } - if (getBloomEnabled()) - { - wiRenderer::ComputeBloom( - bloomResources, - srcTex, - cmd, - getBloomThreshold(), - getExposure(), - getEyeAdaptionEnabled() ? &luminanceResources.luminance : nullptr - ); - } - - wiRenderer::Postprocess_Tonemap( - srcTex, - rtPostprocess, - cmd, - getExposure(), - getDitherEnabled(), - getColorGradingEnabled() ? (scene->weather.colorGradingMap == nullptr ? nullptr : &scene->weather.colorGradingMap->texture) : nullptr, - nullptr, - getEyeAdaptionEnabled() ? &luminanceResources.luminance : nullptr, - getBloomEnabled() ? &bloomResources.texture_bloom : nullptr, - colorspace - ); - lastPostprocessRT = &rtPostprocess; - - // GUI Background blurring: - { - auto range = wiProfiler::BeginRangeGPU("GUI Background Blur", cmd); - device->EventBegin("GUI Background Blur", cmd); - wiRenderer::Postprocess_Downsample4x(rtPostprocess, rtGUIBlurredBackground[0], cmd); - wiRenderer::Postprocess_Downsample4x(rtGUIBlurredBackground[0], rtGUIBlurredBackground[2], cmd); - wiRenderer::Postprocess_Blur_Gaussian(rtGUIBlurredBackground[2], rtGUIBlurredBackground[1], rtGUIBlurredBackground[2], cmd, -1, -1, true); - device->EventEnd(cmd); - wiProfiler::EndRange(range); - } - }); - - RenderPath2D::Render(); - - wiJobSystem::Wait(ctx); -} - -void RenderPath3D_PathTracing::Compose(CommandList cmd) const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - device->EventBegin("RenderPath3D_PathTracing::Compose", cmd); - - wiRenderer::BindCommonResources(cmd); - - wiImageParams fx; - fx.enableFullScreen(); - fx.blendFlag = BLENDMODE_OPAQUE; - fx.quality = QUALITY_LINEAR; - wiImage::Draw(&rtPostprocess, fx, cmd); - - device->EventEnd(cmd); - - RenderPath2D::Compose(cmd); -} diff --git a/WickedEngine/RenderPath3D_PathTracing.h b/WickedEngine/RenderPath3D_PathTracing.h deleted file mode 100644 index 7fe4c6223..000000000 --- a/WickedEngine/RenderPath3D_PathTracing.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include "RenderPath3D.h" -#include "wiVector.h" - -class RenderPath3D_PathTracing : - public RenderPath3D -{ -protected: - int sam = -1; - int target = 1024; - wiGraphics::Texture traceResult; - - wi::vector texturedata_src; - wi::vector texturedata_dst; - wi::vector texturedata_albedo; - wi::vector texturedata_normal; - wiGraphics::Texture denoiserAlbedo; - wiGraphics::Texture denoiserNormal; - wiGraphics::Texture denoiserResult; - wiJobSystem::context denoiserContext; - - wiGraphics::RenderPass renderpass_debugbvh; - - void ResizeBuffers() override; - -public: - const wiGraphics::Texture* GetDepthStencil() const override { return nullptr; }; - - void Update(float dt) override; - void Render() const override; - void Compose(wiGraphics::CommandList cmd) const override; - - int getCurrentSampleCount() const { return sam; } - void setTargetSampleCount(int value) { target = value; } - float getProgress() const { return (float)sam / (float)target; } - - float denoiserProgress = 0; - float getDenoiserProgress() const { return denoiserProgress; } - bool isDenoiserAvailable() const; - - void resetProgress() { sam = -1; denoiserProgress = 0; } -}; diff --git a/WickedEngine/RenderPath_BindLua.cpp b/WickedEngine/RenderPath_BindLua.cpp deleted file mode 100644 index 5ba11788a..000000000 --- a/WickedEngine/RenderPath_BindLua.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "RenderPath_BindLua.h" - -const char RenderPath_BindLua::className[] = "RenderPath"; - -Luna::FunctionType RenderPath_BindLua::methods[] = { - lunamethod(RenderPath_BindLua, GetLayerMask), - lunamethod(RenderPath_BindLua, SetLayerMask), - { NULL, NULL } -}; -Luna::PropertyType RenderPath_BindLua::properties[] = { - { NULL, NULL } -}; - - -int RenderPath_BindLua::GetLayerMask(lua_State* L) -{ - uint32_t mask = component->getLayerMask(); - wiLua::SSetInt(L, *reinterpret_cast(&mask)); - return 1; -} -int RenderPath_BindLua::SetLayerMask(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - int mask = wiLua::SGetInt(L, 1); - component->setlayerMask(*reinterpret_cast(&mask)); - } - else - wiLua::SError(L, "SetLayerMask(uint mask) not enough arguments!"); - return 0; -} - -void RenderPath_BindLua::Bind() -{ - - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} - diff --git a/WickedEngine/RenderPath_BindLua.h b/WickedEngine/RenderPath_BindLua.h deleted file mode 100644 index 890a5cc61..000000000 --- a/WickedEngine/RenderPath_BindLua.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "RenderPath.h" - -class RenderPath_BindLua -{ -public: - RenderPath* component = nullptr; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - RenderPath_BindLua() = default; - RenderPath_BindLua(RenderPath* component) :component(component) {} - RenderPath_BindLua(lua_State* L) {} - - virtual int GetLayerMask(lua_State* L); - virtual int SetLayerMask(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/SpriteAnim_BindLua.cpp b/WickedEngine/SpriteAnim_BindLua.cpp deleted file mode 100644 index dd8f2d220..000000000 --- a/WickedEngine/SpriteAnim_BindLua.cpp +++ /dev/null @@ -1,415 +0,0 @@ -#include "SpriteAnim_BindLua.h" -#include "Vector_BindLua.h" - -const char SpriteAnim_BindLua::className[] = "SpriteAnim"; - -Luna::FunctionType SpriteAnim_BindLua::methods[] = { - lunamethod(SpriteAnim_BindLua, SetRot), - lunamethod(SpriteAnim_BindLua, SetRotation), - lunamethod(SpriteAnim_BindLua, SetOpacity), - lunamethod(SpriteAnim_BindLua, SetFade), - lunamethod(SpriteAnim_BindLua, SetRepeatable), - lunamethod(SpriteAnim_BindLua, SetVelocity), - lunamethod(SpriteAnim_BindLua, SetScaleX), - lunamethod(SpriteAnim_BindLua, SetScaleY), - lunamethod(SpriteAnim_BindLua, SetMovingTexAnim), - lunamethod(SpriteAnim_BindLua, SetDrawRecAnim), - - lunamethod(SpriteAnim_BindLua, GetRot), - lunamethod(SpriteAnim_BindLua, GetRotation), - lunamethod(SpriteAnim_BindLua, GetOpacity), - lunamethod(SpriteAnim_BindLua, GetFade), - lunamethod(SpriteAnim_BindLua, GetRepeatable), - lunamethod(SpriteAnim_BindLua, GetVelocity), - lunamethod(SpriteAnim_BindLua, GetScaleX), - lunamethod(SpriteAnim_BindLua, GetScaleY), - lunamethod(SpriteAnim_BindLua, GetMovingTexAnim), - lunamethod(SpriteAnim_BindLua, GetDrawRecAnim), - { NULL, NULL } -}; -Luna::PropertyType SpriteAnim_BindLua::properties[] = { - { NULL, NULL } -}; - -SpriteAnim_BindLua::SpriteAnim_BindLua(const wiSprite::Anim& anim) :anim(anim) -{ -} - -SpriteAnim_BindLua::SpriteAnim_BindLua(lua_State *L) -{ - anim = wiSprite::Anim(); -} - - - -int SpriteAnim_BindLua::SetRot(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.rot = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetRot(float rot) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetRotation(lua_State *L) -{ - return SetRot(L); -} -int SpriteAnim_BindLua::SetOpacity(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.opa = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetOpacity(float val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetFade(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.fad = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetFade(float val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetRepeatable(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.repeatable = wiLua::SGetBool(L, 1); - } - else - { - wiLua::SError(L, "SetRepeatable(float val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetVelocity(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&anim.vel, XMLoadFloat4(vec)); - } - else - { - wiLua::SError(L, "SetVelocity(Vector val) argument is not a Vector!"); - } - } - else - { - wiLua::SError(L, "SetVelocity(Vector val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetScaleX(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.scaleX = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetScaleX(float val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetScaleY(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.scaleY = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetScaleY(float val) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetMovingTexAnim(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - MovingTexAnim_BindLua* data = Luna::lightcheck(L, 1); - if (data != nullptr) - { - anim.movingTexAnim = data->anim; - } - else - { - wiLua::SError(L, "SetMovingTexAnim(MovingTexAnim data) argument is not a MovingTexAnim!"); - } - } - else - { - wiLua::SError(L, "SetMovingTexAnim(MovingTexAnim data) not enough arguments!"); - } - return 0; -} -int SpriteAnim_BindLua::SetDrawRecAnim(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - DrawRectAnim_BindLua* data = Luna::lightcheck(L, 1); - if (data != nullptr) - { - anim.drawRectAnim = data->anim; - } - else - { - wiLua::SError(L, "SetDrawRecAnim(DrawRecAnim data) argument is not a DrawRecAnim!"); - } - } - else - { - wiLua::SError(L, "SetDrawRecAnim(DrawRecAnim data) not enough arguments!"); - } - return 0; -} - -int SpriteAnim_BindLua::GetRot(lua_State *L) -{ - wiLua::SSetFloat(L, anim.rot); - return 1; -} -int SpriteAnim_BindLua::GetRotation(lua_State *L) -{ - return GetRot(L); -} -int SpriteAnim_BindLua::GetOpacity(lua_State *L) -{ - wiLua::SSetFloat(L, anim.opa); - return 1; -} -int SpriteAnim_BindLua::GetFade(lua_State *L) -{ - wiLua::SSetFloat(L, anim.fad); - return 1; -} -int SpriteAnim_BindLua::GetRepeatable(lua_State *L) -{ - wiLua::SSetBool(L, anim.repeatable); - return 1; -} -int SpriteAnim_BindLua::GetVelocity(lua_State *L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat3(&anim.vel))); - return 1; -} -int SpriteAnim_BindLua::GetScaleX(lua_State *L) -{ - wiLua::SSetFloat(L, anim.scaleX); - return 1; -} -int SpriteAnim_BindLua::GetScaleY(lua_State *L) -{ - wiLua::SSetFloat(L, anim.scaleY); - return 1; -} -int SpriteAnim_BindLua::GetMovingTexAnim(lua_State *L) -{ - Luna::push(L, new MovingTexAnim_BindLua(anim.movingTexAnim)); - return 1; -} -int SpriteAnim_BindLua::GetDrawRecAnim(lua_State *L) -{ - Luna::push(L, new DrawRectAnim_BindLua(anim.drawRectAnim)); - return 1; -} - -void SpriteAnim_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - Luna::Register(wiLua::GetLuaState()); - Luna::Register(wiLua::GetLuaState()); - } -} - - - - -const char MovingTexAnim_BindLua::className[] = "MovingTexAnim"; - -Luna::FunctionType MovingTexAnim_BindLua::methods[] = { - lunamethod(MovingTexAnim_BindLua, SetSpeedX), - lunamethod(MovingTexAnim_BindLua, SetSpeedY), - - lunamethod(MovingTexAnim_BindLua, GetSpeedX), - lunamethod(MovingTexAnim_BindLua, GetSpeedY), - { NULL, NULL } -}; -Luna::PropertyType MovingTexAnim_BindLua::properties[] = { - { NULL, NULL } -}; - -MovingTexAnim_BindLua::MovingTexAnim_BindLua(const wiSprite::Anim::MovingTexAnim& anim) :anim(anim) -{ -} - -MovingTexAnim_BindLua::MovingTexAnim_BindLua(lua_State *L) -{ - anim = wiSprite::Anim::MovingTexAnim(); - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.speedX = wiLua::SGetFloat(L, 1); - if (argc > 1) - { - anim.speedY = wiLua::SGetFloat(L, 2); - } - } -} - -MovingTexAnim_BindLua::~MovingTexAnim_BindLua() -{ -} - -int MovingTexAnim_BindLua::SetSpeedX(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.speedX = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetSpeedX(float val) not enough arguments!"); - } - return 0; -} -int MovingTexAnim_BindLua::SetSpeedY(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.speedY = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetSpeedY(float val) not enough arguments!"); - } - return 0; -} - -int MovingTexAnim_BindLua::GetSpeedX(lua_State *L) -{ - wiLua::SSetFloat(L, anim.speedX); - return 1; -} -int MovingTexAnim_BindLua::GetSpeedY(lua_State *L) -{ - wiLua::SSetFloat(L, anim.speedY); - return 1; -} - - - -const char DrawRectAnim_BindLua::className[] = "DrawRecAnim"; - -Luna::FunctionType DrawRectAnim_BindLua::methods[] = { - lunamethod(DrawRectAnim_BindLua, SetFrameRate), - lunamethod(DrawRectAnim_BindLua, SetFrameCount), - lunamethod(DrawRectAnim_BindLua, SetHorizontalFrameCount), - - lunamethod(DrawRectAnim_BindLua, GetFrameRate), - lunamethod(DrawRectAnim_BindLua, GetFrameCount), - lunamethod(DrawRectAnim_BindLua, GetHorizontalFrameCount), - { NULL, NULL } -}; -Luna::PropertyType DrawRectAnim_BindLua::properties[] = { - { NULL, NULL } -}; - -DrawRectAnim_BindLua::DrawRectAnim_BindLua(const wiSprite::Anim::DrawRectAnim& data) :anim(anim) -{ -} - -DrawRectAnim_BindLua::DrawRectAnim_BindLua(lua_State *L) -{ - anim = wiSprite::Anim::DrawRectAnim(); -} - -DrawRectAnim_BindLua::~DrawRectAnim_BindLua() -{ -} - -int DrawRectAnim_BindLua::SetFrameRate(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.frameRate = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetFrameRate(float val) not enough arguments!"); - } - return 0; -} -int DrawRectAnim_BindLua::SetFrameCount(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.frameCount = wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetFrameCount(int val) not enough arguments!"); - } - return 0; -} -int DrawRectAnim_BindLua::SetHorizontalFrameCount(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - anim.horizontalFrameCount = wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetHorizontalFrameCount(int val) not enough arguments!"); - } - return 0; -} - -int DrawRectAnim_BindLua::GetFrameRate(lua_State* L) -{ - wiLua::SSetFloat(L, anim.frameRate); - return 1; -} -int DrawRectAnim_BindLua::GetFrameCount(lua_State* L) -{ - wiLua::SSetInt(L, anim.frameCount); - return 1; -} -int DrawRectAnim_BindLua::GetHorizontalFrameCount(lua_State* L) -{ - wiLua::SSetInt(L, anim.horizontalFrameCount); - return 1; -} diff --git a/WickedEngine/SpriteAnim_BindLua.h b/WickedEngine/SpriteAnim_BindLua.h deleted file mode 100644 index ded128b6e..000000000 --- a/WickedEngine/SpriteAnim_BindLua.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "wiSprite.h" - -class SpriteAnim_BindLua -{ -public: - wiSprite::Anim anim; - - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - SpriteAnim_BindLua(const wiSprite::Anim& anim); - SpriteAnim_BindLua(lua_State *L); - - int SetRot(lua_State *L); - int SetRotation(lua_State *L); - int SetOpacity(lua_State *L); - int SetFade(lua_State *L); - int SetRepeatable(lua_State *L); - int SetVelocity(lua_State *L); - int SetScaleX(lua_State *L); - int SetScaleY(lua_State *L); - int SetMovingTexAnim(lua_State *L); - int SetDrawRecAnim(lua_State *L); - - int GetRot(lua_State *L); - int GetRotation(lua_State *L); - int GetOpacity(lua_State *L); - int GetFade(lua_State *L); - int GetRepeatable(lua_State *L); - int GetVelocity(lua_State *L); - int GetScaleX(lua_State *L); - int GetScaleY(lua_State *L); - int GetMovingTexAnim(lua_State *L); - int GetDrawRecAnim(lua_State *L); - - - static void Bind(); -}; - -class MovingTexAnim_BindLua -{ -public: - wiSprite::Anim::MovingTexAnim anim; - - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - MovingTexAnim_BindLua(const wiSprite::Anim::MovingTexAnim& anim); - MovingTexAnim_BindLua(lua_State *L); - ~MovingTexAnim_BindLua(); - - int SetSpeedX(lua_State* L); - int SetSpeedY(lua_State* L); - - int GetSpeedX(lua_State* L); - int GetSpeedY(lua_State* L); -}; - -class DrawRectAnim_BindLua -{ -public: - wiSprite::Anim::DrawRectAnim anim; - - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - DrawRectAnim_BindLua(const wiSprite::Anim::DrawRectAnim& anim); - DrawRectAnim_BindLua(lua_State *L); - ~DrawRectAnim_BindLua(); - - int SetFrameRate(lua_State* L); - int SetFrameCount(lua_State* L); - int SetHorizontalFrameCount(lua_State* L); - - int GetFrameRate(lua_State* L); - int GetFrameCount(lua_State* L); - int GetHorizontalFrameCount(lua_State* L); -}; - diff --git a/WickedEngine/Texture_BindLua.cpp b/WickedEngine/Texture_BindLua.cpp deleted file mode 100644 index 4444f3e1f..000000000 --- a/WickedEngine/Texture_BindLua.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "Texture_BindLua.h" - -using namespace wiGraphics; - -const char Texture_BindLua::className[] = "Texture"; - -Luna::FunctionType Texture_BindLua::methods[] = { - { NULL, NULL } -}; -Luna::PropertyType Texture_BindLua::properties[] = { - { NULL, NULL } -}; - -Texture_BindLua::Texture_BindLua(Texture texture) :texture(texture) -{ -} -Texture_BindLua::Texture_BindLua(lua_State *L) -{ -} - -void Texture_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - Luna::Register(wiLua::GetLuaState()); - initialized = true; - } -} \ No newline at end of file diff --git a/WickedEngine/Texture_BindLua.h b/WickedEngine/Texture_BindLua.h deleted file mode 100644 index e5060a6ac..000000000 --- a/WickedEngine/Texture_BindLua.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include "wiLua.h" -#include "wiLuna.h" -#include "wiGraphics.h" - -class Texture_BindLua -{ -public: - wiGraphics::Texture texture; - - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - Texture_BindLua() = default; - Texture_BindLua(wiGraphics::Texture texture); - Texture_BindLua(lua_State *L); - - static void Bind(); -}; - diff --git a/WickedEngine/Vector_BindLua.cpp b/WickedEngine/Vector_BindLua.cpp deleted file mode 100644 index 9b78b1a42..000000000 --- a/WickedEngine/Vector_BindLua.cpp +++ /dev/null @@ -1,417 +0,0 @@ -#include "Vector_BindLua.h" -#include "Matrix_BindLua.h" - -using namespace DirectX; - - -const char Vector_BindLua::className[] = "Vector"; - -Luna::FunctionType Vector_BindLua::methods[] = { - lunamethod(Vector_BindLua, GetX), - lunamethod(Vector_BindLua, GetY), - lunamethod(Vector_BindLua, GetZ), - lunamethod(Vector_BindLua, GetW), - lunamethod(Vector_BindLua, SetX), - lunamethod(Vector_BindLua, SetY), - lunamethod(Vector_BindLua, SetZ), - lunamethod(Vector_BindLua, SetW), - lunamethod(Vector_BindLua, Transform), - lunamethod(Vector_BindLua, TransformNormal), - lunamethod(Vector_BindLua, TransformCoord), - lunamethod(Vector_BindLua, Length), - lunamethod(Vector_BindLua, Normalize), - lunamethod(Vector_BindLua, QuaternionNormalize), - lunamethod(Vector_BindLua, Add), - lunamethod(Vector_BindLua, Subtract), - lunamethod(Vector_BindLua, Multiply), - lunamethod(Vector_BindLua, Dot), - lunamethod(Vector_BindLua, Cross), - lunamethod(Vector_BindLua, Lerp), - lunamethod(Vector_BindLua, Slerp), - lunamethod(Vector_BindLua, Clamp), - lunamethod(Vector_BindLua, Normalize), - lunamethod(Vector_BindLua, QuaternionMultiply), - lunamethod(Vector_BindLua, QuaternionFromRollPitchYaw), - { NULL, NULL } -}; -Luna::PropertyType Vector_BindLua::properties[] = { - { NULL, NULL } -}; - -Vector_BindLua::Vector_BindLua() -{ - x = 0; - y = 0; - z = 0; - w = 0; -} -Vector_BindLua::Vector_BindLua(const XMFLOAT4& vector) -{ - x = vector.x; - y = vector.y; - z = vector.z; - w = vector.w; -} -Vector_BindLua::Vector_BindLua(const XMVECTOR& vector) -{ - XMStoreFloat4(this, vector); -} -Vector_BindLua::Vector_BindLua(lua_State* L) -{ - x = 0; - y = 0; - z = 0; - w = 0; - - int argc = wiLua::SGetArgCount(L); - - if (argc > 0) - { - x = wiLua::SGetFloat(L, 1); - if (argc > 1) - { - y = wiLua::SGetFloat(L, 2); - if (argc > 2) - { - z = wiLua::SGetFloat(L, 3); - if (argc > 3) - { - w = wiLua::SGetFloat(L, 4); - } - } - } - } -} - - - -int Vector_BindLua::GetX(lua_State* L) -{ - wiLua::SSetFloat(L, x); - return 1; -} -int Vector_BindLua::GetY(lua_State* L) -{ - wiLua::SSetFloat(L, y); - return 1; -} -int Vector_BindLua::GetZ(lua_State* L) -{ - wiLua::SSetFloat(L, z); - return 1; -} -int Vector_BindLua::GetW(lua_State* L) -{ - wiLua::SSetFloat(L, w); - return 1; -} - -int Vector_BindLua::SetX(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - x = wiLua::SGetFloat(L, 1); - } - else - wiLua::SError(L, "SetX(float value) not enough arguments!"); - return 0; -} -int Vector_BindLua::SetY(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - y = wiLua::SGetFloat(L, 1); - } - else - wiLua::SError(L, "SetY(float value) not enough arguments!"); - return 0; -} -int Vector_BindLua::SetZ(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - z = wiLua::SGetFloat(L, 1); - } - else - wiLua::SError(L, "SetZ(float value) not enough arguments!"); - return 0; -} -int Vector_BindLua::SetW(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - w = wiLua::SGetFloat(L, 1); - } - else - wiLua::SError(L, "SetW(float value) not enough arguments!"); - return 0; -} - -int Vector_BindLua::Transform(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - Matrix_BindLua* mat = Luna::lightcheck(L, 2); - if (vec && mat) - { - Luna::push(L, new Vector_BindLua(XMVector4Transform(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); - return 1; - } - else - wiLua::SError(L, "Transform(Vector vec, Matrix matrix) argument types mismatch!"); - } - else - wiLua::SError(L, "Transform(Vector vec, Matrix matrix) not enough arguments!"); - return 0; -} -int Vector_BindLua::TransformNormal(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - Matrix_BindLua* mat = Luna::lightcheck(L, 2); - if (vec && mat) - { - Luna::push(L, new Vector_BindLua(XMVector3TransformNormal(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); - return 1; - } - else - wiLua::SError(L, "TransformNormal(Vector vec, Matrix matrix) argument types mismatch!"); - } - else - wiLua::SError(L, "TransformNormal(Vector vec, Matrix matrix) not enough arguments!"); - return 0; -} -int Vector_BindLua::TransformCoord(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - Matrix_BindLua* mat = Luna::lightcheck(L, 2); - if (vec && mat) - { - Luna::push(L, new Vector_BindLua(XMVector3TransformCoord(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); - return 1; - } - else - wiLua::SError(L, "TransformCoord(Vector vec, Matrix matrix) argument types mismatch!"); - } - else - wiLua::SError(L, "TransformCoord(Vector vec, Matrix matrix) not enough arguments!"); - return 0; -} -int Vector_BindLua::Length(lua_State* L) -{ - wiLua::SSetFloat(L, XMVectorGetX(XMVector3Length(XMLoadFloat4(this)))); - return 1; -} -int Vector_BindLua::Normalize(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMVector3Normalize(XMLoadFloat4(this)))); - return 1; -} -int Vector_BindLua::QuaternionNormalize(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMQuaternionNormalize(XMLoadFloat4(this)))); - return 1; -} -int Vector_BindLua::Clamp(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - float a = wiLua::SGetFloat(L, 1); - float b = wiLua::SGetFloat(L, 2); - Luna::push(L, new Vector_BindLua(XMVectorClamp(XMLoadFloat4(this), XMVectorSet(a, a, a, a), XMVectorSet(b, b, b, b)))); - return 1; - } - else - wiLua::SError(L, "Clamp(float min,max) not enough arguments!"); - return 0; -} -int Vector_BindLua::Saturate(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMVectorSaturate(XMLoadFloat4(this)))); - return 1; -} - - - -int Vector_BindLua::Dot(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - wiLua::SSetFloat(L, XMVectorGetX(XMVector3Dot(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - } - wiLua::SError(L, "Dot(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::Cross(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMVector3Cross(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - } - wiLua::SError(L, "Cross(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::Multiply(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMVectorMultiply(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - else if (v1) - { - Luna::push(L, new Vector_BindLua(XMLoadFloat4(v1) * wiLua::SGetFloat(L, 2))); - return 1; - } - else if (v2) - { - Luna::push(L, new Vector_BindLua(wiLua::SGetFloat(L, 1) * XMLoadFloat4(v2))); - return 1; - } - } - wiLua::SError(L, "Multiply(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::Add(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMVectorAdd(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - } - wiLua::SError(L, "Add(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::Subtract(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMVectorSubtract(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - } - wiLua::SError(L, "Subtract(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::Lerp(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 2) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - float t = wiLua::SGetFloat(L, 3); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMVectorLerp(XMLoadFloat4(v1), XMLoadFloat4(v2), t))); - return 1; - } - } - wiLua::SError(L, "Lerp(Vector v1,v2, float t) not enough arguments!"); - return 0; -} - - -int Vector_BindLua::QuaternionMultiply(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMQuaternionMultiply(XMLoadFloat4(v1), XMLoadFloat4(v2)))); - return 1; - } - } - wiLua::SError(L, "QuaternionMultiply(Vector v1,v2) not enough arguments!"); - return 0; -} -int Vector_BindLua::QuaternionFromRollPitchYaw(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - if (v1) - { - Luna::push(L, new Vector_BindLua(XMQuaternionRotationRollPitchYawFromVector(XMLoadFloat4(v1)))); - return 1; - } - } - wiLua::SError(L, "QuaternionFromRollPitchYaw(Vector rotXYZ) not enough arguments!"); - return 0; -} -int Vector_BindLua::Slerp(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 2) - { - Vector_BindLua* v1 = Luna::lightcheck(L, 1); - Vector_BindLua* v2 = Luna::lightcheck(L, 2); - float t = wiLua::SGetFloat(L, 3); - if (v1 && v2) - { - Luna::push(L, new Vector_BindLua(XMQuaternionSlerp(XMLoadFloat4(v1), XMLoadFloat4(v2), t))); - return 1; - } - } - wiLua::SError(L, "QuaternionSlerp(Vector v1,v2, float t) not enough arguments!"); - return 0; -} - - -void Vector_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - wiLua::RunText("vector = Vector()"); - } -} - diff --git a/WickedEngine/Vector_BindLua.h b/WickedEngine/Vector_BindLua.h deleted file mode 100644 index 258b57830..000000000 --- a/WickedEngine/Vector_BindLua.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiLua.h" -#include "wiLuna.h" -#include "wiMath.h" - -class Vector_BindLua : public XMFLOAT4 -{ -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - - Vector_BindLua(); - Vector_BindLua(const XMFLOAT4& vector); - Vector_BindLua(const XMVECTOR& vector); - Vector_BindLua(lua_State* L); - - int GetX(lua_State* L); - int GetY(lua_State* L); - int GetZ(lua_State* L); - int GetW(lua_State* L); - - int SetX(lua_State* L); - int SetY(lua_State* L); - int SetZ(lua_State* L); - int SetW(lua_State* L); - - int Transform(lua_State* L); - int TransformNormal(lua_State* L); - int TransformCoord(lua_State* L); - int Length(lua_State* L); - int Normalize(lua_State* L); - int QuaternionNormalize(lua_State* L); - int Clamp(lua_State* L); - int Saturate(lua_State* L); - - int Dot(lua_State* L); - int Cross(lua_State* L); - int Multiply(lua_State* L); - int Add(lua_State* L); - int Subtract(lua_State* L); - int Lerp(lua_State* L); - - - int QuaternionMultiply(lua_State* L); - int QuaternionFromRollPitchYaw(lua_State* L); - int Slerp(lua_State* L); - - static void Bind(); -}; - diff --git a/WickedEngine/WickedEngine.h b/WickedEngine/WickedEngine.h index d807ce361..8224dca8e 100644 --- a/WickedEngine/WickedEngine.h +++ b/WickedEngine/WickedEngine.h @@ -1,31 +1,33 @@ -#ifndef WICKED_ENGINE +#ifndef WICKEDENGINE +#define WICKEDENGINE #define WICKED_ENGINE // NOTE: // The purpose of this file is to expose all engine features. -// It should be included in the engine's implementing project not the engine itself! +// It should be included in the engine's implementing application not the engine itself! // It should be included in the precompiled header if available. #include "CommonInclude.h" // High-level interface: -#include "RenderPath.h" -#include "RenderPath2D.h" -#include "RenderPath3D.h" -#include "RenderPath3D_PathTracing.h" -#include "LoadingScreen.h" -#include "MainComponent.h" +#include "wiApplication.h" +#include "wiRenderPath.h" +#include "wiRenderPath2D.h" +#include "wiRenderPath3D.h" +#include "wiRenderPath3D_PathTracing.h" +#include "wiLoadingScreen.h" // Engine-level systems #include "wiVersion.h" #include "wiPlatform.h" -#include "wiBackLog.h" -#include "wiIntersect.h" +#include "wiBacklog.h" +#include "wiPrimitive.h" #include "wiImage.h" #include "wiFont.h" #include "wiSprite.h" #include "wiSpriteFont.h" #include "wiScene.h" +#include "wiECS.h" #include "wiEmittedParticle.h" #include "wiHairParticle.h" #include "wiRenderer.h" @@ -37,31 +39,32 @@ #include "wiInput.h" #include "wiRawInput.h" #include "wiXInput.h" +#include "wiSDLInput.h" #include "wiTextureHelper.h" #include "wiRandom.h" #include "wiColor.h" -#include "wiPhysicsEngine.h" +#include "wiPhysics.h" #include "wiEnums.h" #include "wiInitializer.h" #include "wiLua.h" #include "wiLuna.h" +#include "wiGraphics.h" #include "wiGraphicsDevice.h" #include "wiGUI.h" -#include "wiWidget.h" #include "wiArchive.h" #include "wiSpinLock.h" #include "wiRectPacker.h" #include "wiProfiler.h" #include "wiOcean.h" -#include "wiStartupArguments.h" +#include "wiFFTGenerator.h" +#include "wiArguments.h" #include "wiGPUBVH.h" #include "wiGPUSortLib.h" #include "wiJobSystem.h" #include "wiNetwork.h" -#include "wiEvent.h" +#include "wiEventHandler.h" #include "wiShaderCompiler.h" #include "wiCanvas.h" -#include "wiAllocator.h" #include "wiUnorderedMap.h" #include "wiUnorderedSet.h" #include "wiVector.h" @@ -75,5 +78,95 @@ #endif // _WIN32 +// After version 0.59.11, namespaces were refactored into nested namespaces under the wi:: root namespace. +// To allow compatibility with older user code, the backwards compatibility definitions are included below. +// If you need backwards compatibility features, define the following before including this file: +//#define WICKEDENGINE_BACKWARDS_COMPATIBILITY_0_59 +#ifdef WICKEDENGINE_BACKWARDS_COMPATIBILITY_0_59 -#endif // WICKED_ENGINE +using namespace wi; +using namespace wi::enums; + +namespace wiGraphics = wi::graphics; +namespace wiShaderCompiler = wi::shadercompiler; +namespace wiFFTGenerator = wi::fftgenerator; +namespace wiFont = wi::font; +namespace wiImage = wi::image; +namespace wiGPUSortLib = wi::gpusortlib; +namespace wiRenderer = wi::renderer; +namespace wiTextureHelper = wi::texturehelper; +namespace wiHelper = wi::helper; +namespace wiMath = wi::math; +namespace wiRandom = wi::random; +namespace wiRectPacker = wi::rectpacker; +namespace wiResourceManager = wi::resourcemanager; +namespace wiStartupArguments = wi::arguments; +namespace wiInput = wi::input; +namespace wiXInput = wi::input::xinput; +namespace wiRawInput = wi::input::rawinput; +namespace wiSDLInput = wi::input::sdlinput; +namespace wiAudio = wi::audio; +namespace wiNetwork = wi::network; +namespace wiPhysicsEngine = wi::physics; +namespace wiLua = wi::lua; +namespace wiECS = wi::ecs; +namespace wiEvent = wi::eventhandler; +namespace wiInitializer = wi::initializer; +namespace wiJobSystem = wi::jobsystem; +namespace wiPlatform = wi::platform; +namespace wiScene = wi::scene; +namespace wiBackLog = wi::backlog; +namespace wiProfiler = wi::profiler; +namespace wiVersion = wi::version; + +using MainComponent = wi::Application; +using wiFontParams = wi::font::Params; +using wiImageParams = wi::image::Params; +using wiGPUBVH = wi::GPUBVH; +using wiEmittedParticle = wi::EmittedParticleSystem; +using wiHairParticle = wi::HairParticleSystem; +using wiOcean = wi::Ocean; +using wiSprite = wi::Sprite; +using wiSpriteFont = wi::SpriteFont; +using wiGUI = wi::gui::GUI; +using wiEventArgs = wi::gui::EventArgs; +using wiWidget = wi::gui::Widget; +using wiButton = wi::gui::Button; +using wiLabel = wi::gui::Label; +using wiTextInputField = wi::gui::TextInputField; +using wiSlider = wi::gui::Slider; +using wiCheckBox = wi::gui::CheckBox; +using wiComboBox = wi::gui::ComboBox; +using wiWindow = wi::gui::Window; +using wiColorPicker = wi::gui::ColorPicker; +using wiTreeList = wi::gui::TreeList; +using wiArchive = wi::Archive; +using wiColor = wi::Color; +using wiFadeManager = wi::FadeManager; +using wiResource = wi::Resource; +using wiSpinLock = wi::SpinLock; +using wiTimer = wi::Timer; +using wiCanvas = wi::Canvas; +using AABB = wi::primitive::AABB; +using SPHERE = wi::primitive::Sphere; +using CAPSULE = wi::primitive::Capsule; +using RAY = wi::primitive::Ray; +using Frustum = wi::primitive::Frustum; +using Hitbox2D = wi::primitive::Hitbox2D; + +using wi::image::STENCILMODE; +using wi::image::STENCILREFMODE; +using wi::image::SAMPLEMODE; +using wi::image::QUALITY; +using wi::font::Alignment; + +static constexpr int SYSTEM_EVENT_THREAD_SAFE_POINT = wi::eventhandler::EVENT_THREAD_SAFE_POINT; +static constexpr int SYSTEM_EVENT_RELOAD_SHADERS = wi::eventhandler::EVENT_RELOAD_SHADERS; +static constexpr int SYSTEM_EVENT_SET_VSYNC = wi::eventhandler::EVENT_SET_VSYNC; +static constexpr XMFLOAT4X4 IDENTITYMATRIX = wi::math::IDENTITY_MATRIX; + +#endif // WICKEDENGINE_BACKWARDS_COMPATIBILITY_0_59 + + + +#endif // WICKEDENGINE diff --git a/WickedEngine/WickedEngine_SOURCE.vcxitems b/WickedEngine/WickedEngine_SOURCE.vcxitems index e85487550..98859c0b9 100644 --- a/WickedEngine/WickedEngine_SOURCE.vcxitems +++ b/WickedEngine/WickedEngine_SOURCE.vcxitems @@ -229,7 +229,7 @@ - + @@ -250,13 +250,12 @@ - - + @@ -265,9 +264,9 @@ - - - + + + @@ -294,20 +293,19 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + @@ -325,10 +323,10 @@ - + - + @@ -350,13 +348,12 @@ - + - @@ -500,7 +497,7 @@ - + @@ -527,14 +524,14 @@ - + - - + + false @@ -637,19 +634,18 @@ false - - - - - - - - - - - - - + + + + + + + + + + + + @@ -665,12 +661,12 @@ - - + + - + @@ -688,10 +684,9 @@ - + - diff --git a/WickedEngine/WickedEngine_SOURCE.vcxitems.filters b/WickedEngine/WickedEngine_SOURCE.vcxitems.filters index 447e2a4cf..e9b23577c 100644 --- a/WickedEngine/WickedEngine_SOURCE.vcxitems.filters +++ b/WickedEngine/WickedEngine_SOURCE.vcxitems.filters @@ -13,9 +13,6 @@ {3c39405f-ec30-4b72-9c32-68aefb4fb7a5} - - {a637b1af-3cc6-48c3-89b4-8b931a1eb23e} - {d6f94528-ce59-4fa3-a0b9-d5c04994ac71} @@ -144,25 +141,22 @@ ENGINE\Common - + ENGINE\High level interface - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - - ENGINE\Scripting\LuaBindings - - + ENGINE\Scripting\LuaBindings @@ -174,12 +168,6 @@ ENGINE\Scripting\LuaBindings - - ENGINE\GUI - - - ENGINE\GUI - BULLET @@ -879,7 +867,7 @@ ENGINE\Input - + ENGINE\Tools @@ -912,7 +900,7 @@ UTILITY - + ENGINE\Helpers @@ -924,7 +912,7 @@ ENGINE\System - + ENGINE\Physics @@ -933,28 +921,28 @@ UTILITY - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\High level interface - + ENGINE\High level interface - + ENGINE\High level interface - + ENGINE\High level interface @@ -963,16 +951,13 @@ ENGINE\System - - ENGINE\Helpers - ENGINE\Scripting\LuaBindings - + ENGINE\Helpers - + ENGINE\Scripting\LuaBindings @@ -1044,7 +1029,7 @@ UTILITY - + ENGINE\System @@ -1071,7 +1056,7 @@ ENGINE\System - + ENGINE\High level interface @@ -1086,6 +1071,9 @@ ENGINE\Helpers + + ENGINE\System + @@ -1193,25 +1181,22 @@ ENGINE - + ENGINE\High level interface - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - - ENGINE\Scripting\LuaBindings - - + ENGINE\Scripting\LuaBindings @@ -1223,12 +1208,6 @@ ENGINE\Scripting\LuaBindings - - ENGINE\GUI - - - ENGINE\GUI - BULLET @@ -1694,7 +1673,7 @@ ENGINE\Input - + ENGINE\Tools @@ -1715,7 +1694,7 @@ ENGINE\Graphics\API - + ENGINE\Helpers @@ -1724,34 +1703,34 @@ UTILITY - + ENGINE\Physics ENGINE\Graphics - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\Scripting\LuaBindings - + ENGINE\High level interface - + ENGINE\High level interface - + ENGINE\High level interface - + ENGINE\High level interface @@ -1763,10 +1742,10 @@ ENGINE\Scripting\LuaBindings - + ENGINE\Helpers - + ENGINE\Scripting\LuaBindings @@ -1811,7 +1790,7 @@ ENGINE\Network - + ENGINE\System @@ -1829,6 +1808,9 @@ UTILITY + + ENGINE\System + diff --git a/WickedEngine/offlineshadercompiler.cpp b/WickedEngine/offlineshadercompiler.cpp index 0a6cf61b8..5f0485fe9 100644 --- a/WickedEngine/offlineshadercompiler.cpp +++ b/WickedEngine/offlineshadercompiler.cpp @@ -6,19 +6,19 @@ #include std::mutex locker; -wi::vector shaders[static_cast(wiGraphics::ShaderStage::Count)]; -wi::unordered_map minshadermodels; +wi::vector shaders[static_cast(wi::graphics::ShaderStage::Count)]; +wi::unordered_map minshadermodels; struct Target { - wiGraphics::ShaderFormat format; + wi::graphics::ShaderFormat format; std::string dir; }; wi::vector targets; -wi::unordered_map results; +wi::unordered_map results; bool rebuild = false; bool shaderdump_enabled = false; -using namespace wiGraphics; +using namespace wi::graphics; int main(int argc, char* argv[]) { @@ -31,32 +31,32 @@ int main(int argc, char* argv[]) std::cout << "\tshaderdump : \tShaders will be saved to wiShaderDump.h C++ header file (rebuild is assumed)" << std::endl; std::cout << "Command arguments used: "; - wiStartupArguments::Parse(argc, argv); + wi::arguments::Parse(argc, argv); - if (wiStartupArguments::HasArgument("hlsl5")) + if (wi::arguments::HasArgument("hlsl5")) { targets.push_back({ ShaderFormat::HLSL5, "shaders/hlsl5/" }); std::cout << "hlsl5 "; } - if (wiStartupArguments::HasArgument("hlsl6")) + if (wi::arguments::HasArgument("hlsl6")) { targets.push_back({ ShaderFormat::HLSL6, "shaders/hlsl6/" }); std::cout << "hlsl6 "; } - if (wiStartupArguments::HasArgument("spirv")) + if (wi::arguments::HasArgument("spirv")) { targets.push_back({ ShaderFormat::SPIRV, "shaders/spirv/" }); std::cout << "spirv "; } - if (wiStartupArguments::HasArgument("shaderdump")) + if (wi::arguments::HasArgument("shaderdump")) { shaderdump_enabled = true; rebuild = true; std::cout << "shaderdump "; } - if (wiStartupArguments::HasArgument("rebuild")) + if (wi::arguments::HasArgument("rebuild")) { rebuild = true; std::cout << "rebuild "; @@ -399,20 +399,20 @@ int main(int argc, char* argv[]) minshadermodels["rtaoCS.hlsl"] = ShaderModel::SM_6_5; minshadermodels["surfel_raytraceCS_rtapi.hlsl"] = ShaderModel::SM_6_5; - wiShaderCompiler::Initialize(); - wiJobSystem::Initialize(); - wiJobSystem::context ctx; + wi::shadercompiler::Initialize(); + wi::jobsystem::Initialize(); + wi::jobsystem::context ctx; - std::string SHADERSOURCEPATH = wiRenderer::GetShaderSourcePath(); - wiHelper::MakePathAbsolute(SHADERSOURCEPATH); + std::string SHADERSOURCEPATH = wi::renderer::GetShaderSourcePath(); + wi::helper::MakePathAbsolute(SHADERSOURCEPATH); std::cout << "[Wicked Engine Offline Shader Compiler] Searching for outdated shaders..." << std::endl; - wiTimer timer; + wi::Timer timer; for (auto& target : targets) { std::string SHADERPATH = target.dir; - wiHelper::DirectoryCreate(SHADERPATH); + wi::helper::DirectoryCreate(SHADERPATH); for (int i = 0; i < static_cast(ShaderStage::Count); ++i) { @@ -431,16 +431,16 @@ int main(int argc, char* argv[]) for (auto& shader : shaders[i]) { - wiJobSystem::Execute(ctx, [=](wiJobArgs args) { - std::string shaderbinaryfilename = wiHelper::ReplaceExtension(SHADERPATH + shader, "cso"); - if (!rebuild && !wiShaderCompiler::IsShaderOutdated(shaderbinaryfilename)) + wi::jobsystem::Execute(ctx, [=](wi::jobsystem::JobArgs args) { + std::string shaderbinaryfilename = wi::helper::ReplaceExtension(SHADERPATH + shader, "cso"); + if (!rebuild && !wi::shadercompiler::IsShaderOutdated(shaderbinaryfilename)) { return; } - wiShaderCompiler::CompilerInput input; + wi::shadercompiler::CompilerInput input; input.format = target.format; - input.stage = (wiGraphics::ShaderStage)i; + input.stage = (wi::graphics::ShaderStage)i; input.shadersourcefilename = SHADERSOURCEPATH + shader; input.include_directories.push_back(SHADERSOURCEPATH); @@ -456,12 +456,12 @@ int main(int argc, char* argv[]) return; } - wiShaderCompiler::CompilerOutput output; - wiShaderCompiler::Compile(input, output); + wi::shadercompiler::CompilerOutput output; + wi::shadercompiler::Compile(input, output); if (output.IsValid()) { - wiShaderCompiler::SaveShaderAndMetadata(shaderbinaryfilename, output); + wi::shadercompiler::SaveShaderAndMetadata(shaderbinaryfilename, output); locker.lock(); if (!output.error_message.empty()) @@ -487,7 +487,7 @@ int main(int argc, char* argv[]) } } } - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); std::cout << "[Wicked Engine Offline Shader Compiler] Finished in " << std::setprecision(4) << timer.elapsed_seconds() << " seconds" << std::endl; @@ -526,7 +526,7 @@ int main(int argc, char* argv[]) } ss += "};\n"; // map end ss += "}\n"; // namespace end - wiHelper::FileWrite("wiShaderDump.h", (uint8_t*)ss.c_str(), ss.length()); + wi::helper::FileWrite("wiShaderDump.h", (uint8_t*)ss.c_str(), ss.length()); std::cout << "[Wicked Engine Offline Shader Compiler] ShaderDump written to wiShaderDump.h in " << std::setprecision(4) << timer.elapsed_seconds() << " seconds" << std::endl; } diff --git a/WickedEngine/shaders/ShaderInterop.h b/WickedEngine/shaders/ShaderInterop.h index b77fc896f..61188a0a3 100644 --- a/WickedEngine/shaders/ShaderInterop.h +++ b/WickedEngine/shaders/ShaderInterop.h @@ -6,8 +6,6 @@ // Application-side types: #include "../wiMath.h" -using matrix = XMMATRIX; -using float3x4 = XMFLOAT3X4; using float4x4 = XMFLOAT4X4; using float2 = XMFLOAT2; using float3 = XMFLOAT3; diff --git a/WickedEngine/shaders/ShaderInterop_Renderer.h b/WickedEngine/shaders/ShaderInterop_Renderer.h index 0155cfc7b..4ab3ac4f7 100644 --- a/WickedEngine/shaders/ShaderInterop_Renderer.h +++ b/WickedEngine/shaders/ShaderInterop_Renderer.h @@ -533,7 +533,7 @@ static const uint OPTION_BIT_STATIC_SKY_HDR = 1 << 13; struct FrameCB { - uint options; // wiRenderer bool options packed into bitmask + uint options; // wi::renderer bool options packed into bitmask uint shadow_cascade_count; float shadow_kernel_2D; float shadow_kernel_cube; @@ -643,7 +643,7 @@ struct CameraCB float2 internal_resolution_rcp; uint3 entity_culling_tilecount; - int padding0; + uint sample_count; int texture_depth_index; int texture_lineardepth_index; diff --git a/WickedEngine/shaders/brdf.hlsli b/WickedEngine/shaders/brdf.hlsli index 852b80f17..49aaac59a 100644 --- a/WickedEngine/shaders/brdf.hlsli +++ b/WickedEngine/shaders/brdf.hlsli @@ -326,7 +326,7 @@ struct Surface float v = barycentrics.y; float w = 1 - u - v; - P = p0 * w + p1 * u + p2 * v; + P = mad(p0, w, mad(p1, u, p2 * v)); // p0 * w + p1 * u + p2 * v P = mul(inst.transform.GetMatrix(), float4(P, 1)).xyz; V = normalize(GetCamera().position - P); @@ -345,8 +345,8 @@ struct Surface uv1.zw = unpack_half2(bindless_buffers[NonUniformResourceIndex(mesh.vb_uv1)].Load(i1 * 4)); uv2.zw = unpack_half2(bindless_buffers[NonUniformResourceIndex(mesh.vb_uv1)].Load(i2 * 4)); } - float4 uvsets = uv0 * w + uv1 * u + uv2 * v; - uvsets.xy = uvsets.xy * material.texMulAdd.xy + material.texMulAdd.zw; + float4 uvsets = mad(uv0, w, mad(uv1, u, uv2 * v)); // uv0 * w + uv1 * u + uv2 * v + uvsets.xy = mad(uvsets.xy, material.texMulAdd.xy, material.texMulAdd.zw); float4 baseColor = is_emittedparticle ? 1 : material.baseColor; [branch] @@ -373,7 +373,7 @@ struct Surface c0 = unpack_rgba(bindless_buffers[NonUniformResourceIndex(mesh.vb_col)].Load(i0 * stride_COL)); c1 = unpack_rgba(bindless_buffers[NonUniformResourceIndex(mesh.vb_col)].Load(i1 * stride_COL)); c2 = unpack_rgba(bindless_buffers[NonUniformResourceIndex(mesh.vb_col)].Load(i2 * stride_COL)); - float4 vertexColor = c0 * w + c1 * u + c2 * v; + float4 vertexColor = mad(c0, w, mad(c1, u, c2 * v)); // c0 * w + c1 * u + c2 * v baseColor *= vertexColor; } @@ -437,7 +437,7 @@ struct Surface occlusion *= bindless_textures[NonUniformResourceIndex(material.texture_occlusionmap_index)].SampleLevel(sampler_linear_wrap, UV_occlusionMap, 0).r; } - N = n0 * w + n1 * u + n2 * v; + N = mad(n0, w, mad(n1, u, n2 * v)); // n0 * w + n1 * u + n2 * v N = mul((float3x3)inst.transformInverseTranspose.GetMatrix(), N); N = normalize(N); if (is_frontface == false && !is_hairparticle && !is_emittedparticle) @@ -454,7 +454,7 @@ struct Surface t0 = unpack_utangent(bindless_buffers[NonUniformResourceIndex(mesh.vb_tan)].Load(i0 * stride_TAN)); t1 = unpack_utangent(bindless_buffers[NonUniformResourceIndex(mesh.vb_tan)].Load(i1 * stride_TAN)); t2 = unpack_utangent(bindless_buffers[NonUniformResourceIndex(mesh.vb_tan)].Load(i2 * stride_TAN)); - float4 T = t0 * w + t1 * u + t2 * v; + float4 T = mad(t0, w, mad(t1, u, t2 * v)); // t0 * w + t1 * u + t2 * v T = T * 2 - 1; T.xyz = mul((float3x3)inst.transformInverseTranspose.GetMatrix(), T.xyz); T.xyz = normalize(T.xyz); @@ -474,9 +474,12 @@ struct Surface p1 = asfloat(bindless_buffers[mesh.vb_pre].Load3(i1 * 16)); p2 = asfloat(bindless_buffers[mesh.vb_pre].Load3(i2 * 16)); } - pre = p0 * w + p1 * u + p2 * v; + pre = mad(p0, w, mad(p1, u, p2 * v)); // p0 * w + p1 * u + p2 * v pre = mul(inst.transformPrev.GetMatrix(), float4(pre, 1)).xyz; + sss = material.subsurfaceScattering; + sss_inv = material.subsurfaceScattering_inv; + update(); return true; @@ -607,7 +610,7 @@ float3 BRDF_GetSpecular(in Surface surface, in SurfaceToLight surfaceToLight) specular += D * Vis * surface.clearcoat.F; #endif // BRDF_CLEARCOAT - return specular; + return specular * surfaceToLight.NdotL; } float3 BRDF_GetDiffuse(in Surface surface, in SurfaceToLight surfaceToLight) { @@ -623,7 +626,7 @@ float3 BRDF_GetDiffuse(in Surface surface, in SurfaceToLight surfaceToLight) diffuse *= 1 - surface.clearcoat.F; #endif // BRDF_CLEARCOAT - return diffuse; + return diffuse * surfaceToLight.NdotL_sss; } #endif // WI_BRDF_HF diff --git a/WickedEngine/shaders/generateMIPChain2DCS_float4.hlsl b/WickedEngine/shaders/generateMIPChain2DCS_float4.hlsl index fc784e4c1..c4907eace 100644 --- a/WickedEngine/shaders/generateMIPChain2DCS_float4.hlsl +++ b/WickedEngine/shaders/generateMIPChain2DCS_float4.hlsl @@ -23,11 +23,14 @@ void main(uint3 DTid : SV_DispatchThreadID) if (mipgen.mipgen_options & MIPGEN_OPTION_BIT_PRESERVE_COVERAGE) { float4 alphas = input.GatherAlpha(customsampler, uv, 0); +#if 0 alphas = pow(saturate(alphas), 2.2f); float alpha = (alphas.x + alphas.y + alphas.z + alphas.w) / 4.0f; alpha = pow(saturate(alpha), 1.0f / 2.2f); color.a = alpha; - //color.a = max(alphas.x, max(alphas.y, max(alphas.z, alphas.w))); +#else + color.a = max(alphas.x, max(alphas.y, max(alphas.z, alphas.w))); +#endif } output[DTid.xy] = color; diff --git a/WickedEngine/shaders/globals.hlsli b/WickedEngine/shaders/globals.hlsli index cbe8b830f..24f11278e 100644 --- a/WickedEngine/shaders/globals.hlsli +++ b/WickedEngine/shaders/globals.hlsli @@ -154,7 +154,7 @@ inline float GetFogAmount(float distance, float3 O, float3 V) float Z = -V.y; float effectiveZ = max(abs(Z), 0.001); - float endLineHeight = originHeight + distance * Z; // Isolated vector equation for y + float endLineHeight = mad(distance, Z, originHeight); // Isolated vector equation for y float minLineHeight = min(originHeight, endLineHeight); float heightLineFalloff = max(minLineHeight - fog.height_start, 0); @@ -871,7 +871,7 @@ static const float4 halton64[] = { float4(0.5078125000f, 0.7283950617f, 0.1360000000f, 0.3294460641f), }; -// This the same as wiGraphics::ColorSpace +// This the same as wi::graphics::ColorSpace enum class ColorSpace { SRGB, // SDR color space (8 or 10 bits per channel) diff --git a/WickedEngine/shaders/hairparticlePS.hlsl b/WickedEngine/shaders/hairparticlePS.hlsl index 0f7695735..26b64aebb 100644 --- a/WickedEngine/shaders/hairparticlePS.hlsl +++ b/WickedEngine/shaders/hairparticlePS.hlsl @@ -20,7 +20,6 @@ float4 main(VertexToPixel input) : SV_Target } color *= material.baseColor; - float opacity = 1; float3 V = GetCamera().position - input.pos3D; float dist = length(V); V /= dist; diff --git a/WickedEngine/shaders/hairparticlePS_prepass.hlsl b/WickedEngine/shaders/hairparticlePS_prepass.hlsl index c0a1c79c1..71a6368df 100644 --- a/WickedEngine/shaders/hairparticlePS_prepass.hlsl +++ b/WickedEngine/shaders/hairparticlePS_prepass.hlsl @@ -3,28 +3,25 @@ #include "hairparticleHF.hlsli" #include "ShaderInterop_HairParticle.h" -uint2 main(VertexToPixel input) : SV_TARGET +uint2 main(VertexToPixel input, out uint coverage : SV_Coverage) : SV_Target { ShaderMaterial material = HairGetMaterial(); - const float lineardepth = input.pos.w; - - clip(dither(input.pos.xy + GetTemporalAASampleRotation()) - input.fade); - - float4 color = 1; + float alpha = 1; [branch] if (material.texture_basecolormap_index >= 0) { - color = bindless_textures[material.texture_basecolormap_index].Sample(sampler_linear_clamp, input.tex); + alpha = bindless_textures[material.texture_basecolormap_index].Sample(sampler_linear_clamp, input.tex).a; } - float alphatest = material.alphaTest; - if (GetFrame().options & OPTION_BIT_TEMPORALAA_ENABLED) + // Distance dithered fade: + if (dither(input.pos.xy + GetTemporalAASampleRotation()) - input.fade < 0) { - alphatest = clamp(blue_noise(input.pos.xy, lineardepth).r, 0, 0.99); + alpha = 0; } - clip(color.a - alphatest); + + coverage = AlphaToCoverage(alpha, material.alphaTest, input.pos); PrimitiveID prim; prim.primitiveIndex = input.primitiveID; diff --git a/WickedEngine/shaders/hairparticle_simulateCS.hlsl b/WickedEngine/shaders/hairparticle_simulateCS.hlsl index 6b7e566d2..a4296d284 100644 --- a/WickedEngine/shaders/hairparticle_simulateCS.hlsl +++ b/WickedEngine/shaders/hairparticle_simulateCS.hlsl @@ -201,9 +201,9 @@ void main(uint3 DTid : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint groupIn patchPos = mul(patchPos, TBN); // simplistic wind effect only affects the top, but leaves the base as is: - const float waveoffset = dot(rootposition, GetWeather().wind.direction) * GetWeather().wind.wavesize + rand / 255.0f * GetWeather().wind.randomness; + const float waveoffset = mad(dot(rootposition, GetWeather().wind.direction), GetWeather().wind.wavesize, rand / 255.0f * GetWeather().wind.randomness); const float3 wavedir = GetWeather().wind.direction * (segmentID + patchPos.y); - const float3 wind = sin(GetFrame().time * GetWeather().wind.speed + waveoffset) * wavedir; + const float3 wind = sin(mad(GetFrame().time, GetWeather().wind.speed, waveoffset)) * wavedir; float3 position = rootposition + patchPos + wind; diff --git a/WickedEngine/shaders/imageHF.hlsli b/WickedEngine/shaders/imageHF.hlsli index fc732f7db..40f726a4b 100644 --- a/WickedEngine/shaders/imageHF.hlsli +++ b/WickedEngine/shaders/imageHF.hlsli @@ -50,8 +50,8 @@ struct VertextoPixel float4 texMulAdd = unpack_half4(push.texMulAdd); float4 texMulAdd2 = unpack_half4(push.texMulAdd2); - float2 uv0 = uv * texMulAdd.xy + texMulAdd.zw; - float2 uv1 = uv * texMulAdd2.xy + texMulAdd2.zw; + float2 uv0 = mad(uv, texMulAdd.xy, texMulAdd.zw); + float2 uv1 = mad(uv, texMulAdd2.xy, texMulAdd2.zw); return float4(uv0, uv1); } }; diff --git a/WickedEngine/shaders/lightingHF.hlsli b/WickedEngine/shaders/lightingHF.hlsli index 2bb2141bd..5b501ff52 100644 --- a/WickedEngine/shaders/lightingHF.hlsli +++ b/WickedEngine/shaders/lightingHF.hlsli @@ -50,15 +50,15 @@ inline float3 shadow_2D(in ShaderEntity light, in float3 shadow_pos, in float2 s float3 shadow = 0; #ifndef DISABLE_SOFT_SHADOWMAP // sample along a rectangle pattern around center: - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(-1, -1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(-1, 0) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(-1, 1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(0, -1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(-1, -1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(-1, 0), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(-1, 1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(0, -1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(0, 1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(1, -1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(1, 0) * GetFrame().shadow_kernel_2D, slice), realDistance).r; - shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv + float2(1, 1) * GetFrame().shadow_kernel_2D, slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(0, 1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(1, -1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(1, 0), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; + shadow.x += texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(mad(float2(1, 1), GetFrame().shadow_kernel_2D, shadow_uv), slice), realDistance).r; shadow = shadow.xxx / 9.0; #else shadow = texture_shadowarray_2d.SampleCmpLevelZero(sampler_cmp_depth, float3(shadow_uv, slice), realDistance).r; @@ -88,15 +88,15 @@ inline float3 shadow_cube(in ShaderEntity light, in float3 L, in float3 Lunnorma #ifndef DISABLE_SOFT_SHADOWMAP // sample along a cube pattern around center: L = -L; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(-1, -1, -1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(1, -1, -1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(-1, 1, -1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(1, 1, -1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(-1, -1, -1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(1, -1, -1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(-1, 1, -1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(1, 1, -1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(-1, -1, 1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(1, -1, 1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(-1, 1, 1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; - shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(L + float3(1, 1, 1) * GetFrame().shadow_kernel_cube, slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(-1, -1, 1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(1, -1, 1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(-1, 1, 1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; + shadow += texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(mad(float3(1, 1, 1), GetFrame().shadow_kernel_cube, L), slice), remapped_distance).r; shadow /= 9.0; #else shadow = texture_shadowarray_cube.SampleCmpLevelZero(sampler_cmp_depth, float4(-Lunnormalized, slice), remapped_distance).r; @@ -180,19 +180,16 @@ inline void light_directional(in ShaderEntity light, in Surface surface, inout L [branch] if (any(shadow)) { - float3 atmosphere_transmittance = 1; + float3 light_color = light.GetColor().rgb * light.GetEnergy() * shadow; + + [branch] if (GetFrame().options & OPTION_BIT_REALISTIC_SKY) { - atmosphere_transmittance = GetAtmosphericLightTransmittance(GetWeather().atmosphere, surface.P, L, texture_transmittancelut); + light_color *= GetAtmosphericLightTransmittance(GetWeather().atmosphere, surface.P, L, texture_transmittancelut); } - - float3 light_color = light.GetColor().rgb * light.GetEnergy() * shadow * atmosphere_transmittance; - lighting.direct.diffuse += - max(0, light_color * surface_to_light.NdotL_sss * BRDF_GetDiffuse(surface, surface_to_light)); - - lighting.direct.specular += - max(0, light_color * surface_to_light.NdotL * BRDF_GetSpecular(surface, surface_to_light)); + lighting.direct.diffuse = mad(light_color, BRDF_GetDiffuse(surface, surface_to_light), lighting.direct.diffuse); + lighting.direct.specular = mad(light_color, BRDF_GetSpecular(surface, surface_to_light), lighting.direct.specular); } } } @@ -238,11 +235,8 @@ inline void light_point(in ShaderEntity light, in Surface surface, inout Lightin const float attenuation = att * att; light_color *= attenuation; - lighting.direct.diffuse += - max(0, light_color * surface_to_light.NdotL_sss * BRDF_GetDiffuse(surface, surface_to_light)); - - lighting.direct.specular += - max(0, light_color * surface_to_light.NdotL * BRDF_GetSpecular(surface, surface_to_light)); + lighting.direct.diffuse = mad(light_color, BRDF_GetDiffuse(surface, surface_to_light), lighting.direct.diffuse); + lighting.direct.specular = mad(light_color, BRDF_GetSpecular(surface, surface_to_light), lighting.direct.specular); } } } @@ -302,11 +296,8 @@ inline void light_spot(in ShaderEntity light, in Surface surface, inout Lighting attenuation *= saturate((1 - (1 - spot_factor) * 1 / (1 - spot_cutoff))); light_color *= attenuation; - lighting.direct.diffuse += - max(0, light_color * surface_to_light.NdotL_sss * BRDF_GetDiffuse(surface, surface_to_light)); - - lighting.direct.specular += - max(0, light_color * surface_to_light.NdotL * BRDF_GetSpecular(surface, surface_to_light)); + lighting.direct.diffuse = mad(light_color, BRDF_GetDiffuse(surface, surface_to_light), lighting.direct.diffuse); + lighting.direct.specular = mad(light_color, BRDF_GetSpecular(surface, surface_to_light), lighting.direct.specular); } } } diff --git a/WickedEngine/shaders/objectHF.hlsli b/WickedEngine/shaders/objectHF.hlsli index e79809eb3..2af6c4c14 100644 --- a/WickedEngine/shaders/objectHF.hlsli +++ b/WickedEngine/shaders/objectHF.hlsli @@ -269,7 +269,7 @@ struct VertexSurface tangent = input.GetTangent(); tangent.xyz = normalize(mul((float3x3)input.GetInstance().transformInverseTranspose.GetMatrix(), tangent.xyz)); - uvsets = float4(input.GetUV0() * material.texMulAdd.xy + material.texMulAdd.zw, input.GetUV1()); + uvsets = float4(mad(input.GetUV0(), material.texMulAdd.xy, material.texMulAdd.zw), input.GetUV1()); atlas = input.GetAtlasUV(); @@ -280,9 +280,9 @@ struct VertexSurface if (material.IsUsingWind()) { const float windweight = input.GetWindWeight(); - const float waveoffset = dot(position.xyz, GetWeather().wind.direction) * GetWeather().wind.wavesize + (position.x + position.y + position.z) * GetWeather().wind.randomness; + const float waveoffset = mad(dot(position.xyz, GetWeather().wind.direction), GetWeather().wind.wavesize, (position.x + position.y + position.z) * GetWeather().wind.randomness); const float3 wavedir = GetWeather().wind.direction * windweight; - const float3 wind = sin(GetFrame().time * GetWeather().wind.speed + waveoffset) * wavedir; + const float3 wind = sin(mad(GetFrame().time, GetWeather().wind.speed, waveoffset)) * wavedir; position.xyz += wind; } #endif // OBJECTSHADER_USE_WIND @@ -423,7 +423,7 @@ inline void ParallaxOcclusionMapping(inout float4 uvsets, in float3 V, in float3 float nextH = heightFromTexture - curLayerHeight; float prevH = 1 - texture_displacementmap.SampleGrad(sampler_linear_wrap, prevTCoords, derivX, derivY).r - curLayerHeight + layerHeight; float weight = nextH / (nextH - prevH); - float2 finalTextureCoords = prevTCoords * weight + currentTextureCoords * (1.0 - weight); + float2 finalTextureCoords = mad(prevTCoords, weight, currentTextureCoords * (1.0 - weight)); float2 difference = finalTextureCoords - originalTextureCoords; uvsets += difference.xyxy; } @@ -483,8 +483,8 @@ inline void ForwardLighting(inout Surface surface, inout Lighting lighting) lighting.direct.specular += max(0, decalColor.rgb * decal.GetEmissive() * edgeBlend); // perform manual blending of decals: // NOTE: they are sorted top-to-bottom, but blending is performed bottom-to-top - decalAccumulation.rgb = (1 - decalAccumulation.a) * (decalColor.a*decalColor.rgb) + decalAccumulation.rgb; - decalAccumulation.a = decalColor.a + (1 - decalColor.a) * decalAccumulation.a; + decalAccumulation.rgb = mad(1 - decalAccumulation.a, decalColor.a * decalColor.rgb, decalAccumulation.rgb); + decalAccumulation.a = mad(1 - decalColor.a, decalAccumulation.a, decalColor.a); [branch] if (decalAccumulation.a >= 1.0) { @@ -541,8 +541,8 @@ inline void ForwardLighting(inout Surface surface, inout Lighting lighting) const float4 envmapColor = EnvironmentReflection_Local(surface, probe, probeProjection, clipSpacePos); // perform manual blending of probes: // NOTE: they are sorted top-to-bottom, but blending is performed bottom-to-top - envmapAccumulation.rgb = (1 - envmapAccumulation.a) * (envmapColor.a * envmapColor.rgb) + envmapAccumulation.rgb; - envmapAccumulation.a = envmapColor.a + (1 - envmapColor.a) * envmapAccumulation.a; + envmapAccumulation.rgb = mad(1 - envmapAccumulation.a, envmapColor.a * envmapColor.rgb, envmapAccumulation.rgb); + envmapAccumulation.a = mad(1 - envmapColor.a, envmapAccumulation.a, envmapColor.a); [branch] if (envmapAccumulation.a >= 1.0) { @@ -698,8 +698,8 @@ inline void TiledLighting(inout Surface surface, inout Lighting lighting) lighting.direct.specular += max(0, decalColor.rgb * decal.GetEmissive() * edgeBlend); // perform manual blending of decals: // NOTE: they are sorted top-to-bottom, but blending is performed bottom-to-top - decalAccumulation.rgb = (1 - decalAccumulation.a) * (decalColor.a*decalColor.rgb) + decalAccumulation.rgb; - decalAccumulation.a = decalColor.a + (1 - decalColor.a) * decalAccumulation.a; + decalAccumulation.rgb = mad(1 - decalAccumulation.a, decalColor.a*decalColor.rgb, decalAccumulation.rgb); + decalAccumulation.a = mad(1 - decalColor.a, decalAccumulation.a, decalColor.a); [branch] if (decalAccumulation.a >= 1.0) { @@ -769,8 +769,8 @@ inline void TiledLighting(inout Surface surface, inout Lighting lighting) const float4 envmapColor = EnvironmentReflection_Local(surface, probe, probeProjection, clipSpacePos); // perform manual blending of probes: // NOTE: they are sorted top-to-bottom, but blending is performed bottom-to-top - envmapAccumulation.rgb = (1 - envmapAccumulation.a) * (envmapColor.a * envmapColor.rgb) + envmapAccumulation.rgb; - envmapAccumulation.a = envmapColor.a + (1 - envmapColor.a) * envmapAccumulation.a; + envmapAccumulation.rgb = mad(1 - envmapAccumulation.a, envmapColor.a * envmapColor.rgb, envmapAccumulation.rgb); + envmapAccumulation.a = mad(1 - envmapColor.a, envmapAccumulation.a, envmapColor.a); [branch] if (envmapAccumulation.a >= 1.0) { @@ -934,6 +934,37 @@ inline void ApplyFog(in float distance, float3 P, float3 V, inout float4 color) } } +inline uint AlphaToCoverage(float alpha, float alphaTest, float4 svposition) +{ + if (alphaTest == 0) + { + // No alpha test, force full coverage: + return ~0u; + } + + if (GetFrame().options & OPTION_BIT_TEMPORALAA_ENABLED) + { + // When Temporal AA is enabled, dither the alpha mask with animated blue noise: + alpha -= blue_noise(svposition.xy, svposition.w).x / GetCamera().sample_count; + } + else if (GetCamera().sample_count > 1) + { + // Without Temporal AA, use static dithering: + alpha -= dither(svposition.xy) / GetCamera().sample_count; + } + else + { + // Without Temporal AA and MSAA, regular alpha test behaviour will be used: + alpha -= alphaTest; + } + + if (alpha > 0) + { + return ~0u >> (31u - uint(alpha * GetCamera().sample_count)); + } + return 0; +} + // OBJECT SHADER PROTOTYPE /////////////////////////// @@ -1021,17 +1052,15 @@ PixelInput main(VertexInput input) // WATER - include specialized water shader code // TERRAIN - include specialized terrain material blending code - #ifdef DISABLE_ALPHATEST [earlydepthstencil] #endif // DISABLE_ALPHATEST - // entry point: #ifdef PREPASS -uint2 main(PixelInput input, in uint primitiveID : SV_PrimitiveID) : SV_TARGET +uint2 main(PixelInput input, in uint primitiveID : SV_PrimitiveID, out uint coverage : SV_Coverage) : SV_Target #else -float4 main(PixelInput input, in bool is_frontface : SV_IsFrontFace) : SV_TARGET +float4 main(PixelInput input, in bool is_frontface : SV_IsFrontFace) : SV_Target #endif // PREPASS @@ -1115,19 +1144,14 @@ float4 main(PixelInput input, in bool is_frontface : SV_IsFrontFace) : SV_TARGET #endif // OBJECTSHADER_USE_COLOR - +#ifdef TRANSPARENT #ifndef DISABLE_ALPHATEST - float alphatest = GetMaterial().alphaTest; -#ifndef TRANSPARENT -#ifndef ENVMAPRENDERING - if (GetFrame().options & OPTION_BIT_TEMPORALAA_ENABLED) - { - alphatest = clamp(blue_noise(pixel, lineardepth).r, 0, 0.99); - } -#endif // ENVMAPRENDERING -#endif // TRANSPARENT - clip(color.a - alphatest); + // Alpha test is only done for transparents + // - Prepass will write alpha coverage mask + // - Opaque will + clip(color.a - GetMaterial().alphaTest); #endif // DISABLE_ALPHATEST +#endif // TRANSPARENT @@ -1711,6 +1735,8 @@ float4 main(PixelInput input, in bool is_frontface : SV_IsFrontFace) : SV_TARGET // end point: #ifdef PREPASS + coverage = AlphaToCoverage(color.a, GetMaterial().alphaTest, input.pos); + PrimitiveID prim; prim.primitiveIndex = primitiveID; prim.instanceIndex = input.instanceID; @@ -1719,7 +1745,6 @@ float4 main(PixelInput input, in bool is_frontface : SV_IsFrontFace) : SV_TARGET #else return color; #endif // PREPASS - } diff --git a/WickedEngine/shaders/raytraceCS.hlsl b/WickedEngine/shaders/raytraceCS.hlsl index 979f4a9aa..12d090a95 100644 --- a/WickedEngine/shaders/raytraceCS.hlsl +++ b/WickedEngine/shaders/raytraceCS.hlsl @@ -128,7 +128,6 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) surface.V = -ray.Direction; surface.update(); - result += max(0, energy * surface.emissiveColor); if (!surface.material.IsUnlit()) @@ -158,17 +157,15 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) surfaceToLight.create(surface, L); [branch] - if (surfaceToLight.NdotL > 0) + if (any(surfaceToLight.NdotL_sss)) { lightColor = light.GetColor().rgb * light.GetEnergy(); - float3 atmosphereTransmittance = 1; + [branch] if (GetFrame().options & OPTION_BIT_REALISTIC_SKY) { - AtmosphereParameters Atmosphere = GetWeather().atmosphere; - atmosphereTransmittance = GetAtmosphericLightTransmittance(Atmosphere, surface.P, L, texture_transmittancelut); + lightColor *= GetAtmosphericLightTransmittance(GetWeather().atmosphere, surface.P, L, texture_transmittancelut); } - lightColor *= atmosphereTransmittance; } } break; @@ -187,7 +184,7 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) surfaceToLight.create(surface, L); [branch] - if (surfaceToLight.NdotL > 0) + if (any(surfaceToLight.NdotL_sss)) { lightColor = light.GetColor().rgb * light.GetEnergy(); @@ -214,7 +211,7 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) surfaceToLight.create(surface, L); [branch] - if (surfaceToLight.NdotL > 0) + if (any(surfaceToLight.NdotL_sss)) { const float SpotFactor = dot(L, light.GetDirection()); const float spotCutOff = light.GetConeAngleCos(); @@ -236,13 +233,13 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) break; } - if (surfaceToLight.NdotL > 0 && dist > 0) + if (any(surfaceToLight.NdotL_sss) && dist > 0) { - float3 shadow = surfaceToLight.NdotL * energy; + float3 shadow = energy; RayDesc newRay; newRay.Origin = surface.P; - newRay.Direction = normalize(lerp(L, sample_hemisphere_cos(L, seed, uv), 0.025)); + newRay.Direction = normalize(lerp(L, sample_hemisphere_cos(L, seed, uv), 0.025 + max3(surface.sss))); newRay.TMin = 0.001; newRay.TMax = dist; #ifdef RTAPI @@ -276,9 +273,10 @@ void main(uint3 DTid : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex) #endif // RTAPI if (any(shadow)) { + lightColor *= shadow; lighting.direct.specular = lightColor * BRDF_GetSpecular(surface, surfaceToLight); lighting.direct.diffuse = lightColor * BRDF_GetDiffuse(surface, surfaceToLight); - result += max(0, shadow * (surface.albedo * (1 - surface.transmission) * lighting.direct.diffuse + lighting.direct.specular)) * surface.opacity; + result = mad(mad(surface.albedo * (1 - surface.transmission), lighting.direct.diffuse, lighting.direct.specular), surface.opacity, result); } } } diff --git a/WickedEngine/shaders/screenspaceshadowCS.hlsl b/WickedEngine/shaders/screenspaceshadowCS.hlsl index a413d9e25..1014c92a0 100644 --- a/WickedEngine/shaders/screenspaceshadowCS.hlsl +++ b/WickedEngine/shaders/screenspaceshadowCS.hlsl @@ -214,7 +214,7 @@ void main(uint3 DTid : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint3 GTid : uint seed = 0; float shadow = 0; - ray.Direction = normalize(lerp(L, mul(hemispherepoint_cos(bluenoise.x, bluenoise.y), get_tangentspace(L)), 0.025)); + ray.Direction = normalize(lerp(L, mul(hemispherepoint_cos(bluenoise.x, bluenoise.y), get_tangentspace(L)), 0.025 + max3(surface.sss))); #ifdef RTAPI RayQuery< diff --git a/WickedEngine/shaders/shadowPS_transparent.hlsl b/WickedEngine/shaders/shadowPS_transparent.hlsl index 50c60665d..0ddd87228 100644 --- a/WickedEngine/shaders/shadowPS_transparent.hlsl +++ b/WickedEngine/shaders/shadowPS_transparent.hlsl @@ -19,6 +19,8 @@ float4 main(PixelInput input) : SV_TARGET } color *= input.color; + clip(color.a - GetMaterial().alphaTest); + float opacity = color.a; [branch] diff --git a/WickedEngine/shaders/surfel_raytraceCS.hlsl b/WickedEngine/shaders/surfel_raytraceCS.hlsl index 127e732ea..0116ca47e 100644 --- a/WickedEngine/shaders/surfel_raytraceCS.hlsl +++ b/WickedEngine/shaders/surfel_raytraceCS.hlsl @@ -156,14 +156,14 @@ void main(uint3 DTid : SV_DispatchThreadID) [branch] if (NdotL > 0) { - float3 atmosphereTransmittance = 1.0; + float3 lightColor = light.GetColor().rgb * light.GetEnergy(); + + [branch] if (GetFrame().options & OPTION_BIT_REALISTIC_SKY) { - atmosphereTransmittance = GetAtmosphericLightTransmittance(GetWeather().atmosphere, surface.P, L, texture_transmittancelut); + lightColor *= GetAtmosphericLightTransmittance(GetWeather().atmosphere, surface.P, L, texture_transmittancelut); } - float3 lightColor = light.GetColor().rgb * light.GetEnergy() * atmosphereTransmittance; - lighting.direct.diffuse = lightColor; } } diff --git a/WickedEngine/wiAllocator.h b/WickedEngine/wiAllocator.h deleted file mode 100644 index 751630689..000000000 --- a/WickedEngine/wiAllocator.h +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once -#include "wiSpinLock.h" - -#include -#include - -namespace wiAllocator -{ - // Simple and efficient allocator that reserves a linear memory buffer and can: - // - allocate bottom-up until there is space - // - free from the last allocation top-down, for temporary allocations - // - reset all allocations at once - class LinearAllocator - { - public: - - constexpr size_t get_capacity() const - { - return capacity; - } - - inline void reserve(size_t newCapacity) - { - capacity = newCapacity; - - std::free(buffer); - buffer = (uint8_t*)std::malloc(capacity); - } - - constexpr uint8_t* allocate(size_t size) - { - if (offset + size <= capacity) - { - uint8_t* ret = &buffer[offset]; - offset += size; - return ret; - } - return nullptr; - } - - constexpr void free(size_t size) - { - assert(offset >= size); - offset -= size; - } - - constexpr void reset() - { - offset = 0; - } - - constexpr uint8_t* top() - { - return buffer + offset; - } - - private: - uint8_t* buffer = nullptr; - size_t capacity = 0; - size_t offset = 0; - size_t alignment = 1; - }; - - - - // Fixed size very simple thread safe ring buffer - template - class ThreadSafeRingBuffer - { - public: - // Push an item to the end if there is free space - // Returns true if succesful - // Returns false if there is not enough space - inline bool push_back(const T& item) - { - bool result = false; - lock.lock(); - size_t next = (head + 1) % capacity; - if (next != tail) - { - data[head] = item; - head = next; - result = true; - } - lock.unlock(); - return result; - } - - // Get an item if there are any - // Returns true if succesful - // Returns false if there are no items - inline bool pop_front(T& item) - { - bool result = false; - lock.lock(); - if (tail != head) - { - item = data[tail]; - tail = (tail + 1) % capacity; - result = true; - } - lock.unlock(); - return result; - } - - private: - T data[capacity]; - size_t head = 0; - size_t tail = 0; - wiSpinLock lock; - }; - -} diff --git a/WickedEngine/wiApplication.cpp b/WickedEngine/wiApplication.cpp new file mode 100644 index 000000000..cd09555be --- /dev/null +++ b/WickedEngine/wiApplication.cpp @@ -0,0 +1,537 @@ +#include "wiApplication.h" +#include "wiRenderPath.h" +#include "wiRenderer.h" +#include "wiHelper.h" +#include "wiTimer.h" +#include "wiInput.h" +#include "wiBacklog.h" +#include "wiApplication_BindLua.h" +#include "wiVersion.h" +#include "wiEnums.h" +#include "wiTextureHelper.h" +#include "wiProfiler.h" +#include "wiInitializer.h" +#include "wiArguments.h" +#include "wiFont.h" +#include "wiImage.h" +#include "wiEventHandler.h" + +#include "wiGraphicsDevice_DX12.h" +#include "wiGraphicsDevice_Vulkan.h" + +#include +#include +#include +#include +#include + +static std::atomic number_of_heap_allocations{ 0 }; +static std::atomic size_of_heap_allocations{ 0 }; + +using namespace wi::graphics; + +namespace wi +{ + + void Application::Initialize() + { + if (initialized) + { + return; + } + initialized = true; + + wi::initializer::InitializeComponentsAsync(); + } + + void Application::ActivatePath(RenderPath* component, float fadeSeconds, wi::Color fadeColor) + { + if (component != nullptr) + { + component->init(canvas); + } + + // Fade manager will activate on fadeout + fadeManager.Clear(); + fadeManager.Start(fadeSeconds, fadeColor, [this, component]() { + + if (GetActivePath() != nullptr) + { + GetActivePath()->Stop(); + } + + if (component != nullptr) + { + component->Start(); + } + activePath = component; + }); + + fadeManager.Update(0); // If user calls ActivatePath without fadeout, it will be instant + } + + void Application::Run() + { + + if (!initialized) + { + // Initialize in a lazy way, so the user application doesn't have to call this explicitly + Initialize(); + initialized = true; + } + if (!wi::initializer::IsInitializeFinished()) + { + // Until engine is not loaded, present initialization screen... + CommandList cmd = graphicsDevice->BeginCommandList(); + graphicsDevice->RenderPassBegin(&swapChain, cmd); + wi::image::SetCanvas(canvas, cmd); + wi::font::SetCanvas(canvas, cmd); + Viewport viewport; + viewport.width = (float)swapChain.desc.width; + viewport.height = (float)swapChain.desc.height; + graphicsDevice->BindViewports(1, &viewport, cmd); + wi::font::Params params; + params.posX = 5.f; + params.posY = 5.f; + std::string text = wi::backlog::getText(); + float textheight = wi::font::TextHeight(text, params); + float screenheight = canvas.GetLogicalHeight(); + if (textheight > screenheight) + { + params.posY = screenheight - textheight; + } + wi::font::Draw(text, params, cmd); + graphicsDevice->RenderPassEnd(cmd); + graphicsDevice->SubmitCommandLists(); + return; + } + + static bool startup_script = false; + if (!startup_script) + { + startup_script = true; + wi::lua::RegisterObject(wi::lua::Application_BindLua::className, "main", new wi::lua::Application_BindLua(this)); + wi::lua::RegisterObject(wi::lua::Application_BindLua::className, "application", new wi::lua::Application_BindLua(this)); + wi::lua::RunFile("startup.lua"); + } + + if (!is_window_active) + { + // If the application is not active, disable Update loops: + deltaTimeAccumulator = 0; + return; + } + + wi::profiler::BeginFrame(); + + deltaTime = float(std::max(0.0, timer.elapsed() / 1000.0)); + timer.record(); + + // Wake up the events that need to be executed on the main thread, in thread safe manner: + wi::eventhandler::FireEvent(wi::eventhandler::EVENT_THREAD_SAFE_POINT, 0); + + const float dt = framerate_lock ? (1.0f / targetFrameRate) : deltaTime; + + fadeManager.Update(dt); + + ColorSpace colorspace = graphicsDevice->GetSwapChainColorSpace(&swapChain); + + if (GetActivePath() != nullptr) + { + GetActivePath()->colorspace = colorspace; + GetActivePath()->init(canvas); + GetActivePath()->PreUpdate(); + } + + // Fixed time update: + auto range = wi::profiler::BeginRangeCPU("Fixed Update"); + { + if (frameskip) + { + deltaTimeAccumulator += dt; + if (deltaTimeAccumulator > 10) + { + // application probably lost control, fixed update would take too long + deltaTimeAccumulator = 0; + } + + const float targetFrameRateInv = 1.0f / targetFrameRate; + while (deltaTimeAccumulator >= targetFrameRateInv) + { + FixedUpdate(); + deltaTimeAccumulator -= targetFrameRateInv; + } + } + else + { + FixedUpdate(); + } + } + wi::profiler::EndRange(range); // Fixed Update + + // Variable-timed update: + Update(dt); + + Render(); + + wi::input::Update(window); + + // Begin final compositing: + CommandList cmd = graphicsDevice->BeginCommandList(); + wi::image::SetCanvas(canvas, cmd); + wi::font::SetCanvas(canvas, cmd); + Viewport viewport; + viewport.width = (float)swapChain.desc.width; + viewport.height = (float)swapChain.desc.height; + graphicsDevice->BindViewports(1, &viewport, cmd); + + bool colorspace_conversion_required = colorspace == ColorSpace::HDR10_ST2084; + if (colorspace_conversion_required) + { + // In HDR10, we perform the compositing in a custom linear color space render target + graphicsDevice->RenderPassBegin(&renderpass, cmd); + } + else + { + // If swapchain is SRGB or Linear HDR, it can be used for blending + // - If it is SRGB, the render path will ensure tonemapping to SDR + // - If it is Linear HDR, we can blend trivially in linear space + graphicsDevice->RenderPassBegin(&swapChain, cmd); + } + Compose(cmd); + graphicsDevice->RenderPassEnd(cmd); + + if (colorspace_conversion_required) + { + // In HDR10, we perform a final mapping from linear to HDR10, into the swapchain + graphicsDevice->RenderPassBegin(&swapChain, cmd); + wi::image::Params fx; + fx.enableFullScreen(); + fx.enableHDR10OutputMapping(); + wi::image::Draw(&rendertarget, fx, cmd); + graphicsDevice->RenderPassEnd(cmd); + } + + wi::profiler::EndFrame(cmd); + graphicsDevice->SubmitCommandLists(); + } + + void Application::Update(float dt) + { + auto range = wi::profiler::BeginRangeCPU("Update"); + + wi::lua::SetDeltaTime(double(dt)); + wi::lua::Update(); + + wi::backlog::Update(canvas, dt); + + if (GetActivePath() != nullptr) + { + GetActivePath()->Update(dt); + GetActivePath()->PostUpdate(); + } + + wi::profiler::EndRange(range); // Update + } + + void Application::FixedUpdate() + { + wi::lua::FixedUpdate(); + + if (GetActivePath() != nullptr) + { + GetActivePath()->FixedUpdate(); + } + } + + void Application::Render() + { + auto range = wi::profiler::BeginRangeCPU("Render"); + + wi::lua::Render(); + + if (GetActivePath() != nullptr) + { + GetActivePath()->Render(); + } + + wi::profiler::EndRange(range); // Render + } + + void Application::Compose(CommandList cmd) + { + auto range = wi::profiler::BeginRangeCPU("Compose"); + + if (GetActivePath() != nullptr) + { + GetActivePath()->Compose(cmd); + } + + if (fadeManager.IsActive()) + { + // display fade rect + static wi::image::Params fx; + fx.siz.x = canvas.GetLogicalWidth(); + fx.siz.y = canvas.GetLogicalHeight(); + fx.opacity = fadeManager.opacity; + wi::image::Draw(wi::texturehelper::getColor(fadeManager.color), fx, cmd); + } + + // Draw the information display + if (infoDisplay.active) + { + infodisplay_str.clear(); + if (infoDisplay.watermark) + { + infodisplay_str += "Wicked Engine "; + infodisplay_str += wi::version::GetVersionString(); + infodisplay_str += " "; + +#if defined(_ARM) + infodisplay_str += "[ARM]"; +#elif defined(_WIN64) + infodisplay_str += "[64-bit]"; +#elif defined(_WIN32) + infodisplay_str += "[32-bit]"; +#endif + +#ifdef PLATFORM_UWP + infodisplay_str += "[UWP]"; +#endif + +#ifdef WICKEDENGINE_BUILD_DX12 + if (dynamic_cast(graphicsDevice.get())) + { + infodisplay_str += "[DX12]"; + } +#endif +#ifdef WICKEDENGINE_BUILD_VULKAN + if (dynamic_cast(graphicsDevice.get())) + { + infodisplay_str += "[Vulkan]"; + } +#endif + +#ifdef _DEBUG + infodisplay_str += "[DEBUG]"; +#endif + if (graphicsDevice->IsDebugDevice()) + { + infodisplay_str += "[debugdevice]"; + } + infodisplay_str += "\n"; + } + if (infoDisplay.resolution) + { + infodisplay_str += "Resolution: " + std::to_string(canvas.GetPhysicalWidth()) + " x " + std::to_string(canvas.GetPhysicalHeight()) + " (" + std::to_string(int(canvas.GetDPI())) + " dpi)\n"; + } + if (infoDisplay.logical_size) + { + infodisplay_str += "Logical Size: " + std::to_string(int(canvas.GetLogicalWidth())) + " x " + std::to_string(int(canvas.GetLogicalHeight())) + "\n"; + } + if (infoDisplay.colorspace) + { + infodisplay_str += "Color Space: "; + ColorSpace colorSpace = graphicsDevice->GetSwapChainColorSpace(&swapChain); + switch (colorSpace) + { + default: + case wi::graphics::ColorSpace::SRGB: + infodisplay_str += "sRGB"; + break; + case wi::graphics::ColorSpace::HDR10_ST2084: + infodisplay_str += "ST.2084 (HDR10)"; + break; + case wi::graphics::ColorSpace::HDR_LINEAR: + infodisplay_str += "Linear (HDR)"; + break; + } + infodisplay_str += "\n"; + } + if (infoDisplay.fpsinfo) + { + deltatimes[fps_avg_counter++ % arraysize(deltatimes)] = deltaTime; + float displaydeltatime = deltaTime; + if (fps_avg_counter > arraysize(deltatimes)) + { + float avg_time = 0; + for (int i = 0; i < arraysize(deltatimes); ++i) + { + avg_time += deltatimes[i]; + } + displaydeltatime = avg_time / arraysize(deltatimes); + } + + infodisplay_str += std::to_string(int(std::round(1.0f / displaydeltatime))) + " FPS\n"; + } + if (infoDisplay.heap_allocation_counter) + { + infodisplay_str += "Heap allocations per frame: " + std::to_string(number_of_heap_allocations.load()) + " (" + std::to_string(size_of_heap_allocations.load()) + " bytes)\n"; + number_of_heap_allocations.store(0); + size_of_heap_allocations.store(0); + } + if (infoDisplay.pipeline_count) + { + infodisplay_str += "Graphics pipelines active: " + std::to_string(graphicsDevice->GetActivePipelineCount()) + "\n"; + } + +#ifdef _DEBUG + infodisplay_str += "Warning: This is a [DEBUG] build, performance will be slow!\n"; +#endif + if (graphicsDevice->IsDebugDevice()) + { + infodisplay_str += "Warning: Graphics is in [debugdevice] mode, performance will be slow!\n"; + } + + wi::font::Draw(infodisplay_str, wi::font::Params(4, 4, infoDisplay.size, wi::font::WIFALIGN_LEFT, wi::font::WIFALIGN_TOP, wi::Color(255, 255, 255, 255), wi::Color(0, 0, 0, 255)), cmd); + + if (infoDisplay.colorgrading_helper) + { + wi::image::Draw(wi::texturehelper::getColorGradeDefault(), wi::image::Params(0, 0, 256.0f / canvas.GetDPIScaling(), 16.0f / canvas.GetDPIScaling()), cmd); + } + } + + wi::profiler::DrawData(canvas, 4, 120, cmd); + + wi::backlog::Draw(canvas, cmd); + + wi::profiler::EndRange(range); // Compose + } + + void Application::SetWindow(wi::platform::window_type window, bool fullscreen) + { + this->window = window; + + // User can also create a graphics device if custom logic is desired, but they must do before this function! + if (graphicsDevice == nullptr) + { + bool debugdevice = wi::arguments::HasArgument("debugdevice"); + bool gpuvalidation = wi::arguments::HasArgument("gpuvalidation"); + + bool use_dx12 = wi::arguments::HasArgument("dx12"); + bool use_vulkan = wi::arguments::HasArgument("vulkan"); + +#ifndef WICKEDENGINE_BUILD_DX12 + if (use_dx12) { + wi::helper::messageBox("The engine was built without DX12 support!", "Error"); + use_dx12 = false; + } +#endif +#ifndef WICKEDENGINE_BUILD_VULKAN + if (use_vulkan) { + wi::helper::messageBox("The engine was built without Vulkan support!", "Error"); + use_vulkan = false; + } +#endif + + if (!use_dx12 && !use_vulkan) + { +#if defined(WICKEDENGINE_BUILD_DX12) + use_dx12 = true; +#elif defined(WICKEDENGINE_BUILD_VULKAN) + use_vulkan = true; +#else + wi::backlog::post("No rendering backend is enabled! Please enable at least one so we can use it as default", wi::backlog::LogLevel::Error); + assert(false); +#endif + } + assert(use_dx12 || use_vulkan); + + if (use_vulkan) + { +#ifdef WICKEDENGINE_BUILD_VULKAN + wi::renderer::SetShaderPath(wi::renderer::GetShaderPath() + "spirv/"); + graphicsDevice = std::make_unique(window, debugdevice); +#endif + } + else if (use_dx12) + { +#ifdef WICKEDENGINE_BUILD_DX12 + wi::renderer::SetShaderPath(wi::renderer::GetShaderPath() + "hlsl6/"); + graphicsDevice = std::make_unique(debugdevice, gpuvalidation); +#endif + } + } + wi::graphics::GetDevice() = graphicsDevice.get(); + wi::renderer::InitializeCommonSamplers(); + + canvas.init(window); + + SwapChainDesc desc; + if (swapChain.IsValid()) + { + // it will only resize, but keep format and other settings + desc = swapChain.desc; + } + else + { + // initialize for the first time + desc.buffer_count = 3; + desc.format = Format::R10G10B10A2_UNORM; + } + desc.width = canvas.GetPhysicalWidth(); + desc.height = canvas.GetPhysicalHeight(); + desc.allow_hdr = allow_hdr; + bool success = graphicsDevice->CreateSwapChain(&desc, window, &swapChain); + assert(success); + + swapChainVsyncChangeEvent = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_SET_VSYNC, [this](uint64_t userdata) { + SwapChainDesc desc = swapChain.desc; + desc.vsync = userdata != 0; + bool success = graphicsDevice->CreateSwapChain(&desc, nullptr, &swapChain); + assert(success); + }); + + if (graphicsDevice->GetSwapChainColorSpace(&swapChain) == ColorSpace::HDR10_ST2084) + { + TextureDesc desc; + desc.width = swapChain.desc.width; + desc.height = swapChain.desc.height; + desc.format = Format::R11G11B10_FLOAT; + desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; + bool success = graphicsDevice->CreateTexture(&desc, nullptr, &rendertarget); + assert(success); + graphicsDevice->SetName(&rendertarget, "Application::rendertarget"); + + RenderPassDesc renderpassdesc; + renderpassdesc.attachments.push_back(RenderPassAttachment::RenderTarget(&rendertarget, RenderPassAttachment::LoadOp::CLEAR)); + success = graphicsDevice->CreateRenderPass(&renderpassdesc, &renderpass); + assert(success); + } + } + +} + + +// Heap alloc replacements are used to count heap allocations: +// It is good practice to reduce the amount of heap allocations that happen during the frame, +// so keep an eye on the info display of the engine while Application::InfoDisplayer::heap_allocation_counter is enabled + +void* operator new(std::size_t size) { + number_of_heap_allocations.fetch_add(1); + size_of_heap_allocations.fetch_add(size); + void* p = malloc(size); + if (!p) throw std::bad_alloc(); + return p; +} +void* operator new[](std::size_t size) { + number_of_heap_allocations.fetch_add(1); + size_of_heap_allocations.fetch_add(size); + void* p = malloc(size); + if (!p) throw std::bad_alloc(); + return p; +} +void* operator new[](std::size_t size, const std::nothrow_t&) throw() { + number_of_heap_allocations.fetch_add(1); + size_of_heap_allocations.fetch_add(size); + return malloc(size); +} +void* operator new(std::size_t size, const std::nothrow_t&) throw() { + number_of_heap_allocations.fetch_add(1); + size_of_heap_allocations.fetch_add(size); + return malloc(size); +} +void operator delete(void* ptr) throw() { free(ptr); } +void operator delete (void* ptr, const std::nothrow_t&) throw() { free(ptr); } +void operator delete[](void* ptr) throw() { free(ptr); } +void operator delete[](void* ptr, const std::nothrow_t&) throw() { free(ptr); } diff --git a/WickedEngine/wiApplication.h b/WickedEngine/wiApplication.h new file mode 100644 index 000000000..df2b68806 --- /dev/null +++ b/WickedEngine/wiApplication.h @@ -0,0 +1,122 @@ +#pragma once +#include "CommonInclude.h" +#include "wiPlatform.h" +#include "wiResourceManager.h" +#include "wiColor.h" +#include "wiFadeManager.h" +#include "wiGraphics.h" +#include "wiEventHandler.h" +#include "wiCanvas.h" + +#include +#include + +namespace wi +{ + class RenderPath; + + // This can be used as a Wicked Engine application + // - SetWindow() will set a window from operating system and initialize graphics device + // - Run() will run the main application logic. It needs to be called every frame + class Application + { + protected: + std::unique_ptr graphicsDevice; + wi::eventhandler::Handle swapChainVsyncChangeEvent; + + RenderPath* activePath = nullptr; + float targetFrameRate = 60; + bool frameskip = true; + bool framerate_lock = false; + bool initialized = false; + + wi::FadeManager fadeManager; + + float deltaTime = 0; + float deltaTimeAccumulator = 0; + wi::Timer timer; + + float deltatimes[20] = {}; + int fps_avg_counter = 0; + + // These are used when HDR10 color space is active: + // Because we want to blend in linear color space, but HDR10 is non-linear + wi::graphics::Texture rendertarget; + wi::graphics::RenderPass renderpass; + + std::string infodisplay_str; + + public: + virtual ~Application() = default; + + bool is_window_active = true; + bool allow_hdr = true; + wi::graphics::SwapChain swapChain; + wi::Canvas canvas; + wi::platform::window_type window; + + // Runs the main engine loop + void Run(); + + // This will activate a RenderPath as the active one, so it will run its Update, FixedUpdate, Render and Compose functions + // You can set a fade time and fade screen color so that switching components will happen when the screen is faded out. Then it will fade back to the new component + void ActivatePath(RenderPath* component, float fadeSeconds = 0, wi::Color fadeColor = wi::Color(0, 0, 0, 255)); + inline RenderPath* GetActivePath() { return activePath; } + + // Set the desired target framerate for the FixedUpdate() loop (default = 60) + void setTargetFrameRate(float value) { targetFrameRate = value; } + // Get the desired target framerate for the FixedUpdate() loop + float getTargetFrameRate() const { return targetFrameRate; } + // Set the desired behaviour of the FixedUpdate() loop (default = true) + // enabled : the FixedUpdate() loop will run at targetFrameRate frequency + // disabled : the FixedUpdate() loop will run every frame only once. + void setFrameSkip(bool enabled) { frameskip = enabled; } + void setFrameRateLock(bool enabled) { framerate_lock = enabled; } + + // This is where the critical initializations happen (before any rendering or anything else) + virtual void Initialize(); + // This is where application-wide updates get executed once per frame. + // RenderPath::Update is also called from here for the active component + virtual void Update(float dt); + // This is where application-wide updates get executed in a fixed timestep based manner. + // RenderPath::FixedUpdate is also called from here for the active component + virtual void FixedUpdate(); + // This is where application-wide rendering happens to offscreen buffers. + // RenderPath::Render is also called from here for the active component + virtual void Render(); + // This is where the application will render to the screen (backbuffer). It must render to the provided command list. + virtual void Compose(wi::graphics::CommandList cmd); + + // You need to call this before calling Run() or Initialize() if you want to render + void SetWindow(wi::platform::window_type, bool fullscreen = false); + + + struct InfoDisplayer + { + // activate the whole display + bool active = false; + // display engine version number + bool watermark = true; + // display framerate + bool fpsinfo = false; + // display resolution info + bool resolution = false; + // window's size in logical (DPI scaled) units + bool logical_size = false; + // HDR status and color space + bool colorspace = false; + // display number of heap allocations per frame + bool heap_allocation_counter = false; + // display the active graphics pipeline count + bool pipeline_count = false; + // text size + int size = 16; + // display default color grading helper texture in top left corner of the screen + bool colorgrading_helper = false; + }; + // display all-time engine information text + InfoDisplayer infoDisplay; + + }; + +} diff --git a/WickedEngine/wiApplication_BindLua.cpp b/WickedEngine/wiApplication_BindLua.cpp new file mode 100644 index 000000000..3cc8444e6 --- /dev/null +++ b/WickedEngine/wiApplication_BindLua.cpp @@ -0,0 +1,417 @@ +#include "wiApplication_BindLua.h" +#include "wiRenderPath_BindLua.h" +#include "wiRenderPath3D_BindLua.h" +#include "wiRenderPath2D_BindLua.h" +#include "wiLoadingScreen_BindLua.h" +#include "wiProfiler.h" + +namespace wi::lua +{ + + const char Application_BindLua::className[] = "Application"; + + Luna::FunctionType Application_BindLua::methods[] = { + lunamethod(Application_BindLua, GetActivePath), + lunamethod(Application_BindLua, SetActivePath), + lunamethod(Application_BindLua, SetFrameSkip), + lunamethod(Application_BindLua, SetTargetFrameRate), + lunamethod(Application_BindLua, SetFrameRateLock), + lunamethod(Application_BindLua, SetInfoDisplay), + lunamethod(Application_BindLua, SetWatermarkDisplay), + lunamethod(Application_BindLua, SetFPSDisplay), + lunamethod(Application_BindLua, SetResolutionDisplay), + lunamethod(Application_BindLua, SetLogicalSizeDisplay), + lunamethod(Application_BindLua, SetPipelineCountDisplay), + lunamethod(Application_BindLua, SetHeapAllocationCountDisplay), + lunamethod(Application_BindLua, GetCanvas), + { NULL, NULL } + }; + Luna::PropertyType Application_BindLua::properties[] = { + { NULL, NULL } + }; + + Application_BindLua::Application_BindLua(Application* component) :component(component) + { + } + + Application_BindLua::Application_BindLua(lua_State* L) + { + component = nullptr; + } + + int Application_BindLua::GetActivePath(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "GetActivePath() component is empty!"); + return 0; + } + + //return 3d component if the active one is of that type + RenderPath3D* comp3D = dynamic_cast(component->GetActivePath()); + if (comp3D != nullptr) + { + Luna::push(L, new RenderPath3D_BindLua(comp3D)); + return 1; + } + + //return loading component if the active one is of that type + LoadingScreen* compLoad = dynamic_cast(component->GetActivePath()); + if (compLoad != nullptr) + { + Luna::push(L, new LoadingScreen_BindLua(compLoad)); + return 1; + } + + //return 2d component if the active one is of that type + RenderPath2D* comp2D = dynamic_cast(component->GetActivePath()); + if (comp2D != nullptr) + { + Luna::push(L, new RenderPath2D_BindLua(comp2D)); + return 1; + } + + //return component if the active one is of that type + RenderPath* comp = dynamic_cast(component->GetActivePath()); + if (comp != nullptr) + { + Luna::push(L, new RenderPath_BindLua(comp)); + return 1; + } + + wi::lua::SError(L, "GetActivePath() Warning: type of active component not registered!"); + return 0; + } + int Application_BindLua::SetActivePath(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetActivePath(RenderPath component) component is empty!"); + return 0; + } + + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + float fadeSeconds = 0; + wi::Color fadeColor = wi::Color(0, 0, 0, 255); + if (argc > 1) + { + fadeSeconds = wi::lua::SGetFloat(L, 2); + if (argc > 2) + { + fadeColor.setR((uint8_t)wi::lua::SGetInt(L, 3)); + if (argc > 3) + { + fadeColor.setG((uint8_t)wi::lua::SGetInt(L, 4)); + if (argc > 4) + { + fadeColor.setB((uint8_t)wi::lua::SGetInt(L, 5)); + } + } + } + } + + RenderPath3D_BindLua* comp3D = Luna::lightcheck(L, 1); + if (comp3D != nullptr) + { + component->ActivatePath(comp3D->component, fadeSeconds, fadeColor); + return 0; + } + + LoadingScreen_BindLua* compLoad = Luna::lightcheck(L, 1); + if (compLoad != nullptr) + { + component->ActivatePath(compLoad->component, fadeSeconds, fadeColor); + return 0; + } + + RenderPath2D_BindLua* comp2D = Luna::lightcheck(L, 1); + if (comp2D != nullptr) + { + component->ActivatePath(comp2D->component, fadeSeconds, fadeColor); + return 0; + } + + RenderPath_BindLua* comp = Luna::lightcheck(L, 1); + if (comp != nullptr) + { + component->ActivatePath(comp->component, fadeSeconds, fadeColor); + return 0; + } + } + else + { + wi::lua::SError(L, "SetActivePath(RenderPath component, opt int fadeFrames,fadeColorR,fadeColorG,fadeColorB) not enought arguments!"); + return 0; + } + return 0; + } + int Application_BindLua::SetFrameSkip(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetFrameSkip(bool enabled) component is empty!"); + return 0; + } + + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->setFrameSkip(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetFrameSkip(bool enabled) not enought arguments!"); + return 0; + } + int Application_BindLua::SetTargetFrameRate(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetTargetFrameRate(float value) component is empty!"); + return 0; + } + + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->setTargetFrameRate(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetTargetFrameRate(float value) not enought arguments!"); + return 0; + } + int Application_BindLua::SetFrameRateLock(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetFrameRateLock(bool enabled) component is empty!"); + return 0; + } + + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->setFrameRateLock(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetFrameRateLock(bool enabled) not enought arguments!"); + return 0; + } + int Application_BindLua::SetInfoDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetInfoDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.active = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetInfoDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetWatermarkDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetWatermarkDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.watermark = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetWatermarkDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetFPSDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetFPSDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.fpsinfo = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetFPSDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetResolutionDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetResolutionDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.resolution = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetResolutionDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetLogicalSizeDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetLogicalSizeDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.logical_size = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetLogicalSizeDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetPipelineCountDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetPipelineCountDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.pipeline_count = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetPipelineCountDisplay(bool active) not enough arguments!"); + return 0; + } + int Application_BindLua::SetHeapAllocationCountDisplay(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetHeapAllocationCountDisplay() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + component->infoDisplay.heap_allocation_counter = wi::lua::SGetBool(L, 1); + } + else + wi::lua::SError(L, "SetHeapAllocationCountDisplay(bool active) not enough arguments!"); + return 0; + } + + int Application_BindLua::GetCanvas(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "GetCanvas() component is empty!"); + return 0; + } + Luna::push(L, new Canvas_BindLua(component->canvas)); + return 1; + } + + + int SetProfilerEnabled(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::profiler::SetEnabled(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetProfilerEnabled(bool active) not enough arguments!"); + + return 0; + } + + void Application_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + + wi::lua::RegisterFunc("SetProfilerEnabled", SetProfilerEnabled); + } + } + + + + + + + + + + + const char Canvas_BindLua::className[] = "Canvas"; + + Luna::FunctionType Canvas_BindLua::methods[] = { + lunamethod(Canvas_BindLua, GetDPI), + lunamethod(Canvas_BindLua, GetDPIScaling), + lunamethod(Canvas_BindLua, GetPhysicalWidth), + lunamethod(Canvas_BindLua, GetPhysicalHeight), + lunamethod(Canvas_BindLua, GetLogicalWidth), + lunamethod(Canvas_BindLua, GetLogicalHeight), + { NULL, NULL } + }; + Luna::PropertyType Canvas_BindLua::properties[] = { + { NULL, NULL } + }; + + + int Canvas_BindLua::GetDPI(lua_State* L) + { + wi::lua::SSetFloat(L, canvas.GetDPI()); + return 1; + } + int Canvas_BindLua::GetDPIScaling(lua_State* L) + { + wi::lua::SSetFloat(L, canvas.GetDPIScaling()); + return 1; + } + int Canvas_BindLua::GetPhysicalWidth(lua_State* L) + { + wi::lua::SSetInt(L, canvas.GetPhysicalWidth()); + return 1; + } + int Canvas_BindLua::GetPhysicalHeight(lua_State* L) + { + wi::lua::SSetInt(L, canvas.GetPhysicalHeight()); + return 1; + } + int Canvas_BindLua::GetLogicalWidth(lua_State* L) + { + wi::lua::SSetFloat(L, canvas.GetLogicalWidth()); + return 1; + } + int Canvas_BindLua::GetLogicalHeight(lua_State* L) + { + wi::lua::SSetFloat(L, canvas.GetLogicalHeight()); + return 1; + } + + void Canvas_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + +} diff --git a/WickedEngine/wiApplication_BindLua.h b/WickedEngine/wiApplication_BindLua.h new file mode 100644 index 000000000..f5519a71d --- /dev/null +++ b/WickedEngine/wiApplication_BindLua.h @@ -0,0 +1,60 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiApplication.h" + +namespace wi::lua +{ + + class Canvas_BindLua + { + public: + wi::Canvas canvas; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + Canvas_BindLua(const wi::Canvas& canvas) : canvas(canvas) {} + Canvas_BindLua(lua_State* L) {} + + int GetDPI(lua_State* L); + int GetDPIScaling(lua_State* L); + int GetPhysicalWidth(lua_State* L); + int GetPhysicalHeight(lua_State* L); + int GetLogicalWidth(lua_State* L); + int GetLogicalHeight(lua_State* L); + + static void Bind(); + }; + + class Application_BindLua + { + private: + Application* component = nullptr; + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + Application_BindLua(Application* component = nullptr); + Application_BindLua(lua_State* L); + + int GetActivePath(lua_State* L); + int SetActivePath(lua_State* L); + int SetFrameSkip(lua_State* L); + int SetTargetFrameRate(lua_State* L); + int SetFrameRateLock(lua_State* L); + int SetInfoDisplay(lua_State* L); + int SetWatermarkDisplay(lua_State* L); + int SetFPSDisplay(lua_State* L); + int SetResolutionDisplay(lua_State* L); + int SetLogicalSizeDisplay(lua_State* L); + int SetPipelineCountDisplay(lua_State* L); + int SetHeapAllocationCountDisplay(lua_State* L); + + int GetCanvas(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiArchive.cpp b/WickedEngine/wiArchive.cpp index eaab9bfc9..91d82faea 100644 --- a/WickedEngine/wiArchive.cpp +++ b/WickedEngine/wiArchive.cpp @@ -3,101 +3,106 @@ #include -// this should always be only INCREMENTED and only if a new serialization is implemeted somewhere! -uint64_t __archiveVersion = 73; -// this is the version number of which below the archive is not compatible with the current version -uint64_t __archiveVersionBarrier = 22; - -// version history is logged in ArchiveVersionHistory.txt file! - -wiArchive::wiArchive() +namespace wi { - CreateEmpty(); -} -wiArchive::wiArchive(const std::string& fileName, bool readMode) : fileName(fileName), readMode(readMode) -{ - if (!fileName.empty()) + + // this should always be only INCREMENTED and only if a new serialization is implemeted somewhere! + static constexpr uint64_t __archiveVersion = 73; + // this is the version number of which below the archive is not compatible with the current version + static constexpr uint64_t __archiveVersionBarrier = 22; + + // version history is logged in ArchiveVersionHistory.txt file! + + Archive::Archive() { - directory = wiHelper::GetDirectoryFromPath(fileName); - if (readMode) + CreateEmpty(); + } + Archive::Archive(const std::string& fileName, bool readMode) : fileName(fileName), readMode(readMode) + { + if (!fileName.empty()) { - if (wiHelper::FileRead(fileName, DATA)) + directory = wi::helper::GetDirectoryFromPath(fileName); + if (readMode) { - data_ptr = DATA.data(); - (*this) >> version; - if (version < __archiveVersionBarrier) + if (wi::helper::FileRead(fileName, DATA)) { - wiHelper::messageBox("The archive version (" + std::to_string(version) + ") is no longer supported!", "Error!"); - Close(); - } - if (version > __archiveVersion) - { - wiHelper::messageBox("The archive version (" + std::to_string(version) + ") is higher than the program's (" + std::to_string(__archiveVersion) + ")!", "Error!"); - Close(); + data_ptr = DATA.data(); + (*this) >> version; + if (version < __archiveVersionBarrier) + { + wi::helper::messageBox("The archive version (" + std::to_string(version) + ") is no longer supported!", "Error!"); + Close(); + } + if (version > __archiveVersion) + { + wi::helper::messageBox("The archive version (" + std::to_string(version) + ") is higher than the program's (" + std::to_string(__archiveVersion) + ")!", "Error!"); + Close(); + } } } + else + { + CreateEmpty(); + } + } + } + + Archive::Archive(const uint8_t* data) + { + data_ptr = data; + SetReadModeAndResetPos(true); + } + + void Archive::CreateEmpty() + { + version = __archiveVersion; + DATA.resize(128); // starting size + data_ptr = DATA.data(); + SetReadModeAndResetPos(false); + } + + void Archive::SetReadModeAndResetPos(bool isReadMode) + { + readMode = isReadMode; + pos = 0; + + if (readMode) + { + (*this) >> version; } else { - CreateEmpty(); + (*this) << version; } } -} -wiArchive::wiArchive(const uint8_t* data) -{ - data_ptr = data; - SetReadModeAndResetPos(true); -} - -void wiArchive::CreateEmpty() -{ - version = __archiveVersion; - DATA.resize(128); // starting size - data_ptr = DATA.data(); - SetReadModeAndResetPos(false); -} - -void wiArchive::SetReadModeAndResetPos(bool isReadMode) -{ - readMode = isReadMode; - pos = 0; - - if (readMode) + void Archive::Close() { - (*this) >> version; + if (!readMode && !fileName.empty()) + { + SaveFile(fileName); + } + DATA.clear(); } - else + + bool Archive::SaveFile(const std::string& fileName) { - (*this) << version; + return wi::helper::FileWrite(fileName, data_ptr, pos); } -} -void wiArchive::Close() -{ - if (!readMode && !fileName.empty()) + bool Archive::SaveHeaderFile(const std::string& fileName, const std::string& dataName) { - SaveFile(fileName); + return wi::helper::Bin2H(data_ptr, pos, fileName, dataName.c_str()); } - DATA.clear(); -} -bool wiArchive::SaveFile(const std::string& fileName) -{ - return wiHelper::FileWrite(fileName, data_ptr, pos); -} + const std::string& Archive::GetSourceDirectory() const + { + return directory; + } -bool wiArchive::SaveHeaderFile(const std::string& fileName, const std::string& dataName) -{ - return wiHelper::Bin2H(data_ptr, pos, fileName, dataName.c_str()); -} + const std::string& Archive::GetSourceFileName() const + { + return fileName; + } -const std::string& wiArchive::GetSourceDirectory() const -{ - return directory; -} - -const std::string& wiArchive::GetSourceFileName() const -{ - return fileName; } diff --git a/WickedEngine/wiArchive.h b/WickedEngine/wiArchive.h index 7b19a88dc..099ea8e95 100644 --- a/WickedEngine/wiArchive.h +++ b/WickedEngine/wiArchive.h @@ -5,370 +5,372 @@ #include -// This is a data container used for serialization purposes. -// It can be used to READ or WRITE data, but not both at the same time. -// An archive that was created in WRITE mode can be changed to read mode and vica-versa -// The data flow is always FIFO (first in, first out) -class wiArchive +namespace wi { -private: - uint64_t version = 0; // the version number is used for maintaining backwards compatibility with earlier archive versions - bool readMode = false; // archive can be either read or write mode, but not both - size_t pos = 0; // position of the next memory operation, relative to the data's beginning - wi::vector DATA; // data suitable for read/write operations - const uint8_t* data_ptr = nullptr; // this can either be a memory mapped pointer (read only), or the DATA's pointer + // This is a data container used for serialization purposes. + // It can be used to READ or WRITE data, but not both at the same time. + // An archive that was created in WRITE mode can be changed to read mode and vica-versa + // The data flow is always FIFO (first in, first out) + class Archive + { + private: + uint64_t version = 0; // the version number is used for maintaining backwards compatibility with earlier archive versions + bool readMode = false; // archive can be either read or write mode, but not both + size_t pos = 0; // position of the next memory operation, relative to the data's beginning + wi::vector DATA; // data suitable for read/write operations + const uint8_t* data_ptr = nullptr; // this can either be a memory mapped pointer (read only), or the DATA's pointer - std::string fileName; // save to this file on closing if not empty - std::string directory; // the directory part from the fileName + std::string fileName; // save to this file on closing if not empty + std::string directory; // the directory part from the fileName - void CreateEmpty(); // creates new archive in write mode + void CreateEmpty(); // creates new archive in write mode -public: - // Create empty arhive for writing - wiArchive(); - wiArchive(const wiArchive&) = default; - wiArchive(wiArchive&&) = default; - // Create archive from a file. - // If readMode == true, the whole file will be loaded into the archive in read mode - // If readMode == false, the file will be written when the archive is destroyed or Close() is called - wiArchive(const std::string& fileName, bool readMode = true); - // Creates a memory mapped archive in read mode - wiArchive(const uint8_t* data); - ~wiArchive() { Close(); } + public: + // Create empty arhive for writing + Archive(); + Archive(const Archive&) = default; + Archive(Archive&&) = default; + // Create archive from a file. + // If readMode == true, the whole file will be loaded into the archive in read mode + // If readMode == false, the file will be written when the archive is destroyed or Close() is called + Archive(const std::string& fileName, bool readMode = true); + // Creates a memory mapped archive in read mode + Archive(const uint8_t* data); + ~Archive() { Close(); } - wiArchive& operator=(const wiArchive&) = default; - wiArchive& operator=(wiArchive&&) = default; + Archive& operator=(const Archive&) = default; + Archive& operator=(Archive&&) = default; - const uint8_t* GetData() const { return data_ptr; } - constexpr uint64_t GetVersion() const { return version; } - constexpr bool IsReadMode() const { return readMode; } - // This can set the archive into either read or write mode, and it will reset it's position - void SetReadModeAndResetPos(bool isReadMode); - // Check if the archive has any data - bool IsOpen() const { return data_ptr != nullptr; }; - // Close the archive. - // If it was opened from a file in write mode, the file will be written at this point - // The data will be deleted, the archive will be empty after this - void Close(); - // Write the archive contents to a specific file - // The archive data will be written starting from the beginning, to the current position - bool SaveFile(const std::string& fileName); - // Write the archive contents into a C++ header file - // dataName : it will be the name of the byte data array in the header, that can be memory mapped - bool SaveHeaderFile(const std::string& fileName, const std::string& dataName); - // If the archive was opened from a file, this will return the file's directory - const std::string& GetSourceDirectory() const; - // If the archive was opened from a file, this will return the file's name - // The file's name will include the directory as well - const std::string& GetSourceFileName() const; + const uint8_t* GetData() const { return data_ptr; } + constexpr uint64_t GetVersion() const { return version; } + constexpr bool IsReadMode() const { return readMode; } + // This can set the archive into either read or write mode, and it will reset it's position + void SetReadModeAndResetPos(bool isReadMode); + // Check if the archive has any data + bool IsOpen() const { return data_ptr != nullptr; }; + // Close the archive. + // If it was opened from a file in write mode, the file will be written at this point + // The data will be deleted, the archive will be empty after this + void Close(); + // Write the archive contents to a specific file + // The archive data will be written starting from the beginning, to the current position + bool SaveFile(const std::string& fileName); + // Write the archive contents into a C++ header file + // dataName : it will be the name of the byte data array in the header, that can be memory mapped + bool SaveHeaderFile(const std::string& fileName, const std::string& dataName); + // If the archive was opened from a file, this will return the file's directory + const std::string& GetSourceDirectory() const; + // If the archive was opened from a file, this will return the file's name + // The file's name will include the directory as well + const std::string& GetSourceFileName() const; - // It could be templated but we have to be extremely careful of different datasizes on different platforms - // because serialized data should be interchangeable! - // So providing exact copy operations for exact types enforces platform agnosticism + // It could be templated but we have to be extremely careful of different datasizes on different platforms + // because serialized data should be interchangeable! + // So providing exact copy operations for exact types enforces platform agnosticism - // Write operations - inline wiArchive& operator<<(bool data) - { - _write((uint32_t)(data ? 1 : 0)); - return *this; - } - inline wiArchive& operator<<(char data) - { - _write((int8_t)data); - return *this; - } - inline wiArchive& operator<<(unsigned char data) - { - _write((uint8_t)data); - return *this; - } - inline wiArchive& operator<<(int data) - { - _write((int64_t)data); - return *this; - } - inline wiArchive& operator<<(unsigned int data) - { - _write((uint64_t)data); - return *this; - } - inline wiArchive& operator<<(long data) - { - _write((int64_t)data); - return *this; - } - inline wiArchive& operator<<(unsigned long data) - { - _write((uint64_t)data); - return *this; - } - inline wiArchive& operator<<(long long data) - { - _write((int64_t)data); - return *this; - } - inline wiArchive& operator<<(unsigned long long data) - { - _write((uint64_t)data); - return *this; - } - inline wiArchive& operator<<(float data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(double data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT2& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT3& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT4& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT3X3& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT4X3& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMFLOAT4X4& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMUINT2& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMUINT3& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const XMUINT4& data) - { - _write(data); - return *this; - } - inline wiArchive& operator<<(const std::string& data) - { - (*this) << data.length(); - for (const auto& x : data) + // Write operations + inline Archive& operator<<(bool data) { - (*this) << x; + _write((uint32_t)(data ? 1 : 0)); + return *this; } - return *this; - } - template - inline wiArchive& operator<<(const wi::vector& data) - { - // Here we will use the << operator so that non-specified types will have compile error! - (*this) << data.size(); - for (const T& x : data) + inline Archive& operator<<(char data) { - (*this) << x; + _write((int8_t)data); + return *this; } - return *this; - } - - // Read operations - inline wiArchive& operator>>(bool& data) - { - uint32_t temp; - _read(temp); - data = (temp == 1); - return *this; - } - inline wiArchive& operator>>(char& data) - { - int8_t temp; - _read(temp); - data = (char)temp; - return *this; - } - inline wiArchive& operator>>(unsigned char& data) - { - uint8_t temp; - _read(temp); - data = (unsigned char)temp; - return *this; - } - inline wiArchive& operator>>(int& data) - { - int64_t temp; - _read(temp); - data = (int)temp; - return *this; - } - inline wiArchive& operator>>(unsigned int& data) - { - uint64_t temp; - _read(temp); - data = (unsigned int)temp; - return *this; - } - inline wiArchive& operator>>(long& data) - { - int64_t temp; - _read(temp); - data = (long)temp; - return *this; - } - inline wiArchive& operator>>(unsigned long& data) - { - uint64_t temp; - _read(temp); - data = (unsigned long)temp; - return *this; - } - inline wiArchive& operator>>(long long& data) - { - int64_t temp; - _read(temp); - data = (long long)temp; - return *this; - } - inline wiArchive& operator>>(unsigned long long& data) - { - uint64_t temp; - _read(temp); - data = (unsigned long long)temp; - return *this; - } - inline wiArchive& operator>>(float& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(double& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT2& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT3& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT4& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT3X3& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT4X3& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMFLOAT4X4& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMUINT2& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMUINT3& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(XMUINT4& data) - { - _read(data); - return *this; - } - inline wiArchive& operator>>(std::string& data) - { - uint64_t len; - (*this) >> len; - data.resize(len); - for (size_t i = 0; i < len; ++i) + inline Archive& operator<<(unsigned char data) { - (*this) >> data[i]; + _write((uint8_t)data); + return *this; } - if (!data.empty() && GetVersion() < 73) + inline Archive& operator<<(int data) { - // earlier versions of archive saved the strings with 0 terminator - data.pop_back(); + _write((int64_t)data); + return *this; } - return *this; - } - template - inline wiArchive& operator>>(wi::vector& data) - { - // Here we will use the >> operator so that non-specified types will have compile error! - size_t count; - (*this) >> count; - data.resize(count); - for (size_t i = 0; i < count; ++i) + inline Archive& operator<<(unsigned int data) { - (*this) >> data[i]; + _write((uint64_t)data); + return *this; } - return *this; - } - - - -private: - - // This should not be exposed to avoid misaligning data by mistake - // Any specific type serialization should be implemented by hand - // But these can be used as helper functions inside this class - - // Write data using memory operations - template - inline void _write(const T& data) - { - assert(!readMode); - assert(!DATA.empty()); - const size_t _right = pos + sizeof(data); - if (_right > DATA.size()) + inline Archive& operator<<(long data) { - DATA.resize(_right * 2); - data_ptr = DATA.data(); + _write((int64_t)data); + return *this; + } + inline Archive& operator<<(unsigned long data) + { + _write((uint64_t)data); + return *this; + } + inline Archive& operator<<(long long data) + { + _write((int64_t)data); + return *this; + } + inline Archive& operator<<(unsigned long long data) + { + _write((uint64_t)data); + return *this; + } + inline Archive& operator<<(float data) + { + _write(data); + return *this; + } + inline Archive& operator<<(double data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT2& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT3& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT4& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT3X3& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT4X3& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMFLOAT4X4& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMUINT2& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMUINT3& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const XMUINT4& data) + { + _write(data); + return *this; + } + inline Archive& operator<<(const std::string& data) + { + (*this) << data.length(); + for (const auto& x : data) + { + (*this) << x; + } + return *this; + } + template + inline Archive& operator<<(const wi::vector& data) + { + // Here we will use the << operator so that non-specified types will have compile error! + (*this) << data.size(); + for (const T& x : data) + { + (*this) << x; + } + return *this; } - *(T*)(DATA.data() + pos) = data; - pos = _right; - } - // Read data using memory operations - template - inline void _read(T& data) - { - assert(readMode); - assert(data_ptr != nullptr); - data = *(const T*)(data_ptr + pos); - pos += (size_t)(sizeof(data)); - } -}; + // Read operations + inline Archive& operator>>(bool& data) + { + uint32_t temp; + _read(temp); + data = (temp == 1); + return *this; + } + inline Archive& operator>>(char& data) + { + int8_t temp; + _read(temp); + data = (char)temp; + return *this; + } + inline Archive& operator>>(unsigned char& data) + { + uint8_t temp; + _read(temp); + data = (unsigned char)temp; + return *this; + } + inline Archive& operator>>(int& data) + { + int64_t temp; + _read(temp); + data = (int)temp; + return *this; + } + inline Archive& operator>>(unsigned int& data) + { + uint64_t temp; + _read(temp); + data = (unsigned int)temp; + return *this; + } + inline Archive& operator>>(long& data) + { + int64_t temp; + _read(temp); + data = (long)temp; + return *this; + } + inline Archive& operator>>(unsigned long& data) + { + uint64_t temp; + _read(temp); + data = (unsigned long)temp; + return *this; + } + inline Archive& operator>>(long long& data) + { + int64_t temp; + _read(temp); + data = (long long)temp; + return *this; + } + inline Archive& operator>>(unsigned long long& data) + { + uint64_t temp; + _read(temp); + data = (unsigned long long)temp; + return *this; + } + inline Archive& operator>>(float& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(double& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT2& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT3& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT4& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT3X3& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT4X3& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMFLOAT4X4& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMUINT2& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMUINT3& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(XMUINT4& data) + { + _read(data); + return *this; + } + inline Archive& operator>>(std::string& data) + { + uint64_t len; + (*this) >> len; + data.resize(len); + for (size_t i = 0; i < len; ++i) + { + (*this) >> data[i]; + } + if (!data.empty() && GetVersion() < 73) + { + // earlier versions of archive saved the strings with 0 terminator + data.pop_back(); + } + return *this; + } + template + inline Archive& operator>>(wi::vector& data) + { + // Here we will use the >> operator so that non-specified types will have compile error! + size_t count; + (*this) >> count; + data.resize(count); + for (size_t i = 0; i < count; ++i) + { + (*this) >> data[i]; + } + return *this; + } + + + private: + + // This should not be exposed to avoid misaligning data by mistake + // Any specific type serialization should be implemented by hand + // But these can be used as helper functions inside this class + + // Write data using memory operations + template + inline void _write(const T& data) + { + assert(!readMode); + assert(!DATA.empty()); + const size_t _right = pos + sizeof(data); + if (_right > DATA.size()) + { + DATA.resize(_right * 2); + data_ptr = DATA.data(); + } + *(T*)(DATA.data() + pos) = data; + pos = _right; + } + + // Read data using memory operations + template + inline void _read(T& data) + { + assert(readMode); + assert(data_ptr != nullptr); + data = *(const T*)(data_ptr + pos); + pos += (size_t)(sizeof(data)); + } + }; +} diff --git a/WickedEngine/wiStartupArguments.cpp b/WickedEngine/wiArguments.cpp similarity index 85% rename from WickedEngine/wiStartupArguments.cpp rename to WickedEngine/wiArguments.cpp index ca02bc1e8..5fa010a80 100644 --- a/WickedEngine/wiStartupArguments.cpp +++ b/WickedEngine/wiArguments.cpp @@ -1,11 +1,11 @@ -#include "wiStartupArguments.h" +#include "wiArguments.h" #include "wiHelper.h" #include "wiUnorderedSet.h" #include #include -namespace wiStartupArguments +namespace wi::arguments { wi::unordered_set params; @@ -13,7 +13,7 @@ namespace wiStartupArguments { std::wstring from = args; std::string to; - wiHelper::StringConvert(from, to); + wi::helper::StringConvert(from, to); std::istringstream iss(to); diff --git a/WickedEngine/wiStartupArguments.h b/WickedEngine/wiArguments.h similarity index 58% rename from WickedEngine/wiStartupArguments.h rename to WickedEngine/wiArguments.h index 1972127dd..b40af335b 100644 --- a/WickedEngine/wiStartupArguments.h +++ b/WickedEngine/wiArguments.h @@ -2,7 +2,8 @@ #include -namespace wiStartupArguments +// This can be used to parse and retrieve startup/command arguments of the application +namespace wi::arguments { void Parse(const wchar_t* args); void Parse(int argc, char *argv[]); diff --git a/WickedEngine/wiAudio.cpp b/WickedEngine/wiAudio.cpp index 73c27a379..f3dfc955c 100644 --- a/WickedEngine/wiAudio.cpp +++ b/WickedEngine/wiAudio.cpp @@ -1,5 +1,5 @@ #include "wiAudio.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiHelper.h" #include "wiTimer.h" #include "wiVector.h" @@ -23,7 +23,7 @@ #define fourccXWMA 'AMWX' #define fourccDPDS 'sdpd' -namespace wiAudio +namespace wi::audio { static const XAUDIO2FX_REVERB_I3DL2_PARAMETERS reverbPresets[] = { @@ -91,7 +91,7 @@ namespace wiAudio if (masteringVoice == nullptr) { - wiBackLog::post("Failed to create XAudio2 mastering voice!"); + wi::backlog::post("Failed to create XAudio2 mastering voice!"); return; } @@ -193,13 +193,13 @@ namespace wiAudio void Initialize() { - wiTimer timer; + wi::Timer timer; audio = std::make_shared(); if (audio->success) { - wiBackLog::post("wiAudio Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::audio Initialized [XAudio2] (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } } @@ -256,7 +256,7 @@ namespace wiAudio bool CreateSound(const std::string& filename, Sound* sound) { wi::vector filedata; - bool success = wiHelper::FileRead(filename, filedata); + bool success = wi::helper::FileRead(filename, filedata); if (!success) { return false; @@ -562,7 +562,7 @@ namespace wiAudio #define fourccFMT 0x20746d66 #define fourccDATA 0x61746164 -namespace wiAudio +namespace wi::audio { static const FAudioFXReverbI3DL2Parameters reverbPresets[] = { FAUDIOFX_I3DL2_PRESET_DEFAULT, @@ -695,13 +695,13 @@ namespace wiAudio }; void Initialize() { - wiTimer timer; + wi::Timer timer; audio = std::make_shared(); if (audio->success) { - wiBackLog::post("wiAudio Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::audio Initialized [FAudio] (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } } SoundInternal* to_internal(const Sound* param) @@ -765,7 +765,7 @@ namespace wiAudio bool CreateSound(const std::string& filename, Sound* sound) { wi::vector filedata; - bool success = wiHelper::FileRead(filename, filedata); + bool success = wi::helper::FileRead(filename, filedata); if (!success) { return false; @@ -1036,7 +1036,7 @@ namespace wiAudio #else -namespace wiAudio +namespace wi::audio { void Initialize() {} diff --git a/WickedEngine/wiAudio.h b/WickedEngine/wiAudio.h index 6c4f674bf..13015670d 100644 --- a/WickedEngine/wiAudio.h +++ b/WickedEngine/wiAudio.h @@ -9,10 +9,12 @@ #include #endif -namespace wiAudio +namespace wi::audio { void Initialize(); + // SUBMIX_TYPE specifies the playback channel of sound instances + // Do not change the order as this enum can be serialized! enum SUBMIX_TYPE { SUBMIX_TYPE_SOUNDEFFECT, @@ -24,11 +26,14 @@ namespace wiAudio ENUM_FORCE_UINT32 = 0xFFFFFFFF, // submix type can be serialized }; + // Sound is holding the sound data needed for playback, but it can't be played by itself. + // Use SoundInstance for playback the sound data struct Sound { std::shared_ptr internal_state; inline bool IsValid() const { return internal_state.get() != nullptr; } }; + // SoundInstance can be used to play back a Sound with specified effects struct SoundInstance { std::shared_ptr internal_state; @@ -66,6 +71,7 @@ namespace wiAudio void SetSubmixVolume(SUBMIX_TYPE type, float volume); float GetSubmixVolume(SUBMIX_TYPE type); + // SoundInstance3D can be attached to a SoundInstance for a 3D effect struct SoundInstance3D { XMFLOAT3 listenerPos = XMFLOAT3(0, 0, 0); @@ -78,8 +84,10 @@ namespace wiAudio XMFLOAT3 emitterVelocity = XMFLOAT3(0, 0, 0); float emitterRadius = 0; }; + // Call this every frame the listener or the sound instance 3D orientation changes void Update3D(SoundInstance* instance, const SoundInstance3D& instance3D); + // Reverb effects can be used for 3D sound instances globally enum REVERB_PRESET { REVERB_PRESET_DEFAULT, diff --git a/WickedEngine/wiAudio_BindLua.cpp b/WickedEngine/wiAudio_BindLua.cpp index 792e2b539..2ca18e94c 100644 --- a/WickedEngine/wiAudio_BindLua.cpp +++ b/WickedEngine/wiAudio_BindLua.cpp @@ -1,504 +1,509 @@ #include "wiAudio_BindLua.h" #include "wiAudio.h" -#include "Vector_BindLua.h" +#include "wiMath_BindLua.h" -const char wiAudio_BindLua::className[] = "Audio"; - -Luna::FunctionType wiAudio_BindLua::methods[] = { - lunamethod(wiAudio_BindLua, CreateSound), - lunamethod(wiAudio_BindLua, CreateSoundInstance), - lunamethod(wiAudio_BindLua, Play), - lunamethod(wiAudio_BindLua, Pause), - lunamethod(wiAudio_BindLua, Stop), - lunamethod(wiAudio_BindLua, GetVolume), - lunamethod(wiAudio_BindLua, SetVolume), - lunamethod(wiAudio_BindLua, ExitLoop), - lunamethod(wiAudio_BindLua, GetSubmixVolume), - lunamethod(wiAudio_BindLua, SetSubmixVolume), - lunamethod(wiAudio_BindLua, Update3D), - lunamethod(wiAudio_BindLua, SetReverb), - { NULL, NULL } -}; -Luna::PropertyType wiAudio_BindLua::properties[] = { - { NULL, NULL } -}; - -int wiAudio_BindLua::CreateSound(lua_State* L) +namespace wi::lua { - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + + const char Audio_BindLua::className[] = "Audio"; + + Luna::FunctionType Audio_BindLua::methods[] = { + lunamethod(Audio_BindLua, CreateSound), + lunamethod(Audio_BindLua, CreateSoundInstance), + lunamethod(Audio_BindLua, Play), + lunamethod(Audio_BindLua, Pause), + lunamethod(Audio_BindLua, Stop), + lunamethod(Audio_BindLua, GetVolume), + lunamethod(Audio_BindLua, SetVolume), + lunamethod(Audio_BindLua, ExitLoop), + lunamethod(Audio_BindLua, GetSubmixVolume), + lunamethod(Audio_BindLua, SetSubmixVolume), + lunamethod(Audio_BindLua, Update3D), + lunamethod(Audio_BindLua, SetReverb), + { NULL, NULL } + }; + Luna::PropertyType Audio_BindLua::properties[] = { + { NULL, NULL } + }; + + int Audio_BindLua::CreateSound(lua_State* L) { - wiSound_BindLua* sound = Luna::lightcheck(L, 2); - if (sound != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - bool result = wiAudio::CreateSound(wiLua::GetScriptPath() + wiLua::SGetString(L, 1), &sound->sound); - wiLua::SSetBool(L, result); + Sound_BindLua* sound = Luna::lightcheck(L, 2); + if (sound != nullptr) + { + bool result = wi::audio::CreateSound(wi::lua::GetScriptPath() + wi::lua::SGetString(L, 1), &sound->sound); + wi::lua::SSetBool(L, result); + } + else + { + wi::lua::SError(L, "CreateSound(string filename, Sound sound) second argument is not a Sound!"); + } } else - { - wiLua::SError(L, "CreateSound(string filename, Sound sound) second argument is not a Sound!"); - } + wi::lua::SError(L, "CreateSound(string filename, Sound sound) not enough arguments!"); + return 0; } - else - wiLua::SError(L, "CreateSound(string filename, Sound sound) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::CreateSoundInstance(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + int Audio_BindLua::CreateSoundInstance(lua_State* L) { - wiSound_BindLua* sound = Luna::lightcheck(L, 1); - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 2); - if (sound != nullptr && soundinstance != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - bool result = wiAudio::CreateSoundInstance(&sound->sound, &soundinstance->soundinstance); - wiLua::SSetBool(L, result); + Sound_BindLua* sound = Luna::lightcheck(L, 1); + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 2); + if (sound != nullptr && soundinstance != nullptr) + { + bool result = wi::audio::CreateSoundInstance(&sound->sound, &soundinstance->soundinstance); + wi::lua::SSetBool(L, result); + return 1; + } + else + { + wi::lua::SError(L, "CreateSoundInstance(Sound sound, SoundInstance soundinstance) argument types don't match!"); + } + } + else + wi::lua::SError(L, "CreateSoundInstance(Sound sound, SoundInstance soundinstance) not enough arguments!"); + return 0; + } + int Audio_BindLua::Play(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + if (soundinstance != nullptr) + { + wi::audio::Play(&soundinstance->soundinstance); + } + else + { + wi::lua::SError(L, "Play(SoundInstance soundinstance) argument is not a SoundInstance!"); + } + } + else + wi::lua::SError(L, "Play(SoundInstance soundinstance) not enough arguments!"); + return 0; + } + int Audio_BindLua::Pause(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + if (soundinstance != nullptr) + { + wi::audio::Pause(&soundinstance->soundinstance); + } + else + { + wi::lua::SError(L, "Pause(SoundInstance soundinstance) argument is not a SoundInstance!"); + } + } + else + wi::lua::SError(L, "Pause(SoundInstance soundinstance) not enough arguments!"); + return 0; + } + int Audio_BindLua::Stop(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + if (soundinstance != nullptr) + { + wi::audio::Stop(&soundinstance->soundinstance); + } + else + { + wi::lua::SError(L, "Stop(SoundInstance soundinstance) argument is not a SoundInstance!"); + } + } + else + wi::lua::SError(L, "Stop(SoundInstance soundinstance) not enough arguments!"); + return 0; + } + int Audio_BindLua::GetVolume(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + float volume = wi::audio::GetVolume(soundinstance == nullptr ? nullptr : &soundinstance->soundinstance); + wi::lua::SSetFloat(L, volume); return 1; } else - { - wiLua::SError(L, "CreateSoundInstance(Sound sound, SoundInstance soundinstance) argument types don't match!"); - } - } - else - wiLua::SError(L, "CreateSoundInstance(Sound sound, SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::Play(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - if (soundinstance != nullptr) - { - wiAudio::Play(&soundinstance->soundinstance); - } - else - { - wiLua::SError(L, "Play(SoundInstance soundinstance) argument is not a SoundInstance!"); - } - } - else - wiLua::SError(L, "Play(SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::Pause(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - if (soundinstance != nullptr) - { - wiAudio::Pause(&soundinstance->soundinstance); - } - else - { - wiLua::SError(L, "Pause(SoundInstance soundinstance) argument is not a SoundInstance!"); - } - } - else - wiLua::SError(L, "Pause(SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::Stop(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - if (soundinstance != nullptr) - { - wiAudio::Stop(&soundinstance->soundinstance); - } - else - { - wiLua::SError(L, "Stop(SoundInstance soundinstance) argument is not a SoundInstance!"); - } - } - else - wiLua::SError(L, "Stop(SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::GetVolume(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - float volume = wiAudio::GetVolume(soundinstance == nullptr ? nullptr : &soundinstance->soundinstance); - wiLua::SSetFloat(L, volume); - return 1; - } - else - wiLua::SError(L, "GetVolume(opt SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::SetVolume(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - float volume = wiLua::SGetFloat(L, 1); - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 2); - wiAudio::SetVolume(volume, soundinstance == nullptr ? nullptr : &soundinstance->soundinstance); + wi::lua::SError(L, "GetVolume(opt SoundInstance soundinstance) not enough arguments!"); return 0; } - else - wiLua::SError(L, "SetVolume(float volume, opt SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::ExitLoop(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + int Audio_BindLua::SetVolume(lua_State* L) { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - if (soundinstance != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - wiAudio::ExitLoop(&soundinstance->soundinstance); + float volume = wi::lua::SGetFloat(L, 1); + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 2); + wi::audio::SetVolume(volume, soundinstance == nullptr ? nullptr : &soundinstance->soundinstance); + return 0; } else - { - wiLua::SError(L, "ExitLoop(SoundInstance soundinstance) argument is not a SoundInstance!"); - } - } - else - wiLua::SError(L, "ExitLoop(SoundInstance soundinstance) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::GetSubmixVolume(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiAudio::SUBMIX_TYPE type = (wiAudio::SUBMIX_TYPE)wiLua::SGetInt(L, 1); - float volume = wiAudio::GetSubmixVolume(type); - wiLua::SSetFloat(L, volume); - return 1; - } - else - wiLua::SError(L, "GetSubmixVolume(int submixtype) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::SetSubmixVolume(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - wiAudio::SUBMIX_TYPE type = (wiAudio::SUBMIX_TYPE)wiLua::SGetInt(L, 1); - float volume = wiLua::SGetFloat(L, 2); - wiAudio::SetSubmixVolume(type, volume); + wi::lua::SError(L, "SetVolume(float volume, opt SoundInstance soundinstance) not enough arguments!"); return 0; } - else - wiLua::SError(L, "SetSubmixVolume(int submixtype, float volume) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::Update3D(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) + int Audio_BindLua::ExitLoop(lua_State* L) { - wiSoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); - wiSoundInstance3D_BindLua* soundinstance3D = Luna::lightcheck(L, 2); - if (soundinstance != nullptr && soundinstance3D != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - wiAudio::Update3D(&soundinstance->soundinstance, soundinstance3D->soundinstance3D); + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + if (soundinstance != nullptr) + { + wi::audio::ExitLoop(&soundinstance->soundinstance); + } + else + { + wi::lua::SError(L, "ExitLoop(SoundInstance soundinstance) argument is not a SoundInstance!"); + } } else + wi::lua::SError(L, "ExitLoop(SoundInstance soundinstance) not enough arguments!"); + return 0; + } + int Audio_BindLua::GetSubmixVolume(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - wiLua::SError(L, "Update3D(SoundInstance soundinstance, SoundInstance3D instance3D) argument types mismatch!"); + wi::audio::SUBMIX_TYPE type = (wi::audio::SUBMIX_TYPE)wi::lua::SGetInt(L, 1); + float volume = wi::audio::GetSubmixVolume(type); + wi::lua::SSetFloat(L, volume); + return 1; + } + else + wi::lua::SError(L, "GetSubmixVolume(int submixtype) not enough arguments!"); + return 0; + } + int Audio_BindLua::SetSubmixVolume(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + wi::audio::SUBMIX_TYPE type = (wi::audio::SUBMIX_TYPE)wi::lua::SGetInt(L, 1); + float volume = wi::lua::SGetFloat(L, 2); + wi::audio::SetSubmixVolume(type, volume); + return 0; + } + else + wi::lua::SError(L, "SetSubmixVolume(int submixtype, float volume) not enough arguments!"); + return 0; + } + int Audio_BindLua::Update3D(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + SoundInstance_BindLua* soundinstance = Luna::lightcheck(L, 1); + SoundInstance3D_BindLua* soundinstance3D = Luna::lightcheck(L, 2); + if (soundinstance != nullptr && soundinstance3D != nullptr) + { + wi::audio::Update3D(&soundinstance->soundinstance, soundinstance3D->soundinstance3D); + } + else + { + wi::lua::SError(L, "Update3D(SoundInstance soundinstance, SoundInstance3D instance3D) argument types mismatch!"); + } + } + else + wi::lua::SError(L, "Update3D(SoundInstance soundinstance, SoundInstance3D instance3D) not enough arguments!"); + return 0; + } + int Audio_BindLua::SetReverb(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::audio::SetReverb((wi::audio::REVERB_PRESET)wi::lua::SGetInt(L, 1)); + } + else + wi::lua::SError(L, "SetReverb(int reverbtype) not enough arguments!"); + return 0; + } + + void Audio_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + + wi::lua::RunText("audio = Audio()"); + + wi::lua::RunText("SUBMIX_TYPE_SOUNDEFFECT = 0"); + wi::lua::RunText("SUBMIX_TYPE_MUSIC = 1"); + wi::lua::RunText("SUBMIX_TYPE_USER0 = 2"); + wi::lua::RunText("SUBMIX_TYPE_USER1 = 3"); + + wi::lua::RunText("REVERB_PRESET_DEFAULT = 0"); + wi::lua::RunText("REVERB_PRESET_GENERIC = 1"); + wi::lua::RunText("REVERB_PRESET_FOREST = 2"); + wi::lua::RunText("REVERB_PRESET_PADDEDCELL = 3"); + wi::lua::RunText("REVERB_PRESET_ROOM = 4"); + wi::lua::RunText("REVERB_PRESET_BATHROOM = 5"); + wi::lua::RunText("REVERB_PRESET_LIVINGROOM = 6"); + wi::lua::RunText("REVERB_PRESET_STONEROOM = 7"); + wi::lua::RunText("REVERB_PRESET_AUDITORIUM = 8"); + wi::lua::RunText("REVERB_PRESET_CONCERTHALL = 9"); + wi::lua::RunText("REVERB_PRESET_CAVE = 10"); + wi::lua::RunText("REVERB_PRESET_ARENA = 11"); + wi::lua::RunText("REVERB_PRESET_HANGAR = 12"); + wi::lua::RunText("REVERB_PRESET_CARPETEDHALLWAY = 13"); + wi::lua::RunText("REVERB_PRESET_HALLWAY = 14"); + wi::lua::RunText("REVERB_PRESET_STONECORRIDOR = 15"); + wi::lua::RunText("REVERB_PRESET_ALLEY = 16"); + wi::lua::RunText("REVERB_PRESET_CITY = 17"); + wi::lua::RunText("REVERB_PRESET_MOUNTAINS = 18"); + wi::lua::RunText("REVERB_PRESET_QUARRY = 19"); + wi::lua::RunText("REVERB_PRESET_PLAIN = 20"); + wi::lua::RunText("REVERB_PRESET_PARKINGLOT = 21"); + wi::lua::RunText("REVERB_PRESET_SEWERPIPE = 22"); + wi::lua::RunText("REVERB_PRESET_UNDERWATER = 23"); + wi::lua::RunText("REVERB_PRESET_SMALLROOM = 24"); + wi::lua::RunText("REVERB_PRESET_MEDIUMROOM = 25"); + wi::lua::RunText("REVERB_PRESET_LARGEROOM = 26"); + wi::lua::RunText("REVERB_PRESET_MEDIUMHALL = 27"); + wi::lua::RunText("REVERB_PRESET_LARGEHALL = 28"); + wi::lua::RunText("REVERB_PRESET_PLATE = 29"); + + Sound_BindLua::Bind(); + SoundInstance_BindLua::Bind(); + SoundInstance3D_BindLua::Bind(); } } - else - wiLua::SError(L, "Update3D(SoundInstance soundinstance, SoundInstance3D instance3D) not enough arguments!"); - return 0; -} -int wiAudio_BindLua::SetReverb(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + + + + + const char Sound_BindLua::className[] = "Sound"; + + Luna::FunctionType Sound_BindLua::methods[] = { + { NULL, NULL } + }; + Luna::PropertyType Sound_BindLua::properties[] = { + { NULL, NULL } + }; + + void Sound_BindLua::Bind() { - wiAudio::SetReverb((wiAudio::REVERB_PRESET)wiLua::SGetInt(L, 1)); - } - else - wiLua::SError(L, "SetReverb(int reverbtype) not enough arguments!"); - return 0; -} - -void wiAudio_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - - wiLua::RunText("audio = Audio()"); - - wiLua::RunText("SUBMIX_TYPE_SOUNDEFFECT = 0"); - wiLua::RunText("SUBMIX_TYPE_MUSIC = 1"); - wiLua::RunText("SUBMIX_TYPE_USER0 = 2"); - wiLua::RunText("SUBMIX_TYPE_USER1 = 3"); - - wiLua::RunText("REVERB_PRESET_DEFAULT = 0"); - wiLua::RunText("REVERB_PRESET_GENERIC = 1"); - wiLua::RunText("REVERB_PRESET_FOREST = 2"); - wiLua::RunText("REVERB_PRESET_PADDEDCELL = 3"); - wiLua::RunText("REVERB_PRESET_ROOM = 4"); - wiLua::RunText("REVERB_PRESET_BATHROOM = 5"); - wiLua::RunText("REVERB_PRESET_LIVINGROOM = 6"); - wiLua::RunText("REVERB_PRESET_STONEROOM = 7"); - wiLua::RunText("REVERB_PRESET_AUDITORIUM = 8"); - wiLua::RunText("REVERB_PRESET_CONCERTHALL = 9"); - wiLua::RunText("REVERB_PRESET_CAVE = 10"); - wiLua::RunText("REVERB_PRESET_ARENA = 11"); - wiLua::RunText("REVERB_PRESET_HANGAR = 12"); - wiLua::RunText("REVERB_PRESET_CARPETEDHALLWAY = 13"); - wiLua::RunText("REVERB_PRESET_HALLWAY = 14"); - wiLua::RunText("REVERB_PRESET_STONECORRIDOR = 15"); - wiLua::RunText("REVERB_PRESET_ALLEY = 16"); - wiLua::RunText("REVERB_PRESET_CITY = 17"); - wiLua::RunText("REVERB_PRESET_MOUNTAINS = 18"); - wiLua::RunText("REVERB_PRESET_QUARRY = 19"); - wiLua::RunText("REVERB_PRESET_PLAIN = 20"); - wiLua::RunText("REVERB_PRESET_PARKINGLOT = 21"); - wiLua::RunText("REVERB_PRESET_SEWERPIPE = 22"); - wiLua::RunText("REVERB_PRESET_UNDERWATER = 23"); - wiLua::RunText("REVERB_PRESET_SMALLROOM = 24"); - wiLua::RunText("REVERB_PRESET_MEDIUMROOM = 25"); - wiLua::RunText("REVERB_PRESET_LARGEROOM = 26"); - wiLua::RunText("REVERB_PRESET_MEDIUMHALL = 27"); - wiLua::RunText("REVERB_PRESET_LARGEHALL = 28"); - wiLua::RunText("REVERB_PRESET_PLATE = 29"); - - wiSound_BindLua::Bind(); - wiSoundInstance_BindLua::Bind(); - wiSoundInstance3D_BindLua::Bind(); - } -} - - - - -const char wiSound_BindLua::className[] = "Sound"; - -Luna::FunctionType wiSound_BindLua::methods[] = { - { NULL, NULL } -}; -Luna::PropertyType wiSound_BindLua::properties[] = { - { NULL, NULL } -}; - -void wiSound_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} - - - - -const char wiSoundInstance_BindLua::className[] = "SoundInstance"; - -Luna::FunctionType wiSoundInstance_BindLua::methods[] = { - lunamethod(wiSoundInstance_BindLua, SetSubmixType), - { NULL, NULL } -}; -Luna::PropertyType wiSoundInstance_BindLua::properties[] = { - { NULL, NULL } -}; - -int wiSoundInstance_BindLua::SetSubmixType(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiAudio::SUBMIX_TYPE type = (wiAudio::SUBMIX_TYPE)wiLua::SGetInt(L, 1); - soundinstance.type = type; - } - else - wiLua::SError(L, "SetSubmixType(int submixtype) not enough arguments!"); - return 0; -} - -void wiSoundInstance_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} - - - - -const char wiSoundInstance3D_BindLua::className[] = "SoundInstance3D"; - -Luna::FunctionType wiSoundInstance3D_BindLua::methods[] = { - lunamethod(wiSoundInstance3D_BindLua, SetListenerPos), - lunamethod(wiSoundInstance3D_BindLua, SetListenerUp), - lunamethod(wiSoundInstance3D_BindLua, SetListenerFront), - lunamethod(wiSoundInstance3D_BindLua, SetListenerVelocity), - lunamethod(wiSoundInstance3D_BindLua, SetEmitterPos), - lunamethod(wiSoundInstance3D_BindLua, SetEmitterUp), - lunamethod(wiSoundInstance3D_BindLua, SetEmitterFront), - lunamethod(wiSoundInstance3D_BindLua, SetEmitterVelocity), - lunamethod(wiSoundInstance3D_BindLua, SetEmitterRadius), - { NULL, NULL } -}; -Luna::PropertyType wiSoundInstance3D_BindLua::properties[] = { - { NULL, NULL } -}; - -int wiSoundInstance3D_BindLua::SetListenerPos(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) + static bool initialized = false; + if (!initialized) { - XMStoreFloat3(&soundinstance3D.listenerPos, XMLoadFloat4(vec)); + initialized = true; + Luna::Register(wi::lua::GetLuaState()); } } - else - wiLua::SError(L, "SetListenerPos(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetListenerUp(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.listenerUp, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetListenerUp(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetListenerFront(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.listenerFront, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetListenerFront(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetListenerVelocity(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.listenerVelocity, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetListenerVelocity(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetEmitterPos(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.emitterPos, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetEmitterPos(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetEmitterUp(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.emitterUp, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetEmitterUp(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetEmitterFront(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.emitterFront, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetEmitterFront(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetEmitterVelocity(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - XMStoreFloat3(&soundinstance3D.emitterVelocity, XMLoadFloat4(vec)); - } - } - else - wiLua::SError(L, "SetEmitterVelocity(Vector value) not enough arguments!"); - return 0; -} -int wiSoundInstance3D_BindLua::SetEmitterRadius(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - soundinstance3D.emitterRadius = wiLua::SGetFloat(L, 1); - } - else - wiLua::SError(L, "SetEmitterVelocity(Vector value) not enough arguments!"); - return 0; -} -void wiSoundInstance3D_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) + + + const char SoundInstance_BindLua::className[] = "SoundInstance"; + + Luna::FunctionType SoundInstance_BindLua::methods[] = { + lunamethod(SoundInstance_BindLua, SetSubmixType), + { NULL, NULL } + }; + Luna::PropertyType SoundInstance_BindLua::properties[] = { + { NULL, NULL } + }; + + int SoundInstance_BindLua::SetSubmixType(lua_State* L) { - initialized = true; - Luna::Register(wiLua::GetLuaState()); + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::audio::SUBMIX_TYPE type = (wi::audio::SUBMIX_TYPE)wi::lua::SGetInt(L, 1); + soundinstance.type = type; + } + else + wi::lua::SError(L, "SetSubmixType(int submixtype) not enough arguments!"); + return 0; } + + void SoundInstance_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + + + + + const char SoundInstance3D_BindLua::className[] = "SoundInstance3D"; + + Luna::FunctionType SoundInstance3D_BindLua::methods[] = { + lunamethod(SoundInstance3D_BindLua, SetListenerPos), + lunamethod(SoundInstance3D_BindLua, SetListenerUp), + lunamethod(SoundInstance3D_BindLua, SetListenerFront), + lunamethod(SoundInstance3D_BindLua, SetListenerVelocity), + lunamethod(SoundInstance3D_BindLua, SetEmitterPos), + lunamethod(SoundInstance3D_BindLua, SetEmitterUp), + lunamethod(SoundInstance3D_BindLua, SetEmitterFront), + lunamethod(SoundInstance3D_BindLua, SetEmitterVelocity), + lunamethod(SoundInstance3D_BindLua, SetEmitterRadius), + { NULL, NULL } + }; + Luna::PropertyType SoundInstance3D_BindLua::properties[] = { + { NULL, NULL } + }; + + int SoundInstance3D_BindLua::SetListenerPos(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.listenerPos, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetListenerPos(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetListenerUp(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.listenerUp, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetListenerUp(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetListenerFront(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.listenerFront, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetListenerFront(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetListenerVelocity(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.listenerVelocity, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetListenerVelocity(Vector value) not enough arguments!"); + return 0; + } + + int SoundInstance3D_BindLua::SetEmitterPos(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.emitterPos, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetEmitterPos(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetEmitterUp(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.emitterUp, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetEmitterUp(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetEmitterFront(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.emitterFront, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetEmitterFront(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetEmitterVelocity(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&soundinstance3D.emitterVelocity, XMLoadFloat4(vec)); + } + } + else + wi::lua::SError(L, "SetEmitterVelocity(Vector value) not enough arguments!"); + return 0; + } + int SoundInstance3D_BindLua::SetEmitterRadius(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + soundinstance3D.emitterRadius = wi::lua::SGetFloat(L, 1); + } + else + wi::lua::SError(L, "SetEmitterVelocity(Vector value) not enough arguments!"); + return 0; + } + + void SoundInstance3D_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + } diff --git a/WickedEngine/wiAudio_BindLua.h b/WickedEngine/wiAudio_BindLua.h index 5694657fd..07c1c4017 100644 --- a/WickedEngine/wiAudio_BindLua.h +++ b/WickedEngine/wiAudio_BindLua.h @@ -3,87 +3,90 @@ #include "wiLuna.h" #include "wiAudio.h" -class wiAudio_BindLua +namespace wi::lua { -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + class Audio_BindLua + { + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiAudio_BindLua(lua_State* L) {} + Audio_BindLua(lua_State* L) {} - int CreateSound(lua_State* L); - int CreateSoundInstance(lua_State* L); - int Play(lua_State* L); - int Pause(lua_State* L); - int Stop(lua_State* L); - int GetVolume(lua_State* L); - int SetVolume(lua_State* L); - int ExitLoop(lua_State* L); + int CreateSound(lua_State* L); + int CreateSoundInstance(lua_State* L); + int Play(lua_State* L); + int Pause(lua_State* L); + int Stop(lua_State* L); + int GetVolume(lua_State* L); + int SetVolume(lua_State* L); + int ExitLoop(lua_State* L); - int GetSubmixVolume(lua_State* L); - int SetSubmixVolume(lua_State* L); + int GetSubmixVolume(lua_State* L); + int SetSubmixVolume(lua_State* L); - int Update3D(lua_State* L); - int SetReverb(lua_State* L); + int Update3D(lua_State* L); + int SetReverb(lua_State* L); - static void Bind(); -}; + static void Bind(); + }; -class wiSound_BindLua -{ -public: - wiAudio::Sound sound; + class Sound_BindLua + { + public: + wi::audio::Sound sound; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiSound_BindLua(lua_State* L) {} - wiSound_BindLua(const wiAudio::Sound& sound) :sound(sound) {} + Sound_BindLua(lua_State* L) {} + Sound_BindLua(const wi::audio::Sound& sound) :sound(sound) {} - static void Bind(); -}; + static void Bind(); + }; -class wiSoundInstance_BindLua -{ -public: - wiAudio::SoundInstance soundinstance; + class SoundInstance_BindLua + { + public: + wi::audio::SoundInstance soundinstance; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiSoundInstance_BindLua(lua_State* L) { } - ~wiSoundInstance_BindLua() { } + SoundInstance_BindLua(lua_State* L) { } + ~SoundInstance_BindLua() { } - int SetSubmixType(lua_State* L); + int SetSubmixType(lua_State* L); - static void Bind(); -}; + static void Bind(); + }; -class wiSoundInstance3D_BindLua -{ -public: - wiAudio::SoundInstance3D soundinstance3D; + class SoundInstance3D_BindLua + { + public: + wi::audio::SoundInstance3D soundinstance3D; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiSoundInstance3D_BindLua(lua_State* L) { } - wiSoundInstance3D_BindLua(const wiAudio::SoundInstance3D& soundinstance3D) : soundinstance3D(soundinstance3D) {} - ~wiSoundInstance3D_BindLua() { } + SoundInstance3D_BindLua(lua_State* L) { } + SoundInstance3D_BindLua(const wi::audio::SoundInstance3D& soundinstance3D) : soundinstance3D(soundinstance3D) {} + ~SoundInstance3D_BindLua() { } - int SetListenerPos(lua_State* L); - int SetListenerUp(lua_State* L); - int SetListenerFront(lua_State* L); - int SetListenerVelocity(lua_State* L); - int SetEmitterPos(lua_State* L); - int SetEmitterUp(lua_State* L); - int SetEmitterFront(lua_State* L); - int SetEmitterVelocity(lua_State* L); - int SetEmitterRadius(lua_State* L); + int SetListenerPos(lua_State* L); + int SetListenerUp(lua_State* L); + int SetListenerFront(lua_State* L); + int SetListenerVelocity(lua_State* L); + int SetEmitterPos(lua_State* L); + int SetEmitterUp(lua_State* L); + int SetEmitterFront(lua_State* L); + int SetEmitterVelocity(lua_State* L); + int SetEmitterRadius(lua_State* L); - static void Bind(); -}; + static void Bind(); + }; +} diff --git a/WickedEngine/wiBackLog_BindLua.cpp b/WickedEngine/wiBackLog_BindLua.cpp deleted file mode 100644 index eb2aead25..000000000 --- a/WickedEngine/wiBackLog_BindLua.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include "wiBackLog_BindLua.h" -#include "wiBackLog.h" -#include "wiLua.h" - -#include - -namespace wiBackLog_BindLua -{ - int backlog_clear(lua_State* L) - { - wiBackLog::clear(); - return 0; - } - int backlog_post(lua_State* L) - { - int argc = wiLua::SGetArgCount(L); - - std::string ss; - - for (int i = 1; i <= argc; i++) - { - ss += wiLua::SGetString(L, i); - } - - if (!ss.empty()) - { - wiBackLog::post(ss); - } - - return 0; - } - int backlog_fontsize(lua_State* L) - { - int argc = wiLua::SGetArgCount(L); - - if (argc > 0) - { - wiBackLog::setFontSize(wiLua::SGetInt(L, 1)); - } - else - wiLua::SError(L, "backlog_fontsize(int val) not enough arguments!"); - - return 0; - } - int backlog_isactive(lua_State* L) - { - wiLua::SSetBool(L, wiBackLog::isActive()); - return 1; - } - int backlog_fontrowspacing(lua_State* L) - { - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiBackLog::setFontRowspacing(wiLua::SGetFloat(L, 1)); - } - else - wiLua::SError(L, "backlog_fontrowspacing(int val) not enough arguments!"); - return 0; - } - int backlog_setlevel(lua_State* L) - { - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiBackLog::SetLogLevel((wiBackLog::LogLevel)wiLua::SGetInt(L, 1)); - } - else - wiLua::SError(L, "backlog_setlevel(int val) not enough arguments!"); - return 0; - } - int backlog_lock(lua_State* L) - { - wiBackLog::Lock(); - return 0; - } - int backlog_unlock(lua_State* L) - { - wiBackLog::Unlock(); - return 0; - } - int backlog_blocklua(lua_State* L) - { - wiBackLog::BlockLuaExecution(); - return 0; - } - int backlog_unblocklua(lua_State* L) - { - wiBackLog::UnblockLuaExecution(); - return 0; - } - - void Bind() - { - static bool initialized = false; - if (!initialized) - { - initialized = true; - wiLua::RegisterFunc("backlog_clear", backlog_clear); - wiLua::RegisterFunc("backlog_post", backlog_post); - wiLua::RegisterFunc("backlog_fontsize", backlog_fontsize); - wiLua::RegisterFunc("backlog_isactive", backlog_isactive); - wiLua::RegisterFunc("backlog_fontrowspacing", backlog_fontrowspacing); - wiLua::RegisterFunc("backlog_setlevel", backlog_setlevel); - wiLua::RegisterFunc("backlog_lock", backlog_lock); - wiLua::RegisterFunc("backlog_unlock", backlog_unlock); - wiLua::RegisterFunc("backlog_blocklua", backlog_blocklua); - wiLua::RegisterFunc("backlog_unblocklua", backlog_unblocklua); - } - } -} diff --git a/WickedEngine/wiBackLog.cpp b/WickedEngine/wiBacklog.cpp similarity index 76% rename from WickedEngine/wiBackLog.cpp rename to WickedEngine/wiBacklog.cpp index 815141001..96e3eb6d1 100644 --- a/WickedEngine/wiBackLog.cpp +++ b/WickedEngine/wiBacklog.cpp @@ -1,4 +1,4 @@ -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiMath.h" #include "wiResourceManager.h" #include "wiTextureHelper.h" @@ -17,9 +17,9 @@ #include #include -using namespace wiGraphics; +using namespace wi::graphics; -namespace wiBackLog +namespace wi::backlog { static bool enabled = false; static std::deque stream; @@ -30,8 +30,8 @@ namespace wiBackLog static float scroll = 0; static std::string inputArea; static int historyPos = 0; - static wiSpriteFont font; - static wiSpinLock logLock; + static wi::SpriteFont font; + static wi::SpinLock logLock; static Texture backgroundTex; static bool refitscroll = false; @@ -41,9 +41,9 @@ namespace wiBackLog static void write_logfile() { - std::string filename = wiHelper::GetTempDirectoryPath() + "wiBackLog.txt"; + std::string filename = wi::helper::GetTempDirectoryPath() + "wiBacklog.txt"; std::string text = getText(); // will lock mutex - wiHelper::FileWrite(filename, (const uint8_t*)text.c_str(), text.length()); + wi::helper::FileWrite(filename, (const uint8_t*)text.c_str(), text.length()); } // The logwriter object will automatically write out the backlog to the temp folder when it's destroyed @@ -64,34 +64,34 @@ namespace wiBackLog { scroll += dir; } - void Update(const wiCanvas& canvas, float dt) + void Update(const wi::Canvas& canvas, float dt) { if (!locked) { - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_HOME)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_HOME)) { Toggle(); } if (isActive()) { - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_UP)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_UP)) { historyPrev(); } - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_DOWN)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_DOWN)) { historyNext(); } - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_ENTER)) + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_ENTER)) { acceptInput(); } - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_PAGEUP)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_PAGEUP)) { Scroll(1000.0f * dt); } - if (wiInput::Down(wiInput::KEYBOARD_BUTTON_PAGEDOWN)) + if (wi::input::Down(wi::input::KEYBOARD_BUTTON_PAGEDOWN)) { Scroll(-1000.0f * dt); } @@ -106,33 +106,33 @@ namespace wiBackLog { pos -= speed * dt; } - pos = wiMath::Clamp(pos, -canvas.GetLogicalHeight(), 0); + pos = wi::math::Clamp(pos, -canvas.GetLogicalHeight(), 0); } - void Draw(const wiCanvas& canvas, CommandList cmd) + void Draw(const wi::Canvas& canvas, CommandList cmd) { if (pos > -canvas.GetLogicalHeight()) { if (!backgroundTex.IsValid()) { const uint8_t colorData[] = { 0, 0, 43, 200, 43, 31, 141, 223 }; - wiTextureHelper::CreateTexture(backgroundTex, colorData, 1, 2); + wi::texturehelper::CreateTexture(backgroundTex, colorData, 1, 2); } - wiImageParams fx = wiImageParams((float)canvas.GetLogicalWidth(), (float)canvas.GetLogicalHeight()); + wi::image::Params fx = wi::image::Params((float)canvas.GetLogicalWidth(), (float)canvas.GetLogicalHeight()); fx.pos = XMFLOAT3(0, pos, 0); - fx.opacity = wiMath::Lerp(1, 0, -pos / canvas.GetLogicalHeight()); - wiImage::Draw(&backgroundTex, fx, cmd); + fx.opacity = wi::math::Lerp(1, 0, -pos / canvas.GetLogicalHeight()); + wi::image::Draw(&backgroundTex, fx, cmd); - wiFontParams params = wiFontParams(10, canvas.GetLogicalHeight() - 10, WIFONTSIZE_DEFAULT, WIFALIGN_LEFT, WIFALIGN_BOTTOM); + wi::font::Params params = wi::font::Params(10, canvas.GetLogicalHeight() - 10, wi::font::WIFONTSIZE_DEFAULT, wi::font::WIFALIGN_LEFT, wi::font::WIFALIGN_BOTTOM); params.h_wrap = canvas.GetLogicalWidth() - params.posX; - params.v_align = WIFALIGN_BOTTOM; - wiFont::Draw(inputArea, params, cmd); + params.v_align = wi::font::WIFALIGN_BOTTOM; + wi::font::Draw(inputArea, params, cmd); font.SetText(getText()); if (refitscroll) { refitscroll = false; - float textheight = font.textHeight(); + float textheight = font.TextHeight(); float limit = canvas.GetLogicalHeight() * 0.9f; if (scroll + textheight > limit) { @@ -147,13 +147,13 @@ namespace wiBackLog rect.right = (int32_t)canvas.GetPhysicalWidth(); rect.top = 0; rect.bottom = int32_t(canvas.GetPhysicalHeight() * 0.9f); - wiGraphics::GetDevice()->BindScissorRects(1, &rect, cmd); + wi::graphics::GetDevice()->BindScissorRects(1, &rect, cmd); font.Draw(cmd); rect.left = -std::numeric_limits::max(); rect.right = std::numeric_limits::max(); rect.top = -std::numeric_limits::max(); rect.bottom = std::numeric_limits::max(); - wiGraphics::GetDevice()->BindScissorRects(1, &rect, cmd); + wi::graphics::GetDevice()->BindScissorRects(1, &rect, cmd); } } @@ -250,11 +250,11 @@ namespace wiBackLog } if (!blockLuaExec) { - wiLua::RunText(inputArea); + wi::lua::RunText(inputArea); } else { - wiBackLog::post("Lua execution is disabled", LogLevel::Error); + post("Lua execution is disabled", LogLevel::Error); } inputArea.clear(); } diff --git a/WickedEngine/wiBackLog.h b/WickedEngine/wiBacklog.h similarity index 78% rename from WickedEngine/wiBackLog.h rename to WickedEngine/wiBacklog.h index a2c7a7f61..12280935f 100644 --- a/WickedEngine/wiBackLog.h +++ b/WickedEngine/wiBacklog.h @@ -5,7 +5,7 @@ #include -namespace wiBackLog +namespace wi::backlog { // Do not modify the order, as this is exposed to LUA scripts as int! enum class LogLevel @@ -18,8 +18,8 @@ namespace wiBackLog void Toggle(); void Scroll(int direction); - void Update(const wiCanvas& canvas, float dt = 1.0f / 60.0f); - void Draw(const wiCanvas& canvas, wiGraphics::CommandList cmd); + void Update(const wi::Canvas& canvas, float dt = 1.0f / 60.0f); + void Draw(const wi::Canvas& canvas, wi::graphics::CommandList cmd); std::string getText(); void clear(); @@ -33,7 +33,7 @@ namespace wiBackLog bool isActive(); - void setBackground(wiGraphics::Texture* texture); + void setBackground(wi::graphics::Texture* texture); void setFontSize(int value); void setFontRowspacing(float value); diff --git a/WickedEngine/wiBacklog_BindLua.cpp b/WickedEngine/wiBacklog_BindLua.cpp new file mode 100644 index 000000000..e23febb2d --- /dev/null +++ b/WickedEngine/wiBacklog_BindLua.cpp @@ -0,0 +1,111 @@ +#include "wiBacklog_BindLua.h" +#include "wiBacklog.h" +#include "wiLua.h" + +#include + +namespace wi::lua::backlog +{ + int backlog_clear(lua_State* L) + { + wi::backlog::clear(); + return 0; + } + int backlog_post(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + + std::string ss; + + for (int i = 1; i <= argc; i++) + { + ss += wi::lua::SGetString(L, i); + } + + if (!ss.empty()) + { + wi::backlog::post(ss); + } + + return 0; + } + int backlog_fontsize(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + + if (argc > 0) + { + wi::backlog::setFontSize(wi::lua::SGetInt(L, 1)); + } + else + wi::lua::SError(L, "backlog_fontsize(int val) not enough arguments!"); + + return 0; + } + int backlog_isactive(lua_State* L) + { + wi::lua::SSetBool(L, wi::backlog::isActive()); + return 1; + } + int backlog_fontrowspacing(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::backlog::setFontRowspacing(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "backlog_fontrowspacing(int val) not enough arguments!"); + return 0; + } + int backlog_setlevel(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::backlog::SetLogLevel((wi::backlog::LogLevel)wi::lua::SGetInt(L, 1)); + } + else + wi::lua::SError(L, "backlog_setlevel(int val) not enough arguments!"); + return 0; + } + int backlog_lock(lua_State* L) + { + wi::backlog::Lock(); + return 0; + } + int backlog_unlock(lua_State* L) + { + wi::backlog::Unlock(); + return 0; + } + int backlog_blocklua(lua_State* L) + { + wi::backlog::BlockLuaExecution(); + return 0; + } + int backlog_unblocklua(lua_State* L) + { + wi::backlog::UnblockLuaExecution(); + return 0; + } + + void Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + wi::lua::RegisterFunc("backlog_clear", backlog_clear); + wi::lua::RegisterFunc("backlog_post", backlog_post); + wi::lua::RegisterFunc("backlog_fontsize", backlog_fontsize); + wi::lua::RegisterFunc("backlog_isactive", backlog_isactive); + wi::lua::RegisterFunc("backlog_fontrowspacing", backlog_fontrowspacing); + wi::lua::RegisterFunc("backlog_setlevel", backlog_setlevel); + wi::lua::RegisterFunc("backlog_lock", backlog_lock); + wi::lua::RegisterFunc("backlog_unlock", backlog_unlock); + wi::lua::RegisterFunc("backlog_blocklua", backlog_blocklua); + wi::lua::RegisterFunc("backlog_unblocklua", backlog_unblocklua); + } + } +} diff --git a/WickedEngine/wiBackLog_BindLua.h b/WickedEngine/wiBacklog_BindLua.h similarity index 54% rename from WickedEngine/wiBackLog_BindLua.h rename to WickedEngine/wiBacklog_BindLua.h index 151f8110a..9f4f629c4 100644 --- a/WickedEngine/wiBackLog_BindLua.h +++ b/WickedEngine/wiBacklog_BindLua.h @@ -1,6 +1,6 @@ #pragma once -namespace wiBackLog_BindLua +namespace wi::lua::backlog { void Bind(); }; diff --git a/WickedEngine/wiCanvas.h b/WickedEngine/wiCanvas.h index 4068d6397..507463ab7 100644 --- a/WickedEngine/wiCanvas.h +++ b/WickedEngine/wiCanvas.h @@ -3,55 +3,59 @@ #include "wiPlatform.h" #include "wiMath.h" -// The canvas specifies a DPI-aware drawing area -struct wiCanvas +namespace wi { - uint32_t width = 0; - uint32_t height = 0; - float dpi = 96; + // The canvas specifies a DPI-aware drawing area + struct Canvas + { + uint32_t width = 0; + uint32_t height = 0; + float dpi = 96; - // Create a canvas from physical measurements - inline void init(uint32_t width, uint32_t height, float dpi = 96) - { - this->width = width; - this->height = height; - this->dpi = dpi; - } - // Copy canvas from other canvas - inline void init(const wiCanvas& other) - { - *this = other; - } - // Create the canvas straight from window handle - inline void init(wiPlatform::window_type window) - { - wiPlatform::WindowProperties windowprops; - wiPlatform::GetWindowProperties(window, &windowprops); - init((uint32_t)windowprops.width, (uint32_t)windowprops.height, windowprops.dpi); - } + // Create a canvas from physical measurements + inline void init(uint32_t width, uint32_t height, float dpi = 96) + { + this->width = width; + this->height = height; + this->dpi = dpi; + } + // Copy canvas from other canvas + inline void init(const Canvas& other) + { + *this = other; + } + // Create the canvas straight from window handle + inline void init(platform::window_type window) + { + platform::WindowProperties windowprops; + platform::GetWindowProperties(window, &windowprops); + init((uint32_t)windowprops.width, (uint32_t)windowprops.height, windowprops.dpi); + } - // How many pixels there are per inch - inline float GetDPI() const { return dpi; } - // The scaling factor between logical and physical coordinates - inline float GetDPIScaling() const { return GetDPI() / 96.f; } - // Returns native resolution width in pixels: - // Use this for texture allocations - // Use this for scissor, viewport - inline uint32_t GetPhysicalWidth() const { return width; } - // Returns native resolution height in pixels: - // Use this for texture allocations - // Use this for scissor, viewport - inline uint32_t GetPhysicalHeight() const { return height; } - // Returns the width with DPI scaling applied (subpixel size): - // Use this for logic and positioning drawable elements - inline float GetLogicalWidth() const { return GetPhysicalWidth() / GetDPIScaling(); } - // Returns the height with DPI scaling applied (subpixel size): - // Use this for logic and positioning drawable elements - inline float GetLogicalHeight() const { return GetPhysicalHeight() / GetDPIScaling(); } - // Returns projection matrix that maps logical to physical space - // Use this to render to a graphics viewport - inline XMMATRIX GetProjection() const - { - return XMMatrixOrthographicOffCenterLH(0, (float)GetLogicalWidth(), (float)GetLogicalHeight(), 0, -1, 1); - } -}; + // How many pixels there are per inch + inline float GetDPI() const { return dpi; } + // The scaling factor between logical and physical coordinates + inline float GetDPIScaling() const { return GetDPI() / 96.f; } + // Returns native resolution width in pixels: + // Use this for texture allocations + // Use this for scissor, viewport + inline uint32_t GetPhysicalWidth() const { return width; } + // Returns native resolution height in pixels: + // Use this for texture allocations + // Use this for scissor, viewport + inline uint32_t GetPhysicalHeight() const { return height; } + // Returns the width with DPI scaling applied (subpixel size): + // Use this for logic and positioning drawable elements + inline float GetLogicalWidth() const { return GetPhysicalWidth() / GetDPIScaling(); } + // Returns the height with DPI scaling applied (subpixel size): + // Use this for logic and positioning drawable elements + inline float GetLogicalHeight() const { return GetPhysicalHeight() / GetDPIScaling(); } + // Returns projection matrix that maps logical to physical space + // Use this to render to a graphics viewport + inline XMMATRIX GetProjection() const + { + return XMMatrixOrthographicOffCenterLH(0, (float)GetLogicalWidth(), (float)GetLogicalHeight(), 0, -1, 1); + } + }; + +} diff --git a/WickedEngine/wiColor.h b/WickedEngine/wiColor.h index 553fd3fe5..614155048 100644 --- a/WickedEngine/wiColor.h +++ b/WickedEngine/wiColor.h @@ -2,70 +2,72 @@ #include "CommonInclude.h" #include "wiMath.h" -struct wiColor +namespace wi { - uint32_t rgba = 0; - - constexpr wiColor(uint32_t rgba) :rgba(rgba) {} - constexpr wiColor(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255) : rgba((r << 0) | (g << 8) | (b << 16) | (a << 24)) {} - - constexpr uint8_t getR() const { return (rgba >> 0) & 0xFF; } - constexpr uint8_t getG() const { return (rgba >> 8) & 0xFF; } - constexpr uint8_t getB() const { return (rgba >> 16) & 0xFF; } - constexpr uint8_t getA() const { return (rgba >> 24) & 0xFF; } - - constexpr void setR(uint8_t value) { *this = wiColor(value, getG(), getB(), getA()); } - constexpr void setG(uint8_t value) { *this = wiColor(getR(), value, getB(), getA()); } - constexpr void setB(uint8_t value) { *this = wiColor(getR(), getG(), value, getA()); } - constexpr void setA(uint8_t value) { *this = wiColor(getR(), getG(), getB(), value); } - - constexpr XMFLOAT3 toFloat3() const + struct Color { - return XMFLOAT3( - ((rgba >> 0) & 0xFF) / 255.0f, - ((rgba >> 8) & 0xFF) / 255.0f, - ((rgba >> 16) & 0xFF) / 255.0f - ); - } - constexpr XMFLOAT4 toFloat4() const - { - return XMFLOAT4( - ((rgba >> 0) & 0xFF) / 255.0f, - ((rgba >> 8) & 0xFF) / 255.0f, - ((rgba >> 16) & 0xFF) / 255.0f, - ((rgba >> 24) & 0xFF) / 255.0f - ); - } - constexpr operator XMFLOAT3() const { return toFloat3(); } - constexpr operator XMFLOAT4() const { return toFloat4(); } - constexpr operator uint32_t() const { return rgba; } + uint32_t rgba = 0; - static constexpr wiColor fromFloat4(const XMFLOAT4& value) - { - return wiColor((uint8_t)(value.x * 255), (uint8_t)(value.y * 255), (uint8_t)(value.z * 255), (uint8_t)(value.w * 255)); - } - static constexpr wiColor fromFloat3(const XMFLOAT3& value) - { - return wiColor((uint8_t)(value.x * 255), (uint8_t)(value.y * 255), (uint8_t)(value.z * 255)); - } + constexpr Color(uint32_t rgba) :rgba(rgba) {} + constexpr Color(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255) : rgba((r << 0) | (g << 8) | (b << 16) | (a << 24)) {} - static constexpr wiColor lerp(wiColor a, wiColor b, float i) - { - return fromFloat4(wiMath::Lerp(a.toFloat4(), b.toFloat4(), i)); - } + constexpr uint8_t getR() const { return (rgba >> 0) & 0xFF; } + constexpr uint8_t getG() const { return (rgba >> 8) & 0xFF; } + constexpr uint8_t getB() const { return (rgba >> 16) & 0xFF; } + constexpr uint8_t getA() const { return (rgba >> 24) & 0xFF; } - static constexpr wiColor Red() { return wiColor(255, 0, 0, 255); } - static constexpr wiColor Green() { return wiColor(0, 255, 0, 255); } - static constexpr wiColor Blue() { return wiColor(0, 0, 255, 255); } - static constexpr wiColor Black() { return wiColor(0, 0, 0, 255); } - static constexpr wiColor White() { return wiColor(255, 255, 255, 255); } - static constexpr wiColor Yellow() { return wiColor(255, 255, 0, 255); } - static constexpr wiColor Purple() { return wiColor(255, 0, 255, 255); } - static constexpr wiColor Cyan() { return wiColor(0, 255, 255, 255); } - static constexpr wiColor Transparent() { return wiColor(0, 0, 0, 0); } - static constexpr wiColor Gray() { return wiColor(127, 127, 127, 255); } - static constexpr wiColor Ghost() { return wiColor(127, 127, 127, 127); } - static constexpr wiColor Booger() { return wiColor(127, 127, 127, 200); } -}; + constexpr void setR(uint8_t value) { *this = Color(value, getG(), getB(), getA()); } + constexpr void setG(uint8_t value) { *this = Color(getR(), value, getB(), getA()); } + constexpr void setB(uint8_t value) { *this = Color(getR(), getG(), value, getA()); } + constexpr void setA(uint8_t value) { *this = Color(getR(), getG(), getB(), value); } + constexpr XMFLOAT3 toFloat3() const + { + return XMFLOAT3( + ((rgba >> 0) & 0xFF) / 255.0f, + ((rgba >> 8) & 0xFF) / 255.0f, + ((rgba >> 16) & 0xFF) / 255.0f + ); + } + constexpr XMFLOAT4 toFloat4() const + { + return XMFLOAT4( + ((rgba >> 0) & 0xFF) / 255.0f, + ((rgba >> 8) & 0xFF) / 255.0f, + ((rgba >> 16) & 0xFF) / 255.0f, + ((rgba >> 24) & 0xFF) / 255.0f + ); + } + constexpr operator XMFLOAT3() const { return toFloat3(); } + constexpr operator XMFLOAT4() const { return toFloat4(); } + constexpr operator uint32_t() const { return rgba; } + + static constexpr Color fromFloat4(const XMFLOAT4& value) + { + return Color((uint8_t)(value.x * 255), (uint8_t)(value.y * 255), (uint8_t)(value.z * 255), (uint8_t)(value.w * 255)); + } + static constexpr Color fromFloat3(const XMFLOAT3& value) + { + return Color((uint8_t)(value.x * 255), (uint8_t)(value.y * 255), (uint8_t)(value.z * 255)); + } + + static constexpr Color lerp(Color a, Color b, float i) + { + return fromFloat4(wi::math::Lerp(a.toFloat4(), b.toFloat4(), i)); + } + + static constexpr Color Red() { return Color(255, 0, 0, 255); } + static constexpr Color Green() { return Color(0, 255, 0, 255); } + static constexpr Color Blue() { return Color(0, 0, 255, 255); } + static constexpr Color Black() { return Color(0, 0, 0, 255); } + static constexpr Color White() { return Color(255, 255, 255, 255); } + static constexpr Color Yellow() { return Color(255, 255, 0, 255); } + static constexpr Color Purple() { return Color(255, 0, 255, 255); } + static constexpr Color Cyan() { return Color(0, 255, 255, 255); } + static constexpr Color Transparent() { return Color(0, 0, 0, 0); } + static constexpr Color Gray() { return Color(127, 127, 127, 255); } + static constexpr Color Ghost() { return Color(127, 127, 127, 127); } + static constexpr Color Booger() { return Color(127, 127, 127, 200); } + }; +} diff --git a/WickedEngine/wiECS.h b/WickedEngine/wiECS.h index 2ab750cec..5979b657c 100644 --- a/WickedEngine/wiECS.h +++ b/WickedEngine/wiECS.h @@ -10,8 +10,13 @@ #include #include -namespace wiECS +// Entity-Component System +namespace wi::ecs { + // The Entity is a global unique persistent identifier within the entity-component system + // It can be stored and used for the duration of the application + // The entity can be a different value on a different run of the application, if it was serialized + // It must be only serialized with the SerializeEntity() function. It will ensure that entities still match with their components correctly after serialization using Entity = uint32_t; static const Entity INVALID_ENTITY = 0; // Runtime can create a new entity with this @@ -23,17 +28,17 @@ namespace wiECS struct EntitySerializer { - wiJobSystem::context ctx; // allow components to spawn serialization subtasks + wi::jobsystem::context ctx; // allow components to spawn serialization subtasks wi::unordered_map remap; bool allow_remap = true; ~EntitySerializer() { - wiJobSystem::Wait(ctx); // automatically wait for all subtasks after serialization + wi::jobsystem::Wait(ctx); // automatically wait for all subtasks after serialization } }; // This is the safe way to serialize an entity - inline void SerializeEntity(wiArchive& archive, Entity& entity, EntitySerializer& seri) + inline void SerializeEntity(wi::Archive& archive, Entity& entity, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -65,6 +70,7 @@ namespace wiECS } } + // The ComponentManager is a container that stores components and matches them with entities template class ComponentManager { @@ -117,7 +123,7 @@ namespace wiECS } // Read/Write everything to an archive depending on the archive state - inline void Serialize(wiArchive& archive, EntitySerializer& seri) + inline void Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { diff --git a/WickedEngine/wiEmittedParticle.cpp b/WickedEngine/wiEmittedParticle.cpp index bb90d3d86..9bfb88f54 100644 --- a/WickedEngine/wiEmittedParticle.cpp +++ b/WickedEngine/wiEmittedParticle.cpp @@ -2,1005 +2,1006 @@ #include "wiScene.h" #include "wiRenderer.h" #include "wiResourceManager.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiRandom.h" #include "wiArchive.h" #include "wiTextureHelper.h" #include "wiGPUSortLib.h" #include "wiProfiler.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiTimer.h" #include "wiVector.h" #include -using namespace wiGraphics; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::enums; -namespace wiScene +namespace wi { + static Shader vertexShader; + static Shader meshShader; + static Shader pixelShader[EmittedParticleSystem::PARTICLESHADERTYPE_COUNT]; + static Shader kickoffUpdateCS; + static Shader finishUpdateCS; + static Shader emitCS; + static Shader emitCS_VOLUME; + static Shader emitCS_FROMMESH; + static Shader sphpartitionCS; + static Shader sphpartitionoffsetsCS; + static Shader sphpartitionoffsetsresetCS; + static Shader sphdensityCS; + static Shader sphforceCS; + static Shader simulateCS; + static Shader simulateCS_SORTING; + static Shader simulateCS_DEPTHCOLLISIONS; + static Shader simulateCS_SORTING_DEPTHCOLLISIONS; -static Shader vertexShader; -static Shader meshShader; -static Shader pixelShader[wiEmittedParticle::PARTICLESHADERTYPE_COUNT]; -static Shader kickoffUpdateCS; -static Shader finishUpdateCS; -static Shader emitCS; -static Shader emitCS_VOLUME; -static Shader emitCS_FROMMESH; -static Shader sphpartitionCS; -static Shader sphpartitionoffsetsCS; -static Shader sphpartitionoffsetsresetCS; -static Shader sphdensityCS; -static Shader sphforceCS; -static Shader simulateCS; -static Shader simulateCS_SORTING; -static Shader simulateCS_DEPTHCOLLISIONS; -static Shader simulateCS_SORTING_DEPTHCOLLISIONS; + static BlendState blendStates[BLENDMODE_COUNT]; + static RasterizerState rasterizerState; + static RasterizerState wireFrameRS; + static DepthStencilState depthStencilState; + static PipelineState PSO[BLENDMODE_COUNT][EmittedParticleSystem::PARTICLESHADERTYPE_COUNT]; + static PipelineState PSO_wire; -static BlendState blendStates[BLENDMODE_COUNT]; -static RasterizerState rasterizerState; -static RasterizerState wireFrameRS; -static DepthStencilState depthStencilState; -static PipelineState PSO[BLENDMODE_COUNT][wiEmittedParticle::PARTICLESHADERTYPE_COUNT]; -static PipelineState PSO_wire; - -static bool ALLOW_MESH_SHADER = false; + static bool ALLOW_MESH_SHADER = false; -void wiEmittedParticle::SetMaxParticleCount(uint32_t value) -{ - MAX_PARTICLES = value; - counterBuffer = {}; // will be recreated -} - -void wiEmittedParticle::CreateSelfBuffers() -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - if (particleBuffer.desc.size < MAX_PARTICLES * sizeof(Particle)) + void EmittedParticleSystem::SetMaxParticleCount(uint32_t value) { - GPUBufferDesc bd; - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - - // Particle buffer: - bd.stride = sizeof(Particle); - bd.size = bd.stride * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &particleBuffer); - device->SetName(&particleBuffer, "particleBuffer"); - - // Alive index lists (double buffered): - bd.stride = sizeof(uint32_t); - bd.size = bd.stride * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &aliveList[0]); - device->SetName(&aliveList[0], "aliveList[0]"); - device->CreateBuffer(&bd, nullptr, &aliveList[1]); - device->SetName(&aliveList[1], "aliveList[1]"); - device->CreateBuffer(&bd, nullptr, &culledIndirectionBuffer); - device->SetName(&culledIndirectionBuffer, "culledIndirectionBuffer"); - device->CreateBuffer(&bd, nullptr, &culledIndirectionBuffer2); - device->SetName(&culledIndirectionBuffer2, "culledIndirectionBuffer2"); - - // Dead index list: - wi::vector indices(MAX_PARTICLES); - for (uint32_t i = 0; i < MAX_PARTICLES; ++i) - { - indices[i] = i; - } - device->CreateBuffer(&bd, indices.data(), &deadList); - device->SetName(&deadList, "deadList"); - - - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) - { - bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; - } - bd.stride = sizeof(MeshComponent::Vertex_POS); - bd.size = bd.stride * 4 * MAX_PARTICLES; - wi::vector positionData(4 * MAX_PARTICLES); - std::fill(positionData.begin(), positionData.end(), MeshComponent::Vertex_POS()); - device->CreateBuffer(&bd, positionData.data(), &vertexBuffer_POS); - device->SetName(&vertexBuffer_POS, "vertexBuffer_POS"); - - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - bd.stride = sizeof(MeshComponent::Vertex_TEX); - bd.size = bd.stride * 4 * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX); - device->SetName(&vertexBuffer_TEX, "vertexBuffer_TEX"); - - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - bd.stride = sizeof(MeshComponent::Vertex_TEX); - bd.size = bd.stride * 4 * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX2); - device->SetName(&vertexBuffer_TEX2, "vertexBuffer_TEX2"); - - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - bd.stride = sizeof(MeshComponent::Vertex_COL); - bd.size = bd.stride * 4 * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &vertexBuffer_COL); - device->SetName(&vertexBuffer_COL, "vertexBuffer_COL"); - - bd.bind_flags = BindFlag::SHADER_RESOURCE; - bd.misc_flags = ResourceMiscFlag::NONE; - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) - { - bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; - } - bd.format = Format::R32_UINT; - bd.stride = sizeof(uint); - bd.size = bd.stride * 6 * MAX_PARTICLES; - wi::vector primitiveData(6 * MAX_PARTICLES); - for (uint particleID = 0; particleID < MAX_PARTICLES; ++particleID) - { - uint v0 = particleID * 4; - uint i0 = particleID * 6; - primitiveData[i0 + 0] = v0 + 0; - primitiveData[i0 + 1] = v0 + 1; - primitiveData[i0 + 2] = v0 + 2; - primitiveData[i0 + 3] = v0 + 2; - primitiveData[i0 + 4] = v0 + 1; - primitiveData[i0 + 5] = v0 + 3; - } - device->CreateBuffer(&bd, primitiveData.data(), &primitiveBuffer); - device->SetName(&primitiveBuffer, "primitiveBuffer"); + MAX_PARTICLES = value; + counterBuffer = {}; // will be recreated } - if (IsSorted() && distanceBuffer.desc.size < MAX_PARTICLES * sizeof(float)) + void EmittedParticleSystem::CreateSelfBuffers() { - // Distance buffer: - GPUBufferDesc bd; - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - bd.stride = sizeof(float); - bd.size = bd.stride * MAX_PARTICLES; - wi::vector distances(MAX_PARTICLES); - std::fill(distances.begin(), distances.end(), 0.0f); - device->CreateBuffer(&bd, distances.data(), &distanceBuffer); - device->SetName(&distanceBuffer, "distanceBuffer"); - } + GraphicsDevice* device = wi::graphics::GetDevice(); - if (IsSPHEnabled()) - { - GPUBufferDesc bd; - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - - if (sphPartitionCellIndices.desc.size < MAX_PARTICLES * sizeof(float)) + if (particleBuffer.desc.size < MAX_PARTICLES * sizeof(Particle)) { - // SPH Partitioning grid indices per particle: - bd.stride = sizeof(float); // really, it is uint, but sorting is performing comparisons on floats, so whateva + GPUBufferDesc bd; + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + + // Particle buffer: + bd.stride = sizeof(Particle); bd.size = bd.stride * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &sphPartitionCellIndices); - device->SetName(&sphPartitionCellIndices, "sphPartitionCellIndices"); + device->CreateBuffer(&bd, nullptr, &particleBuffer); + device->SetName(&particleBuffer, "particleBuffer"); - // Density buffer (for SPH simulation): + // Alive index lists (double buffered): + bd.stride = sizeof(uint32_t); + bd.size = bd.stride * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &aliveList[0]); + device->SetName(&aliveList[0], "aliveList[0]"); + device->CreateBuffer(&bd, nullptr, &aliveList[1]); + device->SetName(&aliveList[1], "aliveList[1]"); + device->CreateBuffer(&bd, nullptr, &culledIndirectionBuffer); + device->SetName(&culledIndirectionBuffer, "culledIndirectionBuffer"); + device->CreateBuffer(&bd, nullptr, &culledIndirectionBuffer2); + device->SetName(&culledIndirectionBuffer2, "culledIndirectionBuffer2"); + + // Dead index list: + wi::vector indices(MAX_PARTICLES); + for (uint32_t i = 0; i < MAX_PARTICLES; ++i) + { + indices[i] = i; + } + device->CreateBuffer(&bd, indices.data(), &deadList); + device->SetName(&deadList, "deadList"); + + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + { + bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + } + bd.stride = sizeof(MeshComponent::Vertex_POS); + bd.size = bd.stride * 4 * MAX_PARTICLES; + wi::vector positionData(4 * MAX_PARTICLES); + std::fill(positionData.begin(), positionData.end(), MeshComponent::Vertex_POS()); + device->CreateBuffer(&bd, positionData.data(), &vertexBuffer_POS); + device->SetName(&vertexBuffer_POS, "vertexBuffer_POS"); + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + bd.stride = sizeof(MeshComponent::Vertex_TEX); + bd.size = bd.stride * 4 * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX); + device->SetName(&vertexBuffer_TEX, "vertexBuffer_TEX"); + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + bd.stride = sizeof(MeshComponent::Vertex_TEX); + bd.size = bd.stride * 4 * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX2); + device->SetName(&vertexBuffer_TEX2, "vertexBuffer_TEX2"); + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + bd.stride = sizeof(MeshComponent::Vertex_COL); + bd.size = bd.stride * 4 * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &vertexBuffer_COL); + device->SetName(&vertexBuffer_COL, "vertexBuffer_COL"); + + bd.bind_flags = BindFlag::SHADER_RESOURCE; + bd.misc_flags = ResourceMiscFlag::NONE; + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + { + bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + } + bd.format = Format::R32_UINT; + bd.stride = sizeof(uint); + bd.size = bd.stride * 6 * MAX_PARTICLES; + wi::vector primitiveData(6 * MAX_PARTICLES); + for (uint particleID = 0; particleID < MAX_PARTICLES; ++particleID) + { + uint v0 = particleID * 4; + uint i0 = particleID * 6; + primitiveData[i0 + 0] = v0 + 0; + primitiveData[i0 + 1] = v0 + 1; + primitiveData[i0 + 2] = v0 + 2; + primitiveData[i0 + 3] = v0 + 2; + primitiveData[i0 + 4] = v0 + 1; + primitiveData[i0 + 5] = v0 + 3; + } + device->CreateBuffer(&bd, primitiveData.data(), &primitiveBuffer); + device->SetName(&primitiveBuffer, "primitiveBuffer"); + } + + if (IsSorted() && distanceBuffer.desc.size < MAX_PARTICLES * sizeof(float)) + { + // Distance buffer: + GPUBufferDesc bd; + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; bd.stride = sizeof(float); bd.size = bd.stride * MAX_PARTICLES; - device->CreateBuffer(&bd, nullptr, &densityBuffer); - device->SetName(&densityBuffer, "densityBuffer"); + wi::vector distances(MAX_PARTICLES); + std::fill(distances.begin(), distances.end(), 0.0f); + device->CreateBuffer(&bd, distances.data(), &distanceBuffer); + device->SetName(&distanceBuffer, "distanceBuffer"); } - if (sphPartitionCellOffsets.desc.size < SPH_PARTITION_BUCKET_COUNT * sizeof(uint32_t)) - { - // SPH Partitioning grid cell offsets into particle index list: - bd.stride = sizeof(uint32_t); - bd.size = bd.stride * SPH_PARTITION_BUCKET_COUNT; - device->CreateBuffer(&bd, nullptr, &sphPartitionCellOffsets); - device->SetName(&sphPartitionCellOffsets, "sphPartitionCellOffsets"); - } - } - else - { - sphPartitionCellIndices = {}; - densityBuffer = {}; - sphPartitionCellOffsets = {}; - } - - if (!counterBuffer.IsValid()) - { - // Particle System statistics: - ParticleCounters counters; - counters.aliveCount = 0; - counters.deadCount = MAX_PARTICLES; - counters.realEmitCount = 0; - counters.aliveCount_afterSimulation = 0; - - GPUBufferDesc bd; - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - bd.size = sizeof(counters); - bd.stride = sizeof(counters); - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - device->CreateBuffer(&bd, &counters, &counterBuffer); - device->SetName(&counterBuffer, "counterBuffer"); - } - - if(!indirectBuffers.IsValid()) - { - GPUBufferDesc bd; - - // Indirect Execution buffer: - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW | ResourceMiscFlag::INDIRECT_ARGS; - bd.size = - sizeof(wiGraphics::IndirectDispatchArgs) + - sizeof(wiGraphics::IndirectDispatchArgs) + - sizeof(wiGraphics::IndirectDrawArgsInstanced); - device->CreateBuffer(&bd, nullptr, &indirectBuffers); - device->SetName(&indirectBuffers, "indirectBuffers"); - - // Constant buffer: - bd.usage = Usage::DEFAULT; - bd.size = sizeof(EmittedParticleCB); - bd.bind_flags = BindFlag::CONSTANT_BUFFER; - bd.misc_flags = ResourceMiscFlag::NONE; - device->CreateBuffer(&bd, nullptr, &constantBuffer); - device->SetName(&constantBuffer, "constantBuffer"); - - // Debug information CPU-readback buffer: - { - GPUBufferDesc debugBufDesc = counterBuffer.GetDesc(); - debugBufDesc.usage = Usage::READBACK; - debugBufDesc.bind_flags = BindFlag::NONE; - debugBufDesc.misc_flags = ResourceMiscFlag::NONE; - for (int i = 0; i < arraysize(statisticsReadbackBuffer); ++i) - { - device->CreateBuffer(&debugBufDesc, nullptr, &statisticsReadbackBuffer[i]); - device->SetName(&statisticsReadbackBuffer[i], "statisticsReadbackBuffer"); - } - } - } - - if (!subsetBuffer.IsValid()) - { - GPUBufferDesc desc; - desc.stride = sizeof(ShaderMeshSubset); - desc.size = desc.stride; - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - device->CreateBuffer(&desc, nullptr, &subsetBuffer); - } - - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING) && primitiveBuffer.IsValid()) - { - RaytracingAccelerationStructureDesc desc; - desc.type = RaytracingAccelerationStructureDesc::Type::BOTTOMLEVEL; - desc.flags |= RaytracingAccelerationStructureDesc::FLAG_ALLOW_UPDATE; - desc.flags |= RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; - - desc.bottom_level.geometries.emplace_back(); - auto& geometry = desc.bottom_level.geometries.back(); - geometry.type = RaytracingAccelerationStructureDesc::BottomLevel::Geometry::Type::TRIANGLES; - geometry.triangles.vertex_buffer = vertexBuffer_POS; - geometry.triangles.index_buffer = primitiveBuffer; - geometry.triangles.index_format = IndexBufferFormat::UINT32; - geometry.triangles.index_count = (uint32_t)(primitiveBuffer.desc.size / primitiveBuffer.desc.stride); - geometry.triangles.index_offset = 0; - geometry.triangles.vertex_count = (uint32_t)(vertexBuffer_POS.desc.size / vertexBuffer_POS.desc.stride); - geometry.triangles.vertex_format = Format::R32G32B32_FLOAT; - geometry.triangles.vertex_stride = sizeof(MeshComponent::Vertex_POS); - - bool success = device->CreateRaytracingAccelerationStructure(&desc, &BLAS); - assert(success); - device->SetName(&BLAS, "BLAS_hair"); - } - -} - -uint64_t wiEmittedParticle::GetMemorySizeInBytes() const -{ - if (!particleBuffer.IsValid()) - return 0; - - uint64_t retVal = 0; - - retVal += particleBuffer.GetDesc().size; - retVal += aliveList[0].GetDesc().size; - retVal += aliveList[1].GetDesc().size; - retVal += deadList.GetDesc().size; - retVal += distanceBuffer.GetDesc().size; - retVal += sphPartitionCellIndices.GetDesc().size; - retVal += sphPartitionCellOffsets.GetDesc().size; - retVal += densityBuffer.GetDesc().size; - retVal += counterBuffer.GetDesc().size; - retVal += indirectBuffers.GetDesc().size; - retVal += constantBuffer.GetDesc().size; - retVal += vertexBuffer_POS.GetDesc().size; - retVal += vertexBuffer_TEX.GetDesc().size; - retVal += vertexBuffer_TEX2.GetDesc().size; - retVal += vertexBuffer_COL.GetDesc().size; - retVal += primitiveBuffer.GetDesc().size; - retVal += culledIndirectionBuffer.GetDesc().size; - retVal += culledIndirectionBuffer2.GetDesc().size; - retVal += subsetBuffer.GetDesc().size; - - return retVal; -} - -void wiEmittedParticle::UpdateCPU(const TransformComponent& transform, float dt) -{ - CreateSelfBuffers(); - - if (IsPaused()) - return; - - emit = std::max(0.0f, emit - std::floor(emit)); - - center = transform.GetPosition(); - - emit += (float)count*dt; - - emit += burst; - burst = 0; - - // Swap CURRENT alivelist with NEW alivelist - std::swap(aliveList[0], aliveList[1]); - - // Read back statistics (with GPU delay): - if (statisticsReadBackIndex > arraysize(statisticsReadbackBuffer)) - { - const uint32_t oldest_stat_index = (statisticsReadBackIndex + 1) % arraysize(statisticsReadbackBuffer); - memcpy(&statistics, statisticsReadbackBuffer[oldest_stat_index].mapped_data, sizeof(statistics)); - } - statisticsReadBackIndex++; -} -void wiEmittedParticle::Burst(int num) -{ - if (IsPaused()) - return; - - burst += num; -} -void wiEmittedParticle::Restart() -{ - SetPaused(false); - counterBuffer = {}; // will be recreated -} - -void wiEmittedParticle::UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const TransformComponent& transform, const MeshComponent* mesh, CommandList cmd) const -{ - if (!particleBuffer.IsValid()) - { - return; - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - device->EventBegin("UpdateEmittedParticles", cmd); - - if (!IsPaused()) - { - EmittedParticleCB cb; - cb.xEmitterWorld = transform.world; - cb.xEmitCount = (uint32_t)emit; - cb.xEmitterMeshIndexCount = mesh == nullptr ? 0 : (uint32_t)mesh->indices.size(); - cb.xEmitterMeshVertexPositionStride = sizeof(MeshComponent::Vertex_POS); - cb.xEmitterRandomness = wiRandom::getRandom(0, 1000) * 0.001f; - cb.xParticleLifeSpan = life; - cb.xParticleLifeSpanRandomness = random_life; - cb.xParticleNormalFactor = normal_factor; - cb.xParticleRandomFactor = random_factor; - cb.xParticleScaling = scaleX; - cb.xParticleSize = size; - cb.xParticleMotionBlurAmount = motionBlurAmount; - cb.xParticleRotation = rotation * XM_PI * 60; - cb.xParticleMass = mass; - cb.xEmitterMaxParticleCount = MAX_PARTICLES; - cb.xEmitterFixedTimestep = FIXED_TIMESTEP; - cb.xEmitterFramesXY = uint2(std::max(1u, framesX), std::max(1u, framesY)); - cb.xEmitterFrameCount = std::max(1u, frameCount); - cb.xEmitterFrameStart = frameStart; - cb.xEmitterTexMul = float2(1.0f / (float)cb.xEmitterFramesXY.x, 1.0f / (float)cb.xEmitterFramesXY.y); - cb.xEmitterFrameRate = frameRate; - cb.xParticleGravity = gravity; - cb.xParticleDrag = drag; - XMStoreFloat3(&cb.xParticleVelocity, XMVector3TransformNormal(XMLoadFloat3(&velocity), XMLoadFloat4x4(&transform.world))); - cb.xParticleRandomColorFactor = random_color; - cb.xEmitterLayerMask = layerMask; - cb.xEmitterInstanceIndex = instanceIndex; - - ShaderMeshSubset subset; - subset.init(); - subset.indexOffset = 0; - subset.materialIndex = materialIndex; - device->UpdateBuffer(&subsetBuffer, &subset, cmd); - - cb.xEmitterOptions = 0; if (IsSPHEnabled()) { - cb.xEmitterOptions |= EMITTER_OPTION_BIT_SPH_ENABLED; + GPUBufferDesc bd; + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + + if (sphPartitionCellIndices.desc.size < MAX_PARTICLES * sizeof(float)) + { + // SPH Partitioning grid indices per particle: + bd.stride = sizeof(float); // really, it is uint, but sorting is performing comparisons on floats, so whateva + bd.size = bd.stride * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &sphPartitionCellIndices); + device->SetName(&sphPartitionCellIndices, "sphPartitionCellIndices"); + + // Density buffer (for SPH simulation): + bd.stride = sizeof(float); + bd.size = bd.stride * MAX_PARTICLES; + device->CreateBuffer(&bd, nullptr, &densityBuffer); + device->SetName(&densityBuffer, "densityBuffer"); + } + + if (sphPartitionCellOffsets.desc.size < SPH_PARTITION_BUCKET_COUNT * sizeof(uint32_t)) + { + // SPH Partitioning grid cell offsets into particle index list: + bd.stride = sizeof(uint32_t); + bd.size = bd.stride * SPH_PARTITION_BUCKET_COUNT; + device->CreateBuffer(&bd, nullptr, &sphPartitionCellOffsets); + device->SetName(&sphPartitionCellOffsets, "sphPartitionCellOffsets"); + } } - if (IsFrameBlendingEnabled()) + else { - cb.xEmitterOptions |= EMITTER_OPTION_BIT_FRAME_BLENDING_ENABLED; - } - if (ALLOW_MESH_SHADER && device->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) - { - cb.xEmitterOptions |= EMITTER_OPTION_BIT_MESH_SHADER_ENABLED; + sphPartitionCellIndices = {}; + densityBuffer = {}; + sphPartitionCellOffsets = {}; } - // SPH: - cb.xSPH_h = SPH_h; - cb.xSPH_h_rcp = 1.0f / SPH_h; - cb.xSPH_h2 = SPH_h * SPH_h; - cb.xSPH_h3 = cb.xSPH_h2 * SPH_h; - const float h6 = cb.xSPH_h2 * cb.xSPH_h2 * cb.xSPH_h2; - const float h9 = h6 * cb.xSPH_h3; - cb.xSPH_poly6_constant = (315.0f / (64.0f * XM_PI * h9)); - cb.xSPH_spiky_constant = (-45.0f / (XM_PI * h6)); - cb.xSPH_K = SPH_K; - cb.xSPH_p0 = SPH_p0; - cb.xSPH_e = SPH_e; + if (!counterBuffer.IsValid()) + { + // Particle System statistics: + ParticleCounters counters; + counters.aliveCount = 0; + counters.deadCount = MAX_PARTICLES; + counters.realEmitCount = 0; + counters.aliveCount_afterSimulation = 0; + + GPUBufferDesc bd; + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + bd.size = sizeof(counters); + bd.stride = sizeof(counters); + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + device->CreateBuffer(&bd, &counters, &counterBuffer); + device->SetName(&counterBuffer, "counterBuffer"); + } + + if (!indirectBuffers.IsValid()) + { + GPUBufferDesc bd; + + // Indirect Execution buffer: + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW | ResourceMiscFlag::INDIRECT_ARGS; + bd.size = + sizeof(wi::graphics::IndirectDispatchArgs) + + sizeof(wi::graphics::IndirectDispatchArgs) + + sizeof(wi::graphics::IndirectDrawArgsInstanced); + device->CreateBuffer(&bd, nullptr, &indirectBuffers); + device->SetName(&indirectBuffers, "indirectBuffers"); + + // Constant buffer: + bd.usage = Usage::DEFAULT; + bd.size = sizeof(EmittedParticleCB); + bd.bind_flags = BindFlag::CONSTANT_BUFFER; + bd.misc_flags = ResourceMiscFlag::NONE; + device->CreateBuffer(&bd, nullptr, &constantBuffer); + device->SetName(&constantBuffer, "constantBuffer"); + + // Debug information CPU-readback buffer: + { + GPUBufferDesc debugBufDesc = counterBuffer.GetDesc(); + debugBufDesc.usage = Usage::READBACK; + debugBufDesc.bind_flags = BindFlag::NONE; + debugBufDesc.misc_flags = ResourceMiscFlag::NONE; + for (int i = 0; i < arraysize(statisticsReadbackBuffer); ++i) + { + device->CreateBuffer(&debugBufDesc, nullptr, &statisticsReadbackBuffer[i]); + device->SetName(&statisticsReadbackBuffer[i], "statisticsReadbackBuffer"); + } + } + } + + if (!subsetBuffer.IsValid()) + { + GPUBufferDesc desc; + desc.stride = sizeof(ShaderMeshSubset); + desc.size = desc.stride; + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + device->CreateBuffer(&desc, nullptr, &subsetBuffer); + } + + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING) && primitiveBuffer.IsValid()) + { + RaytracingAccelerationStructureDesc desc; + desc.type = RaytracingAccelerationStructureDesc::Type::BOTTOMLEVEL; + desc.flags |= RaytracingAccelerationStructureDesc::FLAG_ALLOW_UPDATE; + desc.flags |= RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; + + desc.bottom_level.geometries.emplace_back(); + auto& geometry = desc.bottom_level.geometries.back(); + geometry.type = RaytracingAccelerationStructureDesc::BottomLevel::Geometry::Type::TRIANGLES; + geometry.triangles.vertex_buffer = vertexBuffer_POS; + geometry.triangles.index_buffer = primitiveBuffer; + geometry.triangles.index_format = IndexBufferFormat::UINT32; + geometry.triangles.index_count = (uint32_t)(primitiveBuffer.desc.size / primitiveBuffer.desc.stride); + geometry.triangles.index_offset = 0; + geometry.triangles.vertex_count = (uint32_t)(vertexBuffer_POS.desc.size / vertexBuffer_POS.desc.stride); + geometry.triangles.vertex_format = Format::R32G32B32_FLOAT; + geometry.triangles.vertex_stride = sizeof(MeshComponent::Vertex_POS); + + bool success = device->CreateRaytracingAccelerationStructure(&desc, &BLAS); + assert(success); + device->SetName(&BLAS, "BLAS_hair"); + } + + } + + uint64_t EmittedParticleSystem::GetMemorySizeInBytes() const + { + if (!particleBuffer.IsValid()) + return 0; + + uint64_t retVal = 0; + + retVal += particleBuffer.GetDesc().size; + retVal += aliveList[0].GetDesc().size; + retVal += aliveList[1].GetDesc().size; + retVal += deadList.GetDesc().size; + retVal += distanceBuffer.GetDesc().size; + retVal += sphPartitionCellIndices.GetDesc().size; + retVal += sphPartitionCellOffsets.GetDesc().size; + retVal += densityBuffer.GetDesc().size; + retVal += counterBuffer.GetDesc().size; + retVal += indirectBuffers.GetDesc().size; + retVal += constantBuffer.GetDesc().size; + retVal += vertexBuffer_POS.GetDesc().size; + retVal += vertexBuffer_TEX.GetDesc().size; + retVal += vertexBuffer_TEX2.GetDesc().size; + retVal += vertexBuffer_COL.GetDesc().size; + retVal += primitiveBuffer.GetDesc().size; + retVal += culledIndirectionBuffer.GetDesc().size; + retVal += culledIndirectionBuffer2.GetDesc().size; + retVal += subsetBuffer.GetDesc().size; + + return retVal; + } + + void EmittedParticleSystem::UpdateCPU(const TransformComponent& transform, float dt) + { + CreateSelfBuffers(); + + if (IsPaused()) + return; + + emit = std::max(0.0f, emit - std::floor(emit)); + + center = transform.GetPosition(); + + emit += (float)count * dt; + + emit += burst; + burst = 0; + + // Swap CURRENT alivelist with NEW alivelist + std::swap(aliveList[0], aliveList[1]); + + // Read back statistics (with GPU delay): + if (statisticsReadBackIndex > arraysize(statisticsReadbackBuffer)) + { + const uint32_t oldest_stat_index = (statisticsReadBackIndex + 1) % arraysize(statisticsReadbackBuffer); + memcpy(&statistics, statisticsReadbackBuffer[oldest_stat_index].mapped_data, sizeof(statistics)); + } + statisticsReadBackIndex++; + } + void EmittedParticleSystem::Burst(int num) + { + if (IsPaused()) + return; + + burst += num; + } + void EmittedParticleSystem::Restart() + { + SetPaused(false); + counterBuffer = {}; // will be recreated + } + + void EmittedParticleSystem::UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const TransformComponent& transform, const MeshComponent* mesh, CommandList cmd) const + { + if (!particleBuffer.IsValid()) + { + return; + } + + GraphicsDevice* device = wi::graphics::GetDevice(); + device->EventBegin("UpdateEmittedParticles", cmd); + + if (!IsPaused()) + { + EmittedParticleCB cb; + cb.xEmitterWorld = transform.world; + cb.xEmitCount = (uint32_t)emit; + cb.xEmitterMeshIndexCount = mesh == nullptr ? 0 : (uint32_t)mesh->indices.size(); + cb.xEmitterMeshVertexPositionStride = sizeof(MeshComponent::Vertex_POS); + cb.xEmitterRandomness = wi::random::GetRandom(0, 1000) * 0.001f; + cb.xParticleLifeSpan = life; + cb.xParticleLifeSpanRandomness = random_life; + cb.xParticleNormalFactor = normal_factor; + cb.xParticleRandomFactor = random_factor; + cb.xParticleScaling = scaleX; + cb.xParticleSize = size; + cb.xParticleMotionBlurAmount = motionBlurAmount; + cb.xParticleRotation = rotation * XM_PI * 60; + cb.xParticleMass = mass; + cb.xEmitterMaxParticleCount = MAX_PARTICLES; + cb.xEmitterFixedTimestep = FIXED_TIMESTEP; + cb.xEmitterFramesXY = uint2(std::max(1u, framesX), std::max(1u, framesY)); + cb.xEmitterFrameCount = std::max(1u, frameCount); + cb.xEmitterFrameStart = frameStart; + cb.xEmitterTexMul = float2(1.0f / (float)cb.xEmitterFramesXY.x, 1.0f / (float)cb.xEmitterFramesXY.y); + cb.xEmitterFrameRate = frameRate; + cb.xParticleGravity = gravity; + cb.xParticleDrag = drag; + XMStoreFloat3(&cb.xParticleVelocity, XMVector3TransformNormal(XMLoadFloat3(&velocity), XMLoadFloat4x4(&transform.world))); + cb.xParticleRandomColorFactor = random_color; + cb.xEmitterLayerMask = layerMask; + cb.xEmitterInstanceIndex = instanceIndex; + + ShaderMeshSubset subset; + subset.init(); + subset.indexOffset = 0; + subset.materialIndex = materialIndex; + device->UpdateBuffer(&subsetBuffer, &subset, cmd); + + cb.xEmitterOptions = 0; + if (IsSPHEnabled()) + { + cb.xEmitterOptions |= EMITTER_OPTION_BIT_SPH_ENABLED; + } + if (IsFrameBlendingEnabled()) + { + cb.xEmitterOptions |= EMITTER_OPTION_BIT_FRAME_BLENDING_ENABLED; + } + if (ALLOW_MESH_SHADER && device->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) + { + cb.xEmitterOptions |= EMITTER_OPTION_BIT_MESH_SHADER_ENABLED; + } + + // SPH: + cb.xSPH_h = SPH_h; + cb.xSPH_h_rcp = 1.0f / SPH_h; + cb.xSPH_h2 = SPH_h * SPH_h; + cb.xSPH_h3 = cb.xSPH_h2 * SPH_h; + const float h6 = cb.xSPH_h2 * cb.xSPH_h2 * cb.xSPH_h2; + const float h9 = h6 * cb.xSPH_h3; + cb.xSPH_poly6_constant = (315.0f / (64.0f * XM_PI * h9)); + cb.xSPH_spiky_constant = (-45.0f / (XM_PI * h6)); + cb.xSPH_K = SPH_K; + cb.xSPH_p0 = SPH_p0; + cb.xSPH_e = SPH_e; + + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&constantBuffer, ResourceState::CONSTANT_BUFFER, ResourceState::COPY_DST), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->UpdateBuffer(&constantBuffer, &cb, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&constantBuffer, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), + GPUBarrier::Buffer(&subsetBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(EmittedParticleCB), cmd); + + const GPUResource* uavs[] = { + &particleBuffer, + &aliveList[0], // CURRENT alivelist + &aliveList[1], // NEW alivelist + &deadList, + &counterBuffer, + &indirectBuffers, + &distanceBuffer, + &vertexBuffer_POS, + &vertexBuffer_TEX, + &vertexBuffer_TEX2, + &vertexBuffer_COL, + &culledIndirectionBuffer, + &culledIndirectionBuffer2, + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + if (mesh != nullptr) + { + const GPUResource* resources[] = { + &mesh->indexBuffer, + (mesh->streamoutBuffer_POS.IsValid() ? &mesh->streamoutBuffer_POS : &mesh->vertexBuffer_POS), + }; + device->BindResources(resources, 0, arraysize(resources), cmd); + } + + GPUBarrier barrier_indirect_uav = GPUBarrier::Buffer(&indirectBuffers, ResourceState::INDIRECT_ARGUMENT, ResourceState::UNORDERED_ACCESS); + GPUBarrier barrier_uav_indirect = GPUBarrier::Buffer(&indirectBuffers, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT); + GPUBarrier barrier_memory = GPUBarrier::Memory(); + + device->Barrier(&barrier_indirect_uav, 1, cmd); + + // kick off updating, set up state + device->EventBegin("KickOff Update", cmd); + device->BindComputeShader(&kickoffUpdateCS, cmd); + device->Dispatch(1, 1, 1, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + device->Barrier(&barrier_uav_indirect, 1, cmd); + + // emit the required amount if there are free slots in dead list + device->EventBegin("Emit", cmd); + device->BindComputeShader(mesh == nullptr ? (IsVolumeEnabled() ? &emitCS_VOLUME : &emitCS) : &emitCS_FROMMESH, cmd); + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHEMIT, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + if (IsSPHEnabled()) + { + auto range = wi::profiler::BeginRangeGPU("SPH - Simulation", cmd); + + // Smooth Particle Hydrodynamics: + device->EventBegin("SPH - Simulation", cmd); + +#ifdef SPH_USE_ACCELERATION_GRID + // 1.) Assign particles into partitioning grid: + device->EventBegin("Partitioning", cmd); + device->BindComputeShader(&sphpartitionCS, cmd); + const GPUResource* res_partition[] = { + &aliveList[0], // CURRENT alivelist + &counterBuffer, + &particleBuffer, + }; + device->BindResources(res_partition, 0, arraysize(res_partition), cmd); + const GPUResource* uav_partition[] = { + &sphPartitionCellIndices, + }; + device->BindUAVs(uav_partition, 0, arraysize(uav_partition), cmd); + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + // 2.) Sort particle index list based on partition grid cell index: + wi::gpusortlib::Sort(MAX_PARTICLES, sphPartitionCellIndices, counterBuffer, PARTICLECOUNTER_OFFSET_ALIVECOUNT, aliveList[0], cmd); + + // 3.) Reset grid cell offset buffer with invalid offsets (max uint): + device->EventBegin("PartitionOffsetsReset", cmd); + device->BindComputeShader(&sphpartitionoffsetsresetCS, cmd); + const GPUResource* uav_partitionoffsets[] = { + &sphPartitionCellOffsets, + }; + device->BindUAVs(uav_partitionoffsets, 0, arraysize(uav_partitionoffsets), cmd); + device->Dispatch((SPH_PARTITION_BUCKET_COUNT + THREADCOUNT_SIMULATION - 1) / THREADCOUNT_SIMULATION, 1, 1, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + // 4.) Assemble grid cell offsets from the sorted particle index list <--> grid cell index list connection: + device->EventBegin("PartitionOffsets", cmd); + device->BindComputeShader(&sphpartitionoffsetsCS, cmd); + const GPUResource* res_partitionoffsets[] = { + &aliveList[0], // CURRENT alivelist + &counterBuffer, + &sphPartitionCellIndices, + }; + device->BindResources(res_partitionoffsets, 0, arraysize(res_partitionoffsets), cmd); + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + +#endif // SPH_USE_ACCELERATION_GRID + + // 5.) Compute particle density field: + device->EventBegin("Density Evaluation", cmd); + device->BindComputeShader(&sphdensityCS, cmd); + const GPUResource* res_density[] = { + &aliveList[0], // CURRENT alivelist + &counterBuffer, + &particleBuffer, + &sphPartitionCellIndices, + &sphPartitionCellOffsets, + }; + device->BindResources(res_density, 0, arraysize(res_density), cmd); + const GPUResource* uav_density[] = { + &densityBuffer + }; + device->BindUAVs(uav_density, 0, arraysize(uav_density), cmd); + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + // 6.) Compute particle pressure forces: + device->EventBegin("Force Evaluation", cmd); + device->BindComputeShader(&sphforceCS, cmd); + const GPUResource* res_force[] = { + &aliveList[0], // CURRENT alivelist + &counterBuffer, + &densityBuffer, + &sphPartitionCellIndices, + &sphPartitionCellOffsets, + }; + device->BindResources(res_force, 0, arraysize(res_force), cmd); + const GPUResource* uav_force[] = { + &particleBuffer, + }; + device->BindUAVs(uav_force, 0, arraysize(uav_force), cmd); + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); + device->Barrier(&barrier_memory, 1, cmd); + device->EventEnd(cmd); + + + device->EventEnd(cmd); + + wi::profiler::EndRange(range); + } + + device->EventBegin("Simulate", cmd); + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + // update CURRENT alive list, write NEW alive list + if (IsSorted()) + { + if (IsDepthCollisionEnabled()) + { + device->BindComputeShader(&simulateCS_SORTING_DEPTHCOLLISIONS, cmd); + } + else + { + device->BindComputeShader(&simulateCS_SORTING, cmd); + } + } + else + { + if (IsDepthCollisionEnabled()) + { + device->BindComputeShader(&simulateCS_DEPTHCOLLISIONS, cmd); + } + else + { + device->BindComputeShader(&simulateCS, cmd); + } + } + device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Memory(), + GPUBarrier::Buffer(&counterBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&distanceBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), + }; + } + device->EventEnd(cmd); + + } + + if (IsSorted()) + { + wi::gpusortlib::Sort(MAX_PARTICLES, distanceBuffer, counterBuffer, PARTICLECOUNTER_OFFSET_CULLEDCOUNT, culledIndirectionBuffer, cmd); + } + + if (!IsPaused()) + { + // finish updating, update draw argument buffer: + device->EventBegin("FinishUpdate", cmd); + device->BindComputeShader(&finishUpdateCS, cmd); + + const GPUResource* res[] = { + &counterBuffer, + }; + device->BindResources(res, 0, arraysize(res), cmd); + + const GPUResource* uavs[] = { + &indirectBuffers, + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + { + GPUBarrier barriers[] = { + GPUBarrier::Memory(), + GPUBarrier::Buffer(&indirectBuffers, ResourceState::INDIRECT_ARGUMENT, ResourceState::UNORDERED_ACCESS), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + device->Dispatch(1, 1, 1, cmd); + + device->EventEnd(cmd); + + } { GPUBarrier barriers[] = { - GPUBarrier::Buffer(&constantBuffer, ResourceState::CONSTANT_BUFFER, ResourceState::COPY_DST), + GPUBarrier::Memory(), + GPUBarrier::Buffer(&counterBuffer, ResourceState::SHADER_RESOURCE, ResourceState::COPY_SRC), }; device->Barrier(barriers, arraysize(barriers), cmd); } - device->UpdateBuffer(&constantBuffer, &cb, cmd); + + // Statistics is copied to readback: + device->CopyResource(&statisticsReadbackBuffer[(statisticsReadBackIndex - 1) % arraysize(statisticsReadbackBuffer)], &counterBuffer, cmd); + { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&constantBuffer, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), - GPUBarrier::Buffer(&subsetBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), + const GPUBarrier barriers[] = { + GPUBarrier::Buffer(&indirectBuffers, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT), + GPUBarrier::Buffer(&counterBuffer, ResourceState::COPY_SRC, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&particleBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&aliveList[1], ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&vertexBuffer_POS, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&vertexBuffer_TEX, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&vertexBuffer_TEX2, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&vertexBuffer_COL, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&culledIndirectionBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), + GPUBarrier::Buffer(&culledIndirectionBuffer2, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), }; device->Barrier(barriers, arraysize(barriers), cmd); } + device->EventEnd(cmd); + } + + + void EmittedParticleSystem::Draw(const MaterialComponent& material, CommandList cmd) const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + device->EventBegin("EmittedParticle", cmd); + + if (wi::renderer::IsWireRender()) + { + device->BindPipelineState(&PSO_wire, cmd); + } + else + { + const wi::enums::BLENDMODE blendMode = material.GetBlendMode(); + device->BindPipelineState(&PSO[blendMode][shaderType], cmd); + + device->BindShadingRate(material.shadingRate, cmd); + } + device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(EmittedParticleCB), cmd); - const GPUResource* uavs[] = { - &particleBuffer, - &aliveList[0], // CURRENT alivelist - &aliveList[1], // NEW alivelist - &deadList, + const GPUResource* res[] = { &counterBuffer, - &indirectBuffers, - &distanceBuffer, - &vertexBuffer_POS, - &vertexBuffer_TEX, - &vertexBuffer_TEX2, - &vertexBuffer_COL, + &particleBuffer, &culledIndirectionBuffer, &culledIndirectionBuffer2, }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + device->BindResources(res, 20, arraysize(res), cmd); - if (mesh != nullptr) + if (ALLOW_MESH_SHADER && device->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) { - const GPUResource* resources[] = { - &mesh->indexBuffer, - (mesh->streamoutBuffer_POS.IsValid() ? &mesh->streamoutBuffer_POS : &mesh->vertexBuffer_POS), - }; - device->BindResources(resources, 0, arraysize(resources), cmd); + device->DispatchMeshIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DRAWPARTICLES, cmd); + } + else + { + device->DrawInstancedIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DRAWPARTICLES, cmd); } - GPUBarrier barrier_indirect_uav = GPUBarrier::Buffer(&indirectBuffers, ResourceState::INDIRECT_ARGUMENT, ResourceState::UNORDERED_ACCESS); - GPUBarrier barrier_uav_indirect = GPUBarrier::Buffer(&indirectBuffers, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT); - GPUBarrier barrier_memory = GPUBarrier::Memory(); - - device->Barrier(&barrier_indirect_uav, 1, cmd); - - // kick off updating, set up state - device->EventBegin("KickOff Update", cmd); - device->BindComputeShader(&kickoffUpdateCS, cmd); - device->Dispatch(1, 1, 1, cmd); - device->Barrier(&barrier_memory, 1, cmd); device->EventEnd(cmd); + } - device->Barrier(&barrier_uav_indirect, 1, cmd); - // emit the required amount if there are free slots in dead list - device->EventBegin("Emit", cmd); - device->BindComputeShader(mesh == nullptr ? (IsVolumeEnabled() ? &emitCS_VOLUME : &emitCS) : &emitCS_FROMMESH, cmd); - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHEMIT, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - - if (IsSPHEnabled()) + namespace EmittedParticleSystem_Internal + { + void LoadShaders() { - auto range = wiProfiler::BeginRangeGPU("SPH - Simulation", cmd); + wi::renderer::LoadShader(ShaderStage::VS, vertexShader, "emittedparticleVS.cso"); - // Smooth Particle Hydrodynamics: - device->EventBegin("SPH - Simulation", cmd); - -#ifdef SPH_USE_ACCELERATION_GRID - // 1.) Assign particles into partitioning grid: - device->EventBegin("Partitioning", cmd); - device->BindComputeShader(&sphpartitionCS, cmd); - const GPUResource* res_partition[] = { - &aliveList[0], // CURRENT alivelist - &counterBuffer, - &particleBuffer, - }; - device->BindResources(res_partition, 0, arraysize(res_partition), cmd); - const GPUResource* uav_partition[] = { - &sphPartitionCellIndices, - }; - device->BindUAVs(uav_partition, 0, arraysize(uav_partition), cmd); - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - - // 2.) Sort particle index list based on partition grid cell index: - wiGPUSortLib::Sort(MAX_PARTICLES, sphPartitionCellIndices, counterBuffer, PARTICLECOUNTER_OFFSET_ALIVECOUNT, aliveList[0], cmd); - - // 3.) Reset grid cell offset buffer with invalid offsets (max uint): - device->EventBegin("PartitionOffsetsReset", cmd); - device->BindComputeShader(&sphpartitionoffsetsresetCS, cmd); - const GPUResource* uav_partitionoffsets[] = { - &sphPartitionCellOffsets, - }; - device->BindUAVs(uav_partitionoffsets, 0, arraysize(uav_partitionoffsets), cmd); - device->Dispatch((SPH_PARTITION_BUCKET_COUNT + THREADCOUNT_SIMULATION - 1) / THREADCOUNT_SIMULATION, 1, 1, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - - // 4.) Assemble grid cell offsets from the sorted particle index list <--> grid cell index list connection: - device->EventBegin("PartitionOffsets", cmd); - device->BindComputeShader(&sphpartitionoffsetsCS, cmd); - const GPUResource* res_partitionoffsets[] = { - &aliveList[0], // CURRENT alivelist - &counterBuffer, - &sphPartitionCellIndices, - }; - device->BindResources(res_partitionoffsets, 0, arraysize(res_partitionoffsets), cmd); - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - -#endif // SPH_USE_ACCELERATION_GRID - - // 5.) Compute particle density field: - device->EventBegin("Density Evaluation", cmd); - device->BindComputeShader(&sphdensityCS, cmd); - const GPUResource* res_density[] = { - &aliveList[0], // CURRENT alivelist - &counterBuffer, - &particleBuffer, - &sphPartitionCellIndices, - &sphPartitionCellOffsets, - }; - device->BindResources(res_density, 0, arraysize(res_density), cmd); - const GPUResource* uav_density[] = { - &densityBuffer - }; - device->BindUAVs(uav_density, 0, arraysize(uav_density), cmd); - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - - // 6.) Compute particle pressure forces: - device->EventBegin("Force Evaluation", cmd); - device->BindComputeShader(&sphforceCS, cmd); - const GPUResource* res_force[] = { - &aliveList[0], // CURRENT alivelist - &counterBuffer, - &densityBuffer, - &sphPartitionCellIndices, - &sphPartitionCellOffsets, - }; - device->BindResources(res_force, 0, arraysize(res_force), cmd); - const GPUResource* uav_force[] = { - &particleBuffer, - }; - device->BindUAVs(uav_force, 0, arraysize(uav_force), cmd); - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); - device->Barrier(&barrier_memory, 1, cmd); - device->EventEnd(cmd); - - - device->EventEnd(cmd); - - wiProfiler::EndRange(range); - } - - device->EventBegin("Simulate", cmd); - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - - // update CURRENT alive list, write NEW alive list - if (IsSorted()) - { - if (IsDepthCollisionEnabled()) + if (ALLOW_MESH_SHADER && wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) { - device->BindComputeShader(&simulateCS_SORTING_DEPTHCOLLISIONS, cmd); + wi::renderer::LoadShader(ShaderStage::MS, meshShader, "emittedparticleMS.cso"); + } + + wi::renderer::LoadShader(ShaderStage::PS, pixelShader[EmittedParticleSystem::SOFT], "emittedparticlePS_soft.cso"); + wi::renderer::LoadShader(ShaderStage::PS, pixelShader[EmittedParticleSystem::SOFT_DISTORTION], "emittedparticlePS_soft_distortion.cso"); + wi::renderer::LoadShader(ShaderStage::PS, pixelShader[EmittedParticleSystem::SIMPLE], "emittedparticlePS_simple.cso"); + wi::renderer::LoadShader(ShaderStage::PS, pixelShader[EmittedParticleSystem::SOFT_LIGHTING], "emittedparticlePS_soft_lighting.cso"); + + wi::renderer::LoadShader(ShaderStage::CS, kickoffUpdateCS, "emittedparticle_kickoffUpdateCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, finishUpdateCS, "emittedparticle_finishUpdateCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, emitCS, "emittedparticle_emitCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, emitCS_VOLUME, "emittedparticle_emitCS_volume.cso"); + wi::renderer::LoadShader(ShaderStage::CS, emitCS_FROMMESH, "emittedparticle_emitCS_FROMMESH.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sphpartitionCS, "emittedparticle_sphpartitionCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sphpartitionoffsetsCS, "emittedparticle_sphpartitionoffsetsCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sphpartitionoffsetsresetCS, "emittedparticle_sphpartitionoffsetsresetCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sphdensityCS, "emittedparticle_sphdensityCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sphforceCS, "emittedparticle_sphforceCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, simulateCS, "emittedparticle_simulateCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, simulateCS_SORTING, "emittedparticle_simulateCS_SORTING.cso"); + wi::renderer::LoadShader(ShaderStage::CS, simulateCS_DEPTHCOLLISIONS, "emittedparticle_simulateCS_DEPTHCOLLISIONS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, simulateCS_SORTING_DEPTHCOLLISIONS, "emittedparticle_simulateCS_SORTING_DEPTHCOLLISIONS.cso"); + + + GraphicsDevice* device = wi::graphics::GetDevice(); + + for (int i = 0; i < BLENDMODE_COUNT; ++i) + { + PipelineStateDesc desc; + desc.pt = PrimitiveTopology::TRIANGLESTRIP; + if (ALLOW_MESH_SHADER && wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) + { + desc.ms = &meshShader; + } + else + { + desc.vs = &vertexShader; + } + desc.bs = &blendStates[i]; + desc.rs = &rasterizerState; + desc.dss = &depthStencilState; + + for (int j = 0; j < EmittedParticleSystem::PARTICLESHADERTYPE_COUNT; ++j) + { + desc.ps = &pixelShader[j]; + device->CreatePipelineState(&desc, &PSO[i][j]); + } + } + + { + PipelineStateDesc desc; + desc.pt = PrimitiveTopology::TRIANGLESTRIP; + if (ALLOW_MESH_SHADER && wi::graphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) + { + desc.ms = &meshShader; + } + else + { + desc.vs = &vertexShader; + } + desc.ps = &pixelShader[EmittedParticleSystem::SIMPLE]; + desc.bs = &blendStates[BLENDMODE_ALPHA]; + desc.rs = &wireFrameRS; + desc.dss = &depthStencilState; + + device->CreatePipelineState(&desc, &PSO_wire); + } + + } + } + + void EmittedParticleSystem::Initialize() + { + wi::Timer timer; + + RasterizerState rs; + rs.fill_mode = FillMode::SOLID; + rs.cull_mode = CullMode::NONE; + rs.front_counter_clockwise = true; + rs.depth_bias = 0; + rs.depth_bias_clamp = 0; + rs.slope_scaled_depth_bias = 0; + rs.depth_clip_enable = false; + rs.multisample_enable = false; + rs.antialiased_line_enable = false; + rasterizerState = rs; + + + rs.fill_mode = FillMode::WIREFRAME; + rs.cull_mode = CullMode::NONE; + rs.front_counter_clockwise = true; + rs.depth_bias = 0; + rs.depth_bias_clamp = 0; + rs.slope_scaled_depth_bias = 0; + rs.depth_clip_enable = false; + rs.multisample_enable = false; + rs.antialiased_line_enable = false; + wireFrameRS = rs; + + + DepthStencilState dsd; + dsd.depth_enable = true; + dsd.depth_write_mask = DepthWriteMask::ZERO; + dsd.depth_func = ComparisonFunc::GREATER_EQUAL; + dsd.stencil_enable = false; + depthStencilState = dsd; + + + BlendState bd; + bd.render_target[0].blend_enable = true; + bd.render_target[0].src_blend = Blend::SRC_ALPHA; + bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; + bd.render_target[0].blend_op = BlendOp::ADD; + bd.render_target[0].src_blend_alpha = Blend::ONE; + bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA; + bd.render_target[0].blend_op_alpha = BlendOp::ADD; + bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; + bd.independent_blend_enable = false; + blendStates[BLENDMODE_ALPHA] = bd; + + bd.render_target[0].blend_enable = true; + bd.render_target[0].src_blend = Blend::SRC_ALPHA; + bd.render_target[0].dest_blend = Blend::ONE; + bd.render_target[0].blend_op = BlendOp::ADD; + bd.render_target[0].src_blend_alpha = Blend::ZERO; + bd.render_target[0].dest_blend_alpha = Blend::ONE; + bd.render_target[0].blend_op_alpha = BlendOp::ADD; + bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; + bd.independent_blend_enable = false; + blendStates[BLENDMODE_ADDITIVE] = bd; + + bd.render_target[0].blend_enable = true; + bd.render_target[0].src_blend = Blend::ONE; + bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; + bd.render_target[0].blend_op = BlendOp::ADD; + bd.render_target[0].src_blend_alpha = Blend::ONE; + bd.render_target[0].dest_blend_alpha = Blend::ONE; + bd.render_target[0].blend_op_alpha = BlendOp::ADD; + bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; + bd.independent_blend_enable = false; + blendStates[BLENDMODE_PREMULTIPLIED] = bd; + + bd.render_target[0].blend_enable = false; + blendStates[BLENDMODE_OPAQUE] = bd; + + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { EmittedParticleSystem_Internal::LoadShaders(); }); + EmittedParticleSystem_Internal::LoadShaders(); + + wi::backlog::post("wi::EmittedParticleSystem Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + } + + + void EmittedParticleSystem::Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri) + { + if (archive.IsReadMode()) + { + archive >> _flags; + archive >> (uint32_t&)shaderType; + wi::ecs::SerializeEntity(archive, meshID, seri); + archive >> MAX_PARTICLES; + archive >> FIXED_TIMESTEP; + archive >> size; + archive >> random_factor; + archive >> normal_factor; + archive >> count; + archive >> life; + archive >> random_life; + archive >> scaleX; + archive >> scaleY; + archive >> rotation; + archive >> motionBlurAmount; + archive >> mass; + archive >> SPH_h; + archive >> SPH_K; + archive >> SPH_p0; + archive >> SPH_e; + + if (archive.GetVersion() >= 45) + { + archive >> framesX; + archive >> framesY; + archive >> frameCount; + archive >> frameStart; + archive >> frameRate; + } + + if (archive.GetVersion() == 48) + { + uint8_t shadingRate; + archive >> shadingRate; // no longer needed + } + + if (archive.GetVersion() >= 64) + { + archive >> velocity; + archive >> gravity; + archive >> drag; + archive >> random_color; } else { - device->BindComputeShader(&simulateCS_SORTING, cmd); + if (IsSPHEnabled()) + { + gravity = XMFLOAT3(0, -9.8f * 2, 0); + drag = 0.98f; + } } } else { - if (IsDepthCollisionEnabled()) + archive << _flags; + archive << (uint32_t)shaderType; + wi::ecs::SerializeEntity(archive, meshID, seri); + archive << MAX_PARTICLES; + archive << FIXED_TIMESTEP; + archive << size; + archive << random_factor; + archive << normal_factor; + archive << count; + archive << life; + archive << random_life; + archive << scaleX; + archive << scaleY; + archive << rotation; + archive << motionBlurAmount; + archive << mass; + archive << SPH_h; + archive << SPH_K; + archive << SPH_p0; + archive << SPH_e; + + if (archive.GetVersion() >= 45) { - device->BindComputeShader(&simulateCS_DEPTHCOLLISIONS, cmd); + archive << framesX; + archive << framesY; + archive << frameCount; + archive << frameStart; + archive << frameRate; } - else + + if (archive.GetVersion() >= 64) { - device->BindComputeShader(&simulateCS, cmd); - } - } - device->DispatchIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DISPATCHSIMULATION, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Memory(), - GPUBarrier::Buffer(&counterBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&distanceBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), - }; - } - device->EventEnd(cmd); - - } - - if (IsSorted()) - { - wiGPUSortLib::Sort(MAX_PARTICLES, distanceBuffer, counterBuffer, PARTICLECOUNTER_OFFSET_CULLEDCOUNT, culledIndirectionBuffer, cmd); - } - - if (!IsPaused()) - { - // finish updating, update draw argument buffer: - device->EventBegin("FinishUpdate", cmd); - device->BindComputeShader(&finishUpdateCS, cmd); - - const GPUResource* res[] = { - &counterBuffer, - }; - device->BindResources(res, 0, arraysize(res), cmd); - - const GPUResource* uavs[] = { - &indirectBuffers, - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - - { - GPUBarrier barriers[] = { - GPUBarrier::Memory(), - GPUBarrier::Buffer(&indirectBuffers, ResourceState::INDIRECT_ARGUMENT, ResourceState::UNORDERED_ACCESS), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - device->Dispatch(1, 1, 1, cmd); - - device->EventEnd(cmd); - - } - - { - GPUBarrier barriers[] = { - GPUBarrier::Memory(), - GPUBarrier::Buffer(&counterBuffer, ResourceState::SHADER_RESOURCE, ResourceState::COPY_SRC), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - // Statistics is copied to readback: - device->CopyResource(&statisticsReadbackBuffer[(statisticsReadBackIndex - 1) % arraysize(statisticsReadbackBuffer)], &counterBuffer, cmd); - - { - const GPUBarrier barriers[] = { - GPUBarrier::Buffer(&indirectBuffers, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT), - GPUBarrier::Buffer(&counterBuffer, ResourceState::COPY_SRC, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&particleBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&aliveList[1], ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&vertexBuffer_POS, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&vertexBuffer_TEX, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&vertexBuffer_TEX2, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&vertexBuffer_COL, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&culledIndirectionBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), - GPUBarrier::Buffer(&culledIndirectionBuffer2, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE_COMPUTE), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - device->EventEnd(cmd); -} - - -void wiEmittedParticle::Draw(const MaterialComponent& material, CommandList cmd) const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - device->EventBegin("EmittedParticle", cmd); - - if (wiRenderer::IsWireRender()) - { - device->BindPipelineState(&PSO_wire, cmd); - } - else - { - const BLENDMODE blendMode = material.GetBlendMode(); - device->BindPipelineState(&PSO[blendMode][shaderType], cmd); - - device->BindShadingRate(material.shadingRate, cmd); - } - - device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(EmittedParticleCB), cmd); - - const GPUResource* res[] = { - &counterBuffer, - &particleBuffer, - &culledIndirectionBuffer, - &culledIndirectionBuffer2, - }; - device->BindResources(res, 20, arraysize(res), cmd); - - if (ALLOW_MESH_SHADER && device->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) - { - device->DispatchMeshIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DRAWPARTICLES, cmd); - } - else - { - device->DrawInstancedIndirect(&indirectBuffers, ARGUMENTBUFFER_OFFSET_DRAWPARTICLES, cmd); - } - - device->EventEnd(cmd); -} - - -namespace wiEmittedParticle_Internal -{ - void LoadShaders() - { - wiRenderer::LoadShader(ShaderStage::VS, vertexShader, "emittedparticleVS.cso"); - - if (ALLOW_MESH_SHADER && wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) - { - wiRenderer::LoadShader(ShaderStage::MS, meshShader, "emittedparticleMS.cso"); - } - - wiRenderer::LoadShader(ShaderStage::PS, pixelShader[wiEmittedParticle::SOFT], "emittedparticlePS_soft.cso"); - wiRenderer::LoadShader(ShaderStage::PS, pixelShader[wiEmittedParticle::SOFT_DISTORTION], "emittedparticlePS_soft_distortion.cso"); - wiRenderer::LoadShader(ShaderStage::PS, pixelShader[wiEmittedParticle::SIMPLE], "emittedparticlePS_simple.cso"); - wiRenderer::LoadShader(ShaderStage::PS, pixelShader[wiEmittedParticle::SOFT_LIGHTING], "emittedparticlePS_soft_lighting.cso"); - - wiRenderer::LoadShader(ShaderStage::CS, kickoffUpdateCS, "emittedparticle_kickoffUpdateCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, finishUpdateCS, "emittedparticle_finishUpdateCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, emitCS, "emittedparticle_emitCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, emitCS_VOLUME, "emittedparticle_emitCS_volume.cso"); - wiRenderer::LoadShader(ShaderStage::CS, emitCS_FROMMESH, "emittedparticle_emitCS_FROMMESH.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sphpartitionCS, "emittedparticle_sphpartitionCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sphpartitionoffsetsCS, "emittedparticle_sphpartitionoffsetsCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sphpartitionoffsetsresetCS, "emittedparticle_sphpartitionoffsetsresetCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sphdensityCS, "emittedparticle_sphdensityCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sphforceCS, "emittedparticle_sphforceCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, simulateCS, "emittedparticle_simulateCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, simulateCS_SORTING, "emittedparticle_simulateCS_SORTING.cso"); - wiRenderer::LoadShader(ShaderStage::CS, simulateCS_DEPTHCOLLISIONS, "emittedparticle_simulateCS_DEPTHCOLLISIONS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, simulateCS_SORTING_DEPTHCOLLISIONS, "emittedparticle_simulateCS_SORTING_DEPTHCOLLISIONS.cso"); - - - GraphicsDevice* device = wiGraphics::GetDevice(); - - for (int i = 0; i < BLENDMODE_COUNT; ++i) - { - PipelineStateDesc desc; - desc.pt = PrimitiveTopology::TRIANGLESTRIP; - if (ALLOW_MESH_SHADER && wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) - { - desc.ms = &meshShader; - } - else - { - desc.vs = &vertexShader; - } - desc.bs = &blendStates[i]; - desc.rs = &rasterizerState; - desc.dss = &depthStencilState; - - for (int j = 0; j < wiEmittedParticle::PARTICLESHADERTYPE_COUNT; ++j) - { - desc.ps = &pixelShader[j]; - device->CreatePipelineState(&desc, &PSO[i][j]); - } - } - - { - PipelineStateDesc desc; - desc.pt = PrimitiveTopology::TRIANGLESTRIP; - if (ALLOW_MESH_SHADER && wiGraphics::GetDevice()->CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) - { - desc.ms = &meshShader; - } - else - { - desc.vs = &vertexShader; - } - desc.ps = &pixelShader[wiEmittedParticle::SIMPLE]; - desc.bs = &blendStates[BLENDMODE_ALPHA]; - desc.rs = &wireFrameRS; - desc.dss = &depthStencilState; - - device->CreatePipelineState(&desc, &PSO_wire); - } - - } -} - -void wiEmittedParticle::Initialize() -{ - wiTimer timer; - - RasterizerState rs; - rs.fill_mode = FillMode::SOLID; - rs.cull_mode = CullMode::NONE; - rs.front_counter_clockwise = true; - rs.depth_bias = 0; - rs.depth_bias_clamp = 0; - rs.slope_scaled_depth_bias = 0; - rs.depth_clip_enable = false; - rs.multisample_enable = false; - rs.antialiased_line_enable = false; - rasterizerState = rs; - - - rs.fill_mode = FillMode::WIREFRAME; - rs.cull_mode = CullMode::NONE; - rs.front_counter_clockwise = true; - rs.depth_bias = 0; - rs.depth_bias_clamp = 0; - rs.slope_scaled_depth_bias = 0; - rs.depth_clip_enable = false; - rs.multisample_enable = false; - rs.antialiased_line_enable = false; - wireFrameRS = rs; - - - DepthStencilState dsd; - dsd.depth_enable = true; - dsd.depth_write_mask = DepthWriteMask::ZERO; - dsd.depth_func = ComparisonFunc::GREATER_EQUAL; - dsd.stencil_enable = false; - depthStencilState = dsd; - - - BlendState bd; - bd.render_target[0].blend_enable = true; - bd.render_target[0].src_blend = Blend::SRC_ALPHA; - bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ONE; - bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - bd.independent_blend_enable = false; - blendStates[BLENDMODE_ALPHA] = bd; - - bd.render_target[0].blend_enable = true; - bd.render_target[0].src_blend = Blend::SRC_ALPHA; - bd.render_target[0].dest_blend = Blend::ONE; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ZERO; - bd.render_target[0].dest_blend_alpha = Blend::ONE; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - bd.independent_blend_enable = false; - blendStates[BLENDMODE_ADDITIVE] = bd; - - bd.render_target[0].blend_enable = true; - bd.render_target[0].src_blend = Blend::ONE; - bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ONE; - bd.render_target[0].dest_blend_alpha = Blend::ONE; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - bd.independent_blend_enable = false; - blendStates[BLENDMODE_PREMULTIPLIED] = bd; - - bd.render_target[0].blend_enable = false; - blendStates[BLENDMODE_OPAQUE] = bd; - - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiEmittedParticle_Internal::LoadShaders(); }); - wiEmittedParticle_Internal::LoadShaders(); - - wiBackLog::post("wiEmittedParticle Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); -} - - -void wiEmittedParticle::Serialize(wiArchive& archive, wiECS::EntitySerializer& seri) -{ - if (archive.IsReadMode()) - { - archive >> _flags; - archive >> (uint32_t&)shaderType; - wiECS::SerializeEntity(archive, meshID, seri); - archive >> MAX_PARTICLES; - archive >> FIXED_TIMESTEP; - archive >> size; - archive >> random_factor; - archive >> normal_factor; - archive >> count; - archive >> life; - archive >> random_life; - archive >> scaleX; - archive >> scaleY; - archive >> rotation; - archive >> motionBlurAmount; - archive >> mass; - archive >> SPH_h; - archive >> SPH_K; - archive >> SPH_p0; - archive >> SPH_e; - - if (archive.GetVersion() >= 45) - { - archive >> framesX; - archive >> framesY; - archive >> frameCount; - archive >> frameStart; - archive >> frameRate; - } - - if (archive.GetVersion() == 48) - { - uint8_t shadingRate; - archive >> shadingRate; // no longer needed - } - - if (archive.GetVersion() >= 64) - { - archive >> velocity; - archive >> gravity; - archive >> drag; - archive >> random_color; - } - else - { - if (IsSPHEnabled()) - { - gravity = XMFLOAT3(0, -9.8f * 2, 0); - drag = 0.98f; + archive << velocity; + archive << gravity; + archive << drag; + archive << random_color; } } } - else - { - archive << _flags; - archive << (uint32_t)shaderType; - wiECS::SerializeEntity(archive, meshID, seri); - archive << MAX_PARTICLES; - archive << FIXED_TIMESTEP; - archive << size; - archive << random_factor; - archive << normal_factor; - archive << count; - archive << life; - archive << random_life; - archive << scaleX; - archive << scaleY; - archive << rotation; - archive << motionBlurAmount; - archive << mass; - archive << SPH_h; - archive << SPH_K; - archive << SPH_p0; - archive << SPH_e; - - if (archive.GetVersion() >= 45) - { - archive << framesX; - archive << framesY; - archive << frameCount; - archive << frameStart; - archive << frameRate; - } - - if (archive.GetVersion() >= 64) - { - archive << velocity; - archive << gravity; - archive << drag; - archive << random_color; - } - } -} } diff --git a/WickedEngine/wiEmittedParticle.h b/WickedEngine/wiEmittedParticle.h index 73a6c0ce1..04ba09997 100644 --- a/WickedEngine/wiEmittedParticle.h +++ b/WickedEngine/wiEmittedParticle.h @@ -1,155 +1,157 @@ #pragma once #include "CommonInclude.h" #include "wiGraphicsDevice.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "shaders/ShaderInterop_EmittedParticle.h" #include "wiEnums.h" #include "wiMath.h" -#include "wiScene_Decl.h" #include "wiECS.h" +#include "wiScene_Decl.h" #include -class wiArchive; - -namespace wiScene +namespace wi { + class Archive; +} -class wiEmittedParticle +namespace wi { -public: - - // This is serialized, order of enums shouldn't change! - enum PARTICLESHADERTYPE + class EmittedParticleSystem { - SOFT, - SOFT_DISTORTION, - SIMPLE, - SOFT_LIGHTING, - PARTICLESHADERTYPE_COUNT, - ENUM_FORCE_UINT32 = 0xFFFFFFFF, + public: + + // This is serialized, order of enums shouldn't change! + enum PARTICLESHADERTYPE + { + SOFT, + SOFT_DISTORTION, + SIMPLE, + SOFT_LIGHTING, + PARTICLESHADERTYPE_COUNT, + ENUM_FORCE_UINT32 = 0xFFFFFFFF, + }; + + ParticleCounters statistics = {}; + wi::graphics::GPUBuffer statisticsReadbackBuffer[wi::graphics::GraphicsDevice::GetBufferCount() + 1]; + + wi::graphics::GPUBuffer particleBuffer; + wi::graphics::GPUBuffer aliveList[2]; + wi::graphics::GPUBuffer deadList; + wi::graphics::GPUBuffer distanceBuffer; // for sorting + wi::graphics::GPUBuffer sphPartitionCellIndices; // for SPH + wi::graphics::GPUBuffer sphPartitionCellOffsets; // for SPH + wi::graphics::GPUBuffer densityBuffer; // for SPH + wi::graphics::GPUBuffer counterBuffer; + wi::graphics::GPUBuffer indirectBuffers; // kickoffUpdate, simulation, draw + wi::graphics::GPUBuffer constantBuffer; + wi::graphics::GPUBuffer vertexBuffer_POS; + wi::graphics::GPUBuffer vertexBuffer_TEX; + wi::graphics::GPUBuffer vertexBuffer_TEX2; + wi::graphics::GPUBuffer vertexBuffer_COL; + wi::graphics::GPUBuffer primitiveBuffer; // raytracing + wi::graphics::GPUBuffer culledIndirectionBuffer; // rasterization + wi::graphics::GPUBuffer culledIndirectionBuffer2; // rasterization + wi::graphics::GPUBuffer subsetBuffer; + + wi::graphics::RaytracingAccelerationStructure BLAS; + + private: + void CreateSelfBuffers(); + + float emit = 0.0f; + int burst = 0; + + uint32_t MAX_PARTICLES = 1000; + + public: + void UpdateCPU(const wi::scene::TransformComponent& transform, float dt); + void Burst(int num); + void Restart(); + + // Must have a transform and material component, but mesh is optional + void UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const wi::scene::TransformComponent& transform, const wi::scene::MeshComponent* mesh, wi::graphics::CommandList cmd) const; + void Draw(const wi::scene::MaterialComponent& material, wi::graphics::CommandList cmd) const; + + ParticleCounters GetStatistics() { return statistics; } + + enum FLAGS + { + FLAG_EMPTY = 0, + FLAG_DEBUG = 1 << 0, + FLAG_PAUSED = 1 << 1, + FLAG_SORTING = 1 << 2, + FLAG_DEPTHCOLLISION = 1 << 3, + FLAG_SPH_FLUIDSIMULATION = 1 << 4, + FLAG_HAS_VOLUME = 1 << 5, + FLAG_FRAME_BLENDING = 1 << 6, + }; + uint32_t _flags = FLAG_EMPTY; + + PARTICLESHADERTYPE shaderType = SOFT; + + wi::ecs::Entity meshID = wi::ecs::INVALID_ENTITY; + + float FIXED_TIMESTEP = -1.0f; // -1 : variable timestep; >=0 : fixed timestep + + float size = 1.0f; + float random_factor = 1.0f; + float normal_factor = 1.0f; + float count = 0.0f; + float life = 1.0f; + float random_life = 1.0f; + float scaleX = 1.0f; + float scaleY = 1.0f; + float rotation = 0.0f; + float motionBlurAmount = 0.0f; + float mass = 1.0f; + float random_color = 0; + + XMFLOAT3 velocity = {}; // starting velocity of all new particles + XMFLOAT3 gravity = {}; // constant gravity force + float drag = 1.0f; // constant drag (per frame velocity multiplier, reducing it will make particles slow down over time) + + float SPH_h = 1.0f; // smoothing radius + float SPH_K = 250.0f; // pressure constant + float SPH_p0 = 1.0f; // reference density + float SPH_e = 0.018f; // viscosity constant + + // Sprite sheet properties: + uint32_t framesX = 1; + uint32_t framesY = 1; + uint32_t frameCount = 1; + uint32_t frameStart = 0; + float frameRate = 0; // frames per second + + void SetMaxParticleCount(uint32_t value); + uint32_t GetMaxParticleCount() const { return MAX_PARTICLES; } + uint64_t GetMemorySizeInBytes() const; + + // Non-serialized attributes: + XMFLOAT3 center; + uint32_t statisticsReadBackIndex = 0; + uint32_t layerMask = ~0u; + + inline bool IsDebug() const { return _flags & FLAG_DEBUG; } + inline bool IsPaused() const { return _flags & FLAG_PAUSED; } + inline bool IsSorted() const { return _flags & FLAG_SORTING; } + inline bool IsDepthCollisionEnabled() const { return _flags & FLAG_DEPTHCOLLISION; } + inline bool IsSPHEnabled() const { return _flags & FLAG_SPH_FLUIDSIMULATION; } + inline bool IsVolumeEnabled() const { return _flags & FLAG_HAS_VOLUME; } + inline bool IsFrameBlendingEnabled() const { return _flags & FLAG_FRAME_BLENDING; } + + inline void SetDebug(bool value) { if (value) { _flags |= FLAG_DEBUG; } else { _flags &= ~FLAG_DEBUG; } } + inline void SetPaused(bool value) { if (value) { _flags |= FLAG_PAUSED; } else { _flags &= ~FLAG_PAUSED; } } + inline void SetSorted(bool value) { if (value) { _flags |= FLAG_SORTING; } else { _flags &= ~FLAG_SORTING; } } + inline void SetDepthCollisionEnabled(bool value) { if (value) { _flags |= FLAG_DEPTHCOLLISION; } else { _flags &= ~FLAG_DEPTHCOLLISION; } } + inline void SetSPHEnabled(bool value) { if (value) { _flags |= FLAG_SPH_FLUIDSIMULATION; } else { _flags &= ~FLAG_SPH_FLUIDSIMULATION; } } + inline void SetVolumeEnabled(bool value) { if (value) { _flags |= FLAG_HAS_VOLUME; } else { _flags &= ~FLAG_HAS_VOLUME; } } + inline void SetFrameBlendingEnabled(bool value) { if (value) { _flags |= FLAG_FRAME_BLENDING; } else { _flags &= ~FLAG_FRAME_BLENDING; } } + + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); + + static void Initialize(); }; - ParticleCounters statistics = {}; - wiGraphics::GPUBuffer statisticsReadbackBuffer[wiGraphics::GraphicsDevice::GetBufferCount() + 1]; - - wiGraphics::GPUBuffer particleBuffer; - wiGraphics::GPUBuffer aliveList[2]; - wiGraphics::GPUBuffer deadList; - wiGraphics::GPUBuffer distanceBuffer; // for sorting - wiGraphics::GPUBuffer sphPartitionCellIndices; // for SPH - wiGraphics::GPUBuffer sphPartitionCellOffsets; // for SPH - wiGraphics::GPUBuffer densityBuffer; // for SPH - wiGraphics::GPUBuffer counterBuffer; - wiGraphics::GPUBuffer indirectBuffers; // kickoffUpdate, simulation, draw - wiGraphics::GPUBuffer constantBuffer; - wiGraphics::GPUBuffer vertexBuffer_POS; - wiGraphics::GPUBuffer vertexBuffer_TEX; - wiGraphics::GPUBuffer vertexBuffer_TEX2; - wiGraphics::GPUBuffer vertexBuffer_COL; - wiGraphics::GPUBuffer primitiveBuffer; // raytracing - wiGraphics::GPUBuffer culledIndirectionBuffer; // rasterization - wiGraphics::GPUBuffer culledIndirectionBuffer2; // rasterization - wiGraphics::GPUBuffer subsetBuffer; - - wiGraphics::RaytracingAccelerationStructure BLAS; - -private: - void CreateSelfBuffers(); - - float emit = 0.0f; - int burst = 0; - - uint32_t MAX_PARTICLES = 1000; - -public: - void UpdateCPU(const TransformComponent& transform, float dt); - void Burst(int num); - void Restart(); - - // Must have a transform and material component, but mesh is optional - void UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const TransformComponent& transform, const MeshComponent* mesh, wiGraphics::CommandList cmd) const; - void Draw(const MaterialComponent& material, wiGraphics::CommandList cmd) const; - - ParticleCounters GetStatistics() { return statistics; } - - enum FLAGS - { - FLAG_EMPTY = 0, - FLAG_DEBUG = 1 << 0, - FLAG_PAUSED = 1 << 1, - FLAG_SORTING = 1 << 2, - FLAG_DEPTHCOLLISION = 1 << 3, - FLAG_SPH_FLUIDSIMULATION = 1 << 4, - FLAG_HAS_VOLUME = 1 << 5, - FLAG_FRAME_BLENDING = 1 << 6, - }; - uint32_t _flags = FLAG_EMPTY; - - PARTICLESHADERTYPE shaderType = SOFT; - - wiECS::Entity meshID = wiECS::INVALID_ENTITY; - - float FIXED_TIMESTEP = -1.0f; // -1 : variable timestep; >=0 : fixed timestep - - float size = 1.0f; - float random_factor = 1.0f; - float normal_factor = 1.0f; - float count = 0.0f; - float life = 1.0f; - float random_life = 1.0f; - float scaleX = 1.0f; - float scaleY = 1.0f; - float rotation = 0.0f; - float motionBlurAmount = 0.0f; - float mass = 1.0f; - float random_color = 0; - - XMFLOAT3 velocity = {}; // starting velocity of all new particles - XMFLOAT3 gravity = {}; // constant gravity force - float drag = 1.0f; // constant drag (per frame velocity multiplier, reducing it will make particles slow down over time) - - float SPH_h = 1.0f; // smoothing radius - float SPH_K = 250.0f; // pressure constant - float SPH_p0 = 1.0f; // reference density - float SPH_e = 0.018f; // viscosity constant - - // Sprite sheet properties: - uint32_t framesX = 1; - uint32_t framesY = 1; - uint32_t frameCount = 1; - uint32_t frameStart = 0; - float frameRate = 0; // frames per second - - void SetMaxParticleCount(uint32_t value); - uint32_t GetMaxParticleCount() const { return MAX_PARTICLES; } - uint64_t GetMemorySizeInBytes() const; - - // Non-serialized attributes: - XMFLOAT3 center; - uint32_t statisticsReadBackIndex = 0; - uint32_t layerMask = ~0u; - - inline bool IsDebug() const { return _flags & FLAG_DEBUG; } - inline bool IsPaused() const { return _flags & FLAG_PAUSED; } - inline bool IsSorted() const { return _flags & FLAG_SORTING; } - inline bool IsDepthCollisionEnabled() const { return _flags & FLAG_DEPTHCOLLISION; } - inline bool IsSPHEnabled() const { return _flags & FLAG_SPH_FLUIDSIMULATION; } - inline bool IsVolumeEnabled() const { return _flags & FLAG_HAS_VOLUME; } - inline bool IsFrameBlendingEnabled() const { return _flags & FLAG_FRAME_BLENDING; } - - inline void SetDebug(bool value) { if (value) { _flags |= FLAG_DEBUG; } else { _flags &= ~FLAG_DEBUG; } } - inline void SetPaused(bool value) { if (value) { _flags |= FLAG_PAUSED; } else { _flags &= ~FLAG_PAUSED; } } - inline void SetSorted(bool value) { if (value) { _flags |= FLAG_SORTING; } else { _flags &= ~FLAG_SORTING; } } - inline void SetDepthCollisionEnabled(bool value) { if (value) { _flags |= FLAG_DEPTHCOLLISION; } else { _flags &= ~FLAG_DEPTHCOLLISION; } } - inline void SetSPHEnabled(bool value) { if (value) { _flags |= FLAG_SPH_FLUIDSIMULATION; } else { _flags &= ~FLAG_SPH_FLUIDSIMULATION; } } - inline void SetVolumeEnabled(bool value) { if (value) { _flags |= FLAG_HAS_VOLUME; } else { _flags &= ~FLAG_HAS_VOLUME; } } - inline void SetFrameBlendingEnabled(bool value) { if (value) { _flags |= FLAG_FRAME_BLENDING; } else { _flags &= ~FLAG_FRAME_BLENDING; } } - - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); - - static void Initialize(); -}; - } diff --git a/WickedEngine/wiEnums.h b/WickedEngine/wiEnums.h index e010e33f8..0e087b0b9 100644 --- a/WickedEngine/wiEnums.h +++ b/WickedEngine/wiEnums.h @@ -1,433 +1,428 @@ #pragma once -// Common blendmodes used across multiple systems -enum BLENDMODE +namespace wi::enums { - BLENDMODE_OPAQUE, - BLENDMODE_ALPHA, - BLENDMODE_PREMULTIPLIED, - BLENDMODE_ADDITIVE, - BLENDMODE_MULTIPLY, - BLENDMODE_COUNT -}; + // Common blendmodes used across multiple systems + enum BLENDMODE + { + BLENDMODE_OPAQUE, + BLENDMODE_ALPHA, + BLENDMODE_PREMULTIPLIED, + BLENDMODE_ADDITIVE, + BLENDMODE_MULTIPLY, + BLENDMODE_COUNT + }; -enum GBUFFER -{ - GBUFFER_PRIMITIVEID, - GBUFFER_VELOCITY, - GBUFFER_COUNT -}; + // Do not alter order or value because it is bound to lua manually! + enum RENDERTYPE + { + RENDERTYPE_VOID = 0, + RENDERTYPE_OPAQUE = 1 << 0, + RENDERTYPE_TRANSPARENT = 1 << 1, + RENDERTYPE_WATER = 1 << 2, + RENDERTYPE_ALL = RENDERTYPE_OPAQUE | RENDERTYPE_TRANSPARENT | RENDERTYPE_WATER + }; -// Do not alter order or value because it is bound to lua manually! -enum RENDERTYPE -{ - RENDERTYPE_VOID = 0, - RENDERTYPE_OPAQUE = 1 << 0, - RENDERTYPE_TRANSPARENT = 1 << 1, - RENDERTYPE_WATER = 1 << 2, - RENDERTYPE_ALL = RENDERTYPE_OPAQUE | RENDERTYPE_TRANSPARENT | RENDERTYPE_WATER -}; + enum RENDERPASS + { + RENDERPASS_MAIN, + RENDERPASS_PREPASS, + RENDERPASS_ENVMAPCAPTURE, + RENDERPASS_SHADOW, + RENDERPASS_SHADOWCUBE, + RENDERPASS_VOXELIZE, + RENDERPASS_COUNT + }; -enum RENDERPASS -{ - RENDERPASS_MAIN, - RENDERPASS_PREPASS, - RENDERPASS_ENVMAPCAPTURE, - RENDERPASS_SHADOW, - RENDERPASS_SHADOWCUBE, - RENDERPASS_VOXELIZE, - RENDERPASS_COUNT -}; + // There are two different kinds of stencil refs: + // ENGINE : managed by the engine systems (STENCILREF enum values between 0-15) + // USER : managed by the user (raw numbers between 0-15) + enum STENCILREF_MASK + { + STENCILREF_MASK_ENGINE = 0x0F, + STENCILREF_MASK_USER = 0xF0, + STENCILREF_MASK_ALL = STENCILREF_MASK_ENGINE | STENCILREF_MASK_USER, + }; -// There are two different kinds of stencil refs: -// ENGINE : managed by the engine systems (STENCILREF enum values between 0-15) -// USER : managed by the user (raw numbers between 0-15) -enum STENCILREF_MASK -{ - STENCILREF_MASK_ENGINE = 0x0F, - STENCILREF_MASK_USER = 0xF0, - STENCILREF_MASK_ALL = STENCILREF_MASK_ENGINE | STENCILREF_MASK_USER, -}; + // engine stencil reference values. These can be in range of [0, 15]. + // Do not alter order or value because it is bound to lua manually! + enum STENCILREF + { + STENCILREF_EMPTY = 0, + STENCILREF_DEFAULT = 1, + STENCILREF_CUSTOMSHADER = 2, + STENCILREF_LAST = 15 + }; -// engine stencil reference values. These can be in range of [0, 15]. -// Do not alter order or value because it is bound to lua manually! -enum STENCILREF -{ - STENCILREF_EMPTY = 0, - STENCILREF_DEFAULT = 1, - STENCILREF_CUSTOMSHADER = 2, - STENCILREF_LAST = 15 -}; + // constant buffers + enum CBTYPES + { + CBTYPE_FRAME, + CBTYPE_COUNT + }; -// constant buffers -enum CBTYPES -{ - CBTYPE_FRAME, - CBTYPE_COUNT -}; + // resource buffers (StructuredBuffer, Buffer, etc.) + enum RBTYPES + { + RBTYPE_ENTITYARRAY, + RBTYPE_VOXELSCENE, + RBTYPE_MATRIXARRAY, + RBTYPE_COUNT + }; -// resource buffers (StructuredBuffer, Buffer, etc.) -enum RBTYPES -{ - RBTYPE_ENTITYARRAY, - RBTYPE_VOXELSCENE, - RBTYPE_MATRIXARRAY, - RBTYPE_COUNT -}; + // textures + enum TEXTYPES + { + TEXTYPE_3D_VOXELRADIANCE, + TEXTYPE_3D_VOXELRADIANCE_HELPER, + TEXTYPE_2D_SKYATMOSPHERE_TRANSMITTANCELUT, + TEXTYPE_2D_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT, + TEXTYPE_2D_SKYATMOSPHERE_SKYVIEWLUT, + TEXTYPE_2D_SKYATMOSPHERE_SKYLUMINANCELUT, + TEXTYPE_2D_SHEENLUT, + TEXTYPE_COUNT + }; -// textures -enum TEXTYPES -{ - TEXTYPE_3D_VOXELRADIANCE, - TEXTYPE_3D_VOXELRADIANCE_HELPER, - TEXTYPE_2D_SKYATMOSPHERE_TRANSMITTANCELUT, - TEXTYPE_2D_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT, - TEXTYPE_2D_SKYATMOSPHERE_SKYVIEWLUT, - TEXTYPE_2D_SKYATMOSPHERE_SKYLUMINANCELUT, - TEXTYPE_2D_SHEENLUT, - TEXTYPE_COUNT -}; - -// shaders -enum SHADERTYPE -{ - // vertex shaders - VSTYPE_OBJECT_DEBUG, - VSTYPE_OBJECT_COMMON, - VSTYPE_OBJECT_SIMPLE, - VSTYPE_OBJECT_PREPASS, - VSTYPE_OBJECT_PREPASS_ALPHATEST, - VSTYPE_OBJECT_COMMON_TESSELLATION, - VSTYPE_OBJECT_PREPASS_TESSELLATION, - VSTYPE_OBJECT_PREPASS_ALPHATEST_TESSELLATION, - VSTYPE_OBJECT_SIMPLE_TESSELLATION, - VSTYPE_SHADOW, - VSTYPE_SHADOW_ALPHATEST, - VSTYPE_SHADOW_TRANSPARENT, - VSTYPE_SHADOWCUBEMAPRENDER, - VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST, - VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT, - VSTYPE_IMPOSTOR, - VSTYPE_VERTEXCOLOR, - VSTYPE_VOLUMETRICLIGHT_DIRECTIONAL, - VSTYPE_VOLUMETRICLIGHT_POINT, - VSTYPE_VOLUMETRICLIGHT_SPOT, - VSTYPE_LIGHTVISUALIZER_SPOTLIGHT, - VSTYPE_LIGHTVISUALIZER_POINTLIGHT, - VSTYPE_SKY, - VSTYPE_ENVMAP, - VSTYPE_ENVMAP_SKY, - VSTYPE_SPHERE, - VSTYPE_CUBE, - VSTYPE_VOXELIZER, - VSTYPE_VOXEL, - VSTYPE_FORCEFIELDVISUALIZER_POINT, - VSTYPE_FORCEFIELDVISUALIZER_PLANE, - VSTYPE_RENDERLIGHTMAP, - VSTYPE_RAYTRACE_SCREEN, - VSTYPE_SCREEN, - VSTYPE_LENSFLARE, + // shaders + enum SHADERTYPE + { + // vertex shaders + VSTYPE_OBJECT_DEBUG, + VSTYPE_OBJECT_COMMON, + VSTYPE_OBJECT_SIMPLE, + VSTYPE_OBJECT_PREPASS, + VSTYPE_OBJECT_PREPASS_ALPHATEST, + VSTYPE_OBJECT_COMMON_TESSELLATION, + VSTYPE_OBJECT_PREPASS_TESSELLATION, + VSTYPE_OBJECT_PREPASS_ALPHATEST_TESSELLATION, + VSTYPE_OBJECT_SIMPLE_TESSELLATION, + VSTYPE_SHADOW, + VSTYPE_SHADOW_ALPHATEST, + VSTYPE_SHADOW_TRANSPARENT, + VSTYPE_SHADOWCUBEMAPRENDER, + VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST, + VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT, + VSTYPE_IMPOSTOR, + VSTYPE_VERTEXCOLOR, + VSTYPE_VOLUMETRICLIGHT_DIRECTIONAL, + VSTYPE_VOLUMETRICLIGHT_POINT, + VSTYPE_VOLUMETRICLIGHT_SPOT, + VSTYPE_LIGHTVISUALIZER_SPOTLIGHT, + VSTYPE_LIGHTVISUALIZER_POINTLIGHT, + VSTYPE_SKY, + VSTYPE_ENVMAP, + VSTYPE_ENVMAP_SKY, + VSTYPE_SPHERE, + VSTYPE_CUBE, + VSTYPE_VOXELIZER, + VSTYPE_VOXEL, + VSTYPE_FORCEFIELDVISUALIZER_POINT, + VSTYPE_FORCEFIELDVISUALIZER_PLANE, + VSTYPE_RENDERLIGHTMAP, + VSTYPE_RAYTRACE_SCREEN, + VSTYPE_SCREEN, + VSTYPE_LENSFLARE, - // pixel shaders - PSTYPE_OBJECT, - PSTYPE_OBJECT_TRANSPARENT, - PSTYPE_OBJECT_PLANARREFLECTION, - PSTYPE_OBJECT_TRANSPARENT_PLANARREFLECTION, - PSTYPE_OBJECT_POM, - PSTYPE_OBJECT_TRANSPARENT_POM, - PSTYPE_OBJECT_ANISOTROPIC, - PSTYPE_OBJECT_TRANSPARENT_ANISOTROPIC, - PSTYPE_OBJECT_CLOTH, - PSTYPE_OBJECT_TRANSPARENT_CLOTH, - PSTYPE_OBJECT_CLEARCOAT, - PSTYPE_OBJECT_TRANSPARENT_CLEARCOAT, - PSTYPE_OBJECT_CLOTH_CLEARCOAT, - PSTYPE_OBJECT_TRANSPARENT_CLOTH_CLEARCOAT, - PSTYPE_OBJECT_CARTOON, - PSTYPE_OBJECT_TRANSPARENT_CARTOON, - PSTYPE_OBJECT_UNLIT, - PSTYPE_OBJECT_TRANSPARENT_UNLIT, - PSTYPE_OBJECT_WATER, - PSTYPE_OBJECT_TERRAIN, - PSTYPE_IMPOSTOR, + // pixel shaders + PSTYPE_OBJECT, + PSTYPE_OBJECT_TRANSPARENT, + PSTYPE_OBJECT_PLANARREFLECTION, + PSTYPE_OBJECT_TRANSPARENT_PLANARREFLECTION, + PSTYPE_OBJECT_POM, + PSTYPE_OBJECT_TRANSPARENT_POM, + PSTYPE_OBJECT_ANISOTROPIC, + PSTYPE_OBJECT_TRANSPARENT_ANISOTROPIC, + PSTYPE_OBJECT_CLOTH, + PSTYPE_OBJECT_TRANSPARENT_CLOTH, + PSTYPE_OBJECT_CLEARCOAT, + PSTYPE_OBJECT_TRANSPARENT_CLEARCOAT, + PSTYPE_OBJECT_CLOTH_CLEARCOAT, + PSTYPE_OBJECT_TRANSPARENT_CLOTH_CLEARCOAT, + PSTYPE_OBJECT_CARTOON, + PSTYPE_OBJECT_TRANSPARENT_CARTOON, + PSTYPE_OBJECT_UNLIT, + PSTYPE_OBJECT_TRANSPARENT_UNLIT, + PSTYPE_OBJECT_WATER, + PSTYPE_OBJECT_TERRAIN, + PSTYPE_IMPOSTOR, - PSTYPE_OBJECT_HOLOGRAM, + PSTYPE_OBJECT_HOLOGRAM, - PSTYPE_OBJECT_DEBUG, - PSTYPE_OBJECT_PAINTRADIUS, - PSTYPE_OBJECT_SIMPLE, - PSTYPE_OBJECT_PREPASS, - PSTYPE_OBJECT_PREPASS_ALPHATEST, - PSTYPE_IMPOSTOR_PREPASS, - PSTYPE_IMPOSTOR_SIMPLE, - PSTYPE_IMPOSTOR_WIRE, + PSTYPE_OBJECT_DEBUG, + PSTYPE_OBJECT_PAINTRADIUS, + PSTYPE_OBJECT_SIMPLE, + PSTYPE_OBJECT_PREPASS, + PSTYPE_OBJECT_PREPASS_ALPHATEST, + PSTYPE_IMPOSTOR_PREPASS, + PSTYPE_IMPOSTOR_SIMPLE, + PSTYPE_IMPOSTOR_WIRE, - PSTYPE_SHADOW_ALPHATEST, - PSTYPE_SHADOW_TRANSPARENT, - PSTYPE_SHADOW_WATER, + PSTYPE_SHADOW_ALPHATEST, + PSTYPE_SHADOW_TRANSPARENT, + PSTYPE_SHADOW_WATER, - PSTYPE_VERTEXCOLOR, - PSTYPE_LIGHTVISUALIZER, - PSTYPE_VOLUMETRICLIGHT_DIRECTIONAL, - PSTYPE_VOLUMETRICLIGHT_POINT, - PSTYPE_VOLUMETRICLIGHT_SPOT, - PSTYPE_SKY_STATIC, - PSTYPE_SKY_DYNAMIC, - PSTYPE_SUN, - PSTYPE_ENVMAP, - PSTYPE_ENVMAP_TERRAIN, - PSTYPE_ENVMAP_SKY_STATIC, - PSTYPE_ENVMAP_SKY_DYNAMIC, - PSTYPE_CUBEMAP, - PSTYPE_CAPTUREIMPOSTOR_ALBEDO, - PSTYPE_CAPTUREIMPOSTOR_NORMAL, - PSTYPE_CAPTUREIMPOSTOR_SURFACE, - PSTYPE_VOXELIZER, - PSTYPE_VOXELIZER_TERRAIN, - PSTYPE_VOXEL, - PSTYPE_FORCEFIELDVISUALIZER, - PSTYPE_RENDERLIGHTMAP, - PSTYPE_RAYTRACE_DEBUGBVH, - PSTYPE_DOWNSAMPLEDEPTHBUFFER, - PSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL, - PSTYPE_POSTPROCESS_OUTLINE, - PSTYPE_LENSFLARE, + PSTYPE_VERTEXCOLOR, + PSTYPE_LIGHTVISUALIZER, + PSTYPE_VOLUMETRICLIGHT_DIRECTIONAL, + PSTYPE_VOLUMETRICLIGHT_POINT, + PSTYPE_VOLUMETRICLIGHT_SPOT, + PSTYPE_SKY_STATIC, + PSTYPE_SKY_DYNAMIC, + PSTYPE_SUN, + PSTYPE_ENVMAP, + PSTYPE_ENVMAP_TERRAIN, + PSTYPE_ENVMAP_SKY_STATIC, + PSTYPE_ENVMAP_SKY_DYNAMIC, + PSTYPE_CUBEMAP, + PSTYPE_CAPTUREIMPOSTOR_ALBEDO, + PSTYPE_CAPTUREIMPOSTOR_NORMAL, + PSTYPE_CAPTUREIMPOSTOR_SURFACE, + PSTYPE_VOXELIZER, + PSTYPE_VOXELIZER_TERRAIN, + PSTYPE_VOXEL, + PSTYPE_FORCEFIELDVISUALIZER, + PSTYPE_RENDERLIGHTMAP, + PSTYPE_RAYTRACE_DEBUGBVH, + PSTYPE_DOWNSAMPLEDEPTHBUFFER, + PSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL, + PSTYPE_POSTPROCESS_OUTLINE, + PSTYPE_LENSFLARE, - // geometry shaders - GSTYPE_SHADOWCUBEMAPRENDER_EMULATION, - GSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST_EMULATION, - GSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT_EMULATION, - GSTYPE_ENVMAP_EMULATION, - GSTYPE_ENVMAP_SKY_EMULATION, - GSTYPE_VOXELIZER, - GSTYPE_VOXEL, + // geometry shaders + GSTYPE_SHADOWCUBEMAPRENDER_EMULATION, + GSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST_EMULATION, + GSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT_EMULATION, + GSTYPE_ENVMAP_EMULATION, + GSTYPE_ENVMAP_SKY_EMULATION, + GSTYPE_VOXELIZER, + GSTYPE_VOXEL, - // hull shaders - HSTYPE_OBJECT, - HSTYPE_OBJECT_PREPASS, - HSTYPE_OBJECT_PREPASS_ALPHATEST, - HSTYPE_OBJECT_SIMPLE, + // hull shaders + HSTYPE_OBJECT, + HSTYPE_OBJECT_PREPASS, + HSTYPE_OBJECT_PREPASS_ALPHATEST, + HSTYPE_OBJECT_SIMPLE, - // domain shaders - DSTYPE_OBJECT, - DSTYPE_OBJECT_PREPASS, - DSTYPE_OBJECT_PREPASS_ALPHATEST, - DSTYPE_OBJECT_SIMPLE, + // domain shaders + DSTYPE_OBJECT, + DSTYPE_OBJECT_PREPASS, + DSTYPE_OBJECT_PREPASS_ALPHATEST, + DSTYPE_OBJECT_SIMPLE, - - // compute shaders - CSTYPE_LUMINANCE_PASS1, - CSTYPE_LUMINANCE_PASS2, - CSTYPE_SHADINGRATECLASSIFICATION, - CSTYPE_SHADINGRATECLASSIFICATION_DEBUG, - CSTYPE_TILEFRUSTUMS, - CSTYPE_LIGHTCULLING, - CSTYPE_LIGHTCULLING_DEBUG, - CSTYPE_LIGHTCULLING_ADVANCED, - CSTYPE_LIGHTCULLING_ADVANCED_DEBUG, - CSTYPE_RESOLVEMSAADEPTHSTENCIL, - CSTYPE_VOXELSCENECOPYCLEAR, - CSTYPE_VOXELSCENECOPYCLEAR_TEMPORALSMOOTHING, - CSTYPE_VOXELRADIANCESECONDARYBOUNCE, - CSTYPE_VOXELCLEARONLYNORMAL, - CSTYPE_SKYATMOSPHERE_TRANSMITTANCELUT, - CSTYPE_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT, - CSTYPE_SKYATMOSPHERE_SKYVIEWLUT, - CSTYPE_SKYATMOSPHERE_SKYLUMINANCELUT, - CSTYPE_GENERATEMIPCHAIN2D_UNORM4, - CSTYPE_GENERATEMIPCHAIN2D_FLOAT4, - CSTYPE_GENERATEMIPCHAIN3D_UNORM4, - CSTYPE_GENERATEMIPCHAIN3D_FLOAT4, - CSTYPE_GENERATEMIPCHAINCUBE_UNORM4, - CSTYPE_GENERATEMIPCHAINCUBE_FLOAT4, - CSTYPE_GENERATEMIPCHAINCUBEARRAY_UNORM4, - CSTYPE_GENERATEMIPCHAINCUBEARRAY_FLOAT4, - CSTYPE_FILTERENVMAP, - CSTYPE_COPYTEXTURE2D_UNORM4, - CSTYPE_COPYTEXTURE2D_FLOAT4, - CSTYPE_COPYTEXTURE2D_UNORM4_BORDEREXPAND, - CSTYPE_COPYTEXTURE2D_FLOAT4_BORDEREXPAND, - CSTYPE_SKINNING, - CSTYPE_RAYTRACE, - CSTYPE_PAINT_TEXTURE, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT1, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT3, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT4, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM1, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM4, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT1, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT3, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT4, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM1, - CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM4, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT1, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT3, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT4, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM1, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM4, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT1, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT3, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT4, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM1, - CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM4, - CSTYPE_POSTPROCESS_SSAO, - CSTYPE_POSTPROCESS_HBAO, - CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS1, - CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS2, - CSTYPE_POSTPROCESS_MSAO_INTERLEAVE, - CSTYPE_POSTPROCESS_MSAO, - CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE, - CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_BLENDOUT, - CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN, - CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN_BLENDOUT, - CSTYPE_POSTPROCESS_SSR_RAYTRACE, - CSTYPE_POSTPROCESS_SSR_RESOLVE, - CSTYPE_POSTPROCESS_SSR_TEMPORAL, - CSTYPE_POSTPROCESS_SSR_MEDIAN, - CSTYPE_POSTPROCESS_LIGHTSHAFTS, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_HORIZONTAL, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_VERTICAL, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_NEIGHBORHOODMAXCOC, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_KICKJOBS, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS_EARLYEXIT, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_EARLYEXIT, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_CHEAP, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_POSTFILTER, - CSTYPE_POSTPROCESS_DEPTHOFFIELD_UPSAMPLE, - CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_HORIZONTAL, - CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_VERTICAL, - CSTYPE_POSTPROCESS_MOTIONBLUR_NEIGHBORHOODMAXVELOCITY, - CSTYPE_POSTPROCESS_MOTIONBLUR_KICKJOBS, - CSTYPE_POSTPROCESS_MOTIONBLUR, - CSTYPE_POSTPROCESS_MOTIONBLUR_EARLYEXIT, - CSTYPE_POSTPROCESS_MOTIONBLUR_CHEAP, - CSTYPE_POSTPROCESS_BLOOMSEPARATE, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_SHAPENOISE, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_DETAILNOISE, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_CURLNOISE, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_WEATHERMAP, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_RENDER, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_REPROJECT, - CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_TEMPORAL, - CSTYPE_POSTPROCESS_FXAA, - CSTYPE_POSTPROCESS_TEMPORALAA, - CSTYPE_POSTPROCESS_SHARPEN, - CSTYPE_POSTPROCESS_TONEMAP, - CSTYPE_POSTPROCESS_FSR_UPSCALING, - CSTYPE_POSTPROCESS_FSR_SHARPEN, - CSTYPE_POSTPROCESS_CHROMATIC_ABERRATION, - CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT1, - CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM1, - CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT4, - CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM4, - CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UINT4, - CSTYPE_POSTPROCESS_DOWNSAMPLE4X, - CSTYPE_POSTPROCESS_NORMALSFROMDEPTH, - CSTYPE_POSTPROCESS_SCREENSPACESHADOW, - CSTYPE_POSTPROCESS_RTSHADOW, - CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TILECLASSIFICATION, - CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_FILTER, - CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TEMPORAL, - CSTYPE_POSTPROCESS_RTAO, - CSTYPE_POSTPROCESS_RTAO_DENOISE_TILECLASSIFICATION, - CSTYPE_POSTPROCESS_RTAO_DENOISE_FILTER, - CSTYPE_SURFEL_COVERAGE, - CSTYPE_SURFEL_INDIRECTPREPARE, - CSTYPE_SURFEL_RAYTRACE, - CSTYPE_SURFEL_UPDATE, - CSTYPE_SURFEL_GRIDRESET, - CSTYPE_SURFEL_GRIDOFFSETS, - CSTYPE_SURFEL_BINNING, - CSTYPE_VISIBILITY_RESOLVE, - CSTYPE_VISIBILITY_RESOLVE_MSAA, + + // compute shaders + CSTYPE_LUMINANCE_PASS1, + CSTYPE_LUMINANCE_PASS2, + CSTYPE_SHADINGRATECLASSIFICATION, + CSTYPE_SHADINGRATECLASSIFICATION_DEBUG, + CSTYPE_TILEFRUSTUMS, + CSTYPE_LIGHTCULLING, + CSTYPE_LIGHTCULLING_DEBUG, + CSTYPE_LIGHTCULLING_ADVANCED, + CSTYPE_LIGHTCULLING_ADVANCED_DEBUG, + CSTYPE_RESOLVEMSAADEPTHSTENCIL, + CSTYPE_VOXELSCENECOPYCLEAR, + CSTYPE_VOXELSCENECOPYCLEAR_TEMPORALSMOOTHING, + CSTYPE_VOXELRADIANCESECONDARYBOUNCE, + CSTYPE_VOXELCLEARONLYNORMAL, + CSTYPE_SKYATMOSPHERE_TRANSMITTANCELUT, + CSTYPE_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT, + CSTYPE_SKYATMOSPHERE_SKYVIEWLUT, + CSTYPE_SKYATMOSPHERE_SKYLUMINANCELUT, + CSTYPE_GENERATEMIPCHAIN2D_UNORM4, + CSTYPE_GENERATEMIPCHAIN2D_FLOAT4, + CSTYPE_GENERATEMIPCHAIN3D_UNORM4, + CSTYPE_GENERATEMIPCHAIN3D_FLOAT4, + CSTYPE_GENERATEMIPCHAINCUBE_UNORM4, + CSTYPE_GENERATEMIPCHAINCUBE_FLOAT4, + CSTYPE_GENERATEMIPCHAINCUBEARRAY_UNORM4, + CSTYPE_GENERATEMIPCHAINCUBEARRAY_FLOAT4, + CSTYPE_FILTERENVMAP, + CSTYPE_COPYTEXTURE2D_UNORM4, + CSTYPE_COPYTEXTURE2D_FLOAT4, + CSTYPE_COPYTEXTURE2D_UNORM4_BORDEREXPAND, + CSTYPE_COPYTEXTURE2D_FLOAT4_BORDEREXPAND, + CSTYPE_SKINNING, + CSTYPE_RAYTRACE, + CSTYPE_PAINT_TEXTURE, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT1, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT3, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT4, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM1, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM4, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT1, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT3, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT4, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM1, + CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM4, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT1, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT3, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT4, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM1, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM4, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT1, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT3, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT4, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM1, + CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM4, + CSTYPE_POSTPROCESS_SSAO, + CSTYPE_POSTPROCESS_HBAO, + CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS1, + CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS2, + CSTYPE_POSTPROCESS_MSAO_INTERLEAVE, + CSTYPE_POSTPROCESS_MSAO, + CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE, + CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_BLENDOUT, + CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN, + CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN_BLENDOUT, + CSTYPE_POSTPROCESS_SSR_RAYTRACE, + CSTYPE_POSTPROCESS_SSR_RESOLVE, + CSTYPE_POSTPROCESS_SSR_TEMPORAL, + CSTYPE_POSTPROCESS_SSR_MEDIAN, + CSTYPE_POSTPROCESS_LIGHTSHAFTS, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_HORIZONTAL, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_VERTICAL, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_NEIGHBORHOODMAXCOC, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_KICKJOBS, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS_EARLYEXIT, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_EARLYEXIT, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_CHEAP, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_POSTFILTER, + CSTYPE_POSTPROCESS_DEPTHOFFIELD_UPSAMPLE, + CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_HORIZONTAL, + CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_VERTICAL, + CSTYPE_POSTPROCESS_MOTIONBLUR_NEIGHBORHOODMAXVELOCITY, + CSTYPE_POSTPROCESS_MOTIONBLUR_KICKJOBS, + CSTYPE_POSTPROCESS_MOTIONBLUR, + CSTYPE_POSTPROCESS_MOTIONBLUR_EARLYEXIT, + CSTYPE_POSTPROCESS_MOTIONBLUR_CHEAP, + CSTYPE_POSTPROCESS_BLOOMSEPARATE, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_SHAPENOISE, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_DETAILNOISE, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_CURLNOISE, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_WEATHERMAP, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_RENDER, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_REPROJECT, + CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_TEMPORAL, + CSTYPE_POSTPROCESS_FXAA, + CSTYPE_POSTPROCESS_TEMPORALAA, + CSTYPE_POSTPROCESS_SHARPEN, + CSTYPE_POSTPROCESS_TONEMAP, + CSTYPE_POSTPROCESS_FSR_UPSCALING, + CSTYPE_POSTPROCESS_FSR_SHARPEN, + CSTYPE_POSTPROCESS_CHROMATIC_ABERRATION, + CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT1, + CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM1, + CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT4, + CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM4, + CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UINT4, + CSTYPE_POSTPROCESS_DOWNSAMPLE4X, + CSTYPE_POSTPROCESS_NORMALSFROMDEPTH, + CSTYPE_POSTPROCESS_SCREENSPACESHADOW, + CSTYPE_POSTPROCESS_RTSHADOW, + CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TILECLASSIFICATION, + CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_FILTER, + CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TEMPORAL, + CSTYPE_POSTPROCESS_RTAO, + CSTYPE_POSTPROCESS_RTAO_DENOISE_TILECLASSIFICATION, + CSTYPE_POSTPROCESS_RTAO_DENOISE_FILTER, + CSTYPE_SURFEL_COVERAGE, + CSTYPE_SURFEL_INDIRECTPREPARE, + CSTYPE_SURFEL_RAYTRACE, + CSTYPE_SURFEL_UPDATE, + CSTYPE_SURFEL_GRIDRESET, + CSTYPE_SURFEL_GRIDOFFSETS, + CSTYPE_SURFEL_BINNING, + CSTYPE_VISIBILITY_RESOLVE, + CSTYPE_VISIBILITY_RESOLVE_MSAA, - // raytracing pipelines: - RTTYPE_RTREFLECTION, + // raytracing pipelines: + RTTYPE_RTREFLECTION, - SHADERTYPE_COUNT, -}; + SHADERTYPE_COUNT, + }; -// input layouts -enum ILTYPES -{ - ILTYPE_OBJECT_DEBUG, - ILTYPE_RENDERLIGHTMAP, - ILTYPE_VERTEXCOLOR, - ILTYPE_COUNT -}; -// rasterizer states -enum RSTYPES -{ - RSTYPE_FRONT, - RSTYPE_BACK, - RSTYPE_DOUBLESIDED, - RSTYPE_WIRE, - RSTYPE_WIRE_SMOOTH, - RSTYPE_WIRE_DOUBLESIDED, - RSTYPE_WIRE_DOUBLESIDED_SMOOTH, - RSTYPE_SHADOW, - RSTYPE_SHADOW_DOUBLESIDED, - RSTYPE_OCCLUDEE, - RSTYPE_VOXELIZE, - RSTYPE_SKY, - RSTYPE_COUNT -}; -// depth-stencil states -enum DSSTYPES -{ - DSSTYPE_DEFAULT, - DSSTYPE_SHADOW, - DSSTYPE_DEPTHDISABLED, - DSSTYPE_DEPTHREAD, - DSSTYPE_DEPTHREADEQUAL, - DSSTYPE_ENVMAP, - DSSTYPE_CAPTUREIMPOSTOR, - DSSTYPE_WRITEONLY, - DSSTYPE_HOLOGRAM, - DSSTYPE_COUNT -}; -// blend states -enum BSTYPES -{ - BSTYPE_OPAQUE, - BSTYPE_TRANSPARENT, - BSTYPE_INVERSE, - BSTYPE_ADDITIVE, - BSTYPE_PREMULTIPLIED, - BSTYPE_COLORWRITEDISABLE, - BSTYPE_DECAL, - BSTYPE_MULTIPLY, - BSTYPE_TRANSPARENTSHADOW, - BSTYPE_COUNT -}; + // input layouts + enum ILTYPES + { + ILTYPE_OBJECT_DEBUG, + ILTYPE_RENDERLIGHTMAP, + ILTYPE_VERTEXCOLOR, + ILTYPE_COUNT + }; + // rasterizer states + enum RSTYPES + { + RSTYPE_FRONT, + RSTYPE_BACK, + RSTYPE_DOUBLESIDED, + RSTYPE_WIRE, + RSTYPE_WIRE_SMOOTH, + RSTYPE_WIRE_DOUBLESIDED, + RSTYPE_WIRE_DOUBLESIDED_SMOOTH, + RSTYPE_SHADOW, + RSTYPE_SHADOW_DOUBLESIDED, + RSTYPE_OCCLUDEE, + RSTYPE_VOXELIZE, + RSTYPE_SKY, + RSTYPE_COUNT + }; + // depth-stencil states + enum DSSTYPES + { + DSSTYPE_DEFAULT, + DSSTYPE_SHADOW, + DSSTYPE_DEPTHDISABLED, + DSSTYPE_DEPTHREAD, + DSSTYPE_DEPTHREADEQUAL, + DSSTYPE_ENVMAP, + DSSTYPE_CAPTUREIMPOSTOR, + DSSTYPE_WRITEONLY, + DSSTYPE_HOLOGRAM, + DSSTYPE_COUNT + }; + // blend states + enum BSTYPES + { + BSTYPE_OPAQUE, + BSTYPE_TRANSPARENT, + BSTYPE_ADDITIVE, + BSTYPE_PREMULTIPLIED, + BSTYPE_COLORWRITEDISABLE, + BSTYPE_MULTIPLY, + BSTYPE_TRANSPARENTSHADOW, + BSTYPE_COUNT + }; -enum SAMPLERTYPES -{ - // Can be changed by user - SAMPLER_OBJECTSHADER, + enum SAMPLERTYPES + { + // Can be changed by user + SAMPLER_OBJECTSHADER, - // Persistent samplers - // These are bound once and are alive forever - SAMPLER_LINEAR_CLAMP, - SAMPLER_LINEAR_WRAP, - SAMPLER_LINEAR_MIRROR, - SAMPLER_POINT_CLAMP, - SAMPLER_POINT_WRAP, - SAMPLER_POINT_MIRROR, - SAMPLER_ANISO_CLAMP, - SAMPLER_ANISO_WRAP, - SAMPLER_ANISO_MIRROR, - SAMPLER_CMP_DEPTH, + // Persistent samplers + // These are bound once and are alive forever + SAMPLER_LINEAR_CLAMP, + SAMPLER_LINEAR_WRAP, + SAMPLER_LINEAR_MIRROR, + SAMPLER_POINT_CLAMP, + SAMPLER_POINT_WRAP, + SAMPLER_POINT_MIRROR, + SAMPLER_ANISO_CLAMP, + SAMPLER_ANISO_WRAP, + SAMPLER_ANISO_MIRROR, + SAMPLER_CMP_DEPTH, - SAMPLER_COUNT, -}; + SAMPLER_COUNT, + }; + +} diff --git a/WickedEngine/wiEvent.cpp b/WickedEngine/wiEventHandler.cpp similarity index 97% rename from WickedEngine/wiEvent.cpp rename to WickedEngine/wiEventHandler.cpp index 04f1048ad..fd109e690 100644 --- a/WickedEngine/wiEvent.cpp +++ b/WickedEngine/wiEventHandler.cpp @@ -1,11 +1,11 @@ -#include "wiEvent.h" +#include "wiEventHandler.h" #include "wiUnorderedMap.h" #include "wiVector.h" #include #include -namespace wiEvent +namespace wi::eventhandler { struct EventManager { diff --git a/WickedEngine/wiEvent.h b/WickedEngine/wiEventHandler.h similarity index 67% rename from WickedEngine/wiEvent.h rename to WickedEngine/wiEventHandler.h index 306b705f9..91a0d1f71 100644 --- a/WickedEngine/wiEvent.h +++ b/WickedEngine/wiEventHandler.h @@ -4,12 +4,12 @@ #include #include -static const int SYSTEM_EVENT_THREAD_SAFE_POINT = -1; -static const int SYSTEM_EVENT_RELOAD_SHADERS = -2; -static const int SYSTEM_EVENT_SET_VSYNC = -3; - -namespace wiEvent +namespace wi::eventhandler { + static constexpr int EVENT_THREAD_SAFE_POINT = -1; + static constexpr int EVENT_RELOAD_SHADERS = -2; + static constexpr int EVENT_SET_VSYNC = -3; + struct Handle { std::shared_ptr internal_state; @@ -24,7 +24,6 @@ namespace wiEvent // helper event wrappers can be placed below: inline void SetVSync(bool enabled) { - wiEvent::FireEvent(SYSTEM_EVENT_SET_VSYNC, enabled ? 1ull : 0ull); + FireEvent(EVENT_SET_VSYNC, enabled ? 1ull : 0ull); } } - diff --git a/WickedEngine/wiFFTGenerator.cpp b/WickedEngine/wiFFTGenerator.cpp index 17382a611..75805c517 100644 --- a/WickedEngine/wiFFTGenerator.cpp +++ b/WickedEngine/wiFFTGenerator.cpp @@ -7,9 +7,9 @@ #include #include -using namespace wiGraphics; +using namespace wi::graphics; -namespace wiFFTGenerator +namespace wi::fftgenerator { Shader radix008A_CS; Shader radix008A_CS2; @@ -33,7 +33,7 @@ namespace wiFFTGenerator // Setup execution configuration uint32_t grid = thread_count / COHERENCY_GRANULARITY; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); // Buffers const GPUResource* srvs[1] = { &pSRV_Src }; @@ -71,7 +71,7 @@ namespace wiFFTGenerator CommandList cmd) { const uint32_t thread_count = fft_plan.slices * (512 * 512) / 8; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); const GPUBuffer* cs_cbs; uint32_t istride = 512 * 512 / 8; @@ -168,7 +168,7 @@ namespace wiFFTGenerator void fft512x512_create_plan(CSFFT512x512_Plan& plan, uint32_t slices) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); plan.slices = slices; @@ -189,8 +189,8 @@ namespace wiFFTGenerator void LoadShaders() { - wiRenderer::LoadShader(ShaderStage::CS, radix008A_CS, "fft_512x512_c2c_CS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, radix008A_CS2, "fft_512x512_c2c_v2_CS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, radix008A_CS, "fft_512x512_c2c_CS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, radix008A_CS2, "fft_512x512_c2c_v2_CS.cso"); } } diff --git a/WickedEngine/wiFFTGenerator.h b/WickedEngine/wiFFTGenerator.h index 939bd9de8..97ce22682 100644 --- a/WickedEngine/wiFFTGenerator.h +++ b/WickedEngine/wiFFTGenerator.h @@ -2,7 +2,7 @@ #include "CommonInclude.h" #include "wiGraphicsDevice.h" -namespace wiFFTGenerator +namespace wi::fftgenerator { struct CSFFT512x512_Plan @@ -11,9 +11,9 @@ namespace wiFFTGenerator uint32_t slices; // For 512x512 config, we need 6 constant buffers - wiGraphics::GPUBuffer pRadix008A_CB[6]; + wi::graphics::GPUBuffer pRadix008A_CB[6]; - wiGraphics::GPUBuffer pBuffer_Tmp; + wi::graphics::GPUBuffer pBuffer_Tmp; }; @@ -21,10 +21,10 @@ namespace wiFFTGenerator void fft_512x512_c2c( const CSFFT512x512_Plan& fft_plan, - const wiGraphics::GPUResource& pUAV_Dst, - const wiGraphics::GPUResource& pSRV_Dst, - const wiGraphics::GPUResource& pSRV_Src, - wiGraphics::CommandList cmd); + const wi::graphics::GPUResource& pUAV_Dst, + const wi::graphics::GPUResource& pSRV_Dst, + const wi::graphics::GPUResource& pSRV_Src, + wi::graphics::CommandList cmd); void LoadShaders(); } diff --git a/WickedEngine/wiFadeManager.cpp b/WickedEngine/wiFadeManager.cpp index 11f9b55de..34d6f0bda 100644 --- a/WickedEngine/wiFadeManager.cpp +++ b/WickedEngine/wiFadeManager.cpp @@ -1,55 +1,60 @@ #include "wiFadeManager.h" -void wiFadeManager::Clear() +namespace wi { - opacity = 0; - state = FADE_FINISHED; -} -void wiFadeManager::Update(float dt) -{ - if (!IsActive()) - return; - - if (targetFadeTimeInSeconds <= 0) + void FadeManager::Clear() { - // skip fade, just launch the job - onFade(); + opacity = 0; state = FADE_FINISHED; } - float t = timer / targetFadeTimeInSeconds; - timer += wiMath::Clamp(dt, 0, 0.033f); + void FadeManager::Update(float dt) + { + if (!IsActive()) + return; - if (state == FADE_IN) - { - opacity = wiMath::Lerp(0.0f, 1.0f, t); - if (t >= 1.0f) - { - state = FADE_MID; - opacity = 1.0f; - } - } - else if (state == FADE_MID) - { - state = FADE_OUT; - opacity = 1.0f; - onFade(); - timer = 0; - } - else if (state == FADE_OUT) - { - opacity = wiMath::Lerp(1.0f, 0.0f, t); - if (t >= 1.0f) + if (targetFadeTimeInSeconds <= 0) { + // skip fade, just launch the job + onFade(); state = FADE_FINISHED; - opacity = 0.0f; } - } - else if (state == FADE_FINISHED) - { - opacity = 0.0f; - onFade = [] {}; + + float t = timer / targetFadeTimeInSeconds; + timer += wi::math::Clamp(dt, 0, 0.033f); + + if (state == FADE_IN) + { + opacity = wi::math::Lerp(0.0f, 1.0f, t); + if (t >= 1.0f) + { + state = FADE_MID; + opacity = 1.0f; + } + } + else if (state == FADE_MID) + { + state = FADE_OUT; + opacity = 1.0f; + onFade(); + timer = 0; + } + else if (state == FADE_OUT) + { + opacity = wi::math::Lerp(1.0f, 0.0f, t); + if (t >= 1.0f) + { + state = FADE_FINISHED; + opacity = 0.0f; + } + } + else if (state == FADE_FINISHED) + { + opacity = 0.0f; + onFade = [] {}; + } + } } diff --git a/WickedEngine/wiFadeManager.h b/WickedEngine/wiFadeManager.h index 7c65beade..70fe13e0c 100644 --- a/WickedEngine/wiFadeManager.h +++ b/WickedEngine/wiFadeManager.h @@ -6,44 +6,45 @@ #include -class wiFadeManager +namespace wi { -public: - - float opacity = 0; - float timer = 0; - float targetFadeTimeInSeconds = 1.0f; - enum FADE_STATE - { - FADE_IN, // no fade -> faded - FADE_MID, // completely faded - FADE_OUT, // faded -> no fade - FADE_FINISHED, - } state = FADE_FINISHED; - wiColor color = wiColor(0, 0, 0, 255); - std::function onFade = [] {}; - - wiFadeManager() - { - Clear(); - } - void Clear(); - void Start(float seconds, wiColor color, std::function onFadeFunction) - { - targetFadeTimeInSeconds = seconds; - this->color = color; - timer = 0; - state = FADE_IN; - onFade = onFadeFunction; - } - void Update(float dt); - bool IsFaded() - { - return state == FADE_MID; - } - bool IsActive() - { - return state != FADE_FINISHED; - } -}; + class FadeManager + { + public: + float opacity = 0; + float timer = 0; + float targetFadeTimeInSeconds = 1.0f; + enum FADE_STATE + { + FADE_IN, // no fade -> faded + FADE_MID, // completely faded + FADE_OUT, // faded -> no fade + FADE_FINISHED, + } state = FADE_FINISHED; + wi::Color color = wi::Color(0, 0, 0, 255); + std::function onFade = [] {}; + FadeManager() + { + Clear(); + } + void Clear(); + void Start(float seconds, wi::Color color, std::function onFadeFunction) + { + targetFadeTimeInSeconds = seconds; + this->color = color; + timer = 0; + state = FADE_IN; + onFade = onFadeFunction; + } + void Update(float dt); + bool IsFaded() + { + return state == FADE_MID; + } + bool IsActive() + { + return state != FADE_FINISHED; + } + }; +} diff --git a/WickedEngine/wiFont.cpp b/WickedEngine/wiFont.cpp index 5aa2dbfa1..56f27dbe3 100644 --- a/WickedEngine/wiFont.cpp +++ b/WickedEngine/wiFont.cpp @@ -3,12 +3,12 @@ #include "wiResourceManager.h" #include "wiHelper.h" #include "shaders/ShaderInterop_Font.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTextureHelper.h" #include "wiRectPacker.h" #include "wiSpinLock.h" #include "wiPlatform.h" -#include "wiEvent.h" +#include "wiEventHandler.h" #include "wiTimer.h" #include "wiUnorderedMap.h" #include "wiUnorderedSet.h" @@ -20,672 +20,670 @@ #include #include -using namespace wiGraphics; -using namespace wiRectPacker; +using namespace wi::graphics; +using namespace wi::rectpacker; +namespace wi::font +{ #define WHITESPACE_SIZE ((float(params.size) + params.spacingX) * params.scaling * 0.25f) #define TAB_SIZE (WHITESPACE_SIZE * 4) #define LINEBREAK_SIZE ((float(params.size) + params.spacingY) * params.scaling) -namespace wiFont_Internal -{ - BlendState blendState; - RasterizerState rasterizerState; - DepthStencilState depthStencilState; - Sampler sampler; - - Shader vertexShader; - Shader pixelShader; - PipelineState PSO; - - wiCanvas canvases[COMMANDLIST_COUNT]; - - std::atomic_bool initialized { false }; - - Texture texture; - - struct Glyph + namespace font_internal { - float x; - float y; - float width; - float height; - uint16_t tc_left; - uint16_t tc_right; - uint16_t tc_top; - uint16_t tc_bottom; - }; - wi::unordered_map glyph_lookup; - wi::unordered_map rect_lookup; - // pack glyph identifiers to a 32-bit hash: - // height: 10 bits (height supported: 0 - 1023) - // style: 6 bits (number of font styles supported: 0 - 63) - // code: 16 bits (character code range supported: 0 - 65535) - constexpr int32_t glyphhash(int code, int style, int height) { return ((code & 0xFFFF) << 16) | ((style & 0x3F) << 10) | (height & 0x3FF); } - constexpr int codefromhash(int64_t hash) { return int((hash >> 16) & 0xFFFF); } - constexpr int stylefromhash(int64_t hash) { return int((hash >> 10) & 0x3F); } - constexpr int heightfromhash(int64_t hash) { return int((hash >> 0) & 0x3FF); } - wi::unordered_set pendingGlyphs; - wiSpinLock glyphLock; + BlendState blendState; + RasterizerState rasterizerState; + DepthStencilState depthStencilState; + Sampler sampler; - struct wiFontStyle - { - std::string name; - wi::vector fontBuffer; // only used if loaded from file, need to keep alive - stbtt_fontinfo fontInfo; - int ascent, descent, lineGap; - void Create(const std::string& newName, const uint8_t* data, size_t size) + Shader vertexShader; + Shader pixelShader; + PipelineState PSO; + + wi::Canvas canvases[COMMANDLIST_COUNT]; + + std::atomic_bool initialized{ false }; + + Texture texture; + + struct Glyph { - name = newName; - int offset = stbtt_GetFontOffsetForIndex(data, 0); + float x; + float y; + float width; + float height; + uint16_t tc_left; + uint16_t tc_right; + uint16_t tc_top; + uint16_t tc_bottom; + }; + wi::unordered_map glyph_lookup; + wi::unordered_map rect_lookup; + // pack glyph identifiers to a 32-bit hash: + // height: 10 bits (height supported: 0 - 1023) + // style: 6 bits (number of font styles supported: 0 - 63) + // code: 16 bits (character code range supported: 0 - 65535) + constexpr int32_t glyphhash(int code, int style, int height) { return ((code & 0xFFFF) << 16) | ((style & 0x3F) << 10) | (height & 0x3FF); } + constexpr int codefromhash(int64_t hash) { return int((hash >> 16) & 0xFFFF); } + constexpr int stylefromhash(int64_t hash) { return int((hash >> 10) & 0x3F); } + constexpr int heightfromhash(int64_t hash) { return int((hash >> 0) & 0x3FF); } + wi::unordered_set pendingGlyphs; + wi::SpinLock glyphLock; - if (!stbtt_InitFont(&fontInfo, data, offset)) - { - wiBackLog::post("Failed to load font: " + name + " (file was unrecognized, it must be a .ttf file)"); - } - - stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap); - } - void Create(const std::string& newName) + struct FontStyle { - if (wiHelper::FileRead(newName, fontBuffer)) + std::string name; + wi::vector fontBuffer; // only used if loaded from file, need to keep alive + stbtt_fontinfo fontInfo; + int ascent, descent, lineGap; + void Create(const std::string& newName, const uint8_t* data, size_t size) { - Create(newName, fontBuffer.data(), fontBuffer.size()); - } - else - { - wiBackLog::post("Failed to load font: " + name + " (file could not be opened)"); - } - } - }; - wi::vector fontStyles; + name = newName; + int offset = stbtt_GetFontOffsetForIndex(data, 0); - struct FontVertex - { - XMFLOAT2 Pos; - XMHALF2 Tex; - }; - - template - uint32_t WriteVertices(volatile FontVertex* vertexList, const T* text, wiFontParams params) - { - const wiFontStyle& fontStyle = fontStyles[params.style]; - const float fontScale = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, (float)params.size); - - uint32_t quadCount = 0; - float line = 0; - float pos = 0; - float pos_last_letter = 0; - size_t last_word_begin = 0; - bool start_new_word = false; - - auto word_wrap = [&] { - start_new_word = true; - if (last_word_begin > 0 && params.h_wrap >= 0 && pos >= params.h_wrap - 1) - { - // Word ended and wrap detected, push down last word by one line: - float word_offset = vertexList[last_word_begin].Pos.x; - for (size_t i = last_word_begin; i < quadCount * 4; ++i) + if (!stbtt_InitFont(&fontInfo, data, offset)) { - vertexList[i].Pos.x -= word_offset; - vertexList[i].Pos.y += LINEBREAK_SIZE; + wi::backlog::post("Failed to load font: " + name + " (file was unrecognized, it must be a .ttf file)"); + } + + stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap); + } + void Create(const std::string& newName) + { + if (wi::helper::FileRead(newName, fontBuffer)) + { + Create(newName, fontBuffer.data(), fontBuffer.size()); + } + else + { + wi::backlog::post("Failed to load font: " + name + " (file could not be opened)"); } - line += LINEBREAK_SIZE; - pos -= word_offset; } }; + wi::vector fontStyles; - int code_prev = 0; - size_t i = 0; - while(text[i] != 0) + struct FontVertex { - T character = text[i++]; - int code = (int)character; + XMFLOAT2 Pos; + XMHALF2 Tex; + }; + + template + uint32_t WriteVertices(volatile FontVertex* vertexList, const T* text, Params params) + { + const FontStyle& fontStyle = fontStyles[params.style]; + const float fontScale = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, (float)params.size); + + uint32_t quadCount = 0; + float line = 0; + float pos = 0; + float pos_last_letter = 0; + size_t last_word_begin = 0; + bool start_new_word = false; + + auto word_wrap = [&] { + start_new_word = true; + if (last_word_begin > 0 && params.h_wrap >= 0 && pos >= params.h_wrap - 1) + { + // Word ended and wrap detected, push down last word by one line: + float word_offset = vertexList[last_word_begin].Pos.x; + for (size_t i = last_word_begin; i < quadCount * 4; ++i) + { + vertexList[i].Pos.x -= word_offset; + vertexList[i].Pos.y += LINEBREAK_SIZE; + } + line += LINEBREAK_SIZE; + pos -= word_offset; + } + }; + + int code_prev = 0; + size_t i = 0; + while (text[i] != 0) + { + T character = text[i++]; + int code = (int)character; + const int32_t hash = glyphhash(code, params.style, params.size); + + if (glyph_lookup.count(hash) == 0) + { + // glyph not packed yet, so add to pending list: + glyphLock.lock(); + pendingGlyphs.insert(hash); + glyphLock.unlock(); + continue; + } + + if (code == '\n') + { + word_wrap(); + line += LINEBREAK_SIZE; + pos = 0; + code_prev = 0; + } + else if (code == ' ') + { + word_wrap(); + pos += WHITESPACE_SIZE; + code_prev = 0; + } + else if (code == '\t') + { + word_wrap(); + pos += TAB_SIZE; + code_prev = 0; + } + else + { + const Glyph& glyph = glyph_lookup.at(hash); + const float glyphWidth = glyph.width * params.scaling; + const float glyphHeight = glyph.height * params.scaling; + const float glyphOffsetX = glyph.x * params.scaling; + const float glyphOffsetY = glyph.y * params.scaling; + + const size_t vertexID = size_t(quadCount) * 4; + + if (start_new_word) + { + last_word_begin = vertexID; + } + start_new_word = false; + + if (code_prev != 0) + { + int kern = stbtt_GetCodepointKernAdvance(&fontStyle.fontInfo, code_prev, code); + pos += kern * fontScale; + } + code_prev = code; + + const float left = pos + glyphOffsetX; + const float right = left + glyphWidth; + const float top = line + glyphOffsetY; + const float bottom = top + glyphHeight; + + vertexList[vertexID + 0].Pos.x = left; + vertexList[vertexID + 0].Pos.y = top; + vertexList[vertexID + 1].Pos.x = right; + vertexList[vertexID + 1].Pos.y = top; + vertexList[vertexID + 2].Pos.x = left; + vertexList[vertexID + 2].Pos.y = bottom; + vertexList[vertexID + 3].Pos.x = right; + vertexList[vertexID + 3].Pos.y = bottom; + + vertexList[vertexID + 0].Tex.x = glyph.tc_left; + vertexList[vertexID + 0].Tex.y = glyph.tc_top; + vertexList[vertexID + 1].Tex.x = glyph.tc_right; + vertexList[vertexID + 1].Tex.y = glyph.tc_top; + vertexList[vertexID + 2].Tex.x = glyph.tc_left; + vertexList[vertexID + 2].Tex.y = glyph.tc_bottom; + vertexList[vertexID + 3].Tex.x = glyph.tc_right; + vertexList[vertexID + 3].Tex.y = glyph.tc_bottom; + + pos += glyph.width * params.scaling + params.spacingX; + pos_last_letter = pos; + + quadCount++; + } + + } + + word_wrap(); + + return quadCount; + } + + } + using namespace font_internal; + + void LoadShaders() + { + wi::renderer::LoadShader(ShaderStage::VS, vertexShader, "fontVS.cso"); + + + pixelShader.auto_samplers.emplace_back(); + pixelShader.auto_samplers.back().sampler = sampler; + pixelShader.auto_samplers.back().slot = 0; + + wi::renderer::LoadShader(ShaderStage::PS, pixelShader, "fontPS.cso"); + + + PipelineStateDesc desc; + desc.vs = &vertexShader; + desc.ps = &pixelShader; + desc.bs = &blendState; + desc.dss = &depthStencilState; + desc.rs = &rasterizerState; + desc.pt = PrimitiveTopology::TRIANGLESTRIP; + wi::graphics::GetDevice()->CreatePipelineState(&desc, &PSO); + } + void Initialize() + { + if (initialized) + { + return; + } + + wi::Timer timer; + + // add default font if there is none yet: + if (fontStyles.empty()) + { + AddFontStyle("arial", arial, sizeof(arial)); + } + + GraphicsDevice* device = wi::graphics::GetDevice(); + + RasterizerState rs; + rs.fill_mode = FillMode::SOLID; + rs.cull_mode = CullMode::FRONT; + rs.front_counter_clockwise = true; + rs.depth_bias = 0; + rs.depth_bias_clamp = 0; + rs.slope_scaled_depth_bias = 0; + rs.depth_clip_enable = false; + rs.multisample_enable = false; + rs.antialiased_line_enable = false; + rasterizerState = rs; + + BlendState bd; + bd.render_target[0].blend_enable = true; + bd.render_target[0].src_blend = Blend::ONE; + bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; + bd.render_target[0].blend_op = BlendOp::ADD; + bd.render_target[0].src_blend_alpha = Blend::ONE; + bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA; + bd.render_target[0].blend_op_alpha = BlendOp::ADD; + bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; + bd.independent_blend_enable = false; + blendState = bd; + + DepthStencilState dsd; + dsd.depth_enable = false; + dsd.stencil_enable = false; + depthStencilState = dsd; + + SamplerDesc samplerDesc; + samplerDesc.filter = Filter::MIN_MAG_LINEAR_MIP_POINT; + samplerDesc.address_u = TextureAddressMode::BORDER; + samplerDesc.address_v = TextureAddressMode::BORDER; + samplerDesc.address_w = TextureAddressMode::BORDER; + samplerDesc.mip_lod_bias = 0.0f; + samplerDesc.max_anisotropy = 0; + samplerDesc.comparison_func = ComparisonFunc::NEVER; + samplerDesc.border_color = SamplerBorderColor::TRANSPARENT_BLACK; + samplerDesc.min_lod = 0; + samplerDesc.max_lod = 0; + device->CreateSampler(&samplerDesc, &sampler); + + static wi::eventhandler::Handle handle1 = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); + LoadShaders(); + + + wi::backlog::post("wi::font Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + initialized.store(true); + } + + void UpdatePendingGlyphs() + { + glyphLock.lock(); + + // If there are pending glyphs, render them and repack the atlas: + if (!pendingGlyphs.empty()) + { + // Pad the glyph rects in the atlas to avoid bleeding from nearby texels: + const int borderPadding = 1; + + // Font resolution is upscaled to make it sharper: + const float upscaling = 2.0f; + + for (int32_t hash : pendingGlyphs) + { + const int code = codefromhash(hash); + const int style = stylefromhash(hash); + const float height = (float)heightfromhash(hash) * upscaling; + FontStyle& fontStyle = fontStyles[style]; + + float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, height); + + // get bounding box for character (may be offset to account for chars that dip above or below the line + int left, top, right, bottom; + stbtt_GetCodepointBitmapBox(&fontStyle.fontInfo, code, fontScaling, fontScaling, &left, &top, &right, &bottom); + + // Glyph dimensions are calculated without padding: + Glyph& glyph = glyph_lookup[hash]; + glyph.x = float(left); + glyph.y = float(top) + float(fontStyle.ascent) * fontScaling; + glyph.width = float(right - left); + glyph.height = float(bottom - top); + + // Remove dpi upscaling: + glyph.x = glyph.x / upscaling; + glyph.y = glyph.y / upscaling; + glyph.width = glyph.width / upscaling; + glyph.height = glyph.height / upscaling; + + // Add padding to the rectangle that will be packed in the atlas: + right += borderPadding * 2; + bottom += borderPadding * 2; + rect_lookup[hash] = rect_ltrb(left, top, right, bottom); + } + pendingGlyphs.clear(); + + // This reference array will be used for packing: + wi::vector out_rects; + out_rects.reserve(rect_lookup.size()); + for (auto& it : rect_lookup) + { + out_rects.push_back(&it.second); + } + + // Perform packing and process the result if successful: + wi::vector bins; + if (pack(out_rects.data(), (int)out_rects.size(), 4096, bins)) + { + assert(bins.size() == 1 && "The regions won't fit into one texture!"); + + // Retrieve texture atlas dimensions: + const int bitmapWidth = bins[0].size.w; + const int bitmapHeight = bins[0].size.h; + const float inv_width = 1.0f / bitmapWidth; + const float inv_height = 1.0f / bitmapHeight; + + // Create the CPU-side texture atlas and fill with transparency (0): + wi::vector bitmap(size_t(bitmapWidth) * size_t(bitmapHeight)); + std::fill(bitmap.begin(), bitmap.end(), 0); + + // Iterate all packed glyph rectangles: + for (auto it : rect_lookup) + { + const int32_t hash = it.first; + const wchar_t code = codefromhash(hash); + const int style = stylefromhash(hash); + const float height = (float)heightfromhash(hash) * upscaling; + const FontStyle& fontStyle = fontStyles[style]; + rect_xywh& rect = it.second; + Glyph& glyph = glyph_lookup[hash]; + + // Remove border padding from the packed rectangle (we don't want to touch the border, it should stay transparent): + rect.x += borderPadding; + rect.y += borderPadding; + rect.w -= borderPadding * 2; + rect.h -= borderPadding * 2; + + float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, height); + + // Render the glyph inside the CPU-side atlas: + int byteOffset = rect.x + (rect.y * bitmapWidth); + stbtt_MakeCodepointBitmap(&fontStyle.fontInfo, bitmap.data() + byteOffset, rect.w, rect.h, bitmapWidth, fontScaling, fontScaling, code); + + // Compute texture coordinates for the glyph: + float tc_left = float(rect.x); + float tc_right = tc_left + float(rect.w); + float tc_top = float(rect.y); + float tc_bottom = tc_top + float(rect.h); + + tc_left *= inv_width; + tc_right *= inv_width; + tc_top *= inv_height; + tc_bottom *= inv_height; + + glyph.tc_left = XMConvertFloatToHalf(tc_left); + glyph.tc_right = XMConvertFloatToHalf(tc_right); + glyph.tc_top = XMConvertFloatToHalf(tc_top); + glyph.tc_bottom = XMConvertFloatToHalf(tc_bottom); + } + + // Upload the CPU-side texture atlas bitmap to the GPU: + wi::texturehelper::CreateTexture(texture, bitmap.data(), bitmapWidth, bitmapHeight, Format::R8_UNORM); + } + } + + glyphLock.unlock(); + } + const Texture* GetAtlas() + { + return &texture; + } + int AddFontStyle(const std::string& fontName) + { + for (size_t i = 0; i < fontStyles.size(); i++) + { + const FontStyle& fontStyle = fontStyles[i]; + if (!fontStyle.name.compare(fontName)) + { + return int(i); + } + } + fontStyles.emplace_back(); + fontStyles.back().Create(fontName); + return int(fontStyles.size() - 1); + } + int AddFontStyle(const std::string& fontName, const uint8_t* data, size_t size) + { + for (size_t i = 0; i < fontStyles.size(); i++) + { + const FontStyle& fontStyle = fontStyles[i]; + if (!fontStyle.name.compare(fontName)) + { + return int(i); + } + } + fontStyles.emplace_back(); + fontStyles.back().Create(fontName, data, size); + return int(fontStyles.size() - 1); + } + + + template + float TextWidth_internal(const T* text, const Params& params) + { + if (params.style >= (int)fontStyles.size()) + { + return 0; + } + + // TODO: account for word wrap + float maxWidth = 0; + float currentLineWidth = 0; + size_t i = 0; + while (text[i] != 0) + { + int code = (int)text[i++]; const int32_t hash = glyphhash(code, params.style, params.size); if (glyph_lookup.count(hash) == 0) { - // glyph not packed yet, so add to pending list: - glyphLock.lock(); - pendingGlyphs.insert(hash); - glyphLock.unlock(); + // glyph not packed yet, we just continue (it will be added if it is actually rendered) continue; } if (code == '\n') { - word_wrap(); - line += LINEBREAK_SIZE; - pos = 0; - code_prev = 0; + currentLineWidth = 0; } else if (code == ' ') { - word_wrap(); - pos += WHITESPACE_SIZE; - code_prev = 0; + currentLineWidth += WHITESPACE_SIZE; } else if (code == '\t') { - word_wrap(); - pos += TAB_SIZE; - code_prev = 0; + currentLineWidth += TAB_SIZE; } else { const Glyph& glyph = glyph_lookup.at(hash); - const float glyphWidth = glyph.width * params.scaling; - const float glyphHeight = glyph.height * params.scaling; - const float glyphOffsetX = glyph.x * params.scaling; - const float glyphOffsetY = glyph.y * params.scaling; - - const size_t vertexID = size_t(quadCount) * 4; - - if (start_new_word) - { - last_word_begin = vertexID; - } - start_new_word = false; - - if (code_prev != 0) - { - int kern = stbtt_GetCodepointKernAdvance(&fontStyle.fontInfo, code_prev, code); - pos += kern * fontScale; - } - code_prev = code; - - const float left = pos + glyphOffsetX; - const float right = left + glyphWidth; - const float top = line + glyphOffsetY; - const float bottom = top + glyphHeight; - - vertexList[vertexID + 0].Pos.x = left; - vertexList[vertexID + 0].Pos.y = top; - vertexList[vertexID + 1].Pos.x = right; - vertexList[vertexID + 1].Pos.y = top; - vertexList[vertexID + 2].Pos.x = left; - vertexList[vertexID + 2].Pos.y = bottom; - vertexList[vertexID + 3].Pos.x = right; - vertexList[vertexID + 3].Pos.y = bottom; - - vertexList[vertexID + 0].Tex.x = glyph.tc_left; - vertexList[vertexID + 0].Tex.y = glyph.tc_top; - vertexList[vertexID + 1].Tex.x = glyph.tc_right; - vertexList[vertexID + 1].Tex.y = glyph.tc_top; - vertexList[vertexID + 2].Tex.x = glyph.tc_left; - vertexList[vertexID + 2].Tex.y = glyph.tc_bottom; - vertexList[vertexID + 3].Tex.x = glyph.tc_right; - vertexList[vertexID + 3].Tex.y = glyph.tc_bottom; - - pos += glyph.width * params.scaling + params.spacingX; - pos_last_letter = pos; - - quadCount++; + currentLineWidth += glyph.width + float(params.spacingX) * params.scaling; } - + maxWidth = std::max(maxWidth, currentLineWidth); } - word_wrap(); - - return quadCount; + return maxWidth; } -} -using namespace wiFont_Internal; - -namespace wiFont -{ - - -void LoadShaders() -{ - wiRenderer::LoadShader(ShaderStage::VS, vertexShader, "fontVS.cso"); - - - pixelShader.auto_samplers.emplace_back(); - pixelShader.auto_samplers.back().sampler = sampler; - pixelShader.auto_samplers.back().slot = 0; - - wiRenderer::LoadShader(ShaderStage::PS, pixelShader, "fontPS.cso"); - - - PipelineStateDesc desc; - desc.vs = &vertexShader; - desc.ps = &pixelShader; - desc.bs = &blendState; - desc.dss = &depthStencilState; - desc.rs = &rasterizerState; - desc.pt = PrimitiveTopology::TRIANGLESTRIP; - wiGraphics::GetDevice()->CreatePipelineState(&desc, &PSO); -} -void Initialize() -{ - if (initialized) + template + float TextHeight_internal(const T* text, const Params& params) { - return; - } - - wiTimer timer; - - // add default font if there is none yet: - if (fontStyles.empty()) - { - AddFontStyle("arial", arial, sizeof(arial)); - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - - RasterizerState rs; - rs.fill_mode = FillMode::SOLID; - rs.cull_mode = CullMode::FRONT; - rs.front_counter_clockwise = true; - rs.depth_bias = 0; - rs.depth_bias_clamp = 0; - rs.slope_scaled_depth_bias = 0; - rs.depth_clip_enable = false; - rs.multisample_enable = false; - rs.antialiased_line_enable = false; - rasterizerState = rs; - - BlendState bd; - bd.render_target[0].blend_enable = true; - bd.render_target[0].src_blend = Blend::ONE; - bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ONE; - bd.render_target[0].dest_blend_alpha = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - bd.independent_blend_enable = false; - blendState = bd; - - DepthStencilState dsd; - dsd.depth_enable = false; - dsd.stencil_enable = false; - depthStencilState = dsd; - - SamplerDesc samplerDesc; - samplerDesc.filter = Filter::MIN_MAG_LINEAR_MIP_POINT; - samplerDesc.address_u = TextureAddressMode::BORDER; - samplerDesc.address_v = TextureAddressMode::BORDER; - samplerDesc.address_w = TextureAddressMode::BORDER; - samplerDesc.mip_lod_bias = 0.0f; - samplerDesc.max_anisotropy = 0; - samplerDesc.comparison_func = ComparisonFunc::NEVER; - samplerDesc.border_color = SamplerBorderColor::TRANSPARENT_BLACK; - samplerDesc.min_lod = 0; - samplerDesc.max_lod = 0; - device->CreateSampler(&samplerDesc, &sampler); - - static wiEvent::Handle handle1 = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); - LoadShaders(); - - - wiBackLog::post("wiFont Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); - initialized.store(true); -} - -void UpdatePendingGlyphs() -{ - glyphLock.lock(); - - // If there are pending glyphs, render them and repack the atlas: - if (!pendingGlyphs.empty()) - { - // Pad the glyph rects in the atlas to avoid bleeding from nearby texels: - const int borderPadding = 1; - - // Font resolution is upscaled to make it sharper: - const float upscaling = 2.0f; - - for (int32_t hash : pendingGlyphs) + if (params.style >= (int)fontStyles.size()) { - const int code = codefromhash(hash); - const int style = stylefromhash(hash); - const float height = (float)heightfromhash(hash) * upscaling; - wiFontStyle& fontStyle = fontStyles[style]; - - float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, height); - - // get bounding box for character (may be offset to account for chars that dip above or below the line - int left, top, right, bottom; - stbtt_GetCodepointBitmapBox(&fontStyle.fontInfo, code, fontScaling, fontScaling, &left, &top, &right, &bottom); - - // Glyph dimensions are calculated without padding: - Glyph& glyph = glyph_lookup[hash]; - glyph.x = float(left); - glyph.y = float(top) + float(fontStyle.ascent) * fontScaling; - glyph.width = float(right - left); - glyph.height = float(bottom - top); - - // Remove dpi upscaling: - glyph.x = glyph.x / upscaling; - glyph.y = glyph.y / upscaling; - glyph.width = glyph.width / upscaling; - glyph.height = glyph.height / upscaling; - - // Add padding to the rectangle that will be packed in the atlas: - right += borderPadding * 2; - bottom += borderPadding * 2; - rect_lookup[hash] = rect_ltrb(left, top, right, bottom); - } - pendingGlyphs.clear(); - - // This reference array will be used for packing: - wi::vector out_rects; - out_rects.reserve(rect_lookup.size()); - for (auto& it : rect_lookup) - { - out_rects.push_back(&it.second); + return 0; } - // Perform packing and process the result if successful: - wi::vector bins; - if (pack(out_rects.data(), (int)out_rects.size(), 4096, bins)) + // TODO: account for word wrap + float height = LINEBREAK_SIZE; + size_t i = 0; + while (text[i] != 0) { - assert(bins.size() == 1 && "The regions won't fit into one texture!"); - - // Retrieve texture atlas dimensions: - const int bitmapWidth = bins[0].size.w; - const int bitmapHeight = bins[0].size.h; - const float inv_width = 1.0f / bitmapWidth; - const float inv_height = 1.0f / bitmapHeight; - - // Create the CPU-side texture atlas and fill with transparency (0): - wi::vector bitmap(size_t(bitmapWidth) * size_t(bitmapHeight)); - std::fill(bitmap.begin(), bitmap.end(), 0); - - // Iterate all packed glyph rectangles: - for (auto it : rect_lookup) + int code = (int)text[i++]; + if (code == '\n') { - const int32_t hash = it.first; - const wchar_t code = codefromhash(hash); - const int style = stylefromhash(hash); - const float height = (float)heightfromhash(hash) * upscaling; - const wiFontStyle& fontStyle = fontStyles[style]; - rect_xywh& rect = it.second; - Glyph& glyph = glyph_lookup[hash]; + height += LINEBREAK_SIZE; + } + } - // Remove border padding from the packed rectangle (we don't want to touch the border, it should stay transparent): - rect.x += borderPadding; - rect.y += borderPadding; - rect.w -= borderPadding * 2; - rect.h -= borderPadding * 2; + return height; + } - float fontScaling = stbtt_ScaleForPixelHeight(&fontStyle.fontInfo, height); + template + void Draw_internal(const T* text, size_t text_length, const Params& params, CommandList cmd) + { + if (text_length <= 0 || !initialized.load()) + { + return; + } - // Render the glyph inside the CPU-side atlas: - int byteOffset = rect.x + (rect.y * bitmapWidth); - stbtt_MakeCodepointBitmap(&fontStyle.fontInfo, bitmap.data() + byteOffset, rect.w, rect.h, bitmapWidth, fontScaling, fontScaling, code); + Params newProps = params; - // Compute texture coordinates for the glyph: - float tc_left = float(rect.x); - float tc_right = tc_left + float(rect.w); - float tc_top = float(rect.y); - float tc_bottom = tc_top + float(rect.h); + if (params.h_align == WIFALIGN_CENTER) + newProps.posX -= TextWidth_internal(text, newProps) / 2; + else if (params.h_align == WIFALIGN_RIGHT) + newProps.posX -= TextWidth_internal(text, newProps); + if (params.v_align == WIFALIGN_CENTER) + newProps.posY -= TextHeight_internal(text, newProps) / 2; + else if (params.v_align == WIFALIGN_BOTTOM) + newProps.posY -= TextHeight_internal(text, newProps); - tc_left *= inv_width; - tc_right *= inv_width; - tc_top *= inv_height; - tc_bottom *= inv_height; + GraphicsDevice* device = wi::graphics::GetDevice(); - glyph.tc_left = XMConvertFloatToHalf(tc_left); - glyph.tc_right = XMConvertFloatToHalf(tc_right); - glyph.tc_top = XMConvertFloatToHalf(tc_top); - glyph.tc_bottom = XMConvertFloatToHalf(tc_bottom); + GraphicsDevice::GPUAllocation mem = device->AllocateGPU(sizeof(FontVertex) * text_length * 4, cmd); + if (!mem.IsValid()) + { + return; + } + volatile FontVertex* textBuffer = (volatile FontVertex*)mem.data; + const uint32_t quadCount = WriteVertices(textBuffer, text, newProps); + + if (quadCount > 0) + { + device->EventBegin("Font", cmd); + + device->BindPipelineState(&PSO, cmd); + + PushConstantsFont push; + push.buffer_index = device->GetDescriptorIndex(&mem.buffer, SubresourceType::SRV); + push.buffer_offset = (uint32_t)mem.offset; + push.texture_index = device->GetDescriptorIndex(&texture, SubresourceType::SRV); + + const wi::Canvas& canvas = canvases[cmd]; + // Asserts will check that a proper canvas was set for this cmd with wi::image::SetCanvas() + // The canvas must be set to have dpi aware rendering + assert(canvas.width > 0); + assert(canvas.height > 0); + assert(canvas.dpi > 0); + const XMMATRIX Projection = canvas.GetProjection(); + + if (newProps.shadowColor.getA() > 0) + { + // font shadow render: + XMStoreFloat4x4(&push.transform, + XMMatrixTranslation((float)newProps.posX + 1, (float)newProps.posY + 1, 0) + * Projection + ); + push.color = newProps.shadowColor.rgba; + + device->PushConstants(&push, sizeof(push), cmd); + device->DrawInstanced(4, quadCount, 0, 0, cmd); } - // Upload the CPU-side texture atlas bitmap to the GPU: - wiTextureHelper::CreateTexture(texture, bitmap.data(), bitmapWidth, bitmapHeight, Format::R8_UNORM); - } - } - - glyphLock.unlock(); -} -const Texture* GetAtlas() -{ - return &texture; -} -int AddFontStyle(const std::string& fontName) -{ - for (size_t i = 0; i < fontStyles.size(); i++) - { - const wiFontStyle& fontStyle = fontStyles[i]; - if (!fontStyle.name.compare(fontName)) - { - return int(i); - } - } - fontStyles.emplace_back(); - fontStyles.back().Create(fontName); - return int(fontStyles.size() - 1); -} -int AddFontStyle(const std::string& fontName, const uint8_t* data, size_t size) -{ - for (size_t i = 0; i < fontStyles.size(); i++) - { - const wiFontStyle& fontStyle = fontStyles[i]; - if (!fontStyle.name.compare(fontName)) - { - return int(i); - } - } - fontStyles.emplace_back(); - fontStyles.back().Create(fontName, data, size); - return int(fontStyles.size() - 1); -} - - -template -float textWidth_internal(const T* text, const wiFontParams& params) -{ - if (params.style >= (int)fontStyles.size()) - { - return 0; - } - - // TODO: account for word wrap - float maxWidth = 0; - float currentLineWidth = 0; - size_t i = 0; - while (text[i] != 0) - { - int code = (int)text[i++]; - const int32_t hash = glyphhash(code, params.style, params.size); - - if (glyph_lookup.count(hash) == 0) - { - // glyph not packed yet, we just continue (it will be added if it is actually rendered) - continue; - } - - if (code == '\n') - { - currentLineWidth = 0; - } - else if (code == ' ') - { - currentLineWidth += WHITESPACE_SIZE; - } - else if (code == '\t') - { - currentLineWidth += TAB_SIZE; - } - else - { - const Glyph& glyph = glyph_lookup.at(hash); - currentLineWidth += glyph.width + float(params.spacingX) * params.scaling; - } - maxWidth = std::max(maxWidth, currentLineWidth); - } - - return maxWidth; -} - -template -float textHeight_internal(const T* text, const wiFontParams& params) -{ - if (params.style >= (int)fontStyles.size()) - { - return 0; - } - - // TODO: account for word wrap - float height = LINEBREAK_SIZE; - size_t i = 0; - while (text[i] != 0) - { - int code = (int)text[i++]; - if (code == '\n') - { - height += LINEBREAK_SIZE; - } - } - - return height; -} - -template -void Draw_internal(const T* text, size_t text_length, const wiFontParams& params, CommandList cmd) -{ - if (text_length <= 0 || !initialized.load()) - { - return; - } - - wiFontParams newProps = params; - - if (params.h_align == WIFALIGN_CENTER) - newProps.posX -= textWidth_internal(text, newProps) / 2; - else if (params.h_align == WIFALIGN_RIGHT) - newProps.posX -= textWidth_internal(text, newProps); - if (params.v_align == WIFALIGN_CENTER) - newProps.posY -= textHeight_internal(text, newProps) / 2; - else if (params.v_align == WIFALIGN_BOTTOM) - newProps.posY -= textHeight_internal(text, newProps); - - GraphicsDevice* device = wiGraphics::GetDevice(); - - GraphicsDevice::GPUAllocation mem = device->AllocateGPU(sizeof(FontVertex) * text_length * 4, cmd); - if (!mem.IsValid()) - { - return; - } - volatile FontVertex* textBuffer = (volatile FontVertex*)mem.data; - const uint32_t quadCount = WriteVertices(textBuffer, text, newProps); - - if (quadCount > 0) - { - device->EventBegin("Font", cmd); - - device->BindPipelineState(&PSO, cmd); - - PushConstantsFont push; - push.buffer_index = device->GetDescriptorIndex(&mem.buffer, SubresourceType::SRV); - push.buffer_offset = (uint32_t)mem.offset; - push.texture_index = device->GetDescriptorIndex(&texture, SubresourceType::SRV); - - const wiCanvas& canvas = canvases[cmd]; - // Asserts will check that a proper canvas was set for this cmd with wiImage::SetCanvas() - // The canvas must be set to have dpi aware rendering - assert(canvas.width > 0); - assert(canvas.height > 0); - assert(canvas.dpi > 0); - const XMMATRIX Projection = canvas.GetProjection(); - - if (newProps.shadowColor.getA() > 0) - { - // font shadow render: + // font base render: XMStoreFloat4x4(&push.transform, - XMMatrixTranslation((float)newProps.posX + 1, (float)newProps.posY + 1, 0) + XMMatrixTranslation((float)newProps.posX, (float)newProps.posY, 0) * Projection ); - push.color = newProps.shadowColor.rgba; + push.color = newProps.color.rgba; device->PushConstants(&push, sizeof(push), cmd); device->DrawInstanced(4, quadCount, 0, 0, cmd); + + device->EventEnd(cmd); } - // font base render: - XMStoreFloat4x4(&push.transform, - XMMatrixTranslation((float)newProps.posX, (float)newProps.posY, 0) - * Projection - ); - push.color = newProps.color.rgba; - - device->PushConstants(&push, sizeof(push), cmd); - device->DrawInstanced(4, quadCount, 0, 0, cmd); - - device->EventEnd(cmd); + UpdatePendingGlyphs(); } - UpdatePendingGlyphs(); -} - -void SetCanvas(const wiCanvas& canvas, wiGraphics::CommandList cmd) -{ - canvases[cmd] = canvas; -} - -void Draw(const char* text, const wiFontParams& params, CommandList cmd) -{ - size_t text_length = strlen(text); - if (text_length == 0) + void SetCanvas(const wi::Canvas& canvas, wi::graphics::CommandList cmd) { - return; + canvases[cmd] = canvas; } - Draw_internal(text, text_length, params, cmd); -} -void Draw(const wchar_t* text, const wiFontParams& params, CommandList cmd) -{ - size_t text_length = wcslen(text); - if (text_length == 0) + + void Draw(const char* text, const Params& params, CommandList cmd) { - return; + size_t text_length = strlen(text); + if (text_length == 0) + { + return; + } + Draw_internal(text, text_length, params, cmd); + } + void Draw(const wchar_t* text, const Params& params, CommandList cmd) + { + size_t text_length = wcslen(text); + if (text_length == 0) + { + return; + } + Draw_internal(text, text_length, params, cmd); + } + void Draw(const std::string& text, const Params& params, CommandList cmd) + { + Draw_internal(text.c_str(), text.length(), params, cmd); + } + void Draw(const std::wstring& text, const Params& params, CommandList cmd) + { + Draw_internal(text.c_str(), text.length(), params, cmd); } - Draw_internal(text, text_length, params, cmd); -} -void Draw(const std::string& text, const wiFontParams& params, CommandList cmd) -{ - Draw_internal(text.c_str(), text.length(), params, cmd); -} -void Draw(const std::wstring& text, const wiFontParams& params, CommandList cmd) -{ - Draw_internal(text.c_str(), text.length(), params, cmd); -} -float textWidth(const char* text, const wiFontParams& params) -{ - return textWidth_internal(text, params); -} -float textWidth(const wchar_t* text, const wiFontParams& params) -{ - return textWidth_internal(text, params); -} -float textWidth(const std::string& text, const wiFontParams& params) -{ - return textWidth_internal(text.c_str(), params); -} -float textWidth(const std::wstring& text, const wiFontParams& params) -{ - return textWidth_internal(text.c_str(), params); -} + float TextWidth(const char* text, const Params& params) + { + return TextWidth_internal(text, params); + } + float TextWidth(const wchar_t* text, const Params& params) + { + return TextWidth_internal(text, params); + } + float TextWidth(const std::string& text, const Params& params) + { + return TextWidth_internal(text.c_str(), params); + } + float TextWidth(const std::wstring& text, const Params& params) + { + return TextWidth_internal(text.c_str(), params); + } -float textHeight(const char* text, const wiFontParams& params) -{ - return textHeight_internal(text, params); -} -float textHeight(const wchar_t* text, const wiFontParams& params) -{ - return textHeight_internal(text, params); -} -float textHeight(const std::string& text, const wiFontParams& params) -{ - return textHeight_internal(text.c_str(), params); -} -float textHeight(const std::wstring& text, const wiFontParams& params) -{ - return textHeight_internal(text.c_str(), params); -} + float TextHeight(const char* text, const Params& params) + { + return TextHeight_internal(text, params); + } + float TextHeight(const wchar_t* text, const Params& params) + { + return TextHeight_internal(text, params); + } + float TextHeight(const std::string& text, const Params& params) + { + return TextHeight_internal(text.c_str(), params); + } + float TextHeight(const std::wstring& text, const Params& params) + { + return TextHeight_internal(text.c_str(), params); + } } diff --git a/WickedEngine/wiFont.h b/WickedEngine/wiFont.h index 086588b2b..80a5a18b7 100644 --- a/WickedEngine/wiFont.h +++ b/WickedEngine/wiFont.h @@ -6,57 +6,57 @@ #include -// Do not alter order because it is bound to lua manually -enum wiFontAlign +namespace wi::font { - WIFALIGN_LEFT, - WIFALIGN_CENTER, - WIFALIGN_RIGHT, - WIFALIGN_TOP, - WIFALIGN_BOTTOM -}; + // Do not alter order because it is bound to lua manually + enum Alignment + { + WIFALIGN_LEFT, + WIFALIGN_CENTER, + WIFALIGN_RIGHT, + WIFALIGN_TOP, + WIFALIGN_BOTTOM + }; -static constexpr int WIFONTSIZE_DEFAULT = 16; + static constexpr int WIFONTSIZE_DEFAULT = 16; -struct wiFontParams -{ - float posX = 0; - float posY = 0; - int size = WIFONTSIZE_DEFAULT; // line height in DPI scaled units - float scaling = 1; - float spacingX = 1, spacingY = 1; // minimum spacing between characters - wiFontAlign h_align, v_align; - wiColor color; - wiColor shadowColor; - float h_wrap = -1; // wrap start width (-1 default for no wrap) - int style = 0; + struct Params + { + float posX = 0; + float posY = 0; + int size = WIFONTSIZE_DEFAULT; // line height in DPI scaled units + float scaling = 1; + float spacingX = 1, spacingY = 1; // minimum spacing between characters + Alignment h_align, v_align; + wi::Color color; + wi::Color shadowColor; + float h_wrap = -1; // wrap start width (-1 default for no wrap) + int style = 0; - wiFontParams( - float posX = 0, - float posY = 0, - int size = WIFONTSIZE_DEFAULT, - wiFontAlign h_align = WIFALIGN_LEFT, - wiFontAlign v_align = WIFALIGN_TOP, - wiColor color = wiColor(255, 255, 255, 255), - wiColor shadowColor = wiColor(0,0,0,0) - ): - posX(posX), - posY(posY), - size(size), - h_align(h_align), - v_align(v_align), - color(color), - shadowColor(shadowColor) - {} -}; + Params( + float posX = 0, + float posY = 0, + int size = WIFONTSIZE_DEFAULT, + Alignment h_align = WIFALIGN_LEFT, + Alignment v_align = WIFALIGN_TOP, + wi::Color color = wi::Color(255, 255, 255, 255), + wi::Color shadowColor = wi::Color(0, 0, 0, 0) + ) : + posX(posX), + posY(posY), + size(size), + h_align(h_align), + v_align(v_align), + color(color), + shadowColor(shadowColor) + {} + }; -namespace wiFont -{ // Initializes the font renderer void Initialize(); // Get the texture that contains currently cached glyphs - const wiGraphics::Texture* GetAtlas(); + const wi::graphics::Texture* GetAtlas(); // Create a font from a file. It must be an existing .ttf file. // fontName : path to .ttf font @@ -73,21 +73,21 @@ namespace wiFont int AddFontStyle(const std::string& fontName, const uint8_t* data, size_t size); // Set canvas for the CommandList to handle DPI-aware font rendering - void SetCanvas(const wiCanvas& canvas, wiGraphics::CommandList cmd); + void SetCanvas(const wi::Canvas& canvas, wi::graphics::CommandList cmd); - void Draw(const char* text, const wiFontParams& params, wiGraphics::CommandList cmd); - void Draw(const wchar_t* text, const wiFontParams& params, wiGraphics::CommandList cmd); - void Draw(const std::string& text, const wiFontParams& params, wiGraphics::CommandList cmd); - void Draw(const std::wstring& text, const wiFontParams& params, wiGraphics::CommandList cmd); + void Draw(const char* text, const Params& params, wi::graphics::CommandList cmd); + void Draw(const wchar_t* text, const Params& params, wi::graphics::CommandList cmd); + void Draw(const std::string& text, const Params& params, wi::graphics::CommandList cmd); + void Draw(const std::wstring& text, const Params& params, wi::graphics::CommandList cmd); - float textWidth(const char* text, const wiFontParams& params); - float textWidth(const wchar_t* text, const wiFontParams& params); - float textWidth(const std::string& text, const wiFontParams& params); - float textWidth(const std::wstring& text, const wiFontParams& params); + float TextWidth(const char* text, const Params& params); + float TextWidth(const wchar_t* text, const Params& params); + float TextWidth(const std::string& text, const Params& params); + float TextWidth(const std::wstring& text, const Params& params); - float textHeight(const char* text, const wiFontParams& params); - float textHeight(const wchar_t* text, const wiFontParams& params); - float textHeight(const std::string& text, const wiFontParams& params); - float textHeight(const std::wstring& text, const wiFontParams& params); + float TextHeight(const char* text, const Params& params); + float TextHeight(const wchar_t* text, const Params& params); + float TextHeight(const std::string& text, const Params& params); + float TextHeight(const std::wstring& text, const Params& params); -}; +} diff --git a/WickedEngine/wiGPUBVH.cpp b/WickedEngine/wiGPUBVH.cpp index 8e4cbdff7..0541090d7 100644 --- a/WickedEngine/wiGPUBVH.cpp +++ b/WickedEngine/wiGPUBVH.cpp @@ -6,154 +6,34 @@ #include "wiResourceManager.h" #include "wiGPUSortLib.h" #include "wiTextureHelper.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiTimer.h" //#define BVH_VALIDATE // slow but great for debug! -using namespace wiGraphics; -using namespace wiScene; -using namespace wiECS; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::ecs; -enum CSTYPES_BVH +namespace wi { - CSTYPE_BVH_PRIMITIVES, - CSTYPE_BVH_HIERARCHY, - CSTYPE_BVH_PROPAGATEAABB, - CSTYPE_BVH_COUNT -}; -static Shader computeShaders[CSTYPE_BVH_COUNT]; -void wiGPUBVH::Update(const wiScene::Scene& scene) -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - // Pre-gather scene properties: - uint totalTriangles = 0; - for (size_t i = 0; i < scene.objects.GetCount(); ++i) + enum CSTYPES_BVH { - const ObjectComponent& object = scene.objects[i]; + CSTYPE_BVH_PRIMITIVES, + CSTYPE_BVH_HIERARCHY, + CSTYPE_BVH_PROPAGATEAABB, + CSTYPE_BVH_COUNT + }; + static Shader computeShaders[CSTYPE_BVH_COUNT]; - if (object.meshID != INVALID_ENTITY) - { - const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); - - totalTriangles += (uint)mesh.indices.size() / 3; - } - } - for (size_t i = 0; i < scene.hairs.GetCount(); ++i) + void GPUBVH::Update(const wi::scene::Scene& scene) { - const wiHairParticle& hair = scene.hairs[i]; - - if (hair.meshID != INVALID_ENTITY) - { - totalTriangles += hair.segmentCount * hair.strandCount * 2; - } - } - for (size_t i = 0; i < scene.emitters.GetCount(); ++i) - { - const wiEmittedParticle& emitter = scene.emitters[i]; - totalTriangles += emitter.GetMaxParticleCount() * 2; - } - - if (totalTriangles > 0 && !primitiveCounterBuffer.IsValid()) - { - GPUBufferDesc desc; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - desc.stride = sizeof(uint); - desc.size = desc.stride; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &primitiveCounterBuffer); - device->SetName(&primitiveCounterBuffer, "primitiveCounterBuffer"); - } - - if (totalTriangles == 0) - { - primitiveCounterBuffer = {}; - } - - if (totalTriangles > primitiveCapacity) - { - primitiveCapacity = std::max(2u, totalTriangles); - - GPUBufferDesc desc; - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.stride = sizeof(BVHNode); - desc.size = desc.stride * primitiveCapacity * 2; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &bvhNodeBuffer); - device->SetName(&bvhNodeBuffer, "BVHNodeBuffer"); - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.stride = sizeof(uint); - desc.size = desc.stride * primitiveCapacity * 2; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &bvhParentBuffer); - device->SetName(&bvhParentBuffer, "BVHParentBuffer"); - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.stride = sizeof(uint); - desc.size = desc.stride * (((primitiveCapacity - 1) + 31) / 32); // bitfield for internal nodes - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &bvhFlagBuffer); - device->SetName(&bvhFlagBuffer, "BVHFlagBuffer"); - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.stride = sizeof(uint); - desc.size = desc.stride * primitiveCapacity; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &primitiveIDBuffer); - device->SetName(&primitiveIDBuffer, "primitiveIDBuffer"); - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.stride = sizeof(BVHPrimitive); - desc.size = desc.stride * primitiveCapacity; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; - desc.usage = Usage::DEFAULT; - device->CreateBuffer(&desc, nullptr, &primitiveBuffer); - device->SetName(&primitiveBuffer, "primitiveBuffer"); - - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - desc.size = desc.stride * primitiveCapacity; - desc.format = Format::UNKNOWN; - desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - desc.usage = Usage::DEFAULT; - desc.stride = sizeof(float); // morton buffer is float because sorting must be done and gpu sort operates on floats for now! - device->CreateBuffer(&desc, nullptr, &primitiveMortonBuffer); - device->SetName(&primitiveMortonBuffer, "primitiveMortonBuffer"); - } -} -void wiGPUBVH::Build(const Scene& scene, CommandList cmd) const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - auto range = wiProfiler::BeginRangeGPU("BVH Rebuild", cmd); - - uint32_t primitiveCount = 0; - - device->EventBegin("BVH - Primitive Builder", cmd); - { - device->BindComputeShader(&computeShaders[CSTYPE_BVH_PRIMITIVES], cmd); - const GPUResource* uavs[] = { - &primitiveIDBuffer, - &primitiveBuffer, - &primitiveMortonBuffer, - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + GraphicsDevice* device = wi::graphics::GetDevice(); + // Pre-gather scene properties: + uint totalTriangles = 0; for (size_t i = 0; i < scene.objects.GetCount(); ++i) { const ObjectComponent& object = scene.objects[i]; @@ -162,14 +42,163 @@ void wiGPUBVH::Build(const Scene& scene, CommandList cmd) const { const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); - for (size_t j = 0; j < mesh.subsets.size(); ++j) - { - auto& subset = mesh.subsets[j]; + totalTriangles += (uint)mesh.indices.size() / 3; + } + } + for (size_t i = 0; i < scene.hairs.GetCount(); ++i) + { + const wi::HairParticleSystem& hair = scene.hairs[i]; + if (hair.meshID != INVALID_ENTITY) + { + totalTriangles += hair.segmentCount * hair.strandCount * 2; + } + } + for (size_t i = 0; i < scene.emitters.GetCount(); ++i) + { + const wi::EmittedParticleSystem& emitter = scene.emitters[i]; + totalTriangles += emitter.GetMaxParticleCount() * 2; + } + + if (totalTriangles > 0 && !primitiveCounterBuffer.IsValid()) + { + GPUBufferDesc desc; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + desc.stride = sizeof(uint); + desc.size = desc.stride; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &primitiveCounterBuffer); + device->SetName(&primitiveCounterBuffer, "primitiveCounterBuffer"); + } + + if (totalTriangles == 0) + { + primitiveCounterBuffer = {}; + } + + if (totalTriangles > primitiveCapacity) + { + primitiveCapacity = std::max(2u, totalTriangles); + + GPUBufferDesc desc; + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.stride = sizeof(BVHNode); + desc.size = desc.stride * primitiveCapacity * 2; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &bvhNodeBuffer); + device->SetName(&bvhNodeBuffer, "BVHNodeBuffer"); + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.stride = sizeof(uint); + desc.size = desc.stride * primitiveCapacity * 2; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &bvhParentBuffer); + device->SetName(&bvhParentBuffer, "BVHParentBuffer"); + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.stride = sizeof(uint); + desc.size = desc.stride * (((primitiveCapacity - 1) + 31) / 32); // bitfield for internal nodes + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &bvhFlagBuffer); + device->SetName(&bvhFlagBuffer, "BVHFlagBuffer"); + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.stride = sizeof(uint); + desc.size = desc.stride * primitiveCapacity; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &primitiveIDBuffer); + device->SetName(&primitiveIDBuffer, "primitiveIDBuffer"); + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.stride = sizeof(BVHPrimitive); + desc.size = desc.stride * primitiveCapacity; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; + desc.usage = Usage::DEFAULT; + device->CreateBuffer(&desc, nullptr, &primitiveBuffer); + device->SetName(&primitiveBuffer, "primitiveBuffer"); + + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.size = desc.stride * primitiveCapacity; + desc.format = Format::UNKNOWN; + desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + desc.usage = Usage::DEFAULT; + desc.stride = sizeof(float); // morton buffer is float because sorting must be done and gpu sort operates on floats for now! + device->CreateBuffer(&desc, nullptr, &primitiveMortonBuffer); + device->SetName(&primitiveMortonBuffer, "primitiveMortonBuffer"); + } + } + void GPUBVH::Build(const Scene& scene, CommandList cmd) const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + + auto range = wi::profiler::BeginRangeGPU("BVH Rebuild", cmd); + + uint32_t primitiveCount = 0; + + device->EventBegin("BVH - Primitive Builder", cmd); + { + device->BindComputeShader(&computeShaders[CSTYPE_BVH_PRIMITIVES], cmd); + const GPUResource* uavs[] = { + &primitiveIDBuffer, + &primitiveBuffer, + &primitiveMortonBuffer, + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + for (size_t i = 0; i < scene.objects.GetCount(); ++i) + { + const ObjectComponent& object = scene.objects[i]; + + if (object.meshID != INVALID_ENTITY) + { + const MeshComponent& mesh = *scene.meshes.GetComponent(object.meshID); + + for (size_t j = 0; j < mesh.subsets.size(); ++j) + { + auto& subset = mesh.subsets[j]; + + BVHPushConstants push; + push.instanceIndex = (uint)i; + push.subsetIndex = (uint)j; + push.primitiveCount = subset.indexCount / 3; + push.primitiveOffset = primitiveCount; + device->PushConstants(&push, sizeof(push), cmd); + + primitiveCount += push.primitiveCount; + + device->Dispatch( + (push.primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, + 1, + 1, + cmd + ); + } + + } + } + + for (size_t i = 0; i < scene.hairs.GetCount(); ++i) + { + const wi::HairParticleSystem& hair = scene.hairs[i]; + + if (hair.meshID != INVALID_ENTITY) + { BVHPushConstants push; - push.instanceIndex = (uint)i; - push.subsetIndex = (uint)j; - push.primitiveCount = subset.indexCount / 3; + push.instanceIndex = (uint)(scene.objects.GetCount() + i); + push.subsetIndex = 0; + push.primitiveCount = hair.segmentCount * hair.strandCount * 2; push.primitiveOffset = primitiveCount; device->PushConstants(&push, sizeof(push), cmd); @@ -182,248 +211,223 @@ void wiGPUBVH::Build(const Scene& scene, CommandList cmd) const cmd ); } - } - } - for (size_t i = 0; i < scene.hairs.GetCount(); ++i) - { - const wiHairParticle& hair = scene.hairs[i]; - - if (hair.meshID != INVALID_ENTITY) + for (size_t i = 0; i < scene.emitters.GetCount(); ++i) { - BVHPushConstants push; - push.instanceIndex = (uint)(scene.objects.GetCount() + i); - push.subsetIndex = 0; - push.primitiveCount = hair.segmentCount * hair.strandCount * 2; - push.primitiveOffset = primitiveCount; - device->PushConstants(&push, sizeof(push), cmd); + const wi::EmittedParticleSystem& emitter = scene.emitters[i]; - primitiveCount += push.primitiveCount; + if (emitter.GetMaxParticleCount() > 0) + { + BVHPushConstants push; + push.instanceIndex = (uint)(scene.objects.GetCount() + i); + push.subsetIndex = 0; + push.primitiveCount = emitter.GetMaxParticleCount() * 2; + push.primitiveOffset = primitiveCount; + device->PushConstants(&push, sizeof(push), cmd); - device->Dispatch( - (push.primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, - 1, - 1, - cmd - ); + primitiveCount += push.primitiveCount; + + device->Dispatch( + (push.primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, + 1, + 1, + cmd + ); + } } + + GPUBarrier barriers[] = { + GPUBarrier::Memory() + }; + device->Barrier(barriers, arraysize(barriers), cmd); } - for (size_t i = 0; i < scene.emitters.GetCount(); ++i) { - const wiEmittedParticle& emitter = scene.emitters[i]; - - if (emitter.GetMaxParticleCount() > 0) - { - BVHPushConstants push; - push.instanceIndex = (uint)(scene.objects.GetCount() + i); - push.subsetIndex = 0; - push.primitiveCount = emitter.GetMaxParticleCount() * 2; - push.primitiveOffset = primitiveCount; - device->PushConstants(&push, sizeof(push), cmd); - - primitiveCount += push.primitiveCount; - - device->Dispatch( - (push.primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, - 1, - 1, - cmd - ); - } + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&primitiveCounterBuffer, ResourceState::SHADER_RESOURCE, ResourceState::COPY_DST), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->UpdateBuffer(&primitiveCounterBuffer, &primitiveCount, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&primitiveCounterBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), + }; + device->Barrier(barriers, arraysize(barriers), cmd); } - GPUBarrier barriers[] = { - GPUBarrier::Memory() - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } + device->EventEnd(cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&primitiveCounterBuffer, ResourceState::SHADER_RESOURCE, ResourceState::COPY_DST), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->UpdateBuffer(&primitiveCounterBuffer, &primitiveCount, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&primitiveCounterBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } + device->EventBegin("BVH - Sort Primitive Mortons", cmd); + wi::gpusortlib::Sort(primitiveCount, primitiveMortonBuffer, primitiveCounterBuffer, 0, primitiveIDBuffer, cmd); + device->EventEnd(cmd); - device->EventEnd(cmd); + device->EventBegin("BVH - Build Hierarchy", cmd); + { + device->BindComputeShader(&computeShaders[CSTYPE_BVH_HIERARCHY], cmd); + const GPUResource* uavs[] = { + &bvhNodeBuffer, + &bvhParentBuffer, + &bvhFlagBuffer + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - device->EventBegin("BVH - Sort Primitive Mortons", cmd); - wiGPUSortLib::Sort(primitiveCount, primitiveMortonBuffer, primitiveCounterBuffer, 0, primitiveIDBuffer, cmd); - device->EventEnd(cmd); + const GPUResource* res[] = { + &primitiveCounterBuffer, + &primitiveIDBuffer, + &primitiveMortonBuffer, + }; + device->BindResources(res, 0, arraysize(res), cmd); - device->EventBegin("BVH - Build Hierarchy", cmd); - { - device->BindComputeShader(&computeShaders[CSTYPE_BVH_HIERARCHY], cmd); - const GPUResource* uavs[] = { - &bvhNodeBuffer, - &bvhParentBuffer, - &bvhFlagBuffer - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); - const GPUResource* res[] = { - &primitiveCounterBuffer, - &primitiveIDBuffer, - &primitiveMortonBuffer, - }; - device->BindResources(res, 0, arraysize(res), cmd); + GPUBarrier barriers[] = { + GPUBarrier::Memory() + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->EventEnd(cmd); - device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); + device->EventBegin("BVH - Propagate AABB", cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Memory() + }; + device->Barrier(barriers, arraysize(barriers), cmd); - GPUBarrier barriers[] = { - GPUBarrier::Memory() - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->EventEnd(cmd); + device->BindComputeShader(&computeShaders[CSTYPE_BVH_PROPAGATEAABB], cmd); + const GPUResource* uavs[] = { + &bvhNodeBuffer, + &bvhFlagBuffer, + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - device->EventBegin("BVH - Propagate AABB", cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Memory() - }; - device->Barrier(barriers, arraysize(barriers), cmd); + const GPUResource* res[] = { + &primitiveCounterBuffer, + &primitiveIDBuffer, + &primitiveBuffer, + &bvhParentBuffer, + }; + device->BindResources(res, 0, arraysize(res), cmd); - device->BindComputeShader(&computeShaders[CSTYPE_BVH_PROPAGATEAABB], cmd); - const GPUResource* uavs[] = { - &bvhNodeBuffer, - &bvhFlagBuffer, - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); - const GPUResource* res[] = { - &primitiveCounterBuffer, - &primitiveIDBuffer, - &primitiveBuffer, - &bvhParentBuffer, - }; - device->BindResources(res, 0, arraysize(res), cmd); + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->EventEnd(cmd); - device->Dispatch((primitiveCount + BVH_BUILDER_GROUPSIZE - 1) / BVH_BUILDER_GROUPSIZE, 1, 1, cmd); - - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->EventEnd(cmd); - - wiProfiler::EndRange(range); // BVH rebuild + wi::profiler::EndRange(range); // BVH rebuild #ifdef BVH_VALIDATE - { - GPUBufferDesc readback_desc; - bool download_success; - - // Download primitive count: - readback_desc = primitiveCounterBuffer.GetDesc(); - readback_desc.usage = USAGE_STAGING; - readback_desc.CPUAccessFlags = CPU_ACCESS_READ; - readback_desc.bind_flags = 0; - readback_desc.Flags = 0; - GPUBuffer readback_primitiveCounterBuffer; - device->CreateBuffer(&readback_desc, nullptr, &readback_primitiveCounterBuffer); - uint primitiveCount; - download_success = device->DownloadResource(&primitiveCounterBuffer, &readback_primitiveCounterBuffer, &primitiveCount, cmd); - assert(download_success); - - if (primitiveCount > 0) { - const uint leafNodeOffset = primitiveCount - 1; + GPUBufferDesc readback_desc; + bool download_success; - // Validate node buffer: - readback_desc = bvhNodeBuffer.GetDesc(); + // Download primitive count: + readback_desc = primitiveCounterBuffer.GetDesc(); readback_desc.usage = USAGE_STAGING; readback_desc.CPUAccessFlags = CPU_ACCESS_READ; readback_desc.bind_flags = 0; readback_desc.Flags = 0; - GPUBuffer readback_nodeBuffer; - device->CreateBuffer(&readback_desc, nullptr, &readback_nodeBuffer); - vector nodes(readback_desc.size / sizeof(BVHNode)); - download_success = device->DownloadResource(&bvhNodeBuffer, &readback_nodeBuffer, nodes.data(), cmd); + GPUBuffer readback_primitiveCounterBuffer; + device->CreateBuffer(&readback_desc, nullptr, &readback_primitiveCounterBuffer); + uint primitiveCount; + download_success = device->DownloadResource(&primitiveCounterBuffer, &readback_primitiveCounterBuffer, &primitiveCount, cmd); assert(download_success); - set visitedLeafs; - vector stack; - stack.push_back(0); - while (!stack.empty()) - { - uint nodeIndex = stack.back(); - stack.pop_back(); - if (nodeIndex >= leafNodeOffset) - { - // leaf node - assert(visitedLeafs.count(nodeIndex) == 0); // leaf node was already visited, this must not happen! - visitedLeafs.insert(nodeIndex); - } - else - { - // internal node - BVHNode& node = nodes[nodeIndex]; - stack.push_back(node.LeftChildIndex); - stack.push_back(node.RightChildIndex); - } - } - for (uint i = 0; i < primitiveCount; ++i) + if (primitiveCount > 0) { - uint nodeIndex = leafNodeOffset + i; - BVHNode& leaf = nodes[nodeIndex]; - assert(leaf.LeftChildIndex == 0 && leaf.RightChildIndex == 0); // a leaf must have no children - assert(visitedLeafs.count(nodeIndex) > 0); // every leaf node must have been visited in the traversal above - } + const uint leafNodeOffset = primitiveCount - 1; - // Validate flag buffer: - readback_desc = bvhFlagBuffer.GetDesc(); - readback_desc.usage = USAGE_STAGING; - readback_desc.CPUAccessFlags = CPU_ACCESS_READ; - readback_desc.bind_flags = 0; - readback_desc.Flags = 0; - GPUBuffer readback_flagBuffer; - device->CreateBuffer(&readback_desc, nullptr, &readback_flagBuffer); - vector flags(readback_desc.size / sizeof(uint)); - download_success = device->DownloadResource(&bvhFlagBuffer, &readback_flagBuffer, flags.data(), cmd); - assert(download_success); - for (auto& x : flags) - { - if (x > 2) + // Validate node buffer: + readback_desc = bvhNodeBuffer.GetDesc(); + readback_desc.usage = USAGE_STAGING; + readback_desc.CPUAccessFlags = CPU_ACCESS_READ; + readback_desc.bind_flags = 0; + readback_desc.Flags = 0; + GPUBuffer readback_nodeBuffer; + device->CreateBuffer(&readback_desc, nullptr, &readback_nodeBuffer); + vector nodes(readback_desc.size / sizeof(BVHNode)); + download_success = device->DownloadResource(&bvhNodeBuffer, &readback_nodeBuffer, nodes.data(), cmd); + assert(download_success); + set visitedLeafs; + vector stack; + stack.push_back(0); + while (!stack.empty()) { - assert(0); // flagbuffer anomaly detected: node can't have more than two children (AABB propagation step)! - break; + uint nodeIndex = stack.back(); + stack.pop_back(); + + if (nodeIndex >= leafNodeOffset) + { + // leaf node + assert(visitedLeafs.count(nodeIndex) == 0); // leaf node was already visited, this must not happen! + visitedLeafs.insert(nodeIndex); + } + else + { + // internal node + BVHNode& node = nodes[nodeIndex]; + stack.push_back(node.LeftChildIndex); + stack.push_back(node.RightChildIndex); + } + } + for (uint i = 0; i < primitiveCount; ++i) + { + uint nodeIndex = leafNodeOffset + i; + BVHNode& leaf = nodes[nodeIndex]; + assert(leaf.LeftChildIndex == 0 && leaf.RightChildIndex == 0); // a leaf must have no children + assert(visitedLeafs.count(nodeIndex) > 0); // every leaf node must have been visited in the traversal above + } + + // Validate flag buffer: + readback_desc = bvhFlagBuffer.GetDesc(); + readback_desc.usage = USAGE_STAGING; + readback_desc.CPUAccessFlags = CPU_ACCESS_READ; + readback_desc.bind_flags = 0; + readback_desc.Flags = 0; + GPUBuffer readback_flagBuffer; + device->CreateBuffer(&readback_desc, nullptr, &readback_flagBuffer); + vector flags(readback_desc.size / sizeof(uint)); + download_success = device->DownloadResource(&bvhFlagBuffer, &readback_flagBuffer, flags.data(), cmd); + assert(download_success); + for (auto& x : flags) + { + if (x > 2) + { + assert(0); // flagbuffer anomaly detected: node can't have more than two children (AABB propagation step)! + break; + } } } } - } #endif // BVH_VALIDATE -} + } -void wiGPUBVH::Clear() -{ - primitiveCapacity = 0; -} - -namespace wiGPUBVH_Internal -{ - void LoadShaders() + void GPUBVH::Clear() { - wiRenderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_PRIMITIVES], "bvh_primitivesCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_HIERARCHY], "bvh_hierarchyCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_PROPAGATEAABB], "bvh_propagateaabbCS.cso"); + primitiveCapacity = 0; + } + + namespace GPUBVH_Internal + { + void LoadShaders() + { + wi::renderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_PRIMITIVES], "bvh_primitivesCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_HIERARCHY], "bvh_hierarchyCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, computeShaders[CSTYPE_BVH_PROPAGATEAABB], "bvh_propagateaabbCS.cso"); + } + } + + void GPUBVH::Initialize() + { + wi::Timer timer; + + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { GPUBVH_Internal::LoadShaders(); }); + GPUBVH_Internal::LoadShaders(); + + wi::backlog::post("wi::GPUBVH Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } } - -void wiGPUBVH::Initialize() -{ - wiTimer timer; - - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiGPUBVH_Internal::LoadShaders(); }); - wiGPUBVH_Internal::LoadShaders(); - - wiBackLog::post("wiGPUBVH Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); -} diff --git a/WickedEngine/wiGPUBVH.h b/WickedEngine/wiGPUBVH.h index beca46bef..8ed1eef3a 100644 --- a/WickedEngine/wiGPUBVH.h +++ b/WickedEngine/wiGPUBVH.h @@ -3,23 +3,26 @@ #include "wiGraphicsDevice.h" #include "wiScene_Decl.h" -struct wiGPUBVH +namespace wi { - // Scene BVH intersection resources: - wiGraphics::GPUBuffer bvhNodeBuffer; - wiGraphics::GPUBuffer bvhParentBuffer; - wiGraphics::GPUBuffer bvhFlagBuffer; - wiGraphics::GPUBuffer primitiveCounterBuffer; - wiGraphics::GPUBuffer primitiveIDBuffer; - wiGraphics::GPUBuffer primitiveBuffer; - wiGraphics::GPUBuffer primitiveMortonBuffer; - uint32_t primitiveCapacity = 0; - bool IsValid() const { return primitiveCounterBuffer.IsValid(); } + struct GPUBVH + { + // Scene BVH intersection resources: + wi::graphics::GPUBuffer bvhNodeBuffer; + wi::graphics::GPUBuffer bvhParentBuffer; + wi::graphics::GPUBuffer bvhFlagBuffer; + wi::graphics::GPUBuffer primitiveCounterBuffer; + wi::graphics::GPUBuffer primitiveIDBuffer; + wi::graphics::GPUBuffer primitiveBuffer; + wi::graphics::GPUBuffer primitiveMortonBuffer; + uint32_t primitiveCapacity = 0; + bool IsValid() const { return primitiveCounterBuffer.IsValid(); } - void Update(const wiScene::Scene& scene); - void Build(const wiScene::Scene& scene, wiGraphics::CommandList cmd) const; + void Update(const wi::scene::Scene& scene); + void Build(const wi::scene::Scene& scene, wi::graphics::CommandList cmd) const; - void Clear(); + void Clear(); - static void Initialize(); -}; + static void Initialize(); + }; +} diff --git a/WickedEngine/wiGPUSortLib.cpp b/WickedEngine/wiGPUSortLib.cpp index 07125a681..9ee4f76f0 100644 --- a/WickedEngine/wiGPUSortLib.cpp +++ b/WickedEngine/wiGPUSortLib.cpp @@ -2,13 +2,13 @@ #include "wiRenderer.h" #include "wiResourceManager.h" #include "shaders/ShaderInterop_GPUSortLib.h" -#include "wiEvent.h" +#include "wiEventHandler.h" #include "wiTimer.h" -#include "wiBackLog.h" +#include "wiBacklog.h" -using namespace wiGraphics; +using namespace wi::graphics; -namespace wiGPUSortLib +namespace wi::gpusortlib { static GPUBuffer indirectBuffer; static Shader kickoffSortCS; @@ -19,28 +19,28 @@ namespace wiGPUSortLib void LoadShaders() { - wiRenderer::LoadShader(ShaderStage::CS, kickoffSortCS, "gpusortlib_kickoffSortCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sortCS, "gpusortlib_sortCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sortInnerCS, "gpusortlib_sortInnerCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, sortStepCS, "gpusortlib_sortStepCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, kickoffSortCS, "gpusortlib_kickoffSortCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sortCS, "gpusortlib_sortCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sortInnerCS, "gpusortlib_sortInnerCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, sortStepCS, "gpusortlib_sortStepCS.cso"); } void Initialize() { - wiTimer timer; + wi::Timer timer; GPUBufferDesc bd; bd.usage = Usage::DEFAULT; bd.bind_flags = BindFlag::UNORDERED_ACCESS; bd.misc_flags = ResourceMiscFlag::INDIRECT_ARGS | ResourceMiscFlag::BUFFER_RAW; bd.size = sizeof(IndirectDispatchArgs); - wiGraphics::GetDevice()->CreateBuffer(&bd, nullptr, &indirectBuffer); + wi::graphics::GetDevice()->CreateBuffer(&bd, nullptr, &indirectBuffer); - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); LoadShaders(); - wiBackLog::post("wiGPUSortLib Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::gpusortlib Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } @@ -52,7 +52,7 @@ namespace wiGPUSortLib const GPUBuffer& indexBuffer_write, CommandList cmd) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("GPUSortLib", cmd); diff --git a/WickedEngine/wiGPUSortLib.h b/WickedEngine/wiGPUSortLib.h index a856915df..96954dda6 100644 --- a/WickedEngine/wiGPUSortLib.h +++ b/WickedEngine/wiGPUSortLib.h @@ -2,7 +2,7 @@ #include "CommonInclude.h" #include "wiGraphicsDevice.h" -namespace wiGPUSortLib +namespace wi::gpusortlib { // Perform bitonic sort on a GPU dataset // maxCount - Maximum size of the dataset. GPU count can be smaller (see: counterBuffer_read param) @@ -12,11 +12,11 @@ namespace wiGPUSortLib // indexBuffer_write - The index list which to sort. Contains index values which can index the sortBase_read buffer. This will be modified (Read + Write) void Sort( uint32_t maxCount, - const wiGraphics::GPUBuffer& comparisonBuffer_read, - const wiGraphics::GPUBuffer& counterBuffer_read, + const wi::graphics::GPUBuffer& comparisonBuffer_read, + const wi::graphics::GPUBuffer& counterBuffer_read, uint32_t counterReadOffset, - const wiGraphics::GPUBuffer& indexBuffer_write, - wiGraphics::CommandList cmd + const wi::graphics::GPUBuffer& indexBuffer_write, + wi::graphics::CommandList cmd ); void Initialize(); diff --git a/WickedEngine/wiGUI.cpp b/WickedEngine/wiGUI.cpp index 5bc3175a7..bb1e5b798 100644 --- a/WickedEngine/wiGUI.cpp +++ b/WickedEngine/wiGUI.cpp @@ -1,142 +1,3172 @@ #include "wiGUI.h" #include "wiInput.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiProfiler.h" +#include "wiRenderer.h" +#include "wiTimer.h" +#include "wiEventHandler.h" +#include "wiFont.h" +#include "wiImage.h" +#include "wiTextureHelper.h" +#include "wiBacklog.h" -using namespace wiGraphics; +#include -void wiGUI::Update(const wiCanvas& canvas, float dt) +using namespace wi::graphics; +using namespace wi::primitive; + +namespace wi::gui { - if (!visible) + static wi::graphics::PipelineState PSO_colored; + + void LoadShaders() { - return; + PipelineStateDesc desc; + desc.vs = wi::renderer::GetShader(wi::enums::VSTYPE_VERTEXCOLOR); + desc.ps = wi::renderer::GetShader(wi::enums::PSTYPE_VERTEXCOLOR); + desc.il = wi::renderer::GetInputLayout(wi::enums::ILTYPE_VERTEXCOLOR); + desc.dss = wi::renderer::GetDepthStencilState(wi::enums::DSSTYPE_DEPTHDISABLED); + desc.bs = wi::renderer::GetBlendState(wi::enums::BSTYPE_TRANSPARENT); + desc.rs = wi::renderer::GetRasterizerState(wi::enums::RSTYPE_DOUBLESIDED); + desc.pt = PrimitiveTopology::TRIANGLESTRIP; + wi::graphics::GetDevice()->CreatePipelineState(&desc, &PSO_colored); } - auto range = wiProfiler::BeginRangeCPU("GUI Update"); - - XMFLOAT4 pointer = wiInput::GetPointer(); - Hitbox2D pointerHitbox = Hitbox2D(XMFLOAT2(pointer.x, pointer.y), XMFLOAT2(1, 1)); - - uint32_t priority = 0; - - focus = false; - for (auto& widget : widgets) + void Initialize() { - widget->force_disable = focus; - widget->Update(canvas, dt); - widget->force_disable = false; + wi::Timer timer; - if (widget->priority_change) + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); + LoadShaders(); + + wi::backlog::post("wi::gui Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + } + + + void GUI::Update(const wi::Canvas& canvas, float dt) + { + if (!visible) { - widget->priority_change = false; - widget->priority = priority++; + return; + } + + auto range = wi::profiler::BeginRangeCPU("GUI Update"); + + XMFLOAT4 pointer = wi::input::GetPointer(); + Hitbox2D pointerHitbox = Hitbox2D(XMFLOAT2(pointer.x, pointer.y), XMFLOAT2(1, 1)); + + uint32_t priority = 0; + + focus = false; + for (auto& widget : widgets) + { + widget->force_disable = focus; + widget->Update(canvas, dt); + widget->force_disable = false; + + if (widget->priority_change) + { + widget->priority_change = false; + widget->priority = priority++; + } + else + { + widget->priority = ~0u; + } + + if (widget->IsVisible() && widget->hitBox.intersects(pointerHitbox)) + { + focus = true; + } + if (widget->GetState() > IDLE) + { + focus = true; + } + } + + //Sort only if there are priority changes + if (priority > 0) + { + //Use std::stable_sort instead of std::sort to preserve UI element order with equal priorities + std::stable_sort(widgets.begin(), widgets.end(), [](const Widget* a, const Widget* b) { + return a->priority < b->priority; + }); + } + + wi::profiler::EndRange(range); + } + void GUI::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!visible) + { + return; + } + + auto range_cpu = wi::profiler::BeginRangeCPU("GUI Render"); + auto range_gpu = wi::profiler::BeginRangeGPU("GUI Render", cmd); + + Rect scissorRect; + scissorRect.bottom = (int32_t)(canvas.GetPhysicalHeight()); + scissorRect.left = (int32_t)(0); + scissorRect.right = (int32_t)(canvas.GetPhysicalWidth()); + scissorRect.top = (int32_t)(0); + + GraphicsDevice* device = wi::graphics::GetDevice(); + + device->EventBegin("GUI", cmd); + // Rendering is back to front: + for (auto it = widgets.rbegin(); it != widgets.rend(); ++it) + { + const Widget* widget = (*it); + device->BindScissorRects(1, &scissorRect, cmd); + widget->Render(canvas, cmd); + } + + device->BindScissorRects(1, &scissorRect, cmd); + for (auto& x : widgets) + { + x->RenderTooltip(canvas, cmd); + } + + device->EventEnd(cmd); + + wi::profiler::EndRange(range_cpu); + wi::profiler::EndRange(range_gpu); + } + void GUI::AddWidget(Widget* widget) + { + if (widget != nullptr) + { + assert(std::find(widgets.begin(), widgets.end(), widget) == widgets.end()); // don't attach one widget twice! + widgets.push_back(widget); + } + } + void GUI::RemoveWidget(Widget* widget) + { + for (auto& x : widgets) + { + if (x == widget) + { + x = widgets.back(); + widgets.pop_back(); + break; + } + } + } + Widget* GUI::GetWidget(const std::string& name) + { + for (auto& x : widgets) + { + if (x->GetName() == name) + { + return x; + } + } + return nullptr; + } + bool GUI::HasFocus() + { + if (!visible) + { + return false; + } + + return focus; + } + + + + Widget::Widget() + { + sprites[IDLE].params.color = wi::Color::Booger(); + sprites[FOCUS].params.color = wi::Color::Gray(); + sprites[ACTIVE].params.color = wi::Color::White(); + sprites[DEACTIVATING].params.color = wi::Color::Gray(); + font.params.shadowColor = wi::Color::Black(); + + for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) + { + sprites[i].params.blendFlag = wi::enums::BLENDMODE_OPAQUE; + sprites[i].params.enableBackground(); + } + } + void Widget::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + if (force_disable) + { + state = IDLE; + } + + hitBox = Hitbox2D(XMFLOAT2(translation.x, translation.y), XMFLOAT2(scale.x, scale.y)); + + if (!force_disable && GetState() != WIDGETSTATE::ACTIVE && !tooltip.empty() && GetPointerHitbox().intersects(hitBox)) + { + tooltipTimer++; } else { - widget->priority = ~0u; + tooltipTimer = 0; } - if (widget->IsVisible() && widget->hitBox.intersects(pointerHitbox)) + UpdateTransform(); + + if (parent != nullptr) { - focus = true; + this->UpdateTransform_Parented(*parent); } - if (widget->GetState() > wiWidget::IDLE) + + XMVECTOR S, R, T; + XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&world)); + XMStoreFloat3(&translation, T); + XMStoreFloat3(&scale, S); + + scissorRect.bottom = (int32_t)(translation.y + scale.y); + scissorRect.left = (int32_t)(translation.x); + scissorRect.right = (int32_t)(translation.x + scale.x); + scissorRect.top = (int32_t)(translation.y); + + // default sprite and font placement: + for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) { - focus = true; + sprites[i].params.pos.x = translation.x; + sprites[i].params.pos.y = translation.y; + sprites[i].params.siz.x = scale.x; + sprites[i].params.siz.y = scale.y; + sprites[i].params.fade = enabled ? 0.0f : 0.5f; + } + font.params.posX = translation.x; + font.params.posY = translation.y; + } + void Widget::RenderTooltip(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + + if (tooltipTimer > 25) + { + float screenwidth = canvas.GetLogicalWidth(); + float screenheight = canvas.GetLogicalHeight(); + + wi::font::Params fontProps = wi::font::Params(0, 0, wi::font::WIFONTSIZE_DEFAULT, wi::font::WIFALIGN_LEFT, wi::font::WIFALIGN_TOP); + fontProps.color = wi::Color(25, 25, 25, 255); + wi::SpriteFont tooltipFont = wi::SpriteFont(tooltip, fontProps); + if (!scriptTip.empty()) + { + tooltipFont.SetText(tooltip + "\n" + scriptTip); + } + + static const float _border = 2; + float textWidth = tooltipFont.TextWidth() + _border * 2; + float textHeight = tooltipFont.TextHeight() + _border * 2; + + XMFLOAT2 pointer = GetPointerHitbox().pos; + tooltipFont.params.posX = pointer.x; + tooltipFont.params.posY = pointer.y; + + if (tooltipFont.params.posX + textWidth > screenwidth) + { + tooltipFont.params.posX -= tooltipFont.params.posX + textWidth - screenwidth; + } + if (tooltipFont.params.posX < 0) + { + tooltipFont.params.posX = 0; + } + + if (tooltipFont.params.posY > screenheight * 0.8f) + { + tooltipFont.params.posY -= 30; + } + else + { + tooltipFont.params.posY += 40; + } + + wi::image::Draw(wi::texturehelper::getWhite(), + wi::image::Params(tooltipFont.params.posX - _border, tooltipFont.params.posY - _border, + textWidth, textHeight, wi::Color(255, 234, 165)), cmd); + tooltipFont.SetText(tooltip); + tooltipFont.Draw(cmd); + if (!scriptTip.empty()) + { + tooltipFont.SetText(scriptTip); + tooltipFont.params.posY += (int)(textHeight / 2); + tooltipFont.params.color = wi::Color(25, 25, 25, 110); + tooltipFont.Draw(cmd); + } + } + } + const std::string& Widget::GetName() const + { + return name; + } + void Widget::SetName(const std::string& value) + { + if (value.length() <= 0) + { + static std::atomic widgetID{ 0 }; + name = "widget_" + std::to_string(widgetID.fetch_add(1)); + } + else + { + name = value; + } + } + const std::string Widget::GetText() const + { + return font.GetTextA(); + } + void Widget::SetText(const std::string& value) + { + font.SetText(value); + } + void Widget::SetText(std::string&& value) + { + font.SetText(value); + } + void Widget::SetTooltip(const std::string& value) + { + tooltip = value; + } + void Widget::SetTooltip(std::string&& value) + { + tooltip = value; + } + void Widget::SetScriptTip(const std::string& value) + { + scriptTip = value; + } + void Widget::SetScriptTip(std::string&& value) + { + scriptTip = value; + } + void Widget::SetPos(const XMFLOAT2& value) + { + SetDirty(); + translation_local.x = value.x; + translation_local.y = value.y; + UpdateTransform(); + + translation = translation_local; + } + void Widget::SetSize(const XMFLOAT2& value) + { + SetDirty(); + scale_local.x = value.x; + scale_local.y = value.y; + UpdateTransform(); + + scale = scale_local; + } + WIDGETSTATE Widget::GetState() const + { + return state; + } + void Widget::SetEnabled(bool val) + { + if (enabled != val) + { + priority_change = val; + enabled = val; + } + } + bool Widget::IsEnabled() const + { + return enabled && visible && !force_disable; + } + void Widget::SetVisible(bool val) + { + if (visible != val) + { + priority_change |= val; + visible = val; + } + } + bool Widget::IsVisible() const + { + return visible; + } + void Widget::Activate() + { + priority_change = true; + state = ACTIVE; + tooltipTimer = 0; + } + void Widget::Deactivate() + { + state = DEACTIVATING; + tooltipTimer = 0; + } + void Widget::SetColor(wi::Color color, WIDGETSTATE state) + { + if (state == WIDGETSTATE_COUNT) + { + for (int i = 0; i < WIDGETSTATE_COUNT; ++i) + { + sprites[i].params.color = color; + } + } + else + { + sprites[state].params.color = color; + } + } + wi::Color Widget::GetColor() const + { + return wi::Color::fromFloat4(sprites[GetState()].params.color); + } + void Widget::SetImage(wi::Resource textureResource, WIDGETSTATE state) + { + if (state == WIDGETSTATE_COUNT) + { + for (int i = 0; i < WIDGETSTATE_COUNT; ++i) + { + sprites[i].textureResource = textureResource; + } + } + else + { + sprites[state].textureResource = textureResource; } } - //Sort only if there are priority changes - if (priority > 0) + void Widget::AttachTo(Widget* parent) { - //Use std::stable_sort instead of std::sort to preserve UI element order with equal priorities - std::stable_sort(widgets.begin(), widgets.end(), [](const wiWidget* a, const wiWidget* b) { - return a->priority < b->priority; - }); - } + this->parent = parent; - wiProfiler::EndRange(range); -} - -void wiGUI::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!visible) - { - return; - } - - auto range_cpu = wiProfiler::BeginRangeCPU("GUI Render"); - auto range_gpu = wiProfiler::BeginRangeGPU("GUI Render", cmd); - - Rect scissorRect; - scissorRect.bottom = (int32_t)(canvas.GetPhysicalHeight()); - scissorRect.left = (int32_t)(0); - scissorRect.right = (int32_t)(canvas.GetPhysicalWidth()); - scissorRect.top = (int32_t)(0); - - GraphicsDevice* device = wiGraphics::GetDevice(); - - device->EventBegin("GUI", cmd); - // Rendering is back to front: - for (auto it = widgets.rbegin(); it != widgets.rend(); ++it) - { - const wiWidget* widget = (*it); - device->BindScissorRects(1, &scissorRect, cmd); - widget->Render(canvas, cmd); - } - - device->BindScissorRects(1, &scissorRect, cmd); - for (auto& x : widgets) - { - x->RenderTooltip(canvas, cmd); - } - - device->EventEnd(cmd); - - wiProfiler::EndRange(range_cpu); - wiProfiler::EndRange(range_gpu); -} - -void wiGUI::AddWidget(wiWidget* widget) -{ - if (widget != nullptr) - { - assert(std::find(widgets.begin(), widgets.end(), widget) == widgets.end()); // don't attach one widget twice! - widgets.push_back(widget); - } -} - -void wiGUI::RemoveWidget(wiWidget* widget) -{ - for (auto& x : widgets) - { - if (x == widget) + if (parent != nullptr) { - x = widgets.back(); - widgets.pop_back(); + parent->UpdateTransform(); + XMMATRIX B = XMMatrixInverse(nullptr, XMLoadFloat4x4(&parent->world)); + MatrixTransform(B); + } + + UpdateTransform(); + + if (parent != nullptr) + { + UpdateTransform_Parented(*parent); + } + } + void Widget::Detach() + { + if (parent != nullptr) + { + parent = nullptr; + ApplyTransform(); + } + } + void Widget::ApplyScissor(const wi::Canvas& canvas, const Rect rect, CommandList cmd, bool constrain_to_parent) const + { + Rect scissor = rect; + + if (constrain_to_parent && parent != nullptr) + { + Widget* recurse_parent = parent; + while (recurse_parent != nullptr) + { + scissor.bottom = std::min(scissor.bottom, recurse_parent->scissorRect.bottom); + scissor.top = std::max(scissor.top, recurse_parent->scissorRect.top); + scissor.left = std::max(scissor.left, recurse_parent->scissorRect.left); + scissor.right = std::min(scissor.right, recurse_parent->scissorRect.right); + + recurse_parent = recurse_parent->parent; + } + } + + if (scissor.left > scissor.right) + { + scissor.left = scissor.right; + } + if (scissor.top > scissor.bottom) + { + scissor.top = scissor.bottom; + } + + GraphicsDevice* device = wi::graphics::GetDevice(); + float scale = canvas.GetDPIScaling(); + scissor.bottom = int32_t((float)scissor.bottom * scale); + scissor.top = int32_t((float)scissor.top * scale); + scissor.left = int32_t((float)scissor.left * scale); + scissor.right = int32_t((float)scissor.right * scale); + device->BindScissorRects(1, &scissor, cmd); + } + Hitbox2D Widget::GetPointerHitbox() const + { + XMFLOAT4 pointer = wi::input::GetPointer(); + return Hitbox2D(XMFLOAT2(pointer.x, pointer.y), XMFLOAT2(1, 1)); + } + + + + + void Button::Create(const std::string& name) + { + SetName(name); + SetText(name); + OnClick([](EventArgs args) {}); + OnDragStart([](EventArgs args) {}); + OnDrag([](EventArgs args) {}); + OnDragEnd([](EventArgs args) {}); + SetSize(XMFLOAT2(100, 30)); + + font.params.h_align = wi::font::WIFALIGN_CENTER; + font.params.v_align = wi::font::WIFALIGN_CENTER; + } + void Button::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + if (IsEnabled()) + { + hitBox.pos.x = translation.x; + hitBox.pos.y = translation.y; + hitBox.siz.x = scale.x; + hitBox.siz.y = scale.y; + + Hitbox2D pointerHitbox = GetPointerHitbox(); + + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + EventArgs args; + args.clickPos = pointerHitbox.pos; + onDragEnd(args); + + if (pointerHitbox.intersects(hitBox)) + { + // Click occurs when the button is released within the bounds + onClick(args); + } + + state = IDLE; + } + if (state == ACTIVE) + { + Deactivate(); + } + + bool clicked = false; + // hover the button + if (pointerHitbox.intersects(hitBox)) + { + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == FOCUS) + { + // activate + clicked = true; + } + } + + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == DEACTIVATING) + { + // Keep pressed until mouse is released + Activate(); + + EventArgs args; + args.clickPos = pointerHitbox.pos; + XMFLOAT3 posDelta; + posDelta.x = pointerHitbox.pos.x - prevPos.x; + posDelta.y = pointerHitbox.pos.y - prevPos.y; + posDelta.z = 0; + args.deltaPos = XMFLOAT2(posDelta.x, posDelta.y); + onDrag(args); + } + } + + if (clicked) + { + EventArgs args; + args.clickPos = pointerHitbox.pos; + dragStart = args.clickPos; + args.startPos = dragStart; + onDragStart(args); + Activate(); + } + + prevPos.x = pointerHitbox.pos.x; + prevPos.y = pointerHitbox.pos.y; + } + + switch (font.params.h_align) + { + case wi::font::WIFALIGN_LEFT: + font.params.posX = translation.x + 2; + break; + case wi::font::WIFALIGN_RIGHT: + font.params.posX = translation.x + scale.x - 2; + break; + case wi::font::WIFALIGN_CENTER: + default: + font.params.posX = translation.x + scale.x * 0.5f; + break; + } + switch (font.params.v_align) + { + case wi::font::WIFALIGN_TOP: + font.params.posY = translation.y + 2; + break; + case wi::font::WIFALIGN_BOTTOM: + font.params.posY = translation.y + scale.y - 2; + break; + case wi::font::WIFALIGN_CENTER: + default: + font.params.posY = translation.y + scale.y * 0.5f; break; } } -} - -wiWidget* wiGUI::GetWidget(const std::string& name) -{ - for (auto& x : widgets) + void Button::Render(const wi::Canvas& canvas, CommandList cmd) const { - if (x->GetName() == name) + if (!IsVisible()) { - return x; + return; + } + + wi::Color color = GetColor(); + + ApplyScissor(canvas, scissorRect, cmd); + + sprites[state].Draw(cmd); + font.Draw(cmd); + } + void Button::OnClick(std::function func) + { + onClick = move(func); + } + void Button::OnDragStart(std::function func) + { + onDragStart = move(func); + } + void Button::OnDrag(std::function func) + { + onDrag = move(func); + } + void Button::OnDragEnd(std::function func) + { + onDragEnd = move(func); + } + + + + + void Label::Create(const std::string& name) + { + SetName(name); + SetText(name); + SetSize(XMFLOAT2(100, 20)); + } + void Label::Update(const wi::Canvas& canvas, float dt) + { + Widget::Update(canvas, dt); + + font.params.h_wrap = scale.x; + + switch (font.params.h_align) + { + case wi::font::WIFALIGN_LEFT: + font.params.posX = translation.x + 2; + break; + case wi::font::WIFALIGN_RIGHT: + font.params.posX = translation.x + scale.x - 2; + break; + case wi::font::WIFALIGN_CENTER: + default: + font.params.posX = translation.x + scale.x * 0.5f; + break; + } + switch (font.params.v_align) + { + case wi::font::WIFALIGN_TOP: + font.params.posY = translation.y + 2; + break; + case wi::font::WIFALIGN_BOTTOM: + font.params.posY = translation.y + scale.y - 2; + break; + case wi::font::WIFALIGN_CENTER: + default: + font.params.posY = translation.y + scale.y * 0.5f; + break; } } - return nullptr; -} - -bool wiGUI::HasFocus() -{ - if (!visible) + void Label::Render(const wi::Canvas& canvas, CommandList cmd) const { - return false; + if (!IsVisible()) + { + return; + } + + wi::Color color = GetColor(); + + ApplyScissor(canvas, scissorRect, cmd); + + sprites[state].Draw(cmd); + font.Draw(cmd); } - return focus; + + + + wi::SpriteFont TextInputField::font_input; + void TextInputField::Create(const std::string& name) + { + SetName(name); + SetText(name); + OnInputAccepted([](EventArgs args) {}); + SetSize(XMFLOAT2(100, 30)); + + font.params.v_align = wi::font::WIFALIGN_CENTER; + + font_description.params = font.params; + font_description.params.h_align = wi::font::WIFALIGN_RIGHT; + } + void TextInputField::SetValue(const std::string& newValue) + { + font.SetText(newValue); + } + void TextInputField::SetValue(int newValue) + { + std::stringstream ss(""); + ss << newValue; + font.SetText(ss.str()); + } + void TextInputField::SetValue(float newValue) + { + std::stringstream ss(""); + ss << newValue; + font.SetText(ss.str()); + } + const std::string TextInputField::GetValue() + { + return font.GetTextA(); + } + void TextInputField::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + if (IsEnabled()) + { + hitBox.pos.x = translation.x; + hitBox.pos.y = translation.y; + hitBox.siz.x = scale.x; + hitBox.siz.y = scale.y; + + Hitbox2D pointerHitbox = GetPointerHitbox(); + bool intersectsPointer = pointerHitbox.intersects(hitBox); + + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + + bool clicked = false; + // hover the button + if (intersectsPointer) + { + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == FOCUS) + { + // activate + clicked = true; + } + } + + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == DEACTIVATING) + { + // Keep pressed until mouse is released + Activate(); + } + } + + if (clicked) + { + Activate(); + + font_input.SetText(font.GetText()); + } + + if (state == ACTIVE) + { + if (wi::input::Press(wi::input::KEYBOARD_BUTTON_ENTER)) + { + // accept input... + + font.SetText(font_input.GetText()); + font_input.text.clear(); + + EventArgs args; + args.sValue = font.GetTextA(); + args.iValue = atoi(args.sValue.c_str()); + args.fValue = (float)atof(args.sValue.c_str()); + onInputAccepted(args); + + Deactivate(); + } + else if ((wi::input::Press(wi::input::MOUSE_BUTTON_LEFT) && !intersectsPointer) || + wi::input::Press(wi::input::KEYBOARD_BUTTON_ESCAPE)) + { + // cancel input + font_input.text.clear(); + Deactivate(); + } + + } + } + + font.params.posX = translation.x + 2; + font.params.posY = translation.y + scale.y * 0.5f; + font_description.params.posX = translation.x - 2; + font_description.params.posY = translation.y + scale.y * 0.5f; + + if (state == ACTIVE) + { + font_input.params = font.params; + } + } + void TextInputField::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + + wi::Color color = GetColor(); + + font_description.Draw(cmd); + + ApplyScissor(canvas, scissorRect, cmd); + + sprites[state].Draw(cmd); + + if (state == ACTIVE) + { + font_input.Draw(cmd); + } + else + { + font.Draw(cmd); + } + + } + void TextInputField::OnInputAccepted(std::function func) + { + onInputAccepted = move(func); + } + void TextInputField::AddInput(const char inputChar) + { + std::string value_new = font_input.GetTextA(); + value_new.push_back(inputChar); + font_input.SetText(value_new); + } + void TextInputField::DeleteFromInput() + { + std::string value_new = font_input.GetTextA(); + if (!value_new.empty()) + { + value_new.pop_back(); + } + font_input.SetText(value_new); + } + + + + + + void Slider::Create(float start, float end, float defaultValue, float step, const std::string& name) + { + this->start = start; + this->end = end; + this->value = defaultValue; + this->step = std::max(step, 1.0f); + + SetName(name); + SetText(name); + OnSlide([](EventArgs args) {}); + SetSize(XMFLOAT2(200, 40)); + + valueInputField.Create(name + "_endInputField"); + valueInputField.SetTooltip("Enter number to modify value even outside slider limits. Enter \"reset\" to reset slider to initial state."); + valueInputField.SetValue(end); + valueInputField.OnInputAccepted([this, start, end, defaultValue](EventArgs args) { + if (args.sValue.compare("reset") != std::string::npos) + { + this->value = defaultValue; + this->start = start; + this->end = end; + args.fValue = this->value; + args.iValue = (int)this->value; + } + else + { + this->value = args.fValue; + this->start = std::min(this->start, args.fValue); + this->end = std::max(this->end, args.fValue); + } + onSlide(args); + }); + + for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) + { + sprites_knob[i].params = sprites[i].params; + } + + sprites[IDLE].params.color = wi::Color(60, 60, 60, 200); + sprites[FOCUS].params.color = wi::Color(50, 50, 50, 200); + sprites[ACTIVE].params.color = wi::Color(50, 50, 50, 200); + sprites[DEACTIVATING].params.color = wi::Color(60, 60, 60, 200); + + font.params.h_align = wi::font::WIFALIGN_RIGHT; + font.params.v_align = wi::font::WIFALIGN_CENTER; + } + void Slider::SetValue(float value) + { + this->value = value; + } + float Slider::GetValue() const + { + return value; + } + void Slider::SetRange(float start, float end) + { + this->start = start; + this->end = end; + this->value = wi::math::Clamp(this->value, start, end); + } + void Slider::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + valueInputField.Detach(); + valueInputField.SetSize(XMFLOAT2(std::max(scale.y * 2, wi::font::TextWidth(valueInputField.GetText(), valueInputField.font.params) + 4), scale.y)); + valueInputField.SetPos(XMFLOAT2(translation.x + scale.x + 2, translation.y)); + valueInputField.AttachTo(this); + + scissorRect.bottom = (int32_t)(translation.y + scale.y); + scissorRect.left = (int32_t)(translation.x); + scissorRect.right = (int32_t)(translation.x + scale.x + 20 + scale.y * 2); // include the valueInputField + scissorRect.top = (int32_t)(translation.y); + + for (int i = 0; i < WIDGETSTATE_COUNT; ++i) + { + sprites_knob[i].params.siz.x = 16.0f; + valueInputField.SetColor(wi::Color::fromFloat4(this->sprites_knob[i].params.color), (WIDGETSTATE)i); + } + valueInputField.font.params.color = this->font.params.color; + valueInputField.font.params.shadowColor = this->font.params.shadowColor; + valueInputField.SetEnabled(enabled); + valueInputField.force_disable = force_disable; + valueInputField.Update(canvas, dt); + + if (IsEnabled()) + { + bool dragged = false; + + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + if (state == ACTIVE) + { + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == ACTIVE) + { + // continue drag if already grabbed wheter it is intersecting or not + dragged = true; + } + } + else + { + Deactivate(); + } + } + + const float knobWidth = sprites_knob[state].params.siz.x; + hitBox.pos.x = translation.x - knobWidth * 0.5f; + hitBox.pos.y = translation.y; + hitBox.siz.x = scale.x + knobWidth; + hitBox.siz.y = scale.y; + + Hitbox2D pointerHitbox = GetPointerHitbox(); + + + if (pointerHitbox.intersects(hitBox)) + { + // hover the slider + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == FOCUS) + { + // activate + dragged = true; + } + } + + + if (dragged) + { + EventArgs args; + args.clickPos = pointerHitbox.pos; + value = wi::math::InverseLerp(translation.x, translation.x + scale.x, args.clickPos.x); + value = wi::math::Clamp(value, 0, 1); + value *= step; + value = std::floor(value); + value /= step; + value = wi::math::Lerp(start, end, value); + args.fValue = value; + args.iValue = (int)value; + onSlide(args); + Activate(); + } + + valueInputField.SetValue(value); + } + + font.params.posY = translation.y + scale.y * 0.5f; + + const float knobWidth = sprites_knob[state].params.siz.x; + const float knobWidthHalf = knobWidth * 0.5f; + sprites_knob[state].params.pos.x = wi::math::Lerp(translation.x + knobWidthHalf + 2, translation.x + scale.x - knobWidthHalf - 2, wi::math::Clamp(wi::math::InverseLerp(start, end, value), 0, 1)); + sprites_knob[state].params.pos.y = translation.y + 2; + sprites_knob[state].params.siz.y = scale.y - 4; + sprites_knob[state].params.pivot = XMFLOAT2(0.5f, 0); + sprites_knob[state].params.fade = sprites[state].params.fade; + } + void Slider::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + + font.Draw(cmd); + + ApplyScissor(canvas, scissorRect, cmd); + + // base + sprites[state].Draw(cmd); + + // knob + sprites_knob[state].Draw(cmd); + + valueInputField.Render(canvas, cmd); + } + void Slider::RenderTooltip(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const + { + Widget::RenderTooltip(canvas, cmd); + valueInputField.RenderTooltip(canvas, cmd); + } + void Slider::OnSlide(std::function func) + { + onSlide = move(func); + } + + + + + + void CheckBox::Create(const std::string& name) + { + SetName(name); + SetText(name); + OnClick([](EventArgs args) {}); + SetSize(XMFLOAT2(20, 20)); + + font.params.h_align = wi::font::WIFALIGN_RIGHT; + font.params.v_align = wi::font::WIFALIGN_CENTER; + + for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) + { + sprites_check[i].params = sprites[i].params; + sprites_check[i].params.color = wi::math::Lerp(sprites[i].params.color, wi::Color::White().toFloat4(), 0.8f); + } + } + void CheckBox::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + if (IsEnabled()) + { + + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + if (state == ACTIVE) + { + Deactivate(); + } + + hitBox.pos.x = translation.x; + hitBox.pos.y = translation.y; + hitBox.siz.x = scale.x; + hitBox.siz.y = scale.y; + + Hitbox2D pointerHitbox = GetPointerHitbox(); + + // hover the button + if (pointerHitbox.intersects(hitBox)) + { + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == FOCUS) + { + Activate(); + } + } + + if (state == DEACTIVATING) + { + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + // Keep pressed until mouse is released + Activate(); + } + else + { + // Deactivation event + SetCheck(!GetCheck()); + EventArgs args; + args.clickPos = pointerHitbox.pos; + args.bValue = GetCheck(); + onClick(args); + } + } + } + + font.params.posY = translation.y + scale.y * 0.5f; + + sprites_check[state].params.pos.x = translation.x + scale.x * 0.25f; + sprites_check[state].params.pos.y = translation.y + scale.y * 0.25f; + sprites_check[state].params.siz = XMFLOAT2(scale.x * 0.5f, scale.y * 0.5f); + } + void CheckBox::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + + font.Draw(cmd); + + ApplyScissor(canvas, scissorRect, cmd); + + // control + sprites[state].Draw(cmd); + + // check + if (GetCheck()) + { + sprites_check[state].Draw(cmd); + } + + } + void CheckBox::OnClick(std::function func) + { + onClick = move(func); + } + void CheckBox::SetCheck(bool value) + { + checked = value; + } + bool CheckBox::GetCheck() const + { + return checked; + } + + + + + + void ComboBox::Create(const std::string& name) + { + SetName(name); + SetText(name); + OnSelect([](EventArgs args) {}); + SetSize(XMFLOAT2(100, 20)); + + font.params.h_align = wi::font::WIFALIGN_RIGHT; + font.params.v_align = wi::font::WIFALIGN_CENTER; + } + float ComboBox::GetItemOffset(int index) const + { + index = std::max(firstItemVisible, index) - firstItemVisible; + return scale.y * (index + 1) + 1; + } + bool ComboBox::HasScrollbar() const + { + return maxVisibleItemCount < (int)items.size(); + } + void ComboBox::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + if (IsEnabled()) + { + + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + if (state == ACTIVE && combostate == COMBOSTATE_SELECTING) + { + hovered = -1; + Deactivate(); + } + if (state == IDLE) + { + combostate = COMBOSTATE_INACTIVE; + } + + hitBox.pos.x = translation.x; + hitBox.pos.y = translation.y; + hitBox.siz.x = scale.x + scale.y + 1; // + drop-down indicator arrow + little offset + hitBox.siz.y = scale.y; + + Hitbox2D pointerHitbox = GetPointerHitbox(); + + bool clicked = false; + // hover the button + if (pointerHitbox.intersects(hitBox)) + { + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + // activate + clicked = true; + } + + bool click_down = false; + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + click_down = true; + if (state == DEACTIVATING) + { + // Keep pressed until mouse is released + Activate(); + } + } + + + if (clicked && state == FOCUS) + { + Activate(); + } + + const float scrollbar_begin = translation.y + scale.y + 1 + scale.y * 0.5f; + const float scrollbar_end = scrollbar_begin + std::max(0.0f, (float)std::min(maxVisibleItemCount, (int)items.size()) - 1) * scale.y; + + if (state == ACTIVE) + { + if (HasScrollbar()) + { + if (combostate != COMBOSTATE_SELECTING && combostate != COMBOSTATE_INACTIVE) + { + if (combostate == COMBOSTATE_SCROLLBAR_GRABBED || pointerHitbox.intersects(Hitbox2D(XMFLOAT2(translation.x + scale.x + 1, translation.y + scale.y + 1), XMFLOAT2(scale.y, (float)std::min(maxVisibleItemCount, (int)items.size()) * scale.y)))) + { + if (click_down) + { + combostate = COMBOSTATE_SCROLLBAR_GRABBED; + scrollbar_delta = wi::math::Clamp(pointerHitbox.pos.y, scrollbar_begin, scrollbar_end) - scrollbar_begin; + const float scrollbar_value = wi::math::InverseLerp(scrollbar_begin, scrollbar_end, scrollbar_begin + scrollbar_delta); + firstItemVisible = int(float(std::max(0, (int)items.size() - maxVisibleItemCount)) * scrollbar_value + 0.5f); + firstItemVisible = std::max(0, std::min((int)items.size() - maxVisibleItemCount, firstItemVisible)); + } + else + { + combostate = COMBOSTATE_SCROLLBAR_HOVER; + } + } + else if (!click_down) + { + combostate = COMBOSTATE_HOVER; + } + } + } + + if (combostate == COMBOSTATE_INACTIVE) + { + combostate = COMBOSTATE_HOVER; + } + else if (combostate == COMBOSTATE_SELECTING) + { + Deactivate(); + combostate = COMBOSTATE_INACTIVE; + } + else if (combostate == COMBOSTATE_HOVER) + { + int scroll = (int)wi::input::GetPointer().z; + firstItemVisible -= scroll; + firstItemVisible = std::max(0, std::min((int)items.size() - maxVisibleItemCount, firstItemVisible)); + if (scroll) + { + const float scrollbar_value = wi::math::InverseLerp(0, float(std::max(0, (int)items.size() - maxVisibleItemCount)), float(firstItemVisible)); + scrollbar_delta = wi::math::Lerp(scrollbar_begin, scrollbar_end, scrollbar_value) - scrollbar_begin; + } + + hovered = -1; + for (int i = firstItemVisible; i < (firstItemVisible + std::min(maxVisibleItemCount, (int)items.size())); ++i) + { + Hitbox2D itembox; + itembox.pos.x = translation.x; + itembox.pos.y = translation.y + GetItemOffset(i); + itembox.siz.x = scale.x; + itembox.siz.y = scale.y; + if (pointerHitbox.intersects(itembox)) + { + hovered = i; + break; + } + } + + if (clicked) + { + combostate = COMBOSTATE_SELECTING; + if (hovered >= 0) + { + SetSelected(hovered); + } + } + } + } + } + + font.params.posY = translation.y + sprites[state].params.siz.y * 0.5f; + } + void ComboBox::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + GraphicsDevice* device = wi::graphics::GetDevice(); + + wi::Color color = GetColor(); + if (combostate != COMBOSTATE_INACTIVE) + { + color = wi::Color::fromFloat4(sprites[FOCUS].params.color); + } + + font.Draw(cmd); + + struct Vertex + { + XMFLOAT4 pos; + XMFLOAT4 col; + }; + static GPUBuffer vb_triangle; + if (!vb_triangle.IsValid()) + { + Vertex vertices[3]; + vertices[0].col = XMFLOAT4(1, 1, 1, 1); + vertices[1].col = XMFLOAT4(1, 1, 1, 1); + vertices[2].col = XMFLOAT4(1, 1, 1, 1); + wi::math::ConstructTriangleEquilateral(1, vertices[0].pos, vertices[1].pos, vertices[2].pos); + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = sizeof(vertices); + device->CreateBuffer(&desc, &vertices, &vb_triangle); + } + const XMMATRIX Projection = canvas.GetProjection(); + + // control-arrow-background + wi::image::Params fx = sprites[state].params; + fx.pos = XMFLOAT3(translation.x + scale.x + 1, translation.y, 0); + fx.siz = XMFLOAT2(scale.y, scale.y); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); + + // control-arrow-triangle + { + device->BindPipelineState(&PSO_colored, cmd); + + MiscCB cb; + cb.g_xColor = sprites[ACTIVE].params.color; + XMStoreFloat4x4(&cb.g_xTransform, XMMatrixScaling(scale.y * 0.25f, scale.y * 0.25f, 1) * + XMMatrixRotationZ(XM_PIDIV2) * + XMMatrixTranslation(translation.x + scale.x + 1 + scale.y * 0.5f, translation.y + scale.y * 0.5f, 0) * + Projection + ); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_triangle, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + + device->Draw(3, 0, cmd); + } + + ApplyScissor(canvas, scissorRect, cmd); + + // control-base + sprites[state].Draw(cmd); + + if (selected >= 0) + { + wi::font::Draw(items[selected].name, wi::font::Params(translation.x + scale.x * 0.5f, translation.y + scale.y * 0.5f, wi::font::WIFONTSIZE_DEFAULT, wi::font::WIFALIGN_CENTER, wi::font::WIFALIGN_CENTER, + font.params.color, font.params.shadowColor), cmd); + } + + // drop-down + if (state == ACTIVE) + { + if (HasScrollbar()) + { + Rect rect; + rect.left = int(translation.x + scale.x + 1); + rect.right = int(translation.x + scale.x + 1 + scale.y); + rect.top = int(translation.y + scale.y + 1); + rect.bottom = int(translation.y + scale.y + 1 + scale.y * maxVisibleItemCount); + ApplyScissor(canvas, rect, cmd, false); + + // control-scrollbar-base + { + fx = sprites[state].params; + fx.pos = XMFLOAT3(translation.x + scale.x + 1, translation.y + scale.y + 1, 0); + fx.siz = XMFLOAT2(scale.y, scale.y * maxVisibleItemCount); + fx.color = wi::math::Lerp(wi::Color::Transparent(), sprites[IDLE].params.color, 0.5f); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); + } + + // control-scrollbar-grab + { + wi::Color col = wi::Color::fromFloat4(sprites[IDLE].params.color); + if (combostate == COMBOSTATE_SCROLLBAR_HOVER) + { + col = wi::Color::fromFloat4(sprites[FOCUS].params.color); + } + else if (combostate == COMBOSTATE_SCROLLBAR_GRABBED) + { + col = wi::Color::fromFloat4(sprites[ACTIVE].params.color); + } + wi::image::Draw(wi::texturehelper::getWhite() + , wi::image::Params(translation.x + scale.x + 1, translation.y + scale.y + 1 + scrollbar_delta, scale.y, scale.y, col), cmd); + } + } + + Rect rect; + rect.left = int(translation.x); + rect.right = rect.left + int(scale.x); + rect.top = int(translation.y + scale.y + 1); + rect.bottom = rect.top + int(scale.y * maxVisibleItemCount); + ApplyScissor(canvas, rect, cmd, false); + + // control-list + for (int i = firstItemVisible; i < (firstItemVisible + std::min(maxVisibleItemCount, (int)items.size())); ++i) + { + fx = sprites[state].params; + fx.pos = XMFLOAT3(translation.x, translation.y + GetItemOffset(i), 0); + fx.siz = XMFLOAT2(scale.x, scale.y); + fx.color = wi::math::Lerp(wi::Color::Transparent(), sprites[IDLE].params.color, 0.5f); + if (hovered == i) + { + if (combostate == COMBOSTATE_HOVER) + { + fx.color = sprites[FOCUS].params.color; + } + else if (combostate == COMBOSTATE_SELECTING) + { + fx.color = sprites[ACTIVE].params.color; + } + } + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); + wi::font::Draw(items[i].name, wi::font::Params(translation.x + scale.x * 0.5f, translation.y + scale.y * 0.5f + GetItemOffset(i), wi::font::WIFONTSIZE_DEFAULT, wi::font::WIFALIGN_CENTER, wi::font::WIFALIGN_CENTER, + font.params.color, font.params.shadowColor), cmd); + } + } + } + void ComboBox::OnSelect(std::function func) + { + onSelect = move(func); + } + void ComboBox::AddItem(const std::string& name, uint64_t userdata) + { + items.emplace_back(); + items.back().name = name; + items.back().userdata = userdata; + + if (selected < 0) + { + selected = 0; + } + } + void ComboBox::RemoveItem(int index) + { + wi::vector newItems(0); + newItems.reserve(items.size()); + for (size_t i = 0; i < items.size(); ++i) + { + if (i != index) + { + newItems.push_back(items[i]); + } + } + items = newItems; + + if (items.empty()) + { + selected = -1; + } + else if (selected > index) + { + selected--; + } + } + void ComboBox::ClearItems() + { + items.clear(); + + selected = -1; + } + void ComboBox::SetMaxVisibleItemCount(int value) + { + maxVisibleItemCount = value; + } + void ComboBox::SetSelected(int index) + { + selected = index; + + if (onSelect != nullptr) + { + EventArgs args; + args.iValue = selected; + args.sValue = GetItemText(selected); + args.userdata = GetItemUserData(selected); + onSelect(args); + } + } + void ComboBox::SetSelectedByUserdata(uint64_t userdata) + { + for (int i = 0; i < GetItemCount(); ++i) + { + if (userdata == GetItemUserData(i)) + { + SetSelected(i); + return; + } + } + } + std::string ComboBox::GetItemText(int index) const + { + if (index >= 0) + { + return items[index].name; + } + return ""; + } + uint64_t ComboBox::GetItemUserData(int index) const + { + if (index >= 0) + { + return items[index].userdata; + } + return 0; + } + int ComboBox::GetSelected() const + { + return selected; + } + + + + + + + static const float windowcontrolSize = 20.0f; + void Window::Create(const std::string& name, bool window_controls) + { + SetColor(wi::Color::Ghost()); + + SetName(name); + SetText(name); + SetSize(XMFLOAT2(640, 480)); + + for (int i = IDLE + 1; i < WIDGETSTATE_COUNT; ++i) + { + sprites[i].params.color = sprites[IDLE].params.color; + } + + // Add controls + if (window_controls) + { + // Add a resizer control to the upperleft corner + resizeDragger_UpperLeft.Create(name + "_resize_dragger_upper_left"); + resizeDragger_UpperLeft.SetText(""); + resizeDragger_UpperLeft.OnDrag([this](EventArgs args) { + auto saved_parent = this->parent; + this->Detach(); + XMFLOAT2 scaleDiff; + scaleDiff.x = (scale.x - args.deltaPos.x) / scale.x; + scaleDiff.y = (scale.y - args.deltaPos.y) / scale.y; + this->Translate(XMFLOAT3(args.deltaPos.x, args.deltaPos.y, 0)); + this->Scale(XMFLOAT3(scaleDiff.x, scaleDiff.y, 1)); + this->scale_local = wi::math::Max(this->scale_local, XMFLOAT3(windowcontrolSize * 3, windowcontrolSize * 2, 1)); // don't allow resize to negative or too small + this->AttachTo(saved_parent); + }); + AddWidget(&resizeDragger_UpperLeft); + + // Add a resizer control to the bottom right corner + resizeDragger_BottomRight.Create(name + "_resize_dragger_bottom_right"); + resizeDragger_BottomRight.SetText(""); + resizeDragger_BottomRight.OnDrag([this](EventArgs args) { + auto saved_parent = this->parent; + this->Detach(); + XMFLOAT2 scaleDiff; + scaleDiff.x = (scale.x + args.deltaPos.x) / scale.x; + scaleDiff.y = (scale.y + args.deltaPos.y) / scale.y; + this->Scale(XMFLOAT3(scaleDiff.x, scaleDiff.y, 1)); + this->scale_local = wi::math::Max(this->scale_local, XMFLOAT3(windowcontrolSize * 3, windowcontrolSize * 2, 1)); // don't allow resize to negative or too small + this->AttachTo(saved_parent); + }); + AddWidget(&resizeDragger_BottomRight); + + // Add a grabber onto the title bar + moveDragger.Create(name + "_move_dragger"); + moveDragger.SetText(name); + moveDragger.font.params.h_align = wi::font::WIFALIGN_LEFT; + moveDragger.OnDrag([this](EventArgs args) { + auto saved_parent = this->parent; + this->Detach(); + this->Translate(XMFLOAT3(args.deltaPos.x, args.deltaPos.y, 0)); + this->AttachTo(saved_parent); + }); + AddWidget(&moveDragger); + + // Add close button to the top right corner + closeButton.Create(name + "_close_button"); + closeButton.SetText("x"); + closeButton.OnClick([this](EventArgs args) { + this->SetVisible(false); + }); + closeButton.SetTooltip("Close window"); + AddWidget(&closeButton); + + // Add minimize button to the top right corner + minimizeButton.Create(name + "_minimize_button"); + minimizeButton.SetText("-"); + minimizeButton.OnClick([this](EventArgs args) { + this->SetMinimized(!this->IsMinimized()); + }); + minimizeButton.SetTooltip("Minimize window"); + AddWidget(&minimizeButton); + } + else + { + // Simple title bar + label.Create(name); + label.SetText(name); + label.font.params.h_align = wi::font::WIFALIGN_LEFT; + AddWidget(&label); + } + + + SetEnabled(true); + SetVisible(true); + SetMinimized(false); + } + void Window::AddWidget(Widget* widget) + { + widget->SetEnabled(this->IsEnabled()); + widget->SetVisible(this->IsVisible()); + widget->AttachTo(this); + + widgets.push_back(widget); + } + void Window::RemoveWidget(Widget* widget) + { + for (auto& x : widgets) + { + if (x == widget) + { + x = widgets.back(); + widgets.pop_back(); + break; + } + } + } + void Window::RemoveWidgets() + { + widgets.clear(); + } + void Window::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + moveDragger.force_disable = force_disable; + resizeDragger_UpperLeft.force_disable = force_disable; + resizeDragger_BottomRight.force_disable = force_disable; + + moveDragger.Update(canvas, dt); + resizeDragger_UpperLeft.Update(canvas, dt); + resizeDragger_BottomRight.Update(canvas, dt); + + // Don't allow moving outside of screen: + if (parent == nullptr) + { + translation_local.x = wi::math::Clamp(translation_local.x, 0, canvas.GetLogicalWidth() - scale_local.x); + translation_local.y = wi::math::Clamp(translation_local.y, 0, canvas.GetLogicalHeight() - windowcontrolSize); + SetDirty(); + } + + Widget::Update(canvas, dt); + + if (moveDragger.parent != nullptr) + { + moveDragger.Detach(); + moveDragger.SetSize(XMFLOAT2(scale.x - windowcontrolSize * 3, windowcontrolSize)); + moveDragger.SetPos(XMFLOAT2(translation.x + windowcontrolSize, translation.y)); + moveDragger.AttachTo(this); + } + if (closeButton.parent != nullptr) + { + closeButton.Detach(); + closeButton.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); + closeButton.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize, translation.y)); + closeButton.AttachTo(this); + } + if (minimizeButton.parent != nullptr) + { + minimizeButton.Detach(); + minimizeButton.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); + minimizeButton.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize * 2, translation.y)); + minimizeButton.AttachTo(this); + } + if (resizeDragger_UpperLeft.parent != nullptr) + { + resizeDragger_UpperLeft.Detach(); + resizeDragger_UpperLeft.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); + resizeDragger_UpperLeft.SetPos(XMFLOAT2(translation.x, translation.y)); + resizeDragger_UpperLeft.AttachTo(this); + } + if (resizeDragger_BottomRight.parent != nullptr) + { + resizeDragger_BottomRight.Detach(); + resizeDragger_BottomRight.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); + resizeDragger_BottomRight.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize, translation.y + scale.y - windowcontrolSize)); + resizeDragger_BottomRight.AttachTo(this); + } + if (label.parent != nullptr) + { + label.Detach(); + label.SetSize(XMFLOAT2(scale.x, windowcontrolSize)); + label.SetPos(XMFLOAT2(translation.x, translation.y)); + label.AttachTo(this); + } + + Hitbox2D pointerHitbox = GetPointerHitbox(); + + uint32_t priority = 0; + + bool focus = false; + for (auto& widget : widgets) + { + widget->force_disable = force_disable || focus; + widget->Update(canvas, dt); + widget->force_disable = false; + + if (widget->priority_change) + { + widget->priority_change = false; + widget->priority = priority++; + } + else + { + widget->priority = ~0u; + } + + if (widget->IsVisible() && widget->hitBox.intersects(pointerHitbox)) + { + focus = true; + } + if (widget->GetState() > IDLE) + { + focus = true; + } + } + + if (priority > 0) //Sort only if there are priority changes + //Use std::stable_sort instead of std::sort to preserve UI element order with equal priorities + std::stable_sort(widgets.begin(), widgets.end(), [](const Widget* a, const Widget* b) { + return a->priority < b->priority; + }); + + if (IsMinimized()) + { + hitBox.siz.y = windowcontrolSize; + } + + if (IsEnabled() && !IsMinimized()) + { + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + if (state == ACTIVE) + { + Deactivate(); + } + + + bool clicked = false; + if (pointerHitbox.intersects(hitBox)) + { + if (state == IDLE) + { + state = FOCUS; + } + } + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == FOCUS) + { + // activate + clicked = true; + } + } + + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + if (state == DEACTIVATING) + { + // Keep pressed until mouse is released + Activate(); + } + } + + if (clicked) + { + Activate(); + } + } + else + { + state = IDLE; + } + } + void Window::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + + wi::Color color = GetColor(); + + // body + wi::image::Params fx(translation.x - 2, translation.y - 2, scale.x + 4, scale.y + 4, wi::Color(0, 0, 0, 100)); + if (IsMinimized()) + { + fx.siz.y = windowcontrolSize + 4; + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); // shadow + } + else + { + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); // shadow + sprites[state].Draw(cmd); + } + + for (auto it = widgets.rbegin(); it != widgets.rend(); ++it) + { + const Widget* widget = (*it); + ApplyScissor(canvas, scissorRect, cmd); + widget->Render(canvas, cmd); + } + + } + void Window::RenderTooltip(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const + { + Widget::RenderTooltip(canvas, cmd); + for (auto& x : widgets) + { + x->RenderTooltip(canvas, cmd); + } + } + void Window::SetVisible(bool value) + { + Widget::SetVisible(value); + SetMinimized(!value); + for (auto& x : widgets) + { + x->SetVisible(value); + } + } + void Window::SetEnabled(bool value) + { + Widget::SetEnabled(value); + for (auto& x : widgets) + { + if (x == &moveDragger) + continue; + if (x == &minimizeButton) + continue; + if (x == &closeButton) + continue; + if (x == &resizeDragger_UpperLeft) + continue; + if (x == &resizeDragger_BottomRight) + continue; + x->SetEnabled(value); + } + } + void Window::SetMinimized(bool value) + { + minimized = value; + + if (resizeDragger_BottomRight.parent != nullptr) + { + resizeDragger_BottomRight.SetVisible(!value); + } + for (auto& x : widgets) + { + if (x == &moveDragger) + continue; + if (x == &minimizeButton) + continue; + if (x == &closeButton) + continue; + if (x == &resizeDragger_UpperLeft) + continue; + x->SetVisible(!value); + } + } + bool Window::IsMinimized() const + { + return minimized; + } + + + + + struct rgb { + float r; // a fraction between 0 and 1 + float g; // a fraction between 0 and 1 + float b; // a fraction between 0 and 1 + }; + struct hsv { + float h; // angle in degrees + float s; // a fraction between 0 and 1 + float v; // a fraction between 0 and 1 + }; + hsv rgb2hsv(rgb in) + { + hsv out; + float min, max, delta; + + min = in.r < in.g ? in.r : in.g; + min = min < in.b ? min : in.b; + + max = in.r > in.g ? in.r : in.g; + max = max > in.b ? max : in.b; + + out.v = max; // v + delta = max - min; + if (delta < 0.00001f) + { + out.s = 0; + out.h = 0; // undefined, maybe nan? + return out; + } + if (max > 0.0f) { // NOTE: if Max is == 0, this divide would cause a crash + out.s = (delta / max); // s + } + else { + // if max is 0, then r = g = b = 0 + // s = 0, h is undefined + out.s = 0.0f; + out.h = NAN; // its now undefined + return out; + } + if (in.r >= max) // > is bogus, just keeps compilor happy + out.h = (in.g - in.b) / delta; // between yellow & magenta + else + if (in.g >= max) + out.h = 2.0f + (in.b - in.r) / delta; // between cyan & yellow + else + out.h = 4.0f + (in.r - in.g) / delta; // between magenta & cyan + + out.h *= 60.0f; // degrees + + if (out.h < 0.0f) + out.h += 360.0f; + + return out; + } + rgb hsv2rgb(hsv in) + { + float hh, p, q, t, ff; + long i; + rgb out; + + if (in.s <= 0.0f) { // < is bogus, just shuts up warnings + out.r = in.v; + out.g = in.v; + out.b = in.v; + return out; + } + hh = in.h; + if (hh >= 360.0f) hh = 0.0f; + hh /= 60.0f; + i = (long)hh; + ff = hh - i; + p = in.v * (1.0f - in.s); + q = in.v * (1.0f - (in.s * ff)); + t = in.v * (1.0f - (in.s * (1.0f - ff))); + + switch (i) { + case 0: + out.r = in.v; + out.g = t; + out.b = p; + break; + case 1: + out.r = q; + out.g = in.v; + out.b = p; + break; + case 2: + out.r = p; + out.g = in.v; + out.b = t; + break; + + case 3: + out.r = p; + out.g = q; + out.b = in.v; + break; + case 4: + out.r = t; + out.g = p; + out.b = in.v; + break; + case 5: + default: + out.r = in.v; + out.g = p; + out.b = q; + break; + } + return out; + } + + static const float cp_width = 300; + static const float cp_height = 260; + void ColorPicker::Create(const std::string& name, bool window_controls) + { + Window::Create(name, window_controls); + + SetSize(XMFLOAT2(cp_width, cp_height)); + SetColor(wi::Color(100, 100, 100, 100)); + + float x = 250; + float y = 110; + float step = 20; + + text_R.Create("R"); + text_R.SetPos(XMFLOAT2(x, y += step)); + text_R.SetSize(XMFLOAT2(40, 18)); + text_R.SetText(""); + text_R.SetTooltip("Enter value for RED channel (0-255)"); + text_R.SetDescription("R: "); + text_R.OnInputAccepted([this](EventArgs args) { + wi::Color color = GetPickColor(); + color.setR((uint8_t)args.iValue); + SetPickColor(color); + FireEvents(); + }); + AddWidget(&text_R); + + text_G.Create("G"); + text_G.SetPos(XMFLOAT2(x, y += step)); + text_G.SetSize(XMFLOAT2(40, 18)); + text_G.SetText(""); + text_G.SetTooltip("Enter value for GREEN channel (0-255)"); + text_G.SetDescription("G: "); + text_G.OnInputAccepted([this](EventArgs args) { + wi::Color color = GetPickColor(); + color.setG((uint8_t)args.iValue); + SetPickColor(color); + FireEvents(); + }); + AddWidget(&text_G); + + text_B.Create("B"); + text_B.SetPos(XMFLOAT2(x, y += step)); + text_B.SetSize(XMFLOAT2(40, 18)); + text_B.SetText(""); + text_B.SetTooltip("Enter value for BLUE channel (0-255)"); + text_B.SetDescription("B: "); + text_B.OnInputAccepted([this](EventArgs args) { + wi::Color color = GetPickColor(); + color.setB((uint8_t)args.iValue); + SetPickColor(color); + FireEvents(); + }); + AddWidget(&text_B); + + + text_H.Create("H"); + text_H.SetPos(XMFLOAT2(x, y += step)); + text_H.SetSize(XMFLOAT2(40, 18)); + text_H.SetText(""); + text_H.SetTooltip("Enter value for HUE channel (0-360)"); + text_H.SetDescription("H: "); + text_H.OnInputAccepted([this](EventArgs args) { + hue = wi::math::Clamp(args.fValue, 0, 360.0f); + FireEvents(); + }); + AddWidget(&text_H); + + text_S.Create("S"); + text_S.SetPos(XMFLOAT2(x, y += step)); + text_S.SetSize(XMFLOAT2(40, 18)); + text_S.SetText(""); + text_S.SetTooltip("Enter value for SATURATION channel (0-100)"); + text_S.SetDescription("S: "); + text_S.OnInputAccepted([this](EventArgs args) { + saturation = wi::math::Clamp(args.fValue / 100.0f, 0, 1); + FireEvents(); + }); + AddWidget(&text_S); + + text_V.Create("V"); + text_V.SetPos(XMFLOAT2(x, y += step)); + text_V.SetSize(XMFLOAT2(40, 18)); + text_V.SetText(""); + text_V.SetTooltip("Enter value for LUMINANCE channel (0-100)"); + text_V.SetDescription("V: "); + text_V.OnInputAccepted([this](EventArgs args) { + luminance = wi::math::Clamp(args.fValue / 100.0f, 0, 1); + FireEvents(); + }); + AddWidget(&text_V); + + alphaSlider.Create(0, 255, 255, 255, ""); + alphaSlider.SetPos(XMFLOAT2(20, 230)); + alphaSlider.SetSize(XMFLOAT2(150, 18)); + alphaSlider.SetText("A: "); + alphaSlider.SetTooltip("Value for ALPHA - TRANSPARENCY channel (0-255)"); + alphaSlider.OnSlide([this](EventArgs args) { + FireEvents(); + }); + AddWidget(&alphaSlider); + } + static const float colorpicker_radius_triangle = 68; + static const float colorpicker_radius = 75; + static const float colorpicker_width = 22; + void ColorPicker::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Window::Update(canvas, dt); + + if (IsEnabled()) + { + + if (state == DEACTIVATING) + { + state = IDLE; + } + + float sca = std::min(scale.x / cp_width, scale.y / cp_height); + + XMMATRIX W = + XMMatrixScaling(sca, sca, 1) * + XMMatrixTranslation(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f, 0) + ; + + XMFLOAT2 center = XMFLOAT2(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f); + XMFLOAT2 pointer = GetPointerHitbox().pos; + float distance = wi::math::Distance(center, pointer); + bool hover_hue = (distance > colorpicker_radius * sca) && (distance < (colorpicker_radius + colorpicker_width)* sca); + + float distTri = 0; + XMFLOAT4 A, B, C; + wi::math::ConstructTriangleEquilateral(colorpicker_radius_triangle, A, B, C); + XMVECTOR _A = XMLoadFloat4(&A); + XMVECTOR _B = XMLoadFloat4(&B); + XMVECTOR _C = XMLoadFloat4(&C); + XMMATRIX _triTransform = XMMatrixRotationZ(-hue / 360.0f * XM_2PI) * W; + _A = XMVector4Transform(_A, _triTransform); + _B = XMVector4Transform(_B, _triTransform); + _C = XMVector4Transform(_C, _triTransform); + XMVECTOR O = XMVectorSet(pointer.x, pointer.y, 0, 0); + XMVECTOR D = XMVectorSet(0, 0, 1, 0); + bool hover_saturation = TriangleTests::Intersects(O, D, _A, _B, _C, distTri); + + bool dragged = false; + + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + if (hover_hue) + { + colorpickerstate = CPS_HUE; + dragged = true; + } + else if (hover_saturation) + { + colorpickerstate = CPS_SATURATION; + dragged = true; + } + } + + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + if (colorpickerstate > CPS_IDLE) + { + // continue drag if already grabbed whether it is intersecting or not + dragged = true; + } + } + else + { + colorpickerstate = CPS_IDLE; + } + + dragged = dragged; + if (colorpickerstate == CPS_HUE && dragged) + { + //hue pick + const float angle = wi::math::GetAngle(XMFLOAT2(pointer.x - center.x, pointer.y - center.y), XMFLOAT2(colorpicker_radius, 0)); + hue = angle / XM_2PI * 360.0f; + Activate(); + } + else if (colorpickerstate == CPS_SATURATION && dragged) + { + // saturation pick + float u, v, w; + wi::math::GetBarycentric(O, _A, _B, _C, u, v, w, true); + // u = saturated corner (color) + // v = desaturated corner (white) + // w = no luminosity corner (black) + + hsv source; + source.h = hue; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + + XMVECTOR color_corner = XMVectorSet(result.r, result.g, result.b, 1); + XMVECTOR white_corner = XMVectorSet(1, 1, 1, 1); + XMVECTOR black_corner = XMVectorSet(0, 0, 0, 1); + XMVECTOR inner_point = u * color_corner + v * white_corner + w * black_corner; + + result.r = XMVectorGetX(inner_point); + result.g = XMVectorGetY(inner_point); + result.b = XMVectorGetZ(inner_point); + source = rgb2hsv(result); + + saturation = source.s; + luminance = source.v; + + Activate(); + } + else if (state != IDLE) + { + Deactivate(); + } + + wi::Color color = GetPickColor(); + text_R.SetValue((int)color.getR()); + text_G.SetValue((int)color.getG()); + text_B.SetValue((int)color.getB()); + text_H.SetValue(int(hue)); + text_S.SetValue(int(saturation * 100)); + text_V.SetValue(int(luminance * 100)); + + if (dragged) + { + FireEvents(); + } + } + } + void ColorPicker::Render(const wi::Canvas& canvas, CommandList cmd) const + { + Window::Render(canvas, cmd); + + if (!IsVisible() || IsMinimized()) + { + return; + } + + GraphicsDevice* device = wi::graphics::GetDevice(); + + struct Vertex + { + XMFLOAT4 pos; + XMFLOAT4 col; + }; + static wi::graphics::GPUBuffer vb_hue; + static wi::graphics::GPUBuffer vb_picker_saturation; + static wi::graphics::GPUBuffer vb_picker_hue; + static wi::graphics::GPUBuffer vb_preview; + + static wi::vector vertices_saturation; + + static bool buffersComplete = false; + if (!buffersComplete) + { + buffersComplete = true; + + // saturation + { + vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(1,0,0,1) }); // hue + vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(1,1,1,1) }); // white + vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(0,0,0,1) }); // black + wi::math::ConstructTriangleEquilateral(colorpicker_radius_triangle, vertices_saturation[0].pos, vertices_saturation[1].pos, vertices_saturation[2].pos); + + // create alpha blended edge: + vertices_saturation.push_back(vertices_saturation[0]); // outer + vertices_saturation.push_back(vertices_saturation[0]); // inner + vertices_saturation.push_back(vertices_saturation[1]); // outer + vertices_saturation.push_back(vertices_saturation[1]); // inner + vertices_saturation.push_back(vertices_saturation[2]); // outer + vertices_saturation.push_back(vertices_saturation[2]); // inner + vertices_saturation.push_back(vertices_saturation[0]); // outer + vertices_saturation.push_back(vertices_saturation[0]); // inner + wi::math::ConstructTriangleEquilateral(colorpicker_radius_triangle + 4, vertices_saturation[3].pos, vertices_saturation[5].pos, vertices_saturation[7].pos); // extrude outer + vertices_saturation[9].pos = vertices_saturation[3].pos; // last outer + } + // hue + { + const float edge = 2.0f; + wi::vector vertices; + uint32_t segment_count = 100; + // inner alpha blended edge + for (uint32_t i = 0; i <= segment_count; ++i) + { + float p = float(i) / segment_count; + float t = p * XM_2PI; + float x = cos(t); + float y = -sin(t); + hsv source; + source.h = p * 360.0f; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); + XMFLOAT4 coloralpha = XMFLOAT4(result.r, result.g, result.b, 0); + vertices.push_back({ XMFLOAT4((colorpicker_radius - edge) * x, (colorpicker_radius - edge) * y, 0, 1), coloralpha }); + vertices.push_back({ XMFLOAT4(colorpicker_radius * x, colorpicker_radius * y, 0, 1), color }); + } + // middle hue + for (uint32_t i = 0; i <= segment_count; ++i) + { + float p = float(i) / segment_count; + float t = p * XM_2PI; + float x = cos(t); + float y = -sin(t); + hsv source; + source.h = p * 360.0f; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); + vertices.push_back({ XMFLOAT4(colorpicker_radius * x, colorpicker_radius * y, 0, 1), color }); + vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width) * x, (colorpicker_radius + colorpicker_width) * y, 0, 1), color }); + } + // outer alpha blended edge + for (uint32_t i = 0; i <= segment_count; ++i) + { + float p = float(i) / segment_count; + float t = p * XM_2PI; + float x = cos(t); + float y = -sin(t); + hsv source; + source.h = p * 360.0f; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); + XMFLOAT4 coloralpha = XMFLOAT4(result.r, result.g, result.b, 0); + vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width) * x, (colorpicker_radius + colorpicker_width) * y, 0, 1), color }); + vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width + edge) * x, (colorpicker_radius + colorpicker_width + edge) * y, 0, 1), coloralpha }); + } + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = vertices.size() * sizeof(Vertex); + desc.stride = 0; + device->CreateBuffer(&desc, vertices.data(), &vb_hue); + } + // saturation picker (small circle) + { + float _radius = 3; + float _width = 3; + wi::vector vertices; + uint32_t segment_count = 100; + for (uint32_t i = 0; i <= segment_count; ++i) + { + float p = float(i) / 100; + float t = p * XM_2PI; + float x = cos(t); + float y = -sin(t); + vertices.push_back({ XMFLOAT4(_radius * x, _radius * y, 0, 1), XMFLOAT4(1,1,1,1) }); + vertices.push_back({ XMFLOAT4((_radius + _width) * x, (_radius + _width) * y, 0, 1), XMFLOAT4(1,1,1,1) }); + } + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = vertices.size() * sizeof(Vertex); + desc.stride = 0; + device->CreateBuffer(&desc, vertices.data(), &vb_picker_saturation); + } + // hue picker (rectangle) + { + float boldness = 4.0f; + float halfheight = 8.0f; + Vertex vertices[] = { + // left side: + { XMFLOAT4(colorpicker_radius - boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius - boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + + // bottom side: + { XMFLOAT4(colorpicker_radius - boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius - boldness, halfheight - boldness, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight - boldness, 0, 1),XMFLOAT4(1,1,1,1) }, + + // right side: + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + + // top side: + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight + boldness, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius - boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(colorpicker_radius - boldness, -halfheight + boldness, 0, 1),XMFLOAT4(1,1,1,1) }, + }; + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = sizeof(vertices); + desc.stride = 0; + device->CreateBuffer(&desc, vertices, &vb_picker_hue); + } + // preview + { + float _width = 20; + Vertex vertices[] = { + { XMFLOAT4(-_width, -_width, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(_width, -_width, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(-_width, _width, 0, 1),XMFLOAT4(1,1,1,1) }, + { XMFLOAT4(_width, _width, 0, 1),XMFLOAT4(1,1,1,1) }, + }; + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = sizeof(vertices); + device->CreateBuffer(&desc, vertices, &vb_preview); + } + + } + + const wi::Color final_color = GetPickColor(); + const float angle = hue / 360.0f * XM_2PI; + + const XMMATRIX Projection = canvas.GetProjection(); + + device->BindPipelineState(&PSO_colored, cmd); + + ApplyScissor(canvas, scissorRect, cmd); + + float sca = std::min(scale.x / cp_width, scale.y / cp_height); + + XMMATRIX W = + XMMatrixScaling(sca, sca, 1) * + XMMatrixTranslation(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f, 0) + ; + + MiscCB cb; + + // render saturation triangle + { + hsv source; + source.h = hue; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + vertices_saturation[0].col = XMFLOAT4(result.r, result.g, result.b, 1); + + vertices_saturation[3].col = vertices_saturation[0].col; vertices_saturation[3].col.w = 0; + vertices_saturation[4].col = vertices_saturation[0].col; + vertices_saturation[5].col = vertices_saturation[1].col; vertices_saturation[5].col.w = 0; + vertices_saturation[6].col = vertices_saturation[1].col; + vertices_saturation[7].col = vertices_saturation[2].col; vertices_saturation[7].col.w = 0; + vertices_saturation[8].col = vertices_saturation[2].col; + vertices_saturation[9].col = vertices_saturation[0].col; vertices_saturation[9].col.w = 0; + vertices_saturation[10].col = vertices_saturation[0].col; + + size_t alloc_size = sizeof(Vertex) * vertices_saturation.size(); + GraphicsDevice::GPUAllocation vb_saturation = device->AllocateGPU(alloc_size, cmd); + memcpy(vb_saturation.data, vertices_saturation.data(), alloc_size); + + XMStoreFloat4x4(&cb.g_xTransform, + XMMatrixRotationZ(-angle) * + W * + Projection + ); + cb.g_xColor = IsEnabled() ? float4(1, 1, 1, 1) : float4(0.5f, 0.5f, 0.5f, 1); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_saturation.buffer, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + const uint64_t offsets[] = { + vb_saturation.offset, + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, offsets, cmd); + device->Draw((uint32_t)vertices_saturation.size(), 0, cmd); + } + + // render hue circle + { + XMStoreFloat4x4(&cb.g_xTransform, + W * + Projection + ); + cb.g_xColor = IsEnabled() ? float4(1, 1, 1, 1) : float4(0.5f, 0.5f, 0.5f, 1); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_hue, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + device->Draw((uint32_t)(vb_hue.GetDesc().size / sizeof(Vertex)), 0, cmd); + } + + // render hue picker + if (IsEnabled()) + { + XMStoreFloat4x4(&cb.g_xTransform, + XMMatrixRotationZ(-hue / 360.0f * XM_2PI) * + W * + Projection + ); + + hsv source; + source.h = hue; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + cb.g_xColor = float4(1 - result.r, 1 - result.g, 1 - result.b, 1); + + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_picker_hue, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + device->Draw((uint32_t)(vb_picker_hue.GetDesc().size / sizeof(Vertex)), 0, cmd); + } + + // render saturation picker + if (IsEnabled()) + { + XMFLOAT4 A, B, C; + wi::math::ConstructTriangleEquilateral(colorpicker_radius_triangle, A, B, C); + XMVECTOR _A = XMLoadFloat4(&A); + XMVECTOR _B = XMLoadFloat4(&B); + XMVECTOR _C = XMLoadFloat4(&C); + XMMATRIX _triTransform = XMMatrixRotationZ(-hue / 360.0f * XM_2PI); + _A = XMVector4Transform(_A, _triTransform); + _B = XMVector4Transform(_B, _triTransform); + _C = XMVector4Transform(_C, _triTransform); + + hsv source; + source.h = hue; + source.s = 1; + source.v = 1; + rgb result = hsv2rgb(source); + + XMVECTOR color_corner = XMVectorSet(result.r, result.g, result.b, 1); + XMVECTOR white_corner = XMVectorSet(1, 1, 1, 1); + XMVECTOR black_corner = XMVectorSet(0, 0, 0, 1); + + source.h = hue; + source.s = saturation; + source.v = luminance; + result = hsv2rgb(source); + XMVECTOR inner_point = XMVectorSet(result.r, result.g, result.b, 1); + + float u, v, w; + wi::math::GetBarycentric(inner_point, color_corner, white_corner, black_corner, u, v, w, true); + + XMVECTOR picker_center = u * _A + v * _B + w * _C; + + XMStoreFloat4x4(&cb.g_xTransform, + XMMatrixTranslationFromVector(picker_center) * + W * + Projection + ); + cb.g_xColor = float4(1 - final_color.toFloat3().x, 1 - final_color.toFloat3().y, 1 - final_color.toFloat3().z, 1); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_picker_saturation, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + device->Draw((uint32_t)(vb_picker_saturation.GetDesc().size / sizeof(Vertex)), 0, cmd); + } + + // render preview + { + XMStoreFloat4x4(&cb.g_xTransform, + XMMatrixScaling(sca, sca, 1) * + XMMatrixTranslation(translation.x + scale.x - 40 * sca, translation.y + 40, 0) * + Projection + ); + cb.g_xColor = final_color.toFloat4(); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_preview, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + device->Draw((uint32_t)(vb_preview.GetDesc().size / sizeof(Vertex)), 0, cmd); + } + } + wi::Color ColorPicker::GetPickColor() const + { + hsv source; + source.h = hue; + source.s = saturation; + source.v = luminance; + rgb result = hsv2rgb(source); + return wi::Color::fromFloat4(XMFLOAT4(result.r, result.g, result.b, alphaSlider.GetValue() / 255.0f)); + } + void ColorPicker::SetPickColor(wi::Color value) + { + if (colorpickerstate != CPS_IDLE) + { + // Only allow setting the pick color when picking is not active, the RGB and HSV precision combat each other + return; + } + + rgb source; + source.r = value.toFloat3().x; + source.g = value.toFloat3().y; + source.b = value.toFloat3().z; + hsv result = rgb2hsv(source); + if (value.getR() != value.getG() || value.getG() != value.getB() || value.getR() != value.getB()) + { + hue = result.h; // only change the hue when not pure greyscale because those don't retain the saturation value + } + saturation = result.s; + luminance = result.v; + alphaSlider.SetValue((float)value.getA()); + } + void ColorPicker::FireEvents() + { + if (onColorChanged == nullptr) + return; + EventArgs args; + args.color = GetPickColor(); + onColorChanged(args); + } + void ColorPicker::OnColorChanged(std::function func) + { + onColorChanged = move(func); + } + + + + + + + inline float item_height() { return 20.0f; } + inline float tree_scrollbar_width() { return 12.0f; } + void TreeList::Create(const std::string& name) + { + SetName(name); + SetText(name); + OnSelect([](EventArgs args) {}); + SetSize(XMFLOAT2(100, 20)); + + for (int i = FOCUS + 1; i < WIDGETSTATE_COUNT; ++i) + { + sprites[i].params.color = sprites[FOCUS].params.color; + } + font.params.v_align = wi::font::WIFALIGN_CENTER; + } + float TreeList::GetItemOffset(int index) const + { + return 2 + list_offset + index * item_height(); + } + Hitbox2D TreeList::GetHitbox_ListArea() const + { + return Hitbox2D(XMFLOAT2(translation.x, translation.y + item_height() + 1), XMFLOAT2(scale.x - tree_scrollbar_width() - 1, scale.y - item_height() - 1)); + } + Hitbox2D TreeList::GetHitbox_Item(int visible_count, int level) const + { + XMFLOAT2 pos = XMFLOAT2(translation.x + 2 + level * item_height(), translation.y + GetItemOffset(visible_count) + item_height() * 0.5f); + Hitbox2D hitbox; + hitbox.pos = XMFLOAT2(pos.x + item_height() * 0.5f + 2, pos.y - item_height() * 0.5f); + hitbox.siz = XMFLOAT2(scale.x - 2 - item_height() * 0.5f - 2 - level * item_height() - tree_scrollbar_width() - 2, item_height()); + return hitbox; + } + Hitbox2D TreeList::GetHitbox_ItemOpener(int visible_count, int level) const + { + XMFLOAT2 pos = XMFLOAT2(translation.x + 2 + level * item_height(), translation.y + GetItemOffset(visible_count) + item_height() * 0.5f); + return Hitbox2D(XMFLOAT2(pos.x, pos.y - item_height() * 0.25f), XMFLOAT2(item_height() * 0.5f, item_height() * 0.5f)); + } + bool TreeList::HasScrollbar() const + { + return scale.y < (int)items.size()* item_height(); + } + void TreeList::Update(const wi::Canvas& canvas, float dt) + { + if (!IsVisible()) + { + return; + } + + Widget::Update(canvas, dt); + + if (IsEnabled()) + { + if (state == FOCUS) + { + state = IDLE; + } + if (state == DEACTIVATING) + { + state = IDLE; + } + if (state == ACTIVE) + { + Deactivate(); + } + + Hitbox2D hitbox = Hitbox2D(XMFLOAT2(translation.x, translation.y), XMFLOAT2(scale.x, scale.y)); + Hitbox2D pointerHitbox = GetPointerHitbox(); + + if (state == IDLE && hitbox.intersects(pointerHitbox)) + { + state = FOCUS; + } + + bool clicked = false; + if (wi::input::Press(wi::input::MOUSE_BUTTON_LEFT)) + { + clicked = true; + } + + bool click_down = false; + if (wi::input::Down(wi::input::MOUSE_BUTTON_LEFT)) + { + click_down = true; + if (state == FOCUS || state == DEACTIVATING) + { + // Keep pressed until mouse is released + Activate(); + } + } + + // compute control-list height + list_height = 0; + { + int visible_count = 0; + int parent_level = 0; + bool parent_open = true; + for (const Item& item : items) + { + if (!parent_open && item.level > parent_level) + { + continue; + } + visible_count++; + parent_open = item.open; + parent_level = item.level; + list_height += item_height(); + } + } + + const float scrollbar_begin = translation.y + item_height(); + const float scrollbar_end = scrollbar_begin + scale.y - item_height(); + const float scrollbar_size = scrollbar_end - scrollbar_begin; + const float scrollbar_granularity = std::min(1.0f, scrollbar_size / list_height); + scrollbar_height = std::max(tree_scrollbar_width(), scrollbar_size * scrollbar_granularity); + + if (!click_down) + { + scrollbar_state = SCROLLBAR_INACTIVE; + } + + Hitbox2D scroll_box; + scroll_box.pos = XMFLOAT2(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1); + scroll_box.siz = XMFLOAT2(tree_scrollbar_width(), scale.y - item_height() - 1); + if (scroll_box.intersects(pointerHitbox)) + { + if (clicked) + { + scrollbar_state = SCROLLBAR_GRABBED; + } + else if (!click_down) + { + scrollbar_state = SCROLLBAR_HOVER; + state = FOCUS; + } + } + + if (scrollbar_state == SCROLLBAR_GRABBED) + { + Activate(); + scrollbar_delta = pointerHitbox.pos.y - scrollbar_height * 0.5f - scrollbar_begin; + } + + if (state == FOCUS) + { + scrollbar_delta -= wi::input::GetPointer().z * 10; + } + scrollbar_delta = wi::math::Clamp(scrollbar_delta, 0, scrollbar_size - scrollbar_height); + scrollbar_value = wi::math::InverseLerp(scrollbar_begin, scrollbar_end, scrollbar_begin + scrollbar_delta); + + list_offset = -scrollbar_value * list_height; + + Hitbox2D itemlist_box = GetHitbox_ListArea(); + + // control-list + item_highlight = -1; + opener_highlight = -1; + if (scrollbar_state == SCROLLBAR_INACTIVE) + { + int i = -1; + int visible_count = 0; + int parent_level = 0; + bool parent_open = true; + for (Item& item : items) + { + i++; + if (!parent_open && item.level > parent_level) + { + continue; + } + visible_count++; + parent_open = item.open; + parent_level = item.level; + + Hitbox2D open_box = GetHitbox_ItemOpener(visible_count, item.level); + if (!open_box.intersects(itemlist_box)) + { + continue; + } + + if (open_box.intersects(pointerHitbox)) + { + // Opened flag box: + opener_highlight = i; + if (clicked) + { + item.open = !item.open; + Activate(); + } + } + else + { + // Item name box: + Hitbox2D name_box = GetHitbox_Item(visible_count, item.level); + if (name_box.intersects(pointerHitbox)) + { + item_highlight = i; + if (clicked) + { + if (!wi::input::Down(wi::input::KEYBOARD_BUTTON_LCONTROL) && !wi::input::Down(wi::input::KEYBOARD_BUTTON_RCONTROL) + && !wi::input::Down(wi::input::KEYBOARD_BUTTON_LSHIFT) && !wi::input::Down(wi::input::KEYBOARD_BUTTON_RSHIFT)) + { + ClearSelection(); + } + Select(i); + Activate(); + } + } + } + } + } + } + + sprites[state].params.siz.y = item_height(); + font.params.posX = translation.x + 2; + font.params.posY = translation.y + sprites[state].params.siz.y * 0.5f; + } + void TreeList::Render(const wi::Canvas& canvas, CommandList cmd) const + { + if (!IsVisible()) + { + return; + } + GraphicsDevice* device = wi::graphics::GetDevice(); + + // control-base + sprites[state].Draw(cmd); + + ApplyScissor(canvas, scissorRect, cmd); + + font.Draw(cmd); + + // scrollbar background + wi::image::Params fx = sprites[state].params; + fx.pos = XMFLOAT3(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1, 0); + fx.siz = XMFLOAT2(tree_scrollbar_width(), scale.y - item_height() - 1); + fx.color = sprites[IDLE].params.color; + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); + + // scrollbar + wi::Color scrollbar_color = wi::Color::fromFloat4(sprites[IDLE].params.color); + if (scrollbar_state == SCROLLBAR_HOVER) + { + scrollbar_color = wi::Color::fromFloat4(sprites[FOCUS].params.color); + } + else if (scrollbar_state == SCROLLBAR_GRABBED) + { + scrollbar_color = wi::Color::White(); + } + wi::image::Draw(wi::texturehelper::getWhite() + , wi::image::Params(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1 + scrollbar_delta, tree_scrollbar_width(), scrollbar_height, scrollbar_color), cmd); + + // list background + Hitbox2D itemlist_box = GetHitbox_ListArea(); + fx.pos = XMFLOAT3(itemlist_box.pos.x, itemlist_box.pos.y, 0); + fx.siz = XMFLOAT2(itemlist_box.siz.x, itemlist_box.siz.y); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); + + Rect rect_without_scrollbar; + rect_without_scrollbar.left = (int)itemlist_box.pos.x; + rect_without_scrollbar.right = (int)(itemlist_box.pos.x + itemlist_box.siz.x); + rect_without_scrollbar.top = (int)itemlist_box.pos.y; + rect_without_scrollbar.bottom = (int)(itemlist_box.pos.y + itemlist_box.siz.y); + ApplyScissor(canvas, rect_without_scrollbar, cmd); + + struct Vertex + { + XMFLOAT4 pos; + XMFLOAT4 col; + }; + static GPUBuffer vb_triangle; + if (!vb_triangle.IsValid()) + { + Vertex vertices[3]; + vertices[0].col = XMFLOAT4(1, 1, 1, 1); + vertices[1].col = XMFLOAT4(1, 1, 1, 1); + vertices[2].col = XMFLOAT4(1, 1, 1, 1); + wi::math::ConstructTriangleEquilateral(1, vertices[0].pos, vertices[1].pos, vertices[2].pos); + + GPUBufferDesc desc; + desc.bind_flags = BindFlag::VERTEX_BUFFER; + desc.size = sizeof(vertices); + device->CreateBuffer(&desc, vertices, &vb_triangle); + } + const XMMATRIX Projection = canvas.GetProjection(); + + // control-list + int i = -1; + int visible_count = 0; + int parent_level = 0; + bool parent_open = true; + for (const Item& item : items) + { + i++; + if (!parent_open && item.level > parent_level) + { + continue; + } + visible_count++; + parent_open = item.open; + parent_level = item.level; + + Hitbox2D open_box = GetHitbox_ItemOpener(visible_count, item.level); + if (!open_box.intersects(itemlist_box)) + { + continue; + } + + Hitbox2D name_box = GetHitbox_Item(visible_count, item.level); + + // selected box: + if (item.selected || item_highlight == i) + { + wi::image::Draw(wi::texturehelper::getWhite() + , wi::image::Params(name_box.pos.x, name_box.pos.y, name_box.siz.x, name_box.siz.y, + sprites[item.selected ? FOCUS : IDLE].params.color), cmd); + } + + // opened flag triangle: + { + device->BindPipelineState(&PSO_colored, cmd); + + MiscCB cb; + cb.g_xColor = opener_highlight == i ? wi::Color::White().toFloat4() : sprites[FOCUS].params.color; + XMStoreFloat4x4(&cb.g_xTransform, XMMatrixScaling(item_height() * 0.3f, item_height() * 0.3f, 1) * + XMMatrixRotationZ(item.open ? XM_PIDIV2 : 0) * + XMMatrixTranslation(open_box.pos.x + open_box.siz.x * 0.5f, open_box.pos.y + open_box.siz.y * 0.25f, 0) * + Projection + ); + device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); + const GPUBuffer* vbs[] = { + &vb_triangle, + }; + const uint32_t strides[] = { + sizeof(Vertex), + }; + device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); + + device->Draw(3, 0, cmd); + } + + // Item name text: + wi::font::Draw(item.name, wi::font::Params(name_box.pos.x + 1, name_box.pos.y + name_box.siz.y * 0.5f, wi::font::WIFONTSIZE_DEFAULT, wi::font::WIFALIGN_LEFT, wi::font::WIFALIGN_CENTER, + font.params.color, font.params.shadowColor), cmd); + } + } + void TreeList::OnSelect(std::function func) + { + onSelect = move(func); + } + void TreeList::AddItem(const Item& item) + { + items.push_back(item); + } + void TreeList::ClearItems() + { + items.clear(); + } + void TreeList::ClearSelection() + { + for (Item& item : items) + { + item.selected = false; + } + + EventArgs args; + args.iValue = -1; + onSelect(args); + } + void TreeList::Select(int index) + { + items[index].selected = true; + + EventArgs args; + args.iValue = index; + args.sValue = items[index].name; + args.userdata = items[index].userdata; + onSelect(args); + } + const TreeList::Item& TreeList::GetItem(int index) const + { + return items[index]; + } + + } diff --git a/WickedEngine/wiGUI.h b/WickedEngine/wiGUI.h index 4baec249c..d7535c970 100644 --- a/WickedEngine/wiGUI.h +++ b/WickedEngine/wiGUI.h @@ -1,29 +1,419 @@ #pragma once #include "CommonInclude.h" #include "wiGraphicsDevice.h" +#include "wiPrimitive.h" #include "wiCanvas.h" -#include "wiWidget.h" #include "wiVector.h" +#include "wiColor.h" +#include "wiScene.h" +#include "wiSprite.h" +#include "wiSpriteFont.h" -class wiGUI +#include +#include + +namespace wi::gui { -private: - wi::vector widgets; - bool focus = false; - bool visible = true; -public: + void Initialize(); - void Update(const wiCanvas& canvas, float dt); - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const; + class Widget; - void AddWidget(wiWidget* widget); - void RemoveWidget(wiWidget* widget); - wiWidget* GetWidget(const std::string& name); + class GUI + { + private: + wi::vector widgets; + bool focus = false; + bool visible = true; + public: - // returns true if any gui element has the focus - bool HasFocus(); + void Update(const wi::Canvas& canvas, float dt); + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const; - void SetVisible(bool value) { visible = value; } - bool IsVisible() { return visible; } -}; + void AddWidget(Widget* widget); + void RemoveWidget(Widget* widget); + Widget* GetWidget(const std::string& name); + // returns true if any gui element has the focus + bool HasFocus(); + + void SetVisible(bool value) { visible = value; } + bool IsVisible() { return visible; } + }; + + struct EventArgs + { + XMFLOAT2 clickPos; + XMFLOAT2 startPos; + XMFLOAT2 deltaPos; + XMFLOAT2 endPos; + float fValue; + bool bValue; + int iValue; + wi::Color color; + std::string sValue; + uint64_t userdata; + }; + + enum WIDGETSTATE + { + IDLE, // widget is doing nothing + FOCUS, // widget got pointer dragged on or selected + ACTIVE, // widget is interacted with right now + DEACTIVATING, // widget has last been active but no more interactions are occuring + WIDGETSTATE_COUNT, + }; + + class Widget : public wi::scene::TransformComponent + { + private: + int tooltipTimer = 0; + protected: + std::string name; + std::string tooltip; + std::string scriptTip; + bool enabled = true; + bool visible = true; + WIDGETSTATE state = IDLE; + + public: + Widget(); + virtual ~Widget() = default; + + const std::string& GetName() const; + void SetName(const std::string& value); + const std::string GetText() const; + void SetText(const std::string& value); + void SetText(std::string&& value); + void SetTooltip(const std::string& value); + void SetTooltip(std::string&& value); + void SetScriptTip(const std::string& value); + void SetScriptTip(std::string&& value); + void SetPos(const XMFLOAT2& value); + void SetSize(const XMFLOAT2& value); + WIDGETSTATE GetState() const; + virtual void SetEnabled(bool val); + bool IsEnabled() const; + virtual void SetVisible(bool val); + bool IsVisible() const; + // last param default: set color for all states + void SetColor(wi::Color color, WIDGETSTATE state = WIDGETSTATE_COUNT); + wi::Color GetColor() const; + // last param default: set color for all states + void SetImage(wi::Resource textureResource, WIDGETSTATE state = WIDGETSTATE_COUNT); + + virtual void Update(const wi::Canvas& canvas, float dt); + virtual void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const = 0; + virtual void RenderTooltip(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const; + + wi::Sprite sprites[WIDGETSTATE_COUNT]; + wi::SpriteFont font; + + XMFLOAT3 translation = XMFLOAT3(0, 0, 0); + XMFLOAT3 scale = XMFLOAT3(1, 1, 1); + + wi::primitive::Hitbox2D hitBox; + wi::graphics::Rect scissorRect; + + Widget* parent = nullptr; + void AttachTo(Widget* parent); + void Detach(); + + void Activate(); + void Deactivate(); + + void ApplyScissor(const wi::Canvas& canvas, const wi::graphics::Rect rect, wi::graphics::CommandList cmd, bool constrain_to_parent = true) const; + wi::primitive::Hitbox2D GetPointerHitbox() const; + + bool priority_change = true; + uint32_t priority = 0; + bool force_disable = false; + }; + + // Clickable, draggable box + class Button : public Widget + { + protected: + std::function onClick; + std::function onDragStart; + std::function onDrag; + std::function onDragEnd; + XMFLOAT2 dragStart = XMFLOAT2(0, 0); + XMFLOAT2 prevPos = XMFLOAT2(0, 0); + public: + void Create(const std::string& name); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnClick(std::function func); + void OnDragStart(std::function func); + void OnDrag(std::function func); + void OnDragEnd(std::function func); + }; + + // Static box that holds text + class Label : public Widget + { + protected: + public: + void Create(const std::string& name); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + }; + + // Text input box + class TextInputField : public Widget + { + protected: + std::function onInputAccepted; + static wi::SpriteFont font_input; + + public: + void Create(const std::string& name); + + wi::SpriteFont font_description; + + void SetValue(const std::string& newValue); + void SetValue(int newValue); + void SetValue(float newValue); + const std::string GetValue(); + void SetDescription(const std::string& desc) { font_description.SetText(desc); } + const std::string GetDescription() const { return font_description.GetTextA(); } + + // There can only be ONE active text input field, so these methods modify the active one + static void AddInput(const char inputChar); + static void DeleteFromInput(); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnInputAccepted(std::function func); + }; + + // Define an interval and slide the control along it + class Slider : public Widget + { + protected: + std::function onSlide; + float start = 0, end = 1; + float step = 1000; + float value = 0; + + TextInputField valueInputField; + public: + // start : slider minimum value + // end : slider maximum value + // defaultValue : slider default Value + // step : slider step size + void Create(float start, float end, float defaultValue, float step, const std::string& name); + + wi::Sprite sprites_knob[WIDGETSTATE_COUNT]; + + void SetValue(float value); + float GetValue() const; + void SetRange(float start, float end); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + void RenderTooltip(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnSlide(std::function func); + }; + + // Two-state clickable box + class CheckBox :public Widget + { + protected: + std::function onClick; + bool checked = false; + public: + void Create(const std::string& name); + + wi::Sprite sprites_check[WIDGETSTATE_COUNT]; + + void SetCheck(bool value); + bool GetCheck() const; + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnClick(std::function func); + }; + + // Drop-down list + class ComboBox :public Widget + { + protected: + std::function onSelect; + int selected = -1; + int maxVisibleItemCount = 8; + int firstItemVisible = 0; + + // While the widget is active (rolled down) these are the inner states that control behaviour + enum COMBOSTATE + { + COMBOSTATE_INACTIVE, // When the list is just being dropped down, or the widget is not active + COMBOSTATE_HOVER, // The widget is in drop-down state with the last item hovered highlited + COMBOSTATE_SELECTING, // The hovered item is clicked + COMBOSTATE_SCROLLBAR_HOVER, // scrollbar is to be selected + COMBOSTATE_SCROLLBAR_GRABBED, // scrollbar is moved + COMBOSTATE_COUNT, + } combostate = COMBOSTATE_INACTIVE; + int hovered = -1; + + float scrollbar_delta = 0; + + struct Item + { + std::string name; + uint64_t userdata = 0; + }; + wi::vector items; + + float GetItemOffset(int index) const; + public: + void Create(const std::string& name); + + void AddItem(const std::string& name, uint64_t userdata = 0); + void RemoveItem(int index); + void ClearItems(); + void SetMaxVisibleItemCount(int value); + bool HasScrollbar() const; + + void SetSelected(int index); + void SetSelectedByUserdata(uint64_t userdata); + int GetSelected() const; + std::string GetItemText(int index) const; + uint64_t GetItemUserData(int index) const; + size_t GetItemCount() const { return items.size(); } + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnSelect(std::function func); + }; + + // Widget container + class Window :public Widget + { + protected: + Button closeButton; + Button minimizeButton; + Button resizeDragger_UpperLeft; + Button resizeDragger_BottomRight; + Button moveDragger; + Label label; + wi::vector widgets; + bool minimized = false; + public: + void Create(const std::string& name, bool window_controls = true); + + void AddWidget(Widget* widget); + void RemoveWidget(Widget* widget); + void RemoveWidgets(); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + void RenderTooltip(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void SetVisible(bool value) override; + void SetEnabled(bool value) override; + void SetMinimized(bool value); + bool IsMinimized() const; + }; + + // HSV-Color Picker + class ColorPicker : public Window + { + protected: + std::function onColorChanged; + enum COLORPICKERSTATE + { + CPS_IDLE, + CPS_HUE, + CPS_SATURATION, + } colorpickerstate = CPS_IDLE; + float hue = 0.0f; // [0, 360] degrees + float saturation = 0.0f; // [0, 1] + float luminance = 1.0f; // [0, 1] + + TextInputField text_R; + TextInputField text_G; + TextInputField text_B; + TextInputField text_H; + TextInputField text_S; + TextInputField text_V; + Slider alphaSlider; + + void FireEvents(); + public: + void Create(const std::string& name, bool window_controls = true); + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + wi::Color GetPickColor() const; + void SetPickColor(wi::Color value); + + void OnColorChanged(std::function func); + }; + + // List of items in a tree (parent-child relationships) + class TreeList : public Widget + { + public: + struct Item + { + std::string name; + int level = 0; + uint64_t userdata = 0; + bool open = false; + bool selected = false; + }; + protected: + std::function onSelect; + float list_height = 0; + float list_offset = 0; + int item_highlight = -1; + int opener_highlight = -1; + + enum SCROLLBAR_STATE + { + SCROLLBAR_INACTIVE, + SCROLLBAR_HOVER, + SCROLLBAR_GRABBED, + TREESTATE_COUNT, + } scrollbar_state = SCROLLBAR_INACTIVE; + + float scrollbar_delta = 0; + float scrollbar_height = 0; + float scrollbar_value = 0; + + wi::primitive::Hitbox2D GetHitbox_ListArea() const; + wi::primitive::Hitbox2D GetHitbox_Item(int visible_count, int level) const; + wi::primitive::Hitbox2D GetHitbox_ItemOpener(int visible_count, int level) const; + + wi::vector items; + + float GetItemOffset(int index) const; + public: + void Create(const std::string& name); + + void AddItem(const Item& item); + void ClearItems(); + bool HasScrollbar() const; + + void ClearSelection(); + void Select(int index); + + int GetItemCount() const { return (int)items.size(); } + const Item& GetItem(int index) const; + + void Update(const wi::Canvas& canvas, float dt) override; + void Render(const wi::Canvas& canvas, wi::graphics::CommandList cmd) const override; + + void OnSelect(std::function func); + }; + +} diff --git a/WickedEngine/wiGraphics.h b/WickedEngine/wiGraphics.h index 91a0176cd..b525d299c 100644 --- a/WickedEngine/wiGraphics.h +++ b/WickedEngine/wiGraphics.h @@ -7,7 +7,7 @@ #include #include -namespace wiGraphics +namespace wi::graphics { struct Shader; struct GPUResource; @@ -1183,26 +1183,26 @@ namespace wiGraphics } template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; template<> -struct enable_bitmask_operators { +struct enable_bitmask_operators { static const bool enable = true; }; diff --git a/WickedEngine/wiGraphicsDevice.h b/WickedEngine/wiGraphicsDevice.h index 2c276ae71..882882b29 100644 --- a/WickedEngine/wiGraphicsDevice.h +++ b/WickedEngine/wiGraphicsDevice.h @@ -7,7 +7,7 @@ #include #include -namespace wiGraphics +namespace wi::graphics { // CommandList can be used to record graphics commands from a CPU thread // Use GraphicsDevice::BeginCommandList() to start a command list @@ -74,7 +74,7 @@ namespace wiGraphics virtual ~GraphicsDevice() = default; // Create a SwapChain. If the SwapChain is to be recreated, the window handle can be nullptr. - virtual bool CreateSwapChain(const SwapChainDesc* pDesc, wiPlatform::window_type window, SwapChain* swapChain) const = 0; + virtual bool CreateSwapChain(const SwapChainDesc* pDesc, wi::platform::window_type window, SwapChain* swapChain) const = 0; virtual bool CreateBuffer(const GPUBufferDesc *pDesc, const void* pInitialData, GPUBuffer *pBuffer) const = 0; virtual bool CreateTexture(const TextureDesc* pDesc, const SubresourceData *pInitialData, Texture *pTexture) const = 0; virtual bool CreateShader(ShaderStage stage, const void *pShaderBytecode, size_t BytecodeLength, Shader *pShader) const = 0; @@ -216,9 +216,9 @@ namespace wiGraphics struct GPUAllocation { - void* data = nullptr; // application can write to this. Reads might be not supported or slow. The offset is already applied - GPUBuffer buffer; // application can bind it to the GPU - uint64_t offset = 0; // allocation's offset from the GPUbuffer's beginning + void* data = nullptr; // application can write to this. Reads might be not supported or slow. The offset is already applied + GPUBuffer buffer; // application can bind it to the GPU + uint64_t offset = 0; // allocation's offset from the GPUbuffer's beginning // Returns true if the allocation was successful inline bool IsValid() const { return data != nullptr && buffer.IsValid(); } @@ -281,7 +281,7 @@ namespace wiGraphics // This will be done on the CPU to an UPLOAD buffer, so this can be used inside a RenderPass // But this will be only visible on the command list it was bound to template - void BindDynamicConstantBuffer(const T& data, uint32_t slot, wiGraphics::CommandList cmd) + void BindDynamicConstantBuffer(const T& data, uint32_t slot, CommandList cmd) { GPUAllocation allocation = AllocateGPU(sizeof(T), cmd); std::memcpy(allocation.data, &data, sizeof(T)); diff --git a/WickedEngine/wiGraphicsDevice_DX12.cpp b/WickedEngine/wiGraphicsDevice_DX12.cpp index 0a5bca58b..ac0586d61 100644 --- a/WickedEngine/wiGraphicsDevice_DX12.cpp +++ b/WickedEngine/wiGraphicsDevice_DX12.cpp @@ -2,7 +2,7 @@ #ifdef WICKEDENGINE_BUILD_DX12 #include "wiHelper.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTimer.h" #include "wiUnorderedSet.h" @@ -26,10 +26,10 @@ using namespace Microsoft::WRL; -namespace wiGraphics +namespace wi::graphics { -namespace DX12_Internal +namespace dx12_internal { // Bindless allocation limits: #define BINDLESS_RESOURCE_CAPACITY 500000 @@ -1482,7 +1482,7 @@ namespace DX12_Internal return static_cast(param->internal_state.get()); } } -using namespace DX12_Internal; +using namespace dx12_internal; // Allocators: @@ -1553,7 +1553,7 @@ using namespace DX12_Internal; if (cmd.uploadbuffer.desc.size < staging_size) { GPUBufferDesc uploadBufferDesc; - uploadBufferDesc.size = wiMath::GetNextPowerOfTwo(staging_size); + uploadBufferDesc.size = wi::math::GetNextPowerOfTwo(staging_size); uploadBufferDesc.usage = Usage::UPLOAD; bool upload_success = device->CreateBuffer(&uploadBufferDesc, nullptr, &cmd.uploadbuffer); assert(upload_success); @@ -1678,8 +1678,7 @@ using namespace DX12_Internal; if (resources > 0) { // The reservation is the maximum amount of descriptors that can be allocated once - // It can be increased if needed - const uint32_t wrap_reservation = 1000; + static constexpr uint32_t wrap_reservation = DESCRIPTORBINDER_CBV_COUNT + DESCRIPTORBINDER_SRV_COUNT + DESCRIPTORBINDER_UAV_COUNT; const uint32_t wrap_effective_size = device->descriptorheap_res.heapDesc.NumDescriptors - BINDLESS_RESOURCE_CAPACITY - wrap_reservation; assert(wrap_reservation > resources); // for correct lockless wrap behaviour @@ -1876,8 +1875,7 @@ using namespace DX12_Internal; if (samplers > 0) { // The reservation is the maximum amount of descriptors that can be allocated once - // It can be increased if needed - const uint32_t wrap_reservation = 16; + static constexpr uint32_t wrap_reservation = DESCRIPTORBINDER_SAMPLER_COUNT; const uint32_t wrap_effective_size = device->descriptorheap_sam.heapDesc.NumDescriptors - BINDLESS_SAMPLER_CAPACITY - wrap_reservation; assert(wrap_reservation > samplers); // for correct lockless wrap behaviour @@ -2103,7 +2101,7 @@ using namespace DX12_Internal; // Engine functions GraphicsDevice_DX12::GraphicsDevice_DX12(bool debuglayer, bool gpuvalidation) { - wiTimer timer; + wi::Timer timer; ALLOCATION_MIN_ALIGNMENT = D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT; SHADER_IDENTIFIER_SIZE = D3D12_SHADER_IDENTIFIER_SIZE_IN_BYTES; @@ -2118,8 +2116,8 @@ using namespace DX12_Internal; ss << "Failed to load dxcompiler.dll! ERROR: 0x" << std::hex << GetLastError() << std::endl; ss << "Ensure that dxcompiler.dll is found near the exe" << std::endl; ss << "You might also need to install the latest Visual C++ Redistributable package from Microsoft" << std::endl; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } #ifndef PLATFORM_UWP @@ -2128,8 +2126,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load dxgi.dll! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } HMODULE dx12 = LoadLibraryEx(L"d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); @@ -2137,8 +2135,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load d3d12.dll! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } CreateDXGIFactory2 = (PFN_CREATE_DXGI_FACTORY_2)wiGetProcAddress(dxgi, "CreateDXGIFactory2"); @@ -2147,8 +2145,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load CreateDXGIFactory2! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } #ifdef _DEBUG @@ -2165,8 +2163,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load D3D12CreateDevice! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } D3D12SerializeVersionedRootSignature = (PFN_D3D12_SERIALIZE_VERSIONED_ROOT_SIGNATURE)wiGetProcAddress(dx12, "D3D12SerializeVersionedRootSignature"); @@ -2175,8 +2173,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load D3D12SerializeVersionedRootSignature! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } #endif // PLATFORM_UWP @@ -2186,8 +2184,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "Failed to load DxcCreateInstance! ERROR: 0x" << std::hex << GetLastError(); - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } HRESULT hr; @@ -2198,8 +2196,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "DxcCreateInstance failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } #if !defined(PLATFORM_UWP) @@ -2249,8 +2247,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "CreateDXGIFactory2 failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } // Determines whether tearing support is available for fullscreen borderless windows. @@ -2323,15 +2321,15 @@ using namespace DX12_Internal; assert(dxgiAdapter != nullptr); if (dxgiAdapter == nullptr) { - wiHelper::messageBox("DXGI: No capable adapter found!", "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("DXGI: No capable adapter found!", "Error!"); + wi::platform::Exit(); } assert(device != nullptr); if (device == nullptr) { - wiHelper::messageBox("D3D12: Device couldn't be created!", "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("D3D12: Device couldn't be created!", "Error!"); + wi::platform::Exit(); } if (debuglayer) @@ -2374,8 +2372,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "D3D12MA::CreateAllocator failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } queues[QUEUE_GRAPHICS].desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; @@ -2388,8 +2386,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandQueue[QUEUE_GRAPHICS] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } hr = device->CreateFence(0, D3D12_FENCE_FLAG_SHARED, IID_PPV_ARGS(&queues[QUEUE_GRAPHICS].fence)); assert(SUCCEEDED(hr)); @@ -2397,8 +2395,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateFence[QUEUE_GRAPHICS] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } queues[QUEUE_COMPUTE].desc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; @@ -2411,8 +2409,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandQueue[QUEUE_COMPUTE] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } hr = device->CreateFence(0, D3D12_FENCE_FLAG_SHARED, IID_PPV_ARGS(&queues[QUEUE_COMPUTE].fence)); assert(SUCCEEDED(hr)); @@ -2420,8 +2418,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateFence[QUEUE_COMPUTE] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } @@ -2442,8 +2440,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateDescriptorHeap[CBV_SRV_UAV] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } descriptorheap_res.start_cpu = descriptorheap_res.heap_GPU->GetCPUDescriptorHandleForHeapStart(); @@ -2455,8 +2453,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateFence[CBV_SRV_UAV] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } descriptorheap_res.fenceValue = descriptorheap_res.fence->GetCompletedValue(); @@ -2478,8 +2476,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateDescriptorHeap[SAMPLER] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } descriptorheap_sam.start_cpu = descriptorheap_sam.heap_GPU->GetCPUDescriptorHandleForHeapStart(); @@ -2491,8 +2489,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateFence[SAMPLER] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } descriptorheap_sam.fenceValue = descriptorheap_sam.fence->GetCompletedValue(); @@ -2513,8 +2511,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateFence[FRAME] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } } } @@ -2589,8 +2587,8 @@ using namespace DX12_Internal; if (features.HighestRootSignatureVersion() < D3D_ROOT_SIGNATURE_VERSION_1_1) { assert(0); - wiHelper::messageBox("DX12: Root signature version 1.1 not supported!", "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("DX12: Root signature version 1.1 not supported!", "Error!"); + wi::platform::Exit(); } // Create common indirect command signatures: @@ -2615,8 +2613,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandSignature[dispatchIndirect] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } cmd_desc.ByteStride = sizeof(IndirectDrawArgsInstanced); @@ -2628,8 +2626,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandSignature[drawInstancedIndirect] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } cmd_desc.ByteStride = sizeof(IndirectDrawArgsIndexedInstanced); @@ -2641,8 +2639,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandSignature[drawIndexedInstancedIndirect] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } if (CheckCapability(GraphicsDeviceCapability::MESH_SHADER)) @@ -2659,8 +2657,8 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12Device::CreateCommandSignature[dispatchMeshIndirect] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox(ss.str(), "Error!"); + wi::platform::Exit(); } } @@ -2807,10 +2805,10 @@ using namespace DX12_Internal; { std::stringstream ss(""); ss << "ID3D12CommandQueue::GetTimestampFrequency[QUEUE_GRAPHICS] failed! ERROR: 0x" << std::hex << hr; - wiHelper::messageBox(ss.str(), "Warning!"); + wi::helper::messageBox(ss.str(), "Warning!"); } - wiBackLog::post("Created GraphicsDevice_DX12 (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("Created GraphicsDevice_DX12 (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } GraphicsDevice_DX12::~GraphicsDevice_DX12() { @@ -2818,7 +2816,7 @@ using namespace DX12_Internal; copyAllocator.destroy(); } - bool GraphicsDevice_DX12::CreateSwapChain(const SwapChainDesc* pDesc, wiPlatform::window_type window, SwapChain* swapChain) const + bool GraphicsDevice_DX12::CreateSwapChain(const SwapChainDesc* pDesc, wi::platform::window_type window, SwapChain* swapChain) const { auto internal_state = std::static_pointer_cast(swapChain->internal_state); if (swapChain->internal_state == nullptr) @@ -2983,7 +2981,7 @@ using namespace DX12_Internal; internal_state->dummyTexture.desc.format = pDesc->format; internal_state->renderpass = RenderPass(); - wiHelper::hash_combine(internal_state->renderpass.hash, pDesc->format); + wi::helper::hash_combine(internal_state->renderpass.hash, pDesc->format); internal_state->renderpass.desc.attachments.push_back(RenderPassAttachment::RenderTarget(&internal_state->dummyTexture)); return true; @@ -3759,83 +3757,83 @@ using namespace DX12_Internal; } size_t rootconstant_hash = 0; - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.ShaderVisibility); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.ParameterType); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.Num32BitValues); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.RegisterSpace); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.ShaderRegister); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.ShaderVisibility); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.ParameterType); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.Num32BitValues); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.RegisterSpace); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.ShaderRegister); size_t root_binding_hash = 0; for (auto& x : internal_state->root_cbvs) { - wiHelper::hash_combine(root_binding_hash, x.Flags); - wiHelper::hash_combine(root_binding_hash, x.ShaderRegister); - wiHelper::hash_combine(root_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(root_binding_hash, x.Flags); + wi::helper::hash_combine(root_binding_hash, x.ShaderRegister); + wi::helper::hash_combine(root_binding_hash, x.RegisterSpace); } size_t resource_binding_hash = 0; for (auto& x : internal_state->resources) { - wiHelper::hash_combine(resource_binding_hash, x.BaseShaderRegister); - wiHelper::hash_combine(resource_binding_hash, x.NumDescriptors); - wiHelper::hash_combine(resource_binding_hash, x.Flags); - wiHelper::hash_combine(resource_binding_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(resource_binding_hash, x.RangeType); - wiHelper::hash_combine(resource_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(resource_binding_hash, x.BaseShaderRegister); + wi::helper::hash_combine(resource_binding_hash, x.NumDescriptors); + wi::helper::hash_combine(resource_binding_hash, x.Flags); + wi::helper::hash_combine(resource_binding_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(resource_binding_hash, x.RangeType); + wi::helper::hash_combine(resource_binding_hash, x.RegisterSpace); } size_t sampler_binding_hash = 0; for (auto& x : internal_state->samplers) { - wiHelper::hash_combine(sampler_binding_hash, x.BaseShaderRegister); - wiHelper::hash_combine(sampler_binding_hash, x.NumDescriptors); - wiHelper::hash_combine(sampler_binding_hash, x.Flags); - wiHelper::hash_combine(sampler_binding_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(sampler_binding_hash, x.RangeType); - wiHelper::hash_combine(sampler_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(sampler_binding_hash, x.BaseShaderRegister); + wi::helper::hash_combine(sampler_binding_hash, x.NumDescriptors); + wi::helper::hash_combine(sampler_binding_hash, x.Flags); + wi::helper::hash_combine(sampler_binding_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(sampler_binding_hash, x.RangeType); + wi::helper::hash_combine(sampler_binding_hash, x.RegisterSpace); } size_t bindless_hash = 0; for (auto& x : internal_state->bindless_res) { - wiHelper::hash_combine(bindless_hash, x.BaseShaderRegister); - wiHelper::hash_combine(bindless_hash, x.NumDescriptors); - wiHelper::hash_combine(bindless_hash, x.Flags); - wiHelper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(bindless_hash, x.RangeType); - wiHelper::hash_combine(bindless_hash, x.RegisterSpace); + wi::helper::hash_combine(bindless_hash, x.BaseShaderRegister); + wi::helper::hash_combine(bindless_hash, x.NumDescriptors); + wi::helper::hash_combine(bindless_hash, x.Flags); + wi::helper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(bindless_hash, x.RangeType); + wi::helper::hash_combine(bindless_hash, x.RegisterSpace); } for (auto& x : internal_state->bindless_sam) { - wiHelper::hash_combine(bindless_hash, x.BaseShaderRegister); - wiHelper::hash_combine(bindless_hash, x.NumDescriptors); - wiHelper::hash_combine(bindless_hash, x.Flags); - wiHelper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(bindless_hash, x.RangeType); - wiHelper::hash_combine(bindless_hash, x.RegisterSpace); + wi::helper::hash_combine(bindless_hash, x.BaseShaderRegister); + wi::helper::hash_combine(bindless_hash, x.NumDescriptors); + wi::helper::hash_combine(bindless_hash, x.Flags); + wi::helper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(bindless_hash, x.RangeType); + wi::helper::hash_combine(bindless_hash, x.RegisterSpace); } size_t rootsig_hash = 0; - wiHelper::hash_combine(rootsig_hash, rootconstant_hash); - wiHelper::hash_combine(rootsig_hash, root_binding_hash); - wiHelper::hash_combine(rootsig_hash, resource_binding_hash); - wiHelper::hash_combine(rootsig_hash, sampler_binding_hash); - wiHelper::hash_combine(rootsig_hash, bindless_hash); + wi::helper::hash_combine(rootsig_hash, rootconstant_hash); + wi::helper::hash_combine(rootsig_hash, root_binding_hash); + wi::helper::hash_combine(rootsig_hash, resource_binding_hash); + wi::helper::hash_combine(rootsig_hash, sampler_binding_hash); + wi::helper::hash_combine(rootsig_hash, bindless_hash); for (auto& x : internal_state->staticsamplers) { - wiHelper::hash_combine(rootsig_hash, x.AddressU); - wiHelper::hash_combine(rootsig_hash, x.AddressV); - wiHelper::hash_combine(rootsig_hash, x.AddressW); - wiHelper::hash_combine(rootsig_hash, x.BorderColor); - wiHelper::hash_combine(rootsig_hash, x.ComparisonFunc); - wiHelper::hash_combine(rootsig_hash, x.Filter); - wiHelper::hash_combine(rootsig_hash, x.MaxAnisotropy); - wiHelper::hash_combine(rootsig_hash, x.MaxLOD); - wiHelper::hash_combine(rootsig_hash, x.MinLOD); - wiHelper::hash_combine(rootsig_hash, x.MipLODBias); - wiHelper::hash_combine(rootsig_hash, x.RegisterSpace); - wiHelper::hash_combine(rootsig_hash, x.ShaderRegister); - wiHelper::hash_combine(rootsig_hash, x.ShaderVisibility); + wi::helper::hash_combine(rootsig_hash, x.AddressU); + wi::helper::hash_combine(rootsig_hash, x.AddressV); + wi::helper::hash_combine(rootsig_hash, x.AddressW); + wi::helper::hash_combine(rootsig_hash, x.BorderColor); + wi::helper::hash_combine(rootsig_hash, x.ComparisonFunc); + wi::helper::hash_combine(rootsig_hash, x.Filter); + wi::helper::hash_combine(rootsig_hash, x.MaxAnisotropy); + wi::helper::hash_combine(rootsig_hash, x.MaxLOD); + wi::helper::hash_combine(rootsig_hash, x.MinLOD); + wi::helper::hash_combine(rootsig_hash, x.MipLODBias); + wi::helper::hash_combine(rootsig_hash, x.RegisterSpace); + wi::helper::hash_combine(rootsig_hash, x.ShaderRegister); + wi::helper::hash_combine(rootsig_hash, x.ShaderVisibility); } rootsignature_cache_mutex.lock(); @@ -3979,19 +3977,19 @@ using namespace DX12_Internal; pso->desc = *pDesc; pso->hash = 0; - wiHelper::hash_combine(pso->hash, pDesc->ms); - wiHelper::hash_combine(pso->hash, pDesc->as); - wiHelper::hash_combine(pso->hash, pDesc->vs); - wiHelper::hash_combine(pso->hash, pDesc->ps); - wiHelper::hash_combine(pso->hash, pDesc->hs); - wiHelper::hash_combine(pso->hash, pDesc->ds); - wiHelper::hash_combine(pso->hash, pDesc->gs); - wiHelper::hash_combine(pso->hash, pDesc->il); - wiHelper::hash_combine(pso->hash, pDesc->rs); - wiHelper::hash_combine(pso->hash, pDesc->bs); - wiHelper::hash_combine(pso->hash, pDesc->dss); - wiHelper::hash_combine(pso->hash, pDesc->pt); - wiHelper::hash_combine(pso->hash, pDesc->sample_mask); + wi::helper::hash_combine(pso->hash, pDesc->ms); + wi::helper::hash_combine(pso->hash, pDesc->as); + wi::helper::hash_combine(pso->hash, pDesc->vs); + wi::helper::hash_combine(pso->hash, pDesc->ps); + wi::helper::hash_combine(pso->hash, pDesc->hs); + wi::helper::hash_combine(pso->hash, pDesc->ds); + wi::helper::hash_combine(pso->hash, pDesc->gs); + wi::helper::hash_combine(pso->hash, pDesc->il); + wi::helper::hash_combine(pso->hash, pDesc->rs); + wi::helper::hash_combine(pso->hash, pDesc->bs); + wi::helper::hash_combine(pso->hash, pDesc->dss); + wi::helper::hash_combine(pso->hash, pDesc->pt); + wi::helper::hash_combine(pso->hash, pDesc->sample_mask); HRESULT hr = S_OK; @@ -4211,84 +4209,84 @@ using namespace DX12_Internal; } size_t rootconstant_hash = 0; - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.ShaderVisibility); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.ParameterType); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.Num32BitValues); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.RegisterSpace); - wiHelper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.ShaderRegister); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.ShaderVisibility); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.ParameterType); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.Num32BitValues); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.RegisterSpace); + wi::helper::hash_combine(rootconstant_hash, internal_state->rootconstants.Constants.ShaderRegister); size_t root_binding_hash = 0; for (auto& x : internal_state->root_cbvs) { - wiHelper::hash_combine(root_binding_hash, x.Flags); - wiHelper::hash_combine(root_binding_hash, x.ShaderRegister); - wiHelper::hash_combine(root_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(root_binding_hash, x.Flags); + wi::helper::hash_combine(root_binding_hash, x.ShaderRegister); + wi::helper::hash_combine(root_binding_hash, x.RegisterSpace); } size_t resource_binding_hash = 0; for (auto& x : internal_state->resources) { - wiHelper::hash_combine(resource_binding_hash, x.BaseShaderRegister); - wiHelper::hash_combine(resource_binding_hash, x.NumDescriptors); - wiHelper::hash_combine(resource_binding_hash, x.Flags); - wiHelper::hash_combine(resource_binding_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(resource_binding_hash, x.RangeType); - wiHelper::hash_combine(resource_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(resource_binding_hash, x.BaseShaderRegister); + wi::helper::hash_combine(resource_binding_hash, x.NumDescriptors); + wi::helper::hash_combine(resource_binding_hash, x.Flags); + wi::helper::hash_combine(resource_binding_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(resource_binding_hash, x.RangeType); + wi::helper::hash_combine(resource_binding_hash, x.RegisterSpace); } size_t sampler_binding_hash = 0; for (auto& x : internal_state->samplers) { - wiHelper::hash_combine(sampler_binding_hash, x.BaseShaderRegister); - wiHelper::hash_combine(sampler_binding_hash, x.NumDescriptors); - wiHelper::hash_combine(sampler_binding_hash, x.Flags); - wiHelper::hash_combine(sampler_binding_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(sampler_binding_hash, x.RangeType); - wiHelper::hash_combine(sampler_binding_hash, x.RegisterSpace); + wi::helper::hash_combine(sampler_binding_hash, x.BaseShaderRegister); + wi::helper::hash_combine(sampler_binding_hash, x.NumDescriptors); + wi::helper::hash_combine(sampler_binding_hash, x.Flags); + wi::helper::hash_combine(sampler_binding_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(sampler_binding_hash, x.RangeType); + wi::helper::hash_combine(sampler_binding_hash, x.RegisterSpace); } size_t bindless_hash = 0; for (auto& x : internal_state->bindless_res) { - wiHelper::hash_combine(bindless_hash, x.BaseShaderRegister); - wiHelper::hash_combine(bindless_hash, x.NumDescriptors); - wiHelper::hash_combine(bindless_hash, x.Flags); - wiHelper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(bindless_hash, x.RangeType); - wiHelper::hash_combine(bindless_hash, x.RegisterSpace); + wi::helper::hash_combine(bindless_hash, x.BaseShaderRegister); + wi::helper::hash_combine(bindless_hash, x.NumDescriptors); + wi::helper::hash_combine(bindless_hash, x.Flags); + wi::helper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(bindless_hash, x.RangeType); + wi::helper::hash_combine(bindless_hash, x.RegisterSpace); } for (auto& x : internal_state->bindless_sam) { - wiHelper::hash_combine(bindless_hash, x.BaseShaderRegister); - wiHelper::hash_combine(bindless_hash, x.NumDescriptors); - wiHelper::hash_combine(bindless_hash, x.Flags); - wiHelper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); - wiHelper::hash_combine(bindless_hash, x.RangeType); - wiHelper::hash_combine(bindless_hash, x.RegisterSpace); + wi::helper::hash_combine(bindless_hash, x.BaseShaderRegister); + wi::helper::hash_combine(bindless_hash, x.NumDescriptors); + wi::helper::hash_combine(bindless_hash, x.Flags); + wi::helper::hash_combine(bindless_hash, x.OffsetInDescriptorsFromTableStart); + wi::helper::hash_combine(bindless_hash, x.RangeType); + wi::helper::hash_combine(bindless_hash, x.RegisterSpace); } size_t rootsig_hash = 0; - wiHelper::hash_combine(rootsig_hash, pDesc->il); - wiHelper::hash_combine(rootsig_hash, rootconstant_hash); - wiHelper::hash_combine(rootsig_hash, root_binding_hash); - wiHelper::hash_combine(rootsig_hash, resource_binding_hash); - wiHelper::hash_combine(rootsig_hash, sampler_binding_hash); - wiHelper::hash_combine(rootsig_hash, bindless_hash); + wi::helper::hash_combine(rootsig_hash, pDesc->il); + wi::helper::hash_combine(rootsig_hash, rootconstant_hash); + wi::helper::hash_combine(rootsig_hash, root_binding_hash); + wi::helper::hash_combine(rootsig_hash, resource_binding_hash); + wi::helper::hash_combine(rootsig_hash, sampler_binding_hash); + wi::helper::hash_combine(rootsig_hash, bindless_hash); for (auto& x : internal_state->staticsamplers) { - wiHelper::hash_combine(rootsig_hash, x.AddressU); - wiHelper::hash_combine(rootsig_hash, x.AddressV); - wiHelper::hash_combine(rootsig_hash, x.AddressW); - wiHelper::hash_combine(rootsig_hash, x.BorderColor); - wiHelper::hash_combine(rootsig_hash, x.ComparisonFunc); - wiHelper::hash_combine(rootsig_hash, x.Filter); - wiHelper::hash_combine(rootsig_hash, x.MaxAnisotropy); - wiHelper::hash_combine(rootsig_hash, x.MaxLOD); - wiHelper::hash_combine(rootsig_hash, x.MinLOD); - wiHelper::hash_combine(rootsig_hash, x.MipLODBias); - wiHelper::hash_combine(rootsig_hash, x.RegisterSpace); - wiHelper::hash_combine(rootsig_hash, x.ShaderRegister); - wiHelper::hash_combine(rootsig_hash, x.ShaderVisibility); + wi::helper::hash_combine(rootsig_hash, x.AddressU); + wi::helper::hash_combine(rootsig_hash, x.AddressV); + wi::helper::hash_combine(rootsig_hash, x.AddressW); + wi::helper::hash_combine(rootsig_hash, x.BorderColor); + wi::helper::hash_combine(rootsig_hash, x.ComparisonFunc); + wi::helper::hash_combine(rootsig_hash, x.Filter); + wi::helper::hash_combine(rootsig_hash, x.MaxAnisotropy); + wi::helper::hash_combine(rootsig_hash, x.MaxLOD); + wi::helper::hash_combine(rootsig_hash, x.MinLOD); + wi::helper::hash_combine(rootsig_hash, x.MipLODBias); + wi::helper::hash_combine(rootsig_hash, x.RegisterSpace); + wi::helper::hash_combine(rootsig_hash, x.ShaderRegister); + wi::helper::hash_combine(rootsig_hash, x.ShaderVisibility); } rootsignature_cache_mutex.lock(); @@ -4489,14 +4487,14 @@ using namespace DX12_Internal; } renderpass->hash = 0; - wiHelper::hash_combine(renderpass->hash, pDesc->attachments.size()); + wi::helper::hash_combine(renderpass->hash, pDesc->attachments.size()); int resolve_dst_counter = 0; for (auto& attachment : pDesc->attachments) { if (attachment.type == RenderPassAttachment::Type::RENDERTARGET || attachment.type == RenderPassAttachment::Type::DEPTH_STENCIL) { - wiHelper::hash_combine(renderpass->hash, attachment.texture->desc.format); - wiHelper::hash_combine(renderpass->hash, attachment.texture->desc.sample_count); + wi::helper::hash_combine(renderpass->hash, attachment.texture->desc.format); + wi::helper::hash_combine(renderpass->hash, attachment.texture->desc.sample_count); } const Texture* texture = attachment.texture; @@ -4896,7 +4894,7 @@ using namespace DX12_Internal; library_desc.NumExports = 1; D3D12_EXPORT_DESC& export_desc = internal_state->exports.emplace_back(); - wiHelper::StringConvert(x.function_name, internal_state->export_strings.emplace_back()); + wi::helper::StringConvert(x.function_name, internal_state->export_strings.emplace_back()); export_desc.Name = internal_state->export_strings.back().c_str(); library_desc.pExports = &export_desc; @@ -4906,7 +4904,7 @@ using namespace DX12_Internal; internal_state->hitgroup_descs.reserve(pDesc->hit_groups.size()); for (auto& x : pDesc->hit_groups) { - wiHelper::StringConvert(x.name, internal_state->group_strings.emplace_back()); + wi::helper::StringConvert(x.name, internal_state->group_strings.emplace_back()); if (x.type == ShaderHitGroup::Type::GENERAL) continue; @@ -5512,7 +5510,7 @@ using namespace DX12_Internal; void GraphicsDevice_DX12::SetName(GPUResource* pResource, const char* name) { wchar_t text[256]; - if (wiHelper::StringConvert(name, text) > 0) + if (wi::helper::StringConvert(name, text) > 0) { auto internal_state = to_internal(pResource); if (internal_state->resource != nullptr) @@ -6100,10 +6098,10 @@ using namespace DX12_Internal; active_rt[cmd] = nullptr; size_t pipeline_hash = 0; - wiHelper::hash_combine(pipeline_hash, pso->hash); + wi::helper::hash_combine(pipeline_hash, pso->hash); if (active_renderpass[cmd] != nullptr) { - wiHelper::hash_combine(pipeline_hash, active_renderpass[cmd]->hash); + wi::helper::hash_combine(pipeline_hash, active_renderpass[cmd]->hash); } if (prev_pipeline_hash[cmd] == pipeline_hash) { @@ -6611,7 +6609,7 @@ using namespace DX12_Internal; void GraphicsDevice_DX12::EventBegin(const char* name, CommandList cmd) { wchar_t text[128]; - if (wiHelper::StringConvert(name, text) > 0) + if (wi::helper::StringConvert(name, text) > 0) { PIXBeginEvent(GetCommandList(cmd), 0xFF000000, text); } @@ -6623,7 +6621,7 @@ using namespace DX12_Internal; void GraphicsDevice_DX12::SetMarker(const char* name, CommandList cmd) { wchar_t text[128]; - if (wiHelper::StringConvert(name, text) > 0) + if (wi::helper::StringConvert(name, text) > 0) { PIXSetMarker(GetCommandList(cmd), 0xFFFF0000, text); } diff --git a/WickedEngine/wiGraphicsDevice_DX12.h b/WickedEngine/wiGraphicsDevice_DX12.h index 4e2717d88..4e7584fc7 100644 --- a/WickedEngine/wiGraphicsDevice_DX12.h +++ b/WickedEngine/wiGraphicsDevice_DX12.h @@ -22,7 +22,7 @@ #include #include -namespace wiGraphics +namespace wi::graphics { class GraphicsDevice_DX12 final : public GraphicsDevice { @@ -176,7 +176,7 @@ namespace wiGraphics GraphicsDevice_DX12(bool debuglayer = false, bool gpuvalidation = false); virtual ~GraphicsDevice_DX12(); - bool CreateSwapChain(const SwapChainDesc* pDesc, wiPlatform::window_type window, SwapChain* swapChain) const override; + bool CreateSwapChain(const SwapChainDesc* pDesc, wi::platform::window_type window, SwapChain* swapChain) const override; bool CreateBuffer(const GPUBufferDesc *pDesc, const void* pInitialData, GPUBuffer *pBuffer) const override; bool CreateTexture(const TextureDesc* pDesc, const SubresourceData *pInitialData, Texture *pTexture) const override; bool CreateShader(ShaderStage stage, const void *pShaderBytecode, size_t BytecodeLength, Shader *pShader) const override; diff --git a/WickedEngine/wiGraphicsDevice_Vulkan.cpp b/WickedEngine/wiGraphicsDevice_Vulkan.cpp index 05be8db3a..ce1bafa0a 100644 --- a/WickedEngine/wiGraphicsDevice_Vulkan.cpp +++ b/WickedEngine/wiGraphicsDevice_Vulkan.cpp @@ -2,7 +2,7 @@ #ifdef WICKEDENGINE_BUILD_VULKAN #include "wiHelper.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiVersion.h" #include "wiTimer.h" #include "wiUnorderedSet.h" @@ -26,16 +26,16 @@ #include // These shifts are made so that Vulkan resource bindings slots don't interfere with each other across shader stages: -// These are also defined in wiShaderCompiler.cpp as hard coded compiler arguments for SPIRV, so they need to be the same +// These are also defined in wi::shadercompiler.cpp as hard coded compiler arguments for SPIRV, so they need to be the same #define VULKAN_BINDING_SHIFT_B 0 #define VULKAN_BINDING_SHIFT_T 1000 #define VULKAN_BINDING_SHIFT_U 2000 #define VULKAN_BINDING_SHIFT_S 3000 -namespace wiGraphics +namespace wi::graphics { -namespace Vulkan_Internal +namespace vulkan_internal { // Converters: constexpr VkFormat _ConvertFormat(Format value) @@ -374,28 +374,28 @@ namespace Vulkan_Internal { switch (value) { - case wiGraphics::StencilOp::KEEP: + case wi::graphics::StencilOp::KEEP: return VK_STENCIL_OP_KEEP; break; - case wiGraphics::StencilOp::ZERO: + case wi::graphics::StencilOp::ZERO: return VK_STENCIL_OP_ZERO; break; - case wiGraphics::StencilOp::REPLACE: + case wi::graphics::StencilOp::REPLACE: return VK_STENCIL_OP_REPLACE; break; - case wiGraphics::StencilOp::INCR_SAT: + case wi::graphics::StencilOp::INCR_SAT: return VK_STENCIL_OP_INCREMENT_AND_CLAMP; break; - case wiGraphics::StencilOp::DECR_SAT: + case wi::graphics::StencilOp::DECR_SAT: return VK_STENCIL_OP_DECREMENT_AND_CLAMP; break; - case wiGraphics::StencilOp::INVERT: + case wi::graphics::StencilOp::INVERT: return VK_STENCIL_OP_INVERT; break; - case wiGraphics::StencilOp::INCR: + case wi::graphics::StencilOp::INCR: return VK_STENCIL_OP_INCREMENT_AND_WRAP; break; - case wiGraphics::StencilOp::DECR: + case wi::graphics::StencilOp::DECR: return VK_STENCIL_OP_DECREMENT_AND_WRAP; break; default: @@ -604,13 +604,13 @@ namespace Vulkan_Internal { ss += "[Vulkan Warning]: "; ss += callback_data->pMessage; - wiBackLog::post(ss, wiBackLog::LogLevel::Warning); + wi::backlog::post(ss, wi::backlog::LogLevel::Warning); } else if (message_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { ss += "[Vulkan Error]: "; ss += callback_data->pMessage; - wiBackLog::post(ss, wiBackLog::LogLevel::Error); + wi::backlog::post(ss, wi::backlog::LogLevel::Error); } return VK_FALSE; @@ -990,7 +990,7 @@ namespace Vulkan_Internal inline const std::string GetCachePath() { - return wiHelper::GetTempDirectoryPath() + "WickedVkPipelineCache.data"; + return wi::helper::GetTempDirectoryPath() + "WickedVkPipelineCache.data"; } bool CreateSwapChainInternal( @@ -1183,7 +1183,7 @@ namespace Vulkan_Internal renderPassInfo.pDependencies = &dependency; internal_state->renderpass = RenderPass(); - wiHelper::hash_combine(internal_state->renderpass.hash, internal_state->swapChainImageFormat); + wi::helper::hash_combine(internal_state->renderpass.hash, internal_state->swapChainImageFormat); auto renderpass_internal = std::make_shared(); renderpass_internal->allocationhandler = allocationhandler; internal_state->renderpass.internal_state = renderpass_internal; @@ -1264,7 +1264,7 @@ namespace Vulkan_Internal return true; } } -using namespace Vulkan_Internal; +using namespace vulkan_internal; @@ -1412,7 +1412,7 @@ using namespace Vulkan_Internal; if (cmd.uploadbuffer.desc.size < staging_size) { GPUBufferDesc uploaddesc; - uploaddesc.size = wiMath::GetNextPowerOfTwo(staging_size); + uploaddesc.size = wi::math::GetNextPowerOfTwo(staging_size); uploaddesc.usage = Usage::UPLOAD; bool upload_success = device->CreateBuffer(&uploaddesc, nullptr, &cmd.uploadbuffer); assert(upload_success); @@ -1996,7 +1996,7 @@ using namespace Vulkan_Internal; const PipelineState* pso = active_pso[cmd]; size_t pipeline_hash = prev_pipeline_hash[cmd]; - wiHelper::hash_combine(pipeline_hash, vb_hash[cmd]); + wi::helper::hash_combine(pipeline_hash, vb_hash[cmd]); auto internal_state = to_internal(pso); VkPipeline pipeline = VK_NULL_HANDLE; @@ -2219,9 +2219,9 @@ using namespace Vulkan_Internal; } // Engine functions - GraphicsDevice_Vulkan::GraphicsDevice_Vulkan(wiPlatform::window_type window, bool debuglayer) + GraphicsDevice_Vulkan::GraphicsDevice_Vulkan(wi::platform::window_type window, bool debuglayer) { - wiTimer timer; + wi::Timer timer; TOPLEVEL_ACCELERATION_STRUCTURE_INSTANCE_SIZE = sizeof(VkAccelerationStructureInstanceKHR); @@ -2233,8 +2233,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("volkInitialize failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("volkInitialize failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } // Fill out application info: @@ -2243,7 +2243,7 @@ using namespace Vulkan_Internal; appInfo.pApplicationName = "Wicked Engine Application"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Wicked Engine"; - appInfo.engineVersion = VK_MAKE_VERSION(wiVersion::GetMajor(), wiVersion::GetMinor(), wiVersion::GetRevision()); + appInfo.engineVersion = VK_MAKE_VERSION(wi::version::GetMajor(), wi::version::GetMinor(), wi::version::GetRevision()); appInfo.apiVersion = VK_API_VERSION_1_2; // Enumerate available layers and extensions: @@ -2328,8 +2328,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateInstance failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateInstance failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } volkLoadInstanceOnly(instance); @@ -2349,8 +2349,8 @@ using namespace Vulkan_Internal; if (deviceCount == 0) { assert(0); - wiHelper::messageBox("Failed to find GPU with Vulkan support!"); - wiPlatform::Exit(); + wi::helper::messageBox("Failed to find GPU with Vulkan support!"); + wi::platform::Exit(); } wi::vector devices(deviceCount); @@ -2501,8 +2501,8 @@ using namespace Vulkan_Internal; if (physicalDevice == VK_NULL_HANDLE) { assert(0); - wiHelper::messageBox("Failed to find a suitable GPU!"); - wiPlatform::Exit(); + wi::helper::messageBox("Failed to find a suitable GPU!"); + wi::platform::Exit(); } assert(properties2.properties.limits.timestampComputeAndGraphics == VK_TRUE); @@ -2650,8 +2650,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateDevice failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateDevice failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } volkLoadDevice(device); @@ -2681,15 +2681,15 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateSemaphore[QUEUE_GRAPHICS] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateSemaphore[QUEUE_GRAPHICS] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } res = vkCreateSemaphore(device, &createInfo, nullptr, &queues[QUEUE_COMPUTE].semaphore); assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateSemaphore[QUEUE_COMPUTE] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateSemaphore[QUEUE_COMPUTE] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } } @@ -2711,8 +2711,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vmaCreateAllocator failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vmaCreateAllocator failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } copyAllocator.init(this); @@ -2729,8 +2729,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateFence[FRAME] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateFence[FRAME] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } } @@ -2745,8 +2745,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkCreateCommandPool[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkCreateCommandPool[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } VkCommandBufferAllocateInfo commandBufferInfo = {}; @@ -2759,8 +2759,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkAllocateCommandBuffers[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkAllocateCommandBuffers[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } VkCommandBufferBeginInfo beginInfo = {}; @@ -2772,8 +2772,8 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); if (res != VK_SUCCESS) { - wiHelper::messageBox("vkBeginCommandBuffer[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); - wiPlatform::Exit(); + wi::helper::messageBox("vkBeginCommandBuffer[FRAME_INIT] failed! ERROR: " + std::to_string(res), "Error!"); + wi::platform::Exit(); } } } @@ -3002,7 +3002,7 @@ using namespace Vulkan_Internal; wi::vector pipelineData; std::string cachePath = GetCachePath(); - if (!wiHelper::FileRead(cachePath, pipelineData)) + if (!wi::helper::FileRead(cachePath, pipelineData)) { pipelineData.clear(); } @@ -3065,7 +3065,7 @@ using namespace Vulkan_Internal; assert(res == VK_SUCCESS); } - wiBackLog::post("Created GraphicsDevice_Vulkan (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("Created GraphicsDevice_Vulkan (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } GraphicsDevice_Vulkan::~GraphicsDevice_Vulkan() { @@ -3143,7 +3143,7 @@ using namespace Vulkan_Internal; // Write pipeline cache data to a file in binary format std::string cachePath = GetCachePath(); - wiHelper::FileWrite(cachePath, data.data(), size); + wi::helper::FileWrite(cachePath, data.data(), size); // Destroy Vulkan pipeline cache vkDestroyPipelineCache(device, pipelineCache, nullptr); @@ -3156,7 +3156,7 @@ using namespace Vulkan_Internal; } } - bool GraphicsDevice_Vulkan::CreateSwapChain(const SwapChainDesc* pDesc, wiPlatform::window_type window, SwapChain* swapChain) const + bool GraphicsDevice_Vulkan::CreateSwapChain(const SwapChainDesc* pDesc, wi::platform::window_type window, SwapChain* swapChain) const { auto internal_state = std::static_pointer_cast(swapChain->internal_state); if (swapChain->internal_state == nullptr) @@ -3940,22 +3940,22 @@ using namespace Vulkan_Internal; size_t i = 0; for (auto& x : internal_state->layoutBindings) { - wiHelper::hash_combine(internal_state->binding_hash, x.binding); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorCount); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorType); - wiHelper::hash_combine(internal_state->binding_hash, x.stageFlags); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->imageViewTypes[i++]); + wi::helper::hash_combine(internal_state->binding_hash, x.binding); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorCount); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorType); + wi::helper::hash_combine(internal_state->binding_hash, x.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->imageViewTypes[i++]); } for (auto& x : internal_state->bindlessBindings) { - wiHelper::hash_combine(internal_state->binding_hash, x.binding); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorCount); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorType); - wiHelper::hash_combine(internal_state->binding_hash, x.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, x.binding); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorCount); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorType); + wi::helper::hash_combine(internal_state->binding_hash, x.stageFlags); } - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.offset); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.size); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.offset); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.size); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.stageFlags); pso_layout_cache_mutex.lock(); if (pso_layout_cache[internal_state->binding_hash].pipelineLayout == VK_NULL_HANDLE) @@ -4343,19 +4343,19 @@ using namespace Vulkan_Internal; pso->desc = *pDesc; pso->hash = 0; - wiHelper::hash_combine(pso->hash, pDesc->ms); - wiHelper::hash_combine(pso->hash, pDesc->as); - wiHelper::hash_combine(pso->hash, pDesc->vs); - wiHelper::hash_combine(pso->hash, pDesc->ps); - wiHelper::hash_combine(pso->hash, pDesc->hs); - wiHelper::hash_combine(pso->hash, pDesc->ds); - wiHelper::hash_combine(pso->hash, pDesc->gs); - wiHelper::hash_combine(pso->hash, pDesc->il); - wiHelper::hash_combine(pso->hash, pDesc->rs); - wiHelper::hash_combine(pso->hash, pDesc->bs); - wiHelper::hash_combine(pso->hash, pDesc->dss); - wiHelper::hash_combine(pso->hash, pDesc->pt); - wiHelper::hash_combine(pso->hash, pDesc->sample_mask); + wi::helper::hash_combine(pso->hash, pDesc->ms); + wi::helper::hash_combine(pso->hash, pDesc->as); + wi::helper::hash_combine(pso->hash, pDesc->vs); + wi::helper::hash_combine(pso->hash, pDesc->ps); + wi::helper::hash_combine(pso->hash, pDesc->hs); + wi::helper::hash_combine(pso->hash, pDesc->ds); + wi::helper::hash_combine(pso->hash, pDesc->gs); + wi::helper::hash_combine(pso->hash, pDesc->il); + wi::helper::hash_combine(pso->hash, pDesc->rs); + wi::helper::hash_combine(pso->hash, pDesc->bs); + wi::helper::hash_combine(pso->hash, pDesc->dss); + wi::helper::hash_combine(pso->hash, pDesc->pt); + wi::helper::hash_combine(pso->hash, pDesc->sample_mask); VkResult res = VK_SUCCESS; @@ -4448,22 +4448,22 @@ using namespace Vulkan_Internal; size_t i = 0; for (auto& x : internal_state->layoutBindings) { - wiHelper::hash_combine(internal_state->binding_hash, x.binding); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorCount); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorType); - wiHelper::hash_combine(internal_state->binding_hash, x.stageFlags); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->imageViewTypes[i++]); + wi::helper::hash_combine(internal_state->binding_hash, x.binding); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorCount); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorType); + wi::helper::hash_combine(internal_state->binding_hash, x.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->imageViewTypes[i++]); } for (auto& x : internal_state->bindlessBindings) { - wiHelper::hash_combine(internal_state->binding_hash, x.binding); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorCount); - wiHelper::hash_combine(internal_state->binding_hash, x.descriptorType); - wiHelper::hash_combine(internal_state->binding_hash, x.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, x.binding); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorCount); + wi::helper::hash_combine(internal_state->binding_hash, x.descriptorType); + wi::helper::hash_combine(internal_state->binding_hash, x.stageFlags); } - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.offset); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.size); - wiHelper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.stageFlags); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.offset); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.size); + wi::helper::hash_combine(internal_state->binding_hash, internal_state->pushconstants.stageFlags); pso_layout_cache_mutex.lock(); @@ -4775,13 +4775,13 @@ using namespace Vulkan_Internal; renderpass->desc = *pDesc; renderpass->hash = 0; - wiHelper::hash_combine(renderpass->hash, pDesc->attachments.size()); + wi::helper::hash_combine(renderpass->hash, pDesc->attachments.size()); for (auto& attachment : pDesc->attachments) { if (attachment.type == RenderPassAttachment::Type::RENDERTARGET || attachment.type == RenderPassAttachment::Type::DEPTH_STENCIL) { - wiHelper::hash_combine(renderpass->hash, attachment.texture->desc.format); - wiHelper::hash_combine(renderpass->hash, attachment.texture->desc.sample_count); + wi::helper::hash_combine(renderpass->hash, attachment.texture->desc.format); + wi::helper::hash_combine(renderpass->hash, attachment.texture->desc.sample_count); } } @@ -5930,10 +5930,10 @@ using namespace Vulkan_Internal; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; switch (queue) { - case wiGraphics::QUEUE_GRAPHICS: + case wi::graphics::QUEUE_GRAPHICS: poolInfo.queueFamilyIndex = graphicsFamily; break; - case wiGraphics::QUEUE_COMPUTE: + case wi::graphics::QUEUE_COMPUTE: poolInfo.queueFamilyIndex = computeFamily; break; default: @@ -6417,7 +6417,7 @@ using namespace Vulkan_Internal; assert(count <= 8); for (uint32_t i = 0; i < count; ++i) { - wiHelper::hash_combine(hash, strides[i]); + wi::helper::hash_combine(hash, strides[i]); vb_strides[cmd][i] = strides[i]; if (vertexBuffers[i] == nullptr || !vertexBuffers[i]->IsValid()) @@ -6543,10 +6543,10 @@ using namespace Vulkan_Internal; void GraphicsDevice_Vulkan::BindPipelineState(const PipelineState* pso, CommandList cmd) { size_t pipeline_hash = 0; - wiHelper::hash_combine(pipeline_hash, pso->hash); + wi::helper::hash_combine(pipeline_hash, pso->hash); if (active_renderpass[cmd] != nullptr) { - wiHelper::hash_combine(pipeline_hash, active_renderpass[cmd]->hash); + wi::helper::hash_combine(pipeline_hash, active_renderpass[cmd]->hash); } if (prev_pipeline_hash[cmd] == pipeline_hash) { @@ -7274,5 +7274,4 @@ using namespace Vulkan_Internal; } } - #endif // WICKEDENGINE_BUILD_VULKAN diff --git a/WickedEngine/wiGraphicsDevice_Vulkan.h b/WickedEngine/wiGraphicsDevice_Vulkan.h index 5d629e3cd..306840610 100644 --- a/WickedEngine/wiGraphicsDevice_Vulkan.h +++ b/WickedEngine/wiGraphicsDevice_Vulkan.h @@ -25,7 +25,7 @@ #include #include -namespace wiGraphics +namespace wi::graphics { class GraphicsDevice_Vulkan final : public GraphicsDevice { @@ -234,10 +234,10 @@ namespace wiGraphics wi::vector common_samplers; public: - GraphicsDevice_Vulkan(wiPlatform::window_type window, bool debuglayer = false); + GraphicsDevice_Vulkan(wi::platform::window_type window, bool debuglayer = false); virtual ~GraphicsDevice_Vulkan(); - bool CreateSwapChain(const SwapChainDesc* pDesc, wiPlatform::window_type window, SwapChain* swapChain) const override; + bool CreateSwapChain(const SwapChainDesc* pDesc, wi::platform::window_type window, SwapChain* swapChain) const override; bool CreateBuffer(const GPUBufferDesc *pDesc, const void* pInitialData, GPUBuffer *pBuffer) const override; bool CreateTexture(const TextureDesc* pDesc, const SubresourceData *pInitialData, Texture *pTexture) const override; bool CreateShader(ShaderStage stage, const void *pShaderBytecode, size_t BytecodeLength, Shader *pShader) const override; diff --git a/WickedEngine/wiHairParticle.cpp b/WickedEngine/wiHairParticle.cpp index 34f4a640c..ba419c91a 100644 --- a/WickedEngine/wiHairParticle.cpp +++ b/WickedEngine/wiHairParticle.cpp @@ -1,566 +1,567 @@ #include "wiHairParticle.h" #include "wiRenderer.h" #include "wiResourceManager.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiRandom.h" #include "wiArchive.h" #include "shaders/ShaderInterop.h" #include "wiTextureHelper.h" #include "wiScene.h" #include "shaders/ShaderInterop_HairParticle.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiTimer.h" -using namespace wiGraphics; +using namespace wi::primitive; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::enums; -namespace wiScene +namespace wi { + static Shader vs; + static Shader ps_prepass; + static Shader ps; + static Shader ps_simple; + static Shader cs_simulate; + static Shader cs_finishUpdate; + static DepthStencilState dss_default, dss_equal; + static RasterizerState rs, ncrs, wirers; + static BlendState bs; + static PipelineState PSO[RENDERPASS_COUNT]; + static PipelineState PSO_wire; -static Shader vs; -static Shader ps_prepass; -static Shader ps; -static Shader ps_simple; -static Shader cs_simulate; -static Shader cs_finishUpdate; -static DepthStencilState dss_default, dss_equal; -static RasterizerState rs, ncrs, wirers; -static BlendState bs; -static PipelineState PSO[RENDERPASS_COUNT]; -static PipelineState PSO_wire; - -void wiHairParticle::UpdateCPU(const TransformComponent& transform, const MeshComponent& mesh, float dt) -{ - world = transform.world; - - XMFLOAT3 _min = mesh.aabb.getMin(); - XMFLOAT3 _max = mesh.aabb.getMax(); - - _max.x += length; - _max.y += length; - _max.z += length; - - _min.x -= length; - _min.y -= length; - _min.z -= length; - - aabb = AABB(_min, _max); - aabb = aabb.transform(world); - - GraphicsDevice* device = wiGraphics::GetDevice(); - - if (_flags & REBUILD_BUFFERS || !constantBuffer.IsValid() || (strandCount * segmentCount) != simulationBuffer.GetDesc().size / sizeof(PatchSimulationData)) + void HairParticleSystem::UpdateCPU(const TransformComponent& transform, const MeshComponent& mesh, float dt) { - _flags &= ~REBUILD_BUFFERS; - regenerate_frame = true; + world = transform.world; - GPUBufferDesc bd; - bd.usage = Usage::DEFAULT; - bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + XMFLOAT3 _min = mesh.aabb.getMin(); + XMFLOAT3 _max = mesh.aabb.getMax(); - const uint32_t particleCount = strandCount * segmentCount; - if (particleCount > 0) + _max.x += length; + _max.y += length; + _max.z += length; + + _min.x -= length; + _min.y -= length; + _min.z -= length; + + aabb = AABB(_min, _max); + aabb = aabb.transform(world); + + GraphicsDevice* device = wi::graphics::GetDevice(); + + if (_flags & REBUILD_BUFFERS || !constantBuffer.IsValid() || (strandCount * segmentCount) != simulationBuffer.GetDesc().size / sizeof(PatchSimulationData)) { - bd.stride = sizeof(PatchSimulationData); - bd.size = bd.stride * particleCount; - device->CreateBuffer(&bd, nullptr, &simulationBuffer); - device->SetName(&simulationBuffer, "simulationBuffer"); + _flags &= ~REBUILD_BUFFERS; + regenerate_frame = true; - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + GPUBufferDesc bd; + bd.usage = Usage::DEFAULT; + bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + + const uint32_t particleCount = strandCount * segmentCount; + if (particleCount > 0) { - bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + bd.stride = sizeof(PatchSimulationData); + bd.size = bd.stride * particleCount; + device->CreateBuffer(&bd, nullptr, &simulationBuffer); + device->SetName(&simulationBuffer, "simulationBuffer"); + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + { + bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + } + bd.stride = sizeof(MeshComponent::Vertex_POS); + bd.size = bd.stride * 4 * particleCount; + device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[0]); + device->SetName(&vertexBuffer_POS[0], "vertexBuffer_POS[0]"); + device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[1]); + device->SetName(&vertexBuffer_POS[1], "vertexBuffer_POS[1]"); + + bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; + bd.stride = sizeof(MeshComponent::Vertex_TEX); + bd.size = bd.stride * 4 * particleCount; + device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX); + device->SetName(&vertexBuffer_TEX, "vertexBuffer_TEX"); + + bd.bind_flags = BindFlag::SHADER_RESOURCE; + bd.misc_flags = ResourceMiscFlag::NONE; + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + { + bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + } + bd.format = Format::R32_UINT; + bd.stride = sizeof(uint); + bd.size = bd.stride * 6 * particleCount; + wi::vector primitiveData(6 * particleCount); + for (uint particleID = 0; particleID < particleCount; ++particleID) + { + uint v0 = particleID * 4; + uint i0 = particleID * 6; + primitiveData[i0 + 0] = v0 + 0; + primitiveData[i0 + 1] = v0 + 1; + primitiveData[i0 + 2] = v0 + 2; + primitiveData[i0 + 3] = v0 + 2; + primitiveData[i0 + 4] = v0 + 1; + primitiveData[i0 + 5] = v0 + 3; + } + device->CreateBuffer(&bd, primitiveData.data(), &primitiveBuffer); + device->SetName(&primitiveBuffer, "primitiveBuffer"); + + bd.bind_flags = BindFlag::INDEX_BUFFER | BindFlag::UNORDERED_ACCESS; + bd.misc_flags = ResourceMiscFlag::NONE; + bd.format = Format::R32_UINT; + bd.stride = sizeof(uint); + bd.size = bd.stride * 6 * particleCount; + device->CreateBuffer(&bd, nullptr, &culledIndexBuffer); + device->SetName(&culledIndexBuffer, "culledIndexBuffer"); } - bd.stride = sizeof(MeshComponent::Vertex_POS); - bd.size = bd.stride * 4 * particleCount; - device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[0]); - device->SetName(&vertexBuffer_POS[0], "vertexBuffer_POS[0]"); - device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[1]); - device->SetName(&vertexBuffer_POS[1], "vertexBuffer_POS[1]"); - bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; - bd.stride = sizeof(MeshComponent::Vertex_TEX); - bd.size = bd.stride * 4 * particleCount; - device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX); - device->SetName(&vertexBuffer_TEX, "vertexBuffer_TEX"); - - bd.bind_flags = BindFlag::SHADER_RESOURCE; + bd.usage = Usage::DEFAULT; + bd.size = sizeof(HairParticleCB); + bd.bind_flags = BindFlag::CONSTANT_BUFFER; bd.misc_flags = ResourceMiscFlag::NONE; - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) + device->CreateBuffer(&bd, nullptr, &constantBuffer); + device->SetName(&constantBuffer, "constantBuffer"); + + if (vertex_lengths.size() != mesh.vertex_positions.size()) { - bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; + vertex_lengths.resize(mesh.vertex_positions.size()); + std::fill(vertex_lengths.begin(), vertex_lengths.end(), 1.0f); } - bd.format = Format::R32_UINT; - bd.stride = sizeof(uint); - bd.size = bd.stride * 6 * particleCount; - wi::vector primitiveData(6 * particleCount); - for (uint particleID = 0; particleID < particleCount; ++particleID) + + indices.clear(); + for (size_t j = 0; j < mesh.indices.size(); j += 3) { - uint v0 = particleID * 4; - uint i0 = particleID * 6; - primitiveData[i0 + 0] = v0 + 0; - primitiveData[i0 + 1] = v0 + 1; - primitiveData[i0 + 2] = v0 + 2; - primitiveData[i0 + 3] = v0 + 2; - primitiveData[i0 + 4] = v0 + 1; - primitiveData[i0 + 5] = v0 + 3; + const uint32_t triangle[] = { + mesh.indices[j + 0], + mesh.indices[j + 1], + mesh.indices[j + 2], + }; + if (vertex_lengths[triangle[0]] > 0 || vertex_lengths[triangle[1]] > 0 || vertex_lengths[triangle[2]] > 0) + { + indices.push_back(triangle[0]); + indices.push_back(triangle[1]); + indices.push_back(triangle[2]); + } } - device->CreateBuffer(&bd, primitiveData.data(), &primitiveBuffer); - device->SetName(&primitiveBuffer, "primitiveBuffer"); - bd.bind_flags = BindFlag::INDEX_BUFFER | BindFlag::UNORDERED_ACCESS; - bd.misc_flags = ResourceMiscFlag::NONE; - bd.format = Format::R32_UINT; - bd.stride = sizeof(uint); - bd.size = bd.stride * 6 * particleCount; - device->CreateBuffer(&bd, nullptr, &culledIndexBuffer); - device->SetName(&culledIndexBuffer, "culledIndexBuffer"); - } - - bd.usage = Usage::DEFAULT; - bd.size = sizeof(HairParticleCB); - bd.bind_flags = BindFlag::CONSTANT_BUFFER; - bd.misc_flags = ResourceMiscFlag::NONE; - device->CreateBuffer(&bd, nullptr, &constantBuffer); - device->SetName(&constantBuffer, "constantBuffer"); - - if (vertex_lengths.size() != mesh.vertex_positions.size()) - { - vertex_lengths.resize(mesh.vertex_positions.size()); - std::fill(vertex_lengths.begin(), vertex_lengths.end(), 1.0f); - } - - indices.clear(); - for (size_t j = 0; j < mesh.indices.size(); j += 3) - { - const uint32_t triangle[] = { - mesh.indices[j + 0], - mesh.indices[j + 1], - mesh.indices[j + 2], - }; - if (vertex_lengths[triangle[0]] > 0 || vertex_lengths[triangle[1]] > 0 || vertex_lengths[triangle[2]] > 0) + if (!vertex_lengths.empty()) { - indices.push_back(triangle[0]); - indices.push_back(triangle[1]); - indices.push_back(triangle[2]); + wi::vector ulengths; + ulengths.reserve(vertex_lengths.size()); + for (auto& x : vertex_lengths) + { + ulengths.push_back(uint8_t(wi::math::Clamp(x, 0, 1) * 255.0f)); + } + + bd.misc_flags = ResourceMiscFlag::NONE; + bd.bind_flags = BindFlag::SHADER_RESOURCE; + bd.format = Format::R8_UNORM; + bd.stride = sizeof(uint8_t); + bd.size = bd.stride * (uint32_t)ulengths.size(); + device->CreateBuffer(&bd, ulengths.data(), &vertexBuffer_length); + } + if (!indices.empty()) + { + bd.misc_flags = ResourceMiscFlag::NONE; + bd.bind_flags = BindFlag::SHADER_RESOURCE; + bd.format = Format::R32_UINT; + bd.stride = sizeof(uint32_t); + bd.size = bd.stride * (uint32_t)indices.size(); + device->CreateBuffer(&bd, indices.data(), &indexBuffer); + } + + if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING) && primitiveBuffer.IsValid()) + { + RaytracingAccelerationStructureDesc desc; + desc.type = RaytracingAccelerationStructureDesc::Type::BOTTOMLEVEL; + desc.flags |= RaytracingAccelerationStructureDesc::FLAG_ALLOW_UPDATE; + desc.flags |= RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; + + desc.bottom_level.geometries.emplace_back(); + auto& geometry = desc.bottom_level.geometries.back(); + geometry.type = RaytracingAccelerationStructureDesc::BottomLevel::Geometry::Type::TRIANGLES; + geometry.triangles.vertex_buffer = vertexBuffer_POS[0]; + geometry.triangles.index_buffer = primitiveBuffer; + geometry.triangles.index_format = IndexBufferFormat::UINT32; + geometry.triangles.index_count = (uint32_t)(primitiveBuffer.desc.size / primitiveBuffer.desc.stride); + geometry.triangles.index_offset = 0; + geometry.triangles.vertex_count = (uint32_t)(vertexBuffer_POS[0].desc.size / vertexBuffer_POS[0].desc.stride); + geometry.triangles.vertex_format = Format::R32G32B32_FLOAT; + geometry.triangles.vertex_stride = sizeof(MeshComponent::Vertex_POS); + + bool success = device->CreateRaytracingAccelerationStructure(&desc, &BLAS); + assert(success); + device->SetName(&BLAS, "BLAS_hair"); } } - if (!vertex_lengths.empty()) + if (!indirectBuffer.IsValid()) { - wi::vector ulengths; - ulengths.reserve(vertex_lengths.size()); - for (auto& x : vertex_lengths) - { - ulengths.push_back(uint8_t(wiMath::Clamp(x, 0, 1) * 255.0f)); - } - - bd.misc_flags = ResourceMiscFlag::NONE; - bd.bind_flags = BindFlag::SHADER_RESOURCE; - bd.format = Format::R8_UNORM; - bd.stride = sizeof(uint8_t); - bd.size = bd.stride * (uint32_t)ulengths.size(); - device->CreateBuffer(&bd, ulengths.data(), &vertexBuffer_length); - } - if (!indices.empty()) - { - bd.misc_flags = ResourceMiscFlag::NONE; - bd.bind_flags = BindFlag::SHADER_RESOURCE; - bd.format = Format::R32_UINT; - bd.stride = sizeof(uint32_t); - bd.size = bd.stride * (uint32_t)indices.size(); - device->CreateBuffer(&bd, indices.data(), &indexBuffer); + GPUBufferDesc desc; + desc.size = sizeof(uint) + sizeof(IndirectDrawArgsIndexedInstanced); // counter + draw args + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW | ResourceMiscFlag::INDIRECT_ARGS; + desc.bind_flags = BindFlag::UNORDERED_ACCESS; + device->CreateBuffer(&desc, nullptr, &indirectBuffer); } - if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING) && primitiveBuffer.IsValid()) + if (!subsetBuffer.IsValid()) { - RaytracingAccelerationStructureDesc desc; - desc.type = RaytracingAccelerationStructureDesc::Type::BOTTOMLEVEL; - desc.flags |= RaytracingAccelerationStructureDesc::FLAG_ALLOW_UPDATE; - desc.flags |= RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; - - desc.bottom_level.geometries.emplace_back(); - auto& geometry = desc.bottom_level.geometries.back(); - geometry.type = RaytracingAccelerationStructureDesc::BottomLevel::Geometry::Type::TRIANGLES; - geometry.triangles.vertex_buffer = vertexBuffer_POS[0]; - geometry.triangles.index_buffer = primitiveBuffer; - geometry.triangles.index_format = IndexBufferFormat::UINT32; - geometry.triangles.index_count = (uint32_t)(primitiveBuffer.desc.size / primitiveBuffer.desc.stride); - geometry.triangles.index_offset = 0; - geometry.triangles.vertex_count = (uint32_t)(vertexBuffer_POS[0].desc.size / vertexBuffer_POS[0].desc.stride); - geometry.triangles.vertex_format = Format::R32G32B32_FLOAT; - geometry.triangles.vertex_stride = sizeof(MeshComponent::Vertex_POS); - - bool success = device->CreateRaytracingAccelerationStructure(&desc, &BLAS); - assert(success); - device->SetName(&BLAS, "BLAS_hair"); + GPUBufferDesc desc; + desc.stride = sizeof(ShaderMeshSubset); + desc.size = desc.stride; + desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + device->CreateBuffer(&desc, nullptr, &subsetBuffer); } - } - if (!indirectBuffer.IsValid()) - { - GPUBufferDesc desc; - desc.size = sizeof(uint) + sizeof(IndirectDrawArgsIndexedInstanced); // counter + draw args - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW | ResourceMiscFlag::INDIRECT_ARGS; - desc.bind_flags = BindFlag::UNORDERED_ACCESS; - device->CreateBuffer(&desc, nullptr, &indirectBuffer); - } + std::swap(vertexBuffer_POS[0], vertexBuffer_POS[1]); - if (!subsetBuffer.IsValid()) - { - GPUBufferDesc desc; - desc.stride = sizeof(ShaderMeshSubset); - desc.size = desc.stride; - desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - device->CreateBuffer(&desc, nullptr, &subsetBuffer); - } - - std::swap(vertexBuffer_POS[0], vertexBuffer_POS[1]); - - if (BLAS.IsValid() && !BLAS.desc.bottom_level.geometries.empty()) - { - BLAS.desc.bottom_level.geometries.back().triangles.vertex_buffer = vertexBuffer_POS[0]; - } - -} -void wiHairParticle::UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const MeshComponent& mesh, const MaterialComponent& material, CommandList cmd) const -{ - if (strandCount == 0 || !simulationBuffer.IsValid()) - { - return; - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - device->EventBegin("HairParticle - UpdateGPU", cmd); - - TextureDesc desc; - if (material.textures[MaterialComponent::BASECOLORMAP].resource != nullptr) - { - desc = material.textures[MaterialComponent::BASECOLORMAP].resource->texture.GetDesc(); - } - HairParticleCB hcb; - hcb.xHairWorld = world; - hcb.xHairRegenerate = regenerate_frame ? 1 : 0; - hcb.xLength = length; - hcb.xStiffness = stiffness; - hcb.xHairRandomness = randomness; - hcb.xHairStrandCount = strandCount; - hcb.xHairSegmentCount = std::max(segmentCount, 1u); - hcb.xHairParticleCount = hcb.xHairStrandCount * hcb.xHairSegmentCount; - hcb.xHairRandomSeed = randomSeed; - hcb.xHairViewDistance = viewDistance; - hcb.xHairBaseMeshIndexCount = (indices.empty() ? (uint)mesh.indices.size() : (uint)indices.size()); - hcb.xHairBaseMeshVertexPositionStride = sizeof(MeshComponent::Vertex_POS); - // segmentCount will be loop in the shader, not a threadgroup so we don't need it here: - hcb.xHairNumDispatchGroups = (hcb.xHairParticleCount + THREADCOUNT_SIMULATEHAIR - 1) / THREADCOUNT_SIMULATEHAIR; - hcb.xHairFramesXY = uint2(std::max(1u, framesX), std::max(1u, framesY)); - hcb.xHairFrameCount = std::max(1u, frameCount); - hcb.xHairFrameStart = frameStart; - hcb.xHairTexMul = float2(1.0f / (float)hcb.xHairFramesXY.x, 1.0f / (float)hcb.xHairFramesXY.y); - hcb.xHairAspect = (float)std::max(1u, desc.width) / (float)std::max(1u, desc.height); - hcb.xHairLayerMask = layerMask; - hcb.xHairInstanceIndex = instanceIndex; - device->UpdateBuffer(&constantBuffer, &hcb, cmd); - - ShaderMeshSubset subset; - subset.init(); - subset.indexOffset = 0; - subset.materialIndex = materialIndex; - device->UpdateBuffer(&subsetBuffer, &subset, cmd); - - { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&constantBuffer, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), - GPUBarrier::Buffer(&subsetBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - // Simulate: - { - device->BindComputeShader(&cs_simulate, cmd); - device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); - - const GPUResource* uavs[] = { - &simulationBuffer, - &vertexBuffer_POS[0], - &vertexBuffer_TEX, - &culledIndexBuffer, - &indirectBuffer - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - - const GPUResource* res[] = { - indexBuffer.IsValid() ? &indexBuffer : &mesh.indexBuffer, - mesh.streamoutBuffer_POS.IsValid() ? &mesh.streamoutBuffer_POS : &mesh.vertexBuffer_POS, - &vertexBuffer_length - }; - device->BindResources(res, 0, arraysize(res), cmd); - - device->Dispatch(hcb.xHairNumDispatchGroups, 1, 1, cmd); - - GPUBarrier barriers[] = { - GPUBarrier::Memory() - }; - device->Barrier(barriers, arraysize(barriers), cmd); + if (BLAS.IsValid() && !BLAS.desc.bottom_level.geometries.empty()) + { + BLAS.desc.bottom_level.geometries.back().triangles.vertex_buffer = vertexBuffer_POS[0]; + } } - - // Finish update (reset counter, create indirect draw args): + void HairParticleSystem::UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const MeshComponent& mesh, const MaterialComponent& material, CommandList cmd) const { - device->BindComputeShader(&cs_finishUpdate, cmd); - - const GPUResource* uavs[] = { - &indirectBuffer - }; - device->BindUAVs(uavs, 0, arraysize(uavs), cmd); - - device->Dispatch(1, 1, 1, cmd); - - GPUBarrier barriers[] = { - GPUBarrier::Memory(&indirectBuffer), - GPUBarrier::Buffer(&indirectBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT), - GPUBarrier::Buffer(&vertexBuffer_POS[0], ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&vertexBuffer_TEX, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), - GPUBarrier::Buffer(&culledIndexBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDEX_BUFFER), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - - } - - device->EventEnd(cmd); - - regenerate_frame = false; -} - -void wiHairParticle::Draw(const MaterialComponent& material, RENDERPASS renderPass, CommandList cmd) const -{ - if (strandCount == 0 || !constantBuffer.IsValid()) - { - return; - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - device->EventBegin("HairParticle - Draw", cmd); - - device->BindStencilRef(STENCILREF_DEFAULT, cmd); - - if (wiRenderer::IsWireRender()) - { - if (renderPass == RENDERPASS_PREPASS) + if (strandCount == 0 || !simulationBuffer.IsValid()) { return; } - device->BindPipelineState(&PSO_wire, cmd); - device->BindResource(wiTextureHelper::getWhite(), 0, cmd); - } - else - { - device->BindPipelineState(&PSO[renderPass], cmd); - if (renderPass != RENDERPASS_PREPASS) // depth only alpha test will be full res + GraphicsDevice* device = wi::graphics::GetDevice(); + device->EventBegin("HairParticle - UpdateGPU", cmd); + + TextureDesc desc; + if (material.textures[MaterialComponent::BASECOLORMAP].resource.IsValid()) { - device->BindShadingRate(material.shadingRate, cmd); + desc = material.textures[MaterialComponent::BASECOLORMAP].resource.GetTexture().GetDesc(); } + HairParticleCB hcb; + hcb.xHairWorld = world; + hcb.xHairRegenerate = regenerate_frame ? 1 : 0; + hcb.xLength = length; + hcb.xStiffness = stiffness; + hcb.xHairRandomness = randomness; + hcb.xHairStrandCount = strandCount; + hcb.xHairSegmentCount = std::max(segmentCount, 1u); + hcb.xHairParticleCount = hcb.xHairStrandCount * hcb.xHairSegmentCount; + hcb.xHairRandomSeed = randomSeed; + hcb.xHairViewDistance = viewDistance; + hcb.xHairBaseMeshIndexCount = (indices.empty() ? (uint)mesh.indices.size() : (uint)indices.size()); + hcb.xHairBaseMeshVertexPositionStride = sizeof(MeshComponent::Vertex_POS); + // segmentCount will be loop in the shader, not a threadgroup so we don't need it here: + hcb.xHairNumDispatchGroups = (hcb.xHairParticleCount + THREADCOUNT_SIMULATEHAIR - 1) / THREADCOUNT_SIMULATEHAIR; + hcb.xHairFramesXY = uint2(std::max(1u, framesX), std::max(1u, framesY)); + hcb.xHairFrameCount = std::max(1u, frameCount); + hcb.xHairFrameStart = frameStart; + hcb.xHairTexMul = float2(1.0f / (float)hcb.xHairFramesXY.x, 1.0f / (float)hcb.xHairFramesXY.y); + hcb.xHairAspect = (float)std::max(1u, desc.width) / (float)std::max(1u, desc.height); + hcb.xHairLayerMask = layerMask; + hcb.xHairInstanceIndex = instanceIndex; + device->UpdateBuffer(&constantBuffer, &hcb, cmd); + + ShaderMeshSubset subset; + subset.init(); + subset.indexOffset = 0; + subset.materialIndex = materialIndex; + device->UpdateBuffer(&subsetBuffer, &subset, cmd); + + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&constantBuffer, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), + GPUBarrier::Buffer(&subsetBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + // Simulate: + { + device->BindComputeShader(&cs_simulate, cmd); + device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); + + const GPUResource* uavs[] = { + &simulationBuffer, + &vertexBuffer_POS[0], + &vertexBuffer_TEX, + &culledIndexBuffer, + &indirectBuffer + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + const GPUResource* res[] = { + indexBuffer.IsValid() ? &indexBuffer : &mesh.indexBuffer, + mesh.streamoutBuffer_POS.IsValid() ? &mesh.streamoutBuffer_POS : &mesh.vertexBuffer_POS, + &vertexBuffer_length + }; + device->BindResources(res, 0, arraysize(res), cmd); + + device->Dispatch(hcb.xHairNumDispatchGroups, 1, 1, cmd); + + GPUBarrier barriers[] = { + GPUBarrier::Memory() + }; + device->Barrier(barriers, arraysize(barriers), cmd); + + } + + // Finish update (reset counter, create indirect draw args): + { + device->BindComputeShader(&cs_finishUpdate, cmd); + + const GPUResource* uavs[] = { + &indirectBuffer + }; + device->BindUAVs(uavs, 0, arraysize(uavs), cmd); + + device->Dispatch(1, 1, 1, cmd); + + GPUBarrier barriers[] = { + GPUBarrier::Memory(&indirectBuffer), + GPUBarrier::Buffer(&indirectBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT), + GPUBarrier::Buffer(&vertexBuffer_POS[0], ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&vertexBuffer_TEX, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), + GPUBarrier::Buffer(&culledIndexBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDEX_BUFFER), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + + } + + device->EventEnd(cmd); + + regenerate_frame = false; } - device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); - device->BindResource(&primitiveBuffer, 0, cmd); - - device->BindIndexBuffer(&culledIndexBuffer, IndexBufferFormat::UINT32, 0, cmd); - - device->DrawIndexedInstancedIndirect(&indirectBuffer, 4, cmd); - - device->EventEnd(cmd); -} - - -void wiHairParticle::Serialize(wiArchive& archive, wiECS::EntitySerializer& seri) -{ - if (archive.IsReadMode()) + void HairParticleSystem::Draw(const MaterialComponent& material, wi::enums::RENDERPASS renderPass, CommandList cmd) const { - archive >> _flags; - wiECS::SerializeEntity(archive, meshID, seri); - archive >> strandCount; - archive >> segmentCount; - archive >> randomSeed; - archive >> length; - archive >> stiffness; - archive >> randomness; - archive >> viewDistance; - if (archive.GetVersion() >= 39) + if (strandCount == 0 || !constantBuffer.IsValid()) { - archive >> vertex_lengths; - } - if (archive.GetVersion() >= 42) - { - archive >> framesX; - archive >> framesY; - archive >> frameCount; - archive >> frameStart; + return; } - if (archive.GetVersion() == 48) + GraphicsDevice* device = wi::graphics::GetDevice(); + device->EventBegin("HairParticle - Draw", cmd); + + device->BindStencilRef(STENCILREF_DEFAULT, cmd); + + if (wi::renderer::IsWireRender()) { - uint8_t shadingRate; - archive >> shadingRate; // no longer needed - } - } - else - { - archive << _flags; - wiECS::SerializeEntity(archive, meshID, seri); - archive << strandCount; - archive << segmentCount; - archive << randomSeed; - archive << length; - archive << stiffness; - archive << randomness; - archive << viewDistance; - if (archive.GetVersion() >= 39) - { - archive << vertex_lengths; - } - if (archive.GetVersion() >= 42) - { - archive << framesX; - archive << framesY; - archive << frameCount; - archive << frameStart; - } - } -} - -namespace wiHairParticle_Internal -{ - void LoadShaders() - { - wiRenderer::LoadShader(ShaderStage::VS, vs, "hairparticleVS.cso"); - - wiRenderer::LoadShader(ShaderStage::PS, ps_simple, "hairparticlePS_simple.cso"); - wiRenderer::LoadShader(ShaderStage::PS, ps_prepass, "hairparticlePS_prepass.cso"); - wiRenderer::LoadShader(ShaderStage::PS, ps, "hairparticlePS.cso"); - - wiRenderer::LoadShader(ShaderStage::CS, cs_simulate, "hairparticle_simulateCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, cs_finishUpdate, "hairparticle_finishUpdateCS.cso"); - - GraphicsDevice* device = wiGraphics::GetDevice(); - - for (int i = 0; i < RENDERPASS_COUNT; ++i) - { - if (i == RENDERPASS_PREPASS || i == RENDERPASS_MAIN) + if (renderPass == RENDERPASS_PREPASS) { - PipelineStateDesc desc; - desc.vs = &vs; - desc.bs = &bs; - desc.rs = &ncrs; - desc.dss = &dss_default; - desc.pt = PrimitiveTopology::TRIANGLELIST; + return; + } + device->BindPipelineState(&PSO_wire, cmd); + device->BindResource(wi::texturehelper::getWhite(), 0, cmd); + } + else + { + device->BindPipelineState(&PSO[renderPass], cmd); - switch (i) - { - case RENDERPASS_PREPASS: - desc.ps = &ps_prepass; - break; - case RENDERPASS_MAIN: - desc.ps = &ps; - desc.dss = &dss_equal; - break; - } - - device->CreatePipelineState(&desc, &PSO[i]); + if (renderPass != RENDERPASS_PREPASS) // depth only alpha test will be full res + { + device->BindShadingRate(material.shadingRate, cmd); } } + device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); + device->BindResource(&primitiveBuffer, 0, cmd); + + device->BindIndexBuffer(&culledIndexBuffer, IndexBufferFormat::UINT32, 0, cmd); + + device->DrawIndexedInstancedIndirect(&indirectBuffer, 4, cmd); + + device->EventEnd(cmd); + } + + + void HairParticleSystem::Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri) + { + if (archive.IsReadMode()) { - PipelineStateDesc desc; - desc.vs = &vs; - desc.ps = &ps_simple; - desc.bs = &bs; - desc.rs = &wirers; - desc.dss = &dss_default; - desc.pt = PrimitiveTopology::TRIANGLELIST; - device->CreatePipelineState(&desc, &PSO_wire); + archive >> _flags; + wi::ecs::SerializeEntity(archive, meshID, seri); + archive >> strandCount; + archive >> segmentCount; + archive >> randomSeed; + archive >> length; + archive >> stiffness; + archive >> randomness; + archive >> viewDistance; + if (archive.GetVersion() >= 39) + { + archive >> vertex_lengths; + } + if (archive.GetVersion() >= 42) + { + archive >> framesX; + archive >> framesY; + archive >> frameCount; + archive >> frameStart; + } + + if (archive.GetVersion() == 48) + { + uint8_t shadingRate; + archive >> shadingRate; // no longer needed + } } + else + { + archive << _flags; + wi::ecs::SerializeEntity(archive, meshID, seri); + archive << strandCount; + archive << segmentCount; + archive << randomSeed; + archive << length; + archive << stiffness; + archive << randomness; + archive << viewDistance; + if (archive.GetVersion() >= 39) + { + archive << vertex_lengths; + } + if (archive.GetVersion() >= 42) + { + archive << framesX; + archive << framesY; + archive << frameCount; + archive << frameStart; + } + } + } + + namespace HairParticleSystem_Internal + { + void LoadShaders() + { + wi::renderer::LoadShader(ShaderStage::VS, vs, "hairparticleVS.cso"); + + wi::renderer::LoadShader(ShaderStage::PS, ps_simple, "hairparticlePS_simple.cso"); + wi::renderer::LoadShader(ShaderStage::PS, ps_prepass, "hairparticlePS_prepass.cso"); + wi::renderer::LoadShader(ShaderStage::PS, ps, "hairparticlePS.cso"); + + wi::renderer::LoadShader(ShaderStage::CS, cs_simulate, "hairparticle_simulateCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, cs_finishUpdate, "hairparticle_finishUpdateCS.cso"); + + GraphicsDevice* device = wi::graphics::GetDevice(); + + for (int i = 0; i < RENDERPASS_COUNT; ++i) + { + if (i == RENDERPASS_PREPASS || i == RENDERPASS_MAIN) + { + PipelineStateDesc desc; + desc.vs = &vs; + desc.bs = &bs; + desc.rs = &ncrs; + desc.dss = &dss_default; + desc.pt = PrimitiveTopology::TRIANGLELIST; + + switch (i) + { + case RENDERPASS_PREPASS: + desc.ps = &ps_prepass; + break; + case RENDERPASS_MAIN: + desc.ps = &ps; + desc.dss = &dss_equal; + break; + } + + device->CreatePipelineState(&desc, &PSO[i]); + } + } + + { + PipelineStateDesc desc; + desc.vs = &vs; + desc.ps = &ps_simple; + desc.bs = &bs; + desc.rs = &wirers; + desc.dss = &dss_default; + desc.pt = PrimitiveTopology::TRIANGLELIST; + device->CreatePipelineState(&desc, &PSO_wire); + } + } + } + + void HairParticleSystem::Initialize() + { + wi::Timer timer; + + RasterizerState rsd; + rsd.fill_mode = FillMode::SOLID; + rsd.cull_mode = CullMode::BACK; + rsd.front_counter_clockwise = true; + rsd.depth_bias = 0; + rsd.depth_bias_clamp = 0; + rsd.slope_scaled_depth_bias = 0; + rsd.depth_clip_enable = true; + rsd.multisample_enable = false; + rsd.antialiased_line_enable = false; + rs = rsd; + + rsd.fill_mode = FillMode::SOLID; + rsd.cull_mode = CullMode::NONE; + rsd.front_counter_clockwise = true; + rsd.depth_bias = 0; + rsd.depth_bias_clamp = 0; + rsd.slope_scaled_depth_bias = 0; + rsd.depth_clip_enable = true; + rsd.multisample_enable = false; + rsd.antialiased_line_enable = false; + ncrs = rsd; + + rsd.fill_mode = FillMode::WIREFRAME; + rsd.cull_mode = CullMode::NONE; + rsd.front_counter_clockwise = true; + rsd.depth_bias = 0; + rsd.depth_bias_clamp = 0; + rsd.slope_scaled_depth_bias = 0; + rsd.depth_clip_enable = true; + rsd.multisample_enable = false; + rsd.antialiased_line_enable = false; + wirers = rsd; + + + DepthStencilState dsd; + dsd.depth_enable = true; + dsd.depth_write_mask = DepthWriteMask::ALL; + dsd.depth_func = ComparisonFunc::GREATER; + + dsd.stencil_enable = true; + dsd.stencil_read_mask = 0xFF; + dsd.stencil_write_mask = 0xFF; + dsd.front_face.stencil_func = ComparisonFunc::ALWAYS; + dsd.front_face.stencil_pass_op = StencilOp::REPLACE; + dsd.front_face.stencil_fail_op = StencilOp::KEEP; + dsd.front_face.stencil_depth_fail_op = StencilOp::KEEP; + dsd.back_face.stencil_func = ComparisonFunc::ALWAYS; + dsd.back_face.stencil_pass_op = StencilOp::REPLACE; + dsd.back_face.stencil_fail_op = StencilOp::KEEP; + dsd.back_face.stencil_depth_fail_op = StencilOp::KEEP; + dss_default = dsd; + + dsd.depth_write_mask = DepthWriteMask::ZERO; + dsd.depth_func = ComparisonFunc::EQUAL; + dsd.stencil_enable = false; + dss_equal = dsd; + + + BlendState bld; + bld.render_target[0].blend_enable = false; + bld.alpha_to_coverage_enable = false; + bs = bld; + + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { HairParticleSystem_Internal::LoadShaders(); }); + HairParticleSystem_Internal::LoadShaders(); + + wi::backlog::post("wi::HairParticleSystem Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } } - -void wiHairParticle::Initialize() -{ - wiTimer timer; - - RasterizerState rsd; - rsd.fill_mode = FillMode::SOLID; - rsd.cull_mode = CullMode::BACK; - rsd.front_counter_clockwise = true; - rsd.depth_bias = 0; - rsd.depth_bias_clamp = 0; - rsd.slope_scaled_depth_bias = 0; - rsd.depth_clip_enable = true; - rsd.multisample_enable = false; - rsd.antialiased_line_enable = false; - rs = rsd; - - rsd.fill_mode = FillMode::SOLID; - rsd.cull_mode = CullMode::NONE; - rsd.front_counter_clockwise = true; - rsd.depth_bias = 0; - rsd.depth_bias_clamp = 0; - rsd.slope_scaled_depth_bias = 0; - rsd.depth_clip_enable = true; - rsd.multisample_enable = false; - rsd.antialiased_line_enable = false; - ncrs = rsd; - - rsd.fill_mode = FillMode::WIREFRAME; - rsd.cull_mode = CullMode::NONE; - rsd.front_counter_clockwise = true; - rsd.depth_bias = 0; - rsd.depth_bias_clamp = 0; - rsd.slope_scaled_depth_bias = 0; - rsd.depth_clip_enable = true; - rsd.multisample_enable = false; - rsd.antialiased_line_enable = false; - wirers = rsd; - - - DepthStencilState dsd; - dsd.depth_enable = true; - dsd.depth_write_mask = DepthWriteMask::ALL; - dsd.depth_func = ComparisonFunc::GREATER; - - dsd.stencil_enable = true; - dsd.stencil_read_mask = 0xFF; - dsd.stencil_write_mask = 0xFF; - dsd.front_face.stencil_func = ComparisonFunc::ALWAYS; - dsd.front_face.stencil_pass_op = StencilOp::REPLACE; - dsd.front_face.stencil_fail_op = StencilOp::KEEP; - dsd.front_face.stencil_depth_fail_op = StencilOp::KEEP; - dsd.back_face.stencil_func = ComparisonFunc::ALWAYS; - dsd.back_face.stencil_pass_op = StencilOp::REPLACE; - dsd.back_face.stencil_fail_op = StencilOp::KEEP; - dsd.back_face.stencil_depth_fail_op = StencilOp::KEEP; - dss_default = dsd; - - dsd.depth_write_mask = DepthWriteMask::ZERO; - dsd.depth_func = ComparisonFunc::EQUAL; - dsd.stencil_enable = false; - dss_equal = dsd; - - - BlendState bld; - bld.render_target[0].blend_enable = false; - bld.alpha_to_coverage_enable = false; // maybe for msaa - bs = bld; - - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiHairParticle_Internal::LoadShaders(); }); - wiHairParticle_Internal::LoadShaders(); - - wiBackLog::post("wiHairParticle Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); -} - -} diff --git a/WickedEngine/wiHairParticle.h b/WickedEngine/wiHairParticle.h index 96da168dc..985385b5c 100644 --- a/WickedEngine/wiHairParticle.h +++ b/WickedEngine/wiHairParticle.h @@ -4,74 +4,89 @@ #include "wiEnums.h" #include "wiMath.h" #include "wiECS.h" -#include "wiScene_Decl.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiVector.h" +#include "wiScene_Decl.h" #include -class wiArchive; - -namespace wiScene +namespace wi { - -class wiHairParticle -{ -public: - wiGraphics::GPUBuffer constantBuffer; - wiGraphics::GPUBuffer simulationBuffer; - wiGraphics::GPUBuffer vertexBuffer_POS[2]; - wiGraphics::GPUBuffer vertexBuffer_TEX; - wiGraphics::GPUBuffer primitiveBuffer; - wiGraphics::GPUBuffer culledIndexBuffer; - wiGraphics::GPUBuffer indirectBuffer; - wiGraphics::GPUBuffer subsetBuffer; - - wiGraphics::GPUBuffer indexBuffer; - wiGraphics::GPUBuffer vertexBuffer_length; - - wiGraphics::RaytracingAccelerationStructure BLAS; - - void UpdateCPU(const TransformComponent& transform, const MeshComponent& mesh, float dt); - void UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const MeshComponent& mesh, const MaterialComponent& material, wiGraphics::CommandList cmd) const; - void Draw(const MaterialComponent& material, RENDERPASS renderPass, wiGraphics::CommandList cmd) const; - - enum FLAGS - { - EMPTY = 0, - _DEPRECATED_REGENERATE_FRAME = 1 << 0, - REBUILD_BUFFERS = 1 << 1, - }; - uint32_t _flags = EMPTY; - - wiECS::Entity meshID = wiECS::INVALID_ENTITY; - - uint32_t strandCount = 0; - uint32_t segmentCount = 1; - uint32_t randomSeed = 1; - float length = 1.0f; - float stiffness = 10.0f; - float randomness = 0.2f; - float viewDistance = 200; - wi::vector vertex_lengths; - - // Sprite sheet properties: - uint32_t framesX = 1; - uint32_t framesY = 1; - uint32_t frameCount = 1; - uint32_t frameStart = 0; - - // Non-serialized attributes: - XMFLOAT4X4 world; - XMFLOAT4X4 worldPrev; - AABB aabb; - wi::vector indices; // it is dependent on vertex_lengths and contains triangles with non-zero lengths - uint32_t layerMask = ~0u; - mutable bool regenerate_frame = true; - - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); - - static void Initialize(); -}; - + class Archive; +} + +namespace wi +{ + class HairParticleSystem + { + public: + wi::graphics::GPUBuffer constantBuffer; + wi::graphics::GPUBuffer simulationBuffer; + wi::graphics::GPUBuffer vertexBuffer_POS[2]; + wi::graphics::GPUBuffer vertexBuffer_TEX; + wi::graphics::GPUBuffer primitiveBuffer; + wi::graphics::GPUBuffer culledIndexBuffer; + wi::graphics::GPUBuffer indirectBuffer; + wi::graphics::GPUBuffer subsetBuffer; + + wi::graphics::GPUBuffer indexBuffer; + wi::graphics::GPUBuffer vertexBuffer_length; + + wi::graphics::RaytracingAccelerationStructure BLAS; + + void UpdateCPU( + const wi::scene::TransformComponent& transform, + const wi::scene::MeshComponent& mesh, + float dt + ); + void UpdateGPU( + uint32_t instanceIndex, + uint32_t materialIndex, + const wi::scene::MeshComponent& mesh, + const wi::scene::MaterialComponent& material, + wi::graphics::CommandList cmd + ) const; + void Draw( + const wi::scene::MaterialComponent& material, + wi::enums::RENDERPASS renderPass, + wi::graphics::CommandList cmd + ) const; + + enum FLAGS + { + EMPTY = 0, + _DEPRECATED_REGENERATE_FRAME = 1 << 0, + REBUILD_BUFFERS = 1 << 1, + }; + uint32_t _flags = EMPTY; + + wi::ecs::Entity meshID = wi::ecs::INVALID_ENTITY; + + uint32_t strandCount = 0; + uint32_t segmentCount = 1; + uint32_t randomSeed = 1; + float length = 1.0f; + float stiffness = 10.0f; + float randomness = 0.2f; + float viewDistance = 200; + wi::vector vertex_lengths; + + // Sprite sheet properties: + uint32_t framesX = 1; + uint32_t framesY = 1; + uint32_t frameCount = 1; + uint32_t frameStart = 0; + + // Non-serialized attributes: + XMFLOAT4X4 world; + XMFLOAT4X4 worldPrev; + wi::primitive::AABB aabb; + wi::vector indices; // it is dependent on vertex_lengths and contains triangles with non-zero lengths + uint32_t layerMask = ~0u; + mutable bool regenerate_frame = true; + + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); + + static void Initialize(); + }; } diff --git a/WickedEngine/wiHelper.cpp b/WickedEngine/wiHelper.cpp index 1b277821d..f1ac9ef33 100644 --- a/WickedEngine/wiHelper.cpp +++ b/WickedEngine/wiHelper.cpp @@ -1,7 +1,7 @@ #include "wiHelper.h" #include "wiPlatform.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiMath.h" #include "Utility/stb_image_write.h" @@ -37,7 +37,7 @@ extern basist::etc1_global_selector_codebook g_basis_global_codebook; #endif // _WIN32 -namespace wiHelper +namespace wi::helper { std::string toUpper(const std::string& s) @@ -61,7 +61,7 @@ namespace wiHelper StringConvert(msg, wmessage); StringConvert(caption, wcaption); // UWP can only show message box on main thread: - wiEvent::Subscribe_Once(SYSTEM_EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { + wi::eventhandler::Subscribe_Once(wi::eventhandler::EVENT_THREAD_SAFE_POINT, [=](uint64_t userdata) { winrt::Windows::UI::Popups::MessageDialog(wmessage, wcaption).ShowAsync(); }); #endif // PLATFORM_UWP @@ -70,7 +70,7 @@ namespace wiHelper #endif // _WIN32 } - void screenshot(const wiGraphics::SwapChain& swapchain, const std::string& name) + void screenshot(const wi::graphics::SwapChain& swapchain, const std::string& name) { std::string directory; if (name.empty()) @@ -90,20 +90,20 @@ namespace wiHelper filename = directory + "/sc_" + getCurrentDateTimeAsString() + ".jpg"; } - bool result = saveTextureToFile(wiGraphics::GetDevice()->GetBackBuffer(&swapchain), filename); + bool result = saveTextureToFile(wi::graphics::GetDevice()->GetBackBuffer(&swapchain), filename); assert(result); if (result) { - wiBackLog::post("Screenshot saved: " + filename); + wi::backlog::post("Screenshot saved: " + filename); } } - bool saveTextureToMemory(const wiGraphics::Texture& texture, wi::vector& texturedata) + bool saveTextureToMemory(const wi::graphics::Texture& texture, wi::vector& texturedata) { - using namespace wiGraphics; + using namespace wi::graphics; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); TextureDesc desc = texture.GetDesc(); @@ -174,9 +174,9 @@ namespace wiHelper return stagingTex.mapped_data != nullptr; } - bool saveTextureToMemoryFile(const wiGraphics::Texture& texture, const std::string& fileExtension, wi::vector& filedata) + bool saveTextureToMemoryFile(const wi::graphics::Texture& texture, const std::string& fileExtension, wi::vector& filedata) { - using namespace wiGraphics; + using namespace wi::graphics; TextureDesc desc = texture.GetDesc(); wi::vector texturedata; if (saveTextureToMemory(texture, texturedata)) @@ -186,12 +186,12 @@ namespace wiHelper return false; } - bool saveTextureToMemoryFile(const wi::vector& texturedata, const wiGraphics::TextureDesc& desc, const std::string& fileExtension, wi::vector& filedata) + bool saveTextureToMemoryFile(const wi::vector& texturedata, const wi::graphics::TextureDesc& desc, const std::string& fileExtension, wi::vector& filedata) { - using namespace wiGraphics; + using namespace wi::graphics; uint32_t data_count = desc.width * desc.height; - std::string extension = wiHelper::toUpper(fileExtension); + std::string extension = wi::helper::toUpper(fileExtension); bool basis = !extension.compare("BASIS"); bool ktx2 = !extension.compare("KTX2"); basisu::image basis_image; @@ -421,9 +421,9 @@ namespace wiHelper return write_result != 0; } - bool saveTextureToFile(const wiGraphics::Texture& texture, const std::string& fileName) + bool saveTextureToFile(const wi::graphics::Texture& texture, const std::string& fileName) { - using namespace wiGraphics; + using namespace wi::graphics; TextureDesc desc = texture.GetDesc(); wi::vector data; if (saveTextureToMemory(texture, data)) @@ -433,9 +433,9 @@ namespace wiHelper return false; } - bool saveTextureToFile(const wi::vector& texturedata, const wiGraphics::TextureDesc& desc, const std::string& fileName) + bool saveTextureToFile(const wi::vector& texturedata, const wi::graphics::TextureDesc& desc, const std::string& fileName) { - using namespace wiGraphics; + using namespace wi::graphics; std::string ext = GetExtensionFromFileName(fileName); wi::vector filedata; @@ -616,7 +616,7 @@ namespace wiHelper switch (ex.code()) { case E_ACCESSDENIED: - wiBackLog::post("Opening file failed: " + fileName + " | Reason: Permission Denied!"); + wi::backlog::post("Opening file failed: " + fileName + " | Reason: Permission Denied!"); break; default: break; @@ -641,7 +641,7 @@ namespace wiHelper #endif // PLATFORM_UWP - wiBackLog::post("File not found: " + fileName); + wi::backlog::post("File not found: " + fileName); return false; } @@ -691,7 +691,7 @@ namespace wiHelper switch (ex.code()) { case E_ACCESSDENIED: - wiBackLog::post("Opening file failed: " + fileName + " | Reason: Permission Denied!"); + wi::backlog::post("Opening file failed: " + fileName + " | Reason: Permission Denied!"); break; default: break; diff --git a/WickedEngine/wiHelper.h b/WickedEngine/wiHelper.h index a4fea7b90..66f91f58b 100644 --- a/WickedEngine/wiHelper.h +++ b/WickedEngine/wiHelper.h @@ -6,7 +6,7 @@ #include #include -namespace wiHelper +namespace wi::helper { template constexpr void hash_combine(std::size_t& seed, const T& v) @@ -35,22 +35,22 @@ namespace wiHelper void messageBox(const std::string& msg, const std::string& caption = "Warning!"); - void screenshot(const wiGraphics::SwapChain& swapchain, const std::string& name = ""); + void screenshot(const wi::graphics::SwapChain& swapchain, const std::string& name = ""); // Save raw pixel data from the texture to memory - bool saveTextureToMemory(const wiGraphics::Texture& texture, wi::vector& texturedata); + bool saveTextureToMemory(const wi::graphics::Texture& texture, wi::vector& texturedata); // Save texture to memory as a file format - bool saveTextureToMemoryFile(const wiGraphics::Texture& texture, const std::string& fileExtension, wi::vector& filedata); + bool saveTextureToMemoryFile(const wi::graphics::Texture& texture, const std::string& fileExtension, wi::vector& filedata); // Save raw texture data to memory as file format - bool saveTextureToMemoryFile(const wi::vector& textureData, const wiGraphics::TextureDesc& desc, const std::string& fileExtension, wi::vector& filedata); + bool saveTextureToMemoryFile(const wi::vector& textureData, const wi::graphics::TextureDesc& desc, const std::string& fileExtension, wi::vector& filedata); // Save texture to file format - bool saveTextureToFile(const wiGraphics::Texture& texture, const std::string& fileName); + bool saveTextureToFile(const wi::graphics::Texture& texture, const std::string& fileName); // Save raw texture data to file format - bool saveTextureToFile(const wi::vector& texturedata, const wiGraphics::TextureDesc& desc, const std::string& fileName); + bool saveTextureToFile(const wi::vector& texturedata, const wi::graphics::TextureDesc& desc, const std::string& fileName); std::string getCurrentDateTimeAsString(); diff --git a/WickedEngine/wiImage.cpp b/WickedEngine/wiImage.cpp index aaca32ba9..312243643 100644 --- a/WickedEngine/wiImage.cpp +++ b/WickedEngine/wiImage.cpp @@ -3,17 +3,17 @@ #include "wiRenderer.h" #include "wiHelper.h" #include "shaders/ShaderInterop_Image.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiTimer.h" #include -using namespace wiGraphics; +using namespace wi::graphics; +using namespace wi::enums; -namespace wiImage +namespace wi::image { - enum IMAGE_SHADER { IMAGE_SHADER_STANDARD, @@ -29,7 +29,7 @@ namespace wiImage DepthStencilState depthStencilStates[STENCILMODE_COUNT][STENCILREFMODE_COUNT]; PipelineState imagePSO[IMAGE_SHADER_COUNT][BLENDMODE_COUNT][STENCILMODE_COUNT][STENCILREFMODE_COUNT]; Texture backgroundTextures[COMMANDLIST_COUNT]; - wiCanvas canvases[COMMANDLIST_COUNT]; + wi::Canvas canvases[COMMANDLIST_COUNT]; std::atomic_bool initialized{ false }; @@ -38,56 +38,56 @@ namespace wiImage backgroundTextures[cmd] = texture; } - void SetCanvas(const wiCanvas& canvas, wiGraphics::CommandList cmd) + void SetCanvas(const wi::Canvas& canvas, wi::graphics::CommandList cmd) { canvases[cmd] = canvas; } - void Draw(const Texture* texture, const wiImageParams& params, CommandList cmd) + void Draw(const Texture* texture, const Params& params, CommandList cmd) { if (!initialized.load()) { return; } - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("Image", cmd); uint32_t stencilRef = params.stencilRef; if (params.stencilRefMode == STENCILREFMODE_USER) { - stencilRef = wiRenderer::CombineStencilrefs(STENCILREF_EMPTY, (uint8_t)stencilRef); + stencilRef = wi::renderer::CombineStencilrefs(STENCILREF_EMPTY, (uint8_t)stencilRef); } device->BindStencilRef(stencilRef, cmd); - const Sampler* sampler = wiRenderer::GetSampler(SAMPLER_LINEAR_CLAMP); + const Sampler* sampler = wi::renderer::GetSampler(SAMPLER_LINEAR_CLAMP); if (params.quality == QUALITY_NEAREST) { if (params.sampleFlag == SAMPLEMODE_MIRROR) - sampler = wiRenderer::GetSampler(SAMPLER_POINT_MIRROR); + sampler = wi::renderer::GetSampler(SAMPLER_POINT_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) - sampler = wiRenderer::GetSampler(SAMPLER_POINT_WRAP); + sampler = wi::renderer::GetSampler(SAMPLER_POINT_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) - sampler = wiRenderer::GetSampler(SAMPLER_POINT_CLAMP); + sampler = wi::renderer::GetSampler(SAMPLER_POINT_CLAMP); } else if (params.quality == QUALITY_LINEAR) { if (params.sampleFlag == SAMPLEMODE_MIRROR) - sampler = wiRenderer::GetSampler(SAMPLER_LINEAR_MIRROR); + sampler = wi::renderer::GetSampler(SAMPLER_LINEAR_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) - sampler = wiRenderer::GetSampler(SAMPLER_LINEAR_WRAP); + sampler = wi::renderer::GetSampler(SAMPLER_LINEAR_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) - sampler = wiRenderer::GetSampler(SAMPLER_LINEAR_CLAMP); + sampler = wi::renderer::GetSampler(SAMPLER_LINEAR_CLAMP); } else if (params.quality == QUALITY_ANISOTROPIC) { if (params.sampleFlag == SAMPLEMODE_MIRROR) - sampler = wiRenderer::GetSampler(SAMPLER_ANISO_MIRROR); + sampler = wi::renderer::GetSampler(SAMPLER_ANISO_MIRROR); else if (params.sampleFlag == SAMPLEMODE_WRAP) - sampler = wiRenderer::GetSampler(SAMPLER_ANISO_WRAP); + sampler = wi::renderer::GetSampler(SAMPLER_ANISO_WRAP); else if (params.sampleFlag == SAMPLEMODE_CLAMP) - sampler = wiRenderer::GetSampler(SAMPLER_ANISO_CLAMP); + sampler = wi::renderer::GetSampler(SAMPLER_ANISO_CLAMP); } PushConstantsImage push; @@ -163,8 +163,8 @@ namespace wiImage } else { - const wiCanvas& canvas = canvases[cmd]; - // Asserts will check that a proper canvas was set for this cmd with wiImage::SetCanvas() + const wi::Canvas& canvas = canvases[cmd]; + // Asserts will check that a proper canvas was set for this cmd with wi::image::SetCanvas() // The canvas must be set to have dpi aware rendering assert(canvas.width > 0); assert(canvas.height > 0); @@ -254,14 +254,14 @@ namespace wiImage void LoadShaders() { - wiRenderer::LoadShader(ShaderStage::VS, vertexShader, "imageVS.cso"); - wiRenderer::LoadShader(ShaderStage::VS, screenVS, "screenVS.cso"); + wi::renderer::LoadShader(ShaderStage::VS, vertexShader, "imageVS.cso"); + wi::renderer::LoadShader(ShaderStage::VS, screenVS, "screenVS.cso"); - wiRenderer::LoadShader(ShaderStage::PS, imagePS[IMAGE_SHADER_STANDARD], "imagePS.cso"); - wiRenderer::LoadShader(ShaderStage::PS, imagePS[IMAGE_SHADER_FULLSCREEN], "screenPS.cso"); + wi::renderer::LoadShader(ShaderStage::PS, imagePS[IMAGE_SHADER_STANDARD], "imagePS.cso"); + wi::renderer::LoadShader(ShaderStage::PS, imagePS[IMAGE_SHADER_FULLSCREEN], "screenPS.cso"); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); for (int i = 0; i < IMAGE_SHADER_COUNT; ++i) { @@ -297,9 +297,9 @@ namespace wiImage void Initialize() { - wiTimer timer; + wi::Timer timer; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); RasterizerState rs; rs.fill_mode = FillMode::SOLID; @@ -424,10 +424,10 @@ namespace wiImage bd.independent_blend_enable = false; blendStates[BLENDMODE_MULTIPLY] = bd; - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); LoadShaders(); - wiBackLog::post("wiImage Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::image Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); initialized.store(true); } diff --git a/WickedEngine/wiImage.h b/WickedEngine/wiImage.h index 66aede72f..52d25d7d8 100644 --- a/WickedEngine/wiImage.h +++ b/WickedEngine/wiImage.h @@ -5,154 +5,154 @@ #include "wiColor.h" #include "wiCanvas.h" -struct wiImageParams; - -namespace wiImage +namespace wi::image { + // Do not alter order or value because it is bound to lua manually! + enum STENCILMODE + { + STENCILMODE_DISABLED, + STENCILMODE_EQUAL, + STENCILMODE_LESS, + STENCILMODE_LESSEQUAL, + STENCILMODE_GREATER, + STENCILMODE_GREATEREQUAL, + STENCILMODE_NOT, + STENCILMODE_ALWAYS, + STENCILMODE_COUNT + }; + enum STENCILREFMODE + { + STENCILREFMODE_ENGINE, + STENCILREFMODE_USER, + STENCILREFMODE_ALL, + STENCILREFMODE_COUNT + }; + enum SAMPLEMODE + { + SAMPLEMODE_CLAMP, + SAMPLEMODE_WRAP, + SAMPLEMODE_MIRROR, + SAMPLEMODE_COUNT + }; + enum QUALITY + { + QUALITY_NEAREST, + QUALITY_LINEAR, + QUALITY_ANISOTROPIC, + QUALITY_COUNT + }; + + struct Params + { + enum FLAGS + { + EMPTY = 0, + DRAWRECT = 1 << 0, + DRAWRECT2 = 1 << 1, + MIRROR = 1 << 2, + EXTRACT_NORMALMAP = 1 << 3, + FULLSCREEN = 1 << 4, + BACKGROUND = 1 << 5, + OUTPUT_COLOR_SPACE_HDR10_ST2084 = 1 << 6, + OUTPUT_COLOR_SPACE_LINEAR = 1 << 7, + }; + uint32_t _flags = EMPTY; + + XMFLOAT3 pos = XMFLOAT3(0, 0, 0); + XMFLOAT2 siz = XMFLOAT2(1, 1); + XMFLOAT2 scale = XMFLOAT2(1, 1); + XMFLOAT4 color = XMFLOAT4(1, 1, 1, 1); + XMFLOAT4 drawRect = XMFLOAT4(0, 0, 0, 0); + XMFLOAT4 drawRect2 = XMFLOAT4(0, 0, 0, 0); + XMFLOAT2 texOffset = XMFLOAT2(0, 0); + XMFLOAT2 texOffset2 = XMFLOAT2(0, 0); + XMFLOAT2 pivot = XMFLOAT2(0, 0); // (0,0) : upperleft, (0.5,0.5) : center, (1,1) : bottomright + float rotation = 0; + float fade = 0; + float opacity = 1; + float hdr_scaling = 1.0f; + + // you can deform the image by its corners (0: top left, 1: top right, 2: bottom left, 3: bottom right) + XMFLOAT2 corners[4] = { + XMFLOAT2(0, 0), XMFLOAT2(1, 0), + XMFLOAT2(0, 1), XMFLOAT2(1, 1) + }; + const XMMATRIX* customRotation = nullptr; + const XMMATRIX* customProjection = nullptr; + + uint8_t stencilRef = 0; + STENCILMODE stencilComp = STENCILMODE_DISABLED; + STENCILREFMODE stencilRefMode = STENCILREFMODE_ALL; + wi::enums::BLENDMODE blendFlag = wi::enums::BLENDMODE_ALPHA; + SAMPLEMODE sampleFlag = SAMPLEMODE_MIRROR; + QUALITY quality = QUALITY_LINEAR; + + const wi::graphics::Texture* maskMap = nullptr; + // Generic texture + constexpr void setMaskMap(const wi::graphics::Texture* tex) { maskMap = tex; } + + constexpr bool isDrawRectEnabled() const { return _flags & DRAWRECT; } + constexpr bool isDrawRect2Enabled() const { return _flags & DRAWRECT2; } + constexpr bool isMirrorEnabled() const { return _flags & MIRROR; } + constexpr bool isExtractNormalMapEnabled() const { return _flags & EXTRACT_NORMALMAP; } + constexpr bool isFullScreenEnabled() const { return _flags & FULLSCREEN; } + constexpr bool isBackgroundEnabled() const { return _flags & BACKGROUND; } + constexpr bool isHDR10OutputMappingEnabled() const { return _flags & OUTPUT_COLOR_SPACE_HDR10_ST2084; } + constexpr bool isLinearOutputMappingEnabled() const { return _flags & OUTPUT_COLOR_SPACE_LINEAR; } + + // enables draw rectangle for base texture (cutout texture outside draw rectangle) + constexpr void enableDrawRect(const XMFLOAT4& rect) { _flags |= DRAWRECT; drawRect = rect; } + // enables draw rectangle for mask texture (cutout texture outside draw rectangle) + constexpr void enableDrawRect2(const XMFLOAT4& rect) { _flags |= DRAWRECT2; drawRect2 = rect; } + // mirror the image horizontally + constexpr void enableMirror() { _flags |= MIRROR; } + // enable normal map extraction shader that will perform texcolor * 2 - 1 (preferably onto a signed render target) + constexpr void enableExtractNormalMap() { _flags |= EXTRACT_NORMALMAP; } + // enable full screen override. It just draws texture onto the full screen, disabling any other setup except sampler and stencil) + constexpr void enableFullScreen() { _flags |= FULLSCREEN; } + // enable background blur, which samples a background screen texture on a specified mip level on transparent areas instead of alpha blending + // the background tex should be bound with wi::image::SetBackground() beforehand + constexpr void enableBackground() { _flags |= BACKGROUND; } + // enable HDR10 output mapping, if this image can be interpreted in linear space and converted to HDR10 display format + // this only works together with the enableFullScreen() override! + constexpr void enableHDR10OutputMapping() { _flags |= OUTPUT_COLOR_SPACE_HDR10_ST2084; } + // enable linear output mapping, which means removing gamma curve and outputting in linear space (useful for blending in HDR space) + // this only works together with the enableFullScreen() override! + constexpr void enableLinearOutputMapping(float scaling = 1.0f) { _flags |= OUTPUT_COLOR_SPACE_LINEAR; hdr_scaling = scaling; } + + // disable draw rectangle for base texture (whole texture will be drawn, no cutout) + constexpr void disableDrawRect() { _flags &= ~DRAWRECT; } + // disable draw rectangle for mask texture (whole texture will be drawn, no cutout) + constexpr void disableDrawRect2() { _flags &= ~DRAWRECT2; } + constexpr void disableMirror() { _flags &= ~MIRROR; } + constexpr void disableExtractNormalMap() { _flags &= ~EXTRACT_NORMALMAP; } + constexpr void disableFullScreen() { _flags &= ~FULLSCREEN; } + constexpr void disableBackground() { _flags &= ~BACKGROUND; } + constexpr void disableHDR10OutputMapping() { _flags &= ~OUTPUT_COLOR_SPACE_HDR10_ST2084; } + constexpr void disableLinearOutputMapping() { _flags &= ~OUTPUT_COLOR_SPACE_LINEAR; } + + Params() = default; + Params(float width, float height) : + siz(width, height) + {} + Params(float posX, float posY, float width, float height, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)) : + pos(posX, posY, 0), + siz(width, height), + color(color) + {} + }; + + // Set canvas to handle DPI-aware image rendering (applied to all image rendering commands on this CommandList) - void SetCanvas(const wiCanvas& canvas, wiGraphics::CommandList cmd); + void SetCanvas(const wi::Canvas& canvas, wi::graphics::CommandList cmd); // Set a background texture (applied to all image rendering commands on this CommandList that used enableBackground()) - void SetBackground(const wiGraphics::Texture& texture, wiGraphics::CommandList cmd); + void SetBackground(const wi::graphics::Texture& texture, wi::graphics::CommandList cmd); // Draw the specified texture with the specified parameters - void Draw(const wiGraphics::Texture* texture, const wiImageParams& params, wiGraphics::CommandList cmd); + void Draw(const wi::graphics::Texture* texture, const Params& params, wi::graphics::CommandList cmd); // Initializes the image renderer void Initialize(); -}; -// Do not alter order or value because it is bound to lua manually! -enum STENCILMODE -{ - STENCILMODE_DISABLED, - STENCILMODE_EQUAL, - STENCILMODE_LESS, - STENCILMODE_LESSEQUAL, - STENCILMODE_GREATER, - STENCILMODE_GREATEREQUAL, - STENCILMODE_NOT, - STENCILMODE_ALWAYS, - STENCILMODE_COUNT -}; -enum STENCILREFMODE -{ - STENCILREFMODE_ENGINE, - STENCILREFMODE_USER, - STENCILREFMODE_ALL, - STENCILREFMODE_COUNT -}; -enum SAMPLEMODE -{ - SAMPLEMODE_CLAMP, - SAMPLEMODE_WRAP, - SAMPLEMODE_MIRROR, - SAMPLEMODE_COUNT -}; -enum QUALITY -{ - QUALITY_NEAREST, - QUALITY_LINEAR, - QUALITY_ANISOTROPIC, - QUALITY_COUNT -}; - -struct wiImageParams -{ - enum FLAGS - { - EMPTY = 0, - DRAWRECT = 1 << 0, - DRAWRECT2 = 1 << 1, - MIRROR = 1 << 2, - EXTRACT_NORMALMAP = 1 << 3, - FULLSCREEN = 1 << 4, - BACKGROUND = 1 << 5, - OUTPUT_COLOR_SPACE_HDR10_ST2084 = 1 << 6, - OUTPUT_COLOR_SPACE_LINEAR = 1 << 7, - }; - uint32_t _flags = EMPTY; - - XMFLOAT3 pos = XMFLOAT3(0, 0, 0); - XMFLOAT2 siz = XMFLOAT2(1, 1); - XMFLOAT2 scale = XMFLOAT2(1, 1); - XMFLOAT4 color = XMFLOAT4(1, 1, 1, 1); - XMFLOAT4 drawRect = XMFLOAT4(0, 0, 0, 0); - XMFLOAT4 drawRect2 = XMFLOAT4(0, 0, 0, 0); - XMFLOAT2 texOffset = XMFLOAT2(0, 0); - XMFLOAT2 texOffset2 = XMFLOAT2(0, 0); - XMFLOAT2 pivot = XMFLOAT2(0, 0); // (0,0) : upperleft, (0.5,0.5) : center, (1,1) : bottomright - float rotation = 0; - float fade = 0; - float opacity = 1; - float hdr_scaling = 1.0f; - - // you can deform the image by its corners (0: top left, 1: top right, 2: bottom left, 3: bottom right) - XMFLOAT2 corners[4] = { - XMFLOAT2(0, 0), XMFLOAT2(1, 0), - XMFLOAT2(0, 1), XMFLOAT2(1, 1) - }; - const XMMATRIX* customRotation = nullptr; - const XMMATRIX* customProjection = nullptr; - - uint8_t stencilRef = 0; - STENCILMODE stencilComp = STENCILMODE_DISABLED; - STENCILREFMODE stencilRefMode = STENCILREFMODE_ALL; - BLENDMODE blendFlag = BLENDMODE_ALPHA; - SAMPLEMODE sampleFlag = SAMPLEMODE_MIRROR; - QUALITY quality = QUALITY_LINEAR; - - const wiGraphics::Texture* maskMap = nullptr; - // Generic texture - constexpr void setMaskMap(const wiGraphics::Texture* tex) { maskMap = tex; } - - constexpr bool isDrawRectEnabled() const { return _flags & DRAWRECT; } - constexpr bool isDrawRect2Enabled() const { return _flags & DRAWRECT2; } - constexpr bool isMirrorEnabled() const { return _flags & MIRROR; } - constexpr bool isExtractNormalMapEnabled() const { return _flags & EXTRACT_NORMALMAP; } - constexpr bool isFullScreenEnabled() const { return _flags & FULLSCREEN; } - constexpr bool isBackgroundEnabled() const { return _flags & BACKGROUND; } - constexpr bool isHDR10OutputMappingEnabled() const { return _flags & OUTPUT_COLOR_SPACE_HDR10_ST2084; } - constexpr bool isLinearOutputMappingEnabled() const { return _flags & OUTPUT_COLOR_SPACE_LINEAR; } - - // enables draw rectangle for base texture (cutout texture outside draw rectangle) - constexpr void enableDrawRect(const XMFLOAT4& rect) { _flags |= DRAWRECT; drawRect = rect; } - // enables draw rectangle for mask texture (cutout texture outside draw rectangle) - constexpr void enableDrawRect2(const XMFLOAT4& rect) { _flags |= DRAWRECT2; drawRect2 = rect; } - // mirror the image horizontally - constexpr void enableMirror() { _flags |= MIRROR; } - // enable normal map extraction shader that will perform texcolor * 2 - 1 (preferably onto a signed render target) - constexpr void enableExtractNormalMap() { _flags |= EXTRACT_NORMALMAP; } - // enable full screen override. It just draws texture onto the full screen, disabling any other setup except sampler and stencil) - constexpr void enableFullScreen() { _flags |= FULLSCREEN; } - // enable background blur, which samples a background screen texture on a specified mip level on transparent areas instead of alpha blending - // the background tex should be bound with wiImage::SetBackground() beforehand - constexpr void enableBackground() { _flags |= BACKGROUND; } - // enable HDR10 output mapping, if this image can be interpreted in linear space and converted to HDR10 display format - // this only works together with the enableFullScreen() override! - constexpr void enableHDR10OutputMapping() { _flags |= OUTPUT_COLOR_SPACE_HDR10_ST2084; } - // enable linear output mapping, which means removing gamma curve and outputting in linear space (useful for blending in HDR space) - // this only works together with the enableFullScreen() override! - constexpr void enableLinearOutputMapping(float scaling = 1.0f) { _flags |= OUTPUT_COLOR_SPACE_LINEAR; hdr_scaling = scaling; } - - // disable draw rectangle for base texture (whole texture will be drawn, no cutout) - constexpr void disableDrawRect() { _flags &= ~DRAWRECT; } - // disable draw rectangle for mask texture (whole texture will be drawn, no cutout) - constexpr void disableDrawRect2() { _flags &= ~DRAWRECT2; } - constexpr void disableMirror() { _flags &= ~MIRROR; } - constexpr void disableExtractNormalMap() { _flags &= ~EXTRACT_NORMALMAP; } - constexpr void disableFullScreen() { _flags &= ~FULLSCREEN; } - constexpr void disableBackground() { _flags &= ~BACKGROUND; } - constexpr void disableHDR10OutputMapping() { _flags &= ~OUTPUT_COLOR_SPACE_HDR10_ST2084; } - constexpr void disableLinearOutputMapping() { _flags &= ~OUTPUT_COLOR_SPACE_LINEAR; } - - wiImageParams() = default; - wiImageParams(float width, float height): - siz(width, height) - {} - wiImageParams(float posX, float posY, float width, float height, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)) : - pos(posX, posY, 0), - siz(width, height), - color(color) - {} -}; +} diff --git a/WickedEngine/wiImageParams_BindLua.cpp b/WickedEngine/wiImageParams_BindLua.cpp index 0d977e43f..68e95d6c5 100644 --- a/WickedEngine/wiImageParams_BindLua.cpp +++ b/WickedEngine/wiImageParams_BindLua.cpp @@ -1,490 +1,493 @@ #include "wiImageParams_BindLua.h" -#include "Vector_BindLua.h" +#include "wiMath_BindLua.h" -const char wiImageParams_BindLua::className[] = "ImageParams"; +namespace wi::lua +{ + const char ImageParams_BindLua::className[] = "ImageParams"; -Luna::FunctionType wiImageParams_BindLua::methods[] = { - lunamethod(wiImageParams_BindLua, GetPos), - lunamethod(wiImageParams_BindLua, GetSize), - lunamethod(wiImageParams_BindLua, GetPivot), - lunamethod(wiImageParams_BindLua, GetColor), - lunamethod(wiImageParams_BindLua, GetOpacity), - lunamethod(wiImageParams_BindLua, GetFade), - lunamethod(wiImageParams_BindLua, GetRotation), - lunamethod(wiImageParams_BindLua, GetTexOffset), - lunamethod(wiImageParams_BindLua, GetTexOffset2), - lunamethod(wiImageParams_BindLua, GetDrawRect), - lunamethod(wiImageParams_BindLua, GetDrawRect2), - lunamethod(wiImageParams_BindLua, IsDrawRectEnabled), - lunamethod(wiImageParams_BindLua, IsDrawRect2Enabled), - lunamethod(wiImageParams_BindLua, IsMirrorEnabled), - lunamethod(wiImageParams_BindLua, IsBackgroundBlurEnabled), - lunamethod(wiImageParams_BindLua, IsBackgroundEnabled), + Luna::FunctionType ImageParams_BindLua::methods[] = { + lunamethod(ImageParams_BindLua, GetPos), + lunamethod(ImageParams_BindLua, GetSize), + lunamethod(ImageParams_BindLua, GetPivot), + lunamethod(ImageParams_BindLua, GetColor), + lunamethod(ImageParams_BindLua, GetOpacity), + lunamethod(ImageParams_BindLua, GetFade), + lunamethod(ImageParams_BindLua, GetRotation), + lunamethod(ImageParams_BindLua, GetTexOffset), + lunamethod(ImageParams_BindLua, GetTexOffset2), + lunamethod(ImageParams_BindLua, GetDrawRect), + lunamethod(ImageParams_BindLua, GetDrawRect2), + lunamethod(ImageParams_BindLua, IsDrawRectEnabled), + lunamethod(ImageParams_BindLua, IsDrawRect2Enabled), + lunamethod(ImageParams_BindLua, IsMirrorEnabled), + lunamethod(ImageParams_BindLua, IsBackgroundBlurEnabled), + lunamethod(ImageParams_BindLua, IsBackgroundEnabled), - lunamethod(wiImageParams_BindLua, SetPos), - lunamethod(wiImageParams_BindLua, SetSize), - lunamethod(wiImageParams_BindLua, SetPivot), - lunamethod(wiImageParams_BindLua, SetColor), - lunamethod(wiImageParams_BindLua, SetOpacity), - lunamethod(wiImageParams_BindLua, SetFade), - lunamethod(wiImageParams_BindLua, SetStencil), - lunamethod(wiImageParams_BindLua, SetStencilRefMode), - lunamethod(wiImageParams_BindLua, SetBlendMode), - lunamethod(wiImageParams_BindLua, SetQuality), - lunamethod(wiImageParams_BindLua, SetSampleMode), - lunamethod(wiImageParams_BindLua, SetRotation), - lunamethod(wiImageParams_BindLua, SetTexOffset), - lunamethod(wiImageParams_BindLua, SetTexOffset2), - lunamethod(wiImageParams_BindLua, EnableDrawRect), - lunamethod(wiImageParams_BindLua, EnableDrawRect2), - lunamethod(wiImageParams_BindLua, DisableDrawRect), - lunamethod(wiImageParams_BindLua, DisableDrawRect2), - lunamethod(wiImageParams_BindLua, EnableMirror), - lunamethod(wiImageParams_BindLua, DisableMirror), - lunamethod(wiImageParams_BindLua, EnableBackgroundBlur), - lunamethod(wiImageParams_BindLua, DisableBackgroundBlur), - lunamethod(wiImageParams_BindLua, EnableBackground), - lunamethod(wiImageParams_BindLua, DisableBackground), - { NULL, NULL } -}; -Luna::PropertyType wiImageParams_BindLua::properties[] = { - { NULL, NULL } -}; + lunamethod(ImageParams_BindLua, SetPos), + lunamethod(ImageParams_BindLua, SetSize), + lunamethod(ImageParams_BindLua, SetPivot), + lunamethod(ImageParams_BindLua, SetColor), + lunamethod(ImageParams_BindLua, SetOpacity), + lunamethod(ImageParams_BindLua, SetFade), + lunamethod(ImageParams_BindLua, SetStencil), + lunamethod(ImageParams_BindLua, SetStencilRefMode), + lunamethod(ImageParams_BindLua, SetBlendMode), + lunamethod(ImageParams_BindLua, SetQuality), + lunamethod(ImageParams_BindLua, SetSampleMode), + lunamethod(ImageParams_BindLua, SetRotation), + lunamethod(ImageParams_BindLua, SetTexOffset), + lunamethod(ImageParams_BindLua, SetTexOffset2), + lunamethod(ImageParams_BindLua, EnableDrawRect), + lunamethod(ImageParams_BindLua, EnableDrawRect2), + lunamethod(ImageParams_BindLua, DisableDrawRect), + lunamethod(ImageParams_BindLua, DisableDrawRect2), + lunamethod(ImageParams_BindLua, EnableMirror), + lunamethod(ImageParams_BindLua, DisableMirror), + lunamethod(ImageParams_BindLua, EnableBackgroundBlur), + lunamethod(ImageParams_BindLua, DisableBackgroundBlur), + lunamethod(ImageParams_BindLua, EnableBackground), + lunamethod(ImageParams_BindLua, DisableBackground), + { NULL, NULL } + }; + Luna::PropertyType ImageParams_BindLua::properties[] = { + { NULL, NULL } + }; -wiImageParams_BindLua::wiImageParams_BindLua(const wiImageParams& params) :params(params) -{ -} + ImageParams_BindLua::ImageParams_BindLua(const wi::image::Params& params) :params(params) + { + } -int wiImageParams_BindLua::GetPos(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat3(¶ms.pos))); - return 1; -} -int wiImageParams_BindLua::GetSize(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.siz))); - return 1; -} -int wiImageParams_BindLua::GetPivot(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.pivot))); - return 1; -} -int wiImageParams_BindLua::GetColor(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.color))); - return 1; -} -int wiImageParams_BindLua::GetOpacity(lua_State* L) -{ - wiLua::SSetFloat(L, params.opacity); - return 1; -} -int wiImageParams_BindLua::GetFade(lua_State* L) -{ - wiLua::SSetFloat(L, params.fade); - return 1; -} -int wiImageParams_BindLua::GetRotation(lua_State* L) -{ - wiLua::SSetFloat(L, params.rotation); - return 1; -} -int wiImageParams_BindLua::GetTexOffset(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.texOffset))); - return 1; -} -int wiImageParams_BindLua::GetTexOffset2(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.texOffset2))); - return 1; -} -int wiImageParams_BindLua::GetDrawRect(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.drawRect))); - return 1; -} -int wiImageParams_BindLua::GetDrawRect2(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.drawRect2))); - return 1; -} -int wiImageParams_BindLua::IsDrawRectEnabled(lua_State* L) -{ - wiLua::SSetBool(L, params.isDrawRectEnabled()); - return 1; -} -int wiImageParams_BindLua::IsDrawRect2Enabled(lua_State* L) -{ - wiLua::SSetBool(L, params.isDrawRect2Enabled()); - return 1; -} -int wiImageParams_BindLua::IsMirrorEnabled(lua_State* L) -{ - wiLua::SSetBool(L, params.isMirrorEnabled()); - return 1; -} -int wiImageParams_BindLua::IsBackgroundBlurEnabled(lua_State* L) -{ - wiLua::SSetBool(L, params.isBackgroundEnabled()); - return 1; -} -int wiImageParams_BindLua::IsBackgroundEnabled(lua_State* L) -{ - wiLua::SSetBool(L, params.isBackgroundEnabled()); - return 1; -} + int ImageParams_BindLua::GetPos(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat3(¶ms.pos))); + return 1; + } + int ImageParams_BindLua::GetSize(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.siz))); + return 1; + } + int ImageParams_BindLua::GetPivot(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.pivot))); + return 1; + } + int ImageParams_BindLua::GetColor(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.color))); + return 1; + } + int ImageParams_BindLua::GetOpacity(lua_State* L) + { + wi::lua::SSetFloat(L, params.opacity); + return 1; + } + int ImageParams_BindLua::GetFade(lua_State* L) + { + wi::lua::SSetFloat(L, params.fade); + return 1; + } + int ImageParams_BindLua::GetRotation(lua_State* L) + { + wi::lua::SSetFloat(L, params.rotation); + return 1; + } + int ImageParams_BindLua::GetTexOffset(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.texOffset))); + return 1; + } + int ImageParams_BindLua::GetTexOffset2(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(¶ms.texOffset2))); + return 1; + } + int ImageParams_BindLua::GetDrawRect(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.drawRect))); + return 1; + } + int ImageParams_BindLua::GetDrawRect2(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat4(¶ms.drawRect2))); + return 1; + } + int ImageParams_BindLua::IsDrawRectEnabled(lua_State* L) + { + wi::lua::SSetBool(L, params.isDrawRectEnabled()); + return 1; + } + int ImageParams_BindLua::IsDrawRect2Enabled(lua_State* L) + { + wi::lua::SSetBool(L, params.isDrawRect2Enabled()); + return 1; + } + int ImageParams_BindLua::IsMirrorEnabled(lua_State* L) + { + wi::lua::SSetBool(L, params.isMirrorEnabled()); + return 1; + } + int ImageParams_BindLua::IsBackgroundBlurEnabled(lua_State* L) + { + wi::lua::SSetBool(L, params.isBackgroundEnabled()); + return 1; + } + int ImageParams_BindLua::IsBackgroundEnabled(lua_State* L) + { + wi::lua::SSetBool(L, params.isBackgroundEnabled()); + return 1; + } -int wiImageParams_BindLua::SetPos(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + int ImageParams_BindLua::SetPos(lua_State* L) { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - XMStoreFloat3(¶ms.pos, XMLoadFloat4(vector)); - } - } - else - { - wiLua::SError(L, "SetPos(Vector pos) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetSize(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMStoreFloat2(¶ms.siz, XMLoadFloat4(vector)); - } - } - else - { - wiLua::SError(L, "SetSize(Vector size) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetPivot(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMStoreFloat2(¶ms.pivot, XMLoadFloat4(vector)); - } - } - else - { - wiLua::SError(L, "SetPivot(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetColor(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* param = Luna::lightcheck(L, 1); - if (param != nullptr) - { - XMStoreFloat4(¶ms.color, XMLoadFloat4(param)); - } - } - else - { - wiLua::SError(L, "SetColor(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetOpacity(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.opacity = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetOpacity(float x) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetFade(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.fade = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetFade(float x) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetStencil(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 1) - { - params.stencilComp = (STENCILMODE)wiLua::SGetInt(L, 1); - params.stencilRef = (uint8_t)wiLua::SGetInt(L, 2); - } - else - { - wiLua::SError(L, "SetStencil(int stencilmode,stencilref) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetStencilRefMode(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.stencilRefMode = (STENCILREFMODE)wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetStencilRefMode(int stencilrefmode) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetBlendMode(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.blendFlag = (BLENDMODE)wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetBlendMode(int blendMode) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetQuality(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.quality = (QUALITY)wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetQuality(int quality) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetSampleMode(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.sampleFlag = (SAMPLEMODE)wiLua::SGetInt(L, 1); - } - else - { - wiLua::SError(L, "SetSampleMode(int sampleMode) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetRotation(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - params.rotation = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetRotation(float x) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetTexOffset(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMStoreFloat2(¶ms.texOffset, XMLoadFloat4(vector)); - } - } - else - { - wiLua::SError(L, "SetTexOffset(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::SetTexOffset2(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMStoreFloat2(¶ms.texOffset2, XMLoadFloat4(vector)); - } - } - else - { - wiLua::SError(L, "SetTexOffset2(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::EnableDrawRect(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMFLOAT4 drawrect; - XMStoreFloat4(&drawrect, XMLoadFloat4(vector)); - params.enableDrawRect(drawrect); - } - } - else - { - wiLua::SError(L, "EnableDrawRect(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::EnableDrawRect2(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vector = Luna::lightcheck(L, 1); - if (vector != nullptr) - { - XMFLOAT4 drawrect2; - XMStoreFloat4(&drawrect2, XMLoadFloat4(vector)); - params.enableDrawRect2(drawrect2); - } - } - else - { - wiLua::SError(L, "EnableDrawRect2(Vector value) not enough arguments!"); - } - return 0; -} -int wiImageParams_BindLua::DisableDrawRect(lua_State* L) -{ - params.disableDrawRect(); - return 0; -} -int wiImageParams_BindLua::DisableDrawRect2(lua_State* L) -{ - params.disableDrawRect2(); - return 0; -} -int wiImageParams_BindLua::EnableMirror(lua_State* L) -{ - params.enableMirror(); - return 0; -} -int wiImageParams_BindLua::DisableMirror(lua_State* L) -{ - params.disableMirror(); - return 0; -} -int wiImageParams_BindLua::EnableBackgroundBlur(lua_State* L) -{ - params.enableBackground(); - return 0; -} -int wiImageParams_BindLua::DisableBackgroundBlur(lua_State* L) -{ - params.disableBackground(); - return 0; -} -int wiImageParams_BindLua::EnableBackground(lua_State* L) -{ - params.enableBackground(); - return 0; -} -int wiImageParams_BindLua::DisableBackground(lua_State* L) -{ - params.disableBackground(); - return 0; -} - -wiImageParams_BindLua::wiImageParams_BindLua(lua_State *L) -{ - float x = 0, y = 0, w = 100, h = 100; - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - if (argc < 3)//w - { - w = wiLua::SGetFloat(L, 1); - if (argc > 1)//h + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) { - h = wiLua::SGetFloat(L, 2); + XMStoreFloat3(¶ms.pos, XMLoadFloat4(vector)); } } - else{//x,y,w - x = wiLua::SGetFloat(L, 1); - y = wiLua::SGetFloat(L, 2); - w = wiLua::SGetFloat(L, 3); - if (argc > 3)//h + else + { + wi::lua::SError(L, "SetPos(Vector pos) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetSize(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) { - h = wiLua::SGetFloat(L, 4); + XMStoreFloat2(¶ms.siz, XMLoadFloat4(vector)); } } + else + { + wi::lua::SError(L, "SetSize(Vector size) not enough arguments!"); + } + return 0; } - params = wiImageParams(x, y, w, h); -} - - -void wiImageParams_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) + int ImageParams_BindLua::SetPivot(lua_State* L) { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - - wiLua::RunText("STENCILMODE_DISABLED = 0"); - wiLua::RunText("STENCILMODE_EQUAL = 1"); - wiLua::RunText("STENCILMODE_LESS = 2"); - wiLua::RunText("STENCILMODE_LESSEQUAL = 3"); - wiLua::RunText("STENCILMODE_GREATER = 4"); - wiLua::RunText("STENCILMODE_GREATEREQUAL = 5"); - wiLua::RunText("STENCILMODE_NOT = 6"); - wiLua::RunText("STENCILMODE_ALWAYS = 7"); - - wiLua::RunText("STENCILREFMODE_ENGINE = 0"); - wiLua::RunText("STENCILREFMODE_USER = 1"); - wiLua::RunText("STENCILREFMODE_ALL = 2"); - - wiLua::RunText("SAMPLEMODE_CLAMP = 0"); - wiLua::RunText("SAMPLEMODE_WRAP = 1"); - wiLua::RunText("SAMPLEMODE_MIRROR = 2"); - - wiLua::RunText("QUALITY_NEAREST = 0"); - wiLua::RunText("QUALITY_LINEAR = 1"); - wiLua::RunText("QUALITY_ANISOTROPIC = 2"); - wiLua::RunText("QUALITY_BICUBIC = 3"); - - wiLua::RunText("BLENDMODE_OPAQUE = 0"); - wiLua::RunText("BLENDMODE_ALPHA = 1"); - wiLua::RunText("BLENDMODE_PREMULTIPLIED = 2"); - wiLua::RunText("BLENDMODE_ADDITIVE = 3"); + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + XMStoreFloat2(¶ms.pivot, XMLoadFloat4(vector)); + } + } + else + { + wi::lua::SError(L, "SetPivot(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetColor(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* param = Luna::lightcheck(L, 1); + if (param != nullptr) + { + XMStoreFloat4(¶ms.color, XMLoadFloat4(param)); + } + } + else + { + wi::lua::SError(L, "SetColor(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetOpacity(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.opacity = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetOpacity(float x) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetFade(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.fade = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetFade(float x) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetStencil(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + params.stencilComp = (wi::image::STENCILMODE)wi::lua::SGetInt(L, 1); + params.stencilRef = (uint8_t)wi::lua::SGetInt(L, 2); + } + else + { + wi::lua::SError(L, "SetStencil(int stencilmode,stencilref) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetStencilRefMode(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.stencilRefMode = (wi::image::STENCILREFMODE)wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetStencilRefMode(int stencilrefmode) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetBlendMode(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.blendFlag = (wi::enums::BLENDMODE)wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetBlendMode(int blendMode) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetQuality(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.quality = (wi::image::QUALITY)wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetQuality(int quality) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetSampleMode(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.sampleFlag = (wi::image::SAMPLEMODE)wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetSampleMode(int sampleMode) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetRotation(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + params.rotation = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetRotation(float x) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetTexOffset(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + XMStoreFloat2(¶ms.texOffset, XMLoadFloat4(vector)); + } + } + else + { + wi::lua::SError(L, "SetTexOffset(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::SetTexOffset2(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + XMStoreFloat2(¶ms.texOffset2, XMLoadFloat4(vector)); + } + } + else + { + wi::lua::SError(L, "SetTexOffset2(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::EnableDrawRect(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + XMFLOAT4 drawrect; + XMStoreFloat4(&drawrect, XMLoadFloat4(vector)); + params.enableDrawRect(drawrect); + } + } + else + { + wi::lua::SError(L, "EnableDrawRect(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::EnableDrawRect2(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + XMFLOAT4 drawrect2; + XMStoreFloat4(&drawrect2, XMLoadFloat4(vector)); + params.enableDrawRect2(drawrect2); + } + } + else + { + wi::lua::SError(L, "EnableDrawRect2(Vector value) not enough arguments!"); + } + return 0; + } + int ImageParams_BindLua::DisableDrawRect(lua_State* L) + { + params.disableDrawRect(); + return 0; + } + int ImageParams_BindLua::DisableDrawRect2(lua_State* L) + { + params.disableDrawRect2(); + return 0; + } + int ImageParams_BindLua::EnableMirror(lua_State* L) + { + params.enableMirror(); + return 0; + } + int ImageParams_BindLua::DisableMirror(lua_State* L) + { + params.disableMirror(); + return 0; + } + int ImageParams_BindLua::EnableBackgroundBlur(lua_State* L) + { + params.enableBackground(); + return 0; + } + int ImageParams_BindLua::DisableBackgroundBlur(lua_State* L) + { + params.disableBackground(); + return 0; + } + int ImageParams_BindLua::EnableBackground(lua_State* L) + { + params.enableBackground(); + return 0; + } + int ImageParams_BindLua::DisableBackground(lua_State* L) + { + params.disableBackground(); + return 0; } -} + ImageParams_BindLua::ImageParams_BindLua(lua_State* L) + { + float x = 0, y = 0, w = 100, h = 100; + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + if (argc < 3)//w + { + w = wi::lua::SGetFloat(L, 1); + if (argc > 1)//h + { + h = wi::lua::SGetFloat(L, 2); + } + } + else {//x,y,w + x = wi::lua::SGetFloat(L, 1); + y = wi::lua::SGetFloat(L, 2); + w = wi::lua::SGetFloat(L, 3); + if (argc > 3)//h + { + h = wi::lua::SGetFloat(L, 4); + } + } + } + params = wi::image::Params(x, y, w, h); + } + + + void ImageParams_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + + wi::lua::RunText("STENCILMODE_DISABLED = 0"); + wi::lua::RunText("STENCILMODE_EQUAL = 1"); + wi::lua::RunText("STENCILMODE_LESS = 2"); + wi::lua::RunText("STENCILMODE_LESSEQUAL = 3"); + wi::lua::RunText("STENCILMODE_GREATER = 4"); + wi::lua::RunText("STENCILMODE_GREATEREQUAL = 5"); + wi::lua::RunText("STENCILMODE_NOT = 6"); + wi::lua::RunText("STENCILMODE_ALWAYS = 7"); + + wi::lua::RunText("STENCILREFMODE_ENGINE = 0"); + wi::lua::RunText("STENCILREFMODE_USER = 1"); + wi::lua::RunText("STENCILREFMODE_ALL = 2"); + + wi::lua::RunText("SAMPLEMODE_CLAMP = 0"); + wi::lua::RunText("SAMPLEMODE_WRAP = 1"); + wi::lua::RunText("SAMPLEMODE_MIRROR = 2"); + + wi::lua::RunText("QUALITY_NEAREST = 0"); + wi::lua::RunText("QUALITY_LINEAR = 1"); + wi::lua::RunText("QUALITY_ANISOTROPIC = 2"); + wi::lua::RunText("QUALITY_BICUBIC = 3"); + + wi::lua::RunText("BLENDMODE_OPAQUE = 0"); + wi::lua::RunText("BLENDMODE_ALPHA = 1"); + wi::lua::RunText("BLENDMODE_PREMULTIPLIED = 2"); + wi::lua::RunText("BLENDMODE_ADDITIVE = 3"); + } + } + +} diff --git a/WickedEngine/wiImageParams_BindLua.h b/WickedEngine/wiImageParams_BindLua.h index d25b42221..de1f642b7 100644 --- a/WickedEngine/wiImageParams_BindLua.h +++ b/WickedEngine/wiImageParams_BindLua.h @@ -3,60 +3,62 @@ #include "wiLuna.h" #include "wiImage.h" -class wiImageParams_BindLua +namespace wi::lua { -public: - wiImageParams params; + class ImageParams_BindLua + { + public: + wi::image::Params params; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiImageParams_BindLua(const wiImageParams& params); - wiImageParams_BindLua(lua_State *L); + ImageParams_BindLua(const wi::image::Params& params); + ImageParams_BindLua(lua_State* L); - int GetPos(lua_State* L); - int GetSize(lua_State* L); - int GetPivot(lua_State* L); - int GetColor(lua_State* L); - int GetOpacity(lua_State* L); - int GetFade(lua_State* L); - int GetRotation(lua_State* L); - int GetTexOffset(lua_State* L); - int GetTexOffset2(lua_State* L); - int GetDrawRect(lua_State* L); - int GetDrawRect2(lua_State* L); - int IsDrawRectEnabled(lua_State* L); - int IsDrawRect2Enabled(lua_State* L); - int IsMirrorEnabled(lua_State* L); - int IsBackgroundBlurEnabled(lua_State* L); - int IsBackgroundEnabled(lua_State* L); + int GetPos(lua_State* L); + int GetSize(lua_State* L); + int GetPivot(lua_State* L); + int GetColor(lua_State* L); + int GetOpacity(lua_State* L); + int GetFade(lua_State* L); + int GetRotation(lua_State* L); + int GetTexOffset(lua_State* L); + int GetTexOffset2(lua_State* L); + int GetDrawRect(lua_State* L); + int GetDrawRect2(lua_State* L); + int IsDrawRectEnabled(lua_State* L); + int IsDrawRect2Enabled(lua_State* L); + int IsMirrorEnabled(lua_State* L); + int IsBackgroundBlurEnabled(lua_State* L); + int IsBackgroundEnabled(lua_State* L); - int SetPos(lua_State* L); - int SetSize(lua_State* L); - int SetPivot(lua_State* L); - int SetColor(lua_State* L); - int SetOpacity(lua_State* L); - int SetFade(lua_State* L); - int SetStencil(lua_State* L); - int SetStencilRefMode(lua_State* L); - int SetBlendMode(lua_State* L); - int SetQuality(lua_State* L); - int SetSampleMode(lua_State* L); - int SetRotation(lua_State* L); - int SetTexOffset(lua_State* L); - int SetTexOffset2(lua_State* L); - int EnableDrawRect(lua_State* L); - int EnableDrawRect2(lua_State* L); - int DisableDrawRect(lua_State* L); - int DisableDrawRect2(lua_State* L); - int EnableMirror(lua_State* L); - int DisableMirror(lua_State* L); - int EnableBackgroundBlur(lua_State* L); - int DisableBackgroundBlur(lua_State* L); - int EnableBackground(lua_State* L); - int DisableBackground(lua_State* L); - - static void Bind(); -}; + int SetPos(lua_State* L); + int SetSize(lua_State* L); + int SetPivot(lua_State* L); + int SetColor(lua_State* L); + int SetOpacity(lua_State* L); + int SetFade(lua_State* L); + int SetStencil(lua_State* L); + int SetStencilRefMode(lua_State* L); + int SetBlendMode(lua_State* L); + int SetQuality(lua_State* L); + int SetSampleMode(lua_State* L); + int SetRotation(lua_State* L); + int SetTexOffset(lua_State* L); + int SetTexOffset2(lua_State* L); + int EnableDrawRect(lua_State* L); + int EnableDrawRect2(lua_State* L); + int DisableDrawRect(lua_State* L); + int DisableDrawRect2(lua_State* L); + int EnableMirror(lua_State* L); + int DisableMirror(lua_State* L); + int EnableBackgroundBlur(lua_State* L); + int DisableBackgroundBlur(lua_State* L); + int EnableBackground(lua_State* L); + int DisableBackground(lua_State* L); + static void Bind(); + }; +} diff --git a/WickedEngine/wiInitializer.cpp b/WickedEngine/wiInitializer.cpp index dd6ea1672..148aae85c 100644 --- a/WickedEngine/wiInitializer.cpp +++ b/WickedEngine/wiInitializer.cpp @@ -4,16 +4,16 @@ #include #include -namespace wiInitializer +namespace wi::initializer { bool initializationStarted = false; - wiJobSystem::context ctx; - wiTimer timer; + wi::jobsystem::context ctx; + wi::Timer timer; void InitializeComponentsImmediate() { InitializeComponentsAsync(); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); } void InitializeComponentsAsync() { @@ -22,48 +22,48 @@ namespace wiInitializer initializationStarted = true; std::string ss; - ss += "\n[wiInitializer] Initializing Wicked Engine, please wait...\n"; + ss += "\n[wi::initializer] Initializing Wicked Engine, please wait...\n"; ss += "Version: "; - ss += wiVersion::GetVersionString(); + ss += wi::version::GetVersionString(); ss += "\n"; - wiBackLog::post(ss); + wi::backlog::post(ss); - wiJobSystem::Initialize(); - wiShaderCompiler::Initialize(); + wi::jobsystem::Initialize(); + wi::shadercompiler::Initialize(); - size_t shaderdump_count = wiRenderer::GetShaderDumpCount(); + size_t shaderdump_count = wi::renderer::GetShaderDumpCount(); if (shaderdump_count > 0) { - wiBackLog::post("Embedded shaders found: " + std::to_string(shaderdump_count)); + wi::backlog::post("Embedded shaders found: " + std::to_string(shaderdump_count)); } - wiBackLog::post(""); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiFont::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiImage::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiInput::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiRenderer::Initialize(); wiWidget::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiAudio::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiNetwork::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiTextureHelper::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiScene::wiHairParticle::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiScene::wiEmittedParticle::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiOcean::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiGPUSortLib::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiGPUBVH::Initialize(); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { wiPhysicsEngine::Initialize(); }); + wi::backlog::post(""); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::font::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::image::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::input::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::renderer::Initialize(); wi::gui::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::audio::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::network::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::texturehelper::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::HairParticleSystem::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::EmittedParticleSystem::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::Ocean::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::gpusortlib::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::GPUBVH::Initialize(); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { wi::physics::Initialize(); }); // Initialize this immediately: - wiLua::Initialize(); + wi::lua::Initialize(); std::thread([] { - wiJobSystem::Wait(ctx); - wiBackLog::post("\n[wiInitializer] Wicked Engine Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::jobsystem::Wait(ctx); + wi::backlog::post("\n[wi::initializer] Wicked Engine Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); }).detach(); } bool IsInitializeFinished() { - return initializationStarted && !wiJobSystem::IsBusy(ctx); + return initializationStarted && !wi::jobsystem::IsBusy(ctx); } } diff --git a/WickedEngine/wiInitializer.h b/WickedEngine/wiInitializer.h index 5e4f2a4c6..62e651cb2 100644 --- a/WickedEngine/wiInitializer.h +++ b/WickedEngine/wiInitializer.h @@ -1,7 +1,6 @@ #pragma once - -namespace wiInitializer +namespace wi::initializer { // Initializes systems and blocks CPU until it is complete void InitializeComponentsImmediate(); @@ -10,5 +9,3 @@ namespace wiInitializer // Check if systems have been initialized or not bool IsInitializeFinished(); } - - diff --git a/WickedEngine/wiInput.cpp b/WickedEngine/wiInput.cpp index c6da05a50..896e1bb73 100644 --- a/WickedEngine/wiInput.cpp +++ b/WickedEngine/wiInput.cpp @@ -4,7 +4,7 @@ #include "wiRawInput.h" #include "wiSDLInput.h" #include "wiHelper.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiProfiler.h" #include "wiColor.h" #include "wiTimer.h" @@ -24,9 +24,9 @@ #include #endif // PLATFORM_UWP -namespace wiInput +namespace wi::input { - wiPlatform::window_type window = nullptr; + wi::platform::window_type window = nullptr; #ifdef _WIN32 #ifndef PLATFORM_UWP @@ -83,16 +83,16 @@ namespace wiInput void Initialize() { - wiTimer timer; + wi::Timer timer; - wiRawInput::Initialize(); - wiSDLInput::Initialize(); + wi::input::rawinput::Initialize(); + wi::input::sdlinput::Initialize(); - wiBackLog::post("wiInput Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::input Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); initialized.store(true); } - void Update(wiPlatform::window_type _window) + void Update(wi::platform::window_type _window) { window = _window; if (!initialized.load()) @@ -100,18 +100,18 @@ namespace wiInput return; } - auto range = wiProfiler::BeginRangeCPU("Input"); + auto range = wi::profiler::BeginRangeCPU("Input"); - wiXInput::Update(); - wiRawInput::Update(); - wiSDLInput::Update(); + wi::input::xinput::Update(); + wi::input::rawinput::Update(); + wi::input::sdlinput::Update(); mouse.delta_wheel = 0; mouse.delta_position = XMFLOAT2(0, 0); #ifdef _WIN32 - wiRawInput::GetMouseState(&mouse); // currently only the relative data can be used from this - wiRawInput::GetKeyboardState(&keyboard); + wi::input::rawinput::GetMouseState(&mouse); // currently only the relative data can be used from this + wi::input::rawinput::GetKeyboardState(&keyboard); // apparently checking the mouse here instead of Down() avoids missing the button presses (review!) mouse.left_button_press |= KEY_DOWN(VK_LBUTTON); @@ -130,8 +130,8 @@ namespace wiInput #endif // PLATFORM_UWP #elif SDL2 - wiSDLInput::GetMouseState(&mouse); - wiSDLInput::GetKeyboardState(&keyboard); + wi::input::sdlinput::GetMouseState(&mouse); + wi::input::sdlinput::GetKeyboardState(&keyboard); //TODO controllers //TODO touch #endif @@ -213,9 +213,9 @@ namespace wiInput #endif // Check if low-level XINPUT controller is not registered for playerindex slot and register: - for (int i = 0; i < wiXInput::GetMaxControllerCount(); ++i) + for (int i = 0; i < wi::input::xinput::GetMaxControllerCount(); ++i) { - if (wiXInput::GetControllerState(nullptr, i)) + if (wi::input::xinput::GetControllerState(nullptr, i)) { int slot = -1; for (int j = 0; j < (int)controllers.size(); ++j) @@ -244,9 +244,9 @@ namespace wiInput } // Check if low-level RAWINPUT controller is not registered for playerindex slot and register: - for (int i = 0; i < wiRawInput::GetMaxControllerCount(); ++i) + for (int i = 0; i < wi::input::rawinput::GetMaxControllerCount(); ++i) { - if (wiRawInput::GetControllerState(nullptr, i)) + if (wi::input::rawinput::GetControllerState(nullptr, i)) { int slot = -1; for (int j = 0; j < (int)controllers.size(); ++j) @@ -275,9 +275,9 @@ namespace wiInput } // Check if low-level SDLINPUT controller is not registered for playerindex slot and register: - for (int i = 0; i < wiSDLInput::GetMaxControllerCount(); ++i) + for (int i = 0; i < wi::input::sdlinput::GetMaxControllerCount(); ++i) { - if (wiSDLInput::GetControllerState(nullptr, i)) + if (wi::input::sdlinput::GetControllerState(nullptr, i)) { int slot = -1; for (int j = 0; j < (int)controllers.size(); ++j) @@ -312,13 +312,13 @@ namespace wiInput switch (controller.deviceType) { case Controller::XINPUT: - connected = wiXInput::GetControllerState(&controller.state, controller.deviceIndex); + connected = wi::input::xinput::GetControllerState(&controller.state, controller.deviceIndex); break; case Controller::RAWINPUT: - connected = wiRawInput::GetControllerState(&controller.state, controller.deviceIndex); + connected = wi::input::rawinput::GetControllerState(&controller.state, controller.deviceIndex); break; case Controller::SDLINPUT: - connected = wiSDLInput::GetControllerState(&controller.state, controller.deviceIndex); + connected = wi::input::sdlinput::GetControllerState(&controller.state, controller.deviceIndex); break; } @@ -356,7 +356,7 @@ namespace wiInput touches.clear(); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } bool Down(BUTTON button, int playerindex) @@ -398,196 +398,196 @@ namespace wiInput switch (button) { - case wiInput::MOUSE_BUTTON_LEFT: + case wi::input::MOUSE_BUTTON_LEFT: if (mouse.left_button_press) return true; return false; break; - case wiInput::MOUSE_BUTTON_RIGHT: + case wi::input::MOUSE_BUTTON_RIGHT: if (mouse.right_button_press) return true; return false; break; - case wiInput::MOUSE_BUTTON_MIDDLE: + case wi::input::MOUSE_BUTTON_MIDDLE: if (mouse.middle_button_press) return true; return false; break; #ifdef _WIN32 - case wiInput::KEYBOARD_BUTTON_UP: + case wi::input::KEYBOARD_BUTTON_UP: keycode = VK_UP; break; - case wiInput::KEYBOARD_BUTTON_DOWN: + case wi::input::KEYBOARD_BUTTON_DOWN: keycode = VK_DOWN; break; - case wiInput::KEYBOARD_BUTTON_LEFT: + case wi::input::KEYBOARD_BUTTON_LEFT: keycode = VK_LEFT; break; - case wiInput::KEYBOARD_BUTTON_RIGHT: + case wi::input::KEYBOARD_BUTTON_RIGHT: keycode = VK_RIGHT; break; - case wiInput::KEYBOARD_BUTTON_SPACE: + case wi::input::KEYBOARD_BUTTON_SPACE: keycode = VK_SPACE; break; - case wiInput::KEYBOARD_BUTTON_RSHIFT: + case wi::input::KEYBOARD_BUTTON_RSHIFT: keycode = VK_RSHIFT; break; - case wiInput::KEYBOARD_BUTTON_LSHIFT: + case wi::input::KEYBOARD_BUTTON_LSHIFT: keycode = VK_LSHIFT; break; - case wiInput::KEYBOARD_BUTTON_F1: + case wi::input::KEYBOARD_BUTTON_F1: keycode = VK_F1; break; - case wiInput::KEYBOARD_BUTTON_F2: + case wi::input::KEYBOARD_BUTTON_F2: keycode = VK_F2; break; - case wiInput::KEYBOARD_BUTTON_F3: + case wi::input::KEYBOARD_BUTTON_F3: keycode = VK_F3; break; - case wiInput::KEYBOARD_BUTTON_F4: + case wi::input::KEYBOARD_BUTTON_F4: keycode = VK_F4; break; - case wiInput::KEYBOARD_BUTTON_F5: + case wi::input::KEYBOARD_BUTTON_F5: keycode = VK_F5; break; - case wiInput::KEYBOARD_BUTTON_F6: + case wi::input::KEYBOARD_BUTTON_F6: keycode = VK_F6; break; - case wiInput::KEYBOARD_BUTTON_F7: + case wi::input::KEYBOARD_BUTTON_F7: keycode = VK_F7; break; - case wiInput::KEYBOARD_BUTTON_F8: + case wi::input::KEYBOARD_BUTTON_F8: keycode = VK_F8; break; - case wiInput::KEYBOARD_BUTTON_F9: + case wi::input::KEYBOARD_BUTTON_F9: keycode = VK_F9; break; - case wiInput::KEYBOARD_BUTTON_F10: + case wi::input::KEYBOARD_BUTTON_F10: keycode = VK_F10; break; - case wiInput::KEYBOARD_BUTTON_F11: + case wi::input::KEYBOARD_BUTTON_F11: keycode = VK_F11; break; - case wiInput::KEYBOARD_BUTTON_F12: + case wi::input::KEYBOARD_BUTTON_F12: keycode = VK_F12; break; - case wiInput::KEYBOARD_BUTTON_ENTER: + case wi::input::KEYBOARD_BUTTON_ENTER: keycode = VK_RETURN; break; - case wiInput::KEYBOARD_BUTTON_ESCAPE: + case wi::input::KEYBOARD_BUTTON_ESCAPE: keycode = VK_ESCAPE; break; - case wiInput::KEYBOARD_BUTTON_HOME: + case wi::input::KEYBOARD_BUTTON_HOME: keycode = VK_HOME; break; - case wiInput::KEYBOARD_BUTTON_LCONTROL: + case wi::input::KEYBOARD_BUTTON_LCONTROL: keycode = VK_LCONTROL; break; - case wiInput::KEYBOARD_BUTTON_RCONTROL: + case wi::input::KEYBOARD_BUTTON_RCONTROL: keycode = VK_RCONTROL; break; - case wiInput::KEYBOARD_BUTTON_DELETE: + case wi::input::KEYBOARD_BUTTON_DELETE: keycode = VK_DELETE; break; - case wiInput::KEYBOARD_BUTTON_BACKSPACE: + case wi::input::KEYBOARD_BUTTON_BACKSPACE: keycode = VK_BACK; break; - case wiInput::KEYBOARD_BUTTON_PAGEDOWN: + case wi::input::KEYBOARD_BUTTON_PAGEDOWN: keycode = VK_NEXT; break; - case wiInput::KEYBOARD_BUTTON_PAGEUP: + case wi::input::KEYBOARD_BUTTON_PAGEUP: keycode = VK_PRIOR; break; #elif SDL2 - case wiInput::KEYBOARD_BUTTON_UP: + case wi::input::KEYBOARD_BUTTON_UP: keycode = SDL_SCANCODE_UP; break; - case wiInput::KEYBOARD_BUTTON_DOWN: + case wi::input::KEYBOARD_BUTTON_DOWN: keycode = SDL_SCANCODE_DOWN; break; - case wiInput::KEYBOARD_BUTTON_LEFT: + case wi::input::KEYBOARD_BUTTON_LEFT: keycode = SDL_SCANCODE_LEFT; break; - case wiInput::KEYBOARD_BUTTON_RIGHT: + case wi::input::KEYBOARD_BUTTON_RIGHT: keycode = SDL_SCANCODE_RIGHT; break; - case wiInput::KEYBOARD_BUTTON_SPACE: + case wi::input::KEYBOARD_BUTTON_SPACE: keycode = SDL_SCANCODE_SPACE; break; - case wiInput::KEYBOARD_BUTTON_RSHIFT: + case wi::input::KEYBOARD_BUTTON_RSHIFT: keycode = SDL_SCANCODE_RSHIFT; break; - case wiInput::KEYBOARD_BUTTON_LSHIFT: + case wi::input::KEYBOARD_BUTTON_LSHIFT: keycode = SDL_SCANCODE_LSHIFT; break; - case wiInput::KEYBOARD_BUTTON_F1: + case wi::input::KEYBOARD_BUTTON_F1: keycode = SDL_SCANCODE_F1; break; - case wiInput::KEYBOARD_BUTTON_F2: + case wi::input::KEYBOARD_BUTTON_F2: keycode = SDL_SCANCODE_F2; break; - case wiInput::KEYBOARD_BUTTON_F3: + case wi::input::KEYBOARD_BUTTON_F3: keycode = SDL_SCANCODE_F3; break; - case wiInput::KEYBOARD_BUTTON_F4: + case wi::input::KEYBOARD_BUTTON_F4: keycode = SDL_SCANCODE_F4; break; - case wiInput::KEYBOARD_BUTTON_F5: + case wi::input::KEYBOARD_BUTTON_F5: keycode = SDL_SCANCODE_F5; break; - case wiInput::KEYBOARD_BUTTON_F6: + case wi::input::KEYBOARD_BUTTON_F6: keycode = SDL_SCANCODE_F6; break; - case wiInput::KEYBOARD_BUTTON_F7: + case wi::input::KEYBOARD_BUTTON_F7: keycode = SDL_SCANCODE_F7; break; - case wiInput::KEYBOARD_BUTTON_F8: + case wi::input::KEYBOARD_BUTTON_F8: keycode = SDL_SCANCODE_F8; break; - case wiInput::KEYBOARD_BUTTON_F9: + case wi::input::KEYBOARD_BUTTON_F9: keycode = SDL_SCANCODE_F9; break; - case wiInput::KEYBOARD_BUTTON_F10: + case wi::input::KEYBOARD_BUTTON_F10: keycode = SDL_SCANCODE_F10; break; - case wiInput::KEYBOARD_BUTTON_F11: + case wi::input::KEYBOARD_BUTTON_F11: keycode = SDL_SCANCODE_F11; break; - case wiInput::KEYBOARD_BUTTON_F12: + case wi::input::KEYBOARD_BUTTON_F12: keycode = SDL_SCANCODE_F12; break; - case wiInput::KEYBOARD_BUTTON_ENTER: + case wi::input::KEYBOARD_BUTTON_ENTER: keycode = SDL_SCANCODE_RETURN; break; - case wiInput::KEYBOARD_BUTTON_ESCAPE: + case wi::input::KEYBOARD_BUTTON_ESCAPE: keycode = SDL_SCANCODE_ESCAPE; break; - case wiInput::KEYBOARD_BUTTON_HOME: + case wi::input::KEYBOARD_BUTTON_HOME: keycode = SDL_SCANCODE_HOME; break; - case wiInput::KEYBOARD_BUTTON_LCONTROL: + case wi::input::KEYBOARD_BUTTON_LCONTROL: keycode = SDL_SCANCODE_LCTRL; break; - case wiInput::KEYBOARD_BUTTON_RCONTROL: + case wi::input::KEYBOARD_BUTTON_RCONTROL: keycode = SDL_SCANCODE_RCTRL; break; - case wiInput::KEYBOARD_BUTTON_DELETE: + case wi::input::KEYBOARD_BUTTON_DELETE: keycode = SDL_SCANCODE_DELETE; break; - case wiInput::KEYBOARD_BUTTON_BACKSPACE: + case wi::input::KEYBOARD_BUTTON_BACKSPACE: keycode = SDL_SCANCODE_BACKSPACE; break; - case wiInput::KEYBOARD_BUTTON_PAGEDOWN: + case wi::input::KEYBOARD_BUTTON_PAGEDOWN: keycode = SDL_SCANCODE_PAGEDOWN; break; - case wiInput::KEYBOARD_BUTTON_PAGEUP: + case wi::input::KEYBOARD_BUTTON_PAGEUP: keycode = SDL_SCANCODE_PAGEUP; break; //Translating engine's keycode mapping (which comes from Win32 i presume) to the matching SDL2 keycode //Win32 Link: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes //SDL2 Link: https://wiki.libsdl.org/SDL_Keycode //Numbers start from enum 48 to 57, 58 to 64 are undefined, 65 to 90 are alphabets. - //Usage: the same as win32 platform, which is (for example) wiInput::Down((wiInput::BUTTON)'A' (referenced from Editor.cpp for the engine's editor program) + //Usage: the same as win32 platform, which is (for example) wi::input::Down((wi::input::BUTTON)'A' (referenced from Editor.cpp for the engine's editor program) case 48: keycode = SDL_SCANCODE_0; break; @@ -830,11 +830,11 @@ namespace wiInput if (controller.deviceType == Controller::XINPUT) { - wiXInput::SetControllerFeedback(data, controller.deviceIndex); + wi::input::xinput::SetControllerFeedback(data, controller.deviceIndex); } else if (controller.deviceType == Controller::RAWINPUT) { - wiRawInput::SetControllerFeedback(data, controller.deviceIndex); + wi::input::rawinput::SetControllerFeedback(data, controller.deviceIndex); } } } diff --git a/WickedEngine/wiInput.h b/WickedEngine/wiInput.h index 42661f996..3c269ff52 100644 --- a/WickedEngine/wiInput.h +++ b/WickedEngine/wiInput.h @@ -4,7 +4,7 @@ #include "wiColor.h" #include "wiVector.h" -namespace wiInput +namespace wi::input { // Do not alter order as it is bound to lua manually! enum BUTTON @@ -103,14 +103,14 @@ namespace wiInput { float vibration_left = 0; // left vibration motor (0: no vibration, 1: maximum vibration) float vibration_right = 0; // right vibration motor (0: no vibration, 1: maximum vibration) - wiColor led_color; // led color + wi::Color led_color; // led color }; // call once at app start void Initialize(); // call once per frame - void Update(wiPlatform::window_type window); + void Update(wi::platform::window_type window); const KeyboardState& GetKeyboardState(); const MouseState& GetMouseState(); diff --git a/WickedEngine/wiInput_BindLua.cpp b/WickedEngine/wiInput_BindLua.cpp index dbca7e389..d94ebd7ac 100644 --- a/WickedEngine/wiInput_BindLua.cpp +++ b/WickedEngine/wiInput_BindLua.cpp @@ -1,370 +1,375 @@ #include "wiInput_BindLua.h" -#include "Vector_BindLua.h" +#include "wiMath_BindLua.h" -const char wiInput_BindLua::className[] = "Input"; +namespace wi::lua +{ -Luna::FunctionType wiInput_BindLua::methods[] = { - lunamethod(wiInput_BindLua, Down), - lunamethod(wiInput_BindLua, Press), - lunamethod(wiInput_BindLua, Hold), - lunamethod(wiInput_BindLua, GetPointer), - lunamethod(wiInput_BindLua, SetPointer), - lunamethod(wiInput_BindLua, GetPointerDelta), - lunamethod(wiInput_BindLua, HidePointer), - lunamethod(wiInput_BindLua, GetAnalog), - lunamethod(wiInput_BindLua, GetTouches), - lunamethod(wiInput_BindLua, SetControllerFeedback), - { NULL, NULL } -}; -Luna::PropertyType wiInput_BindLua::properties[] = { - { NULL, NULL } -}; + const char Input_BindLua::className[] = "Input"; -int wiInput_BindLua::Down(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiInput::BUTTON button = (wiInput::BUTTON)wiLua::SGetInt(L, 1); - int playerindex = 0; - if (argc > 1) - { - playerindex = wiLua::SGetInt(L, 2); - } - wiLua::SSetBool(L, wiInput::Down(button, playerindex)); - return 1; - } - else - wiLua::SError(L, "Down(int code, opt int playerindex = 0) not enough arguments!"); - return 0; -} -int wiInput_BindLua::Press(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiInput::BUTTON code = (wiInput::BUTTON)wiLua::SGetInt(L, 1); - int playerindex = 0; - if (argc > 1) - { - playerindex = wiLua::SGetInt(L, 2); - } - wiLua::SSetBool(L, wiInput::Press(code, playerindex)); - return 1; - } - else - wiLua::SError(L, "Press(int code, opt int playerindex = 0) not enough arguments!"); - return 0; -} -int wiInput_BindLua::Hold(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiInput::BUTTON button = (wiInput::BUTTON)wiLua::SGetInt(L, 1); - uint32_t duration = 30; - if (argc > 1) - { - duration = wiLua::SGetInt(L, 2); - } - bool continuous = false; - if (argc > 2) - { - continuous = wiLua::SGetBool(L, 3); - } - int playerindex = 0; - if (argc > 3) - { - playerindex = wiLua::SGetInt(L, 4); - } - wiLua::SSetBool(L, wiInput::Hold(button, duration, continuous, playerindex)); - return 1; - } - else - wiLua::SError(L, "Hold(int code, opt int duration = 30, opt boolean continuous = false, opt int playerindex = 0) not enough arguments!"); - return 0; -} -int wiInput_BindLua::GetPointer(lua_State* L) -{ - XMFLOAT4 P = wiInput::GetPointer(); - Luna::push(L, new Vector_BindLua(XMLoadFloat4(&P))); - return 1; -} -int wiInput_BindLua::SetPointer(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) - { - wiInput::SetPointer(*vec); - } - else - wiLua::SError(L, "SetPointer(Vector props) argument is not a Vector!"); - } - else - wiLua::SError(L, "SetPointer(Vector props) not enough arguments!"); - return 0; -} -int wiInput_BindLua::GetPointerDelta(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(&wiInput::GetMouseState().delta_position))); - return 1; -} -int wiInput_BindLua::HidePointer(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiInput::HidePointer(wiLua::SGetBool(L, 1)); - } - else - wiLua::SError(L, "HidePointer(bool value) not enough arguments!"); - return 0; -} -int wiInput_BindLua::GetAnalog(lua_State* L) -{ - XMFLOAT4 result = XMFLOAT4(0, 0, 0, 0); + Luna::FunctionType Input_BindLua::methods[] = { + lunamethod(Input_BindLua, Down), + lunamethod(Input_BindLua, Press), + lunamethod(Input_BindLua, Hold), + lunamethod(Input_BindLua, GetPointer), + lunamethod(Input_BindLua, SetPointer), + lunamethod(Input_BindLua, GetPointerDelta), + lunamethod(Input_BindLua, HidePointer), + lunamethod(Input_BindLua, GetAnalog), + lunamethod(Input_BindLua, GetTouches), + lunamethod(Input_BindLua, SetControllerFeedback), + { NULL, NULL } + }; + Luna::PropertyType Input_BindLua::properties[] = { + { NULL, NULL } + }; - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + int Input_BindLua::Down(lua_State* L) { - wiInput::GAMEPAD_ANALOG type = (wiInput::GAMEPAD_ANALOG)wiLua::SGetInt(L, 1); - int playerindex = 0; - if (argc > 1) - { - playerindex = wiLua::SGetInt(L, 2); - } - result = wiInput::GetAnalog(type, playerindex); - } - else - wiLua::SError(L, "GetAnalog(int type, opt int playerindex = 0) not enough arguments!"); - - Luna::push(L, new Vector_BindLua(XMLoadFloat4(&result))); - return 1; -} -int wiInput_BindLua::GetTouches(lua_State* L) -{ - auto& touches = wiInput::GetTouches(); - for (auto& touch : touches) - { - Luna::push(L, new Touch_BindLua(touch)); - } - return (int)touches.size(); -} -int wiInput_BindLua::SetControllerFeedback(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - ControllerFeedback_BindLua* fb = Luna::lightcheck(L, 1); // Ferdinand Braun - if (fb != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { + wi::input::BUTTON button = (wi::input::BUTTON)wi::lua::SGetInt(L, 1); int playerindex = 0; if (argc > 1) { - playerindex = wiLua::SGetInt(L, 2); + playerindex = wi::lua::SGetInt(L, 2); } - wiInput::SetControllerFeedback(fb->feedback, playerindex); + wi::lua::SSetBool(L, wi::input::Down(button, playerindex)); + return 1; + } + else + wi::lua::SError(L, "Down(int code, opt int playerindex = 0) not enough arguments!"); + return 0; + } + int Input_BindLua::Press(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::input::BUTTON code = (wi::input::BUTTON)wi::lua::SGetInt(L, 1); + int playerindex = 0; + if (argc > 1) + { + playerindex = wi::lua::SGetInt(L, 2); + } + wi::lua::SSetBool(L, wi::input::Press(code, playerindex)); + return 1; + } + else + wi::lua::SError(L, "Press(int code, opt int playerindex = 0) not enough arguments!"); + return 0; + } + int Input_BindLua::Hold(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::input::BUTTON button = (wi::input::BUTTON)wi::lua::SGetInt(L, 1); + uint32_t duration = 30; + if (argc > 1) + { + duration = wi::lua::SGetInt(L, 2); + } + bool continuous = false; + if (argc > 2) + { + continuous = wi::lua::SGetBool(L, 3); + } + int playerindex = 0; + if (argc > 3) + { + playerindex = wi::lua::SGetInt(L, 4); + } + wi::lua::SSetBool(L, wi::input::Hold(button, duration, continuous, playerindex)); + return 1; + } + else + wi::lua::SError(L, "Hold(int code, opt int duration = 30, opt boolean continuous = false, opt int playerindex = 0) not enough arguments!"); + return 0; + } + int Input_BindLua::GetPointer(lua_State* L) + { + XMFLOAT4 P = wi::input::GetPointer(); + Luna::push(L, new Vector_BindLua(XMLoadFloat4(&P))); + return 1; + } + int Input_BindLua::SetPointer(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + wi::input::SetPointer(*vec); + } + else + wi::lua::SError(L, "SetPointer(Vector props) argument is not a Vector!"); + } + else + wi::lua::SError(L, "SetPointer(Vector props) not enough arguments!"); + return 0; + } + int Input_BindLua::GetPointerDelta(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(&wi::input::GetMouseState().delta_position))); + return 1; + } + int Input_BindLua::HidePointer(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::input::HidePointer(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "HidePointer(bool value) not enough arguments!"); + return 0; + } + int Input_BindLua::GetAnalog(lua_State* L) + { + XMFLOAT4 result = XMFLOAT4(0, 0, 0, 0); + + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::input::GAMEPAD_ANALOG type = (wi::input::GAMEPAD_ANALOG)wi::lua::SGetInt(L, 1); + int playerindex = 0; + if (argc > 1) + { + playerindex = wi::lua::SGetInt(L, 2); + } + result = wi::input::GetAnalog(type, playerindex); + } + else + wi::lua::SError(L, "GetAnalog(int type, opt int playerindex = 0) not enough arguments!"); + + Luna::push(L, new Vector_BindLua(XMLoadFloat4(&result))); + return 1; + } + int Input_BindLua::GetTouches(lua_State* L) + { + auto& touches = wi::input::GetTouches(); + for (auto& touch : touches) + { + Luna::push(L, new Touch_BindLua(touch)); + } + return (int)touches.size(); + } + int Input_BindLua::SetControllerFeedback(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + ControllerFeedback_BindLua* fb = Luna::lightcheck(L, 1); // Ferdinand Braun + if (fb != nullptr) + { + int playerindex = 0; + if (argc > 1) + { + playerindex = wi::lua::SGetInt(L, 2); + } + wi::input::SetControllerFeedback(fb->feedback, playerindex); + } + else + { + wi::lua::SError(L, "SetControllerFeedback(ControllerFeedback feedback, opt int playerindex = 0) first argument is not a ControllerFeedback!"); + } + } + else + wi::lua::SError(L, "SetControllerFeedback(ControllerFeedback feedback, opt int playerindex = 0) not enough arguments!"); + return 0; + } + + void Input_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + wi::lua::RunText("input = Input()"); + + wi::lua::RunText("MOUSE_BUTTON_LEFT = 1"); + wi::lua::RunText("MOUSE_BUTTON_RIGHT = 2"); + wi::lua::RunText("MOUSE_BUTTON_MIDDLE = 3"); + + wi::lua::RunText("KEYBOARD_BUTTON_UP = 4"); + wi::lua::RunText("KEYBOARD_BUTTON_DOWN = 5"); + wi::lua::RunText("KEYBOARD_BUTTON_LEFT = 6"); + wi::lua::RunText("KEYBOARD_BUTTON_RIGHT = 7"); + wi::lua::RunText("KEYBOARD_BUTTON_SPACE = 8"); + wi::lua::RunText("KEYBOARD_BUTTON_RSHIFT = 9"); + wi::lua::RunText("KEYBOARD_BUTTON_LSHIFT = 10"); + wi::lua::RunText("KEYBOARD_BUTTON_F1 = 11"); + wi::lua::RunText("KEYBOARD_BUTTON_F2 = 12"); + wi::lua::RunText("KEYBOARD_BUTTON_F3 = 13"); + wi::lua::RunText("KEYBOARD_BUTTON_F4 = 14"); + wi::lua::RunText("KEYBOARD_BUTTON_F5 = 15"); + wi::lua::RunText("KEYBOARD_BUTTON_F6 = 16"); + wi::lua::RunText("KEYBOARD_BUTTON_F7 = 17"); + wi::lua::RunText("KEYBOARD_BUTTON_F8 = 18"); + wi::lua::RunText("KEYBOARD_BUTTON_F9 = 19"); + wi::lua::RunText("KEYBOARD_BUTTON_F10 = 20"); + wi::lua::RunText("KEYBOARD_BUTTON_F11 = 21"); + wi::lua::RunText("KEYBOARD_BUTTON_F12 = 22"); + wi::lua::RunText("KEYBOARD_BUTTON_ENTER = 23"); + wi::lua::RunText("KEYBOARD_BUTTON_ESCAPE = 24"); + wi::lua::RunText("KEYBOARD_BUTTON_HOME = 25"); + wi::lua::RunText("KEYBOARD_BUTTON_RCONTROL = 26"); + wi::lua::RunText("KEYBOARD_BUTTON_LCONTROL = 27"); + wi::lua::RunText("KEYBOARD_BUTTON_DELETE = 28"); + wi::lua::RunText("KEYBOARD_BUTTON_BACK = 29"); + wi::lua::RunText("KEYBOARD_BUTTON_PAGEDOWN = 30"); + wi::lua::RunText("KEYBOARD_BUTTON_PAGEUP = 31"); + + wi::lua::RunText("GAMEPAD_BUTTON_UP = 257"); + wi::lua::RunText("GAMEPAD_BUTTON_LEFT = 258"); + wi::lua::RunText("GAMEPAD_BUTTON_DOWN = 259"); + wi::lua::RunText("GAMEPAD_BUTTON_RIGHT = 260"); + wi::lua::RunText("GAMEPAD_BUTTON_1 = 261"); + wi::lua::RunText("GAMEPAD_BUTTON_2 = 262"); + wi::lua::RunText("GAMEPAD_BUTTON_3 = 263"); + wi::lua::RunText("GAMEPAD_BUTTON_4 = 264"); + wi::lua::RunText("GAMEPAD_BUTTON_5 = 265"); + wi::lua::RunText("GAMEPAD_BUTTON_6 = 266"); + wi::lua::RunText("GAMEPAD_BUTTON_7 = 267"); + wi::lua::RunText("GAMEPAD_BUTTON_8 = 268"); + wi::lua::RunText("GAMEPAD_BUTTON_9 = 269"); + wi::lua::RunText("GAMEPAD_BUTTON_10 = 270"); + wi::lua::RunText("GAMEPAD_BUTTON_11 = 271"); + wi::lua::RunText("GAMEPAD_BUTTON_12 = 272"); + wi::lua::RunText("GAMEPAD_BUTTON_13 = 273"); + wi::lua::RunText("GAMEPAD_BUTTON_14 = 274"); + + //Analog + wi::lua::RunText("GAMEPAD_ANALOG_THUMBSTICK_L = 0"); + wi::lua::RunText("GAMEPAD_ANALOG_THUMBSTICK_R = 1"); + wi::lua::RunText("GAMEPAD_ANALOG_TRIGGER_L = 2"); + wi::lua::RunText("GAMEPAD_ANALOG_TRIGGER_R = 3"); + + //Touch + wi::lua::RunText("TOUCHSTATE_PRESSED = 0"); + wi::lua::RunText("TOUCHSTATE_RELEASED = 1"); + wi::lua::RunText("TOUCHSTATE_MOVED = 2"); + } + + Touch_BindLua::Bind(); + ControllerFeedback_BindLua::Bind(); + } + + + + + + + + const char Touch_BindLua::className[] = "Touch"; + + Luna::FunctionType Touch_BindLua::methods[] = { + lunamethod(Touch_BindLua, GetState), + lunamethod(Touch_BindLua, GetPos), + { NULL, NULL } + }; + Luna::PropertyType Touch_BindLua::properties[] = { + { NULL, NULL } + }; + + int Touch_BindLua::GetState(lua_State* L) + { + wi::lua::SSetInt(L, (int)touch.state); + return 1; + } + int Touch_BindLua::GetPos(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat2(&touch.pos))); + return 1; + } + + void Touch_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + + + + + + + + const char ControllerFeedback_BindLua::className[] = "ControllerFeedback"; + + Luna::FunctionType ControllerFeedback_BindLua::methods[] = { + lunamethod(ControllerFeedback_BindLua, SetVibrationRight), + lunamethod(ControllerFeedback_BindLua, SetVibrationLeft), + lunamethod(ControllerFeedback_BindLua, SetLEDColor), + { NULL, NULL } + }; + Luna::PropertyType ControllerFeedback_BindLua::properties[] = { + { NULL, NULL } + }; + + int ControllerFeedback_BindLua::SetVibrationLeft(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + feedback.vibration_left = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetControllerFeedback(ControllerFeedback feedback, opt int playerindex = 0) first argument is not a ControllerFeedback!"); + wi::lua::SError(L, "SetVibrationLeft(float value) not enough arguments!"); } + return 0; } - else - wiLua::SError(L, "SetControllerFeedback(ControllerFeedback feedback, opt int playerindex = 0) not enough arguments!"); - return 0; -} - -void wiInput_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) + int ControllerFeedback_BindLua::SetVibrationRight(lua_State* L) { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - wiLua::RunText("input = Input()"); - - wiLua::RunText("MOUSE_BUTTON_LEFT = 1"); - wiLua::RunText("MOUSE_BUTTON_RIGHT = 2"); - wiLua::RunText("MOUSE_BUTTON_MIDDLE = 3"); - - wiLua::RunText("KEYBOARD_BUTTON_UP = 4"); - wiLua::RunText("KEYBOARD_BUTTON_DOWN = 5"); - wiLua::RunText("KEYBOARD_BUTTON_LEFT = 6"); - wiLua::RunText("KEYBOARD_BUTTON_RIGHT = 7"); - wiLua::RunText("KEYBOARD_BUTTON_SPACE = 8"); - wiLua::RunText("KEYBOARD_BUTTON_RSHIFT = 9"); - wiLua::RunText("KEYBOARD_BUTTON_LSHIFT = 10"); - wiLua::RunText("KEYBOARD_BUTTON_F1 = 11"); - wiLua::RunText("KEYBOARD_BUTTON_F2 = 12"); - wiLua::RunText("KEYBOARD_BUTTON_F3 = 13"); - wiLua::RunText("KEYBOARD_BUTTON_F4 = 14"); - wiLua::RunText("KEYBOARD_BUTTON_F5 = 15"); - wiLua::RunText("KEYBOARD_BUTTON_F6 = 16"); - wiLua::RunText("KEYBOARD_BUTTON_F7 = 17"); - wiLua::RunText("KEYBOARD_BUTTON_F8 = 18"); - wiLua::RunText("KEYBOARD_BUTTON_F9 = 19"); - wiLua::RunText("KEYBOARD_BUTTON_F10 = 20"); - wiLua::RunText("KEYBOARD_BUTTON_F11 = 21"); - wiLua::RunText("KEYBOARD_BUTTON_F12 = 22"); - wiLua::RunText("KEYBOARD_BUTTON_ENTER = 23"); - wiLua::RunText("KEYBOARD_BUTTON_ESCAPE = 24"); - wiLua::RunText("KEYBOARD_BUTTON_HOME = 25"); - wiLua::RunText("KEYBOARD_BUTTON_RCONTROL = 26"); - wiLua::RunText("KEYBOARD_BUTTON_LCONTROL = 27"); - wiLua::RunText("KEYBOARD_BUTTON_DELETE = 28"); - wiLua::RunText("KEYBOARD_BUTTON_BACK = 29"); - wiLua::RunText("KEYBOARD_BUTTON_PAGEDOWN = 30"); - wiLua::RunText("KEYBOARD_BUTTON_PAGEUP = 31"); - - wiLua::RunText("GAMEPAD_BUTTON_UP = 257"); - wiLua::RunText("GAMEPAD_BUTTON_LEFT = 258"); - wiLua::RunText("GAMEPAD_BUTTON_DOWN = 259"); - wiLua::RunText("GAMEPAD_BUTTON_RIGHT = 260"); - wiLua::RunText("GAMEPAD_BUTTON_1 = 261"); - wiLua::RunText("GAMEPAD_BUTTON_2 = 262"); - wiLua::RunText("GAMEPAD_BUTTON_3 = 263"); - wiLua::RunText("GAMEPAD_BUTTON_4 = 264"); - wiLua::RunText("GAMEPAD_BUTTON_5 = 265"); - wiLua::RunText("GAMEPAD_BUTTON_6 = 266"); - wiLua::RunText("GAMEPAD_BUTTON_7 = 267"); - wiLua::RunText("GAMEPAD_BUTTON_8 = 268"); - wiLua::RunText("GAMEPAD_BUTTON_9 = 269"); - wiLua::RunText("GAMEPAD_BUTTON_10 = 270"); - wiLua::RunText("GAMEPAD_BUTTON_11 = 271"); - wiLua::RunText("GAMEPAD_BUTTON_12 = 272"); - wiLua::RunText("GAMEPAD_BUTTON_13 = 273"); - wiLua::RunText("GAMEPAD_BUTTON_14 = 274"); - - //Analog - wiLua::RunText("GAMEPAD_ANALOG_THUMBSTICK_L = 0"); - wiLua::RunText("GAMEPAD_ANALOG_THUMBSTICK_R = 1"); - wiLua::RunText("GAMEPAD_ANALOG_TRIGGER_L = 2"); - wiLua::RunText("GAMEPAD_ANALOG_TRIGGER_R = 3"); - - //Touch - wiLua::RunText("TOUCHSTATE_PRESSED = 0"); - wiLua::RunText("TOUCHSTATE_RELEASED = 1"); - wiLua::RunText("TOUCHSTATE_MOVED = 2"); - } - - Touch_BindLua::Bind(); - ControllerFeedback_BindLua::Bind(); -} - - - - - - - -const char Touch_BindLua::className[] = "Touch"; - -Luna::FunctionType Touch_BindLua::methods[] = { - lunamethod(Touch_BindLua, GetState), - lunamethod(Touch_BindLua, GetPos), - { NULL, NULL } -}; -Luna::PropertyType Touch_BindLua::properties[] = { - { NULL, NULL } -}; - -int Touch_BindLua::GetState(lua_State* L) -{ - wiLua::SSetInt(L, (int)touch.state); - return 1; -} -int Touch_BindLua::GetPos(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMLoadFloat2(&touch.pos))); - return 1; -} - -void Touch_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} - - - - - - - -const char ControllerFeedback_BindLua::className[] = "ControllerFeedback"; - -Luna::FunctionType ControllerFeedback_BindLua::methods[] = { - lunamethod(ControllerFeedback_BindLua, SetVibrationRight), - lunamethod(ControllerFeedback_BindLua, SetVibrationLeft), - lunamethod(ControllerFeedback_BindLua, SetLEDColor), - { NULL, NULL } -}; -Luna::PropertyType ControllerFeedback_BindLua::properties[] = { - { NULL, NULL } -}; - -int ControllerFeedback_BindLua::SetVibrationLeft(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - feedback.vibration_left = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetVibrationLeft(float value) not enough arguments!"); - } - return 0; -} -int ControllerFeedback_BindLua::SetVibrationRight(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - feedback.vibration_right = wiLua::SGetFloat(L, 1); - } - else - { - wiLua::SError(L, "SetVibrationRight(float value) not enough arguments!"); - } - return 0; -} -int ControllerFeedback_BindLua::SetLEDColor(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* vec = Luna::lightcheck(L, 1); - if (vec != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - feedback.led_color = wiColor::fromFloat4(*vec); + feedback.vibration_right = wi::lua::SGetFloat(L, 1); } else { - feedback.led_color.rgba = wiLua::SGetInt(L, 1); + wi::lua::SError(L, "SetVibrationRight(float value) not enough arguments!"); + } + return 0; + } + int ControllerFeedback_BindLua::SetLEDColor(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + feedback.led_color = wi::Color::fromFloat4(*vec); + } + else + { + feedback.led_color.rgba = wi::lua::SGetInt(L, 1); + } + } + else + { + wi::lua::SError(L, "SetLEDColor(int hexcolor) not enough arguments!"); + } + return 0; + } + + void ControllerFeedback_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); } } - else - { - wiLua::SError(L, "SetLEDColor(int hexcolor) not enough arguments!"); - } - return 0; -} -void ControllerFeedback_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } } diff --git a/WickedEngine/wiInput_BindLua.h b/WickedEngine/wiInput_BindLua.h index 4033fac93..6fe89b24d 100644 --- a/WickedEngine/wiInput_BindLua.h +++ b/WickedEngine/wiInput_BindLua.h @@ -3,60 +3,65 @@ #include "wiLuna.h" #include "wiInput.h" -class wiInput_BindLua +namespace wi::lua { -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - wiInput_BindLua(lua_State* L){} + class Input_BindLua + { + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - int Down(lua_State* L); - int Press(lua_State* L); - int Hold(lua_State* L); - int GetPointer(lua_State* L); - int SetPointer(lua_State* L); - int GetPointerDelta(lua_State* L); - int HidePointer(lua_State* L); - int GetAnalog(lua_State* L); - int GetTouches(lua_State* L); - int SetControllerFeedback(lua_State* L); + Input_BindLua(lua_State* L) {} - static void Bind(); -}; + int Down(lua_State* L); + int Press(lua_State* L); + int Hold(lua_State* L); + int GetPointer(lua_State* L); + int SetPointer(lua_State* L); + int GetPointerDelta(lua_State* L); + int HidePointer(lua_State* L); + int GetAnalog(lua_State* L); + int GetTouches(lua_State* L); + int SetControllerFeedback(lua_State* L); -class Touch_BindLua -{ -public: - wiInput::Touch touch; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static void Bind(); + }; - Touch_BindLua(lua_State* L) {} - Touch_BindLua(const wiInput::Touch& touch) :touch(touch) {} + class Touch_BindLua + { + public: + wi::input::Touch touch; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - int GetState(lua_State* L); - int GetPos(lua_State* L); + Touch_BindLua(lua_State* L) {} + Touch_BindLua(const wi::input::Touch& touch) :touch(touch) {} - static void Bind(); -}; + int GetState(lua_State* L); + int GetPos(lua_State* L); -class ControllerFeedback_BindLua -{ -public: - wiInput::ControllerFeedback feedback; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static void Bind(); + }; - ControllerFeedback_BindLua(lua_State* L) {} - ControllerFeedback_BindLua(const wiInput::ControllerFeedback& feedback) :feedback(feedback) {} + class ControllerFeedback_BindLua + { + public: + wi::input::ControllerFeedback feedback; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - int SetVibrationLeft(lua_State* L); - int SetVibrationRight(lua_State* L); - int SetLEDColor(lua_State* L); + ControllerFeedback_BindLua(lua_State* L) {} + ControllerFeedback_BindLua(const wi::input::ControllerFeedback& feedback) :feedback(feedback) {} - static void Bind(); -}; + int SetVibrationLeft(lua_State* L); + int SetVibrationRight(lua_State* L); + int SetLEDColor(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiIntersect.cpp b/WickedEngine/wiIntersect.cpp deleted file mode 100644 index 3ef4c0408..000000000 --- a/WickedEngine/wiIntersect.cpp +++ /dev/null @@ -1,400 +0,0 @@ -#include "wiIntersect.h" - -void AABB::createFromHalfWidth(const XMFLOAT3& center, const XMFLOAT3& halfwidth) -{ - _min = XMFLOAT3(center.x - halfwidth.x, center.y - halfwidth.y, center.z - halfwidth.z); - _max = XMFLOAT3(center.x + halfwidth.x, center.y + halfwidth.y, center.z + halfwidth.z); -} -AABB AABB::transform(const XMMATRIX& mat) const -{ - XMFLOAT3 corners[8]; - for (int i = 0; i < 8; ++i) - { - XMFLOAT3 C = corner(i); - XMVECTOR point = XMVector3Transform(XMLoadFloat3(&C), mat); - XMStoreFloat3(&corners[i], point); - } - XMFLOAT3 min = corners[0]; - XMFLOAT3 max = corners[6]; - for (int i = 0; i < 8; ++i) - { - const XMFLOAT3& p = corners[i]; - - if (p.x < min.x) min.x = p.x; - if (p.y < min.y) min.y = p.y; - if (p.z < min.z) min.z = p.z; - - if (p.x > max.x) max.x = p.x; - if (p.y > max.y) max.y = p.y; - if (p.z > max.z) max.z = p.z; - } - - return AABB(min, max); -} -AABB AABB::transform(const XMFLOAT4X4& mat) const -{ - return transform(XMLoadFloat4x4(&mat)); -} -XMFLOAT3 AABB::getCenter() const -{ - return XMFLOAT3((_min.x + _max.x)*0.5f, (_min.y + _max.y)*0.5f, (_min.z + _max.z)*0.5f); -} -XMFLOAT3 AABB::getHalfWidth() const -{ - XMFLOAT3 center = getCenter(); - return XMFLOAT3(abs(_max.x - center.x), abs(_max.y - center.y), abs(_max.z - center.z)); -} -XMMATRIX AABB::AABB::getAsBoxMatrix() const -{ - XMFLOAT3 ext = getHalfWidth(); - XMMATRIX sca = XMMatrixScaling(ext.x, ext.y, ext.z); - XMFLOAT3 pos = getCenter(); - XMMATRIX tra = XMMatrixTranslation(pos.x, pos.y, pos.z); - - return sca*tra; -} -float AABB::getArea() const -{ - XMFLOAT3 _min = getMin(); - XMFLOAT3 _max = getMax(); - return (_max.x - _min.x)*(_max.y - _min.y)*(_max.z - _min.z); -} -float AABB::getRadius() const { - XMFLOAT3 abc = getHalfWidth(); - return std::max(std::max(abc.x, abc.y), abc.z); -} -AABB::INTERSECTION_TYPE AABB::intersects(const AABB& b) const { - - XMFLOAT3 aMin = getMin(), aMax = getMax(); - XMFLOAT3 bMin = b.getMin(), bMax = b.getMax(); - - if (bMin.x >= aMin.x && bMax.x <= aMax.x && - bMin.y >= aMin.y && bMax.y <= aMax.y && - bMin.z >= aMin.z && bMax.z <= aMax.z) - { - return INSIDE; - } - - if (aMax.x < bMin.x || aMin.x > bMax.x) - return OUTSIDE; - if (aMax.y < bMin.y || aMin.y > bMax.y) - return OUTSIDE; - if (aMax.z < bMin.z || aMin.z > bMax.z) - return OUTSIDE; - - return INTERSECTS; -} -AABB::INTERSECTION_TYPE AABB::intersects2D(const AABB& b) const { - - XMFLOAT3 aMin = getMin(), aMax = getMax(); - XMFLOAT3 bMin = b.getMin(), bMax = b.getMax(); - - if (bMin.x >= aMin.x && bMax.x <= aMax.x && - bMin.y >= aMin.y && bMax.y <= aMax.y) - { - return INSIDE; - } - - if (aMax.x < bMin.x || aMin.x > bMax.x) - return OUTSIDE; - if (aMax.y < bMin.y || aMin.y > bMax.y) - return OUTSIDE; - - return INTERSECTS; -} -bool AABB::intersects(const XMFLOAT3& p) const { - XMFLOAT3 max = getMax(); - XMFLOAT3 min = getMin(); - if (p.x>max.x) return false; - if (p.xmax.y) return false; - if (p.ymax.z) return false; - if (p.z= tmin; -} -bool AABB::intersects(const SPHERE& sphere) const -{ - return sphere.intersects(*this); -} -bool AABB::intersects(const BoundingFrustum& frustum) const -{ - BoundingBox bb = BoundingBox(getCenter(), getHalfWidth()); - bool intersection = frustum.Intersects(bb); - return intersection; -} -AABB AABB::operator* (float a) -{ - XMFLOAT3 min = getMin(); - XMFLOAT3 max = getMax(); - min.x *= a; - min.y *= a; - min.z *= a; - max.x *= a; - max.y *= a; - max.z *= a; - return AABB(min, max); -} -AABB AABB::Merge(const AABB& a, const AABB& b) -{ - return AABB(wiMath::Min(a.getMin(), b.getMin()), wiMath::Max(a.getMax(), b.getMax())); -} -void AABB::Serialize(wiArchive& archive, wiECS::EntitySerializer& seri) -{ - if (archive.IsReadMode()) - { - archive >> _min; - archive >> _max; - - if (archive.GetVersion() >= 69) - { - archive >> layerMask; - archive >> userdata; - } - } - else - { - archive << _min; - archive << _max; - - if (archive.GetVersion() >= 69) - { - archive << layerMask; - archive << userdata; - } - } -} - - - - - - -bool SPHERE::intersects(const AABB& b) const { - XMFLOAT3 min = b.getMin(); - XMFLOAT3 max = b.getMax(); - XMFLOAT3 closestPointInAabb = wiMath::Min(wiMath::Max(center, min), max); - double distanceSquared = wiMath::Distance(closestPointInAabb, center); - return distanceSquared < radius; -} -bool SPHERE::intersects(const SPHERE& b)const { - return wiMath::Distance(center, b.center) <= radius + b.radius; -} -bool SPHERE::intersects(const RAY& b) const { - XMVECTOR o = XMLoadFloat3(&b.origin); - XMVECTOR r = XMLoadFloat3(&b.direction); - XMVECTOR dist = XMVector3LinePointDistance(o, o + r, XMLoadFloat3(¢er)); - return XMVectorGetX(dist) <= radius; -} - - - -bool CAPSULE::intersects(const CAPSULE& other, XMFLOAT3& position, XMFLOAT3& incident_normal, float& penetration_depth) const -{ - if(getAABB().intersects(other.getAABB()) == AABB::INTERSECTION_TYPE::OUTSIDE) - return false; - - XMVECTOR a_Base = XMLoadFloat3(&base); - XMVECTOR a_Tip = XMLoadFloat3(&tip); - XMVECTOR a_Radius = XMVectorReplicate(radius); - XMVECTOR a_Normal = XMVector3Normalize(a_Tip - a_Base); - XMVECTOR a_LineEndOffset = a_Normal * a_Radius; - XMVECTOR a_A = a_Base + a_LineEndOffset; - XMVECTOR a_B = a_Tip - a_LineEndOffset; - - XMVECTOR b_Base = XMLoadFloat3(&other.base); - XMVECTOR b_Tip = XMLoadFloat3(&other.tip); - XMVECTOR b_Radius = XMVectorReplicate(other.radius); - XMVECTOR b_Normal = XMVector3Normalize(b_Tip - b_Base); - XMVECTOR b_LineEndOffset = b_Normal * b_Radius; - XMVECTOR b_A = b_Base + b_LineEndOffset; - XMVECTOR b_B = b_Tip - b_LineEndOffset; - - // Vectors between line endpoints: - XMVECTOR v0 = b_A - a_A; - XMVECTOR v1 = b_B - a_A; - XMVECTOR v2 = b_A - a_B; - XMVECTOR v3 = b_B - a_B; - - // Distances (squared) between line endpoints: - float d0 = XMVectorGetX(XMVector3LengthSq(v0)); - float d1 = XMVectorGetX(XMVector3LengthSq(v1)); - float d2 = XMVectorGetX(XMVector3LengthSq(v2)); - float d3 = XMVectorGetX(XMVector3LengthSq(v3)); - - // Select best potential endpoint on capsule A: - XMVECTOR bestA; - if (d2 < d0 || d2 < d1 || d3 < d0 || d3 < d1) - { - bestA = a_B; - } - else - { - bestA = a_A; - } - - // Select point on capsule B line segment nearest to best potential endpoint on A capsule: - XMVECTOR bestB = wiMath::ClosestPointOnLineSegment(b_A, b_B, bestA); - - // Now do the same for capsule A segment: - bestA = wiMath::ClosestPointOnLineSegment(a_A, a_B, bestB); - - // Finally, sphere collision: - XMVECTOR N = bestA - bestB; - XMVECTOR len = XMVector3Length(N); - N /= len; - float dist = XMVectorGetX(len); - - XMStoreFloat3(&position, bestA - N * radius); - XMStoreFloat3(&incident_normal, N); - penetration_depth = radius + other.radius - dist; - - return penetration_depth > 0; -} - - - -bool RAY::intersects(const AABB& b) const { - return b.intersects(*this); -} -bool RAY::intersects(const SPHERE& b) const { - return b.intersects(*this); -} - - - - -void Frustum::Create(const XMMATRIX& viewProjection) -{ - // We are interested in columns of the matrix, so transpose because we can access only rows: - const XMMATRIX mat = XMMatrixTranspose(viewProjection); - - // Near plane: - XMStoreFloat4(&planes[0], XMPlaneNormalize(mat.r[2])); - - // Far plane: - XMStoreFloat4(&planes[1], XMPlaneNormalize(mat.r[3] - mat.r[2])); - - // Left plane: - XMStoreFloat4(&planes[2], XMPlaneNormalize(mat.r[3] + mat.r[0])); - - // Right plane: - XMStoreFloat4(&planes[3], XMPlaneNormalize(mat.r[3] - mat.r[0])); - - // Top plane: - XMStoreFloat4(&planes[4], XMPlaneNormalize(mat.r[3] - mat.r[1])); - - // Bottom plane: - XMStoreFloat4(&planes[5], XMPlaneNormalize(mat.r[3] + mat.r[1])); -} - -bool Frustum::CheckPoint(const XMFLOAT3& point) const -{ - XMVECTOR p = XMLoadFloat3(&point); - for (short i = 0; i < 6; i++) - { - if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[i]), p)) < 0.0f) - { - return false; - } - } - - return true; -} -bool Frustum::CheckSphere(const XMFLOAT3& center, float radius) const -{ - int i; - XMVECTOR c = XMLoadFloat3(¢er); - for (i = 0; i < 6; i++) - { - if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[i]), c)) < -radius) - { - return false; - } - } - - return true; -} -Frustum::BoxFrustumIntersect Frustum::CheckBox(const AABB& box) const -{ - int iTotalIn = 0; - for (int p = 0; p < 6; ++p) - { - - int iInCount = 8; - int iPtIn = 1; - - for (int i = 0; i < 8; ++i) - { - XMFLOAT3 C = box.corner(i); - if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[p]), XMLoadFloat3(&C))) < 0.0f) - { - iPtIn = 0; - --iInCount; - } - } - if (iInCount == 0) - return BOX_FRUSTUM_OUTSIDE; - iTotalIn += iPtIn; - } - if (iTotalIn == 6) - return(BOX_FRUSTUM_INSIDE); - return(BOX_FRUSTUM_INTERSECTS); -} -bool Frustum::CheckBoxFast(const AABB& box) const -{ - XMVECTOR max = XMLoadFloat3(&box._max); - XMVECTOR min = XMLoadFloat3(&box._min); - XMVECTOR zero = XMVectorZero(); - for (size_t p = 0; p < 6; ++p) - { - auto lt = XMVectorLess(XMLoadFloat4(&planes[p]), zero); - auto furthestFromPlane = XMVectorSelect(max, min, lt); - if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[p]), furthestFromPlane)) < 0.0f) - { - return false; - } - } - return true; -} - -const XMFLOAT4& Frustum::getNearPlane() const { return planes[0]; } -const XMFLOAT4& Frustum::getFarPlane() const { return planes[1]; } -const XMFLOAT4& Frustum::getLeftPlane() const { return planes[2]; } -const XMFLOAT4& Frustum::getRightPlane() const { return planes[3]; } -const XMFLOAT4& Frustum::getTopPlane() const { return planes[4]; } -const XMFLOAT4& Frustum::getBottomPlane() const { return planes[5]; } - - - -bool Hitbox2D::intersects(const Hitbox2D& b) const -{ - return wiMath::Collision2D(pos, siz, b.pos, b.siz); -} diff --git a/WickedEngine/wiIntersect.h b/WickedEngine/wiIntersect.h deleted file mode 100644 index deb5c16dc..000000000 --- a/WickedEngine/wiIntersect.h +++ /dev/null @@ -1,157 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiArchive.h" -#include "wiMath.h" -#include "wiECS.h" - -#include - -struct SPHERE; -struct RAY; -struct AABB; - - -struct AABB -{ - enum INTERSECTION_TYPE - { - OUTSIDE, - INTERSECTS, - INSIDE, - }; - - XMFLOAT3 _min; - uint32_t layerMask = ~0u; - XMFLOAT3 _max; - uint32_t userdata = 0; - - AABB( - const XMFLOAT3& _min = XMFLOAT3(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()), - const XMFLOAT3& _max = XMFLOAT3(std::numeric_limits::lowest(), std::numeric_limits::lowest(), std::numeric_limits::lowest()) - ) : _min(_min), _max(_max) {} - void createFromHalfWidth(const XMFLOAT3& center, const XMFLOAT3& halfwidth); - AABB transform(const XMMATRIX& mat) const; - AABB transform(const XMFLOAT4X4& mat) const; - XMFLOAT3 getCenter() const; - XMFLOAT3 getHalfWidth() const; - XMMATRIX getAsBoxMatrix() const; - float getArea() const; - float getRadius() const; - INTERSECTION_TYPE intersects2D(const AABB& b) const; - INTERSECTION_TYPE intersects(const AABB& b) const; - bool intersects(const XMFLOAT3& p) const; - bool intersects(const RAY& ray) const; - bool intersects(const SPHERE& sphere) const; - bool intersects(const BoundingFrustum& frustum) const; - AABB operator* (float a); - static AABB Merge(const AABB& a, const AABB& b); - - inline XMFLOAT3 getMin() const { return _min; } - inline XMFLOAT3 getMax() const { return _max; } - inline XMFLOAT3 corner(int index) const - { - switch (index) - { - case 0: return _min; - case 1: return XMFLOAT3(_min.x, _max.y, _min.z); - case 2: return XMFLOAT3(_min.x, _max.y, _max.z); - case 3: return XMFLOAT3(_min.x, _min.y, _max.z); - case 4: return XMFLOAT3(_max.x, _min.y, _min.z); - case 5: return XMFLOAT3(_max.x, _max.y, _min.z); - case 6: return _max; - case 7: return XMFLOAT3(_max.x, _min.y, _max.z); - } - assert(0); - return XMFLOAT3(0, 0, 0); - } - - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); -}; -struct SPHERE -{ - XMFLOAT3 center; - float radius; - SPHERE() :center(XMFLOAT3(0, 0, 0)), radius(0) {} - SPHERE(const XMFLOAT3& c, float r) :center(c), radius(r) {} - bool intersects(const AABB& b) const; - bool intersects(const SPHERE& b) const; - bool intersects(const RAY& b) const; -}; -struct CAPSULE -{ - XMFLOAT3 base = XMFLOAT3(0, 0, 0); - XMFLOAT3 tip = XMFLOAT3(0, 0, 0); - float radius = 0; - CAPSULE() = default; - CAPSULE(const XMFLOAT3& base, const XMFLOAT3& tip, float radius) :base(base), tip(tip), radius(radius) {} - CAPSULE(const SPHERE& sphere, float height) : - base(XMFLOAT3(sphere.center.x, sphere.center.y - sphere.radius, sphere.center.z)), - tip(XMFLOAT3(base.x, base.y + height, base.z)), - radius(sphere.radius) - {} - inline AABB getAABB() const - { - XMFLOAT3 halfWidth = XMFLOAT3(radius, radius, radius); - AABB base_aabb; - base_aabb.createFromHalfWidth(base, halfWidth); - AABB tip_aabb; - tip_aabb.createFromHalfWidth(tip, halfWidth); - return AABB::Merge(base_aabb, tip_aabb); - } - bool intersects(const CAPSULE& b, XMFLOAT3& position, XMFLOAT3& incident_normal, float& penetration_depth) const; -}; -struct RAY -{ - XMFLOAT3 origin, direction, direction_inverse; - - RAY(const XMFLOAT3& newOrigin = XMFLOAT3(0, 0, 0), const XMFLOAT3& newDirection = XMFLOAT3(0, 0, 1)) : RAY(XMLoadFloat3(&newOrigin), XMLoadFloat3(&newDirection)) {} - RAY(const XMVECTOR& newOrigin, const XMVECTOR& newDirection) { - XMStoreFloat3(&origin, newOrigin); - XMStoreFloat3(&direction, newDirection); - XMStoreFloat3(&direction_inverse, XMVectorDivide(XMVectorReplicate(1.0f), newDirection)); - } - bool intersects(const AABB& b) const; - bool intersects(const SPHERE& b) const; -}; - -struct Frustum -{ - XMFLOAT4 planes[6]; - - void Create(const XMMATRIX& viewProjection); - - bool CheckPoint(const XMFLOAT3&) const; - bool CheckSphere(const XMFLOAT3&, float) const; - - enum BoxFrustumIntersect - { - BOX_FRUSTUM_OUTSIDE, - BOX_FRUSTUM_INTERSECTS, - BOX_FRUSTUM_INSIDE, - }; - BoxFrustumIntersect CheckBox(const AABB& box) const; - bool CheckBoxFast(const AABB& box) const; - - const XMFLOAT4& getNearPlane() const; - const XMFLOAT4& getFarPlane() const; - const XMFLOAT4& getLeftPlane() const; - const XMFLOAT4& getRightPlane() const; - const XMFLOAT4& getTopPlane() const; - const XMFLOAT4& getBottomPlane() const; -}; - - -class Hitbox2D -{ -public: - XMFLOAT2 pos; - XMFLOAT2 siz; - - Hitbox2D() :pos(XMFLOAT2(0, 0)), siz(XMFLOAT2(0, 0)) {} - Hitbox2D(const XMFLOAT2& newPos, const XMFLOAT2 newSiz) :pos(newPos), siz(newSiz) {} - ~Hitbox2D() {}; - - bool intersects(const Hitbox2D& b) const; -}; - - diff --git a/WickedEngine/wiJobSystem.cpp b/WickedEngine/wiJobSystem.cpp index c59e0962d..b0051fa8c 100644 --- a/WickedEngine/wiJobSystem.cpp +++ b/WickedEngine/wiJobSystem.cpp @@ -1,7 +1,6 @@ #include "wiJobSystem.h" #include "wiSpinLock.h" -#include "wiBackLog.h" -#include "wiAllocator.h" +#include "wiBacklog.h" #include "wiPlatform.h" #include "wiTimer.h" @@ -14,12 +13,12 @@ #include #endif -namespace wiJobSystem +namespace wi::jobsystem { struct Job { context* ctx; - std::function task; + std::function task; uint32_t groupID; uint32_t groupJobOffset; uint32_t groupJobEnd; @@ -32,6 +31,53 @@ namespace wiJobSystem std::mutex wakeMutex; }; + // Fixed size very simple thread safe ring buffer + template + class ThreadSafeRingBuffer + { + public: + // Push an item to the end if there is free space + // Returns true if succesful + // Returns false if there is not enough space + inline bool push_back(const T& item) + { + bool result = false; + lock.lock(); + size_t next = (head + 1) % capacity; + if (next != tail) + { + data[head] = item; + head = next; + result = true; + } + lock.unlock(); + return result; + } + + // Get an item if there are any + // Returns true if succesful + // Returns false if there are no items + inline bool pop_front(T& item) + { + bool result = false; + lock.lock(); + if (tail != head) + { + item = data[tail]; + tail = (tail + 1) % capacity; + result = true; + } + lock.unlock(); + return result; + } + + private: + T data[capacity]; + size_t head = 0; + size_t tail = 0; + wi::SpinLock lock; + }; + // This structure is responsible to stop worker thread loops. // Once this is destroyed, worker threads will be woken up and end their loops. // This is to workaround a problem on Linux, where threads still running their loops don't let the main thread to exit @@ -40,7 +86,7 @@ namespace wiJobSystem uint32_t numCores = 0; uint32_t numThreads = 0; std::shared_ptr worker_state = std::make_shared(); // kept alive by both threads and internal_state - wiAllocator::ThreadSafeRingBuffer jobQueue; + ThreadSafeRingBuffer jobQueue; ~InternalState() { worker_state->alive.store(false); @@ -54,7 +100,7 @@ namespace wiJobSystem Job job; if (internal_state.jobQueue.pop_front(job)) { - wiJobArgs args; + JobArgs args; args.groupID = job.groupID; if (job.sharedmemory_size > 0) { @@ -82,7 +128,7 @@ namespace wiJobSystem void Initialize() { - wiTimer timer; + wi::Timer timer; // Retrieve the number of hardware threads in this system: internal_state.numCores = std::thread::hardware_concurrency(); @@ -121,7 +167,7 @@ namespace wiJobSystem //assert(priority_result != 0); // Name the thread: - std::wstring wthreadname = L"wiJobSystem_" + std::to_wstring(threadID); + std::wstring wthreadname = L"wi::jobsystem_" + std::to_wstring(threadID); HRESULT hr = SetThreadDescription(handle, wthreadname.c_str()); assert(SUCCEEDED(hr)); #elif defined(PLATFORM_LINUX) @@ -139,7 +185,7 @@ namespace wiJobSystem handle_error_en(ret, std::string(" pthread_setaffinity_np[" + std::to_string(threadID) + ']').c_str()); // Name the thread - std::string thread_name = "wiJobSystem_" + std::to_string(threadID); + std::string thread_name = "wi::jobsystem_" + std::to_string(threadID); ret = pthread_setname_np(worker.native_handle(), thread_name.c_str()); if(ret != 0) handle_error_en(ret, std::string(" pthread_setname_np[" + std::to_string(threadID) + ']').c_str()); @@ -149,7 +195,7 @@ namespace wiJobSystem worker.detach(); } - wiBackLog::post("wiJobSystem Initialized with [" + std::to_string(internal_state.numCores) + " cores] [" + std::to_string(internal_state.numThreads) + " threads] (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::jobsystem Initialized with [" + std::to_string(internal_state.numCores) + " cores] [" + std::to_string(internal_state.numThreads) + " threads] (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } uint32_t GetThreadCount() @@ -157,7 +203,7 @@ namespace wiJobSystem return internal_state.numThreads; } - void Execute(context& ctx, const std::function& task) + void Execute(context& ctx, const std::function& task) { // Context state is updated: ctx.counter.fetch_add(1); @@ -177,7 +223,7 @@ namespace wiJobSystem internal_state.worker_state->wakeCondition.notify_one(); } - void Dispatch(context& ctx, uint32_t jobCount, uint32_t groupSize, const std::function& task, size_t sharedmemory_size) + void Dispatch(context& ctx, uint32_t jobCount, uint32_t groupSize, const std::function& task, size_t sharedmemory_size) { if (jobCount == 0 || groupSize == 0) { diff --git a/WickedEngine/wiJobSystem.h b/WickedEngine/wiJobSystem.h index 209c09214..c365ec6c3 100644 --- a/WickedEngine/wiJobSystem.h +++ b/WickedEngine/wiJobSystem.h @@ -3,18 +3,18 @@ #include #include -struct wiJobArgs +namespace wi::jobsystem { - uint32_t jobIndex; // job index relative to dispatch (like SV_DispatchThreadID in HLSL) - uint32_t groupID; // group index relative to dispatch (like SV_GroupID in HLSL) - uint32_t groupIndex; // job index relative to group (like SV_GroupIndex in HLSL) - bool isFirstJobInGroup; // is the current job the first one in the group? - bool isLastJobInGroup; // is the current job the last one in the group? - void* sharedmemory; // stack memory shared within the current group (jobs within a group execute serially) -}; + struct JobArgs + { + uint32_t jobIndex; // job index relative to dispatch (like SV_DispatchThreadID in HLSL) + uint32_t groupID; // group index relative to dispatch (like SV_GroupID in HLSL) + uint32_t groupIndex; // job index relative to group (like SV_GroupIndex in HLSL) + bool isFirstJobInGroup; // is the current job the first one in the group? + bool isLastJobInGroup; // is the current job the last one in the group? + void* sharedmemory; // stack memory shared within the current group (jobs within a group execute serially) + }; -namespace wiJobSystem -{ void Initialize(); uint32_t GetThreadCount(); @@ -26,13 +26,13 @@ namespace wiJobSystem }; // Add a task to execute asynchronously. Any idle thread will execute this. - void Execute(context& ctx, const std::function& task); + void Execute(context& ctx, const std::function& task); // Divide a task onto multiple jobs and execute in parallel. // jobCount : how many jobs to generate for this task. // groupSize : how many jobs to execute per thread. Jobs inside a group execute serially. It might be worth to increase for small jobs - // task : receives a wiJobArgs as parameter - void Dispatch(context& ctx, uint32_t jobCount, uint32_t groupSize, const std::function& task, size_t sharedmemory_size = 0); + // task : receives a JobArgs as parameter + void Dispatch(context& ctx, uint32_t jobCount, uint32_t groupSize, const std::function& task, size_t sharedmemory_size = 0); // Returns the amount of job groups that will be created for a set number of jobs and group size uint32_t DispatchGroupCount(uint32_t jobCount, uint32_t groupSize); diff --git a/WickedEngine/wiLoadingScreen.cpp b/WickedEngine/wiLoadingScreen.cpp new file mode 100644 index 000000000..c201ef578 --- /dev/null +++ b/WickedEngine/wiLoadingScreen.cpp @@ -0,0 +1,60 @@ +#include "wiLoadingScreen.h" +#include "wiApplication.h" + +#include + +namespace wi +{ + + bool LoadingScreen::isActive() + { + return wi::jobsystem::IsBusy(ctx); + } + + void LoadingScreen::addLoadingFunction(std::function loadingFunction) + { + if (loadingFunction != nullptr) + { + tasks.push_back(loadingFunction); + } + } + + void LoadingScreen::addLoadingComponent(RenderPath* component, Application* main, float fadeSeconds, wi::Color fadeColor) + { + addLoadingFunction([=](wi::jobsystem::JobArgs args) { + component->Load(); + }); + onFinished([=] { + main->ActivatePath(component, fadeSeconds, fadeColor); + }); + } + + void LoadingScreen::onFinished(std::function finishFunction) + { + if (finishFunction != nullptr) + finish = finishFunction; + } + + void LoadingScreen::Start() + { + for (auto& x : tasks) + { + wi::jobsystem::Execute(ctx, x); + } + std::thread([this]() { + wi::jobsystem::Wait(ctx); + finish(); + }).detach(); + + RenderPath2D::Start(); + } + + void LoadingScreen::Stop() + { + tasks.clear(); + finish = nullptr; + + RenderPath2D::Stop(); + } + +} diff --git a/WickedEngine/wiLoadingScreen.h b/WickedEngine/wiLoadingScreen.h new file mode 100644 index 000000000..647b2ce68 --- /dev/null +++ b/WickedEngine/wiLoadingScreen.h @@ -0,0 +1,40 @@ +#pragma once +#include "wiRenderPath2D.h" +#include "wiColor.h" +#include "wiJobSystem.h" +#include "wiVector.h" + +#include + +namespace wi +{ + + class Application; + + class LoadingScreen : + public RenderPath2D + { + private: + wi::jobsystem::context ctx; + wi::vector> tasks; + std::function finish; + public: + + //Add a loading task which should be executed + //use std::bind( YourFunctionPointer ) + void addLoadingFunction(std::function loadingFunction); + //Helper for loading a whole renderable component + void addLoadingComponent(RenderPath* component, Application* main, float fadeSeconds = 0, wi::Color fadeColor = wi::Color(0, 0, 0, 255)); + //Set a function that should be called when the loading finishes + //use std::bind( YourFunctionPointer ) + void onFinished(std::function finishFunction); + //See if the loading is currently running + bool isActive(); + + //Start Executing the tasks and mark the loading as active + virtual void Start() override; + //Clear all tasks + virtual void Stop() override; + }; + +} diff --git a/WickedEngine/wiLoadingScreen_BindLua.cpp b/WickedEngine/wiLoadingScreen_BindLua.cpp new file mode 100644 index 000000000..41a1422f9 --- /dev/null +++ b/WickedEngine/wiLoadingScreen_BindLua.cpp @@ -0,0 +1,85 @@ +#include "wiLoadingScreen_BindLua.h" + +namespace wi::lua +{ + + const char LoadingScreen_BindLua::className[] = "LoadingScreen"; + + Luna::FunctionType LoadingScreen_BindLua::methods[] = { + lunamethod(RenderPath2D_BindLua, AddSprite), + lunamethod(RenderPath2D_BindLua, AddFont), + lunamethod(RenderPath2D_BindLua, RemoveSprite), + lunamethod(RenderPath2D_BindLua, RemoveFont), + lunamethod(RenderPath2D_BindLua, ClearSprites), + lunamethod(RenderPath2D_BindLua, ClearFonts), + lunamethod(RenderPath2D_BindLua, GetSpriteOrder), + lunamethod(RenderPath2D_BindLua, GetFontOrder), + lunamethod(RenderPath2D_BindLua, AddLayer), + lunamethod(RenderPath2D_BindLua, GetLayers), + lunamethod(RenderPath2D_BindLua, SetLayerOrder), + lunamethod(RenderPath2D_BindLua, SetSpriteOrder), + lunamethod(RenderPath2D_BindLua, SetFontOrder), + + lunamethod(RenderPath_BindLua, GetLayerMask), + lunamethod(RenderPath_BindLua, SetLayerMask), + + lunamethod(LoadingScreen_BindLua, AddLoadingTask), + lunamethod(LoadingScreen_BindLua, OnFinished), + { NULL, NULL } + }; + Luna::PropertyType LoadingScreen_BindLua::properties[] = { + { NULL, NULL } + }; + + int LoadingScreen_BindLua::AddLoadingTask(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + std::string task = wi::lua::SGetString(L, 1); + LoadingScreen* loading = dynamic_cast(component); + if (loading != nullptr) + { + loading->addLoadingFunction([=](wi::jobsystem::JobArgs args) { + wi::lua::RunText(task); + }); + } + else + wi::lua::SError(L, "AddLoader(string taskScript) component is not a LoadingScreen!"); + } + else + wi::lua::SError(L, "AddLoader(string taskScript) not enough arguments!"); + return 0; + } + int LoadingScreen_BindLua::OnFinished(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + std::string task = wi::lua::SGetString(L, 1); + LoadingScreen* loading = dynamic_cast(component); + if (loading != nullptr) + { + loading->onFinished([=] { + wi::lua::RunText(task); + }); + } + else + wi::lua::SError(L, "OnFinished(string taskScript) component is not a LoadingScreen!"); + } + else + wi::lua::SError(L, "OnFinished(string taskScript) not enough arguments!"); + return 0; + } + + void LoadingScreen_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + +} diff --git a/WickedEngine/wiLoadingScreen_BindLua.h b/WickedEngine/wiLoadingScreen_BindLua.h new file mode 100644 index 000000000..ab732cc53 --- /dev/null +++ b/WickedEngine/wiLoadingScreen_BindLua.h @@ -0,0 +1,34 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiLoadingScreen.h" +#include "wiRenderPath2D_BindLua.h" + +namespace wi::lua +{ + + class LoadingScreen_BindLua : public RenderPath2D_BindLua + { + private: + LoadingScreen loadingscreen; + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + LoadingScreen_BindLua(LoadingScreen* component) + { + this->component = component; + } + LoadingScreen_BindLua(lua_State* L) + { + this->component = &loadingscreen; + } + + int AddLoadingTask(lua_State* L); + int OnFinished(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiLua.cpp b/WickedEngine/wiLua.cpp index 2e9450714..7e23ba369 100644 --- a/WickedEngine/wiLua.cpp +++ b/WickedEngine/wiLua.cpp @@ -1,26 +1,25 @@ #include "wiLua.h" #include "wiLua_Globals.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiHelper.h" -#include "MainComponent_BindLua.h" -#include "RenderPath_BindLua.h" -#include "RenderPath2D_BindLua.h" -#include "LoadingScreen_BindLua.h" -#include "RenderPath3D_BindLua.h" -#include "Texture_BindLua.h" +#include "wiApplication_BindLua.h" +#include "wiRenderPath_BindLua.h" +#include "wiRenderPath2D_BindLua.h" +#include "wiLoadingScreen_BindLua.h" +#include "wiRenderPath3D_BindLua.h" +#include "wiTexture_BindLua.h" #include "wiRenderer_BindLua.h" #include "wiAudio_BindLua.h" #include "wiSprite_BindLua.h" #include "wiImageParams_BindLua.h" -#include "SpriteAnim_BindLua.h" +#include "wiSpriteAnim_BindLua.h" #include "wiScene_BindLua.h" -#include "Vector_BindLua.h" -#include "Matrix_BindLua.h" +#include "wiMath_BindLua.h" #include "wiInput_BindLua.h" #include "wiSpriteFont_BindLua.h" -#include "wiBackLog_BindLua.h" +#include "wiBacklog_BindLua.h" #include "wiNetwork_BindLua.h" -#include "wiIntersect_BindLua.h" +#include "wiPrimitive_BindLua.h" #include "wiTimer.h" #include "wiVector.h" @@ -28,7 +27,7 @@ #define WILUA_ERROR_PREFIX "[Lua Error] " -namespace wiLua +namespace wi::lua { struct LuaInternal { @@ -54,9 +53,9 @@ namespace wiLua { std::string filename = SGetString(L, 1); filename = script_path + filename; - script_path = wiHelper::GetDirectoryFromPath(filename); + script_path = wi::helper::GetDirectoryFromPath(filename); wi::vector filedata; - if (wiHelper::FileRead(filename, filedata)) + if (wi::helper::FileRead(filename, filedata)) { std::string command = std::string(filedata.begin(), filedata.end()); int status = luaL_loadstring(L, command.c_str()); @@ -74,7 +73,7 @@ namespace wiLua std::string ss; ss += WILUA_ERROR_PREFIX; ss += str; - wiBackLog::post(ss, wiBackLog::LogLevel::Error); + wi::backlog::post(ss, wi::backlog::LogLevel::Error); lua_pop(L, 1); // remove error message } } @@ -89,35 +88,35 @@ namespace wiLua void Initialize() { - wiTimer timer; + wi::Timer timer; luainternal.m_luaState = luaL_newstate(); luaL_openlibs(luainternal.m_luaState); RegisterFunc("dofile", Internal_DoFile); RunText(wiLua_Globals); - MainComponent_BindLua::Bind(); + Application_BindLua::Bind(); Canvas_BindLua::Bind(); RenderPath_BindLua::Bind(); RenderPath2D_BindLua::Bind(); LoadingScreen_BindLua::Bind(); RenderPath3D_BindLua::Bind(); Texture_BindLua::Bind(); - wiRenderer_BindLua::Bind(); - wiAudio_BindLua::Bind(); - wiSprite_BindLua::Bind(); - wiImageParams_BindLua::Bind(); + renderer::Bind(); + Audio_BindLua::Bind(); + Sprite_BindLua::Bind(); + ImageParams_BindLua::Bind(); SpriteAnim_BindLua::Bind(); - wiScene_BindLua::Bind(); + scene::Bind(); Vector_BindLua::Bind(); Matrix_BindLua::Bind(); - wiInput_BindLua::Bind(); - wiSpriteFont_BindLua::Bind(); - wiBackLog_BindLua::Bind(); - wiNetwork_BindLua::Bind(); - wiIntersect_BindLua::Bind(); + Input_BindLua::Bind(); + SpriteFont_BindLua::Bind(); + backlog::Bind(); + Network_BindLua::Bind(); + primitive::Bind(); - wiBackLog::post("wiLua Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::lua Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } lua_State* GetLuaState() @@ -157,15 +156,15 @@ namespace wiLua std::string ss; ss += WILUA_ERROR_PREFIX; ss += str; - wiBackLog::post(ss, wiBackLog::LogLevel::Error); + wi::backlog::post(ss, wi::backlog::LogLevel::Error); lua_pop(luainternal.m_luaState, 1); // remove error message } } bool RunFile(const std::string& filename) { - script_path = wiHelper::GetDirectoryFromPath(filename); + script_path = wi::helper::GetDirectoryFromPath(filename); wi::vector filedata; - if (wiHelper::FileRead(filename, filedata)) + if (wi::helper::FileRead(filename, filedata)) { return RunText(std::string(filedata.begin(), filedata.end())); } @@ -410,7 +409,7 @@ namespace wiLua { ss += error; } - wiBackLog::post(ss); + wi::backlog::post(ss); } void SAddMetatable(lua_State* L, const std::string& name) diff --git a/WickedEngine/wiLua.h b/WickedEngine/wiLua.h index 7d16d0ea5..5d1ea707b 100644 --- a/WickedEngine/wiLua.h +++ b/WickedEngine/wiLua.h @@ -13,7 +13,7 @@ extern "C" typedef int(*lua_CFunction) (lua_State* L); -namespace wiLua +namespace wi::lua { void Initialize(); diff --git a/WickedEngine/wiLuna.h b/WickedEngine/wiLuna.h index 074d7a816..3e12f33b1 100644 --- a/WickedEngine/wiLuna.h +++ b/WickedEngine/wiLuna.h @@ -3,7 +3,6 @@ //Luna : Official C++ to Lua binder project, 5th version //modified to fit with Wicked Engine, removed warnings - #define lunamethod(class, name) {#name, &class::name} template < class T > class Luna { diff --git a/WickedEngine/wiMath.cpp b/WickedEngine/wiMath.cpp index ee7dddac1..110d753cc 100644 --- a/WickedEngine/wiMath.cpp +++ b/WickedEngine/wiMath.cpp @@ -1,6 +1,6 @@ #include "wiMath.h" -namespace wiMath +namespace wi::math { float TriangleArea(const XMVECTOR& A, const XMVECTOR& B, const XMVECTOR& C) { diff --git a/WickedEngine/wiMath.h b/WickedEngine/wiMath.h index 95f917322..33aace5ce 100644 --- a/WickedEngine/wiMath.h +++ b/WickedEngine/wiMath.h @@ -1,6 +1,9 @@ #pragma once #include "CommonInclude.h" +#include +#include + #if __has_include("DirectXMath.h") // In this case, DirectXMath is coming from Windows SDK. // It is better to use this on Windows as some Windows libraries could depend on the same @@ -17,15 +20,13 @@ #include "Utility/DirectXCollision.h" #endif -#include -#include - using namespace DirectX; using namespace DirectX::PackedVector; -static constexpr XMFLOAT4X4 IDENTITYMATRIX = XMFLOAT4X4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); -namespace wiMath +namespace wi::math { + static constexpr XMFLOAT4X4 IDENTITY_MATRIX = XMFLOAT4X4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + constexpr float saturate(float x) { return std::min(std::max(x, 0.0f), 1.0f); } inline float Length(const XMFLOAT2& v) diff --git a/WickedEngine/wiMath_BindLua.cpp b/WickedEngine/wiMath_BindLua.cpp new file mode 100644 index 000000000..b85b32da5 --- /dev/null +++ b/WickedEngine/wiMath_BindLua.cpp @@ -0,0 +1,740 @@ +#include "wiMath_BindLua.h" + +namespace wi::lua +{ + + const char Vector_BindLua::className[] = "Vector"; + + Luna::FunctionType Vector_BindLua::methods[] = { + lunamethod(Vector_BindLua, GetX), + lunamethod(Vector_BindLua, GetY), + lunamethod(Vector_BindLua, GetZ), + lunamethod(Vector_BindLua, GetW), + lunamethod(Vector_BindLua, SetX), + lunamethod(Vector_BindLua, SetY), + lunamethod(Vector_BindLua, SetZ), + lunamethod(Vector_BindLua, SetW), + lunamethod(Vector_BindLua, Transform), + lunamethod(Vector_BindLua, TransformNormal), + lunamethod(Vector_BindLua, TransformCoord), + lunamethod(Vector_BindLua, Length), + lunamethod(Vector_BindLua, Normalize), + lunamethod(Vector_BindLua, QuaternionNormalize), + lunamethod(Vector_BindLua, Add), + lunamethod(Vector_BindLua, Subtract), + lunamethod(Vector_BindLua, Multiply), + lunamethod(Vector_BindLua, Dot), + lunamethod(Vector_BindLua, Cross), + lunamethod(Vector_BindLua, Lerp), + lunamethod(Vector_BindLua, Slerp), + lunamethod(Vector_BindLua, Clamp), + lunamethod(Vector_BindLua, Normalize), + lunamethod(Vector_BindLua, QuaternionMultiply), + lunamethod(Vector_BindLua, QuaternionFromRollPitchYaw), + { NULL, NULL } + }; + Luna::PropertyType Vector_BindLua::properties[] = { + { NULL, NULL } + }; + + Vector_BindLua::Vector_BindLua() + { + x = 0; + y = 0; + z = 0; + w = 0; + } + Vector_BindLua::Vector_BindLua(const XMFLOAT4& vector) + { + x = vector.x; + y = vector.y; + z = vector.z; + w = vector.w; + } + Vector_BindLua::Vector_BindLua(const XMVECTOR& vector) + { + XMStoreFloat4(this, vector); + } + Vector_BindLua::Vector_BindLua(lua_State* L) + { + x = 0; + y = 0; + z = 0; + w = 0; + + int argc = wi::lua::SGetArgCount(L); + + if (argc > 0) + { + x = wi::lua::SGetFloat(L, 1); + if (argc > 1) + { + y = wi::lua::SGetFloat(L, 2); + if (argc > 2) + { + z = wi::lua::SGetFloat(L, 3); + if (argc > 3) + { + w = wi::lua::SGetFloat(L, 4); + } + } + } + } + } + + + + int Vector_BindLua::GetX(lua_State* L) + { + wi::lua::SSetFloat(L, x); + return 1; + } + int Vector_BindLua::GetY(lua_State* L) + { + wi::lua::SSetFloat(L, y); + return 1; + } + int Vector_BindLua::GetZ(lua_State* L) + { + wi::lua::SSetFloat(L, z); + return 1; + } + int Vector_BindLua::GetW(lua_State* L) + { + wi::lua::SSetFloat(L, w); + return 1; + } + + int Vector_BindLua::SetX(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + x = wi::lua::SGetFloat(L, 1); + } + else + wi::lua::SError(L, "SetX(float value) not enough arguments!"); + return 0; + } + int Vector_BindLua::SetY(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + y = wi::lua::SGetFloat(L, 1); + } + else + wi::lua::SError(L, "SetY(float value) not enough arguments!"); + return 0; + } + int Vector_BindLua::SetZ(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + z = wi::lua::SGetFloat(L, 1); + } + else + wi::lua::SError(L, "SetZ(float value) not enough arguments!"); + return 0; + } + int Vector_BindLua::SetW(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + w = wi::lua::SGetFloat(L, 1); + } + else + wi::lua::SError(L, "SetW(float value) not enough arguments!"); + return 0; + } + + int Vector_BindLua::Transform(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + Matrix_BindLua* mat = Luna::lightcheck(L, 2); + if (vec && mat) + { + Luna::push(L, new Vector_BindLua(XMVector4Transform(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); + return 1; + } + else + wi::lua::SError(L, "Transform(Vector vec, Matrix matrix) argument types mismatch!"); + } + else + wi::lua::SError(L, "Transform(Vector vec, Matrix matrix) not enough arguments!"); + return 0; + } + int Vector_BindLua::TransformNormal(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + Matrix_BindLua* mat = Luna::lightcheck(L, 2); + if (vec && mat) + { + Luna::push(L, new Vector_BindLua(XMVector3TransformNormal(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); + return 1; + } + else + wi::lua::SError(L, "TransformNormal(Vector vec, Matrix matrix) argument types mismatch!"); + } + else + wi::lua::SError(L, "TransformNormal(Vector vec, Matrix matrix) not enough arguments!"); + return 0; + } + int Vector_BindLua::TransformCoord(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + Matrix_BindLua* mat = Luna::lightcheck(L, 2); + if (vec && mat) + { + Luna::push(L, new Vector_BindLua(XMVector3TransformCoord(XMLoadFloat4(vec), XMLoadFloat4x4(mat)))); + return 1; + } + else + wi::lua::SError(L, "TransformCoord(Vector vec, Matrix matrix) argument types mismatch!"); + } + else + wi::lua::SError(L, "TransformCoord(Vector vec, Matrix matrix) not enough arguments!"); + return 0; + } + int Vector_BindLua::Length(lua_State* L) + { + wi::lua::SSetFloat(L, XMVectorGetX(XMVector3Length(XMLoadFloat4(this)))); + return 1; + } + int Vector_BindLua::Normalize(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMVector3Normalize(XMLoadFloat4(this)))); + return 1; + } + int Vector_BindLua::QuaternionNormalize(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMQuaternionNormalize(XMLoadFloat4(this)))); + return 1; + } + int Vector_BindLua::Clamp(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + float a = wi::lua::SGetFloat(L, 1); + float b = wi::lua::SGetFloat(L, 2); + Luna::push(L, new Vector_BindLua(XMVectorClamp(XMLoadFloat4(this), XMVectorSet(a, a, a, a), XMVectorSet(b, b, b, b)))); + return 1; + } + else + wi::lua::SError(L, "Clamp(float min,max) not enough arguments!"); + return 0; + } + int Vector_BindLua::Saturate(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMVectorSaturate(XMLoadFloat4(this)))); + return 1; + } + + + + int Vector_BindLua::Dot(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + wi::lua::SSetFloat(L, XMVectorGetX(XMVector3Dot(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + } + wi::lua::SError(L, "Dot(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::Cross(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMVector3Cross(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + } + wi::lua::SError(L, "Cross(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::Multiply(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMVectorMultiply(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + else if (v1) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat4(v1) * wi::lua::SGetFloat(L, 2))); + return 1; + } + else if (v2) + { + Luna::push(L, new Vector_BindLua(wi::lua::SGetFloat(L, 1) * XMLoadFloat4(v2))); + return 1; + } + } + wi::lua::SError(L, "Multiply(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::Add(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMVectorAdd(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + } + wi::lua::SError(L, "Add(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::Subtract(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMVectorSubtract(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + } + wi::lua::SError(L, "Subtract(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::Lerp(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 2) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + float t = wi::lua::SGetFloat(L, 3); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMVectorLerp(XMLoadFloat4(v1), XMLoadFloat4(v2), t))); + return 1; + } + } + wi::lua::SError(L, "Lerp(Vector v1,v2, float t) not enough arguments!"); + return 0; + } + + + int Vector_BindLua::QuaternionMultiply(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMQuaternionMultiply(XMLoadFloat4(v1), XMLoadFloat4(v2)))); + return 1; + } + } + wi::lua::SError(L, "QuaternionMultiply(Vector v1,v2) not enough arguments!"); + return 0; + } + int Vector_BindLua::QuaternionFromRollPitchYaw(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + if (v1) + { + Luna::push(L, new Vector_BindLua(XMQuaternionRotationRollPitchYawFromVector(XMLoadFloat4(v1)))); + return 1; + } + } + wi::lua::SError(L, "QuaternionFromRollPitchYaw(Vector rotXYZ) not enough arguments!"); + return 0; + } + int Vector_BindLua::Slerp(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 2) + { + Vector_BindLua* v1 = Luna::lightcheck(L, 1); + Vector_BindLua* v2 = Luna::lightcheck(L, 2); + float t = wi::lua::SGetFloat(L, 3); + if (v1 && v2) + { + Luna::push(L, new Vector_BindLua(XMQuaternionSlerp(XMLoadFloat4(v1), XMLoadFloat4(v2), t))); + return 1; + } + } + wi::lua::SError(L, "QuaternionSlerp(Vector v1,v2, float t) not enough arguments!"); + return 0; + } + + + void Vector_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + wi::lua::RunText("vector = Vector()"); + } + } + + + + + + + const char Matrix_BindLua::className[] = "Matrix"; + + Luna::FunctionType Matrix_BindLua::methods[] = { + lunamethod(Matrix_BindLua, GetRow), + lunamethod(Matrix_BindLua, Translation), + lunamethod(Matrix_BindLua, Rotation), + lunamethod(Matrix_BindLua, RotationX), + lunamethod(Matrix_BindLua, RotationY), + lunamethod(Matrix_BindLua, RotationZ), + lunamethod(Matrix_BindLua, RotationQuaternion), + lunamethod(Matrix_BindLua, Scale), + lunamethod(Matrix_BindLua, LookTo), + lunamethod(Matrix_BindLua, LookAt), + + lunamethod(Matrix_BindLua, Add), + lunamethod(Matrix_BindLua, Multiply), + lunamethod(Matrix_BindLua, Transpose), + lunamethod(Matrix_BindLua, Inverse), + { NULL, NULL } + }; + Luna::PropertyType Matrix_BindLua::properties[] = { + { NULL, NULL } + }; + + Matrix_BindLua::Matrix_BindLua() + { + std::memcpy(this, &wi::math::IDENTITY_MATRIX, sizeof(wi::math::IDENTITY_MATRIX)); + } + Matrix_BindLua::Matrix_BindLua(const XMFLOAT4X4& matrix) + { + std::memcpy(this, &matrix, sizeof(matrix)); + } + Matrix_BindLua::Matrix_BindLua(const XMMATRIX& matrix) + { + XMStoreFloat4x4(this, matrix); + } + Matrix_BindLua::Matrix_BindLua(lua_State* L) + { + std::memcpy(this, &wi::math::IDENTITY_MATRIX, sizeof(wi::math::IDENTITY_MATRIX)); + + int argc = wi::lua::SGetArgCount(L); + + // fill out all the four rows of the matrix + for (int i = 0; i < 4; ++i) + { + float x = 0.f, y = 0.f, z = 0.f, w = 0.f; + if (argc > i * 4) + { + x = wi::lua::SGetFloat(L, i * 4 + 1); + if (argc > i * 4 + 1) + { + y = wi::lua::SGetFloat(L, i * 4 + 2); + if (argc > i * 4 + 2) + { + z = wi::lua::SGetFloat(L, i * 4 + 3); + if (argc > i * 4 + 3) + { + w = wi::lua::SGetFloat(L, i * 4 + 4); + } + } + } + } + this->m[i][0] = x; + this->m[i][1] = x; + this->m[i][2] = x; + this->m[i][3] = x; + } + + } + + int Matrix_BindLua::GetRow(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + int row = 0; + if (argc > 1) + { + row = wi::lua::SGetInt(L, 2); + if (row < 0 || row > 3) + row = 0; + } + XMFLOAT4 r = XMFLOAT4(m[row][0], m[row][1], m[row][2], m[row][3]); + Luna::push(L, new Vector_BindLua(r)); + return 1; + } + + + + int Matrix_BindLua::Translation(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + mat = XMMatrixTranslationFromVector(XMLoadFloat4(vector)); + } + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::Rotation(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + mat = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat4(vector)); + } + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::RotationX(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + mat = XMMatrixRotationX(wi::lua::SGetFloat(L, 1)); + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::RotationY(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + mat = XMMatrixRotationY(wi::lua::SGetFloat(L, 1)); + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::RotationZ(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + mat = XMMatrixRotationZ(wi::lua::SGetFloat(L, 1)); + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::RotationQuaternion(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + mat = XMMatrixRotationQuaternion(XMLoadFloat4(vector)); + } + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::Scale(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + XMMATRIX mat = XMMatrixIdentity(); + if (argc > 0) + { + Vector_BindLua* vector = Luna::lightcheck(L, 1); + if (vector != nullptr) + { + mat = XMMatrixScalingFromVector(XMLoadFloat4(vector)); + } + } + Luna::push(L, new Matrix_BindLua(mat)); + return 1; + } + + int Matrix_BindLua::LookTo(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* pos = Luna::lightcheck(L, 1); + Vector_BindLua* dir = Luna::lightcheck(L, 2); + if (pos != nullptr && dir != nullptr) + { + XMVECTOR Up; + if (argc > 3) + { + Vector_BindLua* up = Luna::lightcheck(L, 3); + Up = XMLoadFloat4(up); + } + else + Up = XMVectorSet(0, 1, 0, 0); + Luna::push(L, new Matrix_BindLua(XMMatrixLookToLH(XMLoadFloat4(pos), XMLoadFloat4(dir), Up))); + } + else + wi::lua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) argument is not a Vector!"); + } + else + wi::lua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) not enough arguments!"); + return 1; + } + + int Matrix_BindLua::LookAt(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Vector_BindLua* pos = Luna::lightcheck(L, 1); + Vector_BindLua* dir = Luna::lightcheck(L, 2); + if (dir != nullptr) + { + XMVECTOR Up; + if (argc > 3) + { + Vector_BindLua* up = Luna::lightcheck(L, 3); + Up = XMLoadFloat4(up); + } + else + Up = XMVectorSet(0, 1, 0, 0); + Luna::push(L, new Matrix_BindLua(XMMatrixLookAtLH(XMLoadFloat4(pos), XMLoadFloat4(dir), Up))); + } + else + wi::lua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) argument is not a Vector!"); + } + else + wi::lua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) not enough arguments!"); + return 1; + } + + int Matrix_BindLua::Multiply(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Matrix_BindLua* m1 = Luna::lightcheck(L, 1); + Matrix_BindLua* m2 = Luna::lightcheck(L, 2); + if (m1 && m2) + { + Luna::push(L, new Matrix_BindLua(XMMatrixMultiply(XMLoadFloat4x4(m1), XMLoadFloat4x4(m2)))); + return 1; + } + } + wi::lua::SError(L, "Multiply(Matrix m1,m2) not enough arguments!"); + return 0; + } + int Matrix_BindLua::Add(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + Matrix_BindLua* m1 = Luna::lightcheck(L, 1); + Matrix_BindLua* m2 = Luna::lightcheck(L, 2); + if (m1 && m2) + { + Luna::push(L, new Matrix_BindLua(XMLoadFloat4x4(m1) + XMLoadFloat4x4(m2))); + return 1; + } + } + wi::lua::SError(L, "Add(Matrix m1,m2) not enough arguments!"); + return 0; + } + int Matrix_BindLua::Transpose(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Matrix_BindLua* m1 = Luna::lightcheck(L, 1); + if (m1) + { + Luna::push(L, new Matrix_BindLua(XMMatrixTranspose(XMLoadFloat4x4(m1)))); + return 1; + } + } + wi::lua::SError(L, "Transpose(Matrix m) not enough arguments!"); + return 0; + } + int Matrix_BindLua::Inverse(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Matrix_BindLua* m1 = Luna::lightcheck(L, 1); + if (m1) + { + XMVECTOR det; + Luna::push(L, new Matrix_BindLua(XMMatrixInverse(&det, XMLoadFloat4x4(m1)))); + wi::lua::SSetFloat(L, XMVectorGetX(det)); + return 2; + } + } + wi::lua::SError(L, "Inverse(Matrix m) not enough arguments!"); + return 0; + } + + + void Matrix_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + wi::lua::RunText("matrix = Matrix()"); + } + } + +} diff --git a/WickedEngine/wiMath_BindLua.h b/WickedEngine/wiMath_BindLua.h new file mode 100644 index 000000000..187f815ee --- /dev/null +++ b/WickedEngine/wiMath_BindLua.h @@ -0,0 +1,88 @@ +#pragma once +#include "CommonInclude.h" +#include "wiLua.h" +#include "wiLuna.h" +#include "wiMath.h" + +namespace wi::lua +{ + + class Vector_BindLua : public XMFLOAT4 + { + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + Vector_BindLua(); + Vector_BindLua(const XMFLOAT4& vector); + Vector_BindLua(const XMVECTOR& vector); + Vector_BindLua(lua_State* L); + + int GetX(lua_State* L); + int GetY(lua_State* L); + int GetZ(lua_State* L); + int GetW(lua_State* L); + + int SetX(lua_State* L); + int SetY(lua_State* L); + int SetZ(lua_State* L); + int SetW(lua_State* L); + + int Transform(lua_State* L); + int TransformNormal(lua_State* L); + int TransformCoord(lua_State* L); + int Length(lua_State* L); + int Normalize(lua_State* L); + int QuaternionNormalize(lua_State* L); + int Clamp(lua_State* L); + int Saturate(lua_State* L); + + int Dot(lua_State* L); + int Cross(lua_State* L); + int Multiply(lua_State* L); + int Add(lua_State* L); + int Subtract(lua_State* L); + int Lerp(lua_State* L); + + + int QuaternionMultiply(lua_State* L); + int QuaternionFromRollPitchYaw(lua_State* L); + int Slerp(lua_State* L); + + static void Bind(); + }; + + class Matrix_BindLua : public XMFLOAT4X4 + { + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + Matrix_BindLua(); + Matrix_BindLua(const XMMATRIX& matrix); + Matrix_BindLua(const XMFLOAT4X4& matrix); + Matrix_BindLua(lua_State* L); + + int GetRow(lua_State* L); + + int Translation(lua_State* L); + int Rotation(lua_State* L); + int RotationX(lua_State* L); + int RotationY(lua_State* L); + int RotationZ(lua_State* L); + int RotationQuaternion(lua_State* L); + int Scale(lua_State* L); + int LookTo(lua_State* L); + int LookAt(lua_State* L); + + int Multiply(lua_State* L); + int Add(lua_State* L); + int Transpose(lua_State* L); + int Inverse(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiNetwork.h b/WickedEngine/wiNetwork.h index 45685c95e..43534081f 100644 --- a/WickedEngine/wiNetwork.h +++ b/WickedEngine/wiNetwork.h @@ -4,7 +4,7 @@ #include #include -namespace wiNetwork +namespace wi::network { struct Socket { diff --git a/WickedEngine/wiNetwork_BindLua.cpp b/WickedEngine/wiNetwork_BindLua.cpp index 69ba9204c..27663bb52 100644 --- a/WickedEngine/wiNetwork_BindLua.cpp +++ b/WickedEngine/wiNetwork_BindLua.cpp @@ -2,24 +2,28 @@ #include "wiNetwork.h" #include "wiHelper.h" -const char wiNetwork_BindLua::className[] = "Network"; - -Luna::FunctionType wiNetwork_BindLua::methods[] = { - { NULL, NULL } -}; -Luna::PropertyType wiNetwork_BindLua::properties[] = { - { NULL, NULL } -}; - -void wiNetwork_BindLua::Bind() +namespace wi::lua { - static bool initialized = false; - if (!initialized) + + const char Network_BindLua::className[] = "Network"; + + Luna::FunctionType Network_BindLua::methods[] = { + { NULL, NULL } + }; + Luna::PropertyType Network_BindLua::properties[] = { + { NULL, NULL } + }; + + void Network_BindLua::Bind() { - initialized = true; - Luna::Register(wiLua::GetLuaState()); + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); - wiLua::RunText("network = Network()"); + wi::lua::RunText("network = Network()"); + } } -} +} diff --git a/WickedEngine/wiNetwork_BindLua.h b/WickedEngine/wiNetwork_BindLua.h index bc194246f..949b2f44e 100644 --- a/WickedEngine/wiNetwork_BindLua.h +++ b/WickedEngine/wiNetwork_BindLua.h @@ -2,14 +2,19 @@ #include "wiLua.h" #include "wiLuna.h" -class wiNetwork_BindLua +namespace wi::lua { -public: - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; - wiNetwork_BindLua(lua_State* L) {} + class Network_BindLua + { + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - static void Bind(); -}; + Network_BindLua(lua_State* L) {} + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiNetwork_Linux.cpp b/WickedEngine/wiNetwork_Linux.cpp index dbe6313d8..f4edd291a 100644 --- a/WickedEngine/wiNetwork_Linux.cpp +++ b/WickedEngine/wiNetwork_Linux.cpp @@ -2,7 +2,7 @@ #ifdef PLATFORM_LINUX #include "wiNetwork.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTimer.h" #include @@ -12,7 +12,7 @@ #include #include -namespace wiNetwork +namespace wi::network { //For easy address conversion struct in_addr_union { @@ -40,11 +40,11 @@ namespace wiNetwork void Initialize() { - wiTimer timer; + wi::Timer timer; int result; - wiBackLog::post("wiNetwork_Linux Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::network_Linux Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } bool CreateSocket(Socket* sock) @@ -56,7 +56,7 @@ namespace wiNetwork if(socketinternal->handle == -1) { - wiBackLog::post("wiNetwork_Linux error in CreateSocket: Could not create socket"); + wi::backlog::post("wi::network_Linux error in CreateSocket: Could not create socket"); return false; } @@ -80,7 +80,7 @@ namespace wiNetwork int result = sendto(socketinternal->handle, (const char*)data, (int)dataSize, 0, (const sockaddr*)&target, sizeof(target)); if (result < 0) { - wiBackLog::post("wiNetwork_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); + wi::backlog::post("wi::network_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); return false; } @@ -102,7 +102,7 @@ namespace wiNetwork int result = bind(socketinternal->handle, (struct sockaddr *)&target , sizeof(target)); if (result < 0) { - wiBackLog::post("wiNetwork_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); + wi::backlog::post("wi::network_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); return false; } @@ -126,7 +126,7 @@ namespace wiNetwork int result = select(0, &readfds, NULL, NULL, &timeout); if (result < 0) { - wiBackLog::post("wiNetwork_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); + wi::backlog::post("wi::network_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); assert(0); return false; } @@ -146,7 +146,7 @@ namespace wiNetwork int result = recvfrom(socketinternal->handle, (char*)data, (int)dataSize, 0, (sockaddr*)& sender, (socklen_t*)&targetsize); if (result < 0) { - wiBackLog::post("wiNetwork_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); + wi::backlog::post("wi::network_Linux error in Send: (Error Code: " + std::to_string(result) + ") " + std::string(strerror(result))); assert(0); return false; } diff --git a/WickedEngine/wiNetwork_UWP.cpp b/WickedEngine/wiNetwork_UWP.cpp index 139873ab8..c77fd985e 100644 --- a/WickedEngine/wiNetwork_UWP.cpp +++ b/WickedEngine/wiNetwork_UWP.cpp @@ -2,13 +2,13 @@ #if defined(_WIN32) && defined(PLATFORM_UWP) #include "wiNetwork.h" -#include "wiBackLog.h" +#include "wiBacklog.h" -namespace wiNetwork +namespace wi::network { void Initialize() { - wiBackLog::post("TODO wiNetwork_UWP"); + wi::backlog::post("TODO wi::network_UWP"); } bool CreateSocket(Socket* sock) diff --git a/WickedEngine/wiNetwork_Windows.cpp b/WickedEngine/wiNetwork_Windows.cpp index 4d476e245..6f95dff7b 100644 --- a/WickedEngine/wiNetwork_Windows.cpp +++ b/WickedEngine/wiNetwork_Windows.cpp @@ -2,7 +2,7 @@ #if defined(_WIN32) && !defined(PLATFORM_UWP) #include "wiNetwork.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTimer.h" #include @@ -10,22 +10,22 @@ #include #pragma comment(lib,"ws2_32.lib") -namespace wiNetwork +namespace wi::network { - struct wiNetworkInternal + struct NetworkInternal { WSAData wsadata; - ~wiNetworkInternal() + ~NetworkInternal() { WSACleanup(); } }; - std::shared_ptr networkinternal; + std::shared_ptr networkinternal; struct SocketInternal { - std::shared_ptr networkinternal; + std::shared_ptr networkinternal; SOCKET handle = NULL; ~SocketInternal() @@ -45,21 +45,21 @@ namespace wiNetwork void Initialize() { - wiTimer timer; + wi::Timer timer; int result; - networkinternal = std::make_shared(); + networkinternal = std::make_shared(); result = WSAStartup(MAKEWORD(2, 2), &networkinternal->wsadata); if (result) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork Initialization FAILED with error: " + std::to_string(error)); + wi::backlog::post("wi::network Initialization FAILED with error: " + std::to_string(error)); assert(0); } - wiBackLog::post("wiNetwork Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::network Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } bool CreateSocket(Socket* sock) @@ -72,7 +72,7 @@ namespace wiNetwork if (socketinternal->handle == INVALID_SOCKET) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork error in CreateSocket: " + std::to_string(error)); + wi::backlog::post("wi::network error in CreateSocket: " + std::to_string(error)); return false; } @@ -97,7 +97,7 @@ namespace wiNetwork if (result == SOCKET_ERROR) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork error in Send: " + std::to_string(error)); + wi::backlog::post("wi::network error in Send: " + std::to_string(error)); return false; } @@ -121,7 +121,7 @@ namespace wiNetwork if (result == SOCKET_ERROR) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork error in ListenPort: " + std::to_string(error)); + wi::backlog::post("wi::network error in ListenPort: " + std::to_string(error)); return false; } @@ -146,7 +146,7 @@ namespace wiNetwork if (result < 0) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork error in CanReceive: " + std::to_string(error)); + wi::backlog::post("wi::network error in CanReceive: " + std::to_string(error)); assert(0); return false; } @@ -168,7 +168,7 @@ namespace wiNetwork if (result == SOCKET_ERROR) { int error = WSAGetLastError(); - wiBackLog::post("wiNetwork error in Receive: " + std::to_string(error)); + wi::backlog::post("wi::network error in Receive: " + std::to_string(error)); return false; } diff --git a/WickedEngine/wiOcean.cpp b/WickedEngine/wiOcean.cpp index 850115c22..c64849d41 100644 --- a/WickedEngine/wiOcean.cpp +++ b/WickedEngine/wiOcean.cpp @@ -3,465 +3,469 @@ #include "wiResourceManager.h" #include "shaders/ShaderInterop_Ocean.h" #include "wiScene.h" -#include "wiBackLog.h" -#include "wiEvent.h" +#include "wiBacklog.h" +#include "wiEventHandler.h" #include "wiTimer.h" #include "wiVector.h" #include -using namespace wiGraphics; -using namespace wiScene; +using namespace wi::graphics; +using namespace wi::scene; -namespace wiOcean_Internal +namespace wi { - Shader updateSpectrumCS; - Shader updateDisplacementMapCS; - Shader updateGradientFoldingCS; - Shader oceanSurfVS; - Shader wireframePS; - Shader oceanSurfPS; - - RasterizerState rasterizerState; - RasterizerState wireRS; - DepthStencilState depthStencilState; - BlendState blendState; - - PipelineState PSO, PSO_wire; - - wiFFTGenerator::CSFFT512x512_Plan m_fft_plan; - - - void LoadShaders() + namespace ocean_internal { - wiRenderer::LoadShader(ShaderStage::CS, updateSpectrumCS, "oceanSimulatorCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, updateDisplacementMapCS, "oceanUpdateDisplacementMapCS.cso"); - wiRenderer::LoadShader(ShaderStage::CS, updateGradientFoldingCS, "oceanUpdateGradientFoldingCS.cso"); + Shader updateSpectrumCS; + Shader updateDisplacementMapCS; + Shader updateGradientFoldingCS; + Shader oceanSurfVS; + Shader wireframePS; + Shader oceanSurfPS; - wiRenderer::LoadShader(ShaderStage::VS, oceanSurfVS, "oceanSurfaceVS.cso"); + RasterizerState rasterizerState; + RasterizerState wireRS; + DepthStencilState depthStencilState; + BlendState blendState; - wiRenderer::LoadShader(ShaderStage::PS, oceanSurfPS, "oceanSurfacePS.cso"); - wiRenderer::LoadShader(ShaderStage::PS, wireframePS, "oceanSurfaceSimplePS.cso"); + PipelineState PSO, PSO_wire; + + wi::fftgenerator::CSFFT512x512_Plan m_fft_plan; - GraphicsDevice* device = wiGraphics::GetDevice(); - + void LoadShaders() { - PipelineStateDesc desc; - desc.vs = &oceanSurfVS; - desc.ps = &oceanSurfPS; - desc.bs = &blendState; - desc.rs = &rasterizerState; - desc.dss = &depthStencilState; - device->CreatePipelineState(&desc, &PSO); + wi::renderer::LoadShader(ShaderStage::CS, updateSpectrumCS, "oceanSimulatorCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, updateDisplacementMapCS, "oceanUpdateDisplacementMapCS.cso"); + wi::renderer::LoadShader(ShaderStage::CS, updateGradientFoldingCS, "oceanUpdateGradientFoldingCS.cso"); - desc.ps = &wireframePS; - desc.rs = &wireRS; - device->CreatePipelineState(&desc, &PSO_wire); + wi::renderer::LoadShader(ShaderStage::VS, oceanSurfVS, "oceanSurfaceVS.cso"); + + wi::renderer::LoadShader(ShaderStage::PS, oceanSurfPS, "oceanSurfacePS.cso"); + wi::renderer::LoadShader(ShaderStage::PS, wireframePS, "oceanSurfaceSimplePS.cso"); + + + GraphicsDevice* device = wi::graphics::GetDevice(); + + { + PipelineStateDesc desc; + desc.vs = &oceanSurfVS; + desc.ps = &oceanSurfPS; + desc.bs = &blendState; + desc.rs = &rasterizerState; + desc.dss = &depthStencilState; + device->CreatePipelineState(&desc, &PSO); + + desc.ps = &wireframePS; + desc.rs = &wireRS; + device->CreatePipelineState(&desc, &PSO_wire); + } } } -} -using namespace wiOcean_Internal; + using namespace ocean_internal; #define HALF_SQRT_2 0.7071068f #define GRAV_ACCEL 981.0f // The acceleration of gravity, cm/s^2 -// Generating gaussian random number with mean 0 and standard deviation 1. -float Gauss() -{ - float u1 = rand() / (float)RAND_MAX; - float u2 = rand() / (float)RAND_MAX; - if (u1 < 1e-6f) - u1 = 1e-6f; - return std::sqrt(-2 * logf(u1)) * cosf(2 * XM_PI * u2); -} - -// Phillips Spectrum -// K: normalized wave vector, W: wind direction, v: wind velocity, a: amplitude constant -float Phillips(XMFLOAT2 K, XMFLOAT2 W, float v, float a, float dir_depend) -{ - // largest possible wave from constant wind of velocity v - float l = v * v / GRAV_ACCEL; - // damp out waves with very small length w << l - float w = l / 1000; - - float Ksqr = K.x * K.x + K.y * K.y; - float Kcos = K.x * W.x + K.y * W.y; - float phillips = a * expf(-1 / (l * l * Ksqr)) / (Ksqr * Ksqr * Ksqr) * (Kcos * Kcos); - - // filter out waves moving opposite to wind - if (Kcos < 0) - phillips *= dir_depend; - - // damp out waves with very small length w << l - return phillips * expf(-Ksqr * w * w); -} - - - -void wiOcean::Create(const OceanParameters& params) -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - // Height map H(0) - int height_map_size = (params.dmap_dim + 4) * (params.dmap_dim + 1); - wi::vector h0_data(height_map_size); - wi::vector omega_data(height_map_size); - initHeightMap(params, h0_data.data(), omega_data.data()); - - int hmap_dim = params.dmap_dim; - int input_full_size = (hmap_dim + 4) * (hmap_dim + 1); - // This value should be (hmap_dim / 2 + 1) * hmap_dim, but we use full sized buffer here for simplicity. - int input_half_size = hmap_dim * hmap_dim; - int output_size = hmap_dim * hmap_dim; - - // For filling the buffer with zeroes. - wi::vector zero_data(3 * output_size * sizeof(float) * 2); - std::fill(zero_data.begin(), zero_data.end(), 0); - - GPUBufferDesc buf_desc; - buf_desc.usage = Usage::DEFAULT; - buf_desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE; - buf_desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; - - // RW buffer allocations - // H0 - buf_desc.stride = sizeof(float2); - buf_desc.size = buf_desc.stride * input_full_size; - device->CreateBuffer(&buf_desc, h0_data.data(), &buffer_Float2_H0); - - // Notice: The following 3 buffers should be half sized buffer because of conjugate symmetric input. But - // we use full sized buffers due to the CS4.0 restriction. - - // Put H(t), Dx(t) and Dy(t) into one buffer because CS4.0 allows only 1 UAV at a time - buf_desc.stride = sizeof(float2); - buf_desc.size = buf_desc.stride * 3 * input_half_size; - device->CreateBuffer(&buf_desc, zero_data.data(), &buffer_Float2_Ht); - - // omega - buf_desc.stride = sizeof(float); - buf_desc.size = buf_desc.stride * input_full_size; - device->CreateBuffer(&buf_desc, omega_data.data(), &buffer_Float_Omega); - - // Notice: The following 3 should be real number data. But here we use the complex numbers and C2C FFT - // due to the CS4.0 restriction. - // Put Dz, Dx and Dy into one buffer because CS4.0 allows only 1 UAV at a time - buf_desc.stride = sizeof(float2); - buf_desc.size = buf_desc.stride * 3 * output_size; - device->CreateBuffer(&buf_desc, zero_data.data(), &buffer_Float_Dxyz); - - TextureDesc tex_desc; - tex_desc.width = hmap_dim; - tex_desc.height = hmap_dim; - tex_desc.array_size = 1; - tex_desc.sample_count = 1; - tex_desc.usage = Usage::DEFAULT; - tex_desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; - - tex_desc.format = Format::R16G16B16A16_FLOAT; - tex_desc.mip_levels = 0; - tex_desc.layout = ResourceState::SHADER_RESOURCE_COMPUTE; - device->CreateTexture(&tex_desc, nullptr, &gradientMap); - device->SetName(&gradientMap, "gradientMap"); - - for (uint32_t i = 0; i < gradientMap.GetDesc().mip_levels; ++i) + // Generating gaussian random number with mean 0 and standard deviation 1. + float Gauss() { - int subresource_index; - subresource_index = device->CreateSubresource(&gradientMap, SubresourceType::SRV, 0, 1, i, 1); - assert(subresource_index == i); - subresource_index = device->CreateSubresource(&gradientMap, SubresourceType::UAV, 0, 1, i, 1); - assert(subresource_index == i); + float u1 = rand() / (float)RAND_MAX; + float u2 = rand() / (float)RAND_MAX; + if (u1 < 1e-6f) + u1 = 1e-6f; + return std::sqrt(-2 * logf(u1)) * cosf(2 * XM_PI * u2); } - tex_desc.format = Format::R32G32B32A32_FLOAT; - tex_desc.mip_levels = 1; - device->CreateTexture(&tex_desc, nullptr, &displacementMap); - device->SetName(&displacementMap, "displacementMap"); - - - // Constant buffers - uint32_t actual_dim = params.dmap_dim; - uint32_t input_width = actual_dim + 4; - // We use full sized data here. The value "output_width" should be actual_dim/2+1 though. - uint32_t output_width = actual_dim; - uint32_t output_height = actual_dim; - uint32_t dtx_offset = actual_dim * actual_dim; - uint32_t dty_offset = actual_dim * actual_dim * 2; - Ocean_Simulation_ImmutableCB immutable_consts = { actual_dim, input_width, output_width, output_height, dtx_offset, dty_offset }; - - GPUBufferDesc cb_desc; - cb_desc.bind_flags = BindFlag::CONSTANT_BUFFER; - cb_desc.size = sizeof(Ocean_Simulation_ImmutableCB); - device->CreateBuffer(&cb_desc, &immutable_consts, &immutableCB); - - cb_desc.usage = Usage::DEFAULT; - cb_desc.bind_flags = BindFlag::CONSTANT_BUFFER; - cb_desc.size = sizeof(Ocean_Simulation_PerFrameCB); - device->CreateBuffer(&cb_desc, nullptr, &perFrameCB); -} - - - -// Initialize the vector field. -// wlen_x: width of wave tile, in meters -// wlen_y: length of wave tile, in meters -void wiOcean::initHeightMap(const OceanParameters& params, XMFLOAT2* out_h0, float* out_omega) -{ - int i, j; - XMFLOAT2 K; - - XMFLOAT2 wind_dir; - XMStoreFloat2(&wind_dir, XMVector2Normalize(XMLoadFloat2(¶ms.wind_dir))); - float a = params.wave_amplitude * 1e-7f; // It is too small. We must scale it for editing. - float v = params.wind_speed; - float dir_depend = params.wind_dependency; - - int height_map_dim = params.dmap_dim; - float patch_length = params.patch_length; - - - for (i = 0; i <= height_map_dim; i++) + // Phillips Spectrum + // K: normalized wave vector, W: wind direction, v: wind velocity, a: amplitude constant + float Phillips(XMFLOAT2 K, XMFLOAT2 W, float v, float a, float dir_depend) { - // K is wave-vector, range [-|DX/W, |DX/W], [-|DY/H, |DY/H] - K.y = (-height_map_dim / 2.0f + i) * (2 * XM_PI / patch_length); + // largest possible wave from constant wind of velocity v + float l = v * v / GRAV_ACCEL; + // damp out waves with very small length w << l + float w = l / 1000; - for (j = 0; j <= height_map_dim; j++) + float Ksqr = K.x * K.x + K.y * K.y; + float Kcos = K.x * W.x + K.y * W.y; + float phillips = a * expf(-1 / (l * l * Ksqr)) / (Ksqr * Ksqr * Ksqr) * (Kcos * Kcos); + + // filter out waves moving opposite to wind + if (Kcos < 0) + phillips *= dir_depend; + + // damp out waves with very small length w << l + return phillips * expf(-Ksqr * w * w); + } + + + + void Ocean::Create(const OceanParameters& params) + { + GraphicsDevice* device = wi::graphics::GetDevice(); + + // Height map H(0) + int height_map_size = (params.dmap_dim + 4) * (params.dmap_dim + 1); + wi::vector h0_data(height_map_size); + wi::vector omega_data(height_map_size); + initHeightMap(params, h0_data.data(), omega_data.data()); + + int hmap_dim = params.dmap_dim; + int input_full_size = (hmap_dim + 4) * (hmap_dim + 1); + // This value should be (hmap_dim / 2 + 1) * hmap_dim, but we use full sized buffer here for simplicity. + int input_half_size = hmap_dim * hmap_dim; + int output_size = hmap_dim * hmap_dim; + + // For filling the buffer with zeroes. + wi::vector zero_data(3 * output_size * sizeof(float) * 2); + std::fill(zero_data.begin(), zero_data.end(), 0); + + GPUBufferDesc buf_desc; + buf_desc.usage = Usage::DEFAULT; + buf_desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE; + buf_desc.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; + + // RW buffer allocations + // H0 + buf_desc.stride = sizeof(float2); + buf_desc.size = buf_desc.stride * input_full_size; + device->CreateBuffer(&buf_desc, h0_data.data(), &buffer_Float2_H0); + + // Notice: The following 3 buffers should be half sized buffer because of conjugate symmetric input. But + // we use full sized buffers due to the CS4.0 restriction. + + // Put H(t), Dx(t) and Dy(t) into one buffer because CS4.0 allows only 1 UAV at a time + buf_desc.stride = sizeof(float2); + buf_desc.size = buf_desc.stride * 3 * input_half_size; + device->CreateBuffer(&buf_desc, zero_data.data(), &buffer_Float2_Ht); + + // omega + buf_desc.stride = sizeof(float); + buf_desc.size = buf_desc.stride * input_full_size; + device->CreateBuffer(&buf_desc, omega_data.data(), &buffer_Float_Omega); + + // Notice: The following 3 should be real number data. But here we use the complex numbers and C2C FFT + // due to the CS4.0 restriction. + // Put Dz, Dx and Dy into one buffer because CS4.0 allows only 1 UAV at a time + buf_desc.stride = sizeof(float2); + buf_desc.size = buf_desc.stride * 3 * output_size; + device->CreateBuffer(&buf_desc, zero_data.data(), &buffer_Float_Dxyz); + + TextureDesc tex_desc; + tex_desc.width = hmap_dim; + tex_desc.height = hmap_dim; + tex_desc.array_size = 1; + tex_desc.sample_count = 1; + tex_desc.usage = Usage::DEFAULT; + tex_desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + + tex_desc.format = Format::R16G16B16A16_FLOAT; + tex_desc.mip_levels = 0; + tex_desc.layout = ResourceState::SHADER_RESOURCE_COMPUTE; + device->CreateTexture(&tex_desc, nullptr, &gradientMap); + device->SetName(&gradientMap, "gradientMap"); + + for (uint32_t i = 0; i < gradientMap.GetDesc().mip_levels; ++i) { - K.x = (-height_map_dim / 2.0f + j) * (2 * XM_PI / patch_length); + int subresource_index; + subresource_index = device->CreateSubresource(&gradientMap, SubresourceType::SRV, 0, 1, i, 1); + assert(subresource_index == i); + subresource_index = device->CreateSubresource(&gradientMap, SubresourceType::UAV, 0, 1, i, 1); + assert(subresource_index == i); + } - float phil = (K.x == 0 && K.y == 0) ? 0 : std::sqrt(Phillips(K, wind_dir, v, a, dir_depend)); + tex_desc.format = Format::R32G32B32A32_FLOAT; + tex_desc.mip_levels = 1; + device->CreateTexture(&tex_desc, nullptr, &displacementMap); + device->SetName(&displacementMap, "displacementMap"); - out_h0[i * (height_map_dim + 4) + j].x = float(phil * Gauss() * HALF_SQRT_2); - out_h0[i * (height_map_dim + 4) + j].y = float(phil * Gauss() * HALF_SQRT_2); - // The angular frequency is following the dispersion relation: - // out_omega^2 = g*k - // The equation of Gerstner wave: - // x = x0 - K/k * A * sin(dot(K, x0) - sqrt(g * k) * t), x is a 2D vector. - // z = A * cos(dot(K, x0) - sqrt(g * k) * t) - // Gerstner wave shows that a point on a simple sinusoid wave is doing a uniform circular - // motion with the center (x0, y0, z0), radius A, and the circular plane is parallel to - // vector K. - out_omega[i * (height_map_dim + 4) + j] = std::sqrt(GRAV_ACCEL * sqrtf(K.x * K.x + K.y * K.y)); + // Constant buffers + uint32_t actual_dim = params.dmap_dim; + uint32_t input_width = actual_dim + 4; + // We use full sized data here. The value "output_width" should be actual_dim/2+1 though. + uint32_t output_width = actual_dim; + uint32_t output_height = actual_dim; + uint32_t dtx_offset = actual_dim * actual_dim; + uint32_t dty_offset = actual_dim * actual_dim * 2; + Ocean_Simulation_ImmutableCB immutable_consts = { actual_dim, input_width, output_width, output_height, dtx_offset, dty_offset }; + + GPUBufferDesc cb_desc; + cb_desc.bind_flags = BindFlag::CONSTANT_BUFFER; + cb_desc.size = sizeof(Ocean_Simulation_ImmutableCB); + device->CreateBuffer(&cb_desc, &immutable_consts, &immutableCB); + + cb_desc.usage = Usage::DEFAULT; + cb_desc.bind_flags = BindFlag::CONSTANT_BUFFER; + cb_desc.size = sizeof(Ocean_Simulation_PerFrameCB); + device->CreateBuffer(&cb_desc, nullptr, &perFrameCB); + } + + + + // Initialize the vector field. + // wlen_x: width of wave tile, in meters + // wlen_y: length of wave tile, in meters + void Ocean::initHeightMap(const OceanParameters& params, XMFLOAT2* out_h0, float* out_omega) + { + int i, j; + XMFLOAT2 K; + + XMFLOAT2 wind_dir; + XMStoreFloat2(&wind_dir, XMVector2Normalize(XMLoadFloat2(¶ms.wind_dir))); + float a = params.wave_amplitude * 1e-7f; // It is too small. We must scale it for editing. + float v = params.wind_speed; + float dir_depend = params.wind_dependency; + + int height_map_dim = params.dmap_dim; + float patch_length = params.patch_length; + + + for (i = 0; i <= height_map_dim; i++) + { + // K is wave-vector, range [-|DX/W, |DX/W], [-|DY/H, |DY/H] + K.y = (-height_map_dim / 2.0f + i) * (2 * XM_PI / patch_length); + + for (j = 0; j <= height_map_dim; j++) + { + K.x = (-height_map_dim / 2.0f + j) * (2 * XM_PI / patch_length); + + float phil = (K.x == 0 && K.y == 0) ? 0 : std::sqrt(Phillips(K, wind_dir, v, a, dir_depend)); + + out_h0[i * (height_map_dim + 4) + j].x = float(phil * Gauss() * HALF_SQRT_2); + out_h0[i * (height_map_dim + 4) + j].y = float(phil * Gauss() * HALF_SQRT_2); + + // The angular frequency is following the dispersion relation: + // out_omega^2 = g*k + // The equation of Gerstner wave: + // x = x0 - K/k * A * sin(dot(K, x0) - sqrt(g * k) * t), x is a 2D vector. + // z = A * cos(dot(K, x0) - sqrt(g * k) * t) + // Gerstner wave shows that a point on a simple sinusoid wave is doing a uniform circular + // motion with the center (x0, y0, z0), radius A, and the circular plane is parallel to + // vector K. + out_omega[i * (height_map_dim + 4) + j] = std::sqrt(GRAV_ACCEL * sqrtf(K.x * K.x + K.y * K.y)); + } } } -} - -void wiOcean::UpdateDisplacementMap(const OceanParameters& params, CommandList cmd) const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - device->EventBegin("Ocean Simulation", cmd); - - // ---------------------------- H(0) -> H(t), D(x, t), D(y, t) -------------------------------- - - device->BindComputeShader(&updateSpectrumCS, cmd); - - // Buffers - const GPUResource* cs0_srvs[2] = { - &buffer_Float2_H0, - &buffer_Float_Omega - }; - device->BindResources(cs0_srvs, 0, arraysize(cs0_srvs), cmd); - - const GPUResource* cs0_uavs[1] = { &buffer_Float2_Ht }; - device->BindUAVs(cs0_uavs, 0, arraysize(cs0_uavs), cmd); - - Ocean_Simulation_PerFrameCB perFrameData; - perFrameData.g_TimeScale = params.time_scale; - perFrameData.g_ChoppyScale = params.choppy_scale; - perFrameData.g_GridLen = params.dmap_dim / params.patch_length; - - { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&perFrameCB, ResourceState::CONSTANT_BUFFER, ResourceState::COPY_DST), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->UpdateBuffer(&perFrameCB, &perFrameData, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Buffer(&perFrameCB, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - device->BindConstantBuffer(&immutableCB, CB_GETBINDSLOT(Ocean_Simulation_ImmutableCB), cmd); - device->BindConstantBuffer(&perFrameCB, CB_GETBINDSLOT(Ocean_Simulation_PerFrameCB), cmd); - - // Run the CS - uint32_t group_count_x = (params.dmap_dim + OCEAN_COMPUTE_TILESIZE - 1) / OCEAN_COMPUTE_TILESIZE; - uint32_t group_count_y = (params.dmap_dim + OCEAN_COMPUTE_TILESIZE - 1) / OCEAN_COMPUTE_TILESIZE; - device->Dispatch(group_count_x, group_count_y, 1, cmd); - - { - GPUBarrier barriers[] = { - GPUBarrier::Memory(), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - - - // ------------------------------------ Perform FFT ------------------------------------------- - fft_512x512_c2c(m_fft_plan, buffer_Float_Dxyz, buffer_Float_Dxyz, buffer_Float2_Ht, cmd); - - - - device->BindConstantBuffer(&immutableCB, CB_GETBINDSLOT(Ocean_Simulation_ImmutableCB), cmd); - device->BindConstantBuffer(&perFrameCB, CB_GETBINDSLOT(Ocean_Simulation_PerFrameCB), cmd); - - - // Update displacement map: - device->BindComputeShader(&updateDisplacementMapCS, cmd); - const GPUResource* cs_uavs[] = { &displacementMap }; - device->BindUAVs(cs_uavs, 0, 1, cmd); - const GPUResource* cs_srvs[1] = { &buffer_Float_Dxyz }; - device->BindResources(cs_srvs, 0, 1, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Image(&displacementMap, displacementMap.desc.layout, ResourceState::UNORDERED_ACCESS), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->Dispatch(params.dmap_dim / OCEAN_COMPUTE_TILESIZE, params.dmap_dim / OCEAN_COMPUTE_TILESIZE, 1, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Image(&displacementMap, ResourceState::UNORDERED_ACCESS, displacementMap.desc.layout), - GPUBarrier::Memory(), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - // Update gradient map: - device->BindComputeShader(&updateGradientFoldingCS, cmd); - cs_uavs[0] = { &gradientMap }; - device->BindUAVs(cs_uavs, 0, 1, cmd); - cs_srvs[0] = &displacementMap; - device->BindResources(cs_srvs, 0, 1, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Image(&gradientMap, gradientMap.desc.layout, ResourceState::UNORDERED_ACCESS), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - device->Dispatch(params.dmap_dim / OCEAN_COMPUTE_TILESIZE, params.dmap_dim / OCEAN_COMPUTE_TILESIZE, 1, cmd); - { - GPUBarrier barriers[] = { - GPUBarrier::Image(&gradientMap, ResourceState::UNORDERED_ACCESS, gradientMap.desc.layout), - GPUBarrier::Memory(), - }; - device->Barrier(barriers, arraysize(barriers), cmd); - } - - // Unbind - - - wiRenderer::GenerateMipChain(gradientMap, wiRenderer::MIPGENFILTER_LINEAR, cmd); - - device->EventEnd(cmd); -} - - -void wiOcean::Render(const CameraComponent& camera, const OceanParameters& params, CommandList cmd) const -{ - GraphicsDevice* device = wiGraphics::GetDevice(); - - device->EventBegin("Ocean Rendering", cmd); - - bool wire = wiRenderer::IsWireRender(); - - if (wire) - { - device->BindPipelineState(&PSO_wire, cmd); - } - else - { - device->BindPipelineState(&PSO, cmd); - } - - - const uint2 dim = uint2(160 * params.surfaceDetail, 90 * params.surfaceDetail); - - Ocean_RenderCB cb; - cb.xOceanWaterColor = params.waterColor; - cb.xOceanTexelLength = params.patch_length / params.dmap_dim; - cb.xOceanScreenSpaceParams = XMFLOAT4((float)dim.x, (float)dim.y, 1.0f / (float)dim.x, 1.0f / (float)dim.y); - cb.xOceanPatchSizeRecip = 1.0f / params.patch_length; - cb.xOceanMapHalfTexel = 0.5f / params.dmap_dim; - cb.xOceanWaterHeight = params.waterHeight; - cb.xOceanSurfaceDisplacementTolerance = std::max(1.0f, params.surfaceDisplacementTolerance); - - device->BindDynamicConstantBuffer(cb, CB_GETBINDSLOT(Ocean_RenderCB), cmd); - - device->BindResource(&displacementMap, 0, cmd); - device->BindResource(&gradientMap, 1, cmd); - - device->Draw(dim.x*dim.y*6, 0, cmd); - - device->EventEnd(cmd); -} - - -void wiOcean::Initialize() -{ - wiTimer timer; - - GraphicsDevice* device = wiGraphics::GetDevice(); - - RasterizerState ras_desc; - ras_desc.fill_mode = FillMode::SOLID; - ras_desc.cull_mode = CullMode::NONE; - ras_desc.front_counter_clockwise = false; - ras_desc.depth_bias = 0; - ras_desc.slope_scaled_depth_bias = 0.0f; - ras_desc.depth_bias_clamp = 0.0f; - ras_desc.depth_clip_enable = true; - ras_desc.multisample_enable = true; - ras_desc.antialiased_line_enable = false; - - rasterizerState = ras_desc; - - ras_desc.fill_mode = FillMode::WIREFRAME; - wireRS = ras_desc; - - DepthStencilState depth_desc; - depth_desc.depth_enable = true; - depth_desc.depth_write_mask = DepthWriteMask::ALL; - depth_desc.depth_func = ComparisonFunc::GREATER; - depth_desc.stencil_enable = false; - depthStencilState = depth_desc; - - BlendState blend_desc; - blend_desc.alpha_to_coverage_enable = false; - blend_desc.independent_blend_enable = false; - blend_desc.render_target[0].blend_enable = true; - blend_desc.render_target[0].src_blend = Blend::SRC_ALPHA; - blend_desc.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; - blend_desc.render_target[0].blend_op = BlendOp::ADD; - blend_desc.render_target[0].src_blend_alpha = Blend::ONE; - blend_desc.render_target[0].dest_blend_alpha = Blend::ZERO; - blend_desc.render_target[0].blend_op_alpha = BlendOp::ADD; - blend_desc.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - blendState = blend_desc; - - - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); wiFFTGenerator::LoadShaders(); }); - - LoadShaders(); - wiFFTGenerator::LoadShaders(); - fft512x512_create_plan(m_fft_plan, 3); - - wiBackLog::post("wiOcean Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); -} - -const Texture* wiOcean::getDisplacementMap() const -{ - return &displacementMap; -} - -const Texture* wiOcean::getGradientMap() const -{ - return &gradientMap; + + void Ocean::UpdateDisplacementMap(const OceanParameters& params, CommandList cmd) const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + + device->EventBegin("Ocean Simulation", cmd); + + // ---------------------------- H(0) -> H(t), D(x, t), D(y, t) -------------------------------- + + device->BindComputeShader(&updateSpectrumCS, cmd); + + // Buffers + const GPUResource* cs0_srvs[2] = { + &buffer_Float2_H0, + &buffer_Float_Omega + }; + device->BindResources(cs0_srvs, 0, arraysize(cs0_srvs), cmd); + + const GPUResource* cs0_uavs[1] = { &buffer_Float2_Ht }; + device->BindUAVs(cs0_uavs, 0, arraysize(cs0_uavs), cmd); + + Ocean_Simulation_PerFrameCB perFrameData; + perFrameData.g_TimeScale = params.time_scale; + perFrameData.g_ChoppyScale = params.choppy_scale; + perFrameData.g_GridLen = params.dmap_dim / params.patch_length; + + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&perFrameCB, ResourceState::CONSTANT_BUFFER, ResourceState::COPY_DST), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->UpdateBuffer(&perFrameCB, &perFrameData, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Buffer(&perFrameCB, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + device->BindConstantBuffer(&immutableCB, CB_GETBINDSLOT(Ocean_Simulation_ImmutableCB), cmd); + device->BindConstantBuffer(&perFrameCB, CB_GETBINDSLOT(Ocean_Simulation_PerFrameCB), cmd); + + // Run the CS + uint32_t group_count_x = (params.dmap_dim + OCEAN_COMPUTE_TILESIZE - 1) / OCEAN_COMPUTE_TILESIZE; + uint32_t group_count_y = (params.dmap_dim + OCEAN_COMPUTE_TILESIZE - 1) / OCEAN_COMPUTE_TILESIZE; + device->Dispatch(group_count_x, group_count_y, 1, cmd); + + { + GPUBarrier barriers[] = { + GPUBarrier::Memory(), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + + + // ------------------------------------ Perform FFT ------------------------------------------- + fft_512x512_c2c(m_fft_plan, buffer_Float_Dxyz, buffer_Float_Dxyz, buffer_Float2_Ht, cmd); + + + + device->BindConstantBuffer(&immutableCB, CB_GETBINDSLOT(Ocean_Simulation_ImmutableCB), cmd); + device->BindConstantBuffer(&perFrameCB, CB_GETBINDSLOT(Ocean_Simulation_PerFrameCB), cmd); + + + // Update displacement map: + device->BindComputeShader(&updateDisplacementMapCS, cmd); + const GPUResource* cs_uavs[] = { &displacementMap }; + device->BindUAVs(cs_uavs, 0, 1, cmd); + const GPUResource* cs_srvs[1] = { &buffer_Float_Dxyz }; + device->BindResources(cs_srvs, 0, 1, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Image(&displacementMap, displacementMap.desc.layout, ResourceState::UNORDERED_ACCESS), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->Dispatch(params.dmap_dim / OCEAN_COMPUTE_TILESIZE, params.dmap_dim / OCEAN_COMPUTE_TILESIZE, 1, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Image(&displacementMap, ResourceState::UNORDERED_ACCESS, displacementMap.desc.layout), + GPUBarrier::Memory(), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + // Update gradient map: + device->BindComputeShader(&updateGradientFoldingCS, cmd); + cs_uavs[0] = { &gradientMap }; + device->BindUAVs(cs_uavs, 0, 1, cmd); + cs_srvs[0] = &displacementMap; + device->BindResources(cs_srvs, 0, 1, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Image(&gradientMap, gradientMap.desc.layout, ResourceState::UNORDERED_ACCESS), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + device->Dispatch(params.dmap_dim / OCEAN_COMPUTE_TILESIZE, params.dmap_dim / OCEAN_COMPUTE_TILESIZE, 1, cmd); + { + GPUBarrier barriers[] = { + GPUBarrier::Image(&gradientMap, ResourceState::UNORDERED_ACCESS, gradientMap.desc.layout), + GPUBarrier::Memory(), + }; + device->Barrier(barriers, arraysize(barriers), cmd); + } + + // Unbind + + + wi::renderer::GenerateMipChain(gradientMap, wi::renderer::MIPGENFILTER_LINEAR, cmd); + + device->EventEnd(cmd); + } + + + void Ocean::Render(const CameraComponent& camera, const OceanParameters& params, CommandList cmd) const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + + device->EventBegin("Ocean Rendering", cmd); + + bool wire = wi::renderer::IsWireRender(); + + if (wire) + { + device->BindPipelineState(&PSO_wire, cmd); + } + else + { + device->BindPipelineState(&PSO, cmd); + } + + + const uint2 dim = uint2(160 * params.surfaceDetail, 90 * params.surfaceDetail); + + Ocean_RenderCB cb; + cb.xOceanWaterColor = params.waterColor; + cb.xOceanTexelLength = params.patch_length / params.dmap_dim; + cb.xOceanScreenSpaceParams = XMFLOAT4((float)dim.x, (float)dim.y, 1.0f / (float)dim.x, 1.0f / (float)dim.y); + cb.xOceanPatchSizeRecip = 1.0f / params.patch_length; + cb.xOceanMapHalfTexel = 0.5f / params.dmap_dim; + cb.xOceanWaterHeight = params.waterHeight; + cb.xOceanSurfaceDisplacementTolerance = std::max(1.0f, params.surfaceDisplacementTolerance); + + device->BindDynamicConstantBuffer(cb, CB_GETBINDSLOT(Ocean_RenderCB), cmd); + + device->BindResource(&displacementMap, 0, cmd); + device->BindResource(&gradientMap, 1, cmd); + + device->Draw(dim.x * dim.y * 6, 0, cmd); + + device->EventEnd(cmd); + } + + + void Ocean::Initialize() + { + wi::Timer timer; + + GraphicsDevice* device = wi::graphics::GetDevice(); + + RasterizerState ras_desc; + ras_desc.fill_mode = FillMode::SOLID; + ras_desc.cull_mode = CullMode::NONE; + ras_desc.front_counter_clockwise = false; + ras_desc.depth_bias = 0; + ras_desc.slope_scaled_depth_bias = 0.0f; + ras_desc.depth_bias_clamp = 0.0f; + ras_desc.depth_clip_enable = true; + ras_desc.multisample_enable = true; + ras_desc.antialiased_line_enable = false; + + rasterizerState = ras_desc; + + ras_desc.fill_mode = FillMode::WIREFRAME; + wireRS = ras_desc; + + DepthStencilState depth_desc; + depth_desc.depth_enable = true; + depth_desc.depth_write_mask = DepthWriteMask::ALL; + depth_desc.depth_func = ComparisonFunc::GREATER; + depth_desc.stencil_enable = false; + depthStencilState = depth_desc; + + BlendState blend_desc; + blend_desc.alpha_to_coverage_enable = false; + blend_desc.independent_blend_enable = false; + blend_desc.render_target[0].blend_enable = true; + blend_desc.render_target[0].src_blend = Blend::SRC_ALPHA; + blend_desc.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; + blend_desc.render_target[0].blend_op = BlendOp::ADD; + blend_desc.render_target[0].src_blend_alpha = Blend::ONE; + blend_desc.render_target[0].dest_blend_alpha = Blend::ZERO; + blend_desc.render_target[0].blend_op_alpha = BlendOp::ADD; + blend_desc.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; + blendState = blend_desc; + + + static wi::eventhandler::Handle handle = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); wi::fftgenerator::LoadShaders(); }); + + LoadShaders(); + wi::fftgenerator::LoadShaders(); + fft512x512_create_plan(m_fft_plan, 3); + + wi::backlog::post("wi::Ocean Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + } + + const Texture* Ocean::getDisplacementMap() const + { + return &displacementMap; + } + + const Texture* Ocean::getGradientMap() const + { + return &gradientMap; + } + } diff --git a/WickedEngine/wiOcean.h b/WickedEngine/wiOcean.h index be37ed3df..e70b600ad 100644 --- a/WickedEngine/wiOcean.h +++ b/WickedEngine/wiOcean.h @@ -5,69 +5,72 @@ #include "wiScene_Decl.h" #include "wiMath.h" -class wiOcean +namespace wi { -public: - struct OceanParameters + class Ocean { - // Must be power of 2. - int dmap_dim = 512; - // Typical value is 1000 ~ 2000 - float patch_length = 50.0f; + public: + struct OceanParameters + { + // Must be power of 2. + int dmap_dim = 512; + // Typical value is 1000 ~ 2000 + float patch_length = 50.0f; - // Adjust the time interval for simulation. - float time_scale = 0.3f; - // Amplitude for transverse wave. Around 1.0 - float wave_amplitude = 1000.0f; - // Wind direction. Normalization not required. - XMFLOAT2 wind_dir = XMFLOAT2(0.8f, 0.6f); - // Around 100 ~ 1000 - float wind_speed = 600.0f; - // This value damps out the waves against the wind direction. - // Smaller value means higher wind dependency. - float wind_dependency = 0.07f; - // The amplitude for longitudinal wave. Must be positive. - float choppy_scale = 1.3f; + // Adjust the time interval for simulation. + float time_scale = 0.3f; + // Amplitude for transverse wave. Around 1.0 + float wave_amplitude = 1000.0f; + // Wind direction. Normalization not required. + XMFLOAT2 wind_dir = XMFLOAT2(0.8f, 0.6f); + // Around 100 ~ 1000 + float wind_speed = 600.0f; + // This value damps out the waves against the wind direction. + // Smaller value means higher wind dependency. + float wind_dependency = 0.07f; + // The amplitude for longitudinal wave. Must be positive. + float choppy_scale = 1.3f; - XMFLOAT4 waterColor = XMFLOAT4(0.0f, 3.0f / 255.0f, 31.0f / 255.0f, 1); - float waterHeight = 0.0f; - uint32_t surfaceDetail = 4; - float surfaceDisplacementTolerance = 2; + XMFLOAT4 waterColor = XMFLOAT4(0.0f, 3.0f / 255.0f, 31.0f / 255.0f, 1); + float waterHeight = 0.0f; + uint32_t surfaceDetail = 4; + float surfaceDisplacementTolerance = 2; + }; + void Create(const OceanParameters& params); + + void UpdateDisplacementMap(const OceanParameters& params, wi::graphics::CommandList cmd) const; + void Render(const wi::scene::CameraComponent& camera, const OceanParameters& params, wi::graphics::CommandList cmd) const; + + const wi::graphics::Texture* getDisplacementMap() const; + const wi::graphics::Texture* getGradientMap() const; + + static void Initialize(); + + bool IsValid() const { return displacementMap.IsValid(); } + + protected: + wi::graphics::Texture displacementMap; // (RGBA32F) + wi::graphics::Texture gradientMap; // (RGBA16F) + + + void initHeightMap(const OceanParameters& params, XMFLOAT2* out_h0, float* out_omega); + + + // Initial height field H(0) generated by Phillips spectrum & Gauss distribution. + wi::graphics::GPUBuffer buffer_Float2_H0; + + // Angular frequency + wi::graphics::GPUBuffer buffer_Float_Omega; + + // Height field H(t), choppy field Dx(t) and Dy(t) in frequency domain, updated each frame. + wi::graphics::GPUBuffer buffer_Float2_Ht; + + // Height & choppy buffer in the space domain, corresponding to H(t), Dx(t) and Dy(t) + wi::graphics::GPUBuffer buffer_Float_Dxyz; + + + wi::graphics::GPUBuffer immutableCB; + wi::graphics::GPUBuffer perFrameCB; }; - void Create(const OceanParameters& params); - - void UpdateDisplacementMap(const OceanParameters& params, wiGraphics::CommandList cmd) const; - void Render(const wiScene::CameraComponent& camera, const OceanParameters& params, wiGraphics::CommandList cmd) const; - - const wiGraphics::Texture* getDisplacementMap() const; - const wiGraphics::Texture* getGradientMap() const; - - static void Initialize(); - - bool IsValid() const { return displacementMap.IsValid(); } - -protected: - wiGraphics::Texture displacementMap; // (RGBA32F) - wiGraphics::Texture gradientMap; // (RGBA16F) - - - void initHeightMap(const OceanParameters& params, XMFLOAT2* out_h0, float* out_omega); - - - // Initial height field H(0) generated by Phillips spectrum & Gauss distribution. - wiGraphics::GPUBuffer buffer_Float2_H0; - - // Angular frequency - wiGraphics::GPUBuffer buffer_Float_Omega; - - // Height field H(t), choppy field Dx(t) and Dy(t) in frequency domain, updated each frame. - wiGraphics::GPUBuffer buffer_Float2_Ht; - - // Height & choppy buffer in the space domain, corresponding to H(t), Dx(t) and Dy(t) - wiGraphics::GPUBuffer buffer_Float_Dxyz; - - - wiGraphics::GPUBuffer immutableCB; - wiGraphics::GPUBuffer perFrameCB; -}; +} diff --git a/WickedEngine/wiPhysicsEngine.h b/WickedEngine/wiPhysics.h similarity index 77% rename from WickedEngine/wiPhysicsEngine.h rename to WickedEngine/wiPhysics.h index cf6b3c633..8fd1046bd 100644 --- a/WickedEngine/wiPhysicsEngine.h +++ b/WickedEngine/wiPhysics.h @@ -1,9 +1,9 @@ #pragma once #include "wiECS.h" -#include "wiScene_Decl.h" +#include "wiScene.h" #include "wiJobSystem.h" -namespace wiPhysicsEngine +namespace wi::physics { // Initializes the physics engine void Initialize(); @@ -30,31 +30,31 @@ namespace wiPhysicsEngine // Update the physics state, run simulation, etc. void RunPhysicsUpdateSystem( - wiJobSystem::context& ctx, - wiScene::Scene& scene, + wi::jobsystem::context& ctx, + wi::scene::Scene& scene, float dt ); // Apply force at body center void ApplyForce( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& force ); // Apply force at body local position void ApplyForceAt( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& force, const XMFLOAT3& at ); // Apply impulse at body center void ApplyBodyImpulse( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& impulse ); // Apply impulse at body local position void ApplyImpulseAt( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& impulse, const XMFLOAT3& at ); diff --git a/WickedEngine/wiPhysicsEngine_Bullet.cpp b/WickedEngine/wiPhysics_Bullet.cpp similarity index 93% rename from WickedEngine/wiPhysicsEngine_Bullet.cpp rename to WickedEngine/wiPhysics_Bullet.cpp index 53c324c11..b45643824 100644 --- a/WickedEngine/wiPhysicsEngine_Bullet.cpp +++ b/WickedEngine/wiPhysics_Bullet.cpp @@ -1,7 +1,7 @@ -#include "wiPhysicsEngine.h" +#include "wiPhysics.h" #include "wiScene.h" #include "wiProfiler.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiJobSystem.h" #include "wiRenderer.h" #include "wiTimer.h" @@ -15,11 +15,10 @@ #include #include -using namespace wiECS; -using namespace wiScene; +using namespace wi::ecs; +using namespace wi::scene; - -namespace wiPhysicsEngine +namespace wi::physics { bool ENABLED = true; bool SIMULATION_ENABLED = true; @@ -39,18 +38,18 @@ namespace wiPhysicsEngine { void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override { - wiRenderer::RenderableLine line; + wi::renderer::RenderableLine line; line.start = XMFLOAT3(from.x(), from.y(), from.z()); line.end = XMFLOAT3(to.x(), to.y(), to.z()); line.color_start = line.color_end = XMFLOAT4(color.x(), color.y(), color.z(), 1.0f); - wiRenderer::DrawLine(line); + wi::renderer::DrawLine(line); } void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) override { } void reportErrorWarning(const char* warningString) override { - wiBackLog::post(warningString); + wi::backlog::post(warningString); } void draw3dText(const btVector3& location, const char* textString) override { @@ -67,7 +66,7 @@ namespace wiPhysicsEngine void Initialize() { - wiTimer timer; + wi::Timer timer; dispatcher = std::make_unique(&collisionConfiguration); dynamicsWorld = std::make_unique(dispatcher.get(), &overlappingPairCache, &solver, &collisionConfiguration); @@ -89,7 +88,7 @@ namespace wiPhysicsEngine softRigidWorld->setDebugDrawer(&debugDraw); - wiBackLog::post("wiPhysicsEngine_Bullet Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::physics Initialized [Bullet] (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } bool IsEnabled() { return ENABLED; } @@ -104,7 +103,7 @@ namespace wiPhysicsEngine int GetAccuracy() { return ACCURACY; } void SetAccuracy(int value) { ACCURACY = value; } - void AddRigidBody(Entity entity, wiScene::RigidBodyPhysicsComponent& physicscomponent, const wiScene::TransformComponent& transform, const wiScene::MeshComponent* mesh) + void AddRigidBody(Entity entity, wi::scene::RigidBodyPhysicsComponent& physicscomponent, const wi::scene::TransformComponent& transform, const wi::scene::MeshComponent* mesh) { btCollisionShape* shape = nullptr; @@ -139,7 +138,7 @@ namespace wiPhysicsEngine } else { - wiBackLog::post("Convex Hull physics requested, but no MeshComponent provided!"); + wi::backlog::post("Convex Hull physics requested, but no MeshComponent provided!"); assert(0); } break; @@ -183,7 +182,7 @@ namespace wiPhysicsEngine } else { - wiBackLog::post("Triangle Mesh physics requested, but no MeshComponent provided!"); + wi::backlog::post("Triangle Mesh physics requested, but no MeshComponent provided!"); assert(0); } break; @@ -237,7 +236,7 @@ namespace wiPhysicsEngine physicscomponent.physicsobject = rigidbody; } } - void AddSoftBody(Entity entity, wiScene::SoftBodyPhysicsComponent& physicscomponent, const wiScene::MeshComponent& mesh) + void AddSoftBody(Entity entity, wi::scene::SoftBodyPhysicsComponent& physicscomponent, const wi::scene::MeshComponent& mesh) { physicscomponent.CreateFromMesh(mesh); @@ -335,7 +334,7 @@ namespace wiPhysicsEngine } void RunPhysicsUpdateSystem( - wiJobSystem::context& ctx, + wi::jobsystem::context& ctx, Scene& scene, float dt ) @@ -343,12 +342,12 @@ namespace wiPhysicsEngine if (!IsEnabled() || dt <= 0) return; - auto range = wiProfiler::BeginRangeCPU("Physics"); + auto range = wi::profiler::BeginRangeCPU("Physics"); btVector3 wind = btVector3(scene.weather.windDirection.x, scene.weather.windDirection.y, scene.weather.windDirection.z); // System will register rigidbodies to objects, and update physics engine state for kinematics: - wiJobSystem::Dispatch(ctx, (uint32_t)scene.rigidbodies.GetCount(), 256, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)scene.rigidbodies.GetCount(), 256, [&](wi::jobsystem::JobArgs args) { RigidBodyPhysicsComponent& physicscomponent = scene.rigidbodies[args.jobIndex]; Entity entity = scene.rigidbodies.GetEntity(args.jobIndex); @@ -420,7 +419,7 @@ namespace wiPhysicsEngine }); // System will register softbodies to meshes and update physics engine state: - wiJobSystem::Dispatch(ctx, (uint32_t)scene.softbodies.GetCount(), 1, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)scene.softbodies.GetCount(), 1, [&](wi::jobsystem::JobArgs args) { SoftBodyPhysicsComponent& physicscomponent = scene.softbodies[args.jobIndex]; Entity entity = scene.softbodies.GetEntity(args.jobIndex); @@ -466,7 +465,7 @@ namespace wiPhysicsEngine btSoftBody::Node& node = softbody->m_nodes[(uint32_t)ind]; uint32_t graphicsInd = physicscomponent.physicsToGraphicsVertexMapping[ind]; XMFLOAT3 position = mesh.vertex_positions[graphicsInd]; - XMVECTOR P = armature == nullptr ? XMLoadFloat3(&position) : wiScene::SkinVertex(mesh, *armature, graphicsInd); + XMVECTOR P = armature == nullptr ? XMLoadFloat3(&position) : wi::scene::SkinVertex(mesh, *armature, graphicsInd); P = XMVector3Transform(P, worldMatrix); XMStoreFloat3(&position, P); node.m_x = btVector3(position.x, position.y, position.z); @@ -475,7 +474,7 @@ namespace wiPhysicsEngine } }); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); // Perform internal simulation step: if (IsSimulationEnabled()) @@ -537,7 +536,7 @@ namespace wiPhysicsEngine btVector3 aabb_min; btVector3 aabb_max; softbody->getAabb(aabb_min, aabb_max); - physicscomponent->aabb = AABB(XMFLOAT3(aabb_min.x(), aabb_min.y(), aabb_min.z()), XMFLOAT3(aabb_max.x(), aabb_max.y(), aabb_max.z())); + physicscomponent->aabb = wi::primitive::AABB(XMFLOAT3(aabb_min.x(), aabb_min.y(), aabb_min.z()), XMFLOAT3(aabb_max.x(), aabb_max.y(), aabb_max.z())); // Soft body simulation nodes will update graphics mesh: for (size_t ind = 0; ind < physicscomponent->vertex_positions_simulation.size(); ++ind) @@ -638,13 +637,13 @@ namespace wiPhysicsEngine dynamicsWorld->debugDrawWorld(); } - wiProfiler::EndRange(range); // Physics + wi::profiler::EndRange(range); // Physics } void ApplyForce( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& force ) { @@ -655,7 +654,7 @@ namespace wiPhysicsEngine } } void ApplyForceAt( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& force, const XMFLOAT3& at ) @@ -668,7 +667,7 @@ namespace wiPhysicsEngine } void ApplyImpulse( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& impulse ) { @@ -679,7 +678,7 @@ namespace wiPhysicsEngine } } void ApplyImpulseAt( - const wiScene::RigidBodyPhysicsComponent& physicscomponent, + const wi::scene::RigidBodyPhysicsComponent& physicscomponent, const XMFLOAT3& impulse, const XMFLOAT3& at ) diff --git a/WickedEngine/wiPlatform.h b/WickedEngine/wiPlatform.h index 190da894f..79425938f 100644 --- a/WickedEngine/wiPlatform.h +++ b/WickedEngine/wiPlatform.h @@ -42,7 +42,7 @@ typedef void* HMODULE; #endif -namespace wiPlatform +namespace wi::platform { #ifdef _WIN32 #ifdef PLATFORM_UWP diff --git a/WickedEngine/wiPrimitive.cpp b/WickedEngine/wiPrimitive.cpp new file mode 100644 index 000000000..caed77f80 --- /dev/null +++ b/WickedEngine/wiPrimitive.cpp @@ -0,0 +1,405 @@ +#include "wiPrimitive.h" + +namespace wi::primitive +{ + + void AABB::createFromHalfWidth(const XMFLOAT3& center, const XMFLOAT3& halfwidth) + { + _min = XMFLOAT3(center.x - halfwidth.x, center.y - halfwidth.y, center.z - halfwidth.z); + _max = XMFLOAT3(center.x + halfwidth.x, center.y + halfwidth.y, center.z + halfwidth.z); + } + AABB AABB::transform(const XMMATRIX& mat) const + { + XMFLOAT3 corners[8]; + for (int i = 0; i < 8; ++i) + { + XMFLOAT3 C = corner(i); + XMVECTOR point = XMVector3Transform(XMLoadFloat3(&C), mat); + XMStoreFloat3(&corners[i], point); + } + XMFLOAT3 min = corners[0]; + XMFLOAT3 max = corners[6]; + for (int i = 0; i < 8; ++i) + { + const XMFLOAT3& p = corners[i]; + + if (p.x < min.x) min.x = p.x; + if (p.y < min.y) min.y = p.y; + if (p.z < min.z) min.z = p.z; + + if (p.x > max.x) max.x = p.x; + if (p.y > max.y) max.y = p.y; + if (p.z > max.z) max.z = p.z; + } + + return AABB(min, max); + } + AABB AABB::transform(const XMFLOAT4X4& mat) const + { + return transform(XMLoadFloat4x4(&mat)); + } + XMFLOAT3 AABB::getCenter() const + { + return XMFLOAT3((_min.x + _max.x) * 0.5f, (_min.y + _max.y) * 0.5f, (_min.z + _max.z) * 0.5f); + } + XMFLOAT3 AABB::getHalfWidth() const + { + XMFLOAT3 center = getCenter(); + return XMFLOAT3(abs(_max.x - center.x), abs(_max.y - center.y), abs(_max.z - center.z)); + } + XMMATRIX AABB::AABB::getAsBoxMatrix() const + { + XMFLOAT3 ext = getHalfWidth(); + XMMATRIX sca = XMMatrixScaling(ext.x, ext.y, ext.z); + XMFLOAT3 pos = getCenter(); + XMMATRIX tra = XMMatrixTranslation(pos.x, pos.y, pos.z); + + return sca * tra; + } + float AABB::getArea() const + { + XMFLOAT3 _min = getMin(); + XMFLOAT3 _max = getMax(); + return (_max.x - _min.x) * (_max.y - _min.y) * (_max.z - _min.z); + } + float AABB::getRadius() const { + XMFLOAT3 abc = getHalfWidth(); + return std::max(std::max(abc.x, abc.y), abc.z); + } + AABB::INTERSECTION_TYPE AABB::intersects(const AABB& b) const { + + XMFLOAT3 aMin = getMin(), aMax = getMax(); + XMFLOAT3 bMin = b.getMin(), bMax = b.getMax(); + + if (bMin.x >= aMin.x && bMax.x <= aMax.x && + bMin.y >= aMin.y && bMax.y <= aMax.y && + bMin.z >= aMin.z && bMax.z <= aMax.z) + { + return INSIDE; + } + + if (aMax.x < bMin.x || aMin.x > bMax.x) + return OUTSIDE; + if (aMax.y < bMin.y || aMin.y > bMax.y) + return OUTSIDE; + if (aMax.z < bMin.z || aMin.z > bMax.z) + return OUTSIDE; + + return INTERSECTS; + } + AABB::INTERSECTION_TYPE AABB::intersects2D(const AABB& b) const { + + XMFLOAT3 aMin = getMin(), aMax = getMax(); + XMFLOAT3 bMin = b.getMin(), bMax = b.getMax(); + + if (bMin.x >= aMin.x && bMax.x <= aMax.x && + bMin.y >= aMin.y && bMax.y <= aMax.y) + { + return INSIDE; + } + + if (aMax.x < bMin.x || aMin.x > bMax.x) + return OUTSIDE; + if (aMax.y < bMin.y || aMin.y > bMax.y) + return OUTSIDE; + + return INTERSECTS; + } + bool AABB::intersects(const XMFLOAT3& p) const { + XMFLOAT3 max = getMax(); + XMFLOAT3 min = getMin(); + if (p.x > max.x) return false; + if (p.x < min.x) return false; + if (p.y > max.y) return false; + if (p.y < min.y) return false; + if (p.z > max.z) return false; + if (p.z < min.z) return false; + return true; + } + bool AABB::intersects(const Ray& ray) const { + if (intersects(ray.origin)) + return true; + + XMFLOAT3 MIN = getMin(); + XMFLOAT3 MAX = getMax(); + + float tx1 = (MIN.x - ray.origin.x) * ray.direction_inverse.x; + float tx2 = (MAX.x - ray.origin.x) * ray.direction_inverse.x; + + float tmin = std::min(tx1, tx2); + float tmax = std::max(tx1, tx2); + + float ty1 = (MIN.y - ray.origin.y) * ray.direction_inverse.y; + float ty2 = (MAX.y - ray.origin.y) * ray.direction_inverse.y; + + tmin = std::max(tmin, std::min(ty1, ty2)); + tmax = std::min(tmax, std::max(ty1, ty2)); + + float tz1 = (MIN.z - ray.origin.z) * ray.direction_inverse.z; + float tz2 = (MAX.z - ray.origin.z) * ray.direction_inverse.z; + + tmin = std::max(tmin, std::min(tz1, tz2)); + tmax = std::min(tmax, std::max(tz1, tz2)); + + return tmax >= tmin; + } + bool AABB::intersects(const Sphere& sphere) const + { + return sphere.intersects(*this); + } + bool AABB::intersects(const BoundingFrustum& frustum) const + { + BoundingBox bb = BoundingBox(getCenter(), getHalfWidth()); + bool intersection = frustum.Intersects(bb); + return intersection; + } + AABB AABB::operator* (float a) + { + XMFLOAT3 min = getMin(); + XMFLOAT3 max = getMax(); + min.x *= a; + min.y *= a; + min.z *= a; + max.x *= a; + max.y *= a; + max.z *= a; + return AABB(min, max); + } + AABB AABB::Merge(const AABB& a, const AABB& b) + { + return AABB(wi::math::Min(a.getMin(), b.getMin()), wi::math::Max(a.getMax(), b.getMax())); + } + void AABB::Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri) + { + if (archive.IsReadMode()) + { + archive >> _min; + archive >> _max; + + if (archive.GetVersion() >= 69) + { + archive >> layerMask; + archive >> userdata; + } + } + else + { + archive << _min; + archive << _max; + + if (archive.GetVersion() >= 69) + { + archive << layerMask; + archive << userdata; + } + } + } + + + + + + + bool Sphere::intersects(const AABB& b) const { + XMFLOAT3 min = b.getMin(); + XMFLOAT3 max = b.getMax(); + XMFLOAT3 closestPointInAabb = wi::math::Min(wi::math::Max(center, min), max); + double distanceSquared = wi::math::Distance(closestPointInAabb, center); + return distanceSquared < radius; + } + bool Sphere::intersects(const Sphere& b)const { + return wi::math::Distance(center, b.center) <= radius + b.radius; + } + bool Sphere::intersects(const Ray& b) const { + XMVECTOR o = XMLoadFloat3(&b.origin); + XMVECTOR r = XMLoadFloat3(&b.direction); + XMVECTOR dist = XMVector3LinePointDistance(o, o + r, XMLoadFloat3(¢er)); + return XMVectorGetX(dist) <= radius; + } + + + + bool Capsule::intersects(const Capsule& other, XMFLOAT3& position, XMFLOAT3& incident_normal, float& penetration_depth) const + { + if (getAABB().intersects(other.getAABB()) == AABB::INTERSECTION_TYPE::OUTSIDE) + return false; + + XMVECTOR a_Base = XMLoadFloat3(&base); + XMVECTOR a_Tip = XMLoadFloat3(&tip); + XMVECTOR a_Radius = XMVectorReplicate(radius); + XMVECTOR a_Normal = XMVector3Normalize(a_Tip - a_Base); + XMVECTOR a_LineEndOffset = a_Normal * a_Radius; + XMVECTOR a_A = a_Base + a_LineEndOffset; + XMVECTOR a_B = a_Tip - a_LineEndOffset; + + XMVECTOR b_Base = XMLoadFloat3(&other.base); + XMVECTOR b_Tip = XMLoadFloat3(&other.tip); + XMVECTOR b_Radius = XMVectorReplicate(other.radius); + XMVECTOR b_Normal = XMVector3Normalize(b_Tip - b_Base); + XMVECTOR b_LineEndOffset = b_Normal * b_Radius; + XMVECTOR b_A = b_Base + b_LineEndOffset; + XMVECTOR b_B = b_Tip - b_LineEndOffset; + + // Vectors between line endpoints: + XMVECTOR v0 = b_A - a_A; + XMVECTOR v1 = b_B - a_A; + XMVECTOR v2 = b_A - a_B; + XMVECTOR v3 = b_B - a_B; + + // Distances (squared) between line endpoints: + float d0 = XMVectorGetX(XMVector3LengthSq(v0)); + float d1 = XMVectorGetX(XMVector3LengthSq(v1)); + float d2 = XMVectorGetX(XMVector3LengthSq(v2)); + float d3 = XMVectorGetX(XMVector3LengthSq(v3)); + + // Select best potential endpoint on capsule A: + XMVECTOR bestA; + if (d2 < d0 || d2 < d1 || d3 < d0 || d3 < d1) + { + bestA = a_B; + } + else + { + bestA = a_A; + } + + // Select point on capsule B line segment nearest to best potential endpoint on A capsule: + XMVECTOR bestB = wi::math::ClosestPointOnLineSegment(b_A, b_B, bestA); + + // Now do the same for capsule A segment: + bestA = wi::math::ClosestPointOnLineSegment(a_A, a_B, bestB); + + // Finally, sphere collision: + XMVECTOR N = bestA - bestB; + XMVECTOR len = XMVector3Length(N); + N /= len; + float dist = XMVectorGetX(len); + + XMStoreFloat3(&position, bestA - N * radius); + XMStoreFloat3(&incident_normal, N); + penetration_depth = radius + other.radius - dist; + + return penetration_depth > 0; + } + + + + bool Ray::intersects(const AABB& b) const { + return b.intersects(*this); + } + bool Ray::intersects(const Sphere& b) const { + return b.intersects(*this); + } + + + + + void Frustum::Create(const XMMATRIX& viewProjection) + { + // We are interested in columns of the matrix, so transpose because we can access only rows: + const XMMATRIX mat = XMMatrixTranspose(viewProjection); + + // Near plane: + XMStoreFloat4(&planes[0], XMPlaneNormalize(mat.r[2])); + + // Far plane: + XMStoreFloat4(&planes[1], XMPlaneNormalize(mat.r[3] - mat.r[2])); + + // Left plane: + XMStoreFloat4(&planes[2], XMPlaneNormalize(mat.r[3] + mat.r[0])); + + // Right plane: + XMStoreFloat4(&planes[3], XMPlaneNormalize(mat.r[3] - mat.r[0])); + + // Top plane: + XMStoreFloat4(&planes[4], XMPlaneNormalize(mat.r[3] - mat.r[1])); + + // Bottom plane: + XMStoreFloat4(&planes[5], XMPlaneNormalize(mat.r[3] + mat.r[1])); + } + + bool Frustum::CheckPoint(const XMFLOAT3& point) const + { + XMVECTOR p = XMLoadFloat3(&point); + for (short i = 0; i < 6; i++) + { + if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[i]), p)) < 0.0f) + { + return false; + } + } + + return true; + } + bool Frustum::CheckSphere(const XMFLOAT3& center, float radius) const + { + int i; + XMVECTOR c = XMLoadFloat3(¢er); + for (i = 0; i < 6; i++) + { + if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[i]), c)) < -radius) + { + return false; + } + } + + return true; + } + Frustum::BoxFrustumIntersect Frustum::CheckBox(const AABB& box) const + { + int iTotalIn = 0; + for (int p = 0; p < 6; ++p) + { + + int iInCount = 8; + int iPtIn = 1; + + for (int i = 0; i < 8; ++i) + { + XMFLOAT3 C = box.corner(i); + if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[p]), XMLoadFloat3(&C))) < 0.0f) + { + iPtIn = 0; + --iInCount; + } + } + if (iInCount == 0) + return BOX_FRUSTUM_OUTSIDE; + iTotalIn += iPtIn; + } + if (iTotalIn == 6) + return(BOX_FRUSTUM_INSIDE); + return(BOX_FRUSTUM_INTERSECTS); + } + bool Frustum::CheckBoxFast(const AABB& box) const + { + XMVECTOR max = XMLoadFloat3(&box._max); + XMVECTOR min = XMLoadFloat3(&box._min); + XMVECTOR zero = XMVectorZero(); + for (size_t p = 0; p < 6; ++p) + { + auto lt = XMVectorLess(XMLoadFloat4(&planes[p]), zero); + auto furthestFromPlane = XMVectorSelect(max, min, lt); + if (XMVectorGetX(XMPlaneDotCoord(XMLoadFloat4(&planes[p]), furthestFromPlane)) < 0.0f) + { + return false; + } + } + return true; + } + + const XMFLOAT4& Frustum::getNearPlane() const { return planes[0]; } + const XMFLOAT4& Frustum::getFarPlane() const { return planes[1]; } + const XMFLOAT4& Frustum::getLeftPlane() const { return planes[2]; } + const XMFLOAT4& Frustum::getRightPlane() const { return planes[3]; } + const XMFLOAT4& Frustum::getTopPlane() const { return planes[4]; } + const XMFLOAT4& Frustum::getBottomPlane() const { return planes[5]; } + + + + bool Hitbox2D::intersects(const Hitbox2D& b) const + { + return wi::math::Collision2D(pos, siz, b.pos, b.siz); + } + +} diff --git a/WickedEngine/wiPrimitive.h b/WickedEngine/wiPrimitive.h new file mode 100644 index 000000000..edd8cbae6 --- /dev/null +++ b/WickedEngine/wiPrimitive.h @@ -0,0 +1,157 @@ +#pragma once +#include "CommonInclude.h" +#include "wiArchive.h" +#include "wiMath.h" +#include "wiECS.h" + +#include + +namespace wi::primitive +{ + struct Sphere; + struct Ray; + struct AABB; + + struct AABB + { + enum INTERSECTION_TYPE + { + OUTSIDE, + INTERSECTS, + INSIDE, + }; + + XMFLOAT3 _min; + uint32_t layerMask = ~0u; + XMFLOAT3 _max; + uint32_t userdata = 0; + + AABB( + const XMFLOAT3& _min = XMFLOAT3(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()), + const XMFLOAT3& _max = XMFLOAT3(std::numeric_limits::lowest(), std::numeric_limits::lowest(), std::numeric_limits::lowest()) + ) : _min(_min), _max(_max) {} + void createFromHalfWidth(const XMFLOAT3& center, const XMFLOAT3& halfwidth); + AABB transform(const XMMATRIX& mat) const; + AABB transform(const XMFLOAT4X4& mat) const; + XMFLOAT3 getCenter() const; + XMFLOAT3 getHalfWidth() const; + XMMATRIX getAsBoxMatrix() const; + float getArea() const; + float getRadius() const; + INTERSECTION_TYPE intersects2D(const AABB& b) const; + INTERSECTION_TYPE intersects(const AABB& b) const; + bool intersects(const XMFLOAT3& p) const; + bool intersects(const Ray& ray) const; + bool intersects(const Sphere& sphere) const; + bool intersects(const BoundingFrustum& frustum) const; + AABB operator* (float a); + static AABB Merge(const AABB& a, const AABB& b); + + inline XMFLOAT3 getMin() const { return _min; } + inline XMFLOAT3 getMax() const { return _max; } + inline XMFLOAT3 corner(int index) const + { + switch (index) + { + case 0: return _min; + case 1: return XMFLOAT3(_min.x, _max.y, _min.z); + case 2: return XMFLOAT3(_min.x, _max.y, _max.z); + case 3: return XMFLOAT3(_min.x, _min.y, _max.z); + case 4: return XMFLOAT3(_max.x, _min.y, _min.z); + case 5: return XMFLOAT3(_max.x, _max.y, _min.z); + case 6: return _max; + case 7: return XMFLOAT3(_max.x, _min.y, _max.z); + } + assert(0); + return XMFLOAT3(0, 0, 0); + } + + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); + }; + struct Sphere + { + XMFLOAT3 center; + float radius; + Sphere() :center(XMFLOAT3(0, 0, 0)), radius(0) {} + Sphere(const XMFLOAT3& c, float r) :center(c), radius(r) {} + bool intersects(const AABB& b) const; + bool intersects(const Sphere& b) const; + bool intersects(const Ray& b) const; + }; + struct Capsule + { + XMFLOAT3 base = XMFLOAT3(0, 0, 0); + XMFLOAT3 tip = XMFLOAT3(0, 0, 0); + float radius = 0; + Capsule() = default; + Capsule(const XMFLOAT3& base, const XMFLOAT3& tip, float radius) :base(base), tip(tip), radius(radius) {} + Capsule(const Sphere& sphere, float height) : + base(XMFLOAT3(sphere.center.x, sphere.center.y - sphere.radius, sphere.center.z)), + tip(XMFLOAT3(base.x, base.y + height, base.z)), + radius(sphere.radius) + {} + inline AABB getAABB() const + { + XMFLOAT3 halfWidth = XMFLOAT3(radius, radius, radius); + AABB base_aabb; + base_aabb.createFromHalfWidth(base, halfWidth); + AABB tip_aabb; + tip_aabb.createFromHalfWidth(tip, halfWidth); + return AABB::Merge(base_aabb, tip_aabb); + } + bool intersects(const Capsule& b, XMFLOAT3& position, XMFLOAT3& incident_normal, float& penetration_depth) const; + }; + struct Ray + { + XMFLOAT3 origin, direction, direction_inverse; + + Ray(const XMFLOAT3& newOrigin = XMFLOAT3(0, 0, 0), const XMFLOAT3& newDirection = XMFLOAT3(0, 0, 1)) : Ray(XMLoadFloat3(&newOrigin), XMLoadFloat3(&newDirection)) {} + Ray(const XMVECTOR& newOrigin, const XMVECTOR& newDirection) { + XMStoreFloat3(&origin, newOrigin); + XMStoreFloat3(&direction, newDirection); + XMStoreFloat3(&direction_inverse, XMVectorDivide(XMVectorReplicate(1.0f), newDirection)); + } + bool intersects(const AABB& b) const; + bool intersects(const Sphere& b) const; + }; + + struct Frustum + { + XMFLOAT4 planes[6]; + + void Create(const XMMATRIX& viewProjection); + + bool CheckPoint(const XMFLOAT3&) const; + bool CheckSphere(const XMFLOAT3&, float) const; + + enum BoxFrustumIntersect + { + BOX_FRUSTUM_OUTSIDE, + BOX_FRUSTUM_INTERSECTS, + BOX_FRUSTUM_INSIDE, + }; + BoxFrustumIntersect CheckBox(const AABB& box) const; + bool CheckBoxFast(const AABB& box) const; + + const XMFLOAT4& getNearPlane() const; + const XMFLOAT4& getFarPlane() const; + const XMFLOAT4& getLeftPlane() const; + const XMFLOAT4& getRightPlane() const; + const XMFLOAT4& getTopPlane() const; + const XMFLOAT4& getBottomPlane() const; + }; + + class Hitbox2D + { + public: + XMFLOAT2 pos; + XMFLOAT2 siz; + + Hitbox2D() :pos(XMFLOAT2(0, 0)), siz(XMFLOAT2(0, 0)) {} + Hitbox2D(const XMFLOAT2& newPos, const XMFLOAT2 newSiz) :pos(newPos), siz(newSiz) {} + ~Hitbox2D() {}; + + bool intersects(const Hitbox2D& b) const; + }; + +} diff --git a/WickedEngine/wiIntersect_BindLua.cpp b/WickedEngine/wiPrimitive_BindLua.cpp similarity index 71% rename from WickedEngine/wiIntersect_BindLua.cpp rename to WickedEngine/wiPrimitive_BindLua.cpp index 4a4709608..015e1e69f 100644 --- a/WickedEngine/wiIntersect_BindLua.cpp +++ b/WickedEngine/wiPrimitive_BindLua.cpp @@ -1,8 +1,9 @@ -#include "wiIntersect_BindLua.h" -#include "Vector_BindLua.h" -#include "Matrix_BindLua.h" +#include "wiPrimitive_BindLua.h" +#include "wiMath_BindLua.h" -namespace wiIntersect_BindLua +using namespace wi::primitive; + +namespace wi::lua::primitive { void Bind() { @@ -11,7 +12,7 @@ namespace wiIntersect_BindLua { initialized = true; - lua_State* L = wiLua::GetLuaState(); + lua_State* L = wi::lua::GetLuaState(); Luna::Register(L); Luna::Register(L); @@ -37,36 +38,36 @@ namespace wiIntersect_BindLua Ray_BindLua::Ray_BindLua(lua_State *L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* o = Luna::lightcheck(L, 1); Vector_BindLua* d = Luna::lightcheck(L, 2); if (o && d) { - ray = RAY(XMLoadFloat4(o), XMLoadFloat4(d)); + ray = Ray(XMLoadFloat4(o), XMLoadFloat4(d)); } else { - wiLua::SError(L, "Ray(Vector origin,direction) requires two arguments of Vector type!"); + wi::lua::SError(L, "Ray(Vector origin,direction) requires two arguments of Vector type!"); } } else { - wiLua::SError(L, "Ray(Vector origin,direction) not enough arguments!"); + wi::lua::SError(L, "Ray(Vector origin,direction) not enough arguments!"); } } int Ray_BindLua::Intersects(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { AABB_BindLua* aabb = Luna::lightcheck(L, 1); if (aabb) { bool intersects = ray.intersects(aabb->aabb); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } @@ -74,12 +75,12 @@ namespace wiIntersect_BindLua if (sphere) { bool intersects = ray.intersects(sphere->sphere); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } } - wiLua::SError(L, "[Intersects(AABB), Intersects(Sphere)] no matching arguments! "); + wi::lua::SError(L, "[Intersects(AABB), Intersects(Sphere)] no matching arguments! "); return 0; } int Ray_BindLua::GetOrigin(lua_State* L) @@ -114,7 +115,7 @@ namespace wiIntersect_BindLua AABB_BindLua::AABB_BindLua(lua_State *L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* _minV = Luna::lightcheck(L, 1); @@ -136,7 +137,7 @@ namespace wiIntersect_BindLua } else { - wiLua::SError(L, "AABB(opt Vector min,max) arguments must be of Vector type!"); + wi::lua::SError(L, "AABB(opt Vector min,max) arguments must be of Vector type!"); } } else @@ -147,15 +148,15 @@ namespace wiIntersect_BindLua int AABB_BindLua::Intersects(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { AABB_BindLua* _aabb = Luna::lightcheck(L, 1); if (_aabb) { //int intersects = (int)aabb.intersects(_aabb->aabb); - //wiLua::SSetInt(L, intersects); - wiLua::SSetBool(L, aabb.intersects(_aabb->aabb) != AABB::INTERSECTION_TYPE::OUTSIDE); // int intersection type cannot be checked like bool in lua so we give simple bool result here! + //wi::lua::SSetInt(L, intersects); + wi::lua::SSetBool(L, aabb.intersects(_aabb->aabb) != AABB::INTERSECTION_TYPE::OUTSIDE); // int intersection type cannot be checked like bool in lua so we give simple bool result here! return 1; } @@ -163,7 +164,7 @@ namespace wiIntersect_BindLua if (_sphere) { bool intersects = aabb.intersects(_sphere->sphere); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } @@ -171,30 +172,30 @@ namespace wiIntersect_BindLua if (ray) { bool intersects = ray->ray.intersects(aabb); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } } - wiLua::SError(L, "[Intersects(AABB), Intersects(Sphere), Intersects(Ray)] no matching arguments! "); + wi::lua::SError(L, "[Intersects(AABB), Intersects(Sphere), Intersects(Ray)] no matching arguments! "); return 0; } int AABB_BindLua::Intersects2D(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { AABB_BindLua* _aabb = Luna::lightcheck(L, 1); if (_aabb) { //int intersects = (int)aabb.intersects(_aabb->aabb); - //wiLua::SSetInt(L, intersects); - wiLua::SSetBool(L, aabb.intersects2D(_aabb->aabb) != AABB::INTERSECTION_TYPE::OUTSIDE); // int intersection type cannot be checked like bool in lua so we give simple bool result here! + //wi::lua::SSetInt(L, intersects); + wi::lua::SSetBool(L, aabb.intersects2D(_aabb->aabb) != AABB::INTERSECTION_TYPE::OUTSIDE); // int intersection type cannot be checked like bool in lua so we give simple bool result here! return 1; } } - wiLua::SError(L, "Intersects2D(AABB) not enough arguments! "); + wi::lua::SError(L, "Intersects2D(AABB) not enough arguments! "); return 0; } int AABB_BindLua::GetMin(lua_State* L) @@ -223,7 +224,7 @@ namespace wiIntersect_BindLua } int AABB_BindLua::Transform(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Matrix_BindLua* _matrix = Luna::lightcheck(L, 1); @@ -234,10 +235,10 @@ namespace wiIntersect_BindLua } else { - wiLua::SError(L, "Transform(Matrix matrix) argument is not a Matrix! "); + wi::lua::SError(L, "Transform(Matrix matrix) argument is not a Matrix! "); } } - wiLua::SError(L, "Transform(Matrix matrix) not enough arguments! "); + wi::lua::SError(L, "Transform(Matrix matrix) not enough arguments! "); return 0; } int AABB_BindLua::GetAsBoxMatrix(lua_State* L) @@ -264,7 +265,7 @@ namespace wiIntersect_BindLua Sphere_BindLua::Sphere_BindLua(lua_State *L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* cV = Luna::lightcheck(L, 1); @@ -273,31 +274,31 @@ namespace wiIntersect_BindLua XMFLOAT3 c; XMStoreFloat3(&c, XMLoadFloat4(cV)); - float r = wiLua::SGetFloat(L, 2); + float r = wi::lua::SGetFloat(L, 2); - sphere = SPHERE(c, r); + sphere = Sphere(c, r); } else { - wiLua::SError(L, "Sphere(Vector center, float radius) requires first argument to be of Vector type!"); + wi::lua::SError(L, "Sphere(Vector center, float radius) requires first argument to be of Vector type!"); } } else { - wiLua::SError(L, "Sphere(Vector center, float radius) not enough arguments!"); + wi::lua::SError(L, "Sphere(Vector center, float radius) not enough arguments!"); } } int Sphere_BindLua::Intersects(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { AABB_BindLua* _aabb = Luna::lightcheck(L, 1); if (_aabb) { bool intersects = sphere.intersects(_aabb->aabb); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } @@ -305,7 +306,7 @@ namespace wiIntersect_BindLua if (_sphere) { bool intersects = sphere.intersects(_sphere->sphere); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } @@ -313,12 +314,12 @@ namespace wiIntersect_BindLua if (ray) { bool intersects = ray->ray.intersects(sphere); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); return 1; } } - wiLua::SError(L, "[Intersects(AABB), Intersects(Sphere), Intersects(Ray)] no matching arguments! "); + wi::lua::SError(L, "[Intersects(AABB), Intersects(Sphere), Intersects(Ray)] no matching arguments! "); return 0; } int Sphere_BindLua::GetCenter(lua_State* L) @@ -328,12 +329,12 @@ namespace wiIntersect_BindLua } int Sphere_BindLua::GetRadius(lua_State* L) { - wiLua::SSetFloat(L, sphere.radius); + wi::lua::SSetFloat(L, sphere.radius); return 1; } int Sphere_BindLua::SetCenter(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* cV = Luna::lightcheck(L, 1); @@ -343,25 +344,25 @@ namespace wiIntersect_BindLua } else { - wiLua::SError(L, "SetCenter(Vector value) requires first argument to be of Vector type!"); + wi::lua::SError(L, "SetCenter(Vector value) requires first argument to be of Vector type!"); } } else { - wiLua::SError(L, "SetCenter(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetCenter(Vector value) not enough arguments!"); } return 0; } int Sphere_BindLua::SetRadius(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - sphere.radius = wiLua::SGetFloat(L, 1); + sphere.radius = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetRadius(float value) not enough arguments!"); + wi::lua::SError(L, "SetRadius(float value) not enough arguments!"); } return 0; } @@ -387,7 +388,7 @@ namespace wiIntersect_BindLua Capsule_BindLua::Capsule_BindLua(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 2) { Vector_BindLua* bV = Luna::lightcheck(L, 1); @@ -399,24 +400,24 @@ namespace wiIntersect_BindLua XMFLOAT3 t; XMStoreFloat3(&t, XMLoadFloat4(tV)); - float r = wiLua::SGetFloat(L, 3); + float r = wi::lua::SGetFloat(L, 3); - capsule = CAPSULE(b, t, r); + capsule = Capsule(b, t, r); } else { - wiLua::SError(L, "Capsule(Vector base, tip, float radius) requires first two arguments to be of Vector type!"); + wi::lua::SError(L, "Capsule(Vector base, tip, float radius) requires first two arguments to be of Vector type!"); } } else { - wiLua::SError(L, "Capsule(Vector base, tip, float radius) not enough arguments!"); + wi::lua::SError(L, "Capsule(Vector base, tip, float radius) not enough arguments!"); } } int Capsule_BindLua::Intersects(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Capsule_BindLua* _capsule = Luna::lightcheck(L, 1); @@ -426,14 +427,14 @@ namespace wiIntersect_BindLua XMFLOAT3 normal = XMFLOAT3(0, 0, 0); float depth = 0; bool intersects = capsule.intersects(_capsule->capsule, position, normal, depth); - wiLua::SSetBool(L, intersects); + wi::lua::SSetBool(L, intersects); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&position))); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&normal))); - wiLua::SSetFloat(L, depth); + wi::lua::SSetFloat(L, depth); return 4; } } - wiLua::SError(L, "Intersects(Capsule other) no matching arguments! "); + wi::lua::SError(L, "Intersects(Capsule other) no matching arguments! "); return 0; } int Capsule_BindLua::GetAABB(lua_State* L) @@ -453,12 +454,12 @@ namespace wiIntersect_BindLua } int Capsule_BindLua::GetRadius(lua_State* L) { - wiLua::SSetFloat(L, capsule.radius); + wi::lua::SSetFloat(L, capsule.radius); return 1; } int Capsule_BindLua::SetBase(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* cV = Luna::lightcheck(L, 1); @@ -468,18 +469,18 @@ namespace wiIntersect_BindLua } else { - wiLua::SError(L, "SetBase(Vector value) requires first argument to be of Vector type!"); + wi::lua::SError(L, "SetBase(Vector value) requires first argument to be of Vector type!"); } } else { - wiLua::SError(L, "SetBase(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetBase(Vector value) not enough arguments!"); } return 0; } int Capsule_BindLua::SetTip(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* cV = Luna::lightcheck(L, 1); @@ -489,25 +490,25 @@ namespace wiIntersect_BindLua } else { - wiLua::SError(L, "SetTip(Vector value) requires first argument to be of Vector type!"); + wi::lua::SError(L, "SetTip(Vector value) requires first argument to be of Vector type!"); } } else { - wiLua::SError(L, "SetTip(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetTip(Vector value) not enough arguments!"); } return 0; } int Capsule_BindLua::SetRadius(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - capsule.radius = wiLua::SGetFloat(L, 1); + capsule.radius = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetRadius(float value) not enough arguments!"); + wi::lua::SError(L, "SetRadius(float value) not enough arguments!"); } return 0; } diff --git a/WickedEngine/wiIntersect_BindLua.h b/WickedEngine/wiPrimitive_BindLua.h similarity index 78% rename from WickedEngine/wiIntersect_BindLua.h rename to WickedEngine/wiPrimitive_BindLua.h index 26d04259b..45e6b82b6 100644 --- a/WickedEngine/wiIntersect_BindLua.h +++ b/WickedEngine/wiPrimitive_BindLua.h @@ -1,9 +1,9 @@ #pragma once #include "wiLua.h" #include "wiLuna.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" -namespace wiIntersect_BindLua +namespace wi::lua::primitive { void Bind(); @@ -11,13 +11,13 @@ namespace wiIntersect_BindLua class Ray_BindLua { public: - RAY ray; + wi::primitive::Ray ray; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - Ray_BindLua(const RAY& ray) : ray(ray) {} + Ray_BindLua(const wi::primitive::Ray& ray) : ray(ray) {} Ray_BindLua(lua_State *L); int Intersects(lua_State* L); @@ -28,13 +28,13 @@ namespace wiIntersect_BindLua class AABB_BindLua { public: - AABB aabb; + wi::primitive::AABB aabb; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - AABB_BindLua(const AABB& aabb) : aabb(aabb) {} + AABB_BindLua(const wi::primitive::AABB& aabb) : aabb(aabb) {} AABB_BindLua(lua_State *L); int Intersects(lua_State* L); @@ -50,13 +50,13 @@ namespace wiIntersect_BindLua class Sphere_BindLua { public: - SPHERE sphere; + wi::primitive::Sphere sphere; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - Sphere_BindLua(const SPHERE& sphere) : sphere(sphere) {} + Sphere_BindLua(const wi::primitive::Sphere& sphere) : sphere(sphere) {} Sphere_BindLua(lua_State *L); int Intersects(lua_State* L); @@ -69,13 +69,13 @@ namespace wiIntersect_BindLua class Capsule_BindLua { public: - CAPSULE capsule; + wi::primitive::Capsule capsule; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - Capsule_BindLua(const CAPSULE& capsule) : capsule(capsule) {} + Capsule_BindLua(const wi::primitive::Capsule& capsule) : capsule(capsule) {} Capsule_BindLua(lua_State* L); int Intersects(lua_State* L); diff --git a/WickedEngine/wiProfiler.cpp b/WickedEngine/wiProfiler.cpp index 17d9c89ec..b482003cd 100644 --- a/WickedEngine/wiProfiler.cpp +++ b/WickedEngine/wiProfiler.cpp @@ -13,9 +13,9 @@ #include #include -using namespace wiGraphics; +using namespace wi::graphics; -namespace wiProfiler +namespace wi::profiler { bool ENABLED = false; bool initialized = false; @@ -36,7 +36,7 @@ namespace wiProfiler float time = 0; CommandList cmd = INVALID_COMMANDLIST; - wiTimer cpuTimer; + wi::Timer cpuTimer; int gpuBegin[arraysize(queryResultBuffer)]; int gpuEnd[arraysize(queryResultBuffer)]; @@ -56,7 +56,7 @@ namespace wiProfiler ranges.reserve(100); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); GPUQueryHeapDesc desc; desc.type = GpuQueryType::TIMESTAMP; @@ -77,7 +77,7 @@ namespace wiProfiler cpu_frame = BeginRangeCPU("CPU Frame"); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); CommandList cmd = device->BeginCommandList(); device->QueryReset( @@ -94,7 +94,7 @@ namespace wiProfiler if (!ENABLED || !initialized) return; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); // note: read the GPU Frame end range manually because it will be on a separate command list than start point: auto& gpu_range = ranges[gpu_frame]; @@ -156,7 +156,7 @@ namespace wiProfiler if (!ENABLED || !initialized) return 0; - range_id id = wiHelper::string_hash(name); + range_id id = wi::helper::string_hash(name); lock.lock(); @@ -164,7 +164,7 @@ namespace wiProfiler size_t differentiator = 0; while (ranges[id].in_use) { - wiHelper::hash_combine(id, differentiator++); + wi::helper::hash_combine(id, differentiator++); } ranges[id].in_use = true; ranges[id].name = name; @@ -179,7 +179,7 @@ namespace wiProfiler if (!ENABLED || !initialized) return 0; - range_id id = wiHelper::string_hash(name); + range_id id = wi::helper::string_hash(name); lock.lock(); @@ -187,14 +187,14 @@ namespace wiProfiler size_t differentiator = 0; while (ranges[id].in_use) { - wiHelper::hash_combine(id, differentiator++); + wi::helper::hash_combine(id, differentiator++); } ranges[id].in_use = true; ranges[id].name = name; ranges[id].cmd = cmd; ranges[id].gpuBegin[queryheap_idx] = nextQuery.fetch_add(1); - wiGraphics::GetDevice()->QueryEnd(&queryHeap, ranges[id].gpuBegin[queryheap_idx], cmd); + wi::graphics::GetDevice()->QueryEnd(&queryHeap, ranges[id].gpuBegin[queryheap_idx], cmd); lock.unlock(); @@ -217,7 +217,7 @@ namespace wiProfiler else { ranges[id].gpuEnd[queryheap_idx] = nextQuery.fetch_add(1); - wiGraphics::GetDevice()->QueryEnd(&queryHeap, it->second.gpuEnd[queryheap_idx], it->second.cmd); + wi::graphics::GetDevice()->QueryEnd(&queryHeap, it->second.gpuEnd[queryheap_idx], it->second.cmd); } } else @@ -235,13 +235,13 @@ namespace wiProfiler }; wi::unordered_map time_cache_cpu; wi::unordered_map time_cache_gpu; - void DrawData(const wiCanvas& canvas, float x, float y, CommandList cmd) + void DrawData(const wi::Canvas& canvas, float x, float y, CommandList cmd) { if (!ENABLED || !initialized) return; - wiImage::SetCanvas(canvas, cmd); - wiFont::SetCanvas(canvas, cmd); + wi::image::SetCanvas(canvas, cmd); + wi::font::SetCanvas(canvas, cmd); std::stringstream ss(""); ss.precision(2); @@ -299,17 +299,17 @@ namespace wiProfiler x.second.total_time = 0; } - wiFontParams params = wiFontParams(x, y, WIFONTSIZE_DEFAULT - 4, WIFALIGN_LEFT, WIFALIGN_TOP, wiColor(255, 255, 255, 255), wiColor(0, 0, 0, 255)); + wi::font::Params params = wi::font::Params(x, y, wi::font::WIFONTSIZE_DEFAULT - 4, wi::font::WIFALIGN_LEFT, wi::font::WIFALIGN_TOP, wi::Color(255, 255, 255, 255), wi::Color(0, 0, 0, 255)); - wiImageParams fx; + wi::image::Params fx; fx.pos.x = (float)params.posX; fx.pos.y = (float)params.posY; - fx.siz.x = (float)wiFont::textWidth(ss.str(), params); - fx.siz.y = (float)wiFont::textHeight(ss.str(), params); - fx.color = wiColor(20, 20, 20, 230); - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); + fx.siz.x = (float)wi::font::TextWidth(ss.str(), params); + fx.siz.y = (float)wi::font::TextHeight(ss.str(), params); + fx.color = wi::Color(20, 20, 20, 230); + wi::image::Draw(wi::texturehelper::getWhite(), fx, cmd); - wiFont::Draw(ss.str(), params, cmd); + wi::font::Draw(ss.str(), params, cmd); } void SetEnabled(bool value) diff --git a/WickedEngine/wiProfiler.h b/WickedEngine/wiProfiler.h index b028b5fbb..679c00bf8 100644 --- a/WickedEngine/wiProfiler.h +++ b/WickedEngine/wiProfiler.h @@ -2,7 +2,7 @@ #include "wiGraphicsDevice.h" #include "wiCanvas.h" -namespace wiProfiler +namespace wi::profiler { typedef size_t range_id; @@ -10,19 +10,19 @@ namespace wiProfiler void BeginFrame(); // Finalize collecting profiling data for the current frame - void EndFrame(wiGraphics::CommandList cmd); + void EndFrame(wi::graphics::CommandList cmd); // Start a CPU profiling range range_id BeginRangeCPU(const char* name); // Start a GPU profiling range - range_id BeginRangeGPU(const char* name, wiGraphics::CommandList cmd); + range_id BeginRangeGPU(const char* name, wi::graphics::CommandList cmd); // End a profiling range void EndRange(range_id id); // Renders a basic text of the Profiling results to the (x,y) screen coordinate - void DrawData(const wiCanvas& canvas, float x, float y, wiGraphics::CommandList cmd); + void DrawData(const wi::Canvas& canvas, float x, float y, wi::graphics::CommandList cmd); // Enable/disable profiling void SetEnabled(bool value); diff --git a/WickedEngine/wiRandom.cpp b/WickedEngine/wiRandom.cpp index 2c14b0148..a8a4ac218 100644 --- a/WickedEngine/wiRandom.cpp +++ b/WickedEngine/wiRandom.cpp @@ -1,41 +1,43 @@ #include "wiRandom.h" + #include -namespace wiRandom +namespace wi::random { - std::mt19937 &generator() { + inline static std::mt19937 &generator() + { static std::random_device rand_dev; - static std::mt19937 generator(rand_dev()); + static std::mt19937 generator(rand_dev()); return generator; } - int getRandom(int minValue, int maxValue) + int GetRandom(int minValue, int maxValue) { std::uniform_int_distribution distr(minValue, maxValue); return distr(generator()); } - int getRandom(int maxValue) + int GetRandom(int maxValue) { - return getRandom(0, maxValue); + return GetRandom(0, maxValue); } - uint32_t getRandom(uint32_t minValue, uint32_t maxValue) + uint32_t GetRandom(uint32_t minValue, uint32_t maxValue) { std::uniform_int_distribution distr(minValue, maxValue); return distr(generator()); } - uint32_t getRandom(uint32_t maxValue) + uint32_t GetRandom(uint32_t maxValue) { - return getRandom(0u, maxValue); + return GetRandom(0u, maxValue); } - uint64_t getRandom(uint64_t minValue, uint64_t maxValue) + uint64_t GetRandom(uint64_t minValue, uint64_t maxValue) { std::uniform_int_distribution distr(minValue, maxValue); return distr(generator()); } - uint64_t getRandom(uint64_t maxValue) + uint64_t GetRandom(uint64_t maxValue) { - return getRandom(0ull, maxValue); + return GetRandom(0ull, maxValue); } } diff --git a/WickedEngine/wiRandom.h b/WickedEngine/wiRandom.h index fc9a3b9bc..7e30b2777 100644 --- a/WickedEngine/wiRandom.h +++ b/WickedEngine/wiRandom.h @@ -1,16 +1,15 @@ #pragma once - #include -namespace wiRandom +namespace wi::random { - int getRandom(int minValue, int maxValue); - int getRandom(int maxValue); + int GetRandom(int minValue, int maxValue); + int GetRandom(int maxValue); - uint32_t getRandom(uint32_t minValue, uint32_t maxValue); - uint32_t getRandom(uint32_t maxValue); + uint32_t GetRandom(uint32_t minValue, uint32_t maxValue); + uint32_t GetRandom(uint32_t maxValue); - uint64_t getRandom(uint64_t minValue, uint64_t maxValue); - uint64_t getRandom(uint64_t maxValue); + uint64_t GetRandom(uint64_t minValue, uint64_t maxValue); + uint64_t GetRandom(uint64_t maxValue); }; diff --git a/WickedEngine/wiRawInput.cpp b/WickedEngine/wiRawInput.cpp index 660f909ae..21755370a 100644 --- a/WickedEngine/wiRawInput.cpp +++ b/WickedEngine/wiRawInput.cpp @@ -4,19 +4,15 @@ #if defined(_WIN32) && !defined(PLATFORM_UWP) #include "wiVector.h" +#include #include #include #pragma comment(lib,"Hid.lib") -namespace wiRawInput +namespace wi::input::rawinput { - - constexpr size_t Align(size_t value, size_t alignment) - { - return ((value + alignment - 1) / alignment) * alignment; - } - + // Simple LinearAllocator that will enforce data alignment class AlignedLinearAllocator { public: @@ -24,12 +20,10 @@ namespace wiRawInput { _aligned_free(buffer); } - constexpr size_t get_capacity() const { return capacity; } - inline void reserve(size_t newCapacity, size_t align) { alignment = align; @@ -39,7 +33,6 @@ namespace wiRawInput _aligned_free(buffer); buffer = (uint8_t*)_aligned_malloc(capacity, alignment); } - constexpr uint8_t* allocate(size_t size) { size = Align(size, alignment); @@ -51,19 +44,16 @@ namespace wiRawInput } return nullptr; } - constexpr void free(size_t size) { size = Align(size, alignment); assert(offset >= size); offset -= size; } - constexpr void reset() { offset = 0; } - constexpr uint8_t* top() { return &buffer[offset]; @@ -74,20 +64,25 @@ namespace wiRawInput size_t capacity = 0; size_t offset = 0; size_t alignment = 1; + + constexpr size_t Align(size_t value, size_t alignment) + { + return ((value + alignment - 1) / alignment) * alignment; + } }; AlignedLinearAllocator allocator; wi::vector input_messages; - wiInput::KeyboardState keyboard; - wiInput::MouseState mouse; + wi::input::KeyboardState keyboard; + wi::input::MouseState mouse; struct Internal_ControllerState { HANDLE handle = NULL; bool is_xinput = false; std::wstring name; - wiInput::ControllerState state; + wi::input::ControllerState state; }; wi::vector controllers; @@ -299,12 +294,12 @@ namespace wiRawInput ); assert(status == HIDP_STATUS_SUCCESS); - wiInput::ControllerState& controller = internal_controller.state; + wi::input::ControllerState& controller = internal_controller.state; for (ULONG i = 0; i < numberOfButtons; i++) { int button = usage[i] - pButtonCaps->Range.UsageMin; - controller.buttons |= 1 << (button + wiInput::GAMEPAD_BUTTON_1 - wiInput::GAMEPAD_RANGE_START - 1); + controller.buttons |= 1 << (button + wi::input::GAMEPAD_BUTTON_1 - wi::input::GAMEPAD_RANGE_START - 1); } for (USHORT i = 0; i < Caps.NumberInputValueCaps; i++) @@ -356,7 +351,7 @@ namespace wiRawInput case POV_UP: case POV_UPRIGHT: case POV_LEFTUP: - controller.buttons |= 1 << (wiInput::GAMEPAD_BUTTON_UP - wiInput::GAMEPAD_RANGE_START - 1); + controller.buttons |= 1 << (wi::input::GAMEPAD_BUTTON_UP - wi::input::GAMEPAD_RANGE_START - 1); break; } switch (pov) @@ -364,7 +359,7 @@ namespace wiRawInput case POV_RIGHT: case POV_UPRIGHT: case POV_RIGHTDOWN: - controller.buttons |= 1 << (wiInput::GAMEPAD_BUTTON_RIGHT - wiInput::GAMEPAD_RANGE_START - 1); + controller.buttons |= 1 << (wi::input::GAMEPAD_BUTTON_RIGHT - wi::input::GAMEPAD_RANGE_START - 1); break; } switch (pov) @@ -372,7 +367,7 @@ namespace wiRawInput case POV_DOWN: case POV_RIGHTDOWN: case POV_DOWNLEFT: - controller.buttons |= 1 << (wiInput::GAMEPAD_BUTTON_DOWN - wiInput::GAMEPAD_RANGE_START - 1); + controller.buttons |= 1 << (wi::input::GAMEPAD_BUTTON_DOWN - wi::input::GAMEPAD_RANGE_START - 1); break; } switch (pov) @@ -380,7 +375,7 @@ namespace wiRawInput case POV_LEFT: case POV_DOWNLEFT: case POV_LEFTUP: - controller.buttons |= 1 << (wiInput::GAMEPAD_BUTTON_LEFT - wiInput::GAMEPAD_RANGE_START - 1); + controller.buttons |= 1 << (wi::input::GAMEPAD_BUTTON_LEFT - wi::input::GAMEPAD_RANGE_START - 1); break; } } @@ -396,11 +391,11 @@ namespace wiRawInput void Update() { - keyboard = wiInput::KeyboardState(); - mouse = wiInput::MouseState(); + keyboard = wi::input::KeyboardState(); + mouse = wi::input::MouseState(); for (auto& internal_controller : controllers) { - internal_controller.state = wiInput::ControllerState(); + internal_controller.state = wi::input::ControllerState(); } // Enumerate devices to detect lost devices: @@ -508,12 +503,12 @@ namespace wiRawInput } } - void GetKeyboardState(wiInput::KeyboardState* state) + void GetKeyboardState(wi::input::KeyboardState* state) { *state = keyboard; } - void GetMouseState(wiInput::MouseState* state) + void GetMouseState(wi::input::MouseState* state) { *state = mouse; } @@ -522,7 +517,7 @@ namespace wiRawInput { return (int)controllers.size(); } - bool GetControllerState(wiInput::ControllerState* state, int index) + bool GetControllerState(wi::input::ControllerState* state, int index) { if (index < (int)controllers.size() && controllers[index].handle && !controllers[index].is_xinput) { @@ -534,7 +529,7 @@ namespace wiRawInput } return false; } - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index) + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index) { if (index < (int)controllers.size() && controllers[index].handle && !controllers[index].is_xinput) { @@ -564,14 +559,14 @@ namespace wiRawInput } #else -namespace wiRawInput +namespace wi::input::rawinput { void Initialize() {} void Update() {} - void GetKeyboardState(wiInput::KeyboardState* state) {} - void GetMouseState(wiInput::MouseState* state) {} + void GetKeyboardState(wi::input::KeyboardState* state) {} + void GetMouseState(wi::input::MouseState* state) {} int GetMaxControllerCount() { return 0; } - bool GetControllerState(wiInput::ControllerState* state, int index) { return false; } - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index) {} + bool GetControllerState(wi::input::ControllerState* state, int index) { return false; } + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index) {} } #endif // _WIN32 diff --git a/WickedEngine/wiRawInput.h b/WickedEngine/wiRawInput.h index 5d35d3755..5b6eb6667 100644 --- a/WickedEngine/wiRawInput.h +++ b/WickedEngine/wiRawInput.h @@ -2,7 +2,7 @@ #include "CommonInclude.h" #include "wiInput.h" -namespace wiRawInput +namespace wi::input::rawinput { // Call this once to register raw input devices void Initialize(); @@ -14,18 +14,18 @@ namespace wiRawInput void ParseMessage(void* lparam); // Writes the keyboard state into state parameter - void GetKeyboardState(wiInput::KeyboardState* state); + void GetKeyboardState(wi::input::KeyboardState* state); // Writes the mouse state into state parameter - void GetMouseState(wiInput::MouseState* state); + void GetMouseState(wi::input::MouseState* state); // Returns how many controller devices have received input ever. This doesn't correlate with which ones are currently available int GetMaxControllerCount(); // Returns whether the controller identified by index parameter is available or not // Id state parameter is not nullptr, and the controller is available, the state will be written into it - bool GetControllerState(wiInput::ControllerState* state, int index); + bool GetControllerState(wi::input::ControllerState* state, int index); // Sends feedback data for the controller identified by index parameter to output - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index); + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index); } diff --git a/WickedEngine/wiRectPacker.cpp b/WickedEngine/wiRectPacker.cpp index 94c12879c..c0b6c18b7 100644 --- a/WickedEngine/wiRectPacker.cpp +++ b/WickedEngine/wiRectPacker.cpp @@ -2,7 +2,7 @@ #include -namespace wiRectPacker +namespace wi::rectpacker { bool area(rect_xywh* a, rect_xywh* b) { diff --git a/WickedEngine/wiRectPacker.h b/WickedEngine/wiRectPacker.h index 28bd0a6c6..baab69340 100644 --- a/WickedEngine/wiRectPacker.h +++ b/WickedEngine/wiRectPacker.h @@ -38,7 +38,7 @@ For description how to tune the algorithm and how it actually works see the .cpp #include "wiVector.h" -namespace wiRectPacker +namespace wi::rectpacker { struct rect_ltrb; diff --git a/WickedEngine/wiRenderPath.h b/WickedEngine/wiRenderPath.h new file mode 100644 index 000000000..3e1b81dce --- /dev/null +++ b/WickedEngine/wiRenderPath.h @@ -0,0 +1,43 @@ +#pragma once +#include "CommonInclude.h" +#include "wiGraphicsDevice.h" +#include "wiCanvas.h" + +namespace wi +{ + class RenderPath : public wi::Canvas + { + private: + uint32_t layerMask = 0xFFFFFFFF; + + public: + virtual ~RenderPath() = default; + + // load resources in background (for example behind loading screen) + virtual void Load() {} + // called when RenderPath gets activated + virtual void Start() {} + // called when RenderPath gets deactivated (for example when switching to an other RenderPath) + virtual void Stop() {} + // executed before Update() + virtual void PreUpdate() {} + // update with fixed frequency + virtual void FixedUpdate() {} + // update once per frame + // dt : elapsed time since last call in seconds + virtual void Update(float dt) {} + // executed after Update() + virtual void PostUpdate() {} + // Render to layers, rendertargets, etc + // This will be rendered offscreen + virtual void Render() const {} + // Compose the rendered layers (for example blend the layers together as Images) + // This will be rendered to the backbuffer + virtual void Compose(wi::graphics::CommandList cmd) const {} + + inline uint32_t getLayerMask() const { return layerMask; } + inline void setlayerMask(uint32_t value) { layerMask = value; } + + wi::graphics::ColorSpace colorspace = wi::graphics::ColorSpace::SRGB; + }; +} diff --git a/WickedEngine/wiRenderPath2D.cpp b/WickedEngine/wiRenderPath2D.cpp new file mode 100644 index 000000000..597d7c84e --- /dev/null +++ b/WickedEngine/wiRenderPath2D.cpp @@ -0,0 +1,554 @@ +#include "wiRenderPath2D.h" +#include "wiResourceManager.h" +#include "wiSprite.h" +#include "wiSpriteFont.h" +#include "wiRenderer.h" + +using namespace wi::graphics; + +namespace wi +{ + + void RenderPath2D::ResizeBuffers() + { + current_buffersize = GetInternalResolution(); + current_layoutscale = 0; // invalidate layout + + GraphicsDevice* device = wi::graphics::GetDevice(); + + const Texture* dsv = GetDepthStencil(); + if (dsv != nullptr && (resolutionScale != 1.0f || dsv->GetDesc().sample_count > 1)) + { + TextureDesc desc = GetDepthStencil()->GetDesc(); + desc.layout = ResourceState::SHADER_RESOURCE; + desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; + desc.format = Format::R8G8B8A8_UNORM; + device->CreateTexture(&desc, nullptr, &rtStenciled); + device->SetName(&rtStenciled, "rtStenciled"); + + if (desc.sample_count > 1) + { + desc.sample_count = 1; + device->CreateTexture(&desc, nullptr, &rtStenciled_resolved); + device->SetName(&rtStenciled_resolved, "rtStenciled_resolved"); + } + } + else + { + rtStenciled = Texture(); // this will be deleted here + } + + { + TextureDesc desc; + desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; + desc.format = Format::R8G8B8A8_UNORM; + desc.width = GetPhysicalWidth(); + desc.height = GetPhysicalHeight(); + device->CreateTexture(&desc, nullptr, &rtFinal); + device->SetName(&rtFinal, "rtFinal"); + } + + if (rtStenciled.IsValid()) + { + RenderPassDesc desc; + desc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtStenciled, RenderPassAttachment::LoadOp::CLEAR)); + desc.attachments.push_back( + RenderPassAttachment::DepthStencil( + dsv, + RenderPassAttachment::LoadOp::LOAD, + RenderPassAttachment::StoreOp::STORE, + ResourceState::DEPTHSTENCIL_READONLY, + ResourceState::DEPTHSTENCIL_READONLY, + ResourceState::DEPTHSTENCIL_READONLY + ) + ); + + if (rtStenciled.GetDesc().sample_count > 1) + { + desc.attachments.push_back(RenderPassAttachment::Resolve(&rtStenciled_resolved)); + } + + device->CreateRenderPass(&desc, &renderpass_stenciled); + + dsv = nullptr; + } + { + RenderPassDesc desc; + desc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtFinal, RenderPassAttachment::LoadOp::CLEAR)); + + if (dsv != nullptr && !rtStenciled.IsValid()) + { + desc.attachments.push_back( + RenderPassAttachment::DepthStencil( + dsv, + RenderPassAttachment::LoadOp::LOAD, + RenderPassAttachment::StoreOp::STORE, + ResourceState::DEPTHSTENCIL_READONLY, + ResourceState::DEPTHSTENCIL_READONLY, + ResourceState::DEPTHSTENCIL_READONLY + ) + ); + } + + device->CreateRenderPass(&desc, &renderpass_final); + } + + } + void RenderPath2D::ResizeLayout() + { + current_layoutscale = GetDPIScaling(); + } + + void RenderPath2D::Update(float dt) + { + XMUINT2 internalResolution = GetInternalResolution(); + + if (current_buffersize.x != internalResolution.x || current_buffersize.y != internalResolution.y) + { + ResizeBuffers(); + } + if (current_layoutscale != GetDPIScaling()) + { + ResizeLayout(); + } + + GetGUI().Update(*this, dt); + + for (auto& x : layers) + { + for (auto& y : x.items) + { + switch (y.type) + { + default: + case RenderItem2D::SPRITE: + if (y.sprite != nullptr) + { + y.sprite->Update(dt); + } + break; + case RenderItem2D::FONT: + if (y.font != nullptr) + { + y.font->Update(dt); + } + break; + } + } + } + + if (colorspace != ColorSpace::SRGB && (rtLinearColorSpace.desc.width != rtFinal.desc.width || rtLinearColorSpace.desc.height != rtFinal.desc.height)) + { + TextureDesc desc = rtFinal.desc; + desc.format = Format::R16G16B16A16_FLOAT; + bool success = wi::graphics::GetDevice()->CreateTexture(&desc, nullptr, &rtLinearColorSpace); + assert(success); + wi::graphics::GetDevice()->SetName(&rtLinearColorSpace, "rtLinearColorSpace"); + + RenderPassDesc renderpassdesc; + renderpassdesc.attachments.push_back(RenderPassAttachment::RenderTarget(&rtLinearColorSpace, RenderPassAttachment::LoadOp::CLEAR)); + success = wi::graphics::GetDevice()->CreateRenderPass(&renderpassdesc, &renderpass_linearize); + assert(success); + } + + RenderPath::Update(dt); + } + void RenderPath2D::FixedUpdate() + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + switch (y.type) + { + default: + case RenderItem2D::SPRITE: + if (y.sprite != nullptr) + { + y.sprite->FixedUpdate(); + } + break; + case RenderItem2D::FONT: + if (y.font != nullptr) + { + y.font->FixedUpdate(); + } + break; + } + } + } + + RenderPath::FixedUpdate(); + } + void RenderPath2D::Render() const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + CommandList cmd = device->BeginCommandList(); + wi::image::SetCanvas(*this, cmd); + wi::font::SetCanvas(*this, cmd); + + wi::renderer::ProcessDeferredMipGenRequests(cmd); + + if (GetGUIBlurredBackground() != nullptr) + { + wi::image::SetBackground(*GetGUIBlurredBackground(), cmd); + } + + // Special care for internal resolution, because stencil buffer is of internal resolution, + // so we might need to render stencil sprites to separate render target that matches internal resolution! + if (rtStenciled.IsValid()) + { + device->RenderPassBegin(&renderpass_stenciled, cmd); + + Viewport vp; + vp.width = (float)rtStenciled.GetDesc().width; + vp.height = (float)rtStenciled.GetDesc().height; + device->BindViewports(1, &vp, cmd); + + device->EventBegin("STENCIL Sprite Layers", cmd); + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::SPRITE && + y.sprite != nullptr && + y.sprite->params.stencilComp != wi::image::STENCILMODE_DISABLED) + { + y.sprite->Draw(cmd); + } + } + } + device->EventEnd(cmd); + + device->RenderPassEnd(cmd); + } + + device->RenderPassBegin(&renderpass_final, cmd); + + Viewport vp; + vp.width = (float)rtFinal.GetDesc().width; + vp.height = (float)rtFinal.GetDesc().height; + device->BindViewports(1, &vp, cmd); + + if (GetDepthStencil() != nullptr) + { + if (rtStenciled.IsValid()) + { + device->EventBegin("Copy STENCIL Sprite Layers", cmd); + wi::image::Params fx; + fx.enableFullScreen(); + if (rtStenciled.GetDesc().sample_count > 1) + { + wi::image::Draw(&rtStenciled_resolved, fx, cmd); + } + else + { + wi::image::Draw(&rtStenciled, fx, cmd); + } + device->EventEnd(cmd); + } + else + { + device->EventBegin("STENCIL Sprite Layers", cmd); + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::SPRITE && + y.sprite != nullptr && + y.sprite->params.stencilComp != wi::image::STENCILMODE_DISABLED) + { + y.sprite->Draw(cmd); + } + } + } + device->EventEnd(cmd); + } + } + + device->EventBegin("Sprite Layers", cmd); + for (auto& x : layers) + { + for (auto& y : x.items) + { + switch (y.type) + { + default: + case RenderItem2D::SPRITE: + if (y.sprite != nullptr && y.sprite->params.stencilComp == wi::image::STENCILMODE_DISABLED) + { + y.sprite->Draw(cmd); + } + break; + case RenderItem2D::FONT: + if (y.font != nullptr) + { + y.font->Draw(cmd); + } + break; + } + } + } + device->EventEnd(cmd); + + GetGUI().Render(*this, cmd); + + device->RenderPassEnd(cmd); + + if (colorspace != ColorSpace::SRGB) + { + // Convert the regular SRGB result of the render path to linear space for HDR compositing: + device->RenderPassBegin(&renderpass_linearize, cmd); + wi::image::Params fx; + fx.enableFullScreen(); + fx.enableLinearOutputMapping(hdr_scaling); + wi::image::Draw(&rtFinal, fx, cmd); + device->RenderPassEnd(cmd); + render_result = rtLinearColorSpace; + } + else + { + render_result = rtFinal; + } + + RenderPath::Render(); + } + void RenderPath2D::Compose(CommandList cmd) const + { + wi::image::Params fx; + fx.enableFullScreen(); + fx.blendFlag = wi::enums::BLENDMODE_PREMULTIPLIED; + wi::image::Draw(&render_result, fx, cmd); + + RenderPath::Compose(cmd); + } + + + void RenderPath2D::AddSprite(wi::Sprite* sprite, const std::string& layer) + { + for (auto& x : layers) + { + if (!x.name.compare(layer)) + { + x.items.push_back(RenderItem2D()); + x.items.back().type = RenderItem2D::SPRITE; + x.items.back().sprite = sprite; + } + } + SortLayers(); + } + void RenderPath2D::RemoveSprite(wi::Sprite* sprite) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::SPRITE && y.sprite == sprite) + { + y.sprite = nullptr; + } + } + } + CleanLayers(); + } + void RenderPath2D::ClearSprites() + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::SPRITE) + { + y.sprite = nullptr; + } + } + } + CleanLayers(); + } + int RenderPath2D::GetSpriteOrder(wi::Sprite* sprite) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.sprite == sprite) + { + return y.order; + } + } + } + return 0; + } + + void RenderPath2D::AddFont(wi::SpriteFont* font, const std::string& layer) + { + for (auto& x : layers) + { + if (!x.name.compare(layer)) + { + x.items.push_back(RenderItem2D()); + x.items.back().type = RenderItem2D::FONT; + x.items.back().font = font; + } + } + SortLayers(); + } + void RenderPath2D::RemoveFont(wi::SpriteFont* font) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::FONT && y.font == font) + { + y.font = nullptr; + } + } + } + CleanLayers(); + } + void RenderPath2D::ClearFonts() + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::FONT) + { + y.font = nullptr; + } + } + } + CleanLayers(); + } + int RenderPath2D::GetFontOrder(wi::SpriteFont* font) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.font == font) + { + return y.order; + } + } + } + return 0; + } + + + void RenderPath2D::AddLayer(const std::string& name) + { + for (auto& x : layers) + { + if (!x.name.compare(name)) + return; + } + RenderLayer2D layer; + layer.name = name; + layer.order = (int)layers.size(); + layers.push_back(layer); + layers.back().items.clear(); + } + void RenderPath2D::SetLayerOrder(const std::string& name, int order) + { + for (auto& x : layers) + { + if (!x.name.compare(name)) + { + x.order = order; + break; + } + } + SortLayers(); + } + void RenderPath2D::SetSpriteOrder(wi::Sprite* sprite, int order) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::SPRITE && y.sprite == sprite) + { + y.order = order; + } + } + } + SortLayers(); + } + void RenderPath2D::SetFontOrder(wi::SpriteFont* font, int order) + { + for (auto& x : layers) + { + for (auto& y : x.items) + { + if (y.type == RenderItem2D::FONT && y.font == font) + { + y.order = order; + } + } + } + SortLayers(); + } + void RenderPath2D::SortLayers() + { + if (layers.empty()) + { + return; + } + + for (size_t i = 0; i < layers.size() - 1; ++i) + { + for (size_t j = i + 1; j < layers.size(); ++j) + { + if (layers[i].order > layers[j].order) + { + RenderLayer2D swap = layers[i]; + layers[i] = layers[j]; + layers[j] = swap; + } + } + } + for (auto& x : layers) + { + if (x.items.empty()) + { + continue; + } + for (size_t i = 0; i < x.items.size() - 1; ++i) + { + for (size_t j = i + 1; j < x.items.size(); ++j) + { + if (x.items[i].order > x.items[j].order) + { + RenderItem2D swap = x.items[i]; + x.items[i] = x.items[j]; + x.items[j] = swap; + } + } + } + } + } + + void RenderPath2D::CleanLayers() + { + for (auto& x : layers) + { + if (x.items.empty()) + { + continue; + } + wi::vector itemsToRetain(0); + for (auto& y : x.items) + { + if (y.sprite != nullptr || y.font != nullptr) + { + itemsToRetain.push_back(y); + } + } + x.items.clear(); + x.items = itemsToRetain; + } + } + +} diff --git a/WickedEngine/wiRenderPath2D.h b/WickedEngine/wiRenderPath2D.h new file mode 100644 index 000000000..13378c127 --- /dev/null +++ b/WickedEngine/wiRenderPath2D.h @@ -0,0 +1,106 @@ +#pragma once +#include "wiRenderPath.h" +#include "wiGUI.h" +#include "wiVector.h" + +#include + +namespace wi +{ + class Sprite; + class SpriteFont; + + struct RenderItem2D + { + enum TYPE + { + SPRITE, + FONT, + } type = SPRITE; + union + { + wi::Sprite* sprite = nullptr; + wi::SpriteFont* font; + }; + int order = 0; + }; + struct RenderLayer2D + { + wi::vector items; + std::string name; + int order = 0; + }; + + class RenderPath2D : + public RenderPath + { + private: + wi::graphics::Texture rtStenciled; + wi::graphics::Texture rtStenciled_resolved; + wi::graphics::Texture rtFinal; + + wi::graphics::RenderPass renderpass_stenciled; + wi::graphics::RenderPass renderpass_final; + + wi::graphics::Texture rtLinearColorSpace; + wi::graphics::RenderPass renderpass_linearize; + + wi::gui::GUI GUI; + + XMUINT2 current_buffersize{}; + float current_layoutscale{}; + + mutable wi::graphics::Texture render_result = rtFinal; + + float hdr_scaling = 9.0f; + + public: + // create resolution dependent resources, such as render targets + virtual void ResizeBuffers(); + // update DPI dependent elements, such as GUI elements, sprites + virtual void ResizeLayout(); + + void Update(float dt) override; + void FixedUpdate() override; + void Render() const override; + void Compose(wi::graphics::CommandList cmd) const override; + + const wi::graphics::Texture& GetRenderResult() const { return render_result; } + virtual const wi::graphics::Texture* GetDepthStencil() const { return nullptr; } + virtual const wi::graphics::Texture* GetGUIBlurredBackground() const { return nullptr; } + + void AddSprite(wi::Sprite* sprite, const std::string& layer = ""); + void RemoveSprite(wi::Sprite* sprite); + void ClearSprites(); + int GetSpriteOrder(wi::Sprite* sprite); + + void AddFont(wi::SpriteFont* font, const std::string& layer = ""); + void RemoveFont(wi::SpriteFont* font); + void ClearFonts(); + int GetFontOrder(wi::SpriteFont* font); + + wi::vector layers{ 1 }; + void AddLayer(const std::string& name); + void SetLayerOrder(const std::string& name, int order); + void SetSpriteOrder(wi::Sprite* sprite, int order); + void SetFontOrder(wi::SpriteFont* font, int order); + void SortLayers(); + void CleanLayers(); + + const wi::gui::GUI& GetGUI() const { return GUI; } + wi::gui::GUI& GetGUI() { return GUI; } + + float resolutionScale = 1.0f; + XMUINT2 GetInternalResolution() const + { + return XMUINT2( + uint32_t((float)GetPhysicalWidth() * resolutionScale), + uint32_t((float)GetPhysicalHeight() * resolutionScale) + ); + } + + float GetHDRScaling() const { return hdr_scaling; } + void SetHDRScaling(float value) { hdr_scaling = value; } + }; + +} diff --git a/WickedEngine/wiRenderPath2D_BindLua.cpp b/WickedEngine/wiRenderPath2D_BindLua.cpp new file mode 100644 index 000000000..b3cb9c1a7 --- /dev/null +++ b/WickedEngine/wiRenderPath2D_BindLua.cpp @@ -0,0 +1,428 @@ +#include "wiRenderPath2D_BindLua.h" +#include "wiSprite_BindLua.h" +#include "wiSpriteFont_BindLua.h" + +#include + +namespace wi::lua +{ + + const char RenderPath2D_BindLua::className[] = "RenderPath2D"; + + Luna::FunctionType RenderPath2D_BindLua::methods[] = { + lunamethod(RenderPath2D_BindLua, AddSprite), + lunamethod(RenderPath2D_BindLua, AddFont), + lunamethod(RenderPath2D_BindLua, RemoveSprite), + lunamethod(RenderPath2D_BindLua, RemoveFont), + lunamethod(RenderPath2D_BindLua, ClearSprites), + lunamethod(RenderPath2D_BindLua, ClearFonts), + lunamethod(RenderPath2D_BindLua, GetSpriteOrder), + lunamethod(RenderPath2D_BindLua, GetFontOrder), + lunamethod(RenderPath2D_BindLua, AddLayer), + lunamethod(RenderPath2D_BindLua, GetLayers), + lunamethod(RenderPath2D_BindLua, SetLayerOrder), + lunamethod(RenderPath2D_BindLua, SetSpriteOrder), + lunamethod(RenderPath2D_BindLua, SetFontOrder), + lunamethod(RenderPath_BindLua, GetLayerMask), + lunamethod(RenderPath_BindLua, SetLayerMask), + { NULL, NULL } + }; + Luna::PropertyType RenderPath2D_BindLua::properties[] = { + { NULL, NULL } + }; + + int RenderPath2D_BindLua::AddSprite(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "AddSprite() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::Sprite_BindLua* sprite = Luna::lightcheck(L, 1); + if (sprite != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + if (argc > 1) + ccomp->AddSprite(&sprite->sprite, wi::lua::SGetString(L, 2)); + else + ccomp->AddSprite(&sprite->sprite); + } + else + { + wi::lua::SError(L, "AddSprite(Sprite sprite, opt string layer) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "AddSprite(Sprite sprite, opt string layer) argument is not a Sprite!"); + } + else + { + wi::lua::SError(L, "AddSprite(Sprite sprite, opt string layer) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::AddFont(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "AddFont() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::SpriteFont_BindLua* font = Luna::lightcheck(L, 1); + if (font != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + if (argc > 1) + ccomp->AddFont(&font->font, wi::lua::SGetString(L, 2)); + else + ccomp->AddFont(&font->font); + } + else + { + wi::lua::SError(L, "AddFont(Font font, opt string layer) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "AddFont(Font font, opt string layer) argument is not a Font!"); + } + else + { + wi::lua::SError(L, "AddFont(Font font, opt string layer) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::RemoveSprite(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "RemoveSprite() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::Sprite_BindLua* sprite = Luna::lightcheck(L, 1); + if (sprite != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->RemoveSprite(&sprite->sprite); + } + else + { + wi::lua::SError(L, "RemoveSprite(Sprite sprite) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "RemoveSprite(Sprite sprite) argument is not a Sprite!"); + } + else + { + wi::lua::SError(L, "RemoveSprite(Sprite sprite) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::RemoveFont(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "RemoveFont() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::SpriteFont_BindLua* font = Luna::lightcheck(L, 1); + if (font != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->RemoveFont(&font->font); + } + else + { + wi::lua::SError(L, "RemoveFont(Font font) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "RemoveFont(Font font) argument is not a Font!"); + } + else + { + wi::lua::SError(L, "RemoveFont(Font font) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::ClearSprites(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "ClearSprites() component is empty!"); + return 0; + } + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->ClearSprites(); + } + else + { + wi::lua::SError(L, "ClearSprites() not a RenderPath2D!"); + } + return 0; + } + int RenderPath2D_BindLua::ClearFonts(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "ClearFonts() component is empty!"); + return 0; + } + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->ClearFonts(); + } + else + { + wi::lua::SError(L, "ClearFonts() not a RenderPath2D!"); + } + return 0; + } + int RenderPath2D_BindLua::GetSpriteOrder(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "GetSpriteOrder() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::Sprite_BindLua* sprite = Luna::lightcheck(L, 1); + if (sprite != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + wi::lua::SSetInt(L, ccomp->GetSpriteOrder(&sprite->sprite)); + return 1; + } + else + { + wi::lua::SError(L, "GetSpriteOrder(Sprite sprite) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "GetSpriteOrder(Sprite sprite) argument is not a Sprite!"); + } + else + { + wi::lua::SError(L, "GetSpriteOrder(Sprite sprite) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::GetFontOrder(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "GetFontOrder() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::SpriteFont_BindLua* font = Luna::lightcheck(L, 1); + if (font != nullptr) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + wi::lua::SSetInt(L, ccomp->GetFontOrder(&font->font)); + return 1; + } + else + { + wi::lua::SError(L, "GetFontOrder(Font font) not a RenderPath2D!"); + } + } + else + wi::lua::SError(L, "GetFontOrder(Font font) argument is not a Sprite!"); + } + else + { + wi::lua::SError(L, "GetFontOrder(Font font) not enough arguments!"); + } + return 0; + } + + int RenderPath2D_BindLua::AddLayer(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "AddLayer() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->AddLayer(wi::lua::SGetString(L, 1)); + } + else + { + wi::lua::SError(L, "AddLayer(string name) not a RenderPath2D!"); + } + } + else + { + wi::lua::SError(L, "AddLayer(string name) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::GetLayers(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "GetLayers() component is empty!"); + return 0; + } + + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + std::string ss; + for (auto& x : ccomp->layers) + { + ss += x.name + "\n"; + } + wi::lua::SSetString(L, ss); + return 1; + } + else + { + wi::lua::SError(L, "GetLayers() not a RenderPath2D!"); + } + + return 0; + } + int RenderPath2D_BindLua::SetLayerOrder(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetLayerOrder() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + ccomp->SetLayerOrder(wi::lua::SGetString(L, 1), wi::lua::SGetInt(L, 2)); + } + else + { + wi::lua::SError(L, "SetLayerOrder(string name, int order) not a RenderPath2D!"); + } + } + else + { + wi::lua::SError(L, "SetLayerOrder(string name, int order) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::SetSpriteOrder(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetSpriteOrder() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + wi::lua::Sprite_BindLua* sprite = Luna::lightcheck(L, 1); + if (sprite != nullptr) + { + ccomp->SetSpriteOrder(&sprite->sprite, wi::lua::SGetInt(L, 2)); + } + else + { + wi::lua::SError(L, "SetSpriteOrder(Sprite sprite, int order) argument is not a Sprite!"); + } + } + else + { + wi::lua::SError(L, "SetSpriteOrder(Sprite sprite, int order) not a RenderPath2D!"); + } + } + else + { + wi::lua::SError(L, "SetSpriteOrder(Sprite sprite, int order) not enough arguments!"); + } + return 0; + } + int RenderPath2D_BindLua::SetFontOrder(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetFontOrder() component is empty!"); + return 0; + } + int argc = wi::lua::SGetArgCount(L); + if (argc > 1) + { + RenderPath2D* ccomp = dynamic_cast(component); + if (ccomp != nullptr) + { + wi::lua::SpriteFont_BindLua* font = Luna::lightcheck(L, 1); + if (font != nullptr) + { + ccomp->SetFontOrder(&font->font, wi::lua::SGetInt(L, 2)); + } + else + { + wi::lua::SError(L, "SetFontOrder(Font font, int order) argument is not a Font!"); + } + } + else + { + wi::lua::SError(L, "SetFontOrder(Font font, int order) not a RenderPath2D!"); + } + } + else + { + wi::lua::SError(L, "SetFontOrder(Font font, int order) not enough arguments!"); + } + return 0; + } + + void RenderPath2D_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + +} diff --git a/WickedEngine/wiRenderPath2D_BindLua.h b/WickedEngine/wiRenderPath2D_BindLua.h new file mode 100644 index 000000000..9e461478e --- /dev/null +++ b/WickedEngine/wiRenderPath2D_BindLua.h @@ -0,0 +1,48 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiRenderPath2D.h" +#include "wiRenderPath_BindLua.h" + + +namespace wi::lua +{ + + class RenderPath2D_BindLua : public RenderPath_BindLua + { + private: + RenderPath2D renderpath; + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + RenderPath2D_BindLua() = default; + RenderPath2D_BindLua(RenderPath2D* component) + { + this->component = component; + } + RenderPath2D_BindLua(lua_State* L) + { + this->component = &renderpath; + } + + int AddSprite(lua_State* L); + int AddFont(lua_State* L); + int RemoveSprite(lua_State* L); + int RemoveFont(lua_State* L); + int ClearSprites(lua_State* L); + int ClearFonts(lua_State* L); + int GetSpriteOrder(lua_State* L); + int GetFontOrder(lua_State* L); + + int AddLayer(lua_State* L); + int GetLayers(lua_State* L); + int SetLayerOrder(lua_State* L); + int SetSpriteOrder(lua_State* L); + int SetFontOrder(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/RenderPath3D.cpp b/WickedEngine/wiRenderPath3D.cpp similarity index 75% rename from WickedEngine/RenderPath3D.cpp rename to WickedEngine/wiRenderPath3D.cpp index 637331ccf..8fd49b2b2 100644 --- a/WickedEngine/RenderPath3D.cpp +++ b/WickedEngine/wiRenderPath3D.cpp @@ -1,15 +1,19 @@ -#include "RenderPath3D.h" +#include "wiRenderPath3D.h" #include "wiRenderer.h" #include "wiImage.h" #include "wiHelper.h" #include "wiTextureHelper.h" #include "wiProfiler.h" -using namespace wiGraphics; +using namespace wi::graphics; +using namespace wi::enums; + +namespace wi +{ void RenderPath3D::ResizeBuffers() { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); XMUINT2 internalResolution = GetInternalResolution(); @@ -50,17 +54,17 @@ void RenderPath3D::ResizeBuffers() desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; desc.format = Format::R32G32_UINT; - device->CreateTexture(&desc, nullptr, &rtGbuffer[GBUFFER_PRIMITIVEID]); - device->SetName(&rtGbuffer[GBUFFER_PRIMITIVEID], "rtGbuffer[GBUFFER_PRIMITIVEID]"); + device->CreateTexture(&desc, nullptr, &rtGbuffer[wi::renderer::GBUFFER_PRIMITIVEID]); + device->SetName(&rtGbuffer[wi::renderer::GBUFFER_PRIMITIVEID], "rtGbuffer[GBUFFER_PRIMITIVEID]"); desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; desc.format = Format::R16G16_FLOAT; - device->CreateTexture(&desc, nullptr, &rtGbuffer[GBUFFER_VELOCITY]); - device->SetName(&rtGbuffer[GBUFFER_VELOCITY], "rtGbuffer[GBUFFER_VELOCITY]"); + device->CreateTexture(&desc, nullptr, &rtGbuffer[wi::renderer::GBUFFER_VELOCITY]); + device->SetName(&rtGbuffer[wi::renderer::GBUFFER_VELOCITY], "rtGbuffer[GBUFFER_VELOCITY]"); if (getMSAASampleCount() > 1) { - desc = rtGbuffer[GBUFFER_PRIMITIVEID].desc; + desc = rtGbuffer[wi::renderer::GBUFFER_PRIMITIVEID].desc; desc.sample_count = getMSAASampleCount(); desc.bind_flags = BindFlag::RENDER_TARGET | BindFlag::SHADER_RESOURCE; @@ -69,7 +73,7 @@ void RenderPath3D::ResizeBuffers() } else { - rtPrimitiveID_render = rtGbuffer[GBUFFER_PRIMITIVEID]; + rtPrimitiveID_render = rtGbuffer[wi::renderer::GBUFFER_PRIMITIVEID]; } } { @@ -207,7 +211,7 @@ void RenderPath3D::ResizeBuffers() device->SetName(&rtGUIBlurredBackground[2], "rtGUIBlurredBackground[2]"); } if(device->CheckCapability(GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2) && - wiRenderer::GetVariableRateShadingClassification()) + wi::renderer::GetVariableRateShadingClassification()) { uint32_t tileSize = device->GetVariableRateShadingTileSize(); @@ -477,20 +481,20 @@ void RenderPath3D::ResizeBuffers() device->CreateTexture(&desc, nullptr, &debugUAV); device->SetName(&debugUAV, "debugUAV"); } - wiRenderer::CreateTiledLightResources(tiledLightResources, internalResolution); - wiRenderer::CreateTiledLightResources(tiledLightResources_planarReflection, XMUINT2(depthBuffer_Reflection.desc.width, depthBuffer_Reflection.desc.height)); - wiRenderer::CreateLuminanceResources(luminanceResources, internalResolution); - wiRenderer::CreateScreenSpaceShadowResources(screenspaceshadowResources, internalResolution); - wiRenderer::CreateDepthOfFieldResources(depthoffieldResources, internalResolution); - wiRenderer::CreateMotionBlurResources(motionblurResources, internalResolution); - wiRenderer::CreateVolumetricCloudResources(volumetriccloudResources, internalResolution); - wiRenderer::CreateVolumetricCloudResources(volumetriccloudResources_reflection, XMUINT2(depthBuffer_Reflection.desc.width, depthBuffer_Reflection.desc.height)); - wiRenderer::CreateBloomResources(bloomResources, internalResolution); - wiRenderer::CreateSurfelGIResources(surfelGIResources, internalResolution); + wi::renderer::CreateTiledLightResources(tiledLightResources, internalResolution); + wi::renderer::CreateTiledLightResources(tiledLightResources_planarReflection, XMUINT2(depthBuffer_Reflection.desc.width, depthBuffer_Reflection.desc.height)); + wi::renderer::CreateLuminanceResources(luminanceResources, internalResolution); + wi::renderer::CreateScreenSpaceShadowResources(screenspaceshadowResources, internalResolution); + wi::renderer::CreateDepthOfFieldResources(depthoffieldResources, internalResolution); + wi::renderer::CreateMotionBlurResources(motionblurResources, internalResolution); + wi::renderer::CreateVolumetricCloudResources(volumetriccloudResources, internalResolution); + wi::renderer::CreateVolumetricCloudResources(volumetriccloudResources_reflection, XMUINT2(depthBuffer_Reflection.desc.width, depthBuffer_Reflection.desc.height)); + wi::renderer::CreateBloomResources(bloomResources, internalResolution); + wi::renderer::CreateSurfelGIResources(surfelGIResources, internalResolution); if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiRenderer::CreateRTShadowResources(rtshadowResources, internalResolution); + wi::renderer::CreateRTShadowResources(rtshadowResources, internalResolution); } setAO(ao); @@ -518,23 +522,23 @@ void RenderPath3D::Update(float dt) if (getSceneUpdateEnabled()) { - if (wiRenderer::GetSurfelGIEnabled() || - wiRenderer::GetRaytracedShadowsEnabled() || + if (wi::renderer::GetSurfelGIEnabled() || + wi::renderer::GetRaytracedShadowsEnabled() || getAO() == AO_RTAO || getRaytracedReflectionEnabled()) { scene->SetAccelerationStructureUpdateRequested(true); } - scene->Update(dt * wiRenderer::GetGameSpeed()); + scene->Update(dt * wi::renderer::GetGameSpeed()); } // Frustum culling for main camera: visibility_main.layerMask = getLayerMask(); visibility_main.scene = scene; visibility_main.camera = camera; - visibility_main.flags = wiRenderer::Visibility::ALLOW_EVERYTHING; - wiRenderer::UpdateVisibility(visibility_main); + visibility_main.flags = wi::renderer::Visibility::ALLOW_EVERYTHING; + wi::renderer::UpdateVisibility(visibility_main); if (visibility_main.planar_reflection_visible) { @@ -545,22 +549,22 @@ void RenderPath3D::Update(float dt) visibility_reflection.layerMask = getLayerMask(); visibility_reflection.scene = scene; visibility_reflection.camera = &camera_reflection; - visibility_reflection.flags = wiRenderer::Visibility::ALLOW_OBJECTS; - wiRenderer::UpdateVisibility(visibility_reflection); + visibility_reflection.flags = wi::renderer::Visibility::ALLOW_OBJECTS; + wi::renderer::UpdateVisibility(visibility_reflection); } XMUINT2 internalResolution = GetInternalResolution(); - wiRenderer::UpdatePerFrameData( + wi::renderer::UpdatePerFrameData( *scene, visibility_main, frameCB, getSceneUpdateEnabled() ? dt : 0 ); - if (wiRenderer::GetTemporalAAEnabled()) + if (wi::renderer::GetTemporalAAEnabled()) { - const XMFLOAT4& halton = wiMath::GetHaltonSequence(wiGraphics::GetDevice()->GetFrameCount() % 256); + const XMFLOAT4& halton = wi::math::GetHaltonSequence(wi::graphics::GetDevice()->GetFrameCount() % 256); camera->jitter.x = (halton.x * 2 - 1) / (float)internalResolution.x; camera->jitter.y = (halton.y * 2 - 1) / (float)internalResolution.y; } @@ -574,7 +578,7 @@ void RenderPath3D::Update(float dt) { rtaoResources.frame = 0; } - if (!wiRenderer::GetRaytracedShadowsEnabled()) + if (!wi::renderer::GetRaytracedShadowsEnabled()) { rtshadowResources.frame = 0; } @@ -586,14 +590,14 @@ void RenderPath3D::Update(float dt) { rtAO = {}; } - if (!wiRenderer::GetScreenSpaceShadowsEnabled() && !wiRenderer::GetRaytracedShadowsEnabled()) + if (!wi::renderer::GetScreenSpaceShadowsEnabled() && !wi::renderer::GetRaytracedShadowsEnabled()) { rtShadow = {}; } - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - if((wiRenderer::GetScreenSpaceShadowsEnabled() || wiRenderer::GetRaytracedShadowsEnabled()) && !rtShadow.IsValid()) + if((wi::renderer::GetScreenSpaceShadowsEnabled() || wi::renderer::GetRaytracedShadowsEnabled()) && !rtShadow.IsValid()) { TextureDesc desc; desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; @@ -610,10 +614,11 @@ void RenderPath3D::Update(float dt) camera->canvas = *this; camera->width = (float)internalResolution.x; camera->height = (float)internalResolution.y; + camera->sample_count = depthBuffer_Main.desc.sample_count; camera->texture_depth_index = device->GetDescriptorIndex(&depthBuffer_Copy, SubresourceType::SRV); camera->texture_lineardepth_index = device->GetDescriptorIndex(&rtLinearDepth, SubresourceType::SRV); - camera->texture_gbuffer0_index = device->GetDescriptorIndex(&rtGbuffer[GBUFFER_PRIMITIVEID], SubresourceType::SRV); - camera->texture_gbuffer1_index = device->GetDescriptorIndex(&rtGbuffer[GBUFFER_VELOCITY], SubresourceType::SRV); + camera->texture_gbuffer0_index = device->GetDescriptorIndex(&rtGbuffer[wi::renderer::GBUFFER_PRIMITIVEID], SubresourceType::SRV); + camera->texture_gbuffer1_index = device->GetDescriptorIndex(&rtGbuffer[wi::renderer::GBUFFER_VELOCITY], SubresourceType::SRV); camera->buffer_entitytiles_opaque_index = device->GetDescriptorIndex(&tiledLightResources.entityTiles_Opaque, SubresourceType::SRV); camera->buffer_entitytiles_transparent_index = device->GetDescriptorIndex(&tiledLightResources.entityTiles_Transparent, SubresourceType::SRV); camera->texture_reflection_index = device->GetDescriptorIndex(&rtReflection, SubresourceType::SRV); @@ -627,6 +632,7 @@ void RenderPath3D::Update(float dt) camera_reflection.canvas = *this; camera_reflection.width = (float)depthBuffer_Reflection.desc.width; camera_reflection.height = (float)depthBuffer_Reflection.desc.height; + camera_reflection.sample_count = depthBuffer_Reflection.desc.sample_count; camera_reflection.texture_depth_index = device->GetDescriptorIndex(&depthBuffer_Reflection, SubresourceType::SRV); camera_reflection.texture_lineardepth_index = -1; camera_reflection.texture_gbuffer0_index = -1; @@ -644,45 +650,45 @@ void RenderPath3D::Update(float dt) void RenderPath3D::Render() const { - GraphicsDevice* device = wiGraphics::GetDevice(); - wiJobSystem::context ctx; + GraphicsDevice* device = wi::graphics::GetDevice(); + wi::jobsystem::context ctx; // Preparing the frame: CommandList cmd = device->BeginCommandList(); CommandList cmd_prepareframe = cmd; - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { - wiRenderer::BindCameraCB( + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::UpdateRenderData(visibility_main, frameCB, cmd); + wi::renderer::UpdateRenderData(visibility_main, frameCB, cmd); }); // async compute parallel with depth prepass cmd = device->BeginCommandList(QUEUE_COMPUTE); device->WaitCommandList(cmd, cmd_prepareframe); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::UpdateRenderDataAsync(visibility_main, frameCB, cmd); + wi::renderer::UpdateRenderDataAsync(visibility_main, frameCB, cmd); if (scene->IsAccelerationStructureUpdateRequested()) { - wiRenderer::UpdateRaytracingAccelerationStructures(*scene, cmd); + wi::renderer::UpdateRaytracingAccelerationStructures(*scene, cmd); } - if (wiRenderer::GetSurfelGIEnabled()) + if (wi::renderer::GetSurfelGIEnabled()) { - wiRenderer::SurfelGI( + wi::renderer::SurfelGI( surfelGIResources, *scene, cmd @@ -692,53 +698,53 @@ void RenderPath3D::Render() const }); static const uint32_t drawscene_flags = - wiRenderer::DRAWSCENE_OPAQUE | - wiRenderer::DRAWSCENE_HAIRPARTICLE | - wiRenderer::DRAWSCENE_TESSELLATION | - wiRenderer::DRAWSCENE_OCCLUSIONCULLING + wi::renderer::DRAWSCENE_OPAQUE | + wi::renderer::DRAWSCENE_HAIRPARTICLE | + wi::renderer::DRAWSCENE_TESSELLATION | + wi::renderer::DRAWSCENE_OCCLUSIONCULLING ; static const uint32_t drawscene_flags_reflections = - wiRenderer::DRAWSCENE_OPAQUE + wi::renderer::DRAWSCENE_OPAQUE ; // Main camera depth prepass + occlusion culling: cmd = device->BeginCommandList(); CommandList cmd_maincamera_prepass = cmd; - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::OcclusionCulling_Reset(visibility_main, cmd); // must be outside renderpass! + wi::renderer::OcclusionCulling_Reset(visibility_main, cmd); // must be outside renderpass! device->RenderPassBegin(&renderpass_depthprepass, cmd); device->EventBegin("Opaque Z-prepass", cmd); - auto range = wiProfiler::BeginRangeGPU("Z-Prepass", cmd); + auto range = wi::profiler::BeginRangeGPU("Z-Prepass", cmd); Viewport vp; vp.width = (float)depthBuffer_Main.GetDesc().width; vp.height = (float)depthBuffer_Main.GetDesc().height; device->BindViewports(1, &vp, cmd); - wiRenderer::DrawScene(visibility_main, RENDERPASS_PREPASS, cmd, drawscene_flags); + wi::renderer::DrawScene(visibility_main, RENDERPASS_PREPASS, cmd, drawscene_flags); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); if (getOcclusionCullingEnabled()) { - wiRenderer::OcclusionCulling_Render(*camera, visibility_main, cmd); + wi::renderer::OcclusionCulling_Render(*camera, visibility_main, cmd); } device->RenderPassEnd(cmd); - wiRenderer::OcclusionCulling_Resolve(visibility_main, cmd); // must be outside renderpass! + wi::renderer::OcclusionCulling_Resolve(visibility_main, cmd); // must be outside renderpass! }); @@ -748,18 +754,18 @@ void RenderPath3D::Render() const cmd = device->BeginCommandList(QUEUE_COMPUTE); device->WaitCommandList(cmd, cmd_maincamera_prepass); CommandList cmd_maincamera_compute_effects = cmd; - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::VisibilityResolve( + wi::renderer::VisibilityResolve( depthBuffer_Main, rtPrimitiveID_render, rtGbuffer, @@ -768,9 +774,9 @@ void RenderPath3D::Render() const cmd ); - if (wiRenderer::GetSurfelGIEnabled()) + if (wi::renderer::GetSurfelGIEnabled()) { - wiRenderer::SurfelGI_Coverage( + wi::renderer::SurfelGI_Coverage( surfelGIResources, *scene, debugUAV, @@ -780,9 +786,9 @@ void RenderPath3D::Render() const RenderAO(cmd); - if (wiRenderer::GetVariableRateShadingClassification() && device->CheckCapability(GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)) + if (wi::renderer::GetVariableRateShadingClassification() && device->CheckCapability(GraphicsDeviceCapability::VARIABLE_RATE_SHADING_TIER2)) { - wiRenderer::ComputeShadingRateClassification( + wi::renderer::ComputeShadingRateClassification( rtShadingRate, debugUAV, cmd @@ -791,27 +797,27 @@ void RenderPath3D::Render() const if (scene->weather.IsVolumetricClouds()) { - wiRenderer::Postprocess_VolumetricClouds( + wi::renderer::Postprocess_VolumetricClouds( volumetriccloudResources, cmd ); } { - auto range = wiProfiler::BeginRangeGPU("Entity Culling", cmd); - wiRenderer::ComputeTiledLightCulling( + auto range = wi::profiler::BeginRangeGPU("Entity Culling", cmd); + wi::renderer::ComputeTiledLightCulling( tiledLightResources, debugUAV, cmd ); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } RenderSSR(cmd); - if (wiRenderer::GetScreenSpaceShadowsEnabled()) + if (wi::renderer::GetScreenSpaceShadowsEnabled()) { - wiRenderer::Postprocess_ScreenSpaceShadow( + wi::renderer::Postprocess_ScreenSpaceShadow( screenspaceshadowResources, tiledLightResources.entityTiles_Opaque, rtShadow, @@ -821,9 +827,9 @@ void RenderPath3D::Render() const ); } - if (wiRenderer::GetRaytracedShadowsEnabled()) + if (wi::renderer::GetRaytracedShadowsEnabled()) { - wiRenderer::Postprocess_RTShadow( + wi::renderer::Postprocess_RTShadow( rtshadowResources, *scene, tiledLightResources.entityTiles_Opaque, @@ -838,32 +844,32 @@ void RenderPath3D::Render() const if (getShadowsEnabled()) { cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { - wiRenderer::DrawShadowmaps(visibility_main, cmd); + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { + wi::renderer::DrawShadowmaps(visibility_main, cmd); }); } // Updating textures: cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [cmd, this](wiJobArgs args) { - wiRenderer::BindCommonResources(cmd); - wiRenderer::BindCameraCB( + wi::jobsystem::Execute(ctx, [cmd, this](wi::jobsystem::JobArgs args) { + wi::renderer::BindCommonResources(cmd); + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::RefreshLightmaps(*scene, cmd); - wiRenderer::RefreshEnvProbes(visibility_main, cmd); - wiRenderer::RefreshImpostors(*scene, cmd); + wi::renderer::RefreshLightmaps(*scene, cmd); + wi::renderer::RefreshEnvProbes(visibility_main, cmd); + wi::renderer::RefreshImpostors(*scene, cmd); }); // Voxel GI: - if (wiRenderer::GetVoxelRadianceEnabled()) + if (wi::renderer::GetVoxelRadianceEnabled()) { cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [cmd, this](wiJobArgs args) { - wiRenderer::VoxelRadiance(visibility_main, cmd); + wi::jobsystem::Execute(ctx, [cmd, this](wi::jobsystem::JobArgs args) { + wi::renderer::VoxelRadiance(visibility_main, cmd); }); } @@ -871,11 +877,11 @@ void RenderPath3D::Render() const { // Planar reflections depth prepass: cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [cmd, this](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [cmd, this](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( camera_reflection, camera_reflection_previous, camera_reflection, @@ -883,7 +889,7 @@ void RenderPath3D::Render() const ); device->EventBegin("Planar reflections Z-Prepass", cmd); - auto range = wiProfiler::BeginRangeGPU("Planar Reflections Z-Prepass", cmd); + auto range = wi::profiler::BeginRangeGPU("Planar Reflections Z-Prepass", cmd); Viewport vp; vp.width = (float)depthBuffer_Reflection.GetDesc().width; @@ -892,44 +898,44 @@ void RenderPath3D::Render() const device->RenderPassBegin(&renderpass_reflection_depthprepass, cmd); - wiRenderer::DrawScene(visibility_reflection, RENDERPASS_PREPASS, cmd, drawscene_flags_reflections); + wi::renderer::DrawScene(visibility_reflection, RENDERPASS_PREPASS, cmd, drawscene_flags_reflections); device->RenderPassEnd(cmd); if (scene->weather.IsVolumetricClouds()) { - wiRenderer::Postprocess_VolumetricClouds( + wi::renderer::Postprocess_VolumetricClouds( volumetriccloudResources_reflection, cmd ); } - wiProfiler::EndRange(range); // Planar Reflections + wi::profiler::EndRange(range); // Planar Reflections device->EventEnd(cmd); }); // Planar reflections opaque color pass: cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [cmd, this](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [cmd, this](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( camera_reflection, camera_reflection_previous, camera_reflection, cmd ); - wiRenderer::ComputeTiledLightCulling( + wi::renderer::ComputeTiledLightCulling( tiledLightResources_planarReflection, Texture(), cmd ); device->EventBegin("Planar reflections", cmd); - auto range = wiProfiler::BeginRangeGPU("Planar Reflections", cmd); + auto range = wi::profiler::BeginRangeGPU("Planar Reflections", cmd); Viewport vp; vp.width = (float)depthBuffer_Reflection.GetDesc().width; @@ -939,22 +945,22 @@ void RenderPath3D::Render() const device->RenderPassBegin(&renderpass_reflection, cmd); - wiRenderer::DrawScene(visibility_reflection, RENDERPASS_MAIN, cmd, drawscene_flags_reflections); - wiRenderer::DrawSky(*scene, cmd); + wi::renderer::DrawScene(visibility_reflection, RENDERPASS_MAIN, cmd, drawscene_flags_reflections); + wi::renderer::DrawSky(*scene, cmd); // Blend the volumetric clouds on top: if (scene->weather.IsVolumetricClouds()) { device->EventBegin("Volumetric Clouds Reflection Blend", cmd); - wiImageParams fx; + wi::image::Params fx; fx.enableFullScreen(); - wiImage::Draw(&volumetriccloudResources_reflection.texture_temporal[device->GetFrameCount() % 2], fx, cmd); + wi::image::Draw(&volumetriccloudResources_reflection.texture_temporal[device->GetFrameCount() % 2], fx, cmd); device->EventEnd(cmd); } device->RenderPassEnd(cmd); - wiProfiler::EndRange(range); // Planar Reflections + wi::profiler::EndRange(range); // Planar Reflections device->EventEnd(cmd); }); } @@ -962,12 +968,12 @@ void RenderPath3D::Render() const // Main camera opaque color pass: cmd = device->BeginCommandList(); device->WaitCommandList(cmd, cmd_maincamera_compute_effects); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("Opaque Scene", cmd); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, @@ -978,7 +984,7 @@ void RenderPath3D::Render() const // because it depends on shadow maps, and envmaps if (getRaytracedReflectionEnabled()) { - wiRenderer::Postprocess_RTReflection( + wi::renderer::Postprocess_RTReflection( rtreflectionResources, *scene, rtSSR, @@ -995,14 +1001,14 @@ void RenderPath3D::Render() const device->Barrier(barriers, arraysize(barriers), cmd); } - auto range = wiProfiler::BeginRangeGPU("Opaque Scene", cmd); + auto range = wi::profiler::BeginRangeGPU("Opaque Scene", cmd); Viewport vp; vp.width = (float)depthBuffer_Main.GetDesc().width; vp.height = (float)depthBuffer_Main.GetDesc().height; device->BindViewports(1, &vp, cmd); - if (wiRenderer::GetRaytracedShadowsEnabled() || wiRenderer::GetScreenSpaceShadowsEnabled()) + if (wi::renderer::GetRaytracedShadowsEnabled() || wi::renderer::GetScreenSpaceShadowsEnabled()) { GPUBarrier barrier = GPUBarrier::Image(&rtShadow, rtShadow.desc.layout, ResourceState::SHADER_RESOURCE); device->Barrier(&barrier, 1, cmd); @@ -1010,10 +1016,10 @@ void RenderPath3D::Render() const device->RenderPassBegin(&renderpass_main, cmd); - wiRenderer::DrawScene(visibility_main, RENDERPASS_MAIN, cmd, drawscene_flags); - wiRenderer::DrawSky(*scene, cmd); + wi::renderer::DrawScene(visibility_main, RENDERPASS_MAIN, cmd, drawscene_flags); + wi::renderer::DrawSky(*scene, cmd); - wiProfiler::EndRange(range); // Opaque Scene + wi::profiler::EndRange(range); // Opaque Scene RenderOutline(cmd); @@ -1021,7 +1027,7 @@ void RenderPath3D::Render() const if (scene->weather.IsVolumetricClouds()) { device->EventBegin("Volumetric Clouds Upsample + Blend", cmd); - wiRenderer::Postprocess_Upsample_Bilateral( + wi::renderer::Postprocess_Upsample_Bilateral( volumetriccloudResources.texture_temporal[device->GetFrameCount() % 2], rtLinearDepth, rtMain_render, // only desc is taken if pixel shader upsampling is used @@ -1033,7 +1039,7 @@ void RenderPath3D::Render() const device->RenderPassEnd(cmd); - if (wiRenderer::GetRaytracedShadowsEnabled() || wiRenderer::GetScreenSpaceShadowsEnabled()) + if (wi::renderer::GetRaytracedShadowsEnabled() || wi::renderer::GetScreenSpaceShadowsEnabled()) { GPUBarrier barrier = GPUBarrier::Image(&rtShadow, ResourceState::SHADER_RESOURCE, rtShadow.desc.layout); device->Barrier(&barrier, 1, cmd); @@ -1044,17 +1050,17 @@ void RenderPath3D::Render() const // Transparents, post processes, etc: cmd = device->BeginCommandList(); - wiJobSystem::Execute(ctx, [this, cmd](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiRenderer::BindCameraCB( + wi::renderer::BindCameraCB( *camera, camera_previous, camera_reflection, cmd ); - wiRenderer::BindCommonResources(cmd); + wi::renderer::BindCommonResources(cmd); RenderLightShafts(cmd); @@ -1079,31 +1085,31 @@ void RenderPath3D::Render() const RenderPath2D::Render(); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); } void RenderPath3D::Compose(CommandList cmd) const { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - wiImageParams fx; + wi::image::Params fx; fx.blendFlag = BLENDMODE_OPAQUE; - fx.quality = QUALITY_LINEAR; + fx.quality = wi::image::QUALITY_LINEAR; fx.enableFullScreen(); device->EventBegin("Composition", cmd); - wiImage::Draw(GetLastPostprocessRT(), fx, cmd); + wi::image::Draw(GetLastPostprocessRT(), fx, cmd); device->EventEnd(cmd); if ( - wiRenderer::GetDebugLightCulling() || - wiRenderer::GetVariableRateShadingClassificationDebug() || - wiRenderer::GetSurfelGIDebugEnabled() + wi::renderer::GetDebugLightCulling() || + wi::renderer::GetVariableRateShadingClassificationDebug() || + wi::renderer::GetSurfelGIDebugEnabled() ) { fx.enableFullScreen(); fx.blendFlag = BLENDMODE_PREMULTIPLIED; - wiImage::Draw(&debugUAV, fx, cmd); + wi::image::Draw(&debugUAV, fx, cmd); } RenderPath2D::Compose(cmd); @@ -1117,7 +1123,7 @@ void RenderPath3D::RenderAO(CommandList cmd) const switch (getAO()) { case AO_SSAO: - wiRenderer::Postprocess_SSAO( + wi::renderer::Postprocess_SSAO( ssaoResources, rtLinearDepth, rtAO, @@ -1128,7 +1134,7 @@ void RenderPath3D::RenderAO(CommandList cmd) const ); break; case AO_HBAO: - wiRenderer::Postprocess_HBAO( + wi::renderer::Postprocess_HBAO( ssaoResources, *camera, rtLinearDepth, @@ -1138,7 +1144,7 @@ void RenderPath3D::RenderAO(CommandList cmd) const ); break; case AO_MSAO: - wiRenderer::Postprocess_MSAO( + wi::renderer::Postprocess_MSAO( msaoResources, *camera, rtLinearDepth, @@ -1148,7 +1154,7 @@ void RenderPath3D::RenderAO(CommandList cmd) const ); break; case AO_RTAO: - wiRenderer::Postprocess_RTAO( + wi::renderer::Postprocess_RTAO( rtaoResources, *scene, rtAO, @@ -1164,7 +1170,7 @@ void RenderPath3D::RenderSSR(CommandList cmd) const { if (getSSREnabled() && !getRaytracedReflectionEnabled()) { - wiRenderer::Postprocess_SSR( + wi::renderer::Postprocess_SSR( ssrResources, rtSceneCopy, rtSSR, @@ -1176,7 +1182,7 @@ void RenderPath3D::RenderOutline(CommandList cmd) const { if (getOutlineEnabled()) { - wiRenderer::Postprocess_Outline(rtLinearDepth, cmd, getOutlineThreshold(), getOutlineThickness(), getOutlineColor()); + wi::renderer::Postprocess_Outline(rtLinearDepth, cmd, getOutlineThreshold(), getOutlineThickness(), getOutlineColor()); } } void RenderPath3D::RenderLightShafts(CommandList cmd) const @@ -1184,7 +1190,7 @@ void RenderPath3D::RenderLightShafts(CommandList cmd) const XMVECTOR sunDirection = XMLoadFloat3(&scene->weather.sunDirection); if (getLightShaftsEnabled() && XMVectorGetX(XMVector3Dot(sunDirection, camera->GetAt())) > 0) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->EventBegin("Light Shafts", cmd); @@ -1197,15 +1203,15 @@ void RenderPath3D::RenderLightShafts(CommandList cmd) const vp.height = (float)depthBuffer_Main.GetDesc().height; device->BindViewports(1, &vp, cmd); - wiRenderer::DrawSun(cmd); + wi::renderer::DrawSun(cmd); if (scene->weather.IsVolumetricClouds()) { device->EventBegin("Volumetric cloud occlusion mask", cmd); - wiImageParams fx; + wi::image::Params fx; fx.enableFullScreen(); fx.blendFlag = BLENDMODE_MULTIPLY; - wiImage::Draw(&volumetriccloudResources.texture_cloudMask, fx, cmd); + wi::image::Draw(&volumetriccloudResources.texture_cloudMask, fx, cmd); device->EventEnd(cmd); } @@ -1220,7 +1226,7 @@ void RenderPath3D::RenderLightShafts(CommandList cmd) const { XMFLOAT2 sun; XMStoreFloat2(&sun, sunPos); - wiRenderer::Postprocess_LightShafts(*renderpass_lightshafts.desc.attachments.back().texture, rtSun[1], cmd, sun); + wi::renderer::Postprocess_LightShafts(*renderpass_lightshafts.desc.attachments.back().texture, rtSun[1], cmd, sun); } } device->EventEnd(cmd); @@ -1230,9 +1236,9 @@ void RenderPath3D::RenderVolumetrics(CommandList cmd) const { if (getVolumeLightsEnabled() && visibility_main.IsRequestedVolumetricLights()) { - auto range = wiProfiler::BeginRangeGPU("Volumetric Lights", cmd); + auto range = wi::profiler::BeginRangeGPU("Volumetric Lights", cmd); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->RenderPassBegin(&renderpass_volumetriclight, cmd); @@ -1241,11 +1247,11 @@ void RenderPath3D::RenderVolumetrics(CommandList cmd) const vp.height = (float)rtVolumetricLights[0].GetDesc().height; device->BindViewports(1, &vp, cmd); - wiRenderer::DrawVolumeLights(visibility_main, cmd); + wi::renderer::DrawVolumeLights(visibility_main, cmd); device->RenderPassEnd(cmd); - wiRenderer::Postprocess_Blur_Bilateral( + wi::renderer::Postprocess_Blur_Bilateral( rtVolumetricLights[0], rtLinearDepth, rtVolumetricLights[1], @@ -1253,14 +1259,14 @@ void RenderPath3D::RenderVolumetrics(CommandList cmd) const cmd ); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } } void RenderPath3D::RenderSceneMIPChain(CommandList cmd) const { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); - auto range = wiProfiler::BeginRangeGPU("Scene MIP Chain", cmd); + auto range = wi::profiler::BeginRangeGPU("Scene MIP Chain", cmd); device->EventBegin("RenderSceneMIPChain", cmd); device->RenderPassBegin(&renderpass_downsamplescene, cmd); @@ -1270,25 +1276,25 @@ void RenderPath3D::RenderSceneMIPChain(CommandList cmd) const vp.height = (float)rtSceneCopy.GetDesc().height; device->BindViewports(1, &vp, cmd); - wiImageParams fx; + wi::image::Params fx; fx.enableFullScreen(); - fx.sampleFlag = SAMPLEMODE_CLAMP; - fx.quality = QUALITY_LINEAR; + fx.sampleFlag = wi::image::SAMPLEMODE_CLAMP; + fx.quality = wi::image::QUALITY_LINEAR; fx.blendFlag = BLENDMODE_OPAQUE; - wiImage::Draw(&rtMain, fx, cmd); + wi::image::Draw(&rtMain, fx, cmd); device->RenderPassEnd(cmd); - wiRenderer::MIPGEN_OPTIONS mipopt; + wi::renderer::MIPGEN_OPTIONS mipopt; mipopt.gaussian_temp = &rtSceneCopy_tmp; - wiRenderer::GenerateMipChain(rtSceneCopy, wiRenderer::MIPGENFILTER_GAUSSIAN, cmd, mipopt); + wi::renderer::GenerateMipChain(rtSceneCopy, wi::renderer::MIPGENFILTER_GAUSSIAN, cmd, mipopt); device->EventEnd(cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } void RenderPath3D::RenderTransparents(CommandList cmd) const { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); // Water ripple rendering: if(!scene->waterRipples.empty()) @@ -1300,7 +1306,7 @@ void RenderPath3D::RenderTransparents(CommandList cmd) const vp.height = (float)rtWaterRipple.GetDesc().height; device->BindViewports(1, &vp, cmd); - wiRenderer::DrawWaterRipples(visibility_main, cmd); + wi::renderer::DrawWaterRipples(visibility_main, cmd); device->RenderPassEnd(cmd); } @@ -1315,28 +1321,28 @@ void RenderPath3D::RenderTransparents(CommandList cmd) const // Transparent scene { - auto range = wiProfiler::BeginRangeGPU("Transparent Scene", cmd); + auto range = wi::profiler::BeginRangeGPU("Transparent Scene", cmd); device->EventBegin("Transparent Scene", cmd); uint32_t drawscene_flags = 0; - drawscene_flags |= wiRenderer::DRAWSCENE_TRANSPARENT; - drawscene_flags |= wiRenderer::DRAWSCENE_OCCLUSIONCULLING; - drawscene_flags |= wiRenderer::DRAWSCENE_HAIRPARTICLE; - drawscene_flags |= wiRenderer::DRAWSCENE_TESSELLATION; - wiRenderer::DrawScene(visibility_main, RENDERPASS_MAIN, cmd, drawscene_flags); + drawscene_flags |= wi::renderer::DRAWSCENE_TRANSPARENT; + drawscene_flags |= wi::renderer::DRAWSCENE_OCCLUSIONCULLING; + drawscene_flags |= wi::renderer::DRAWSCENE_HAIRPARTICLE; + drawscene_flags |= wi::renderer::DRAWSCENE_TESSELLATION; + wi::renderer::DrawScene(visibility_main, RENDERPASS_MAIN, cmd, drawscene_flags); device->EventEnd(cmd); - wiProfiler::EndRange(range); // Transparent Scene + wi::profiler::EndRange(range); // Transparent Scene } - wiRenderer::DrawLightVisualizers(visibility_main, cmd); + wi::renderer::DrawLightVisualizers(visibility_main, cmd); - wiRenderer::DrawSoftParticles(visibility_main, rtLinearDepth, false, cmd); + wi::renderer::DrawSoftParticles(visibility_main, rtLinearDepth, false, cmd); if (getVolumeLightsEnabled() && visibility_main.IsRequestedVolumetricLights()) { device->EventBegin("Contribute Volumetric Lights", cmd); - wiRenderer::Postprocess_Upsample_Bilateral(rtVolumetricLights[0], rtLinearDepth, + wi::renderer::Postprocess_Upsample_Bilateral(rtVolumetricLights[0], rtLinearDepth, *renderpass_transparent.desc.attachments[0].texture, cmd, true, 1.5f); device->EventEnd(cmd); } @@ -1345,23 +1351,23 @@ void RenderPath3D::RenderTransparents(CommandList cmd) const if (getLightShaftsEnabled() && XMVectorGetX(XMVector3Dot(sunDirection, camera->GetAt())) > 0) { device->EventBegin("Contribute LightShafts", cmd); - wiImageParams fx; + wi::image::Params fx; fx.enableFullScreen(); fx.blendFlag = BLENDMODE_ADDITIVE; - wiImage::Draw(&rtSun[1], fx, cmd); + wi::image::Draw(&rtSun[1], fx, cmd); device->EventEnd(cmd); } if (getLensFlareEnabled()) { - wiRenderer::DrawLensFlares( + wi::renderer::DrawLensFlares( visibility_main, cmd, scene->weather.IsVolumetricClouds() ? &volumetriccloudResources.texture_cloudMask : nullptr ); } - wiRenderer::DrawDebugWorld(*scene, *camera, *this, cmd); + wi::renderer::DrawDebugWorld(*scene, *camera, *this, cmd); device->RenderPassEnd(cmd); @@ -1374,14 +1380,14 @@ void RenderPath3D::RenderTransparents(CommandList cmd) const vp.height = (float)rtParticleDistortion.GetDesc().height; device->BindViewports(1, &vp, cmd); - wiRenderer::DrawSoftParticles(visibility_main, rtLinearDepth, true, cmd); + wi::renderer::DrawSoftParticles(visibility_main, rtLinearDepth, true, cmd); device->RenderPassEnd(cmd); } } void RenderPath3D::RenderPostprocessChain(CommandList cmd) const { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); const Texture* rt_first = nullptr; // not ping-ponged with read / write const Texture* rt_read = &rtMain; @@ -1389,13 +1395,13 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const // 1.) HDR post process chain { - if (wiRenderer::GetTemporalAAEnabled() && !wiRenderer::GetTemporalAADebugEnabled()) + if (wi::renderer::GetTemporalAAEnabled() && !wi::renderer::GetTemporalAADebugEnabled()) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); int output = device->GetFrameCount() % 2; int history = 1 - output; - wiRenderer::Postprocess_TemporalAA( + wi::renderer::Postprocess_TemporalAA( *rt_read, rtTemporalAA[history], rtTemporalAA[output], @@ -1406,7 +1412,7 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const if (getDepthOfFieldEnabled() && camera->aperture_size > 0 && getDepthOfFieldStrength() > 0) { - wiRenderer::Postprocess_DepthOfField( + wi::renderer::Postprocess_DepthOfField( depthoffieldResources, rt_first == nullptr ? *rt_read : *rt_first, *rt_write, @@ -1420,7 +1426,7 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const if (getMotionBlurEnabled() && getMotionBlurStrength() > 0) { - wiRenderer::Postprocess_MotionBlur( + wi::renderer::Postprocess_MotionBlur( motionblurResources, rt_first == nullptr ? *rt_read : *rt_first, *rt_write, @@ -1439,7 +1445,7 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const // because they will be applied to the screen in tonemap if (getEyeAdaptionEnabled()) { - wiRenderer::ComputeLuminance( + wi::renderer::ComputeLuminance( luminanceResources, rt_first == nullptr ? *rt_read : *rt_first, cmd, @@ -1449,7 +1455,7 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const } if (getBloomEnabled()) { - wiRenderer::ComputeBloom( + wi::renderer::ComputeBloom( bloomResources, rt_first == nullptr ? *rt_read : *rt_first, cmd, @@ -1459,13 +1465,13 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const ); } - wiRenderer::Postprocess_Tonemap( + wi::renderer::Postprocess_Tonemap( rt_first == nullptr ? *rt_read : *rt_first, *rt_write, cmd, getExposure(), getDitherEnabled(), - getColorGradingEnabled() ? (scene->weather.colorGradingMap == nullptr ? nullptr : &scene->weather.colorGradingMap->texture) : nullptr, + getColorGradingEnabled() ? (scene->weather.colorGradingMap.IsValid() ? &scene->weather.colorGradingMap.GetTexture() : nullptr) : nullptr, getMSAASampleCount() > 1 ? &rtParticleDistortion_Resolved : &rtParticleDistortion, getEyeAdaptionEnabled() ? &luminanceResources.luminance : nullptr, getBloomEnabled() ? &bloomResources.texture_bloom : nullptr, @@ -1480,21 +1486,21 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const { if (getSharpenFilterEnabled()) { - wiRenderer::Postprocess_Sharpen(*rt_read, *rt_write, cmd, getSharpenFilterAmount()); + wi::renderer::Postprocess_Sharpen(*rt_read, *rt_write, cmd, getSharpenFilterAmount()); std::swap(rt_read, rt_write); } if (getFXAAEnabled()) { - wiRenderer::Postprocess_FXAA(*rt_read, *rt_write, cmd); + wi::renderer::Postprocess_FXAA(*rt_read, *rt_write, cmd); std::swap(rt_read, rt_write); } if (getChromaticAberrationEnabled()) { - wiRenderer::Postprocess_Chromatic_Aberration(*rt_read, *rt_write, cmd, getChromaticAberrationAmount()); + wi::renderer::Postprocess_Chromatic_Aberration(*rt_read, *rt_write, cmd, getChromaticAberrationAmount()); std::swap(rt_read, rt_write); } @@ -1503,18 +1509,18 @@ void RenderPath3D::RenderPostprocessChain(CommandList cmd) const // GUI Background blurring: { - auto range = wiProfiler::BeginRangeGPU("GUI Background Blur", cmd); + auto range = wi::profiler::BeginRangeGPU("GUI Background Blur", cmd); device->EventBegin("GUI Background Blur", cmd); - wiRenderer::Postprocess_Downsample4x(*rt_read, rtGUIBlurredBackground[0], cmd); - wiRenderer::Postprocess_Downsample4x(rtGUIBlurredBackground[0], rtGUIBlurredBackground[2], cmd); - wiRenderer::Postprocess_Blur_Gaussian(rtGUIBlurredBackground[2], rtGUIBlurredBackground[1], rtGUIBlurredBackground[2], cmd, -1,-1, true); + wi::renderer::Postprocess_Downsample4x(*rt_read, rtGUIBlurredBackground[0], cmd); + wi::renderer::Postprocess_Downsample4x(rtGUIBlurredBackground[0], rtGUIBlurredBackground[2], cmd); + wi::renderer::Postprocess_Blur_Gaussian(rtGUIBlurredBackground[2], rtGUIBlurredBackground[1], rtGUIBlurredBackground[2], cmd, -1,-1, true); device->EventEnd(cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } if (rtFSR[0].IsValid() && getFSREnabled()) { - wiRenderer::Postprocess_FSR(*rt_read, rtFSR[1], rtFSR[0], cmd, getFSRSharpness()); + wi::renderer::Postprocess_FSR(*rt_read, rtFSR[1], rtFSR[0], cmd, getFSRSharpness()); lastPostprocessRT = &rtFSR[0]; } } @@ -1547,23 +1553,23 @@ void RenderPath3D::setAO(AO value) case RenderPath3D::AO_HBAO: desc.width = internalResolution.x / 2; desc.height = internalResolution.y / 2; - wiRenderer::CreateSSAOResources(ssaoResources, internalResolution); + wi::renderer::CreateSSAOResources(ssaoResources, internalResolution); break; case RenderPath3D::AO_MSAO: desc.width = internalResolution.x; desc.height = internalResolution.y; - wiRenderer::CreateMSAOResources(msaoResources, internalResolution); + wi::renderer::CreateMSAOResources(msaoResources, internalResolution); break; case RenderPath3D::AO_RTAO: desc.width = internalResolution.x / 2; desc.height = internalResolution.y / 2; - wiRenderer::CreateRTAOResources(rtaoResources, internalResolution); + wi::renderer::CreateRTAOResources(rtaoResources, internalResolution); break; default: break; } - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); device->CreateTexture(&desc, nullptr, &rtAO); device->SetName(&rtAO, "rtAO"); } @@ -1574,7 +1580,7 @@ void RenderPath3D::setSSREnabled(bool value) if (value) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); XMUINT2 internalResolution = GetInternalResolution(); TextureDesc desc; @@ -1585,7 +1591,7 @@ void RenderPath3D::setSSREnabled(bool value) device->CreateTexture(&desc, nullptr, &rtSSR); device->SetName(&rtSSR, "rtSSR"); - wiRenderer::CreateSSRResources(ssrResources, internalResolution); + wi::renderer::CreateSSRResources(ssrResources, internalResolution); } else { @@ -1599,7 +1605,7 @@ void RenderPath3D::setRaytracedReflectionsEnabled(bool value) if (value) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); XMUINT2 internalResolution = GetInternalResolution(); TextureDesc desc; @@ -1610,7 +1616,7 @@ void RenderPath3D::setRaytracedReflectionsEnabled(bool value) device->CreateTexture(&desc, nullptr, &rtSSR); device->SetName(&rtSSR, "rtSSR"); - wiRenderer::CreateRTReflectionResources(rtreflectionResources, internalResolution); + wi::renderer::CreateRTReflectionResources(rtreflectionResources, internalResolution); } else { @@ -1624,7 +1630,7 @@ void RenderPath3D::setFSREnabled(bool value) if (resolutionScale < 1.0f && fsrEnabled) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); TextureDesc desc; desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; @@ -1642,3 +1648,5 @@ void RenderPath3D::setFSREnabled(bool value) rtFSR[1] = {}; } } + +} diff --git a/WickedEngine/wiRenderPath3D.h b/WickedEngine/wiRenderPath3D.h new file mode 100644 index 000000000..7fc359984 --- /dev/null +++ b/WickedEngine/wiRenderPath3D.h @@ -0,0 +1,253 @@ +#pragma once +#include "wiRenderPath2D.h" +#include "wiRenderer.h" +#include "wiGraphicsDevice.h" +#include "wiResourceManager.h" +#include "wiScene.h" + +#include + +namespace wi +{ + + class RenderPath3D : + public RenderPath2D + { + public: + enum AO + { + AO_DISABLED, // no ambient occlusion + AO_SSAO, // simple brute force screen space ambient occlusion + AO_HBAO, // horizon based screen space ambient occlusion + AO_MSAO, // multi scale screen space ambient occlusion + AO_RTAO, // ray traced ambient occlusion + // Don't alter order! (bound to lua manually) + }; + private: + float exposure = 1.0f; + float bloomThreshold = 1.0f; + float motionBlurStrength = 100.0f; + float dofStrength = 10.0f; + float sharpenFilterAmount = 0.28f; + float outlineThreshold = 0.2f; + float outlineThickness = 1.0f; + XMFLOAT4 outlineColor = XMFLOAT4(0, 0, 0, 1); + float aoRange = 1.0f; + uint32_t aoSampleCount = 16; + float aoPower = 1.0f; + float chromaticAberrationAmount = 2.0f; + uint32_t screenSpaceShadowSampleCount = 16; + float screenSpaceShadowRange = 1; + float eyeadaptionKey = 0.115f; + float eyeadaptionRate = 1; + float fsrSharpness = 1.0f; + + AO ao = AO_DISABLED; + bool fxaaEnabled = false; + bool ssrEnabled = false; + bool raytracedReflectionsEnabled = false; + bool reflectionsEnabled = true; + bool shadowsEnabled = true; + bool bloomEnabled = true; + bool colorGradingEnabled = true; + bool volumeLightsEnabled = true; + bool lightShaftsEnabled = false; + bool lensFlareEnabled = true; + bool motionBlurEnabled = false; + bool depthOfFieldEnabled = true; + bool eyeAdaptionEnabled = false; + bool sharpenFilterEnabled = false; + bool outlineEnabled = false; + bool chromaticAberrationEnabled = false; + bool ditherEnabled = true; + bool occlusionCullingEnabled = true; + bool sceneUpdateEnabled = true; + bool fsrEnabled = true; + + uint32_t msaaSampleCount = 1; + + public: + wi::graphics::Texture rtMain; + wi::graphics::Texture rtMain_render; // can be MSAA + wi::graphics::Texture rtGbuffer[wi::renderer::GBUFFER_COUNT]; + wi::graphics::Texture rtPrimitiveID_render; // can be MSAA + wi::graphics::Texture rtReflection; // contains the scene rendered for planar reflections + wi::graphics::Texture rtSSR; // standard screen-space reflection results + wi::graphics::Texture rtSceneCopy; // contains the rendered scene that can be fed into transparent pass for distortion effect + wi::graphics::Texture rtSceneCopy_tmp; // temporary for gaussian mipchain + wi::graphics::Texture rtWaterRipple; // water ripple sprite normal maps are rendered into this + wi::graphics::Texture rtParticleDistortion; // contains distortive particles + wi::graphics::Texture rtParticleDistortion_Resolved; // contains distortive particles + wi::graphics::Texture rtVolumetricLights[2]; // contains the volumetric light results + wi::graphics::Texture rtTemporalAA[2]; // temporal AA history buffer + wi::graphics::Texture rtBloom; // contains the bright parts of the image + mipchain + wi::graphics::Texture rtBloom_tmp; // temporary for bloom downsampling + wi::graphics::Texture rtAO; // full res AO + wi::graphics::Texture rtShadow; // raytraced shadows mask + wi::graphics::Texture rtSun[2]; // 0: sun render target used for lightshafts (can be MSAA), 1: radial blurred lightshafts + wi::graphics::Texture rtSun_resolved; // sun render target, but the resolved version if MSAA is enabled + wi::graphics::Texture rtGUIBlurredBackground[3]; // downsampled, gaussian blurred scene for GUI + wi::graphics::Texture rtShadingRate; // UINT8 shading rate per tile + wi::graphics::Texture rtFSR[2]; // FSR upscaling result (full resolution LDR) + + wi::graphics::Texture rtPostprocess; // ping-pong with main scene RT in post-process chain + + wi::graphics::Texture depthBuffer_Main; // used for depth-testing, can be MSAA + wi::graphics::Texture depthBuffer_Copy; // used for shader resource, single sample + wi::graphics::Texture depthBuffer_Copy1; // used for disocclusion check + wi::graphics::Texture depthBuffer_Reflection; // used for reflection, single sample + wi::graphics::Texture rtLinearDepth; // linear depth result + mipchain (max filter) + + wi::graphics::RenderPass renderpass_depthprepass; + wi::graphics::RenderPass renderpass_main; + wi::graphics::RenderPass renderpass_transparent; + wi::graphics::RenderPass renderpass_reflection_depthprepass; + wi::graphics::RenderPass renderpass_reflection; + wi::graphics::RenderPass renderpass_downsamplescene; + wi::graphics::RenderPass renderpass_lightshafts; + wi::graphics::RenderPass renderpass_volumetriclight; + wi::graphics::RenderPass renderpass_particledistortion; + wi::graphics::RenderPass renderpass_waterripples; + + wi::graphics::Texture debugUAV; // debug UAV can be used by some shaders... + wi::renderer::TiledLightResources tiledLightResources; + wi::renderer::TiledLightResources tiledLightResources_planarReflection; + wi::renderer::LuminanceResources luminanceResources; + wi::renderer::SSAOResources ssaoResources; + wi::renderer::MSAOResources msaoResources; + wi::renderer::RTAOResources rtaoResources; + wi::renderer::RTReflectionResources rtreflectionResources; + wi::renderer::SSRResources ssrResources; + wi::renderer::RTShadowResources rtshadowResources; + wi::renderer::ScreenSpaceShadowResources screenspaceshadowResources; + wi::renderer::DepthOfFieldResources depthoffieldResources; + wi::renderer::MotionBlurResources motionblurResources; + wi::renderer::VolumetricCloudResources volumetriccloudResources; + wi::renderer::VolumetricCloudResources volumetriccloudResources_reflection; + wi::renderer::BloomResources bloomResources; + wi::renderer::SurfelGIResources surfelGIResources; + + mutable const wi::graphics::Texture* lastPostprocessRT = &rtPostprocess; + // Post-processes are ping-ponged, this function helps to obtain the last postprocess render target that was written + const wi::graphics::Texture* GetLastPostprocessRT() const + { + return lastPostprocessRT; + } + + virtual void RenderAO(wi::graphics::CommandList cmd) const; + virtual void RenderSSR(wi::graphics::CommandList cmd) const; + virtual void RenderOutline(wi::graphics::CommandList cmd) const; + virtual void RenderLightShafts(wi::graphics::CommandList cmd) const; + virtual void RenderVolumetrics(wi::graphics::CommandList cmd) const; + virtual void RenderSceneMIPChain(wi::graphics::CommandList cmd) const; + virtual void RenderTransparents(wi::graphics::CommandList cmd) const; + virtual void RenderPostprocessChain(wi::graphics::CommandList cmd) const; + + void ResizeBuffers() override; + + wi::scene::CameraComponent* camera = &wi::scene::GetCamera(); + wi::scene::CameraComponent camera_previous; + wi::scene::CameraComponent camera_reflection; + wi::scene::CameraComponent camera_reflection_previous; + + wi::scene::Scene* scene = &wi::scene::GetScene(); + wi::renderer::Visibility visibility_main; + wi::renderer::Visibility visibility_reflection; + + FrameCB frameCB = {}; + + const wi::graphics::Texture* GetDepthStencil() const override { return &depthBuffer_Main; } + const wi::graphics::Texture* GetGUIBlurredBackground() const override { return &rtGUIBlurredBackground[2]; } + + constexpr float getExposure() const { return exposure; } + constexpr float getBloomThreshold() const { return bloomThreshold; } + constexpr float getMotionBlurStrength() const { return motionBlurStrength; } + constexpr float getDepthOfFieldStrength() const { return dofStrength; } + constexpr float getSharpenFilterAmount() const { return sharpenFilterAmount; } + constexpr float getOutlineThreshold() const { return outlineThreshold; } + constexpr float getOutlineThickness() const { return outlineThickness; } + constexpr XMFLOAT4 getOutlineColor() const { return outlineColor; } + constexpr float getAORange() const { return aoRange; } + constexpr uint32_t getAOSampleCount() const { return aoSampleCount; } + constexpr float getAOPower() const { return aoPower; } + constexpr float getChromaticAberrationAmount() const { return chromaticAberrationAmount; } + constexpr uint32_t getScreenSpaceShadowSampleCount() const { return screenSpaceShadowSampleCount; } + constexpr float getScreenSpaceShadowRange() const { return screenSpaceShadowRange; } + constexpr float getEyeAdaptionKey() const { return eyeadaptionKey; } + constexpr float getEyeAdaptionRate() const { return eyeadaptionRate; } + constexpr float getFSRSharpness() const { return fsrSharpness; } + + constexpr bool getAOEnabled() const { return ao != AO_DISABLED; } + constexpr AO getAO() const { return ao; } + constexpr bool getSSREnabled() const { return ssrEnabled; } + constexpr bool getRaytracedReflectionEnabled() const { return raytracedReflectionsEnabled; } + constexpr bool getShadowsEnabled() const { return shadowsEnabled; } + constexpr bool getReflectionsEnabled() const { return reflectionsEnabled; } + constexpr bool getFXAAEnabled() const { return fxaaEnabled; } + constexpr bool getBloomEnabled() const { return bloomEnabled; } + constexpr bool getColorGradingEnabled() const { return colorGradingEnabled; } + constexpr bool getVolumeLightsEnabled() const { return volumeLightsEnabled; } + constexpr bool getLightShaftsEnabled() const { return lightShaftsEnabled; } + constexpr bool getLensFlareEnabled() const { return lensFlareEnabled; } + constexpr bool getMotionBlurEnabled() const { return motionBlurEnabled; } + constexpr bool getDepthOfFieldEnabled() const { return depthOfFieldEnabled; } + constexpr bool getEyeAdaptionEnabled() const { return eyeAdaptionEnabled; } + constexpr bool getSharpenFilterEnabled() const { return sharpenFilterEnabled && getSharpenFilterAmount() > 0; } + constexpr bool getOutlineEnabled() const { return outlineEnabled; } + constexpr bool getChromaticAberrationEnabled() const { return chromaticAberrationEnabled; } + constexpr bool getDitherEnabled() const { return ditherEnabled; } + constexpr bool getOcclusionCullingEnabled() const { return occlusionCullingEnabled; } + constexpr bool getSceneUpdateEnabled() const { return sceneUpdateEnabled; } + constexpr bool getFSREnabled() const { return fsrEnabled; } + + constexpr uint32_t getMSAASampleCount() const { return msaaSampleCount; } + + constexpr void setExposure(float value) { exposure = value; } + constexpr void setBloomThreshold(float value) { bloomThreshold = value; } + constexpr void setMotionBlurStrength(float value) { motionBlurStrength = value; } + constexpr void setDepthOfFieldStrength(float value) { dofStrength = value; } + constexpr void setSharpenFilterAmount(float value) { sharpenFilterAmount = value; } + constexpr void setOutlineThreshold(float value) { outlineThreshold = value; } + constexpr void setOutlineThickness(float value) { outlineThickness = value; } + constexpr void setOutlineColor(const XMFLOAT4& value) { outlineColor = value; } + constexpr void setAORange(float value) { aoRange = value; } + constexpr void setAOSampleCount(uint32_t value) { aoSampleCount = value; } + constexpr void setAOPower(float value) { aoPower = value; } + constexpr void setChromaticAberrationAmount(float value) { chromaticAberrationAmount = value; } + constexpr void setScreenSpaceShadowSampleCount(uint32_t value) { screenSpaceShadowSampleCount = value; } + constexpr void setScreenSpaceShadowRange(float value) { screenSpaceShadowRange = value; } + constexpr void setEyeAdaptionKey(float value) { eyeadaptionKey = value; } + constexpr void setEyeAdaptionRate(float value) { eyeadaptionRate = value; } + constexpr void setFSRSharpness(float value) { fsrSharpness = value; } + + void setAO(AO value); + void setSSREnabled(bool value); + void setRaytracedReflectionsEnabled(bool value); + constexpr void setShadowsEnabled(bool value) { shadowsEnabled = value; } + constexpr void setReflectionsEnabled(bool value) { reflectionsEnabled = value; } + constexpr void setFXAAEnabled(bool value) { fxaaEnabled = value; } + constexpr void setBloomEnabled(bool value) { bloomEnabled = value; } + constexpr void setColorGradingEnabled(bool value) { colorGradingEnabled = value; } + constexpr void setVolumeLightsEnabled(bool value) { volumeLightsEnabled = value; } + constexpr void setLightShaftsEnabled(bool value) { lightShaftsEnabled = value; } + constexpr void setLensFlareEnabled(bool value) { lensFlareEnabled = value; } + constexpr void setMotionBlurEnabled(bool value) { motionBlurEnabled = value; } + constexpr void setDepthOfFieldEnabled(bool value) { depthOfFieldEnabled = value; } + constexpr void setEyeAdaptionEnabled(bool value) { eyeAdaptionEnabled = value; } + constexpr void setSharpenFilterEnabled(bool value) { sharpenFilterEnabled = value; } + constexpr void setOutlineEnabled(bool value) { outlineEnabled = value; } + constexpr void setChromaticAberrationEnabled(bool value) { chromaticAberrationEnabled = value; } + constexpr void setDitherEnabled(bool value) { ditherEnabled = value; } + constexpr void setOcclusionCullingEnabled(bool value) { occlusionCullingEnabled = value; } + constexpr void setSceneUpdateEnabled(bool value) { sceneUpdateEnabled = value; } + void setFSREnabled(bool value); + + virtual void setMSAASampleCount(uint32_t value) { msaaSampleCount = value; } + + void PreUpdate() override; + void Update(float dt) override; + void Render() const override; + void Compose(wi::graphics::CommandList cmd) const override; + }; + +} diff --git a/WickedEngine/wiRenderPath3D_BindLua.cpp b/WickedEngine/wiRenderPath3D_BindLua.cpp new file mode 100644 index 000000000..21dd5255f --- /dev/null +++ b/WickedEngine/wiRenderPath3D_BindLua.cpp @@ -0,0 +1,384 @@ +#include "wiRenderPath3D_BindLua.h" +#include "wiTexture_BindLua.h" + +namespace wi::lua +{ + + const char RenderPath3D_BindLua::className[] = "RenderPath3D"; + + Luna::FunctionType RenderPath3D_BindLua::methods[] = { + lunamethod(RenderPath2D_BindLua, AddSprite), + lunamethod(RenderPath2D_BindLua, AddFont), + lunamethod(RenderPath2D_BindLua, RemoveSprite), + lunamethod(RenderPath2D_BindLua, RemoveFont), + lunamethod(RenderPath2D_BindLua, ClearSprites), + lunamethod(RenderPath2D_BindLua, ClearFonts), + lunamethod(RenderPath2D_BindLua, GetSpriteOrder), + lunamethod(RenderPath2D_BindLua, GetFontOrder), + + lunamethod(RenderPath2D_BindLua, AddLayer), + lunamethod(RenderPath2D_BindLua, GetLayers), + lunamethod(RenderPath2D_BindLua, SetLayerOrder), + lunamethod(RenderPath2D_BindLua, SetSpriteOrder), + lunamethod(RenderPath2D_BindLua, SetFontOrder), + + lunamethod(RenderPath_BindLua, GetLayerMask), + lunamethod(RenderPath_BindLua, SetLayerMask), + + lunamethod(RenderPath3D_BindLua, SetAO), + lunamethod(RenderPath3D_BindLua, SetSSREnabled), + lunamethod(RenderPath3D_BindLua, SetRaytracedReflectionsEnabled), + lunamethod(RenderPath3D_BindLua, SetShadowsEnabled), + lunamethod(RenderPath3D_BindLua, SetReflectionsEnabled), + lunamethod(RenderPath3D_BindLua, SetFXAAEnabled), + lunamethod(RenderPath3D_BindLua, SetBloomEnabled), + lunamethod(RenderPath3D_BindLua, SetBloomThreshold), + lunamethod(RenderPath3D_BindLua, SetColorGradingEnabled), + lunamethod(RenderPath3D_BindLua, SetVolumeLightsEnabled), + lunamethod(RenderPath3D_BindLua, SetLightShaftsEnabled), + lunamethod(RenderPath3D_BindLua, SetLensFlareEnabled), + lunamethod(RenderPath3D_BindLua, SetMotionBlurEnabled), + lunamethod(RenderPath3D_BindLua, SetDitherEnabled), + lunamethod(RenderPath3D_BindLua, SetDepthOfFieldEnabled), + lunamethod(RenderPath3D_BindLua, SetEyeAdaptionEnabled), + lunamethod(RenderPath3D_BindLua, SetMSAASampleCount), + lunamethod(RenderPath3D_BindLua, SetSharpenFilterEnabled), + lunamethod(RenderPath3D_BindLua, SetSharpenFilterAmount), + lunamethod(RenderPath3D_BindLua, SetExposure), + lunamethod(RenderPath3D_BindLua, SetMotionBlurStrength), + lunamethod(RenderPath3D_BindLua, SetDepthOfFieldStrength), + { NULL, NULL } + }; + Luna::PropertyType RenderPath3D_BindLua::properties[] = { + { NULL, NULL } + }; + + + int RenderPath3D_BindLua::SetAO(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetAO(AO value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + int value = wi::lua::SGetInt(L, 1); + RenderPath3D::AO ao = (RenderPath3D::AO)value; + ((RenderPath3D*)component)->setAO(ao); + } + else + wi::lua::SError(L, "SetAO(AO value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetSSREnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetSSREnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setSSREnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetSSREnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetRaytracedReflectionsEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetRaytracedReflectionsEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setRaytracedReflectionsEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetRaytracedReflectionsEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetShadowsEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetShadowsEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setShadowsEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetShadowsEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetReflectionsEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetShadowsEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setReflectionsEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetShadowsEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetFXAAEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetFXAAEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setFXAAEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetFXAAEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetBloomEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetBloomEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setBloomEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetBloomEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetBloomThreshold(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetBloomThreshold(float value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setBloomThreshold(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetBloomThreshold(float value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetColorGradingEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetColorGradingEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setColorGradingEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetColorGradingEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetVolumeLightsEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetVolumeLightsEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setVolumeLightsEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetVolumeLightsEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetLightShaftsEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetLightShaftsEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setLightShaftsEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetLightShaftsEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetLensFlareEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetLensFlareEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setLensFlareEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetLensFlareEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetMotionBlurEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetMotionBlurEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setMotionBlurEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetMotionBlurEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetDitherEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetDitherEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + ((RenderPath3D*)component)->setDitherEnabled(wi::lua::SGetBool(L, 1)); + else + wi::lua::SError(L, "SetDitherEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetDepthOfFieldEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetDepthOfFieldEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setDepthOfFieldEnabled(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetDepthOfFieldEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetEyeAdaptionEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetEyeAdaptionEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setEyeAdaptionEnabled(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetEyeAdaptionEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetMSAASampleCount(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetMSAASampleCount(int value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setMSAASampleCount((uint32_t)wi::lua::SGetInt(L, 1)); + } + else + wi::lua::SError(L, "SetMSAASampleCount(int value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetSharpenFilterEnabled(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetSharpenFilterEnabled(bool value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setSharpenFilterEnabled(wi::lua::SGetBool(L, 1)); + } + else + wi::lua::SError(L, "SetSharpenFilterEnabled(bool value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetSharpenFilterAmount(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetSharpenFilterAmount(float value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setSharpenFilterAmount(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetSharpenFilterAmount(float value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetExposure(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetExposure(float value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setExposure(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetExposure(float value) not enough arguments!"); + return 0; + } + + + int RenderPath3D_BindLua::SetMotionBlurStrength(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetMotionBlurStrength(float value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setMotionBlurStrength(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetMotionBlurStrength(float value) not enough arguments!"); + return 0; + } + int RenderPath3D_BindLua::SetDepthOfFieldStrength(lua_State* L) + { + if (component == nullptr) + { + wi::lua::SError(L, "SetDepthOfFieldStrength(float value) component is null!"); + return 0; + } + if (wi::lua::SGetArgCount(L) > 0) + { + ((RenderPath3D*)component)->setDepthOfFieldStrength(wi::lua::SGetFloat(L, 1)); + } + else + wi::lua::SError(L, "SetDepthOfFieldStrength(float value) not enough arguments!"); + return 0; + } + + void RenderPath3D_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + + wi::lua::RunText("AO_DISABLED = 0"); + wi::lua::RunText("AO_SSAO = 1"); + wi::lua::RunText("AO_HBAO = 2"); + wi::lua::RunText("AO_MSAO = 3"); + wi::lua::RunText("AO_RTAO = 4"); + } + } + +} diff --git a/WickedEngine/wiRenderPath3D_BindLua.h b/WickedEngine/wiRenderPath3D_BindLua.h new file mode 100644 index 000000000..2261e59d2 --- /dev/null +++ b/WickedEngine/wiRenderPath3D_BindLua.h @@ -0,0 +1,55 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiRenderPath3D.h" +#include "wiRenderPath2D_BindLua.h" + +namespace wi::lua +{ + + class RenderPath3D_BindLua : public RenderPath2D_BindLua + { + private: + RenderPath3D renderpath; + public: + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + RenderPath3D_BindLua() = default; + RenderPath3D_BindLua(RenderPath3D* component) + { + this->component = component; + } + RenderPath3D_BindLua(lua_State* L) + { + this->component = &renderpath; + } + + int SetAO(lua_State* L); + int SetSSREnabled(lua_State* L); + int SetRaytracedReflectionsEnabled(lua_State* L); + int SetShadowsEnabled(lua_State* L); + int SetReflectionsEnabled(lua_State* L); + int SetFXAAEnabled(lua_State* L); + int SetBloomEnabled(lua_State* L); + int SetBloomThreshold(lua_State* L); + int SetColorGradingEnabled(lua_State* L); + int SetVolumeLightsEnabled(lua_State* L); + int SetLightShaftsEnabled(lua_State* L); + int SetLensFlareEnabled(lua_State* L); + int SetMotionBlurEnabled(lua_State* L); + int SetDitherEnabled(lua_State* L); + int SetDepthOfFieldEnabled(lua_State* L); + int SetEyeAdaptionEnabled(lua_State* L); + int SetMSAASampleCount(lua_State* L); + int SetSharpenFilterEnabled(lua_State* L); + int SetSharpenFilterAmount(lua_State* L); + int SetExposure(lua_State* L); + int SetMotionBlurStrength(lua_State* L); + int SetDepthOfFieldStrength(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiRenderPath3D_PathTracing.cpp b/WickedEngine/wiRenderPath3D_PathTracing.cpp new file mode 100644 index 000000000..10fc77f10 --- /dev/null +++ b/WickedEngine/wiRenderPath3D_PathTracing.cpp @@ -0,0 +1,411 @@ +#include "wiRenderPath3D_PathTracing.h" +#include "wiRenderer.h" +#include "wiImage.h" +#include "wiHelper.h" +#include "wiTextureHelper.h" +#include "wiSprite.h" +#include "wiProfiler.h" +#include "wiScene.h" +#include "wiBacklog.h" + + +using namespace wi::graphics; +using namespace wi::scene; + + +namespace wi +{ + +#if __has_include("OpenImageDenoise/oidn.hpp") +#define OPEN_IMAGE_DENOISE +#include "OpenImageDenoise/oidn.hpp" +#pragma comment(lib,"OpenImageDenoise.lib") +#pragma comment(lib,"tbb.lib") + // Also provide OpenImageDenoise.dll and tbb.dll near the exe! + bool DenoiserCallback(void* userPtr, double n) + { + auto renderpath = (RenderPath3D_PathTracing*)userPtr; + if (renderpath->getProgress() < 1) + { + renderpath->denoiserProgress = 0; + return false; + } + renderpath->denoiserProgress = (float)n; + return true; + } + bool RenderPath3D_PathTracing::isDenoiserAvailable() const { return true; } +#else + bool RenderPath3D_PathTracing::isDenoiserAvailable() const { return false; } +#endif + + void RenderPath3D_PathTracing::ResizeBuffers() + { + RenderPath2D::ResizeBuffers(); // we don't need to use any buffers from RenderPath3D, so skip those + + GraphicsDevice* device = wi::graphics::GetDevice(); + + XMUINT2 internalResolution = GetInternalResolution(); + + { + TextureDesc desc; + desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE | BindFlag::RENDER_TARGET; + desc.format = Format::R32G32B32A32_FLOAT; + desc.width = internalResolution.x; + desc.height = internalResolution.y; + device->CreateTexture(&desc, nullptr, &traceResult); + device->SetName(&traceResult, "traceResult"); + +#ifdef OPEN_IMAGE_DENOISE + desc.bind_flags = BindFlag::UNORDERED_ACCESS; + desc.layout = ResourceState::UNORDERED_ACCESS; + device->CreateTexture(&desc, nullptr, &denoiserAlbedo); + device->SetName(&denoiserAlbedo, "denoiserAlbedo"); + device->CreateTexture(&desc, nullptr, &denoiserNormal); + device->SetName(&denoiserNormal, "denoiserNormal"); +#endif // OPEN_IMAGE_DENOISE + } + { + TextureDesc desc; + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.format = Format::R11G11B10_FLOAT; + desc.width = internalResolution.x; + desc.height = internalResolution.y; + device->CreateTexture(&desc, nullptr, &rtPostprocess); + device->SetName(&rtPostprocess, "rtPostprocess"); + + + desc.width /= 4; + desc.height /= 4; + desc.bind_flags = BindFlag::UNORDERED_ACCESS | BindFlag::SHADER_RESOURCE; + device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[0]); + device->SetName(&rtGUIBlurredBackground[0], "rtGUIBlurredBackground[0]"); + + desc.width /= 4; + desc.height /= 4; + device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[1]); + device->SetName(&rtGUIBlurredBackground[1], "rtGUIBlurredBackground[1]"); + device->CreateTexture(&desc, nullptr, &rtGUIBlurredBackground[2]); + device->SetName(&rtGUIBlurredBackground[2], "rtGUIBlurredBackground[2]"); + } + + { + RenderPassDesc desc; + desc.attachments.push_back(RenderPassAttachment::RenderTarget(&traceResult, RenderPassAttachment::LoadOp::CLEAR)); + + device->CreateRenderPass(&desc, &renderpass_debugbvh); + } + + wi::renderer::CreateLuminanceResources(luminanceResources, internalResolution); + wi::renderer::CreateBloomResources(bloomResources, internalResolution); + + // also reset accumulation buffer state: + sam = -1; + } + + void RenderPath3D_PathTracing::Update(float dt) + { + setOcclusionCullingEnabled(false); + + if (camera->IsDirty()) + { + camera->SetDirty(false); + sam = -1; + } + else + { + for (size_t i = 0; i < scene->transforms.GetCount(); ++i) + { + const TransformComponent& transform = scene->transforms[i]; + + if (transform.IsDirty()) + { + sam = -1; + break; + } + } + + if (sam >= 0) + { + for (size_t i = 0; i < scene->materials.GetCount(); ++i) + { + const MaterialComponent& material = scene->materials[i]; + + if (material.IsDirty()) + { + sam = -1; + break; + } + } + } + } + sam++; + + if (sam > target) + { + sam = target; + } + if (target < sam) + { + resetProgress(); + } + + scene->SetAccelerationStructureUpdateRequested(sam == 0); + setSceneUpdateEnabled(sam == 0); + + RenderPath3D::Update(dt); + + +#ifdef OPEN_IMAGE_DENOISE + if (sam == target) + { + if (!denoiserResult.IsValid() && !wi::jobsystem::IsBusy(denoiserContext)) + { + //wi::helper::saveTextureToFile(denoiserAlbedo, "C:/PROJECTS/WickedEngine/Editor/_albedo.png"); + //wi::helper::saveTextureToFile(denoiserNormal, "C:/PROJECTS/WickedEngine/Editor/_normal.png"); + + texturedata_src.clear(); + texturedata_dst.clear(); + texturedata_albedo.clear(); + texturedata_normal.clear(); + + if (wi::helper::saveTextureToMemory(traceResult, texturedata_src)) + { + wi::helper::saveTextureToMemory(denoiserAlbedo, texturedata_albedo); + wi::helper::saveTextureToMemory(denoiserNormal, texturedata_normal); + + texturedata_dst.resize(texturedata_src.size()); + + wi::jobsystem::Execute(denoiserContext, [&](wi::jobsystem::JobArgs args) { + + size_t width = (size_t)traceResult.desc.width; + size_t height = (size_t)traceResult.desc.height; + { + // https://github.com/OpenImageDenoise/oidn#c11-api-example + + // Create an Intel Open Image Denoise device + static oidn::DeviceRef device = oidn::newDevice(); + static bool init = false; + if (!init) + { + device.commit(); + init = true; + } + + // Create a denoising filter + oidn::FilterRef filter = device.newFilter("RT"); // generic ray tracing filter + filter.setImage("color", texturedata_src.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); + if (!texturedata_albedo.empty()) + { + filter.setImage("albedo", texturedata_albedo.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); // optional + } + if (!texturedata_normal.empty()) + { + filter.setImage("normal", texturedata_normal.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); // optional + } + filter.setImage("output", texturedata_dst.data(), oidn::Format::Float3, width, height, 0, sizeof(XMFLOAT4)); + filter.set("hdr", true); // image is HDR + //filter.set("cleanAux", true); + filter.commit(); + + denoiserProgress = 0; + filter.setProgressMonitorFunction(DenoiserCallback, this); + + // Filter the image + filter.execute(); + + // Check for errors + const char* errorMessage; + auto error = device.getError(errorMessage); + if (error != oidn::Error::None && error != oidn::Error::Cancelled) + { + wi::backlog::post(std::string("[OpenImageDenoise error] ") + errorMessage); + } + } + + GraphicsDevice* device = wi::graphics::GetDevice(); + + TextureDesc desc; + desc.width = (uint32_t)width; + desc.height = (uint32_t)height; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + desc.format = Format::R32G32B32A32_FLOAT; + + SubresourceData initdata; + initdata.data_ptr = texturedata_dst.data(); + initdata.row_pitch = uint32_t(sizeof(XMFLOAT4) * width); + device->CreateTexture(&desc, &initdata, &denoiserResult); + + }); + } + } + } + else + { + denoiserResult = Texture(); + denoiserProgress = 0; + } +#endif // OPEN_IMAGE_DENOISE + } + + void RenderPath3D_PathTracing::Render() const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + wi::jobsystem::context ctx; + + if (sam < target) + { + // Setup: + CommandList cmd = device->BeginCommandList(); + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { + + wi::renderer::BindCameraCB( + *camera, + camera_previous, + camera_reflection, + cmd + ); + wi::renderer::UpdateRenderData(visibility_main, frameCB, cmd); + wi::renderer::UpdateRenderDataAsync(visibility_main, frameCB, cmd); + + if (scene->IsAccelerationStructureUpdateRequested()) + { + wi::renderer::UpdateRaytracingAccelerationStructures(*scene, cmd); + } + }); + + // Main scene: + cmd = device->BeginCommandList(); + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { + + GraphicsDevice* device = wi::graphics::GetDevice(); + + wi::renderer::BindCameraCB( + *camera, + *camera, + *camera, + cmd + ); + wi::renderer::BindCommonResources(cmd); + + if (wi::renderer::GetRaytraceDebugBVHVisualizerEnabled()) + { + device->RenderPassBegin(&renderpass_debugbvh, cmd); + + Viewport vp; + vp.width = (float)traceResult.GetDesc().width; + vp.height = (float)traceResult.GetDesc().height; + device->BindViewports(1, &vp, cmd); + + wi::renderer::RayTraceSceneBVH(*scene, cmd); + + device->RenderPassEnd(cmd); + } + else + { + auto range = wi::profiler::BeginRangeGPU("Traced Scene", cmd); + + wi::renderer::RayTraceScene( + *scene, + traceResult, + sam, + cmd, + denoiserAlbedo.IsValid() ? &denoiserAlbedo : nullptr, + denoiserNormal.IsValid() ? &denoiserNormal : nullptr + ); + + + wi::profiler::EndRange(range); // Traced Scene + } + + }); + } + + // Tonemap etc: + CommandList cmd = device->BeginCommandList(); + wi::jobsystem::Execute(ctx, [this, cmd](wi::jobsystem::JobArgs args) { + + GraphicsDevice* device = wi::graphics::GetDevice(); + + wi::renderer::BindCameraCB( + *camera, + *camera, + *camera, + cmd + ); + wi::renderer::BindCommonResources(cmd); + + Texture srcTex = denoiserResult.IsValid() && !wi::jobsystem::IsBusy(denoiserContext) ? denoiserResult : traceResult; + + if (getEyeAdaptionEnabled()) + { + wi::renderer::ComputeLuminance( + luminanceResources, + srcTex, + cmd, + getEyeAdaptionRate(), + getEyeAdaptionKey() + ); + } + if (getBloomEnabled()) + { + wi::renderer::ComputeBloom( + bloomResources, + srcTex, + cmd, + getBloomThreshold(), + getExposure(), + getEyeAdaptionEnabled() ? &luminanceResources.luminance : nullptr + ); + } + + wi::renderer::Postprocess_Tonemap( + srcTex, + rtPostprocess, + cmd, + getExposure(), + getDitherEnabled(), + getColorGradingEnabled() ? (scene->weather.colorGradingMap.IsValid() ? &scene->weather.colorGradingMap.GetTexture() : nullptr) : nullptr, + nullptr, + getEyeAdaptionEnabled() ? &luminanceResources.luminance : nullptr, + getBloomEnabled() ? &bloomResources.texture_bloom : nullptr, + colorspace + ); + lastPostprocessRT = &rtPostprocess; + + // GUI Background blurring: + { + auto range = wi::profiler::BeginRangeGPU("GUI Background Blur", cmd); + device->EventBegin("GUI Background Blur", cmd); + wi::renderer::Postprocess_Downsample4x(rtPostprocess, rtGUIBlurredBackground[0], cmd); + wi::renderer::Postprocess_Downsample4x(rtGUIBlurredBackground[0], rtGUIBlurredBackground[2], cmd); + wi::renderer::Postprocess_Blur_Gaussian(rtGUIBlurredBackground[2], rtGUIBlurredBackground[1], rtGUIBlurredBackground[2], cmd, -1, -1, true); + device->EventEnd(cmd); + wi::profiler::EndRange(range); + } + }); + + RenderPath2D::Render(); + + wi::jobsystem::Wait(ctx); + } + + void RenderPath3D_PathTracing::Compose(CommandList cmd) const + { + GraphicsDevice* device = wi::graphics::GetDevice(); + + device->EventBegin("RenderPath3D_PathTracing::Compose", cmd); + + wi::renderer::BindCommonResources(cmd); + + wi::image::Params fx; + fx.enableFullScreen(); + fx.blendFlag = wi::enums::BLENDMODE_OPAQUE; + fx.quality = wi::image::QUALITY_LINEAR; + wi::image::Draw(&rtPostprocess, fx, cmd); + + device->EventEnd(cmd); + + RenderPath2D::Compose(cmd); + } + +} diff --git a/WickedEngine/wiRenderPath3D_PathTracing.h b/WickedEngine/wiRenderPath3D_PathTracing.h new file mode 100644 index 000000000..88ac0be5c --- /dev/null +++ b/WickedEngine/wiRenderPath3D_PathTracing.h @@ -0,0 +1,47 @@ +#pragma once +#include "wiRenderPath3D.h" +#include "wiVector.h" + +namespace wi +{ + + class RenderPath3D_PathTracing : + public RenderPath3D + { + protected: + int sam = -1; + int target = 1024; + wi::graphics::Texture traceResult; + + wi::vector texturedata_src; + wi::vector texturedata_dst; + wi::vector texturedata_albedo; + wi::vector texturedata_normal; + wi::graphics::Texture denoiserAlbedo; + wi::graphics::Texture denoiserNormal; + wi::graphics::Texture denoiserResult; + wi::jobsystem::context denoiserContext; + + wi::graphics::RenderPass renderpass_debugbvh; + + void ResizeBuffers() override; + + public: + const wi::graphics::Texture* GetDepthStencil() const override { return nullptr; }; + + void Update(float dt) override; + void Render() const override; + void Compose(wi::graphics::CommandList cmd) const override; + + int getCurrentSampleCount() const { return sam; } + void setTargetSampleCount(int value) { target = value; } + float getProgress() const { return (float)sam / (float)target; } + + float denoiserProgress = 0; + float getDenoiserProgress() const { return denoiserProgress; } + bool isDenoiserAvailable() const; + + void resetProgress() { sam = -1; denoiserProgress = 0; } + }; + +} diff --git a/WickedEngine/wiRenderPath_BindLua.cpp b/WickedEngine/wiRenderPath_BindLua.cpp new file mode 100644 index 000000000..53dec0e96 --- /dev/null +++ b/WickedEngine/wiRenderPath_BindLua.cpp @@ -0,0 +1,48 @@ +#include "wiRenderPath_BindLua.h" + +namespace wi::lua +{ + + const char RenderPath_BindLua::className[] = "RenderPath"; + + Luna::FunctionType RenderPath_BindLua::methods[] = { + lunamethod(RenderPath_BindLua, GetLayerMask), + lunamethod(RenderPath_BindLua, SetLayerMask), + { NULL, NULL } + }; + Luna::PropertyType RenderPath_BindLua::properties[] = { + { NULL, NULL } + }; + + + int RenderPath_BindLua::GetLayerMask(lua_State* L) + { + uint32_t mask = component->getLayerMask(); + wi::lua::SSetInt(L, *reinterpret_cast(&mask)); + return 1; + } + int RenderPath_BindLua::SetLayerMask(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + int mask = wi::lua::SGetInt(L, 1); + component->setlayerMask(*reinterpret_cast(&mask)); + } + else + wi::lua::SError(L, "SetLayerMask(uint mask) not enough arguments!"); + return 0; + } + + void RenderPath_BindLua::Bind() + { + + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + } + } + +} diff --git a/WickedEngine/wiRenderPath_BindLua.h b/WickedEngine/wiRenderPath_BindLua.h new file mode 100644 index 000000000..20ae9709b --- /dev/null +++ b/WickedEngine/wiRenderPath_BindLua.h @@ -0,0 +1,25 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiRenderPath.h" + +namespace wi::lua +{ + class RenderPath_BindLua + { + public: + RenderPath* component = nullptr; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + RenderPath_BindLua() = default; + RenderPath_BindLua(RenderPath* component) :component(component) {} + RenderPath_BindLua(lua_State* L) {} + + virtual int GetLayerMask(lua_State* L); + virtual int SetLayerMask(lua_State* L); + + static void Bind(); + }; +} diff --git a/WickedEngine/wiRenderer.cpp b/WickedEngine/wiRenderer.cpp index 6f60c0bdc..caaa9e1b5 100644 --- a/WickedEngine/wiRenderer.cpp +++ b/WickedEngine/wiRenderer.cpp @@ -7,15 +7,14 @@ #include "wiTextureHelper.h" #include "wiEnums.h" #include "wiRectPacker.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiProfiler.h" #include "wiOcean.h" #include "wiGPUSortLib.h" -#include "wiAllocator.h" #include "wiGPUBVH.h" #include "wiJobSystem.h" #include "wiSpinLock.h" -#include "wiEvent.h" +#include "wiEventHandler.h" #include "wiPlatform.h" #include "wiSheenLUT.h" #include "wiShaderCompiler.h" @@ -30,12 +29,13 @@ #include #include -using namespace wiGraphics; -using namespace wiScene; -using namespace wiECS; -using namespace wiAllocator; +using namespace wi::primitive; +using namespace wi::graphics; +using namespace wi::enums; +using namespace wi::scene; +using namespace wi::ecs; -namespace wiRenderer +namespace wi::renderer { GraphicsDevice*& device = GetDevice(); @@ -53,6 +53,54 @@ Sampler samplers[SAMPLER_COUNT]; std::string SHADERPATH = "shaders/"; std::string SHADERSOURCEPATH = "../WickedEngine/shaders/"; +// Simple and efficient allocator that reserves a linear memory buffer and can: +// - allocate bottom-up until there is space +// - free from the last allocation top-down, for temporary allocations +// - reset all allocations at once +class LinearAllocator +{ +public: + constexpr size_t get_capacity() const + { + return capacity; + } + inline void reserve(size_t newCapacity) + { + capacity = newCapacity; + + std::free(buffer); + buffer = (uint8_t*)std::malloc(capacity); + } + constexpr uint8_t* allocate(size_t size) + { + if (offset + size <= capacity) + { + uint8_t* ret = &buffer[offset]; + offset += size; + return ret; + } + return nullptr; + } + constexpr void free(size_t size) + { + assert(offset >= size); + offset -= size; + } + constexpr void reset() + { + offset = 0; + } + constexpr uint8_t* top() + { + return buffer + offset; + } + +private: + uint8_t* buffer = nullptr; + size_t capacity = 0; + size_t offset = 0; + size_t alignment = 1; +}; LinearAllocator renderFrameAllocators[COMMANDLIST_COUNT]; // can be used by graphics threads inline LinearAllocator& GetRenderFrameAllocator(CommandList cmd) { @@ -130,8 +178,8 @@ wi::vector renderpasses_shadow2D; wi::vector renderpasses_shadowCube; wi::vector> renderableBoxes; -wi::vector> renderableSpheres; -wi::vector> renderableCapsules; +wi::vector> renderableSpheres; +wi::vector> renderableCapsules; wi::vector renderableLines; wi::vector renderableLines2D; wi::vector renderablePoints; @@ -139,8 +187,8 @@ wi::vector renderableTriangles_solid; wi::vector renderableTriangles_wireframe; wi::vector paintrads; -wiSpinLock deferredMIPGenLock; -wi::vector, bool>> deferredMIPGens; +wi::SpinLock deferredMIPGenLock; +wi::vector> deferredMIPGens; bool volumetric_clouds_precomputed = false; @@ -213,9 +261,9 @@ struct RenderQueue }; -const Sampler* GetSampler(int slot) +const Sampler* GetSampler(SAMPLERTYPES id) { - return &samplers[slot]; + return &samplers[id]; } const Shader* GetShader(SHADERTYPE id) { @@ -466,34 +514,34 @@ SHADERTYPE GetPSTYPE(RENDERPASS renderPass, bool alphatest, bool transparent, Ma case RENDERPASS_MAIN: switch (shaderType) { - case wiScene::MaterialComponent::SHADERTYPE_PBR: + case MaterialComponent::SHADERTYPE_PBR: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT : PSTYPE_OBJECT; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_PLANARREFLECTION: + case MaterialComponent::SHADERTYPE_PBR_PLANARREFLECTION: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_PLANARREFLECTION : PSTYPE_OBJECT_PLANARREFLECTION; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_PARALLAXOCCLUSIONMAPPING: + case MaterialComponent::SHADERTYPE_PBR_PARALLAXOCCLUSIONMAPPING: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_POM : PSTYPE_OBJECT_POM; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_ANISOTROPIC: + case MaterialComponent::SHADERTYPE_PBR_ANISOTROPIC: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_ANISOTROPIC : PSTYPE_OBJECT_ANISOTROPIC; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_CLOTH: + case MaterialComponent::SHADERTYPE_PBR_CLOTH: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_CLOTH : PSTYPE_OBJECT_CLOTH; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_CLEARCOAT: + case MaterialComponent::SHADERTYPE_PBR_CLEARCOAT: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_CLEARCOAT : PSTYPE_OBJECT_CLEARCOAT; break; - case wiScene::MaterialComponent::SHADERTYPE_PBR_CLOTH_CLEARCOAT: + case MaterialComponent::SHADERTYPE_PBR_CLOTH_CLEARCOAT: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_CLOTH_CLEARCOAT : PSTYPE_OBJECT_CLOTH_CLEARCOAT; break; - case wiScene::MaterialComponent::SHADERTYPE_WATER: + case MaterialComponent::SHADERTYPE_WATER: realPS = transparent ? PSTYPE_OBJECT_WATER : SHADERTYPE_COUNT; break; - case wiScene::MaterialComponent::SHADERTYPE_CARTOON: + case MaterialComponent::SHADERTYPE_CARTOON: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_CARTOON : PSTYPE_OBJECT_CARTOON; break; - case wiScene::MaterialComponent::SHADERTYPE_UNLIT: + case MaterialComponent::SHADERTYPE_UNLIT: realPS = transparent ? PSTYPE_OBJECT_TRANSPARENT_UNLIT : PSTYPE_OBJECT_UNLIT; break; default: @@ -628,47 +676,47 @@ bool LoadShader(ShaderStage stage, Shader& shader, const std::string& filename, } else { - wiBackLog::post("shader dump doesn't contain shader: " + shaderbinaryfilename); + wi::backlog::post("shader dump doesn't contain shader: " + shaderbinaryfilename); } #endif // SHADERDUMP_ENABLED - wiShaderCompiler::RegisterShader(shaderbinaryfilename); + wi::shadercompiler::RegisterShader(shaderbinaryfilename); - if (wiShaderCompiler::IsShaderOutdated(shaderbinaryfilename)) + if (wi::shadercompiler::IsShaderOutdated(shaderbinaryfilename)) { - wiShaderCompiler::CompilerInput input; + wi::shadercompiler::CompilerInput input; input.format = device->GetShaderFormat(); input.stage = stage; input.minshadermodel = minshadermodel; std::string sourcedir = SHADERSOURCEPATH; - wiHelper::MakePathAbsolute(sourcedir); + wi::helper::MakePathAbsolute(sourcedir); input.include_directories.push_back(sourcedir); - input.shadersourcefilename = wiHelper::ReplaceExtension(sourcedir + filename, "hlsl"); + input.shadersourcefilename = wi::helper::ReplaceExtension(sourcedir + filename, "hlsl"); - wiShaderCompiler::CompilerOutput output; - wiShaderCompiler::Compile(input, output); + wi::shadercompiler::CompilerOutput output; + wi::shadercompiler::Compile(input, output); if (output.IsValid()) { - wiShaderCompiler::SaveShaderAndMetadata(shaderbinaryfilename, output); + wi::shadercompiler::SaveShaderAndMetadata(shaderbinaryfilename, output); if (!output.error_message.empty()) { - wiBackLog::post(output.error_message); + wi::backlog::post(output.error_message); } - wiBackLog::post("shader compiled: " + shaderbinaryfilename); + wi::backlog::post("shader compiled: " + shaderbinaryfilename); return device->CreateShader(stage, output.shaderdata, output.shadersize, &shader); } else { - wiBackLog::post("shader compile FAILED: " + shaderbinaryfilename + "\n" + output.error_message); + wi::backlog::post("shader compile FAILED: " + shaderbinaryfilename + "\n" + output.error_message); } } wi::vector buffer; - if (wiHelper::FileRead(shaderbinaryfilename, buffer)) + if (wi::helper::FileRead(shaderbinaryfilename, buffer)) { return device->CreateShader(stage, buffer.data(), buffer.size(), &shader); } @@ -679,9 +727,9 @@ bool LoadShader(ShaderStage stage, Shader& shader, const std::string& filename, void LoadShaders() { - wiJobSystem::context ctx; + wi::jobsystem::context ctx; - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { inputLayouts[ILTYPE_OBJECT_DEBUG].elements = { { "POSITION_NORMAL_WIND", 0, MeshComponent::Vertex_POS::FORMAT, 0, InputLayout::APPEND_ALIGNED_ELEMENT, InputClassification::PER_VERTEX_DATA }, @@ -689,29 +737,29 @@ void LoadShaders() LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_DEBUG], "objectVS_debug.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_COMMON], "objectVS_common.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS], "objectVS_prepass.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS_ALPHATEST], "objectVS_prepass_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOW], "shadowVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_SIMPLE], "objectVS_simple.cso"); LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOW_ALPHATEST], "shadowVS_alphatest.cso"); LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOW_TRANSPARENT], "shadowVS_transparent.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { inputLayouts[ILTYPE_VERTEXCOLOR].elements = { { "POSITION", 0, Format::R32G32B32A32_FLOAT, 0, InputLayout::APPEND_ALIGNED_ELEMENT, InputClassification::PER_VERTEX_DATA }, @@ -720,7 +768,7 @@ void LoadShaders() LoadShader(ShaderStage::VS, shaders[VSTYPE_VERTEXCOLOR], "vertexcolorVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { inputLayouts[ILTYPE_RENDERLIGHTMAP].elements = { { "POSITION_NORMAL_WIND", 0, MeshComponent::Vertex_POS::FORMAT, 0, InputLayout::APPEND_ALIGNED_ELEMENT, InputClassification::PER_VERTEX_DATA }, @@ -729,288 +777,288 @@ void LoadShaders() LoadShader(ShaderStage::VS, shaders[VSTYPE_RENDERLIGHTMAP], "renderlightmapVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_COMMON_TESSELLATION], "objectVS_common_tessellation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS_TESSELLATION], "objectVS_prepass_tessellation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS_ALPHATEST_TESSELLATION], "objectVS_prepass_alphatest_tessellation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_SIMPLE_TESSELLATION], "objectVS_simple_tessellation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_IMPOSTOR], "impostorVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_DIRECTIONAL], "volumetriclight_directionalVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_POINT], "volumetriclight_pointVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_SPOT], "volumetriclight_spotVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LIGHTVISUALIZER_SPOTLIGHT], "vSpotLightVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LIGHTVISUALIZER_POINTLIGHT], "vPointLightVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SPHERE], "sphereVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_CUBE], "cubeVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SKY], "skyVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOXELIZER], "objectVS_voxelizer.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOXEL], "voxelVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_FORCEFIELDVISUALIZER_POINT], "forceFieldPointVisualizerVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_FORCEFIELDVISUALIZER_PLANE], "forceFieldPlaneVisualizerVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_RAYTRACE_SCREEN], "raytrace_screenVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SCREEN], "screenVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LENSFLARE], "lensFlareVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_COMMON_TESSELLATION], "objectVS_common_tessellation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS_TESSELLATION], "objectVS_prepass_tessellation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_PREPASS_ALPHATEST_TESSELLATION], "objectVS_prepass_alphatest_tessellation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_OBJECT_SIMPLE_TESSELLATION], "objectVS_simple_tessellation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_IMPOSTOR], "impostorVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_DIRECTIONAL], "volumetriclight_directionalVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_POINT], "volumetriclight_pointVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOLUMETRICLIGHT_SPOT], "volumetriclight_spotVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LIGHTVISUALIZER_SPOTLIGHT], "vSpotLightVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LIGHTVISUALIZER_POINTLIGHT], "vPointLightVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SPHERE], "sphereVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_CUBE], "cubeVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SKY], "skyVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOXELIZER], "objectVS_voxelizer.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_VOXEL], "voxelVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_FORCEFIELDVISUALIZER_POINT], "forceFieldPointVisualizerVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_FORCEFIELDVISUALIZER_PLANE], "forceFieldPlaneVisualizerVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_RAYTRACE_SCREEN], "raytrace_screenVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SCREEN], "screenVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_LENSFLARE], "lensFlareVS.cso"); }); if (device->CheckCapability(GraphicsDeviceCapability::RENDERTARGET_AND_VIEWPORT_ARRAYINDEX_WITHOUT_GS)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP], "envMapVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP_SKY], "envMap_skyVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER], "cubeShadowVS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST], "cubeShadowVS_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT], "cubeShadowVS_transparent.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP], "envMapVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP_SKY], "envMap_skyVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER], "cubeShadowVS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST], "cubeShadowVS_alphatest.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT], "cubeShadowVS_transparent.cso"); }); } else { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP], "envMapVS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP_SKY], "envMap_skyVS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER], "cubeShadowVS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST], "cubeShadowVS_alphatest_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT], "cubeShadowVS_transparent_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP], "envMapVS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_ENVMAP_SKY], "envMap_skyVS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER], "cubeShadowVS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST], "cubeShadowVS_alphatest_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::VS, shaders[VSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT], "cubeShadowVS_transparent_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_ENVMAP_EMULATION], "envMapGS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_ENVMAP_SKY_EMULATION], "envMap_skyGS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_EMULATION], "cubeShadowGS_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST_EMULATION], "cubeShadowGS_alphatest_emulation.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT_EMULATION], "cubeShadowGS_transparent_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_ENVMAP_EMULATION], "envMapGS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_ENVMAP_SKY_EMULATION], "envMap_skyGS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_EMULATION], "cubeShadowGS_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_ALPHATEST_EMULATION], "cubeShadowGS_alphatest_emulation.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_SHADOWCUBEMAPRENDER_TRANSPARENT_EMULATION], "cubeShadowGS_transparent_emulation.cso"); }); } - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT], "objectPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT], "objectPS_transparent.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PLANARREFLECTION], "objectPS_planarreflection.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_PLANARREFLECTION], "objectPS_transparent_planarreflection.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_POM], "objectPS_pom.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_POM], "objectPS_transparent_pom.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_ANISOTROPIC], "objectPS_anisotropic.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_ANISOTROPIC], "objectPS_transparent_anisotropic.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLOTH], "objectPS_cloth.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLOTH], "objectPS_transparent_cloth.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLEARCOAT], "objectPS_clearcoat.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLEARCOAT], "objectPS_transparent_clearcoat.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLOTH_CLEARCOAT], "objectPS_cloth_clearcoat.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLOTH_CLEARCOAT], "objectPS_transparent_cloth_clearcoat.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CARTOON], "objectPS_cartoon.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CARTOON], "objectPS_transparent_cartoon.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_UNLIT], "objectPS_unlit.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_UNLIT], "objectPS_transparent_unlit.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_WATER], "objectPS_water.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TERRAIN], "objectPS_terrain.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR], "impostorPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT], "objectPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT], "objectPS_transparent.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PLANARREFLECTION], "objectPS_planarreflection.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_PLANARREFLECTION], "objectPS_transparent_planarreflection.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_POM], "objectPS_pom.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_POM], "objectPS_transparent_pom.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_ANISOTROPIC], "objectPS_anisotropic.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_ANISOTROPIC], "objectPS_transparent_anisotropic.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLOTH], "objectPS_cloth.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLOTH], "objectPS_transparent_cloth.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLEARCOAT], "objectPS_clearcoat.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLEARCOAT], "objectPS_transparent_clearcoat.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CLOTH_CLEARCOAT], "objectPS_cloth_clearcoat.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CLOTH_CLEARCOAT], "objectPS_transparent_cloth_clearcoat.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_CARTOON], "objectPS_cartoon.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_CARTOON], "objectPS_transparent_cartoon.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_UNLIT], "objectPS_unlit.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TRANSPARENT_UNLIT], "objectPS_transparent_unlit.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_WATER], "objectPS_water.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_TERRAIN], "objectPS_terrain.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR], "impostorPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_HOLOGRAM], "objectPS_hologram.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_HOLOGRAM], "objectPS_hologram.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_DEBUG], "objectPS_debug.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PAINTRADIUS], "objectPS_paintradius.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_SIMPLE], "objectPS_simple.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PREPASS], "objectPS_prepass.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PREPASS_ALPHATEST], "objectPS_prepass_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_PREPASS], "impostorPS_prepass.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_SIMPLE], "impostorPS_simple.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_WIRE], "impostorPS_wire.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_LIGHTVISUALIZER], "lightVisualizerPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_DIRECTIONAL], "volumetricLight_DirectionalPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_POINT], "volumetricLight_PointPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_SPOT], "volumetricLight_SpotPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP], "envMapPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_TERRAIN], "envMapPS_terrain.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_SKY_STATIC], "envMap_skyPS_static.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_SKY_DYNAMIC], "envMap_skyPS_dynamic.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_ALBEDO], "captureImpostorPS_albedo.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_NORMAL], "captureImpostorPS_normal.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_SURFACE], "captureImpostorPS_surface.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CUBEMAP], "cubeMapPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VERTEXCOLOR], "vertexcolorPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SKY_STATIC], "skyPS_static.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SKY_DYNAMIC], "skyPS_dynamic.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SUN], "sunPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_ALPHATEST], "shadowPS_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_TRANSPARENT], "shadowPS_transparent.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_WATER], "shadowPS_water.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXELIZER], "objectPS_voxelizer.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXELIZER_TERRAIN], "objectPS_voxelizer_terrain.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXEL], "voxelPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_FORCEFIELDVISUALIZER], "forceFieldVisualizerPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_DEBUG], "objectPS_debug.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PAINTRADIUS], "objectPS_paintradius.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_SIMPLE], "objectPS_simple.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PREPASS], "objectPS_prepass.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_OBJECT_PREPASS_ALPHATEST], "objectPS_prepass_alphatest.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_PREPASS], "impostorPS_prepass.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_SIMPLE], "impostorPS_simple.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_IMPOSTOR_WIRE], "impostorPS_wire.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_LIGHTVISUALIZER], "lightVisualizerPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_DIRECTIONAL], "volumetricLight_DirectionalPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_POINT], "volumetricLight_PointPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOLUMETRICLIGHT_SPOT], "volumetricLight_SpotPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP], "envMapPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_TERRAIN], "envMapPS_terrain.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_SKY_STATIC], "envMap_skyPS_static.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_ENVMAP_SKY_DYNAMIC], "envMap_skyPS_dynamic.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_ALBEDO], "captureImpostorPS_albedo.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_NORMAL], "captureImpostorPS_normal.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CAPTUREIMPOSTOR_SURFACE], "captureImpostorPS_surface.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_CUBEMAP], "cubeMapPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VERTEXCOLOR], "vertexcolorPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SKY_STATIC], "skyPS_static.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SKY_DYNAMIC], "skyPS_dynamic.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SUN], "sunPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_ALPHATEST], "shadowPS_alphatest.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_TRANSPARENT], "shadowPS_transparent.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_SHADOW_WATER], "shadowPS_water.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXELIZER], "objectPS_voxelizer.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXELIZER_TERRAIN], "objectPS_voxelizer_terrain.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_VOXEL], "voxelPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_FORCEFIELDVISUALIZER], "forceFieldVisualizerPS.cso"); }); if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RENDERLIGHTMAP], "renderlightmapPS_rtapi.cso", ShaderModel::SM_6_5); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RENDERLIGHTMAP], "renderlightmapPS_rtapi.cso", ShaderModel::SM_6_5); }); } else { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RENDERLIGHTMAP], "renderlightmapPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RENDERLIGHTMAP], "renderlightmapPS.cso"); }); } - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RAYTRACE_DEBUGBVH], "raytrace_debugbvhPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_DOWNSAMPLEDEPTHBUFFER], "downsampleDepthBuffer4xPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL], "upsample_bilateralPS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_POSTPROCESS_OUTLINE], "outlinePS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_LENSFLARE], "lensFlarePS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_RAYTRACE_DEBUGBVH], "raytrace_debugbvhPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_DOWNSAMPLEDEPTHBUFFER], "downsampleDepthBuffer4xPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL], "upsample_bilateralPS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_POSTPROCESS_OUTLINE], "outlinePS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::PS, shaders[PSTYPE_LENSFLARE], "lensFlarePS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_VOXELIZER], "objectGS_voxelizer.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_VOXEL], "voxelGS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_VOXELIZER], "objectGS_voxelizer.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::GS, shaders[GSTYPE_VOXEL], "voxelGS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LUMINANCE_PASS1], "luminancePass1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LUMINANCE_PASS2], "luminancePass2CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SHADINGRATECLASSIFICATION], "shadingRateClassificationCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SHADINGRATECLASSIFICATION_DEBUG], "shadingRateClassificationCS_DEBUG.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_TILEFRUSTUMS], "tileFrustumsCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING], "lightCullingCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_DEBUG], "lightCullingCS_DEBUG.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_ADVANCED], "lightCullingCS_ADVANCED.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_ADVANCED_DEBUG], "lightCullingCS_ADVANCED_DEBUG.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RESOLVEMSAADEPTHSTENCIL], "resolveMSAADepthStencilCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELSCENECOPYCLEAR], "voxelSceneCopyClearCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELSCENECOPYCLEAR_TEMPORALSMOOTHING], "voxelSceneCopyClearCS_TemporalSmoothing.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELRADIANCESECONDARYBOUNCE], "voxelRadianceSecondaryBounceCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELCLEARONLYNORMAL], "voxelClearOnlyNormalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_TRANSMITTANCELUT], "skyAtmosphere_transmittanceLutCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT], "skyAtmosphere_multiScatteredLuminanceLutCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_SKYVIEWLUT], "skyAtmosphere_skyViewLutCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_SKYLUMINANCELUT], "skyAtmosphere_skyLuminanceLutCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN2D_UNORM4], "generateMIPChain2DCS_unorm4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN2D_FLOAT4], "generateMIPChain2DCS_float4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN3D_UNORM4], "generateMIPChain3DCS_unorm4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN3D_FLOAT4], "generateMIPChain3DCS_float4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBE_UNORM4], "generateMIPChainCubeCS_unorm4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBE_FLOAT4], "generateMIPChainCubeCS_float4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBEARRAY_UNORM4], "generateMIPChainCubeArrayCS_unorm4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBEARRAY_FLOAT4], "generateMIPChainCubeArrayCS_float4.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_FILTERENVMAP], "filterEnvMapCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_UNORM4], "copytexture2D_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_FLOAT4], "copytexture2D_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_UNORM4_BORDEREXPAND], "copytexture2D_unorm4_borderexpandCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_FLOAT4_BORDEREXPAND], "copytexture2D_float4_borderexpandCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKINNING], "skinningCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LUMINANCE_PASS1], "luminancePass1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LUMINANCE_PASS2], "luminancePass2CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SHADINGRATECLASSIFICATION], "shadingRateClassificationCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SHADINGRATECLASSIFICATION_DEBUG], "shadingRateClassificationCS_DEBUG.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_TILEFRUSTUMS], "tileFrustumsCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING], "lightCullingCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_DEBUG], "lightCullingCS_DEBUG.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_ADVANCED], "lightCullingCS_ADVANCED.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_LIGHTCULLING_ADVANCED_DEBUG], "lightCullingCS_ADVANCED_DEBUG.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RESOLVEMSAADEPTHSTENCIL], "resolveMSAADepthStencilCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELSCENECOPYCLEAR], "voxelSceneCopyClearCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELSCENECOPYCLEAR_TEMPORALSMOOTHING], "voxelSceneCopyClearCS_TemporalSmoothing.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELRADIANCESECONDARYBOUNCE], "voxelRadianceSecondaryBounceCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VOXELCLEARONLYNORMAL], "voxelClearOnlyNormalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_TRANSMITTANCELUT], "skyAtmosphere_transmittanceLutCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_MULTISCATTEREDLUMINANCELUT], "skyAtmosphere_multiScatteredLuminanceLutCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_SKYVIEWLUT], "skyAtmosphere_skyViewLutCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKYATMOSPHERE_SKYLUMINANCELUT], "skyAtmosphere_skyLuminanceLutCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN2D_UNORM4], "generateMIPChain2DCS_unorm4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN2D_FLOAT4], "generateMIPChain2DCS_float4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN3D_UNORM4], "generateMIPChain3DCS_unorm4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAIN3D_FLOAT4], "generateMIPChain3DCS_float4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBE_UNORM4], "generateMIPChainCubeCS_unorm4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBE_FLOAT4], "generateMIPChainCubeCS_float4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBEARRAY_UNORM4], "generateMIPChainCubeArrayCS_unorm4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_GENERATEMIPCHAINCUBEARRAY_FLOAT4], "generateMIPChainCubeArrayCS_float4.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_FILTERENVMAP], "filterEnvMapCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_UNORM4], "copytexture2D_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_FLOAT4], "copytexture2D_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_UNORM4_BORDEREXPAND], "copytexture2D_unorm4_borderexpandCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_COPYTEXTURE2D_FLOAT4_BORDEREXPAND], "copytexture2D_float4_borderexpandCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SKINNING], "skinningCS.cso"); }); if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RAYTRACE], "raytraceCS_rtapi.cso", ShaderModel::SM_6_5); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RAYTRACE], "raytraceCS_rtapi.cso", ShaderModel::SM_6_5); }); } else { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RAYTRACE], "raytraceCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_RAYTRACE], "raytraceCS.cso"); }); } - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_PAINT_TEXTURE], "paint_textureCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_PAINT_TEXTURE], "paint_textureCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT1], "blur_gaussian_float1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT3], "blur_gaussian_float3CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT4], "blur_gaussian_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM1], "blur_gaussian_unorm1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM4], "blur_gaussian_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT1], "blur_gaussian_wide_float1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT3], "blur_gaussian_wide_float3CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT4], "blur_gaussian_wide_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM1], "blur_gaussian_wide_unorm1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM4], "blur_gaussian_wide_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT1], "blur_bilateral_float1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT3], "blur_bilateral_float3CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT4], "blur_bilateral_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM1], "blur_bilateral_unorm1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM4], "blur_bilateral_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT1], "blur_bilateral_wide_float1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT3], "blur_bilateral_wide_float3CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT4], "blur_bilateral_wide_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM1], "blur_bilateral_wide_unorm1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM4], "blur_bilateral_wide_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSAO], "ssaoCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_HBAO], "hbaoCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS1], "msao_preparedepthbuffers1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS2], "msao_preparedepthbuffers2CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_INTERLEAVE], "msao_interleaveCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO], "msaoCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE], "msao_blurupsampleCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_BLENDOUT], "msao_blurupsampleCS_blendout.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN], "msao_blurupsampleCS_premin.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN_BLENDOUT], "msao_blurupsampleCS_premin_blendout.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_RAYTRACE], "ssr_raytraceCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_RESOLVE], "ssr_resolveCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_TEMPORAL], "ssr_temporalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_MEDIAN], "ssr_medianCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_LIGHTSHAFTS], "lightShaftsCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_HORIZONTAL], "depthoffield_tileMaxCOC_horizontalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_VERTICAL], "depthoffield_tileMaxCOC_verticalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_NEIGHBORHOODMAXCOC], "depthoffield_neighborhoodMaxCOCCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_KICKJOBS], "depthoffield_kickjobsCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS], "depthoffield_prepassCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS_EARLYEXIT], "depthoffield_prepassCS_earlyexit.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN], "depthoffield_mainCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_EARLYEXIT], "depthoffield_mainCS_earlyexit.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_CHEAP], "depthoffield_mainCS_cheap.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_POSTFILTER], "depthoffield_postfilterCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_UPSAMPLE], "depthoffield_upsampleCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_HORIZONTAL], "motionblur_tileMaxVelocity_horizontalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_VERTICAL], "motionblur_tileMaxVelocity_verticalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_NEIGHBORHOODMAXVELOCITY], "motionblur_neighborhoodMaxVelocityCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_KICKJOBS], "motionblur_kickjobsCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR], "motionblurCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_EARLYEXIT], "motionblurCS_earlyexit.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_CHEAP], "motionblurCS_cheap.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLOOMSEPARATE], "bloomseparateCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_SHAPENOISE], "volumetricCloud_shapenoiseCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_DETAILNOISE], "volumetricCloud_detailnoiseCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_CURLNOISE], "volumetricCloud_curlnoiseCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_WEATHERMAP], "volumetricCloud_weathermapCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_RENDER], "volumetricCloud_renderCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_REPROJECT], "volumetricCloud_reprojectCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_TEMPORAL], "volumetricCloud_temporalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FXAA], "fxaaCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_TEMPORALAA], "temporalaaCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SHARPEN], "sharpenCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_TONEMAP], "tonemapCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FSR_UPSCALING], "fsr_upscalingCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FSR_SHARPEN], "fsr_sharpenCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_CHROMATIC_ABERRATION], "chromatic_aberrationCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT1], "upsample_bilateral_float1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM1], "upsample_bilateral_unorm1CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT4], "upsample_bilateral_float4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM4], "upsample_bilateral_unorm4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UINT4], "upsample_bilateral_uint4CS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DOWNSAMPLE4X], "downsample4xCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_NORMALSFROMDEPTH], "normalsfromdepthCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SCREENSPACESHADOW], "screenspaceshadowCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT1], "blur_gaussian_float1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT3], "blur_gaussian_float3CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_FLOAT4], "blur_gaussian_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM1], "blur_gaussian_unorm1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_UNORM4], "blur_gaussian_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT1], "blur_gaussian_wide_float1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT3], "blur_gaussian_wide_float3CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_FLOAT4], "blur_gaussian_wide_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM1], "blur_gaussian_wide_unorm1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_GAUSSIAN_WIDE_UNORM4], "blur_gaussian_wide_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT1], "blur_bilateral_float1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT3], "blur_bilateral_float3CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_FLOAT4], "blur_bilateral_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM1], "blur_bilateral_unorm1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_UNORM4], "blur_bilateral_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT1], "blur_bilateral_wide_float1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT3], "blur_bilateral_wide_float3CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_FLOAT4], "blur_bilateral_wide_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM1], "blur_bilateral_wide_unorm1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLUR_BILATERAL_WIDE_UNORM4], "blur_bilateral_wide_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSAO], "ssaoCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_HBAO], "hbaoCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS1], "msao_preparedepthbuffers1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_PREPAREDEPTHBUFFERS2], "msao_preparedepthbuffers2CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_INTERLEAVE], "msao_interleaveCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO], "msaoCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE], "msao_blurupsampleCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_BLENDOUT], "msao_blurupsampleCS_blendout.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN], "msao_blurupsampleCS_premin.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MSAO_BLURUPSAMPLE_PREMIN_BLENDOUT], "msao_blurupsampleCS_premin_blendout.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_RAYTRACE], "ssr_raytraceCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_RESOLVE], "ssr_resolveCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_TEMPORAL], "ssr_temporalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SSR_MEDIAN], "ssr_medianCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_LIGHTSHAFTS], "lightShaftsCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_HORIZONTAL], "depthoffield_tileMaxCOC_horizontalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_TILEMAXCOC_VERTICAL], "depthoffield_tileMaxCOC_verticalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_NEIGHBORHOODMAXCOC], "depthoffield_neighborhoodMaxCOCCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_KICKJOBS], "depthoffield_kickjobsCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS], "depthoffield_prepassCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_PREPASS_EARLYEXIT], "depthoffield_prepassCS_earlyexit.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN], "depthoffield_mainCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_EARLYEXIT], "depthoffield_mainCS_earlyexit.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_MAIN_CHEAP], "depthoffield_mainCS_cheap.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_POSTFILTER], "depthoffield_postfilterCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DEPTHOFFIELD_UPSAMPLE], "depthoffield_upsampleCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_HORIZONTAL], "motionblur_tileMaxVelocity_horizontalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_TILEMAXVELOCITY_VERTICAL], "motionblur_tileMaxVelocity_verticalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_NEIGHBORHOODMAXVELOCITY], "motionblur_neighborhoodMaxVelocityCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_KICKJOBS], "motionblur_kickjobsCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR], "motionblurCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_EARLYEXIT], "motionblurCS_earlyexit.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_MOTIONBLUR_CHEAP], "motionblurCS_cheap.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_BLOOMSEPARATE], "bloomseparateCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_SHAPENOISE], "volumetricCloud_shapenoiseCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_DETAILNOISE], "volumetricCloud_detailnoiseCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_CURLNOISE], "volumetricCloud_curlnoiseCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_WEATHERMAP], "volumetricCloud_weathermapCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_RENDER], "volumetricCloud_renderCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_REPROJECT], "volumetricCloud_reprojectCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_VOLUMETRICCLOUDS_TEMPORAL], "volumetricCloud_temporalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FXAA], "fxaaCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_TEMPORALAA], "temporalaaCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SHARPEN], "sharpenCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_TONEMAP], "tonemapCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FSR_UPSCALING], "fsr_upscalingCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_FSR_SHARPEN], "fsr_sharpenCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_CHROMATIC_ABERRATION], "chromatic_aberrationCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT1], "upsample_bilateral_float1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM1], "upsample_bilateral_unorm1CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_FLOAT4], "upsample_bilateral_float4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UNORM4], "upsample_bilateral_unorm4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL_UINT4], "upsample_bilateral_uint4CS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_DOWNSAMPLE4X], "downsample4xCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_NORMALSFROMDEPTH], "normalsfromdepthCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_SCREENSPACESHADOW], "screenspaceshadowCS.cso"); }); if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW], "rtshadowCS.cso", ShaderModel::SM_6_5); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TILECLASSIFICATION], "rtshadow_denoise_tileclassificationCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_FILTER], "rtshadow_denoise_filterCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TEMPORAL], "rtshadow_denoise_temporalCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW], "rtshadowCS.cso", ShaderModel::SM_6_5); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TILECLASSIFICATION], "rtshadow_denoise_tileclassificationCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_FILTER], "rtshadow_denoise_filterCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTSHADOW_DENOISE_TEMPORAL], "rtshadow_denoise_temporalCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO], "rtaoCS.cso", ShaderModel::SM_6_5); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO_DENOISE_TILECLASSIFICATION], "rtao_denoise_tileclassificationCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO_DENOISE_FILTER], "rtao_denoise_filterCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO], "rtaoCS.cso", ShaderModel::SM_6_5); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO_DENOISE_TILECLASSIFICATION], "rtao_denoise_tileclassificationCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_POSTPROCESS_RTAO_DENOISE_FILTER], "rtao_denoise_filterCS.cso"); }); } - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_COVERAGE], "surfel_coverageCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_INDIRECTPREPARE], "surfel_indirectprepareCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_UPDATE], "surfel_updateCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_GRIDRESET], "surfel_gridresetCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_GRIDOFFSETS], "surfel_gridoffsetsCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_BINNING], "surfel_binningCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_COVERAGE], "surfel_coverageCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_INDIRECTPREPARE], "surfel_indirectprepareCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_UPDATE], "surfel_updateCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_GRIDRESET], "surfel_gridresetCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_GRIDOFFSETS], "surfel_gridoffsetsCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_BINNING], "surfel_binningCS.cso"); }); if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_RAYTRACE], "surfel_raytraceCS_rtapi.cso", ShaderModel::SM_6_5); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_RAYTRACE], "surfel_raytraceCS_rtapi.cso", ShaderModel::SM_6_5); }); } else { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_RAYTRACE], "surfel_raytraceCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_SURFEL_RAYTRACE], "surfel_raytraceCS.cso"); }); } - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VISIBILITY_RESOLVE], "visibility_resolveCS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VISIBILITY_RESOLVE_MSAA], "visibility_resolveCS_MSAA.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VISIBILITY_RESOLVE], "visibility_resolveCS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::CS, shaders[CSTYPE_VISIBILITY_RESOLVE_MSAA], "visibility_resolveCS_MSAA.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT], "objectHS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_PREPASS], "objectHS_prepass.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_PREPASS_ALPHATEST], "objectHS_prepass_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_SIMPLE], "objectHS_simple.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT], "objectHS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_PREPASS], "objectHS_prepass.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_PREPASS_ALPHATEST], "objectHS_prepass_alphatest.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::HS, shaders[HSTYPE_OBJECT_SIMPLE], "objectHS_simple.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT], "objectDS.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_PREPASS], "objectDS_prepass.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_PREPASS_ALPHATEST], "objectDS_prepass_alphatest.cso"); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_SIMPLE], "objectDS_simple.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT], "objectDS.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_PREPASS], "objectDS_prepass.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_PREPASS_ALPHATEST], "objectDS_prepass_alphatest.cso"); }); + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { LoadShader(ShaderStage::DS, shaders[DSTYPE_OBJECT_SIMPLE], "objectDS_simple.cso"); }); - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); // default objectshaders: - wiJobSystem::Dispatch(ctx, MaterialComponent::SHADERTYPE_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, MaterialComponent::SHADERTYPE_COUNT, 1, [](wi::jobsystem::JobArgs args) { MaterialComponent::SHADERTYPE shaderType = (MaterialComponent::SHADERTYPE)args.jobIndex; for (int renderPass = 0; renderPass < RENDERPASS_COUNT; ++renderPass) @@ -1151,7 +1199,7 @@ void LoadShaders() } }); - wiJobSystem::Dispatch(ctx, RENDERPASS_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, RENDERPASS_COUNT, 1, [](wi::jobsystem::JobArgs args) { SHADERTYPE realVS = GetVSTYPE((RENDERPASS) args.jobIndex, false, false, false); @@ -1197,7 +1245,7 @@ void LoadShaders() customShaders.clear(); // Hologram sample shader will be registered as custom shader: - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { SHADERTYPE realVS = GetVSTYPE(RENDERPASS_MAIN, false, false, true); PipelineStateDesc desc; @@ -1220,7 +1268,7 @@ void LoadShaders() }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_OBJECT_SIMPLE]; desc.ps = &shaders[PSTYPE_OBJECT_SIMPLE]; @@ -1236,7 +1284,7 @@ void LoadShaders() desc.ds = &shaders[DSTYPE_OBJECT_SIMPLE]; device->CreatePipelineState(&desc, &PSO_object_wire_tessellation); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_CUBE]; desc.rs = &rasterizers[RSTYPE_OCCLUDEE]; @@ -1246,7 +1294,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_occlusionquery); }); - wiJobSystem::Dispatch(ctx, RENDERPASS_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, RENDERPASS_COUNT, 1, [](wi::jobsystem::JobArgs args) { const bool impostorRequest = args.jobIndex != RENDERPASS_VOXELIZE && args.jobIndex != RENDERPASS_SHADOW && @@ -1282,7 +1330,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_impostor[args.jobIndex]); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_IMPOSTOR]; desc.ps = &shaders[PSTYPE_IMPOSTOR_WIRE]; @@ -1293,7 +1341,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_impostor_wire); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_OBJECT_COMMON]; desc.rs = &rasterizers[RSTYPE_DOUBLESIDED]; @@ -1310,7 +1358,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_captureimpostor_surface); }); - wiJobSystem::Dispatch(ctx, LightComponent::LIGHTTYPE_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, LightComponent::LIGHTTYPE_COUNT, 1, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; // deferred lights: @@ -1371,7 +1419,7 @@ void LoadShaders() }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.il = &inputLayouts[ILTYPE_RENDERLIGHTMAP]; desc.vs = &shaders[VSTYPE_RENDERLIGHTMAP]; @@ -1382,7 +1430,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_renderlightmap); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_SCREEN]; desc.ps = &shaders[PSTYPE_DOWNSAMPLEDEPTHBUFFER]; @@ -1392,7 +1440,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_downsampledepthbuffer); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_SCREEN]; desc.ps = &shaders[PSTYPE_POSTPROCESS_UPSAMPLE_BILATERAL]; @@ -1402,7 +1450,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_upsample_bilateral); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_SCREEN]; desc.ps = &shaders[PSTYPE_POSTPROCESS_OUTLINE]; @@ -1412,7 +1460,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_outline); }); - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.vs = &shaders[VSTYPE_LENSFLARE]; desc.ps = &shaders[PSTYPE_LENSFLARE]; @@ -1423,7 +1471,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_lensflare); }); - wiJobSystem::Dispatch(ctx, SKYRENDERING_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, SKYRENDERING_COUNT, 1, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; desc.rs = &rasterizers[RSTYPE_SKY]; desc.dss = &depthStencils[DSSTYPE_DEPTHREAD]; @@ -1467,7 +1515,7 @@ void LoadShaders() device->CreatePipelineState(&desc, &PSO_sky[args.jobIndex]); }); - wiJobSystem::Dispatch(ctx, DEBUGRENDERING_COUNT, 1, [](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, DEBUGRENDERING_COUNT, 1, [](wi::jobsystem::JobArgs args) { PipelineStateDesc desc; switch (args.jobIndex) @@ -1582,7 +1630,7 @@ void LoadShaders() if(device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { - wiJobSystem::Execute(ctx, [](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [](wi::jobsystem::JobArgs args) { bool success = LoadShader(ShaderStage::LIB, shaders[RTTYPE_RTREFLECTION], "rtreflectionLIB.cso"); assert(success); @@ -1633,7 +1681,7 @@ void LoadShaders() }); }; - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); } void LoadBuffers() @@ -1954,35 +2002,6 @@ void SetUpStates() bd.alpha_to_coverage_enable = false; blendStates[BSTYPE_COLORWRITEDISABLE] = bd; - - bd.render_target[0].src_blend = Blend::INV_SRC_COLOR; - bd.render_target[0].dest_blend = Blend::INV_DEST_COLOR; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ONE; - bd.render_target[0].dest_blend_alpha = Blend::ONE; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].blend_enable = true; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_ALL; - bd.alpha_to_coverage_enable = false; - bd.independent_blend_enable = false; - blendStates[BSTYPE_INVERSE] = bd; - - - bd.render_target[0].src_blend = Blend::SRC_ALPHA; - bd.render_target[0].dest_blend = Blend::INV_SRC_ALPHA; - bd.render_target[0].blend_op = BlendOp::ADD; - bd.render_target[0].src_blend_alpha = Blend::ONE; - bd.render_target[0].dest_blend_alpha = Blend::ONE; - bd.render_target[0].blend_op_alpha = BlendOp::ADD; - bd.render_target[0].blend_enable = true; - bd.render_target[0].render_target_write_mask = ColorWrite::ENABLE_RED | ColorWrite::ENABLE_GREEN | ColorWrite::ENABLE_BLUE; - bd.render_target[1] = bd.render_target[0]; - bd.render_target[1].render_target_write_mask = ColorWrite::ENABLE_RED | ColorWrite::ENABLE_GREEN; - bd.alpha_to_coverage_enable = false; - bd.independent_blend_enable = true; - blendStates[BSTYPE_DECAL] = bd; - - bd.render_target[0].src_blend = Blend::DEST_COLOR; bd.render_target[0].dest_blend = Blend::ZERO; bd.render_target[0].blend_op = BlendOp::ADD; @@ -2033,7 +2052,7 @@ void ReloadShaders() { device->ClearPipelineStateCache(); - wiEvent::FireEvent(SYSTEM_EVENT_RELOAD_SHADERS, 0); + wi::eventhandler::FireEvent(wi::eventhandler::EVENT_RELOAD_SHADERS, 0); } void InitializeCommonSamplers() @@ -2165,18 +2184,18 @@ void InitializeCommonSamplers() } void Initialize() { - wiTimer timer; + wi::Timer timer; SetUpStates(); LoadBuffers(); - static wiEvent::Handle handle2 = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); + static wi::eventhandler::Handle handle2 = wi::eventhandler::Subscribe(wi::eventhandler::EVENT_RELOAD_SHADERS, [](uint64_t userdata) { LoadShaders(); }); LoadShaders(); SetShadowProps2D(SHADOWRES_2D, SHADOWCOUNT_2D); SetShadowPropsCube(SHADOWRES_CUBE, SHADOWCOUNT_CUBE); - wiBackLog::post("wiRenderer Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::renderer Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } void ClearWorld(Scene& scene) { @@ -2193,7 +2212,7 @@ static const uint32_t CASCADE_COUNT = 3; struct SHCAM { XMMATRIX view_projection; - Frustum frustum; // This frustum can be used for intersection test with wiIntersect primitives + Frustum frustum; // This frustum can be used for intersection test with wiPrimitive primitives BoundingFrustum boundingfrustum; // This boundingfrustum can be used for frustum vs frustum intersection test SHCAM() = default; @@ -2297,7 +2316,7 @@ inline void CreateDirLightShadowCams(const LightComponent& light, CameraComponen // Snap cascade to texel grid: const XMVECTOR extent = XMVectorSubtract(vMax, vMin); - const XMVECTOR texelSize = extent / float(wiRenderer::GetShadowRes2D()); + const XMVECTOR texelSize = extent / float(GetShadowRes2D()); vMin = XMVectorFloor(vMin / texelSize) * texelSize; vMax = XMVectorFloor(vMax / texelSize) * texelSize; center = (vMin + vMax) * 0.5f; @@ -2668,7 +2687,7 @@ void RenderImpostors( } const XMFLOAT3 center = aabb.getCenter(); - float distance = wiMath::Distance(vis.camera->Eye, center); + float distance = wi::math::Distance(vis.camera->Eye, center); if (distance < impostor.swapInDistance - impostor.fadeThresholdRadius) { @@ -2706,7 +2725,7 @@ void ProcessDeferredMipGenRequests(CommandList cmd) { MIPGEN_OPTIONS mipopt; mipopt.preserve_coverage = it.second; - GenerateMipChain(it.first->texture, MIPGENFILTER_LINEAR, cmd, mipopt); + GenerateMipChain(it.first, MIPGENFILTER_LINEAR, cmd, mipopt); } deferredMIPGens.clear(); deferredMIPGenLock.unlock(); @@ -2715,9 +2734,9 @@ void ProcessDeferredMipGenRequests(CommandList cmd) void UpdateVisibility(Visibility& vis) { // Perform parallel frustum culling and obtain closest reflector: - wiJobSystem::context ctx; - wiJobSystem::context ctx_lights; - auto range = wiProfiler::BeginRangeCPU("Frustum Culling"); + wi::jobsystem::context ctx; + wi::jobsystem::context ctx_lights; + auto range = wi::profiler::BeginRangeCPU("Frustum Culling"); assert(vis.scene != nullptr); // User must provide a scene! assert(vis.camera != nullptr); // User must provide a camera! @@ -2746,7 +2765,7 @@ void UpdateVisibility(Visibility& vis) { // Cull lights: vis.visibleLights.resize(vis.scene->aabb_lights.GetCount()); - wiJobSystem::Dispatch(ctx_lights, (uint32_t)vis.scene->aabb_lights.GetCount(), groupSize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx_lights, (uint32_t)vis.scene->aabb_lights.GetCount(), groupSize, [&](wi::jobsystem::JobArgs args) { // Setup stream compaction: uint32_t& group_count = *(uint32_t*)args.sharedmemory; @@ -2768,7 +2787,7 @@ void UpdateVisibility(Visibility& vis) float distance = 0; if (light.type != LightComponent::DIRECTIONAL) { - distance = wiMath::DistanceEstimated(light.position, vis.camera->Eye); + distance = wi::math::DistanceEstimated(light.position, vis.camera->Eye); } group_list[group_count].distance = uint16_t(distance * 10); group_count++; @@ -2806,7 +2825,7 @@ void UpdateVisibility(Visibility& vis) { // Cull objects: vis.visibleObjects.resize(vis.scene->aabb_objects.GetCount()); - wiJobSystem::Dispatch(ctx, (uint32_t)vis.scene->aabb_objects.GetCount(), groupSize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)vis.scene->aabb_objects.GetCount(), groupSize, [&](wi::jobsystem::JobArgs args) { // Setup stream compaction: uint32_t& group_count = *(uint32_t*)args.sharedmemory; @@ -2829,7 +2848,7 @@ void UpdateVisibility(Visibility& vis) { if (object.IsRequestPlanarReflection()) { - float dist = wiMath::DistanceEstimated(vis.camera->Eye, object.center); + float dist = wi::math::DistanceEstimated(vis.camera->Eye, object.center); vis.locker.lock(); if (dist < vis.closestRefPlane) { @@ -2880,7 +2899,7 @@ void UpdateVisibility(Visibility& vis) if (vis.flags & Visibility::ALLOW_DECALS) { vis.visibleDecals.resize(vis.scene->aabb_decals.GetCount()); - wiJobSystem::Dispatch(ctx, (uint32_t)vis.scene->aabb_decals.GetCount(), groupSize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)vis.scene->aabb_decals.GetCount(), groupSize, [&](wi::jobsystem::JobArgs args) { // Setup stream compaction: uint32_t& group_count = *(uint32_t*)args.sharedmemory; @@ -2913,7 +2932,7 @@ void UpdateVisibility(Visibility& vis) if (vis.flags & Visibility::ALLOW_ENVPROBES) { - wiJobSystem::Execute(ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { // Cull probes: for (size_t i = 0; i < vis.scene->aabb_probes.GetCount(); ++i) { @@ -2929,11 +2948,11 @@ void UpdateVisibility(Visibility& vis) if (vis.flags & Visibility::ALLOW_EMITTERS) { - wiJobSystem::Execute(ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { // Cull emitters: for (size_t i = 0; i < vis.scene->emitters.GetCount(); ++i) { - const wiEmittedParticle& emitter = vis.scene->emitters[i]; + const wi::EmittedParticleSystem& emitter = vis.scene->emitters[i]; if (!(emitter.layerMask & vis.layerMask)) { continue; @@ -2945,11 +2964,11 @@ void UpdateVisibility(Visibility& vis) if (vis.flags & Visibility::ALLOW_HAIRS) { - wiJobSystem::Execute(ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { // Cull hairs: for (size_t i = 0; i < vis.scene->hairs.GetCount(); ++i) { - const wiHairParticle& hair = vis.scene->hairs[i]; + const wi::HairParticleSystem& hair = vis.scene->hairs[i]; if (!(hair.layerMask & vis.layerMask)) { continue; @@ -2965,13 +2984,13 @@ void UpdateVisibility(Visibility& vis) if (vis.flags & Visibility::ALLOW_LIGHTS) { - wiJobSystem::Wait(ctx_lights); + wi::jobsystem::Wait(ctx_lights); vis.visibleLights.resize((size_t)vis.light_counter.load()); // Sort lights based on distance so that closer lights will receive shadow map priority: std::sort(vis.visibleLights.begin(), vis.visibleLights.end()); } - wiJobSystem::Wait(ctx); + wi::jobsystem::Wait(ctx); // finalize stream compaction: vis.visibleObjects.resize((size_t)vis.object_counter.load()); @@ -2985,7 +3004,7 @@ void UpdateVisibility(Visibility& vis) XMStoreFloat4(&vis.reflectionPlane, _refPlane); } - wiProfiler::EndRange(range); // Frustum Culling + wi::profiler::EndRange(range); // Frustum Culling } void UpdatePerFrameData( Scene& scene, @@ -3005,7 +3024,7 @@ void UpdatePerFrameData( // We don't update it if the scene is empty, this even makes it easier to debug const float f = 0.05f / voxelSceneData.voxelsize; XMFLOAT3 center = XMFLOAT3(std::floor(vis.camera->Eye.x * f) / f, std::floor(vis.camera->Eye.y * f) / f, std::floor(vis.camera->Eye.z * f) / f); - if (wiMath::DistanceSquared(center, voxelSceneData.center) > 0) + if (wi::math::DistanceSquared(center, voxelSceneData.center) > 0) { voxelSceneData.centerChangedThisFrame = true; } @@ -3134,9 +3153,9 @@ void UpdatePerFrameData( { frameCB.options |= OPTION_BIT_FORCE_DIFFUSE_LIGHTING; } - if (vis.scene->weather.skyMap != nullptr) + if (vis.scene->weather.skyMap.IsValid()) { - bool hdr = !IsFormatUnorm(vis.scene->weather.skyMap->texture.desc.format); + bool hdr = !IsFormatUnorm(vis.scene->weather.skyMap.GetTexture().desc.format); if (hdr) { frameCB.options |= OPTION_BIT_STATIC_SKY_HDR; @@ -3146,8 +3165,8 @@ void UpdatePerFrameData( frameCB.scene = vis.scene->shaderscene; frameCB.sampler_objectshader_index = device->GetDescriptorIndex(&samplers[SAMPLER_OBJECTSHADER]); - frameCB.texture_random64x64_index = device->GetDescriptorIndex(wiTextureHelper::getRandom64x64(), SubresourceType::SRV); - frameCB.texture_bluenoise_index = device->GetDescriptorIndex(wiTextureHelper::getBlueNoise(), SubresourceType::SRV); + frameCB.texture_random64x64_index = device->GetDescriptorIndex(wi::texturehelper::getRandom64x64(), SubresourceType::SRV); + frameCB.texture_bluenoise_index = device->GetDescriptorIndex(wi::texturehelper::getBlueNoise(), SubresourceType::SRV); frameCB.texture_sheenlut_index = device->GetDescriptorIndex(&textures[TEXTYPE_2D_SHEENLUT], SubresourceType::SRV); frameCB.texture_skyviewlut_index = device->GetDescriptorIndex(&textures[TEXTYPE_2D_SKYATMOSPHERE_SKYVIEWLUT], SubresourceType::SRV); frameCB.texture_transmittancelut_index = device->GetDescriptorIndex(&textures[TEXTYPE_2D_SKYATMOSPHERE_TRANSMITTANCELUT], SubresourceType::SRV); @@ -3232,8 +3251,8 @@ void UpdateRenderData( { device->EventBegin("UpdateRenderData", cmd); - auto prof_updatebuffer_cpu = wiProfiler::BeginRangeCPU("Update Buffers (CPU)"); - auto prof_updatebuffer_gpu = wiProfiler::BeginRangeGPU("Update Buffers (GPU)", cmd); + auto prof_updatebuffer_cpu = wi::profiler::BeginRangeCPU("Update Buffers (CPU)"); + auto prof_updatebuffer_gpu = wi::profiler::BeginRangeGPU("Update Buffers (GPU)", cmd); device->UpdateBuffer(&constantBuffers[CBTYPE_FRAME], &frameCB, cmd); barrier_stack[cmd].push_back(GPUBarrier::Buffer(&constantBuffers[CBTYPE_FRAME], ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER)); @@ -3319,21 +3338,21 @@ void UpdateRenderData( entityArray[entityCounter].SetType(ENTITY_TYPE_DECAL); entityArray[entityCounter].position = decal.position; entityArray[entityCounter].SetRange(decal.range); - entityArray[entityCounter].color = wiMath::CompressColor(XMFLOAT4(decal.color.x, decal.color.y, decal.color.z, decal.GetOpacity())); + entityArray[entityCounter].color = wi::math::CompressColor(XMFLOAT4(decal.color.x, decal.color.y, decal.color.z, decal.GetOpacity())); entityArray[entityCounter].SetEnergy(decal.emissive); entityArray[entityCounter].SetIndices(matrixCounter, 0); matrixArray[matrixCounter] = XMMatrixInverse(nullptr, XMLoadFloat4x4(&decal.world)); int texture = -1; - if (decal.texture != nullptr) + if (decal.texture.IsValid()) { - texture = device->GetDescriptorIndex(&decal.texture->texture, SubresourceType::SRV); + texture = device->GetDescriptorIndex(&decal.texture.GetTexture(), SubresourceType::SRV); } int normal = -1; - if (decal.normal != nullptr) + if (decal.normal.IsValid()) { - normal = device->GetDescriptorIndex(&decal.normal->texture, SubresourceType::SRV); + normal = device->GetDescriptorIndex(&decal.normal.GetTexture(), SubresourceType::SRV); } matrixArray[matrixCounter].r[0] = XMVectorSetW(matrixArray[matrixCounter].r[0], *(float*)&texture); matrixArray[matrixCounter].r[1] = XMVectorSetW(matrixArray[matrixCounter].r[1], *(float*)&normal); @@ -3411,7 +3430,7 @@ void UpdateRenderData( entityArray[entityCounter].SetType(light.GetType()); entityArray[entityCounter].position = light.position; entityArray[entityCounter].SetRange(light.GetRange()); - entityArray[entityCounter].color = wiMath::CompressColor(light.color); + entityArray[entityCounter].color = wi::math::CompressColor(light.color); entityArray[entityCounter].SetEnergy(light.energy); // mark as no shadow by default: @@ -3582,12 +3601,12 @@ void UpdateRenderData( // Flush buffer updates: barrier_stack_flush(cmd); - wiProfiler::EndRange(prof_updatebuffer_cpu); - wiProfiler::EndRange(prof_updatebuffer_gpu); + wi::profiler::EndRange(prof_updatebuffer_cpu); + wi::profiler::EndRange(prof_updatebuffer_gpu); BindCommonResources(cmd); - auto range = wiProfiler::BeginRangeGPU("Skinning", cmd); + auto range = wi::profiler::BeginRangeGPU("Skinning", cmd); device->EventBegin("Skinning", cmd); { for (size_t i = 0; i < vis.scene->meshes.GetCount(); ++i) @@ -3658,16 +3677,16 @@ void UpdateRenderData( } device->EventEnd(cmd); - wiProfiler::EndRange(range); // skinning + wi::profiler::EndRange(range); // skinning // Hair particle systems GPU simulation: // (This must be non-async too, as prepass will render hairs!) if (!vis.visibleHairs.empty() && frameCB.delta_time > 0) { - range = wiProfiler::BeginRangeGPU("HairParticles - Simulate", cmd); + range = wi::profiler::BeginRangeGPU("HairParticles - Simulate", cmd); for (uint32_t hairIndex : vis.visibleHairs) { - const wiHairParticle& hair = vis.scene->hairs[hairIndex]; + const wi::HairParticleSystem& hair = vis.scene->hairs[hairIndex]; const MeshComponent* mesh = vis.scene->meshes.GetComponent(hair.meshID); if (mesh != nullptr) @@ -3679,7 +3698,7 @@ void UpdateRenderData( hair.UpdateGPU((uint32_t)vis.scene->objects.GetCount() + hairIndex, (uint32_t)materialIndex, *mesh, material, cmd); } } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } if (vis.scene->weather.IsRealisticSky()) @@ -3839,10 +3858,10 @@ void UpdateRenderDataAsync( // GPU Particle systems simulation/sorting/culling: if (!vis.visibleEmitters.empty() && frameCB.delta_time > 0) { - auto range = wiProfiler::BeginRangeGPU("EmittedParticles - Simulate", cmd); + auto range = wi::profiler::BeginRangeGPU("EmittedParticles - Simulate", cmd); for (uint32_t emitterIndex : vis.visibleEmitters) { - const wiEmittedParticle& emitter = vis.scene->emitters[emitterIndex]; + const wi::EmittedParticleSystem& emitter = vis.scene->emitters[emitterIndex]; Entity entity = vis.scene->emitters.GetEntity(emitterIndex); const TransformComponent& transform = *vis.scene->transforms.GetComponent(entity); const MaterialComponent& material = *vis.scene->materials.GetComponent(entity); @@ -3852,15 +3871,15 @@ void UpdateRenderDataAsync( emitter.UpdateGPU(instanceIndex, materialIndex, transform, mesh, cmd); } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } // Compute water simulation: if (vis.scene->weather.IsOceanEnabled()) { - auto range = wiProfiler::BeginRangeGPU("Ocean - Simulate", cmd); + auto range = wi::profiler::BeginRangeGPU("Ocean - Simulate", cmd); vis.scene->ocean.UpdateDisplacementMap(vis.scene->weather.oceanParameters, cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } device->EventEnd(cmd); @@ -3884,8 +3903,8 @@ void UpdateRaytracingAccelerationStructures(const Scene& scene, CommandList cmd) // BLAS: { - auto rangeCPU = wiProfiler::BeginRangeCPU("BLAS Update (CPU)"); - auto range = wiProfiler::BeginRangeGPU("BLAS Update (GPU)", cmd); + auto rangeCPU = wi::profiler::BeginRangeCPU("BLAS Update (CPU)"); + auto range = wi::profiler::BeginRangeGPU("BLAS Update (GPU)", cmd); device->EventBegin("BLAS Update", cmd); for (size_t i = 0; i < scene.meshes.GetCount(); ++i) @@ -3911,7 +3930,7 @@ void UpdateRaytracingAccelerationStructures(const Scene& scene, CommandList cmd) for (size_t i = 0; i < scene.hairs.GetCount(); ++i) { - const wiHairParticle& hair = scene.hairs[i]; + const wi::HairParticleSystem& hair = scene.hairs[i]; if (hair.meshID != INVALID_ENTITY && hair.BLAS.IsValid()) { @@ -3921,7 +3940,7 @@ void UpdateRaytracingAccelerationStructures(const Scene& scene, CommandList cmd) for (size_t i = 0; i < scene.emitters.GetCount(); ++i) { - const wiEmittedParticle& emitter = scene.emitters[i]; + const wi::EmittedParticleSystem& emitter = scene.emitters[i]; if (emitter.BLAS.IsValid()) { @@ -3938,14 +3957,14 @@ void UpdateRaytracingAccelerationStructures(const Scene& scene, CommandList cmd) } device->EventEnd(cmd); - wiProfiler::EndRange(range); - wiProfiler::EndRange(rangeCPU); + wi::profiler::EndRange(range); + wi::profiler::EndRange(rangeCPU); } // TLAS: { - auto rangeCPU = wiProfiler::BeginRangeCPU("TLAS Update (CPU)"); - auto range = wiProfiler::BeginRangeGPU("TLAS Update (GPU)", cmd); + auto rangeCPU = wi::profiler::BeginRangeCPU("TLAS Update (CPU)"); + auto range = wi::profiler::BeginRangeGPU("TLAS Update (GPU)", cmd); device->EventBegin("TLAS Update", cmd); device->BuildRaytracingAccelerationStructure(&scene.TLAS, cmd, nullptr); @@ -3958,8 +3977,8 @@ void UpdateRaytracingAccelerationStructures(const Scene& scene, CommandList cmd) } device->EventEnd(cmd); - wiProfiler::EndRange(range); - wiProfiler::EndRange(rangeCPU); + wi::profiler::EndRange(range); + wi::profiler::EndRange(rangeCPU); } } else @@ -4004,7 +4023,7 @@ void OcclusionCulling_Render(const CameraComponent& camera, const Visibility& vi return; } - auto range = wiProfiler::BeginRangeGPU("Occlusion Culling Render", cmd); + auto range = wi::profiler::BeginRangeGPU("Occlusion Culling Render", cmd); device->BindPipelineState(&PSO_occlusionquery, cmd); @@ -4066,7 +4085,7 @@ void OcclusionCulling_Render(const CameraComponent& camera, const Visibility& vi device->EventEnd(cmd); } - wiProfiler::EndRange(range); // Occlusion Culling Render + wi::profiler::EndRange(range); // Occlusion Culling Render } void OcclusionCulling_Resolve(const Visibility& vis, CommandList cmd) { @@ -4151,8 +4170,8 @@ void DrawSoftParticles( return; } auto range = distortion ? - wiProfiler::BeginRangeGPU("EmittedParticles - Render (Distortion)", cmd) : - wiProfiler::BeginRangeGPU("EmittedParticles - Render", cmd); + wi::profiler::BeginRangeGPU("EmittedParticles - Render (Distortion)", cmd) : + wi::profiler::BeginRangeGPU("EmittedParticles - Render", cmd); // Sort emitters based on distance: assert(emitterCount < 0x0000FFFF); // watch out for sorting hash truncation! @@ -4160,8 +4179,8 @@ void DrawSoftParticles( for (size_t i = 0; i < emitterCount; ++i) { const uint32_t emitterIndex = vis.visibleEmitters[i]; - const wiEmittedParticle& emitter = vis.scene->emitters[emitterIndex]; - float distance = wiMath::DistanceEstimated(emitter.center, vis.camera->Eye); + const wi::EmittedParticleSystem& emitter = vis.scene->emitters[emitterIndex]; + float distance = wi::math::DistanceEstimated(emitter.center, vis.camera->Eye); emitterSortingHashes[i] = 0; emitterSortingHashes[i] |= (uint32_t)i & 0x0000FFFF; emitterSortingHashes[i] |= ((uint32_t)(distance * 10) & 0x0000FFFF) << 16; @@ -4171,15 +4190,15 @@ void DrawSoftParticles( for (size_t i = 0; i < emitterCount; ++i) { const uint32_t emitterIndex = vis.visibleEmitters[emitterSortingHashes[i] & 0x0000FFFF]; - const wiEmittedParticle& emitter = vis.scene->emitters[emitterIndex]; + const wi::EmittedParticleSystem& emitter = vis.scene->emitters[emitterIndex]; const Entity entity = vis.scene->emitters.GetEntity(emitterIndex); const MaterialComponent& material = *vis.scene->materials.GetComponent(entity); - if (distortion && emitter.shaderType == wiEmittedParticle::SOFT_DISTORTION) + if (distortion && emitter.shaderType == wi::EmittedParticleSystem::SOFT_DISTORTION) { emitter.Draw(material, cmd); } - else if (!distortion && (emitter.shaderType == wiEmittedParticle::SOFT || emitter.shaderType == wiEmittedParticle::SOFT_LIGHTING || emitter.shaderType == wiEmittedParticle::SIMPLE || IsWireRender())) + else if (!distortion && (emitter.shaderType == wi::EmittedParticleSystem::SOFT || emitter.shaderType == wi::EmittedParticleSystem::SOFT_LIGHTING || emitter.shaderType == wi::EmittedParticleSystem::SIMPLE || IsWireRender())) { emitter.Draw(material, cmd); } @@ -4189,7 +4208,7 @@ void DrawSoftParticles( device->BindShadingRate(ShadingRate::RATE_1X1, cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } void DrawLightVisualizers( const Visibility& vis, @@ -4368,7 +4387,7 @@ void DrawLensFlares( // Directional light can use occlusion texture (eg. clouds): if (texture_directional_occlusion == nullptr) { - device->BindResource(wiTextureHelper::getWhite(), 0, cmd); + device->BindResource(wi::texturehelper::getWhite(), 0, cmd); } else { @@ -4381,7 +4400,7 @@ void DrawLensFlares( POS = XMLoadFloat3(&light.position); // not using occlusion texture - device->BindResource(wiTextureHelper::getWhite(), 0, cmd); + device->BindResource(wi::texturehelper::getWhite(), 0, cmd); } if (XMVectorGetX(XMVector3Dot(XMVectorSubtract(POS, vis.camera->GetEye()), vis.camera->GetAt())) > 0) // check if the camera is facing towards the flare or not @@ -4397,7 +4416,7 @@ void DrawLensFlares( uint32_t i = 0; for (auto& x : light.lensFlareRimTextures) { - if (x != nullptr) + if (x.IsValid()) { // pre-baked offsets // These values work well for me, but should be tweakable @@ -4406,12 +4425,12 @@ void DrawLensFlares( break; cb.xLensFlareOffset = mods[i]; - cb.xLensFlareSize.x = (float)x->texture.desc.width; - cb.xLensFlareSize.y = (float)x->texture.desc.height; + cb.xLensFlareSize.x = (float)x.GetTexture().desc.width; + cb.xLensFlareSize.y = (float)x.GetTexture().desc.height; device->PushConstants(&cb, sizeof(cb), cmd); - device->BindResource(&x->texture, 1, cmd); + device->BindResource(&x.GetTexture(), 1, cmd); device->Draw(4, 0, cmd); i++; } @@ -4589,7 +4608,7 @@ void DrawShadowmaps( if (!vis.visibleLights.empty()) { device->EventBegin("DrawShadowmaps", cmd); - auto range = wiProfiler::BeginRangeGPU("Shadow Rendering", cmd); + auto range = wi::profiler::BeginRangeGPU("Shadow Rendering", cmd); const bool predicationRequest = device->CheckCapability(GraphicsDeviceCapability::PREDICATION) && @@ -4773,7 +4792,7 @@ void DrawShadowmaps( uint32_t slice = shadowCounter_Cube; shadowCounter_Cube += 1; - SPHERE boundingsphere = SPHERE(light.position, light.GetRange()); + Sphere boundingsphere(light.position, light.GetRange()); RenderQueue renderQueue; bool transparentShadowsRequested = false; @@ -4863,7 +4882,7 @@ void DrawShadowmaps( } // terminate switch } - wiProfiler::EndRange(range); // Shadow Rendering + wi::profiler::EndRange(range); // Shadow Rendering device->EventEnd(cmd); } } @@ -4897,7 +4916,7 @@ void DrawScene( { for (uint32_t hairIndex : vis.visibleHairs) { - const wiHairParticle& hair = vis.scene->hairs[hairIndex]; + const wi::HairParticleSystem& hair = vis.scene->hairs[hairIndex]; Entity entity = vis.scene->hairs.GetEntity(hairIndex); const MaterialComponent& material = *vis.scene->materials.GetComponent(entity); @@ -4937,7 +4956,7 @@ void DrawScene( if (object.IsRenderable() && (object.GetRenderTypes() & renderTypeFlags)) { - const float distance = wiMath::Distance(vis.camera->Eye, object.center); + const float distance = wi::math::Distance(vis.camera->Eye, object.center); if (object.IsImpostorPlacement() && distance > object.impostorSwapDistance + object.impostorFadeThresholdRadius) { continue; @@ -4964,7 +4983,7 @@ void DrawScene( void DrawDebugWorld( const Scene& scene, const CameraComponent& camera, - const wiCanvas& canvas, + const wi::Canvas& canvas, CommandList cmd ) { @@ -5524,7 +5543,7 @@ void DrawDebugWorld( for (auto& x : renderableSpheres) { - const SPHERE& sphere = x.first; + const Sphere& sphere = x.first; XMStoreFloat4x4(&sb.g_xTransform, XMMatrixScaling(sphere.radius, sphere.radius, sphere.radius) * XMMatrixTranslation(sphere.center.x, sphere.center.y, sphere.center.z) * @@ -5568,7 +5587,7 @@ void DrawDebugWorld( int j = 0; for (auto& it : renderableCapsules) { - const CAPSULE& capsule = it.first; + const Capsule& capsule = it.first; const float radius = capsule.radius; XMVECTOR Base = XMLoadFloat3(&capsule.base); @@ -5655,7 +5674,7 @@ void DrawDebugWorld( if (probe.textureIndex < 0) { - device->BindResource(wiTextureHelper::getBlackCubeMap(), 0, cmd); + device->BindResource(wi::texturehelper::getBlackCubeMap(), 0, cmd); } else { @@ -5787,7 +5806,7 @@ void DrawDebugWorld( MiscCB sb; for (size_t i = 0; i < scene.emitters.GetCount(); ++i) { - const wiEmittedParticle& emitter = scene.emitters[i]; + const wi::EmittedParticleSystem& emitter = scene.emitters[i]; Entity entity = scene.emitters.GetEntity(i); const TransformComponent& transform = *scene.transforms.GetComponent(entity); const MeshComponent* mesh = scene.meshes.GetComponent(emitter.meshID); @@ -5991,7 +6010,7 @@ void DrawDebugWorld( void RenderAtmosphericScatteringTextures(CommandList cmd) { device->EventBegin("ComputeAtmosphericScatteringTextures", cmd); - auto range = wiProfiler::BeginRangeGPU("Atmospheric Scattering Textures", cmd); + auto range = wi::profiler::BeginRangeGPU("Atmospheric Scattering Textures", cmd); // Transmittance Lut pass: { @@ -6109,7 +6128,7 @@ void RenderAtmosphericScatteringTextures(CommandList cmd) RefreshAtmosphericScatteringTextures(cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } void RefreshAtmosphericScatteringTextures(CommandList cmd) { @@ -6160,7 +6179,7 @@ void DrawSky(const Scene& scene, CommandList cmd) { device->EventBegin("DrawSky", cmd); - if (scene.weather.skyMap != nullptr) + if (scene.weather.skyMap.IsValid()) { device->BindPipelineState(&PSO_sky[SKYRENDERING_STATIC], cmd); } @@ -6195,7 +6214,7 @@ void RefreshEnvProbes(const Visibility& vis, CommandList cmd) return; device->EventBegin("EnvironmentProbe Refresh", cmd); - auto range = wiProfiler::BeginRangeGPU("Environment Probe Refresh", cmd); + auto range = wi::profiler::BeginRangeGPU("Environment Probe Refresh", cmd); BindCommonResources(cmd); @@ -6243,7 +6262,7 @@ void RefreshEnvProbes(const Visibility& vis, CommandList cmd) // Scene will only be rendered if this is a real probe entity: if (probe_aabb.layerMask & vis.layerMask) { - SPHERE culler = SPHERE(probe.position, zFarP); + Sphere culler(probe.position, zFarP); RenderQueue renderQueue; for (size_t i = 0; i < vis.scene->aabb_objects.GetCount(); ++i) @@ -6272,10 +6291,10 @@ void RefreshEnvProbes(const Visibility& vis, CommandList cmd) // sky { - if (vis.scene->weather.skyMap != nullptr) + if (vis.scene->weather.skyMap.IsValid()) { device->BindPipelineState(&PSO_sky[SKYRENDERING_ENVMAPCAPTURE_STATIC], cmd); - device->BindResource(&vis.scene->weather.skyMap->texture, 0, cmd); + device->BindResource(&vis.scene->weather.skyMap.GetTexture(), 0, cmd); } else { @@ -6384,7 +6403,7 @@ void RefreshEnvProbes(const Visibility& vis, CommandList cmd) } } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); // EnvironmentProbe Refresh } @@ -6408,7 +6427,7 @@ void RefreshImpostors(const Scene& scene, CommandList cmd) const MeshComponent& mesh = *scene.meshes.GetComponent(entity); // impostor camera will fit around mesh bounding sphere: - const SPHERE boundingsphere = mesh.GetBoundingSphere(); + const Sphere boundingsphere = mesh.GetBoundingSphere(); device->BindIndexBuffer(&mesh.indexBuffer, mesh.GetIndexFormat(), 0, cmd); @@ -6494,7 +6513,7 @@ void VoxelRadiance(const Visibility& vis, CommandList cmd) } device->EventBegin("Voxel Radiance", cmd); - auto range = wiProfiler::BeginRangeGPU("Voxel Radiance", cmd); + auto range = wi::profiler::BeginRangeGPU("Voxel Radiance", cmd); static RenderPass renderpass_voxelize; @@ -6624,14 +6643,14 @@ void VoxelRadiance(const Visibility& vis, CommandList cmd) } } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void CreateTiledLightResources(TiledLightResources& res, XMUINT2 resolution) { - res.tileCount = wiRenderer::GetEntityCullingTileCount(resolution); + res.tileCount = GetEntityCullingTileCount(resolution); { GPUBufferDesc bd; @@ -6760,7 +6779,7 @@ void ResolveMSAADepthBuffer(const Texture& dst, const Texture& src, CommandList device->EventEnd(cmd); } -void DownsampleDepthBuffer(const wiGraphics::Texture& src, wiGraphics::CommandList cmd) +void DownsampleDepthBuffer(const Texture& src, CommandList cmd) { device->EventBegin("DownsampleDepthBuffer", cmd); @@ -7148,14 +7167,14 @@ void RayTraceScene( return; device->EventBegin("RayTraceScene", cmd); - auto range = wiProfiler::BeginRangeGPU("RayTraceScene", cmd); + auto range = wi::profiler::BeginRangeGPU("RayTraceScene", cmd); const TextureDesc& desc = output.GetDesc(); BindCommonResources(cmd); - const XMFLOAT4& halton = wiMath::GetHaltonSequence(accumulation_sample); + const XMFLOAT4& halton = wi::math::GetHaltonSequence(accumulation_sample); RaytracingCB cb; cb.xTracePixelOffset = XMFLOAT2(halton.x, halton.y); cb.xTraceAccumulationFactor = 1.0f / ((float)accumulation_sample + 1.0f); @@ -7205,7 +7224,7 @@ void RayTraceScene( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); // RayTraceScene } void RayTraceSceneBVH(const Scene& scene, CommandList cmd) @@ -7220,7 +7239,7 @@ void RefreshLightmaps(const Scene& scene, CommandList cmd) { if (scene.lightmap_refresh_needed.load()) { - auto range = wiProfiler::BeginRangeGPU("Lightmap Processing", cmd); + auto range = wi::profiler::BeginRangeGPU("Lightmap Processing", cmd); if (!scene.TLAS.IsValid() && !scene.BVH.IsValid()) return; @@ -7285,7 +7304,7 @@ void RefreshLightmaps(const Scene& scene, CommandList cmd) cb.xTraceResolution.y = desc.height; cb.xTraceResolution_rcp.x = 1.0f / cb.xTraceResolution.x; cb.xTraceResolution_rcp.y = 1.0f / cb.xTraceResolution.y; - XMFLOAT4 halton = wiMath::GetHaltonSequence(object.lightmapIterationCount); // for jittering the rasterization (good for eliminating atlas border artifacts) + XMFLOAT4 halton = wi::math::GetHaltonSequence(object.lightmapIterationCount); // for jittering the rasterization (good for eliminating atlas border artifacts) cb.xTracePixelOffset.x = (halton.x * 2 - 1) * cb.xTraceResolution_rcp.x; cb.xTracePixelOffset.y = (halton.y * 2 - 1) * cb.xTraceResolution_rcp.y; cb.xTracePixelOffset.x *= 1.4f; // boost the jitter by a bit @@ -7307,7 +7326,7 @@ void RefreshLightmaps(const Scene& scene, CommandList cmd) } scene.lightmap_refresh_needed.store(false); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); } } @@ -7369,6 +7388,7 @@ void BindCameraCB( cb.internal_resolution_rcp = float2(1.0f / cb.internal_resolution.x, 1.0f / cb.internal_resolution.y); cb.entity_culling_tilecount = GetEntityCullingTileCount(cb.internal_resolution); + cb.sample_count = camera.sample_count; cb.texture_depth_index = camera.texture_depth_index; cb.texture_lineardepth_index = camera.texture_lineardepth_index; @@ -7407,7 +7427,7 @@ void ComputeLuminance( ) { device->EventBegin("Compute Luminance", cmd); - auto range = wiProfiler::BeginRangeGPU("Luminance", cmd); + auto range = wi::profiler::BeginRangeGPU("Luminance", cmd); PostProcess postprocess; postprocess.resolution.x = sourceImage.desc.width / 2; @@ -7467,7 +7487,7 @@ void ComputeLuminance( device->Barrier(barriers, arraysize(barriers), cmd); } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } @@ -7507,7 +7527,7 @@ void ComputeBloom( ) { device->EventBegin("Bloom", cmd); - auto range = wiProfiler::BeginRangeGPU("Bloom", cmd); + auto range = wi::profiler::BeginRangeGPU("Bloom", cmd); // Separate bright parts of image to bloom texture: { @@ -7556,10 +7576,10 @@ void ComputeBloom( MIPGEN_OPTIONS mipopt; mipopt.gaussian_temp = &res.texture_temp; mipopt.wide_gauss = true; - GenerateMipChain(res.texture_bloom, wiRenderer::MIPGENFILTER_GAUSSIAN, cmd, mipopt); + GenerateMipChain(res.texture_bloom, MIPGENFILTER_GAUSSIAN, cmd, mipopt); device->EventEnd(cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } @@ -7570,7 +7590,7 @@ void ComputeShadingRateClassification( ) { device->EventBegin("ComputeShadingRateClassification", cmd); - auto range = wiProfiler::BeginRangeGPU("ComputeShadingRateClassification", cmd); + auto range = wi::profiler::BeginRangeGPU("ComputeShadingRateClassification", cmd); if (GetVariableRateShadingClassificationDebug()) { @@ -7622,7 +7642,7 @@ void ComputeShadingRateClassification( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } @@ -7636,7 +7656,7 @@ void VisibilityResolve( ) { device->EventBegin("VisibilityResolve", cmd); - auto range = wiProfiler::BeginRangeGPU("VisibilityResolve", cmd); + auto range = wi::profiler::BeginRangeGPU("VisibilityResolve", cmd); BindCommonResources(cmd); @@ -7691,7 +7711,7 @@ void VisibilityResolve( barrier_stack_flush(cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } @@ -7714,7 +7734,7 @@ void SurfelGI_Coverage( ) { device->EventBegin("SurfelGI - Coverage", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("SurfelGI - Coverage", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("SurfelGI - Coverage", cmd); // Coverage: @@ -7789,19 +7809,19 @@ void SurfelGI_Coverage( } - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void SurfelGI( const SurfelGIResources& res, - const wiScene::Scene& scene, - wiGraphics::CommandList cmd + const Scene& scene, + CommandList cmd ) { if (!scene.TLAS.IsValid() && !scene.BVH.IsValid()) return; - auto prof_range = wiProfiler::BeginRangeGPU("SurfelGI", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("SurfelGI", cmd); device->EventBegin("SurfelGI", cmd); BindCommonResources(cmd); @@ -7982,7 +8002,7 @@ void SurfelGI( device->EventEnd(cmd); } - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } @@ -8279,7 +8299,7 @@ void Postprocess_SSAO( ) { device->EventBegin("Postprocess_SSAO", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("SSAO", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("SSAO", cmd); device->BindComputeShader(&shaders[CSTYPE_POSTPROCESS_SSAO], cmd); @@ -8325,7 +8345,7 @@ void Postprocess_SSAO( Postprocess_Blur_Bilateral(output, lineardepth, res.temp, output, cmd, 1.2f, -1, -1, true); - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void Postprocess_HBAO( @@ -8338,7 +8358,7 @@ void Postprocess_HBAO( ) { device->EventBegin("Postprocess_HBAO", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("HBAO", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("HBAO", cmd); device->BindComputeShader(&shaders[CSTYPE_POSTPROCESS_HBAO], cmd); @@ -8373,7 +8393,7 @@ void Postprocess_HBAO( // horizontal pass: { - device->BindResource(wiTextureHelper::getWhite(), 0, cmd); + device->BindResource(wi::texturehelper::getWhite(), 0, cmd); const GPUResource* uavs[] = { &res.temp, }; @@ -8441,7 +8461,7 @@ void Postprocess_HBAO( Postprocess_Blur_Bilateral(output, lineardepth, res.temp, output, cmd, 1.2f, -1, -1, true); - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void CreateMSAOResources(MSAOResources& res, XMUINT2 resolution) @@ -8540,7 +8560,7 @@ void Postprocess_MSAO( ) { device->EventBegin("Postprocess_MSAO", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("MSAO", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("MSAO", cmd); // Depth downsampling + deinterleaving pass1: { @@ -8911,7 +8931,7 @@ void Postprocess_MSAO( nullptr ); - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void CreateRTAOResources(RTAOResources& res, XMUINT2 resolution) @@ -8966,7 +8986,7 @@ void Postprocess_RTAO( return; device->EventBegin("Postprocess_RTAO", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("RTAO", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("RTAO", cmd); BindCommonResources(cmd); @@ -9177,7 +9197,7 @@ void Postprocess_RTAO( } res.frame++; - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void CreateRTReflectionResources(RTReflectionResources& res, XMUINT2 resolution) @@ -9215,7 +9235,7 @@ void Postprocess_RTReflection( return; device->EventBegin("Postprocess_RTReflection", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("RTReflection", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("RTReflection", cmd); const TextureDesc& desc = output.desc; @@ -9367,7 +9387,7 @@ void Postprocess_RTReflection( res.frame++; - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void CreateSSRResources(SSRResources& res, XMUINT2 resolution) @@ -9397,7 +9417,7 @@ void Postprocess_SSR( ) { device->EventBegin("Postprocess_SSR", cmd); - auto range = wiProfiler::BeginRangeGPU("SSR", cmd); + auto range = wi::profiler::BeginRangeGPU("SSR", cmd); BindCommonResources(cmd); @@ -9572,7 +9592,7 @@ void Postprocess_SSR( res.frame++; - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void CreateRTShadowResources(RTShadowResources& res, XMUINT2 resolution) @@ -9641,7 +9661,7 @@ void Postprocess_RTShadow( return; device->EventBegin("Postprocess_RTShadow", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("RTShadow", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("RTShadow", cmd); const TextureDesc& desc = res.temp.GetDesc(); @@ -9952,7 +9972,7 @@ void Postprocess_RTShadow( device->EventEnd(cmd); } - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void CreateScreenSpaceShadowResources(ScreenSpaceShadowResources& res, XMUINT2 resolution) @@ -9968,7 +9988,7 @@ void Postprocess_ScreenSpaceShadow( ) { device->EventBegin("Postprocess_ScreenSpaceShadow", cmd); - auto prof_range = wiProfiler::BeginRangeGPU("ScreenSpaceShadow", cmd); + auto prof_range = wi::profiler::BeginRangeGPU("ScreenSpaceShadow", cmd); const TextureDesc& desc = output.GetDesc(); @@ -10011,7 +10031,7 @@ void Postprocess_ScreenSpaceShadow( } - wiProfiler::EndRange(prof_range); + wi::profiler::EndRange(prof_range); device->EventEnd(cmd); } void Postprocess_LightShafts( @@ -10022,7 +10042,7 @@ void Postprocess_LightShafts( ) { device->EventBegin("Postprocess_LightShafts", cmd); - auto range = wiProfiler::BeginRangeGPU("LightShafts", cmd); + auto range = wi::profiler::BeginRangeGPU("LightShafts", cmd); device->BindComputeShader(&shaders[CSTYPE_POSTPROCESS_LIGHTSHAFTS], cmd); @@ -10071,7 +10091,7 @@ void Postprocess_LightShafts( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void CreateDepthOfFieldResources(DepthOfFieldResources& res, XMUINT2 resolution) @@ -10132,7 +10152,7 @@ void Postprocess_DepthOfField( ) { device->EventBegin("Postprocess_DepthOfField", cmd); - auto range = wiProfiler::BeginRangeGPU("Depth of Field", cmd); + auto range = wi::profiler::BeginRangeGPU("Depth of Field", cmd); const TextureDesc& desc = output.GetDesc(); @@ -10499,7 +10519,7 @@ void Postprocess_DepthOfField( device->EventEnd(cmd); } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void Postprocess_Outline( @@ -10511,7 +10531,7 @@ void Postprocess_Outline( ) { device->EventBegin("Postprocess_Outline", cmd); - auto range = wiProfiler::BeginRangeGPU("Outline", cmd); + auto range = wi::profiler::BeginRangeGPU("Outline", cmd); device->BindPipelineState(&PSO_outline, cmd); @@ -10532,7 +10552,7 @@ void Postprocess_Outline( device->Draw(3, 0, cmd); - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void CreateMotionBlurResources(MotionBlurResources& res, XMUINT2 resolution) @@ -10575,7 +10595,7 @@ void Postprocess_MotionBlur( ) { device->EventBegin("Postprocess_MotionBlur", cmd); - auto range = wiProfiler::BeginRangeGPU("MotionBlur", cmd); + auto range = wi::profiler::BeginRangeGPU("MotionBlur", cmd); const TextureDesc& desc = output.GetDesc(); @@ -10784,7 +10804,7 @@ void Postprocess_MotionBlur( device->EventEnd(cmd); } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void CreateVolumetricCloudResources(VolumetricCloudResources& res, XMUINT2 resolution) @@ -10838,7 +10858,7 @@ void Postprocess_VolumetricClouds( ) { device->EventBegin("Postprocess_VolumetricClouds", cmd); - auto range = wiProfiler::BeginRangeGPU("Volumetric Clouds", cmd); + auto range = wi::profiler::BeginRangeGPU("Volumetric Clouds", cmd); BindCommonResources(cmd); @@ -10995,7 +11015,7 @@ void Postprocess_VolumetricClouds( res.frame++; - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void Postprocess_FXAA( @@ -11005,7 +11025,7 @@ void Postprocess_FXAA( ) { device->EventBegin("Postprocess_FXAA", cmd); - auto range = wiProfiler::BeginRangeGPU("FXAA", cmd); + auto range = wi::profiler::BeginRangeGPU("FXAA", cmd); device->BindComputeShader(&shaders[CSTYPE_POSTPROCESS_FXAA], cmd); @@ -11048,7 +11068,7 @@ void Postprocess_FXAA( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void Postprocess_TemporalAA( @@ -11059,7 +11079,7 @@ void Postprocess_TemporalAA( ) { device->EventBegin("Postprocess_TemporalAA", cmd); - auto range = wiProfiler::BeginRangeGPU("Temporal AA Resolve", cmd); + auto range = wi::profiler::BeginRangeGPU("Temporal AA Resolve", cmd); device->BindComputeShader(&shaders[CSTYPE_POSTPROCESS_TEMPORALAA], cmd); @@ -11103,7 +11123,7 @@ void Postprocess_TemporalAA( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void Postprocess_Sharpen( @@ -11232,7 +11252,7 @@ void Postprocess_FSR( ) { device->EventBegin("Postprocess_FSR", cmd); - auto range = wiProfiler::BeginRangeGPU("Postprocess_FSR", cmd); + auto range = wi::profiler::BeginRangeGPU("Postprocess_FSR", cmd); const TextureDesc& desc = output.GetDesc(); @@ -11328,7 +11348,7 @@ void Postprocess_FSR( } - wiProfiler::EndRange(range); + wi::profiler::EndRange(range); device->EventEnd(cmd); } void Postprocess_Chromatic_Aberration( @@ -11589,7 +11609,7 @@ void Postprocess_NormalsFromDepth( } -RAY GetPickRay(long cursorX, long cursorY, const wiCanvas& canvas, const CameraComponent& camera) +Ray GetPickRay(long cursorX, long cursorY, const wi::Canvas& canvas, const CameraComponent& camera) { float screenW = canvas.GetLogicalWidth(); float screenH = canvas.GetLogicalHeight(); @@ -11600,18 +11620,18 @@ RAY GetPickRay(long cursorX, long cursorY, const wiCanvas& canvas, const CameraC XMVECTOR lineStart = XMVector3Unproject(XMVectorSet((float)cursorX, (float)cursorY, 1, 1), 0, 0, screenW, screenH, 0.0f, 1.0f, P, V, W); XMVECTOR lineEnd = XMVector3Unproject(XMVectorSet((float)cursorX, (float)cursorY, 0, 1), 0, 0, screenW, screenH, 0.0f, 1.0f, P, V, W); XMVECTOR rayDirection = XMVector3Normalize(XMVectorSubtract(lineEnd, lineStart)); - return RAY(lineStart, rayDirection); + return Ray(lineStart, rayDirection); } void DrawBox(const XMFLOAT4X4& boxMatrix, const XMFLOAT4& color) { renderableBoxes.push_back(std::make_pair(boxMatrix,color)); } -void DrawSphere(const SPHERE& sphere, const XMFLOAT4& color) +void DrawSphere(const Sphere& sphere, const XMFLOAT4& color) { renderableSpheres.push_back(std::make_pair(sphere, color)); } -void DrawCapsule(const CAPSULE& capsule, const XMFLOAT4& color) +void DrawCapsule(const Capsule& capsule, const XMFLOAT4& color) { renderableCapsules.push_back(std::make_pair(capsule, color)); } @@ -11643,10 +11663,10 @@ void DrawPaintRadius(const PaintRadius& paintrad) paintrads.push_back(paintrad); } -void AddDeferredMIPGen(std::shared_ptr resource, bool preserve_coverage) +void AddDeferredMIPGen(const Texture& texture, bool preserve_coverage) { deferredMIPGenLock.lock(); - deferredMIPGens.push_back(std::make_pair(resource, preserve_coverage)); + deferredMIPGens.push_back(std::make_pair(texture, preserve_coverage)); deferredMIPGenLock.unlock(); } diff --git a/WickedEngine/wiRenderer.h b/WickedEngine/wiRenderer.h index c6d6204dd..599b50a3f 100644 --- a/WickedEngine/wiRenderer.h +++ b/WickedEngine/wiRenderer.h @@ -4,7 +4,7 @@ #include "wiGraphicsDevice.h" #include "wiScene.h" #include "wiECS.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiCanvas.h" #include "wiMath.h" #include "shaders/ShaderInterop_Renderer.h" @@ -13,12 +13,16 @@ #include #include -struct RAY; -struct wiResource; - -namespace wiRenderer +namespace wi::renderer { - inline uint32_t CombineStencilrefs(STENCILREF engineStencilRef, uint8_t userStencilRef) + enum GBUFFER + { + GBUFFER_PRIMITIVEID, + GBUFFER_VELOCITY, + GBUFFER_COUNT + }; + + inline uint32_t CombineStencilrefs(wi::enums::STENCILREF engineStencilRef, uint8_t userStencilRef) { return (userStencilRef << 4) | static_cast(engineStencilRef); } @@ -32,16 +36,16 @@ namespace wiRenderer ); } - const wiGraphics::Sampler* GetSampler(int slot); - const wiGraphics::Shader* GetShader(SHADERTYPE id); - const wiGraphics::InputLayout* GetInputLayout(ILTYPES id); - const wiGraphics::RasterizerState* GetRasterizerState(RSTYPES id); - const wiGraphics::DepthStencilState* GetDepthStencilState(DSSTYPES id); - const wiGraphics::BlendState* GetBlendState(BSTYPES id); - const wiGraphics::GPUBuffer* GetConstantBuffer(CBTYPES id); - const wiGraphics::Texture* GetTexture(TEXTYPES id); + const wi::graphics::Sampler* GetSampler(wi::enums::SAMPLERTYPES id); + const wi::graphics::Shader* GetShader(wi::enums::SHADERTYPE id); + const wi::graphics::InputLayout* GetInputLayout(wi::enums::ILTYPES id); + const wi::graphics::RasterizerState* GetRasterizerState(wi::enums::RSTYPES id); + const wi::graphics::DepthStencilState* GetDepthStencilState(wi::enums::DSSTYPES id); + const wi::graphics::BlendState* GetBlendState(wi::enums::BSTYPES id); + const wi::graphics::GPUBuffer* GetConstantBuffer(wi::enums::CBTYPES id); + const wi::graphics::Texture* GetTexture(wi::enums::TEXTYPES id); - void ModifyObjectSampler(const wiGraphics::SamplerDesc& desc); + void ModifyObjectSampler(const wi::graphics::SamplerDesc& desc); // Initializes the samplers, including the global static samplers for the device void InitializeCommonSamplers(); @@ -50,7 +54,7 @@ namespace wiRenderer void Initialize(); // Clears the scene and the associated renderer resources - void ClearWorld(wiScene::Scene& scene); + void ClearWorld(wi::scene::Scene& scene); // Returns the shader binary directory const std::string& GetShaderPath(); @@ -67,10 +71,10 @@ namespace wiRenderer size_t GetShaderDumpCount(); bool LoadShader( - wiGraphics::ShaderStage stage, - wiGraphics::Shader& shader, + wi::graphics::ShaderStage stage, + wi::graphics::Shader& shader, const std::string& filename, - wiGraphics::ShaderModel minshadermodel = wiGraphics::ShaderModel::SM_6_0 + wi::graphics::ShaderModel minshadermodel = wi::graphics::ShaderModel::SM_6_0 ); @@ -78,8 +82,8 @@ namespace wiRenderer { // User fills these: uint32_t layerMask = ~0u; - const wiScene::Scene* scene = nullptr; - const wiScene::CameraComponent* camera = nullptr; + const wi::scene::Scene* scene = nullptr; + const wi::scene::CameraComponent* camera = nullptr; enum FLAGS { EMPTY = 0, @@ -96,8 +100,8 @@ namespace wiRenderer }; uint32_t flags = EMPTY; - // wiRenderer::UpdateVisibility() fills these: - Frustum frustum; + // wi::renderer::UpdateVisibility() fills these: + wi::primitive::Frustum frustum; wi::vector visibleObjects; wi::vector visibleDecals; wi::vector visibleEnvProbes; @@ -118,7 +122,7 @@ namespace wiRenderer std::atomic light_counter; std::atomic decal_counter; - wiSpinLock locker; + wi::SpinLock locker; bool planar_reflection_visible = false; float closestRefPlane = std::numeric_limits::max(); XMFLOAT4 reflectionPlane = XMFLOAT4(0, 1, 0, 0); @@ -156,7 +160,7 @@ namespace wiRenderer void UpdateVisibility(Visibility& vis); // Prepares the scene for rendering void UpdatePerFrameData( - wiScene::Scene& scene, + wi::scene::Scene& scene, const Visibility& vis, FrameCB& frameCB, float dt @@ -165,28 +169,28 @@ namespace wiRenderer void UpdateRenderData( const Visibility& vis, const FrameCB& frameCB, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); // Updates those GPU states that can be async void UpdateRenderDataAsync( const Visibility& vis, const FrameCB& frameCB, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); - void UpdateRaytracingAccelerationStructures(const wiScene::Scene& scene, wiGraphics::CommandList cmd); + void UpdateRaytracingAccelerationStructures(const wi::scene::Scene& scene, wi::graphics::CommandList cmd); // Binds all common constant buffers and samplers that may be used in all shaders - void BindCommonResources(wiGraphics::CommandList cmd); + void BindCommonResources(wi::graphics::CommandList cmd); // Updates the per camera constant buffer need to call for each different camera that is used when calling DrawScene() and the like // camera_previous : camera from previous frame, used for reprojection effects. // camera_reflection : camera that renders planar reflection void BindCameraCB( - const wiScene::CameraComponent& camera, - const wiScene::CameraComponent& camera_previous, - const wiScene::CameraComponent& camera_reflection, - wiGraphics::CommandList cmd + const wi::scene::CameraComponent& camera, + const wi::scene::CameraComponent& camera_previous, + const wi::scene::CameraComponent& camera_reflection, + wi::graphics::CommandList cmd ); @@ -202,160 +206,160 @@ namespace wiRenderer // Draw the world from a camera. You must call BindCameraCB() at least once in this frame prior to this void DrawScene( const Visibility& vis, - RENDERPASS renderPass, - wiGraphics::CommandList cmd, + wi::enums::RENDERPASS renderPass, + wi::graphics::CommandList cmd, uint32_t flags = DRAWSCENE_OPAQUE ); // Render mip levels for textures that reqested it: - void ProcessDeferredMipGenRequests(wiGraphics::CommandList cmd); + void ProcessDeferredMipGenRequests(wi::graphics::CommandList cmd); // Compute essential atmospheric scattering textures for skybox, fog and clouds - void RenderAtmosphericScatteringTextures(wiGraphics::CommandList cmd); + void RenderAtmosphericScatteringTextures(wi::graphics::CommandList cmd); // Update atmospheric scattering primarily for environment probes. - void RefreshAtmosphericScatteringTextures(wiGraphics::CommandList cmd); + void RefreshAtmosphericScatteringTextures(wi::graphics::CommandList cmd); // Draw skydome centered to camera. - void DrawSky(const wiScene::Scene& scene, wiGraphics::CommandList cmd); + void DrawSky(const wi::scene::Scene& scene, wi::graphics::CommandList cmd); // Draw shadow maps for each visible light that has associated shadow maps - void DrawSun(wiGraphics::CommandList cmd); + void DrawSun(wi::graphics::CommandList cmd); // Draw shadow maps for each visible light that has associated shadow maps void DrawShadowmaps( const Visibility& vis, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); // Draw debug world. You must also enable what parts to draw, eg. SetToDrawGridHelper, etc, see implementation for details what can be enabled. void DrawDebugWorld( - const wiScene::Scene& scene, - const wiScene::CameraComponent& camera, - const wiCanvas& canvas, - wiGraphics::CommandList cmd + const wi::scene::Scene& scene, + const wi::scene::CameraComponent& camera, + const wi::Canvas& canvas, + wi::graphics::CommandList cmd ); // Draw Soft offscreen particles. void DrawSoftParticles( const Visibility& vis, - const wiGraphics::Texture& lineardepth, + const wi::graphics::Texture& lineardepth, bool distortion, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); // Draw simple light visualizer geometries void DrawLightVisualizers( const Visibility& vis, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); // Draw volumetric light scattering effects void DrawVolumeLights( const Visibility& vis, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); // Draw Lens Flares for lights that have them enabled void DrawLensFlares( const Visibility& vis, - wiGraphics::CommandList cmd, - const wiGraphics::Texture* texture_directional_occlusion = nullptr + wi::graphics::CommandList cmd, + const wi::graphics::Texture* texture_directional_occlusion = nullptr ); // Call once per frame to re-render out of date environment probes - void RefreshEnvProbes(const Visibility& vis, wiGraphics::CommandList cmd); + void RefreshEnvProbes(const Visibility& vis, wi::graphics::CommandList cmd); // Call once per frame to re-render out of date impostors - void RefreshImpostors(const wiScene::Scene& scene, wiGraphics::CommandList cmd); + void RefreshImpostors(const wi::scene::Scene& scene, wi::graphics::CommandList cmd); // Call once per frame to repack out of date lightmaps in the atlas - void RefreshLightmaps(const wiScene::Scene& scene, wiGraphics::CommandList cmd); + void RefreshLightmaps(const wi::scene::Scene& scene, wi::graphics::CommandList cmd); // Voxelize the scene into a voxel grid 3D texture - void VoxelRadiance(const Visibility& vis, wiGraphics::CommandList cmd); + void VoxelRadiance(const Visibility& vis, wi::graphics::CommandList cmd); // Run a compute shader that will resolve a MSAA depth buffer to a single-sample texture - void ResolveMSAADepthBuffer(const wiGraphics::Texture& dst, const wiGraphics::Texture& src, wiGraphics::CommandList cmd); - void DownsampleDepthBuffer(const wiGraphics::Texture& src, wiGraphics::CommandList cmd); + void ResolveMSAADepthBuffer(const wi::graphics::Texture& dst, const wi::graphics::Texture& src, wi::graphics::CommandList cmd); + void DownsampleDepthBuffer(const wi::graphics::Texture& src, wi::graphics::CommandList cmd); struct TiledLightResources { XMUINT3 tileCount = {}; - wiGraphics::GPUBuffer tileFrustums; // entity culling frustums - wiGraphics::GPUBuffer entityTiles_Opaque; // culled entity indices (for opaque pass) - wiGraphics::GPUBuffer entityTiles_Transparent; // culled entity indices (for transparent pass) + wi::graphics::GPUBuffer tileFrustums; // entity culling frustums + wi::graphics::GPUBuffer entityTiles_Opaque; // culled entity indices (for opaque pass) + wi::graphics::GPUBuffer entityTiles_Transparent; // culled entity indices (for transparent pass) }; void CreateTiledLightResources(TiledLightResources& res, XMUINT2 resolution); // Compute light grid tiles void ComputeTiledLightCulling( const TiledLightResources& res, - const wiGraphics::Texture& debugUAV, - wiGraphics::CommandList cmd + const wi::graphics::Texture& debugUAV, + wi::graphics::CommandList cmd ); struct LuminanceResources { - wiGraphics::GPUBuffer luminance; + wi::graphics::GPUBuffer luminance; }; void CreateLuminanceResources(LuminanceResources& res, XMUINT2 resolution); // Compute the luminance for the source image and return the texture containing the luminance value in pixel [0,0] void ComputeLuminance( const LuminanceResources& res, - const wiGraphics::Texture& sourceImage, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& sourceImage, + wi::graphics::CommandList cmd, float adaption_rate = 1, float eyeadaptionkey = 0.115f ); struct BloomResources { - wiGraphics::Texture texture_bloom; - wiGraphics::Texture texture_temp; + wi::graphics::Texture texture_bloom; + wi::graphics::Texture texture_temp; }; void CreateBloomResources(BloomResources& res, XMUINT2 resolution); void ComputeBloom( const BloomResources& res, - const wiGraphics::Texture& input, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + wi::graphics::CommandList cmd, float threshold = 1.0f, // cutoff value, pixels below this will not contribute to bloom float exposure = 1.0f, - const wiGraphics::GPUBuffer* buffer_luminance = nullptr + const wi::graphics::GPUBuffer* buffer_luminance = nullptr ); void ComputeShadingRateClassification( - const wiGraphics::Texture& output, - const wiGraphics::Texture& debugUAV, - wiGraphics::CommandList cmd + const wi::graphics::Texture& output, + const wi::graphics::Texture& debugUAV, + wi::graphics::CommandList cmd ); void VisibilityResolve( - const wiGraphics::Texture& depthbuffer, - const wiGraphics::Texture& texture_primitiveID, // can be MSAA - const wiGraphics::Texture gbuffer[GBUFFER_COUNT], - const wiGraphics::Texture& depthbuffer_resolved, - const wiGraphics::Texture& lineardepth, - wiGraphics::CommandList cmd + const wi::graphics::Texture& depthbuffer, + const wi::graphics::Texture& texture_primitiveID, // can be MSAA + const wi::graphics::Texture gbuffer[GBUFFER_COUNT], + const wi::graphics::Texture& depthbuffer_resolved, + const wi::graphics::Texture& lineardepth, + wi::graphics::CommandList cmd ); struct SurfelGIResources { - wiGraphics::Texture result; + wi::graphics::Texture result; }; void CreateSurfelGIResources(SurfelGIResources& res, XMUINT2 resolution); void SurfelGI_Coverage( const SurfelGIResources& res, - const wiScene::Scene& scene, - const wiGraphics::Texture& debugUAV, - wiGraphics::CommandList cmd + const wi::scene::Scene& scene, + const wi::graphics::Texture& debugUAV, + wi::graphics::CommandList cmd ); void SurfelGI( const SurfelGIResources& res, - const wiScene::Scene& scene, - wiGraphics::CommandList cmd + const wi::scene::Scene& scene, + wi::graphics::CommandList cmd ); void Postprocess_Blur_Gaussian( - const wiGraphics::Texture& input, - const wiGraphics::Texture& temp, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& temp, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, int mip_src = -1, int mip_dst = -1, bool wide = false ); void Postprocess_Blur_Bilateral( - const wiGraphics::Texture& input, - const wiGraphics::Texture& lineardepth, - const wiGraphics::Texture& temp, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& lineardepth, + const wi::graphics::Texture& temp, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float depth_threshold = 1.0f, int mip_src = -1, int mip_dst = -1, @@ -363,124 +367,124 @@ namespace wiRenderer ); struct SSAOResources { - wiGraphics::Texture temp; + wi::graphics::Texture temp; }; void CreateSSAOResources(SSAOResources& res, XMUINT2 resolution); void Postprocess_SSAO( const SSAOResources& res, - const wiGraphics::Texture& output, - const wiGraphics::Texture& lineardepth, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& output, + const wi::graphics::Texture& lineardepth, + wi::graphics::CommandList cmd, float range = 1.0f, uint32_t samplecount = 16, float power = 1.0f ); void Postprocess_HBAO( const SSAOResources& res, - const wiScene::CameraComponent& camera, - const wiGraphics::Texture& lineardepth, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::scene::CameraComponent& camera, + const wi::graphics::Texture& lineardepth, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float power = 1.0f ); struct MSAOResources { - wiGraphics::Texture texture_lineardepth_downsize1; - wiGraphics::Texture texture_lineardepth_tiled1; - wiGraphics::Texture texture_lineardepth_downsize2; - wiGraphics::Texture texture_lineardepth_tiled2; - wiGraphics::Texture texture_lineardepth_downsize3; - wiGraphics::Texture texture_lineardepth_tiled3; - wiGraphics::Texture texture_lineardepth_downsize4; - wiGraphics::Texture texture_lineardepth_tiled4; - wiGraphics::Texture texture_ao_merged1; - wiGraphics::Texture texture_ao_hq1; - wiGraphics::Texture texture_ao_smooth1; - wiGraphics::Texture texture_ao_merged2; - wiGraphics::Texture texture_ao_hq2; - wiGraphics::Texture texture_ao_smooth2; - wiGraphics::Texture texture_ao_merged3; - wiGraphics::Texture texture_ao_hq3; - wiGraphics::Texture texture_ao_smooth3; - wiGraphics::Texture texture_ao_merged4; - wiGraphics::Texture texture_ao_hq4; + wi::graphics::Texture texture_lineardepth_downsize1; + wi::graphics::Texture texture_lineardepth_tiled1; + wi::graphics::Texture texture_lineardepth_downsize2; + wi::graphics::Texture texture_lineardepth_tiled2; + wi::graphics::Texture texture_lineardepth_downsize3; + wi::graphics::Texture texture_lineardepth_tiled3; + wi::graphics::Texture texture_lineardepth_downsize4; + wi::graphics::Texture texture_lineardepth_tiled4; + wi::graphics::Texture texture_ao_merged1; + wi::graphics::Texture texture_ao_hq1; + wi::graphics::Texture texture_ao_smooth1; + wi::graphics::Texture texture_ao_merged2; + wi::graphics::Texture texture_ao_hq2; + wi::graphics::Texture texture_ao_smooth2; + wi::graphics::Texture texture_ao_merged3; + wi::graphics::Texture texture_ao_hq3; + wi::graphics::Texture texture_ao_smooth3; + wi::graphics::Texture texture_ao_merged4; + wi::graphics::Texture texture_ao_hq4; }; void CreateMSAOResources(MSAOResources& res, XMUINT2 resolution); void Postprocess_MSAO( const MSAOResources& res, - const wiScene::CameraComponent& camera, - const wiGraphics::Texture& lineardepth, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::scene::CameraComponent& camera, + const wi::graphics::Texture& lineardepth, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float power = 1.0f ); struct RTAOResources { - wiGraphics::Texture normals; + wi::graphics::Texture normals; mutable int frame = 0; - wiGraphics::GPUBuffer tiles; - wiGraphics::GPUBuffer metadata; - wiGraphics::Texture scratch[2]; - wiGraphics::Texture moments[2]; + wi::graphics::GPUBuffer tiles; + wi::graphics::GPUBuffer metadata; + wi::graphics::Texture scratch[2]; + wi::graphics::Texture moments[2]; }; void CreateRTAOResources(RTAOResources& res, XMUINT2 resolution); void Postprocess_RTAO( const RTAOResources& res, - const wiScene::Scene& scene, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::scene::Scene& scene, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float range = 1.0f, float power = 1.0f ); struct RTReflectionResources { mutable int frame = 0; - wiGraphics::Texture temporal[2]; - wiGraphics::Texture rayLengths; + wi::graphics::Texture temporal[2]; + wi::graphics::Texture rayLengths; }; void CreateRTReflectionResources(RTReflectionResources& res, XMUINT2 resolution); void Postprocess_RTReflection( const RTReflectionResources& res, - const wiScene::Scene& scene, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::scene::Scene& scene, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float range = 1000.0f ); struct SSRResources { mutable int frame = 0; - wiGraphics::Texture texture_raytrace; - wiGraphics::Texture rayLengths; - wiGraphics::Texture texture_temporal[2]; + wi::graphics::Texture texture_raytrace; + wi::graphics::Texture rayLengths; + wi::graphics::Texture texture_temporal[2]; }; void CreateSSRResources(SSRResources& res, XMUINT2 resolution); void Postprocess_SSR( const SSRResources& res, - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); struct RTShadowResources { - wiGraphics::Texture temp; - wiGraphics::Texture temporal[2]; - wiGraphics::Texture normals; + wi::graphics::Texture temp; + wi::graphics::Texture temporal[2]; + wi::graphics::Texture normals; mutable int frame = 0; - wiGraphics::GPUBuffer tiles; - wiGraphics::GPUBuffer metadata; - wiGraphics::Texture scratch[4][2]; - wiGraphics::Texture moments[4][2]; - wiGraphics::Texture denoised; + wi::graphics::GPUBuffer tiles; + wi::graphics::GPUBuffer metadata; + wi::graphics::Texture scratch[4][2]; + wi::graphics::Texture moments[4][2]; + wi::graphics::Texture denoised; }; void CreateRTShadowResources(RTShadowResources& res, XMUINT2 resolution); void Postprocess_RTShadow( const RTShadowResources& res, - const wiScene::Scene& scene, - const wiGraphics::GPUBuffer& entityTiles_Opaque, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::scene::Scene& scene, + const wi::graphics::GPUBuffer& entityTiles_Opaque, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); struct ScreenSpaceShadowResources { @@ -489,164 +493,164 @@ namespace wiRenderer void CreateScreenSpaceShadowResources(ScreenSpaceShadowResources& res, XMUINT2 resolution); void Postprocess_ScreenSpaceShadow( const ScreenSpaceShadowResources& res, - const wiGraphics::GPUBuffer& entityTiles_Opaque, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::GPUBuffer& entityTiles_Opaque, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float range = 1, uint32_t samplecount = 16 ); void Postprocess_LightShafts( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, const XMFLOAT2& center ); struct DepthOfFieldResources { - wiGraphics::Texture texture_tilemax_horizontal; - wiGraphics::Texture texture_tilemin_horizontal; - wiGraphics::Texture texture_tilemax; - wiGraphics::Texture texture_tilemin; - wiGraphics::Texture texture_neighborhoodmax; - wiGraphics::Texture texture_presort; - wiGraphics::Texture texture_prefilter; - wiGraphics::Texture texture_main; - wiGraphics::Texture texture_postfilter; - wiGraphics::Texture texture_alpha1; - wiGraphics::Texture texture_alpha2; - wiGraphics::GPUBuffer buffer_tile_statistics; - wiGraphics::GPUBuffer buffer_tiles_earlyexit; - wiGraphics::GPUBuffer buffer_tiles_cheap; - wiGraphics::GPUBuffer buffer_tiles_expensive; + wi::graphics::Texture texture_tilemax_horizontal; + wi::graphics::Texture texture_tilemin_horizontal; + wi::graphics::Texture texture_tilemax; + wi::graphics::Texture texture_tilemin; + wi::graphics::Texture texture_neighborhoodmax; + wi::graphics::Texture texture_presort; + wi::graphics::Texture texture_prefilter; + wi::graphics::Texture texture_main; + wi::graphics::Texture texture_postfilter; + wi::graphics::Texture texture_alpha1; + wi::graphics::Texture texture_alpha2; + wi::graphics::GPUBuffer buffer_tile_statistics; + wi::graphics::GPUBuffer buffer_tiles_earlyexit; + wi::graphics::GPUBuffer buffer_tiles_cheap; + wi::graphics::GPUBuffer buffer_tiles_expensive; }; void CreateDepthOfFieldResources(DepthOfFieldResources& res, XMUINT2 resolution); void Postprocess_DepthOfField( const DepthOfFieldResources& res, - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float coc_scale = 10, float max_coc = 18 ); void Postprocess_Outline( - const wiGraphics::Texture& input, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + wi::graphics::CommandList cmd, float threshold = 0.1f, float thickness = 1.0f, const XMFLOAT4& color = XMFLOAT4(0, 0, 0, 1) ); struct MotionBlurResources { - wiGraphics::Texture texture_tilemin_horizontal; - wiGraphics::Texture texture_tilemax_horizontal; - wiGraphics::Texture texture_tilemax; - wiGraphics::Texture texture_tilemin; - wiGraphics::Texture texture_neighborhoodmax; - wiGraphics::GPUBuffer buffer_tile_statistics; - wiGraphics::GPUBuffer buffer_tiles_earlyexit; - wiGraphics::GPUBuffer buffer_tiles_cheap; - wiGraphics::GPUBuffer buffer_tiles_expensive; + wi::graphics::Texture texture_tilemin_horizontal; + wi::graphics::Texture texture_tilemax_horizontal; + wi::graphics::Texture texture_tilemax; + wi::graphics::Texture texture_tilemin; + wi::graphics::Texture texture_neighborhoodmax; + wi::graphics::GPUBuffer buffer_tile_statistics; + wi::graphics::GPUBuffer buffer_tiles_earlyexit; + wi::graphics::GPUBuffer buffer_tiles_cheap; + wi::graphics::GPUBuffer buffer_tiles_expensive; }; void CreateMotionBlurResources(MotionBlurResources& res, XMUINT2 resolution); void Postprocess_MotionBlur( const MotionBlurResources& res, - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float strength = 100.0f ); struct VolumetricCloudResources { mutable int frame = 0; - wiGraphics::Texture texture_cloudRender; - wiGraphics::Texture texture_cloudDepth; - wiGraphics::Texture texture_reproject[2]; - wiGraphics::Texture texture_reproject_depth[2]; - wiGraphics::Texture texture_temporal[2]; - wiGraphics::Texture texture_cloudMask; + wi::graphics::Texture texture_cloudRender; + wi::graphics::Texture texture_cloudDepth; + wi::graphics::Texture texture_reproject[2]; + wi::graphics::Texture texture_reproject_depth[2]; + wi::graphics::Texture texture_temporal[2]; + wi::graphics::Texture texture_cloudMask; }; void CreateVolumetricCloudResources(VolumetricCloudResources& res, XMUINT2 resolution); void Postprocess_VolumetricClouds( const VolumetricCloudResources& res, - wiGraphics::CommandList cmd + wi::graphics::CommandList cmd ); void Postprocess_FXAA( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); void Postprocess_TemporalAA( - const wiGraphics::Texture& input_current, - const wiGraphics::Texture& input_history, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::graphics::Texture& input_current, + const wi::graphics::Texture& input_history, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); void Postprocess_Sharpen( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float amount = 1.0f ); void Postprocess_Tonemap( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float exposure, bool dither, - const wiGraphics::Texture* texture_colorgradinglut = nullptr, - const wiGraphics::Texture* texture_distortion = nullptr, - const wiGraphics::GPUBuffer* buffer_luminance = nullptr, - const wiGraphics::Texture* texture_bloom = nullptr, - wiGraphics::ColorSpace display_colorspace = wiGraphics::ColorSpace::SRGB + const wi::graphics::Texture* texture_colorgradinglut = nullptr, + const wi::graphics::Texture* texture_distortion = nullptr, + const wi::graphics::GPUBuffer* buffer_luminance = nullptr, + const wi::graphics::Texture* texture_bloom = nullptr, + wi::graphics::ColorSpace display_colorspace = wi::graphics::ColorSpace::SRGB ); void Postprocess_FSR( - const wiGraphics::Texture& input, - const wiGraphics::Texture& temp, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& temp, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float sharpness = 1.0f ); void Postprocess_Chromatic_Aberration( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, float amount = 1.0f ); void Postprocess_Upsample_Bilateral( - const wiGraphics::Texture& input, - const wiGraphics::Texture& lineardepth, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& input, + const wi::graphics::Texture& lineardepth, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd, bool is_pixelshader = false, float threshold = 1.0f ); void Postprocess_Downsample4x( - const wiGraphics::Texture& input, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::graphics::Texture& input, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); void Postprocess_NormalsFromDepth( - const wiGraphics::Texture& depthbuffer, - const wiGraphics::Texture& output, - wiGraphics::CommandList cmd + const wi::graphics::Texture& depthbuffer, + const wi::graphics::Texture& output, + wi::graphics::CommandList cmd ); // Render the scene with ray tracing. You provide the ray buffer, where each ray maps to one pixel of the result testure void RayTraceScene( - const wiScene::Scene& scene, - const wiGraphics::Texture& output, + const wi::scene::Scene& scene, + const wi::graphics::Texture& output, int accumulation_sample, - wiGraphics::CommandList cmd, - const wiGraphics::Texture* output_albedo = nullptr, - const wiGraphics::Texture* output_normal = nullptr + wi::graphics::CommandList cmd, + const wi::graphics::Texture* output_albedo = nullptr, + const wi::graphics::Texture* output_normal = nullptr ); // Render the scene BVH with ray tracing to the screen - void RayTraceSceneBVH(const wiScene::Scene& scene, wiGraphics::CommandList cmd); + void RayTraceSceneBVH(const wi::scene::Scene& scene, wi::graphics::CommandList cmd); // Render occluders against a depth buffer - void OcclusionCulling_Reset(const Visibility& vis, wiGraphics::CommandList cmd); - void OcclusionCulling_Render(const wiScene::CameraComponent& camera, const Visibility& vis, wiGraphics::CommandList cmd); - void OcclusionCulling_Resolve(const Visibility& vis, wiGraphics::CommandList cmd); + void OcclusionCulling_Reset(const Visibility& vis, wi::graphics::CommandList cmd); + void OcclusionCulling_Render(const wi::scene::CameraComponent& camera, const Visibility& vis, wi::graphics::CommandList cmd); + void OcclusionCulling_Resolve(const Visibility& vis, wi::graphics::CommandList cmd); enum MIPGENFILTER @@ -658,11 +662,11 @@ namespace wiRenderer struct MIPGEN_OPTIONS { int arrayIndex = -1; - const wiGraphics::Texture* gaussian_temp = nullptr; + const wi::graphics::Texture* gaussian_temp = nullptr; bool preserve_coverage = false; bool wide_gauss = false; }; - void GenerateMipChain(const wiGraphics::Texture& texture, MIPGENFILTER filter, wiGraphics::CommandList cmd, const MIPGEN_OPTIONS& options = {}); + void GenerateMipChain(const wi::graphics::Texture& texture, MIPGENFILTER filter, wi::graphics::CommandList cmd, const MIPGEN_OPTIONS& options = {}); enum BORDEREXPANDSTYLE { @@ -674,13 +678,13 @@ namespace wiRenderer // NOTE: DstMIP can be specified as -1 to use main subresource, otherwise the subresource (>=0) must have been generated explicitly! // Can also expand border region according to desired sampler func void CopyTexture2D( - const wiGraphics::Texture& dst, int DstMIP, int DstX, int DstY, - const wiGraphics::Texture& src, int SrcMIP, - wiGraphics::CommandList cmd, + const wi::graphics::Texture& dst, int DstMIP, int DstX, int DstY, + const wi::graphics::Texture& src, int SrcMIP, + wi::graphics::CommandList cmd, BORDEREXPANDSTYLE borderExpand = BORDEREXPAND_DISABLE ); - void DrawWaterRipples(const Visibility& vis, wiGraphics::CommandList cmd); + void DrawWaterRipples(const Visibility& vis, wi::graphics::CommandList cmd); @@ -769,15 +773,15 @@ namespace wiRenderer bool GetSurfelGIDebugEnabled(); // Gets pick ray according to the current screen resolution and pointer coordinates. Can be used as input into RayIntersectWorld() - RAY GetPickRay(long cursorX, long cursorY, const wiCanvas& canvas, const wiScene::CameraComponent& camera = wiScene::GetCamera()); + wi::primitive::Ray GetPickRay(long cursorX, long cursorY, const wi::Canvas& canvas, const wi::scene::CameraComponent& camera = wi::scene::GetCamera()); // Add box to render in next frame. It will be rendered in DrawDebugWorld() void DrawBox(const XMFLOAT4X4& boxMatrix, const XMFLOAT4& color = XMFLOAT4(1,1,1,1)); // Add sphere to render in next frame. It will be rendered in DrawDebugWorld() - void DrawSphere(const SPHERE& sphere, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)); + void DrawSphere(const wi::primitive::Sphere& sphere, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)); // Add capsule to render in next frame. It will be rendered in DrawDebugWorld() - void DrawCapsule(const CAPSULE& capsule, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)); + void DrawCapsule(const wi::primitive::Capsule& capsule, const XMFLOAT4& color = XMFLOAT4(1, 1, 1, 1)); struct RenderableLine { @@ -820,7 +824,7 @@ namespace wiRenderer struct PaintRadius { - wiECS::Entity objectEntity = wiECS::INVALID_ENTITY; + wi::ecs::Entity objectEntity = wi::ecs::INVALID_ENTITY; int subset = -1; uint32_t uvset = 0; float radius = 0; @@ -830,13 +834,13 @@ namespace wiRenderer void DrawPaintRadius(const PaintRadius& paintrad); // Add a texture that should be mipmapped whenever it is feasible to do so - void AddDeferredMIPGen(std::shared_ptr res, bool preserve_coverage = false); + void AddDeferredMIPGen(const wi::graphics::Texture& texture, bool preserve_coverage = false); struct CustomShader { std::string name; - uint32_t renderTypeFlags = RENDERTYPE_OPAQUE; - wiGraphics::PipelineState pso[RENDERPASS_COUNT] = {}; + uint32_t renderTypeFlags = wi::enums::RENDERTYPE_OPAQUE; + wi::graphics::PipelineState pso[wi::enums::RENDERPASS_COUNT] = {}; }; // Registers a custom shader that can be set to materials. // Returns the ID of the custom shader that can be used with MaterialComponent::SetCustomShaderID() diff --git a/WickedEngine/wiRenderer_BindLua.cpp b/WickedEngine/wiRenderer_BindLua.cpp index dc58edba8..cc699cc09 100644 --- a/WickedEngine/wiRenderer_BindLua.cpp +++ b/WickedEngine/wiRenderer_BindLua.cpp @@ -3,168 +3,167 @@ #include "wiHelper.h" #include "wiScene.h" #include "wiScene_BindLua.h" -#include "Vector_BindLua.h" -#include "Matrix_BindLua.h" -#include "Texture_BindLua.h" +#include "wiMath_BindLua.h" +#include "wiTexture_BindLua.h" #include "wiEmittedParticle.h" #include "wiHairParticle.h" -#include "wiIntersect_BindLua.h" -#include "wiEvent.h" +#include "wiPrimitive_BindLua.h" +#include "wiEventHandler.h" -using namespace wiECS; -using namespace wiGraphics; -using namespace wiScene; -using namespace wiScene_BindLua; -using namespace wiIntersect_BindLua; +using namespace wi::ecs; +using namespace wi::graphics; +using namespace wi::scene; +using namespace wi::lua::scene; +using namespace wi::lua::primitive; -namespace wiRenderer_BindLua +namespace wi::lua::renderer { int SetGamma(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiLua::SSetString(L, "SetGamma() no longer supported!"); + wi::lua::SSetString(L, "SetGamma() no longer supported!"); } else { - wiLua::SError(L, "SetGamma(float) not enough arguments!"); + wi::lua::SError(L, "SetGamma(float) not enough arguments!"); } return 0; } int SetGameSpeed(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetGameSpeed(wiLua::SGetFloat(L, 1)); + wi::renderer::SetGameSpeed(wi::lua::SGetFloat(L, 1)); } else { - wiLua::SError(L,"SetGameSpeed(float) not enough arguments!"); + wi::lua::SError(L,"SetGameSpeed(float) not enough arguments!"); } return 0; } int GetGameSpeed(lua_State* L) { - wiLua::SSetFloat(L, wiRenderer::GetGameSpeed()); + wi::lua::SSetFloat(L, wi::renderer::GetGameSpeed()); return 1; } int SetShadowProps2D(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { - wiRenderer::SetShadowProps2D(wiLua::SGetInt(L, 1), wiLua::SGetInt(L, 2)); + wi::renderer::SetShadowProps2D(wi::lua::SGetInt(L, 1), wi::lua::SGetInt(L, 2)); } else - wiLua::SError(L, "SetShadowProps2D(int resolution, int count) not enough arguments!"); + wi::lua::SError(L, "SetShadowProps2D(int resolution, int count) not enough arguments!"); return 0; } int SetShadowPropsCube(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { - wiRenderer::SetShadowPropsCube(wiLua::SGetInt(L, 1), wiLua::SGetInt(L, 2)); + wi::renderer::SetShadowPropsCube(wi::lua::SGetInt(L, 1), wi::lua::SGetInt(L, 2)); } else - wiLua::SError(L, "SetShadowPropsCube(int resolution, int count) not enough arguments!"); + wi::lua::SError(L, "SetShadowPropsCube(int resolution, int count) not enough arguments!"); return 0; } int SetDebugPartitionTreeEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetToDrawDebugPartitionTree(wiLua::SGetBool(L, 1)); + wi::renderer::SetToDrawDebugPartitionTree(wi::lua::SGetBool(L, 1)); } return 0; } int SetDebugBoxesEnabled(lua_State* L) { - wiLua::SError(L, "SetDebugBoxesEnabled is obsolete! Use SetDebugPartitionTreeEnabled(bool value) instead to draw a partition tree!"); + wi::lua::SError(L, "SetDebugBoxesEnabled is obsolete! Use SetDebugPartitionTreeEnabled(bool value) instead to draw a partition tree!"); return 0; } int SetDebugBonesEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetToDrawDebugBoneLines(wiLua::SGetBool(L, 1)); + wi::renderer::SetToDrawDebugBoneLines(wi::lua::SGetBool(L, 1)); } return 0; } int SetDebugEmittersEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetToDrawDebugEmitters(wiLua::SGetBool(L, 1)); + wi::renderer::SetToDrawDebugEmitters(wi::lua::SGetBool(L, 1)); } return 0; } int SetDebugForceFieldsEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetToDrawDebugForceFields(wiLua::SGetBool(L, 1)); + wi::renderer::SetToDrawDebugForceFields(wi::lua::SGetBool(L, 1)); } return 0; } int SetVSyncEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiEvent::SetVSync(wiLua::SGetBool(L, 1)); + wi::eventhandler::SetVSync(wi::lua::SGetBool(L, 1)); } return 0; } int SetResolution(lua_State* L) { - wiLua::SError(L, "SetResolution() is deprecated, now it's handled by window events!"); + wi::lua::SError(L, "SetResolution() is deprecated, now it's handled by window events!"); return 0; } int SetDebugLightCulling(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetDebugLightCulling(wiLua::SGetBool(L, 1)); + wi::renderer::SetDebugLightCulling(wi::lua::SGetBool(L, 1)); } else { - wiLua::SError(L, "SetDebugLightCulling(bool enabled) not enough arguments!"); + wi::lua::SError(L, "SetDebugLightCulling(bool enabled) not enough arguments!"); } return 0; } int SetOcclusionCullingEnabled(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - wiRenderer::SetOcclusionCullingEnabled(wiLua::SGetBool(L, 1)); + wi::renderer::SetOcclusionCullingEnabled(wi::lua::SGetBool(L, 1)); } else { - wiLua::SError(L, "SetOcclusionCullingEnabled(bool enabled) not enough arguments!"); + wi::lua::SError(L, "SetOcclusionCullingEnabled(bool enabled) not enough arguments!"); } return 0; } int DrawLine(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* a = Luna::lightcheck(L, 1); Vector_BindLua* b = Luna::lightcheck(L, 2); if (a && b) { - wiRenderer::RenderableLine line; + wi::renderer::RenderableLine line; XMStoreFloat3(&line.start, XMLoadFloat4(a)); XMStoreFloat3(&line.end, XMLoadFloat4(b)); if (argc > 2) @@ -176,31 +175,31 @@ namespace wiRenderer_BindLua XMStoreFloat4(&line.color_end, XMLoadFloat4(c)); } else - wiLua::SError(L, "DrawLine(Vector origin,end, opt Vector color) one or more arguments are not vectors!"); + wi::lua::SError(L, "DrawLine(Vector origin,end, opt Vector color) one or more arguments are not vectors!"); } - wiRenderer::DrawLine(line); + wi::renderer::DrawLine(line); } else - wiLua::SError(L, "DrawLine(Vector origin,end, opt Vector color) one or more arguments are not vectors!"); + wi::lua::SError(L, "DrawLine(Vector origin,end, opt Vector color) one or more arguments are not vectors!"); } else - wiLua::SError(L, "DrawLine(Vector origin,end, opt Vector color) not enough arguments!"); + wi::lua::SError(L, "DrawLine(Vector origin,end, opt Vector color) not enough arguments!"); return 0; } int DrawPoint(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* a = Luna::lightcheck(L, 1); if (a) { - wiRenderer::RenderablePoint point; + wi::renderer::RenderablePoint point; XMStoreFloat3(&point.position, XMLoadFloat4(a)); if (argc > 1) { - point.size = wiLua::SGetFloat(L, 2); + point.size = wi::lua::SGetFloat(L, 2); if (argc > 2) { @@ -208,19 +207,19 @@ namespace wiRenderer_BindLua point.color = *color; } } - wiRenderer::DrawPoint(point); + wi::renderer::DrawPoint(point); } else - wiLua::SError(L, "DrawPoint(Vector origin, opt float size, opt Vector color) first argument must be a Vector type!"); + wi::lua::SError(L, "DrawPoint(Vector origin, opt float size, opt Vector color) first argument must be a Vector type!"); } else - wiLua::SError(L, "DrawPoint(Vector origin, opt float size, opt Vector color) not enough arguments!"); + wi::lua::SError(L, "DrawPoint(Vector origin, opt float size, opt Vector color) not enough arguments!"); return 0; } int DrawBox(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Matrix_BindLua* m = Luna::lightcheck(L, 1); @@ -231,24 +230,24 @@ namespace wiRenderer_BindLua Vector_BindLua* color = Luna::lightcheck(L, 2); if (color) { - wiRenderer::DrawBox(*m, *color); + wi::renderer::DrawBox(*m, *color); return 0; } } - wiRenderer::DrawBox(*m); + wi::renderer::DrawBox(*m); } else - wiLua::SError(L, "DrawBox(Matrix boxMatrix, opt Vector color) first argument must be a Matrix type!"); + wi::lua::SError(L, "DrawBox(Matrix boxMatrix, opt Vector color) first argument must be a Matrix type!"); } else - wiLua::SError(L, "DrawBox(Matrix boxMatrix, opt Vector color) not enough arguments!"); + wi::lua::SError(L, "DrawBox(Matrix boxMatrix, opt Vector color) not enough arguments!"); return 0; } int DrawSphere(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Sphere_BindLua* sphere = Luna::lightcheck(L, 1); @@ -259,24 +258,24 @@ namespace wiRenderer_BindLua Vector_BindLua* color = Luna::lightcheck(L, 2); if (color) { - wiRenderer::DrawSphere(sphere->sphere, *color); + wi::renderer::DrawSphere(sphere->sphere, *color); return 0; } } - wiRenderer::DrawSphere(sphere->sphere); + wi::renderer::DrawSphere(sphere->sphere); } else - wiLua::SError(L, "DrawSphere(Sphere sphere, opt Vector color) first argument must be a Matrix type!"); + wi::lua::SError(L, "DrawSphere(Sphere sphere, opt Vector color) first argument must be a Matrix type!"); } else - wiLua::SError(L, "DrawSphere(Sphere sphere, opt Vector color) not enough arguments!"); + wi::lua::SError(L, "DrawSphere(Sphere sphere, opt Vector color) not enough arguments!"); return 0; } int DrawCapsule(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Capsule_BindLua* capsule = Luna::lightcheck(L, 1); @@ -287,39 +286,39 @@ namespace wiRenderer_BindLua Vector_BindLua* color = Luna::lightcheck(L, 2); if (color) { - wiRenderer::DrawCapsule(capsule->capsule, *color); + wi::renderer::DrawCapsule(capsule->capsule, *color); return 0; } } - wiRenderer::DrawCapsule(capsule->capsule); + wi::renderer::DrawCapsule(capsule->capsule); } else - wiLua::SError(L, "DrawCapsule(Capsule capsule, opt Vector color) first argument must be a Matrix type!"); + wi::lua::SError(L, "DrawCapsule(Capsule capsule, opt Vector color) first argument must be a Matrix type!"); } else - wiLua::SError(L, "DrawCapsule(Capsule capsule, opt Vector color) not enough arguments!"); + wi::lua::SError(L, "DrawCapsule(Capsule capsule, opt Vector color) not enough arguments!"); return 0; } int PutWaterRipple(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { - std::string name = wiLua::SGetString(L, 1); + std::string name = wi::lua::SGetString(L, 1); Vector_BindLua* v = Luna::lightcheck(L, 2); if (v) { XMFLOAT3 pos; XMStoreFloat3(&pos, XMLoadFloat4(v)); - wiScene::GetScene().PutWaterRipple(wiLua::GetScriptPath() + name, pos); + wi::scene::GetScene().PutWaterRipple(wi::lua::GetScriptPath() + name, pos); } else - wiLua::SError(L, "PutWaterRipple(String imagename, Vector position) argument is not a Vector!"); + wi::lua::SError(L, "PutWaterRipple(String imagename, Vector position) argument is not a Vector!"); } else - wiLua::SError(L, "PutWaterRipple(String imagename, Vector position) not enough arguments!"); + wi::lua::SError(L, "PutWaterRipple(String imagename, Vector position) not enough arguments!"); return 0; } @@ -328,17 +327,17 @@ namespace wiRenderer_BindLua Scene_BindLua* scene = Luna::lightcheck(L, 1); if (scene == nullptr) { - wiRenderer::ClearWorld(wiScene::GetScene()); + wi::renderer::ClearWorld(wi::scene::GetScene()); } else { - wiRenderer::ClearWorld(*scene->scene); + wi::renderer::ClearWorld(*scene->scene); } return 0; } int ReloadShaders(lua_State* L) { - wiRenderer::ReloadShaders(); + wi::renderer::ReloadShaders(); return 0; } @@ -349,41 +348,41 @@ namespace wiRenderer_BindLua { initialized = true; - wiLua::RegisterFunc("SetGamma", SetGamma); - wiLua::RegisterFunc("SetGameSpeed", SetGameSpeed); - wiLua::RegisterFunc("GetGameSpeed", GetGameSpeed); + wi::lua::RegisterFunc("SetGamma", SetGamma); + wi::lua::RegisterFunc("SetGameSpeed", SetGameSpeed); + wi::lua::RegisterFunc("GetGameSpeed", GetGameSpeed); - wiLua::RunText("GetScreenWidth = function() return main.GetCanvas().GetLogicalWidth() end"); - wiLua::RunText("GetScreenHeight = function() return main.GetCanvas().GetLogicalHeight() end"); + wi::lua::RunText("GetScreenWidth = function() return main.GetCanvas().GetLogicalWidth() end"); + wi::lua::RunText("GetScreenHeight = function() return main.GetCanvas().GetLogicalHeight() end"); - wiLua::RegisterFunc("SetShadowProps2D", SetShadowProps2D); - wiLua::RegisterFunc("SetShadowPropsCube", SetShadowPropsCube); - wiLua::RegisterFunc("SetDebugBoxesEnabled", SetDebugBoxesEnabled); - wiLua::RegisterFunc("SetDebugPartitionTreeEnabled", SetDebugPartitionTreeEnabled); - wiLua::RegisterFunc("SetDebugBonesEnabled", SetDebugBonesEnabled); - wiLua::RegisterFunc("SetDebugEmittersEnabled", SetDebugEmittersEnabled); - wiLua::RegisterFunc("SetDebugForceFieldsEnabled", SetDebugForceFieldsEnabled); - wiLua::RegisterFunc("SetVSyncEnabled", SetVSyncEnabled); - wiLua::RegisterFunc("SetResolution", SetResolution); - wiLua::RegisterFunc("SetDebugLightCulling", SetDebugLightCulling); - wiLua::RegisterFunc("SetOcclusionCullingEnabled", SetOcclusionCullingEnabled); + wi::lua::RegisterFunc("SetShadowProps2D", SetShadowProps2D); + wi::lua::RegisterFunc("SetShadowPropsCube", SetShadowPropsCube); + wi::lua::RegisterFunc("SetDebugBoxesEnabled", SetDebugBoxesEnabled); + wi::lua::RegisterFunc("SetDebugPartitionTreeEnabled", SetDebugPartitionTreeEnabled); + wi::lua::RegisterFunc("SetDebugBonesEnabled", SetDebugBonesEnabled); + wi::lua::RegisterFunc("SetDebugEmittersEnabled", SetDebugEmittersEnabled); + wi::lua::RegisterFunc("SetDebugForceFieldsEnabled", SetDebugForceFieldsEnabled); + wi::lua::RegisterFunc("SetVSyncEnabled", SetVSyncEnabled); + wi::lua::RegisterFunc("SetResolution", SetResolution); + wi::lua::RegisterFunc("SetDebugLightCulling", SetDebugLightCulling); + wi::lua::RegisterFunc("SetOcclusionCullingEnabled", SetOcclusionCullingEnabled); - wiLua::RegisterFunc("DrawLine", DrawLine); - wiLua::RegisterFunc("DrawPoint", DrawPoint); - wiLua::RegisterFunc("DrawBox", DrawBox); - wiLua::RegisterFunc("DrawSphere", DrawSphere); - wiLua::RegisterFunc("DrawCapsule", DrawCapsule); - wiLua::RegisterFunc("PutWaterRipple", PutWaterRipple); + wi::lua::RegisterFunc("DrawLine", DrawLine); + wi::lua::RegisterFunc("DrawPoint", DrawPoint); + wi::lua::RegisterFunc("DrawBox", DrawBox); + wi::lua::RegisterFunc("DrawSphere", DrawSphere); + wi::lua::RegisterFunc("DrawCapsule", DrawCapsule); + wi::lua::RegisterFunc("PutWaterRipple", PutWaterRipple); - wiLua::RunText("PICK_VOID = 0"); - wiLua::RunText("PICK_OPAQUE = 1"); - wiLua::RunText("PICK_TRANSPARENT = 2"); - wiLua::RunText("PICK_WATER = 4"); + wi::lua::RunText("PICK_VOID = 0"); + wi::lua::RunText("PICK_OPAQUE = 1"); + wi::lua::RunText("PICK_TRANSPARENT = 2"); + wi::lua::RunText("PICK_WATER = 4"); - wiLua::RegisterFunc("ClearWorld", ClearWorld); - wiLua::RegisterFunc("ReloadShaders", ReloadShaders); + wi::lua::RegisterFunc("ClearWorld", ClearWorld); + wi::lua::RegisterFunc("ReloadShaders", ReloadShaders); } } }; diff --git a/WickedEngine/wiRenderer_BindLua.h b/WickedEngine/wiRenderer_BindLua.h index cb48834de..3775b77ba 100644 --- a/WickedEngine/wiRenderer_BindLua.h +++ b/WickedEngine/wiRenderer_BindLua.h @@ -1,7 +1,7 @@ #pragma once #include "wiLua.h" -namespace wiRenderer_BindLua +namespace wi::lua::renderer { void Bind(); }; diff --git a/WickedEngine/wiResourceManager.cpp b/WickedEngine/wiResourceManager.cpp index 66892d49b..06f91369c 100644 --- a/WickedEngine/wiResourceManager.cpp +++ b/WickedEngine/wiResourceManager.cpp @@ -12,663 +12,738 @@ extern basist::etc1_global_selector_codebook g_basis_global_codebook; #include #include -using namespace wiGraphics; +using namespace wi::graphics; -namespace wiResourceManager +namespace wi { - std::mutex locker; - wi::unordered_map> resources; - MODE mode = MODE_DISCARD_FILEDATA_AFTER_LOAD; - - void SetMode(MODE param) + struct ResourceInternal { - mode = param; - } - MODE GetMode() - { - return mode; - } - - static const wi::unordered_map types = { - std::make_pair("BASIS", wiResource::IMAGE), - std::make_pair("KTX2", wiResource::IMAGE), - std::make_pair("JPG", wiResource::IMAGE), - std::make_pair("JPEG", wiResource::IMAGE), - std::make_pair("PNG", wiResource::IMAGE), - std::make_pair("BMP", wiResource::IMAGE), - std::make_pair("DDS", wiResource::IMAGE), - std::make_pair("TGA", wiResource::IMAGE), - std::make_pair("WAV", wiResource::SOUND), - std::make_pair("OGG", wiResource::SOUND), + resourcemanager::Flags flags = resourcemanager::Flags::NONE; + wi::graphics::Texture texture; + wi::audio::Sound sound; + wi::vector filedata; }; - wi::vector GetSupportedImageExtensions() + + const wi::vector& Resource::GetFileData() const { - wi::vector ret; - for (auto& x : types) - { - if (x.second == wiResource::IMAGE) - { - ret.push_back(x.first); - } - } - return ret; + const ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + return resourceinternal->filedata; } - wi::vector GetSupportedSoundExtensions() + const wi::graphics::Texture& Resource::GetTexture() const { - wi::vector ret; - for (auto& x : types) - { - if (x.second == wiResource::SOUND) - { - ret.push_back(x.first); - } - } - return ret; + const ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + return resourceinternal->texture; + } + const wi::audio::Sound& Resource::GetSound() const + { + const ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + return resourceinternal->sound; } - std::shared_ptr Load(const std::string& name, uint32_t flags, const uint8_t* filedata, size_t filesize) + void Resource::SetFileData(const wi::vector& data) { - if (mode == MODE_DISCARD_FILEDATA_AFTER_LOAD) + if (internal_state == nullptr) { - flags &= ~IMPORT_RETAIN_FILEDATA; + internal_state = std::make_shared(); + } + ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + resourceinternal->filedata = data; + } + void Resource::SetFileData(wi::vector&& data) + { + if (internal_state == nullptr) + { + internal_state = std::make_shared(); + } + ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + resourceinternal->filedata = data; + } + void Resource::SetTexture(const wi::graphics::Texture& texture) + { + if (internal_state == nullptr) + { + internal_state = std::make_shared(); + } + ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + resourceinternal->texture = texture; + } + void Resource::SetSound(const wi::audio::Sound& sound) + { + if (internal_state == nullptr) + { + internal_state = std::make_shared(); + } + ResourceInternal* resourceinternal = (ResourceInternal*)internal_state.get(); + resourceinternal->sound = sound; + } + + namespace resourcemanager + { + static std::mutex locker; + static wi::unordered_map> resources; + static Mode mode = Mode::DISCARD_FILEDATA_AFTER_LOAD; + + void SetMode(Mode param) + { + mode = param; + } + Mode GetMode() + { + return mode; } - locker.lock(); - std::weak_ptr& weak_resource = resources[name]; - std::shared_ptr resource = weak_resource.lock(); - - static bool basis_init = false; // within lock! - if (!basis_init) + enum class DataType { - basis_init = true; - basist::basisu_transcoder_init(); - } - - if (resource == nullptr) + IMAGE, + SOUND, + }; + static const wi::unordered_map types = { + std::make_pair("BASIS", DataType::IMAGE), + std::make_pair("KTX2", DataType::IMAGE), + std::make_pair("JPG", DataType::IMAGE), + std::make_pair("JPEG", DataType::IMAGE), + std::make_pair("PNG", DataType::IMAGE), + std::make_pair("BMP", DataType::IMAGE), + std::make_pair("DDS", DataType::IMAGE), + std::make_pair("TGA", DataType::IMAGE), + std::make_pair("WAV", DataType::SOUND), + std::make_pair("OGG", DataType::SOUND), + }; + wi::vector GetSupportedImageExtensions() { - resource = std::make_shared(); - resources[name] = resource; - locker.unlock(); - } - else - { - locker.unlock(); - return resource; - } - - if (filedata == nullptr || filesize == 0) - { - if (!wiHelper::FileRead(name, resource->filedata)) + wi::vector ret; + for (auto& x : types) { - resource.reset(); - return nullptr; + if (x.second == DataType::IMAGE) + { + ret.push_back(x.first); + } } - filedata = resource->filedata.data(); - filesize = resource->filedata.size(); + return ret; + } + wi::vector GetSupportedSoundExtensions() + { + wi::vector ret; + for (auto& x : types) + { + if (x.second == DataType::SOUND) + { + ret.push_back(x.first); + } + } + return ret; } - std::string ext = wiHelper::toUpper(wiHelper::GetExtensionFromFileName(name)); - wiResource::DATA_TYPE type; - - // dynamic type selection: + Resource Load(const std::string& name, Flags flags, const uint8_t* filedata, size_t filesize) { - auto it = types.find(ext); - if (it != types.end()) + if (mode == Mode::DISCARD_FILEDATA_AFTER_LOAD) { - type = it->second; + flags &= ~Flags::IMPORT_RETAIN_FILEDATA; + } + + locker.lock(); + std::weak_ptr& weak_resource = resources[name]; + std::shared_ptr resource = weak_resource.lock(); + + static bool basis_init = false; // within lock! + if (!basis_init) + { + basis_init = true; + basist::basisu_transcoder_init(); + } + + if (resource == nullptr) + { + resource = std::make_shared(); + resources[name] = resource; + locker.unlock(); } else { - return nullptr; + locker.unlock(); + Resource retVal; + retVal.internal_state = resource; + return retVal; } - } - bool success = false; - - switch (type) - { - case wiResource::IMAGE: - { - GraphicsDevice* device = wiGraphics::GetDevice(); - if (!ext.compare("KTX2")) + if (filedata == nullptr || filesize == 0) { - basist::ktx2_transcoder transcoder(&g_basis_global_codebook); - if (transcoder.init(filedata, (uint32_t)filesize)) + if (!wi::helper::FileRead(name, resource->filedata)) { - TextureDesc desc; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - desc.width = transcoder.get_width(); - desc.height = transcoder.get_height(); - desc.array_size = std::max(desc.array_size, transcoder.get_layers() * transcoder.get_faces()); - desc.mip_levels = transcoder.get_levels(); - if (transcoder.get_faces() == 6) - { - desc.misc_flags = ResourceMiscFlag::TEXTURECUBE; - } + resource.reset(); + return Resource(); + } + filedata = resource->filedata.data(); + filesize = resource->filedata.size(); + } - basist::transcoder_texture_format fmt; - if (transcoder.get_has_alpha()) - { - fmt = basist::transcoder_texture_format::cTFBC3_RGBA; - desc.format = Format::BC3_UNORM; - } - else - { - fmt = basist::transcoder_texture_format::cTFBC1_RGB; - desc.format = Format::BC1_UNORM; - } - uint32_t bytes_per_block = basis_get_bytes_per_block_or_pixel(fmt); + std::string ext = wi::helper::toUpper(wi::helper::GetExtensionFromFileName(name)); + DataType type; - if (transcoder.start_transcoding()) - { - // all subresources will use one allocation for transcoder destination, so compute combined size: - size_t transcoded_data_size = 0; - for (uint32_t layer = 0; layer < std::max(1u, transcoder.get_layers()); ++layer) - { - for (uint32_t face = 0; face < transcoder.get_faces(); ++face) - { - for (uint32_t mip = 0; mip < transcoder.get_levels(); ++mip) - { - basist::ktx2_image_level_info level_info; - if (transcoder.get_image_level_info(level_info, mip, layer, face)) - { - transcoded_data_size += level_info.m_total_blocks * bytes_per_block; - } - } - } - } - wi::vector transcoded_data(transcoded_data_size); - - wi::vector InitData; - size_t transcoded_data_offset = 0; - for (uint32_t layer = 0; layer < std::max(1u, transcoder.get_layers()); ++layer) - { - for (uint32_t face = 0; face < transcoder.get_faces(); ++face) - { - for (uint32_t mip = 0; mip < transcoder.get_levels(); ++mip) - { - basist::ktx2_image_level_info level_info; - if (transcoder.get_image_level_info(level_info, mip, layer, face)) - { - void* data_ptr = transcoded_data.data() + transcoded_data_offset; - transcoded_data_offset += level_info.m_total_blocks * bytes_per_block; - if (transcoder.transcode_image_level( - mip, layer, face, - data_ptr, - level_info.m_total_blocks, - fmt - )) - { - SubresourceData subresourceData; - subresourceData.data_ptr = data_ptr; - subresourceData.row_pitch = level_info.m_num_blocks_x * bytes_per_block; - subresourceData.slice_pitch = subresourceData.row_pitch * level_info.m_num_blocks_y; - InitData.push_back(subresourceData); - } - } - } - } - } - - if (!InitData.empty()) - { - success = device->CreateTexture(&desc, InitData.data(), &resource->texture); - device->SetName(&resource->texture, name.c_str()); - } - } - transcoder.clear(); + // dynamic type selection: + { + auto it = types.find(ext); + if (it != types.end()) + { + type = it->second; + } + else + { + return Resource(); } } - else if (!ext.compare("BASIS")) + + bool success = false; + + switch (type) { - basist::basisu_transcoder transcoder(&g_basis_global_codebook); - if (transcoder.validate_header(filedata, (uint32_t)filesize)) + case DataType::IMAGE: + { + GraphicsDevice* device = wi::graphics::GetDevice(); + if (!ext.compare("KTX2")) { - basist::basisu_file_info fileInfo; - if (transcoder.get_file_info(filedata, (uint32_t)filesize, fileInfo)) + basist::ktx2_transcoder transcoder(&g_basis_global_codebook); + if (transcoder.init(filedata, (uint32_t)filesize)) { - uint32_t image_index = 0; - basist::basisu_image_info info; - if (transcoder.get_image_info(filedata, (uint32_t)filesize, info, image_index)) + TextureDesc desc; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + desc.width = transcoder.get_width(); + desc.height = transcoder.get_height(); + desc.array_size = std::max(desc.array_size, transcoder.get_layers() * transcoder.get_faces()); + desc.mip_levels = transcoder.get_levels(); + if (transcoder.get_faces() == 6) { - TextureDesc desc; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - desc.width = info.m_width; - desc.height = info.m_height; - desc.mip_levels = info.m_total_levels; - - basist::transcoder_texture_format fmt; - if (info.m_alpha_flag) - { - fmt = basist::transcoder_texture_format::cTFBC3_RGBA; - desc.format = Format::BC3_UNORM; - } - else - { - fmt = basist::transcoder_texture_format::cTFBC1_RGB; - desc.format = Format::BC1_UNORM; - } - uint32_t bytes_per_block = basis_get_bytes_per_block_or_pixel(fmt); - - if (transcoder.start_transcoding(filedata, (uint32_t)filesize)) - { - // all subresources will use one allocation for transcoder destination, so compute combined size: - size_t transcoded_data_size = 0; - for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) - { - basist::basisu_image_level_info level_info; - if (transcoder.get_image_level_info(filedata, (uint32_t)filesize, level_info, image_index, mip)) - { - transcoded_data_size += level_info.m_total_blocks * bytes_per_block; - } - } - wi::vector transcoded_data(transcoded_data_size); - - wi::vector InitData; - size_t transcoded_data_offset = 0; - for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) - { - basist::basisu_image_level_info level_info; - if (transcoder.get_image_level_info(filedata, (uint32_t)filesize, level_info, 0, mip)) - { - void* data_ptr = transcoded_data.data() + transcoded_data_offset; - transcoded_data_offset += level_info.m_total_blocks * bytes_per_block; - if (transcoder.transcode_image_level( - filedata, (uint32_t)filesize, image_index, - mip, - data_ptr, - info.m_total_blocks, - fmt - )) - { - SubresourceData subresourceData; - subresourceData.data_ptr = data_ptr; - subresourceData.row_pitch = level_info.m_num_blocks_x * bytes_per_block; - subresourceData.slice_pitch = subresourceData.row_pitch * level_info.m_num_blocks_y; - InitData.push_back(subresourceData); - } - } - } - - if (!InitData.empty()) - { - success = device->CreateTexture(&desc, InitData.data(), &resource->texture); - device->SetName(&resource->texture, name.c_str()); - } - } + desc.misc_flags = ResourceMiscFlag::TEXTURECUBE; } - } - } - } - else if (!ext.compare("DDS")) - { - // Load dds - tinyddsloader::DDSFile dds; - auto result = dds.Load(filedata, filesize); - - if (result == tinyddsloader::Result::Success) - { - TextureDesc desc; - desc.array_size = 1; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - desc.width = dds.GetWidth(); - desc.height = dds.GetHeight(); - desc.depth = dds.GetDepth(); - desc.mip_levels = dds.GetMipCount(); - desc.array_size = dds.GetArraySize(); - desc.format = Format::R8G8B8A8_UNORM; - desc.layout = ResourceState::SHADER_RESOURCE; - - if (dds.IsCubemap()) - { - desc.misc_flags |= ResourceMiscFlag::TEXTURECUBE; - } - - auto ddsFormat = dds.GetFormat(); - - switch (ddsFormat) - { - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_Float: desc.format = Format::R32G32B32A32_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_UInt: desc.format = Format::R32G32B32A32_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_SInt: desc.format = Format::R32G32B32A32_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_Float: desc.format = Format::R32G32B32_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_UInt: desc.format = Format::R32G32B32_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_SInt: desc.format = Format::R32G32B32_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_Float: desc.format = Format::R16G16B16A16_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_UNorm: desc.format = Format::R16G16B16A16_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_UInt: desc.format = Format::R16G16B16A16_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_SNorm: desc.format = Format::R16G16B16A16_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_SInt: desc.format = Format::R16G16B16A16_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32_Float: desc.format = Format::R32G32_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32_UInt: desc.format = Format::R32G32_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32G32_SInt: desc.format = Format::R32G32_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R10G10B10A2_UNorm: desc.format = Format::R10G10B10A2_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R10G10B10A2_UInt: desc.format = Format::R10G10B10A2_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R11G11B10_Float: desc.format = Format::R11G11B10_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm: desc.format = Format::B8G8R8A8_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm_SRGB: desc.format = Format::B8G8R8A8_UNORM_SRGB; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm: desc.format = Format::R8G8B8A8_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm_SRGB: desc.format = Format::R8G8B8A8_UNORM_SRGB; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UInt: desc.format = Format::R8G8B8A8_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_SNorm: desc.format = Format::R8G8B8A8_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_SInt: desc.format = Format::R8G8B8A8_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16_Float: desc.format = Format::R16G16_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16_UNorm: desc.format = Format::R16G16_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16_UInt: desc.format = Format::R16G16_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16_SNorm: desc.format = Format::R16G16_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16G16_SInt: desc.format = Format::R16G16_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::D32_Float: desc.format = Format::D32_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32_Float: desc.format = Format::R32_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32_UInt: desc.format = Format::R32_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R32_SInt: desc.format = Format::R32_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8_UNorm: desc.format = Format::R8G8_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8_UInt: desc.format = Format::R8G8_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8_SNorm: desc.format = Format::R8G8_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8G8_SInt: desc.format = Format::R8G8_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16_Float: desc.format = Format::R16_FLOAT; break; - case tinyddsloader::DDSFile::DXGIFormat::D16_UNorm: desc.format = Format::D16_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16_UNorm: desc.format = Format::R16_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16_UInt: desc.format = Format::R16_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R16_SNorm: desc.format = Format::R16_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R16_SInt: desc.format = Format::R16_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R8_UNorm: desc.format = Format::R8_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8_UInt: desc.format = Format::R8_UINT; break; - case tinyddsloader::DDSFile::DXGIFormat::R8_SNorm: desc.format = Format::R8_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::R8_SInt: desc.format = Format::R8_SINT; break; - case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm: desc.format = Format::BC1_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm_SRGB: desc.format = Format::BC1_UNORM_SRGB; break; - case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm: desc.format = Format::BC2_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm_SRGB: desc.format = Format::BC2_UNORM_SRGB; break; - case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm: desc.format = Format::BC3_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm_SRGB: desc.format = Format::BC3_UNORM_SRGB; break; - case tinyddsloader::DDSFile::DXGIFormat::BC4_UNorm: desc.format = Format::BC4_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC4_SNorm: desc.format = Format::BC4_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC5_UNorm: desc.format = Format::BC5_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC5_SNorm: desc.format = Format::BC5_SNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC7_UNorm: desc.format = Format::BC7_UNORM; break; - case tinyddsloader::DDSFile::DXGIFormat::BC7_UNorm_SRGB: desc.format = Format::BC7_UNORM_SRGB; break; - default: - assert(0); // incoming format is not supported - break; - } - - wi::vector InitData; - for (uint32_t arrayIndex = 0; arrayIndex < desc.array_size; ++arrayIndex) - { - for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + basist::transcoder_texture_format fmt; + if (transcoder.get_has_alpha()) { - auto imageData = dds.GetImageData(mip, arrayIndex); - SubresourceData subresourceData; - subresourceData.data_ptr = imageData->m_mem; - subresourceData.row_pitch = imageData->m_memPitch; - subresourceData.slice_pitch = imageData->m_memSlicePitch; - InitData.push_back(subresourceData); - } - } - - auto dim = dds.GetTextureDimension(); - switch (dim) - { - case tinyddsloader::DDSFile::TextureDimension::Texture1D: - { - desc.type = TextureDesc::Type::TEXTURE_1D; - } - break; - case tinyddsloader::DDSFile::TextureDimension::Texture2D: - { - desc.type = TextureDesc::Type::TEXTURE_2D; - } - break; - case tinyddsloader::DDSFile::TextureDimension::Texture3D: - { - desc.type = TextureDesc::Type::TEXTURE_3D; - } - break; - default: - assert(0); - break; - } - - if (IsFormatBlockCompressed(desc.format)) - { - desc.width = std::max(GetFormatBlockSize(desc.format), desc.width); - desc.height = std::max(GetFormatBlockSize(desc.format), desc.height); - } - - success = device->CreateTexture(&desc, InitData.data(), &resource->texture); - device->SetName(&resource->texture, name.c_str()); - } - else assert(0); // failed to load DDS - - } - else - { - // png, tga, jpg, etc. loader: - - const int channelCount = 4; - int width, height, bpp; - unsigned char* rgb = stbi_load_from_memory(filedata, (int)filesize, &width, &height, &bpp, channelCount); - - if (rgb != nullptr) - { - TextureDesc desc; - desc.height = uint32_t(height); - desc.width = uint32_t(width); - desc.layout = ResourceState::SHADER_RESOURCE; - - if (flags & IMPORT_COLORGRADINGLUT) - { - if (desc.type != TextureDesc::Type::TEXTURE_2D || - desc.width != 256 || - desc.height != 16) - { - wiHelper::messageBox("The Dimensions must be 256 x 16 for color grading LUT!", "Error"); + fmt = basist::transcoder_texture_format::cTFBC3_RGBA; + desc.format = Format::BC3_UNORM; } else { - uint32_t data[16 * 16 * 16]; - int pixel = 0; - for (int z = 0; z < 16; ++z) + fmt = basist::transcoder_texture_format::cTFBC1_RGB; + desc.format = Format::BC1_UNORM; + } + uint32_t bytes_per_block = basis_get_bytes_per_block_or_pixel(fmt); + + if (transcoder.start_transcoding()) + { + // all subresources will use one allocation for transcoder destination, so compute combined size: + size_t transcoded_data_size = 0; + for (uint32_t layer = 0; layer < std::max(1u, transcoder.get_layers()); ++layer) { - for (int y = 0; y < 16; ++y) + for (uint32_t face = 0; face < transcoder.get_faces(); ++face) { - for (int x = 0; x < 16; ++x) + for (uint32_t mip = 0; mip < transcoder.get_levels(); ++mip) { - int coord = x + y * 256 + z * 16; - data[pixel++] = ((uint32_t*)rgb)[coord]; + basist::ktx2_image_level_info level_info; + if (transcoder.get_image_level_info(level_info, mip, layer, face)) + { + transcoded_data_size += level_info.m_total_blocks * bytes_per_block; + } + } + } + } + wi::vector transcoded_data(transcoded_data_size); + + wi::vector InitData; + size_t transcoded_data_offset = 0; + for (uint32_t layer = 0; layer < std::max(1u, transcoder.get_layers()); ++layer) + { + for (uint32_t face = 0; face < transcoder.get_faces(); ++face) + { + for (uint32_t mip = 0; mip < transcoder.get_levels(); ++mip) + { + basist::ktx2_image_level_info level_info; + if (transcoder.get_image_level_info(level_info, mip, layer, face)) + { + void* data_ptr = transcoded_data.data() + transcoded_data_offset; + transcoded_data_offset += level_info.m_total_blocks * bytes_per_block; + if (transcoder.transcode_image_level( + mip, layer, face, + data_ptr, + level_info.m_total_blocks, + fmt + )) + { + SubresourceData subresourceData; + subresourceData.data_ptr = data_ptr; + subresourceData.row_pitch = level_info.m_num_blocks_x * bytes_per_block; + subresourceData.slice_pitch = subresourceData.row_pitch * level_info.m_num_blocks_y; + InitData.push_back(subresourceData); + } + } } } } - desc.type = TextureDesc::Type::TEXTURE_3D; - desc.width = 16; - desc.height = 16; - desc.depth = 16; - desc.format = Format::R8G8B8A8_UNORM; - desc.bind_flags = BindFlag::SHADER_RESOURCE; - SubresourceData InitData; - InitData.data_ptr = data; - InitData.row_pitch = 16 * sizeof(uint32_t); - InitData.slice_pitch = 16 * InitData.row_pitch; - success = device->CreateTexture(&desc, &InitData, &resource->texture); - device->SetName(&resource->texture, name.c_str()); + if (!InitData.empty()) + { + success = device->CreateTexture(&desc, InitData.data(), &resource->texture); + device->SetName(&resource->texture, name.c_str()); + } + } + transcoder.clear(); + } + } + else if (!ext.compare("BASIS")) + { + basist::basisu_transcoder transcoder(&g_basis_global_codebook); + if (transcoder.validate_header(filedata, (uint32_t)filesize)) + { + basist::basisu_file_info fileInfo; + if (transcoder.get_file_info(filedata, (uint32_t)filesize, fileInfo)) + { + uint32_t image_index = 0; + basist::basisu_image_info info; + if (transcoder.get_image_info(filedata, (uint32_t)filesize, info, image_index)) + { + TextureDesc desc; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + desc.width = info.m_width; + desc.height = info.m_height; + desc.mip_levels = info.m_total_levels; + + basist::transcoder_texture_format fmt; + if (info.m_alpha_flag) + { + fmt = basist::transcoder_texture_format::cTFBC3_RGBA; + desc.format = Format::BC3_UNORM; + } + else + { + fmt = basist::transcoder_texture_format::cTFBC1_RGB; + desc.format = Format::BC1_UNORM; + } + uint32_t bytes_per_block = basis_get_bytes_per_block_or_pixel(fmt); + + if (transcoder.start_transcoding(filedata, (uint32_t)filesize)) + { + // all subresources will use one allocation for transcoder destination, so compute combined size: + size_t transcoded_data_size = 0; + for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + { + basist::basisu_image_level_info level_info; + if (transcoder.get_image_level_info(filedata, (uint32_t)filesize, level_info, image_index, mip)) + { + transcoded_data_size += level_info.m_total_blocks * bytes_per_block; + } + } + wi::vector transcoded_data(transcoded_data_size); + + wi::vector InitData; + size_t transcoded_data_offset = 0; + for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + { + basist::basisu_image_level_info level_info; + if (transcoder.get_image_level_info(filedata, (uint32_t)filesize, level_info, 0, mip)) + { + void* data_ptr = transcoded_data.data() + transcoded_data_offset; + transcoded_data_offset += level_info.m_total_blocks * bytes_per_block; + if (transcoder.transcode_image_level( + filedata, (uint32_t)filesize, image_index, + mip, + data_ptr, + info.m_total_blocks, + fmt + )) + { + SubresourceData subresourceData; + subresourceData.data_ptr = data_ptr; + subresourceData.row_pitch = level_info.m_num_blocks_x * bytes_per_block; + subresourceData.slice_pitch = subresourceData.row_pitch * level_info.m_num_blocks_y; + InitData.push_back(subresourceData); + } + } + } + + if (!InitData.empty()) + { + success = device->CreateTexture(&desc, InitData.data(), &resource->texture); + device->SetName(&resource->texture, name.c_str()); + } + } + } } } - else + } + else if (!ext.compare("DDS")) + { + // Load dds + + tinyddsloader::DDSFile dds; + auto result = dds.Load(filedata, filesize); + + if (result == tinyddsloader::Result::Success) { - desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + TextureDesc desc; + desc.array_size = 1; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + desc.width = dds.GetWidth(); + desc.height = dds.GetHeight(); + desc.depth = dds.GetDepth(); + desc.mip_levels = dds.GetMipCount(); + desc.array_size = dds.GetArraySize(); desc.format = Format::R8G8B8A8_UNORM; - desc.mip_levels = (uint32_t)log2(std::max(width, height)) + 1; - desc.usage = Usage::DEFAULT; desc.layout = ResourceState::SHADER_RESOURCE; - uint32_t mipwidth = width; - wi::vector InitData(desc.mip_levels); - for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + if (dds.IsCubemap()) { - InitData[mip].data_ptr = rgb; // attention! we don't fill the mips here correctly, just always point to the mip0 data by default. Mip levels will be created using compute shader when needed! - InitData[mip].row_pitch = static_cast(mipwidth * channelCount); - mipwidth = std::max(1u, mipwidth / 2); + desc.misc_flags |= ResourceMiscFlag::TEXTURECUBE; + } + + auto ddsFormat = dds.GetFormat(); + + switch (ddsFormat) + { + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_Float: desc.format = Format::R32G32B32A32_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_UInt: desc.format = Format::R32G32B32A32_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32A32_SInt: desc.format = Format::R32G32B32A32_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_Float: desc.format = Format::R32G32B32_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_UInt: desc.format = Format::R32G32B32_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32B32_SInt: desc.format = Format::R32G32B32_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_Float: desc.format = Format::R16G16B16A16_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_UNorm: desc.format = Format::R16G16B16A16_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_UInt: desc.format = Format::R16G16B16A16_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_SNorm: desc.format = Format::R16G16B16A16_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16B16A16_SInt: desc.format = Format::R16G16B16A16_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32_Float: desc.format = Format::R32G32_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32_UInt: desc.format = Format::R32G32_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32G32_SInt: desc.format = Format::R32G32_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R10G10B10A2_UNorm: desc.format = Format::R10G10B10A2_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R10G10B10A2_UInt: desc.format = Format::R10G10B10A2_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R11G11B10_Float: desc.format = Format::R11G11B10_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm: desc.format = Format::B8G8R8A8_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::B8G8R8A8_UNorm_SRGB: desc.format = Format::B8G8R8A8_UNORM_SRGB; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm: desc.format = Format::R8G8B8A8_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UNorm_SRGB: desc.format = Format::R8G8B8A8_UNORM_SRGB; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_UInt: desc.format = Format::R8G8B8A8_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_SNorm: desc.format = Format::R8G8B8A8_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8B8A8_SInt: desc.format = Format::R8G8B8A8_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16_Float: desc.format = Format::R16G16_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16_UNorm: desc.format = Format::R16G16_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16_UInt: desc.format = Format::R16G16_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16_SNorm: desc.format = Format::R16G16_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16G16_SInt: desc.format = Format::R16G16_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::D32_Float: desc.format = Format::D32_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32_Float: desc.format = Format::R32_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32_UInt: desc.format = Format::R32_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R32_SInt: desc.format = Format::R32_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8_UNorm: desc.format = Format::R8G8_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8_UInt: desc.format = Format::R8G8_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8_SNorm: desc.format = Format::R8G8_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8G8_SInt: desc.format = Format::R8G8_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16_Float: desc.format = Format::R16_FLOAT; break; + case tinyddsloader::DDSFile::DXGIFormat::D16_UNorm: desc.format = Format::D16_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16_UNorm: desc.format = Format::R16_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16_UInt: desc.format = Format::R16_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R16_SNorm: desc.format = Format::R16_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R16_SInt: desc.format = Format::R16_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R8_UNorm: desc.format = Format::R8_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8_UInt: desc.format = Format::R8_UINT; break; + case tinyddsloader::DDSFile::DXGIFormat::R8_SNorm: desc.format = Format::R8_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::R8_SInt: desc.format = Format::R8_SINT; break; + case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm: desc.format = Format::BC1_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC1_UNorm_SRGB: desc.format = Format::BC1_UNORM_SRGB; break; + case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm: desc.format = Format::BC2_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC2_UNorm_SRGB: desc.format = Format::BC2_UNORM_SRGB; break; + case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm: desc.format = Format::BC3_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC3_UNorm_SRGB: desc.format = Format::BC3_UNORM_SRGB; break; + case tinyddsloader::DDSFile::DXGIFormat::BC4_UNorm: desc.format = Format::BC4_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC4_SNorm: desc.format = Format::BC4_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC5_UNorm: desc.format = Format::BC5_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC5_SNorm: desc.format = Format::BC5_SNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC7_UNorm: desc.format = Format::BC7_UNORM; break; + case tinyddsloader::DDSFile::DXGIFormat::BC7_UNorm_SRGB: desc.format = Format::BC7_UNORM_SRGB; break; + default: + assert(0); // incoming format is not supported + break; + } + + wi::vector InitData; + for (uint32_t arrayIndex = 0; arrayIndex < desc.array_size; ++arrayIndex) + { + for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + { + auto imageData = dds.GetImageData(mip, arrayIndex); + SubresourceData subresourceData; + subresourceData.data_ptr = imageData->m_mem; + subresourceData.row_pitch = imageData->m_memPitch; + subresourceData.slice_pitch = imageData->m_memSlicePitch; + InitData.push_back(subresourceData); + } + } + + auto dim = dds.GetTextureDimension(); + switch (dim) + { + case tinyddsloader::DDSFile::TextureDimension::Texture1D: + { + desc.type = TextureDesc::Type::TEXTURE_1D; + } + break; + case tinyddsloader::DDSFile::TextureDimension::Texture2D: + { + desc.type = TextureDesc::Type::TEXTURE_2D; + } + break; + case tinyddsloader::DDSFile::TextureDimension::Texture3D: + { + desc.type = TextureDesc::Type::TEXTURE_3D; + } + break; + default: + assert(0); + break; + } + + if (IsFormatBlockCompressed(desc.format)) + { + desc.width = std::max(GetFormatBlockSize(desc.format), desc.width); + desc.height = std::max(GetFormatBlockSize(desc.format), desc.height); } success = device->CreateTexture(&desc, InitData.data(), &resource->texture); device->SetName(&resource->texture, name.c_str()); + } + else assert(0); // failed to load DDS - for (uint32_t i = 0; i < resource->texture.desc.mip_levels; ++i) + } + else + { + // png, tga, jpg, etc. loader: + + const int channelCount = 4; + int width, height, bpp; + unsigned char* rgb = stbi_load_from_memory(filedata, (int)filesize, &width, &height, &bpp, channelCount); + + if (rgb != nullptr) + { + TextureDesc desc; + desc.height = uint32_t(height); + desc.width = uint32_t(width); + desc.layout = ResourceState::SHADER_RESOURCE; + + if (has_flag(flags, Flags::IMPORT_COLORGRADINGLUT)) { - int subresource_index; - subresource_index = device->CreateSubresource(&resource->texture, SubresourceType::SRV, 0, 1, i, 1); - assert(subresource_index == i); - subresource_index = device->CreateSubresource(&resource->texture, SubresourceType::UAV, 0, 1, i, 1); - assert(subresource_index == i); + if (desc.type != TextureDesc::Type::TEXTURE_2D || + desc.width != 256 || + desc.height != 16) + { + wi::helper::messageBox("The Dimensions must be 256 x 16 for color grading LUT!", "Error"); + } + else + { + uint32_t data[16 * 16 * 16]; + int pixel = 0; + for (int z = 0; z < 16; ++z) + { + for (int y = 0; y < 16; ++y) + { + for (int x = 0; x < 16; ++x) + { + int coord = x + y * 256 + z * 16; + data[pixel++] = ((uint32_t*)rgb)[coord]; + } + } + } + + desc.type = TextureDesc::Type::TEXTURE_3D; + desc.width = 16; + desc.height = 16; + desc.depth = 16; + desc.format = Format::R8G8B8A8_UNORM; + desc.bind_flags = BindFlag::SHADER_RESOURCE; + SubresourceData InitData; + InitData.data_ptr = data; + InitData.row_pitch = 16 * sizeof(uint32_t); + InitData.slice_pitch = 16 * InitData.row_pitch; + success = device->CreateTexture(&desc, &InitData, &resource->texture); + device->SetName(&resource->texture, name.c_str()); + } + } + else + { + desc.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; + desc.format = Format::R8G8B8A8_UNORM; + desc.mip_levels = (uint32_t)log2(std::max(width, height)) + 1; + desc.usage = Usage::DEFAULT; + desc.layout = ResourceState::SHADER_RESOURCE; + + uint32_t mipwidth = width; + wi::vector InitData(desc.mip_levels); + for (uint32_t mip = 0; mip < desc.mip_levels; ++mip) + { + InitData[mip].data_ptr = rgb; // attention! we don't fill the mips here correctly, just always point to the mip0 data by default. Mip levels will be created using compute shader when needed! + InitData[mip].row_pitch = static_cast(mipwidth * channelCount); + mipwidth = std::max(1u, mipwidth / 2); + } + + success = device->CreateTexture(&desc, InitData.data(), &resource->texture); + device->SetName(&resource->texture, name.c_str()); + + for (uint32_t i = 0; i < resource->texture.desc.mip_levels; ++i) + { + int subresource_index; + subresource_index = device->CreateSubresource(&resource->texture, SubresourceType::SRV, 0, 1, i, 1); + assert(subresource_index == i); + subresource_index = device->CreateSubresource(&resource->texture, SubresourceType::UAV, 0, 1, i, 1); + assert(subresource_index == i); + } } } + stbi_image_free(rgb); } - stbi_image_free(rgb); } - } - break; - case wiResource::SOUND: - { - success = wiAudio::CreateSound(filedata, filesize, &resource->sound); - } - break; - }; - - if (success) - { - resource->type = type; - resource->flags = flags; - - if (resource->filedata.empty() && (flags & IMPORT_RETAIN_FILEDATA)) + break; + case DataType::SOUND: { - // resource was loaded with external filedata, and we want to retain filedata - resource->filedata.resize(filesize); - std::memcpy(resource->filedata.data(), filedata, filesize); + success = wi::audio::CreateSound(filedata, filesize, &resource->sound); } - else if (!resource->filedata.empty() && (flags & IMPORT_RETAIN_FILEDATA) == 0) - { - // resource was loaded using file name, and we want to discard filedata - resource->filedata.clear(); - } - - if (type == wiResource::IMAGE && resource->texture.desc.mip_levels > 1 - && has_flag(resource->texture.desc.bind_flags, BindFlag::UNORDERED_ACCESS)) - { - wiRenderer::AddDeferredMIPGen(resource, true); - } - - return resource; - } - - return nullptr; - } - - bool Contains(const std::string& name) - { - bool result = false; - locker.lock(); - auto it = resources.find(name); - if (it != resources.end()) - { - auto resource = it->second.lock(); - result = resource != nullptr && resource->type != wiResource::EMPTY; - } - locker.unlock(); - return result; - } - - void Clear() - { - locker.lock(); - resources.clear(); - locker.unlock(); - } - - - void Serialize(wiArchive& archive, ResourceSerializer& seri) - { - if (archive.IsReadMode()) - { - size_t serializable_count = 0; - archive >> serializable_count; - - struct TempResource - { - std::string name; - uint32_t flags = 0; - wi::vector filedata; + break; }; - wi::vector temp_resources; - temp_resources.resize(serializable_count); - wiJobSystem::context ctx; - std::mutex seri_locker; - for (size_t i = 0; i < serializable_count; ++i) + if (success) { - auto& resource = temp_resources[i]; + resource->flags = flags; - archive >> resource.name; - archive >> resource.flags; - archive >> resource.filedata; + if (resource->filedata.empty() && has_flag(flags, Flags::IMPORT_RETAIN_FILEDATA)) + { + // resource was loaded with external filedata, and we want to retain filedata + resource->filedata.resize(filesize); + std::memcpy(resource->filedata.data(), filedata, filesize); + } + else if (!resource->filedata.empty() && has_flag(flags, Flags::IMPORT_RETAIN_FILEDATA) == 0) + { + // resource was loaded using file name, and we want to discard filedata + resource->filedata.clear(); + } - resource.name = archive.GetSourceDirectory() + resource.name; + if (type == DataType::IMAGE && resource->texture.desc.mip_levels > 1 + && has_flag(resource->texture.desc.bind_flags, BindFlag::UNORDERED_ACCESS)) + { + wi::renderer::AddDeferredMIPGen(resource->texture, true); + } - // "Loading" the resource can happen asynchronously to serialization of file data, to improve performance - wiJobSystem::Execute(ctx, [i, &temp_resources, &seri_locker, &seri](wiJobArgs args) { - auto& tmp_resource = temp_resources[i]; - auto res = Load(tmp_resource.name, tmp_resource.flags, tmp_resource.filedata.data(), tmp_resource.filedata.size()); - seri_locker.lock(); - seri.resources.push_back(res); - seri_locker.unlock(); - }); + Resource retVal; + retVal.internal_state = resource; + return retVal; } - wiJobSystem::Wait(ctx); + return Resource(); } - else + + bool Contains(const std::string& name) + { + bool result = false; + locker.lock(); + auto it = resources.find(name); + if (it != resources.end()) + { + auto resource = it->second.lock(); + result = resource != nullptr; + } + locker.unlock(); + return result; + } + + void Clear() { locker.lock(); - size_t serializable_count = 0; + resources.clear(); + locker.unlock(); + } - if (mode == MODE_ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING) + + void Serialize(wi::Archive& archive, ResourceSerializer& seri) + { + if (archive.IsReadMode()) { - // Simply not serialize any embedded resources - serializable_count = 0; - archive << serializable_count; + size_t serializable_count = 0; + archive >> serializable_count; + + struct TempResource + { + std::string name; + Flags flags = Flags::NONE; + wi::vector filedata; + }; + wi::vector temp_resources; + temp_resources.resize(serializable_count); + + wi::jobsystem::context ctx; + std::mutex seri_locker; + for (size_t i = 0; i < serializable_count; ++i) + { + auto& resource = temp_resources[i]; + + archive >> resource.name; + uint32_t flags_temp; + archive >> flags_temp; + resource.flags = (Flags)flags_temp; + archive >> resource.filedata; + + resource.name = archive.GetSourceDirectory() + resource.name; + + // "Loading" the resource can happen asynchronously to serialization of file data, to improve performance + wi::jobsystem::Execute(ctx, [i, &temp_resources, &seri_locker, &seri](wi::jobsystem::JobArgs args) { + auto& tmp_resource = temp_resources[i]; + auto res = Load(tmp_resource.name, tmp_resource.flags, tmp_resource.filedata.data(), tmp_resource.filedata.size()); + seri_locker.lock(); + seri.resources.push_back(res); + seri_locker.unlock(); + }); + } + + wi::jobsystem::Wait(ctx); } else { - // Count embedded resources: - for (auto& it : resources) + locker.lock(); + size_t serializable_count = 0; + + if (mode == Mode::ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING) { - std::shared_ptr resource = it.second.lock(); - if (resource != nullptr && !resource->filedata.empty()) + // Simply not serialize any embedded resources + serializable_count = 0; + archive << serializable_count; + } + else + { + // Count embedded resources: + for (auto& it : resources) { - serializable_count++; - } - } - - // Write all embedded resources: - archive << serializable_count; - for (auto& it : resources) - { - std::shared_ptr resource = it.second.lock(); - - if (resource != nullptr && !resource->filedata.empty()) - { - std::string name = it.first; - wiHelper::MakePathRelative(archive.GetSourceDirectory(), name); - - archive << name; - archive << resource->flags; - archive << resource->filedata; + std::shared_ptr resource = it.second.lock(); + if (resource != nullptr && !resource->filedata.empty()) + { + serializable_count++; + } + } + + // Write all embedded resources: + archive << serializable_count; + for (auto& it : resources) + { + std::shared_ptr resource = it.second.lock(); + + if (resource != nullptr && !resource->filedata.empty()) + { + std::string name = it.first; + wi::helper::MakePathRelative(archive.GetSourceDirectory(), name); + + archive << name; + archive << (uint32_t)resource->flags; + archive << resource->filedata; + } } } + locker.unlock(); } - locker.unlock(); } + } } diff --git a/WickedEngine/wiResourceManager.h b/WickedEngine/wiResourceManager.h index 24a1b5481..d3aeee497 100644 --- a/WickedEngine/wiResourceManager.h +++ b/WickedEngine/wiResourceManager.h @@ -8,64 +8,74 @@ #include -struct wiResource +namespace wi { - wiGraphics::Texture texture; - wiAudio::Sound sound; - - enum DATA_TYPE + // This can hold an asset + // It can be loaded from file or memory using wi::resourcemanager::Load() + struct Resource { - EMPTY, - IMAGE, - SOUND, - } type = EMPTY; + std::shared_ptr internal_state; + inline bool IsValid() const { return internal_state.get() != nullptr; } - uint32_t flags = 0; - wi::vector filedata; -}; - -namespace wiResourceManager -{ - enum MODE - { - MODE_DISCARD_FILEDATA_AFTER_LOAD, // default behaviour: file data will be discarded after loaded. This will not allow serialization of embedded resources, but less memory will be used overall - MODE_ALLOW_RETAIN_FILEDATA, // allows keeping the file datas around. This mode allows serialization of embedded resources which request it via IMPORT_RETAIN_FILEDATA - MODE_ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING // allows keeping file datas, but they won't be embedded by serializer - }; - void SetMode(MODE param); - MODE GetMode(); - wi::vector GetSupportedImageExtensions(); - wi::vector GetSupportedSoundExtensions(); - - // Order of these must not change as the flags can be serialized! - enum FLAGS - { - EMPTY = 0, - IMPORT_COLORGRADINGLUT = 1 << 0, // image import will convert resource to 3D color grading LUT - IMPORT_RETAIN_FILEDATA = 1 << 1, // file data will be kept for later reuse. This is necessary for keeping the resource serializable - }; - - // Load a resource - // name : file name of resource - // flags : specify flags that modify behaviour (optional) - // filedata : pointer to file data, if file was loaded manually (optional) - // filesize : size of file data, if file was loaded manually (optional) - std::shared_ptr Load( - const std::string& name, - uint32_t flags = EMPTY, - const uint8_t* filedata = nullptr, - size_t filesize = 0 - ); - // Check if a resource is currently loaded - bool Contains(const std::string& name); - // Invalidate all resources - void Clear(); - - struct ResourceSerializer - { - wi::vector> resources; - }; - // Serializes all resources that are compatible - // Compatible resources are those whose file data is kept around using the IMPORT_RETAIN_FILEDATA flag when loading. - void Serialize(wiArchive& archive, ResourceSerializer& seri); + const wi::vector& GetFileData() const; + const wi::graphics::Texture& GetTexture() const; + const wi::audio::Sound& GetSound() const; + + void SetFileData(const wi::vector& data); + void SetFileData(wi::vector&& data); + void SetTexture(const wi::graphics::Texture& texture); + void SetSound(const wi::audio::Sound& sound); + }; + + namespace resourcemanager + { + enum class Mode + { + DISCARD_FILEDATA_AFTER_LOAD, // default behaviour: file data will be discarded after loaded. This will not allow serialization of embedded resources, but less memory will be used overall + ALLOW_RETAIN_FILEDATA, // allows keeping the file datas around. This mode allows serialization of embedded resources which request it via IMPORT_RETAIN_FILEDATA + ALLOW_RETAIN_FILEDATA_BUT_DISABLE_EMBEDDING // allows keeping file datas, but they won't be embedded by serializer + }; + void SetMode(Mode param); + Mode GetMode(); + wi::vector GetSupportedImageExtensions(); + wi::vector GetSupportedSoundExtensions(); + + // Order of these must not change as the flags can be serialized! + enum class Flags + { + NONE = 0, + IMPORT_COLORGRADINGLUT = 1 << 0, // image import will convert resource to 3D color grading LUT + IMPORT_RETAIN_FILEDATA = 1 << 1, // file data will be kept for later reuse. This is necessary for keeping the resource serializable + }; + + // Load a resource + // name : file name of resource + // flags : specify flags that modify behaviour (optional) + // filedata : pointer to file data, if file was loaded manually (optional) + // filesize : size of file data, if file was loaded manually (optional) + Resource Load( + const std::string& name, + Flags flags = Flags::NONE, + const uint8_t* filedata = nullptr, + size_t filesize = 0 + ); + // Check if a resource is currently loaded + bool Contains(const std::string& name); + // Invalidate all resources + void Clear(); + + struct ResourceSerializer + { + wi::vector resources; + }; + // Serializes all resources that are compatible + // Compatible resources are those whose file data is kept around using the IMPORT_RETAIN_FILEDATA flag when loading. + void Serialize(wi::Archive& archive, ResourceSerializer& seri); + } + +} + +template<> +struct enable_bitmask_operators { + static const bool enable = true; }; diff --git a/WickedEngine/wiSDLInput.cpp b/WickedEngine/wiSDLInput.cpp index d22df7794..e7593f95e 100644 --- a/WickedEngine/wiSDLInput.cpp +++ b/WickedEngine/wiSDLInput.cpp @@ -3,7 +3,7 @@ #ifdef SDL2 #include "CommonInclude.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiInput.h" #include "wiVector.h" @@ -14,23 +14,23 @@ #include #include -namespace wiSDLInput +namespace wi::input::sdlinput { - wiInput::KeyboardState keyboard; - wiInput::MouseState mouse; + wi::input::KeyboardState keyboard; + wi::input::MouseState mouse; struct Internal_ControllerState { Sint32 portID; SDL_JoystickID internalID; SDL_GameController* controller; - wiInput::ControllerState state; + wi::input::ControllerState state; }; wi::vector controllers; int numSticks = 0; - int to_wiInput(const SDL_Scancode &key); - void controller_to_wiInput(uint32_t *current, Uint8 button, bool pressed); + int to_wicked(const SDL_Scancode &key); + void controller_to_wicked(uint32_t *current, Uint8 button, bool pressed); void AddController(Sint32 id); void RemoveController(Sint32 id); @@ -38,7 +38,7 @@ namespace wiSDLInput void Initialize() { if(!SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt")){ - wiBackLog::post("[SDL Input] No controller config loaded, add gamecontrollerdb.txt file next to the executable or download it from https://github.com/gabomdq/SDL_GameControllerDB"); + wi::backlog::post("[SDL Input] No controller config loaded, add gamecontrollerdb.txt file next to the executable or download it from https://github.com/gabomdq/SDL_GameControllerDB"); } // Attempt to add joysticks at initialization @@ -56,11 +56,11 @@ namespace wiSDLInput auto saved_y = mouse.position.y; // update keyboard and mouse to the latest value (in case of other input systems I suppose) -// keyboard = wiInput::KeyboardState(); -// mouse = wiInput::MouseState(); +// keyboard = wi::input::KeyboardState(); +// mouse = wi::input::MouseState(); // for (auto& internal_controller : controllers) // { -// internal_controller.state = wiInput::ControllerState(); +// internal_controller.state = wi::input::ControllerState(); // } // mouse.position.x = saved_x; // mouse.position.y = saved_y; @@ -100,7 +100,7 @@ namespace wiSDLInput // Keyboard events case SDL_KEYDOWN: // Key pressed { - int converted = to_wiInput(event.key.keysym.scancode); + int converted = to_wicked(event.key.keysym.scancode); if (converted >= 0) { keyboard.buttons[converted] = true; } @@ -108,7 +108,7 @@ namespace wiSDLInput } case SDL_KEYUP: // Key released { - int converted = to_wiInput(event.key.keysym.scancode); + int converted = to_wicked(event.key.keysym.scancode); if (converted >= 0) { keyboard.buttons[converted] = false; } @@ -191,7 +191,7 @@ namespace wiSDLInput if(controller.controller){ //Get controller buttons for(int btn=SDL_CONTROLLER_BUTTON_INVALID; btn #endif -namespace wiSDLInput +namespace wi::input::sdlinput { // Call this once to register raw input devices void Initialize(); @@ -15,18 +15,18 @@ namespace wiSDLInput void Update(); // Writes the keyboard state into state parameter - void GetKeyboardState(wiInput::KeyboardState* state); + void GetKeyboardState(wi::input::KeyboardState* state); // Writes the mouse state into state parameter - void GetMouseState(wiInput::MouseState* state); + void GetMouseState(wi::input::MouseState* state); // Returns how many controller devices have received input ever. This doesn't correlate with which ones are currently available int GetMaxControllerCount(); // Returns whether the controller identified by index parameter is available or not // Id state parameter is not nullptr, and the controller is available, the state will be written into it - bool GetControllerState(wiInput::ControllerState* state, int index); + bool GetControllerState(wi::input::ControllerState* state, int index); // Sends feedback data for the controller identified by index parameter to output - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index); + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index); } diff --git a/WickedEngine/wiScene.cpp b/WickedEngine/wiScene.cpp index ebc07be5f..544c456aa 100644 --- a/WickedEngine/wiScene.cpp +++ b/WickedEngine/wiScene.cpp @@ -1,14 +1,14 @@ #include "wiScene.h" #include "wiTextureHelper.h" #include "wiResourceManager.h" -#include "wiPhysicsEngine.h" +#include "wiPhysics.h" #include "wiArchive.h" #include "wiRenderer.h" #include "wiJobSystem.h" #include "wiSpinLock.h" #include "wiHelper.h" #include "wiRenderer.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTimer.h" #include "wiUnorderedMap.h" @@ -16,10 +16,12 @@ #include -using namespace wiECS; -using namespace wiGraphics; +using namespace wi::ecs; +using namespace wi::enums; +using namespace wi::graphics; +using namespace wi::primitive; -namespace wiScene +namespace wi::scene { XMFLOAT3 TransformComponent::GetPosition() const @@ -230,14 +232,14 @@ namespace wiScene void MaterialComponent::WriteShaderMaterial(ShaderMaterial* dest) const { dest->baseColor = baseColor; - dest->emissive_r11g11b10 = wiMath::Pack_R11G11B10_FLOAT(XMFLOAT3(emissiveColor.x * emissiveColor.w, emissiveColor.y * emissiveColor.w, emissiveColor.z * emissiveColor.w)); - dest->specular_r11g11b10 = wiMath::Pack_R11G11B10_FLOAT(XMFLOAT3(specularColor.x * specularColor.w, specularColor.y * specularColor.w, specularColor.z * specularColor.w)); + dest->emissive_r11g11b10 = wi::math::Pack_R11G11B10_FLOAT(XMFLOAT3(emissiveColor.x * emissiveColor.w, emissiveColor.y * emissiveColor.w, emissiveColor.z * emissiveColor.w)); + dest->specular_r11g11b10 = wi::math::Pack_R11G11B10_FLOAT(XMFLOAT3(specularColor.x * specularColor.w, specularColor.y * specularColor.w, specularColor.z * specularColor.w)); dest->texMulAdd = texMulAdd; dest->roughness = roughness; dest->reflectance = reflectance; dest->metalness = metalness; dest->refraction = refraction; - dest->normalMapStrength = (textures[NORMALMAP].resource == nullptr ? 0 : normalMapStrength); + dest->normalMapStrength = (textures[NORMALMAP].resource.IsValid() ? normalMapStrength : 0); dest->parallaxOcclusionMapping = parallaxOcclusionMapping; dest->displacementMapping = displacementMapping; XMFLOAT4 sss = subsurfaceScattering; @@ -265,7 +267,7 @@ namespace wiScene dest->uvset_clearcoatRoughnessMap = textures[CLEARCOATROUGHNESSMAP].GetUVSet(); dest->uvset_clearcoatNormalMap = textures[CLEARCOATNORMALMAP].GetUVSet(); dest->uvset_specularMap = textures[SPECULARMAP].GetUVSet(); - dest->sheenColor_r11g11b10 = wiMath::Pack_R11G11B10_FLOAT(XMFLOAT3(sheenColor.x, sheenColor.y, sheenColor.z)); + dest->sheenColor_r11g11b10 = wi::math::Pack_R11G11B10_FLOAT(XMFLOAT3(sheenColor.x, sheenColor.y, sheenColor.z)); dest->sheenRoughness = sheenRoughness; dest->clearcoat = clearcoat; dest->clearcoatRoughness = clearcoatRoughness; @@ -320,7 +322,7 @@ namespace wiScene } dest->options = options; // ensure that this memory is not read, so bitwise ORs also not performed with it! - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); dest->texture_basecolormap_index = device->GetDescriptorIndex(textures[BASECOLORMAP].GetGPUResource(), SubresourceType::SRV); dest->texture_surfacemap_index = device->GetDescriptorIndex(textures[SURFACEMAP].GetGPUResource(), SubresourceType::SRV); dest->texture_emissivemap_index = device->GetDescriptorIndex(textures[EMISSIVEMAP].GetGPUResource(), SubresourceType::SRV); @@ -336,7 +338,7 @@ namespace wiScene dest->texture_specularmap_index = device->GetDescriptorIndex(textures[SPECULARMAP].GetGPUResource(), SubresourceType::SRV); } - void MaterialComponent::WriteTextures(const wiGraphics::GPUResource** dest, int count) const + void MaterialComponent::WriteTextures(const wi::graphics::GPUResource** dest, int count) const { count = std::min(count, (int)TEXTURESLOT_COUNT); for (int i = 0; i < count; ++i) @@ -346,9 +348,9 @@ namespace wiScene } uint32_t MaterialComponent::GetRenderTypes() const { - if (IsCustomShader() && customShaderID < (int)wiRenderer::GetCustomShaders().size()) + if (IsCustomShader() && customShaderID < (int)wi::renderer::GetCustomShaders().size()) { - auto& customShader = wiRenderer::GetCustomShaders()[customShaderID]; + auto& customShader = wi::renderer::GetCustomShaders()[customShaderID]; return customShader.renderTypeFlags; } if (shaderType == SHADERTYPE_WATER) @@ -371,18 +373,18 @@ namespace wiScene { if (!x.name.empty()) { - x.resource = wiResourceManager::Load(x.name, wiResourceManager::IMPORT_RETAIN_FILEDATA); + x.resource = wi::resourcemanager::Load(x.name, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); } } } uint32_t MaterialComponent::GetStencilRef() const { - return wiRenderer::CombineStencilrefs(engineStencilRef, userStencilRef); + return wi::renderer::CombineStencilrefs(engineStencilRef, userStencilRef); } void MeshComponent::CreateRenderData() { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); vertex_subsets.resize(vertex_positions.size()); uint32_t subsetCounter = 0; @@ -452,8 +454,8 @@ namespace wiScene const uint8_t wind = vertex_windweights.empty() ? 0xFF : vertex_windweights[i]; vertices[i].FromFULL(pos, nor, wind); - _min = wiMath::Min(_min, pos); - _max = wiMath::Max(_max, pos); + _min = wi::math::Min(_min, pos); + _max = wi::math::Max(_max, pos); } GPUBufferDesc bd; @@ -733,7 +735,7 @@ namespace wiScene void MeshComponent::WriteShaderMesh(ShaderMesh* dest) const { dest->init(); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); dest->ib = device->GetDescriptorIndex(&indexBuffer, SubresourceType::SRV); if (streamoutBuffer_POS.IsValid()) { @@ -886,10 +888,10 @@ namespace wiScene switch (compute) { - case wiScene::MeshComponent::COMPUTE_NORMALS_HARD: + case MeshComponent::COMPUTE_NORMALS_HARD: break; - case wiScene::MeshComponent::COMPUTE_NORMALS_SMOOTH: + case MeshComponent::COMPUTE_NORMALS_SMOOTH: { // Compute smooth surface normals: @@ -1045,7 +1047,7 @@ namespace wiScene } break; - case wiScene::MeshComponent::COMPUTE_NORMALS_SMOOTH_FAST: + case MeshComponent::COMPUTE_NORMALS_SMOOTH_FAST: { for (size_t i = 0; i < vertex_normals.size(); i++) { @@ -1137,11 +1139,11 @@ namespace wiScene CreateRenderData(); } - SPHERE MeshComponent::GetBoundingSphere() const + Sphere MeshComponent::GetBoundingSphere() const { XMFLOAT3 halfwidth = aabb.getHalfWidth(); - SPHERE sphere; + Sphere sphere; sphere.center = aabb.getCenter(); sphere.radius = std::max(halfwidth.x, std::max(halfwidth.y, halfwidth.z)); @@ -1171,7 +1173,7 @@ namespace wiScene { SetLightmapRenderRequest(false); - bool success = wiHelper::saveTextureToMemory(lightmap, lightmapTextureData); + bool success = wi::helper::saveTextureToMemory(lightmap, lightmapTextureData); assert(success); #ifdef OPEN_IMAGE_DENOISE @@ -1207,7 +1209,7 @@ namespace wiScene auto error = device.getError(errorMessage); if (error != oidn::Error::None && error != oidn::Error::Cancelled) { - wiBackLog::post(std::string("[OpenImageDenoise error] ") + errorMessage); + wi::backlog::post(std::string("[OpenImageDenoise error] ") + errorMessage); } } @@ -1217,8 +1219,8 @@ namespace wiScene CompressLightmap(); - wiTextureHelper::CreateTexture(lightmap, lightmapTextureData.data(), lightmapWidth, lightmapHeight, lightmap.desc.format); - wiGraphics::GetDevice()->SetName(&lightmap, "lightmap"); + wi::texturehelper::CreateTexture(lightmap, lightmapTextureData.data(), lightmapWidth, lightmapHeight, lightmap.desc.format); + wi::graphics::GetDevice()->SetName(&lightmap, "lightmap"); } } void ObjectComponent::CompressLightmap() @@ -1226,14 +1228,14 @@ namespace wiScene // BC6 Block compression code that uses DirectXTex library, but it's not cross platform, so disabled: #if 0 - wiTimer timer; - wiBackLog::post("compressing lightmap..."); + wi::Timer timer; + wi::backlog::post("compressing lightmap..."); lightmap.desc.Format = lightmap_block_format; lightmap.desc.BindFlags = BindFlag::SHADER_RESOURCE; - static constexpr wiGraphics::FORMAT lightmap_block_format = wiGraphics::FORMAT_BC6H_UF16; - static constexpr uint32_t lightmap_blocksize = wiGraphics::GetFormatBlockSize(lightmap_block_format); + static constexpr wi::graphics::FORMAT lightmap_block_format = wi::graphics::FORMAT_BC6H_UF16; + static constexpr uint32_t lightmap_blocksize = wi::graphics::GetFormatBlockSize(lightmap_block_format); static_assert(lightmap_blocksize == 4u); const uint32_t bc6_width = lightmapWidth / lightmap_blocksize; const uint32_t bc6_height = lightmapHeight / lightmap_blocksize; @@ -1265,7 +1267,7 @@ namespace wiScene lightmapTextureData = std::move(bc6_data); // replace old (raw) data with compressed data - wiBackLog::post( + wi::backlog::post( "compressing lightmap [" + std::to_string(lightmapWidth) + "x" + @@ -1298,7 +1300,7 @@ namespace wiScene void ArmatureComponent::CreateRenderData() { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); GPUBufferDesc bd; bd.size = sizeof(ShaderTransform) * (uint32_t)boneCollection.size(); @@ -1326,8 +1328,8 @@ namespace wiScene XMStoreFloat3(&nor, XMVector3Normalize(XMVector3TransformNormal(XMLoadFloat3(&nor), W))); const uint8_t wind = mesh.vertex_windweights.empty() ? 0xFF : mesh.vertex_windweights[i]; vertex_positions_simulation[i].FromFULL(pos, nor, wind); - _min = wiMath::Min(_min, pos); - _max = wiMath::Max(_max, pos); + _min = wi::math::Min(_min, pos); + _max = wi::math::Max(_max, pos); } aabb = AABB(_min, _max); @@ -1461,14 +1463,14 @@ namespace wiScene { this->dt = dt; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); instanceArraySize = objects.GetCount() + hairs.GetCount() + emitters.GetCount(); if (instanceBuffer.desc.size < (instanceArraySize * sizeof(ShaderMeshInstance))) { GPUBufferDesc desc; desc.stride = sizeof(ShaderMeshInstance); - desc.size = desc.stride * instanceArraySize; + desc.size = desc.stride * instanceArraySize * 2; // *2 to grow fast desc.bind_flags = BindFlag::SHADER_RESOURCE; desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; device->CreateBuffer(&desc, nullptr, &instanceBuffer); @@ -1490,7 +1492,7 @@ namespace wiScene { GPUBufferDesc desc; desc.stride = sizeof(ShaderMesh); - desc.size = desc.stride * meshArraySize; + desc.size = desc.stride * meshArraySize * 2; // *2 to grow fast desc.bind_flags = BindFlag::SHADER_RESOURCE; desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; device->CreateBuffer(&desc, nullptr, &meshBuffer); @@ -1512,7 +1514,7 @@ namespace wiScene { GPUBufferDesc desc; desc.stride = sizeof(ShaderMaterial); - desc.size = desc.stride * materialArraySize; + desc.size = desc.stride * materialArraySize * 2; // *2 to grow fast desc.bind_flags = BindFlag::SHADER_RESOURCE; desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; device->CreateBuffer(&desc, nullptr, &materialBuffer); @@ -1534,7 +1536,7 @@ namespace wiScene { GPUBufferDesc desc; desc.stride = (uint32_t)device->GetTopLevelAccelerationStructureInstanceSize(); - desc.size = desc.stride * instanceArraySize; + desc.size = desc.stride * instanceArraySize * 2; // *2 to grow fast desc.usage = Usage::UPLOAD; if (TLAS_instancesUpload->desc.size < desc.size) { @@ -1548,7 +1550,7 @@ namespace wiScene } // Occlusion culling read: - if(wiRenderer::GetOcclusionCullingEnabled() && !wiRenderer::GetFreezeCullingCameraEnabled()) + if(wi::renderer::GetOcclusionCullingEnabled() && !wi::renderer::GetFreezeCullingCameraEnabled()) { uint32_t minQueryCount = uint32_t(objects.GetCount() + lights.GetCount()); if (queryHeap.desc.query_count < minQueryCount) @@ -1585,7 +1587,12 @@ namespace wiScene queryAllocator.store(0); } - wiJobSystem::context ctx; + wi::jobsystem::context ctx; + + wi::jobsystem::Execute(ctx, [&](wi::jobsystem::JobArgs args) { + // Must not keep inactive TLAS instances, so zero them out for safety: + std::memset(TLAS_instancesMapped, 0, TLAS_instancesUpload->desc.size); + }); RunPreviousFrameTransformUpdateSystem(ctx); @@ -1593,7 +1600,7 @@ namespace wiScene RunTransformUpdateSystem(ctx); - wiJobSystem::Wait(ctx); // dependencies + wi::jobsystem::Wait(ctx); // dependencies RunHierarchyUpdateSystem(ctx); @@ -1611,9 +1618,9 @@ namespace wiScene RunWeatherUpdateSystem(ctx); - wiJobSystem::Wait(ctx); // dependencies + wi::jobsystem::Wait(ctx); // dependencies - wiPhysicsEngine::RunPhysicsUpdateSystem(ctx, *this, dt); + wi::physics::RunPhysicsUpdateSystem(ctx, *this, dt); RunObjectUpdateSystem(ctx); @@ -1631,7 +1638,7 @@ namespace wiScene RunSoundUpdateSystem(ctx); - wiJobSystem::Wait(ctx); // dependencies + wi::jobsystem::Wait(ctx); // dependencies // Merge parallel bounds computation (depends on object update system): bounds = AABB(); @@ -1648,12 +1655,12 @@ namespace wiScene if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { // Recreate top level acceleration structure if the object count changed: - if (instanceArraySize > 0 && (uint32_t)instanceArraySize != TLAS.desc.top_level.count) + if (TLAS.desc.top_level.count < instanceArraySize) { RaytracingAccelerationStructureDesc desc; desc.flags = RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; desc.type = RaytracingAccelerationStructureDesc::Type::TOPLEVEL; - desc.top_level.count = (uint32_t)instanceArraySize; + desc.top_level.count = (uint32_t)instanceArraySize * 2; // *2 to grow fast GPUBufferDesc bufdesc; bufdesc.misc_flags |= ResourceMiscFlag::RAY_TRACING; bufdesc.stride = (uint32_t)device->GetTopLevelAccelerationStructureInstanceSize(); @@ -1687,7 +1694,7 @@ namespace wiScene } } - if (wiRenderer::GetSurfelGIEnabled()) + if (wi::renderer::GetSurfelGIEnabled()) { if (!surfelBuffer.IsValid()) { @@ -1760,13 +1767,13 @@ namespace wiScene shaderscene.meshbuffer = device->GetDescriptorIndex(&meshBuffer, SubresourceType::SRV); shaderscene.materialbuffer = device->GetDescriptorIndex(&materialBuffer, SubresourceType::SRV); shaderscene.envmaparray = device->GetDescriptorIndex(&envmapArray, SubresourceType::SRV); - if (weather.skyMap == nullptr) + if (weather.skyMap.IsValid()) { - shaderscene.globalenvmap = -1; + shaderscene.globalenvmap = device->GetDescriptorIndex(&weather.skyMap.GetTexture(), SubresourceType::SRV); } else { - shaderscene.globalenvmap = device->GetDescriptorIndex(&weather.skyMap->texture, SubresourceType::SRV); + shaderscene.globalenvmap = -1; } shaderscene.TLAS = device->GetDescriptorIndex(&TLAS, SubresourceType::SRV); shaderscene.BVH_counter = device->GetDescriptorIndex(&BVH.primitiveCounterBuffer, SubresourceType::SRV); @@ -1930,7 +1937,7 @@ namespace wiScene } Entity Scene::Entity_Duplicate(Entity entity) { - wiArchive archive; + wi::Archive archive; // First write the root entity to staging area: archive.SetReadModeAndResetPos(false); @@ -2151,8 +2158,8 @@ namespace wiScene SoundComponent& sound = sounds.Create(entity); sound.filename = filename; - sound.soundResource = wiResourceManager::Load(filename, wiResourceManager::IMPORT_RETAIN_FILEDATA); - wiAudio::CreateSoundInstance(&sound.soundResource->sound, &sound.soundinstance); + sound.soundResource = wi::resourcemanager::Load(filename, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); + wi::audio::CreateSoundInstance(&sound.soundResource.GetSound(), &sound.soundinstance); TransformComponent& transform = transforms.Create(entity); transform.Translate(position); @@ -2269,9 +2276,9 @@ namespace wiScene const uint32_t small_subtask_groupsize = 64; - void Scene::RunPreviousFrameTransformUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunPreviousFrameTransformUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)prev_transforms.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)prev_transforms.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { PreviousFrameTransformComponent& prev_transform = prev_transforms[args.jobIndex]; Entity entity = prev_transforms.GetEntity(args.jobIndex); @@ -2280,7 +2287,7 @@ namespace wiScene prev_transform.world_prev = transform.world; }); } - void Scene::RunAnimationUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunAnimationUpdateSystem(wi::jobsystem::context& ctx) { for (size_t i = 0; i < animations.GetCount(); ++i) { @@ -2448,7 +2455,7 @@ namespace wiScene { float vLeft = animationdata->keyframe_data[keyLeft * animation.morph_weights_temp.size() + j]; float vRight = animationdata->keyframe_data[keyLeft * animation.morph_weights_temp.size() + j]; - float vAnim = wiMath::Lerp(vLeft, vRight, t); + float vAnim = wi::math::Lerp(vLeft, vRight, t); animation.morph_weights_temp[j] = vAnim; } } @@ -2561,7 +2568,7 @@ namespace wiScene for (size_t j = 0; j < target_mesh->targets.size(); ++j) { - target_mesh->targets[j].weight = wiMath::Lerp(target_mesh->targets[j].weight, animation.morph_weights_temp[j], t); + target_mesh->targets[j].weight = wi::math::Lerp(target_mesh->targets[j].weight, animation.morph_weights_temp[j], t); } target_mesh->dirty_morph = true; @@ -2580,15 +2587,15 @@ namespace wiScene } } } - void Scene::RunTransformUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunTransformUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)transforms.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)transforms.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { TransformComponent& transform = transforms[args.jobIndex]; transform.UpdateTransform(); }); } - void Scene::RunHierarchyUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunHierarchyUpdateSystem(wi::jobsystem::context& ctx) { // This needs serialized execution because there are dependencies enforced by component order! @@ -2614,7 +2621,7 @@ namespace wiScene } } - void Scene::RunSpringUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunSpringUpdateSystem(wi::jobsystem::context& ctx) { static float time = 0; time += dt; @@ -2702,7 +2709,7 @@ namespace wiScene *((XMFLOAT3*)&transform->world._41) = spring.center_of_mass; } } - void Scene::RunInverseKinematicsUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunInverseKinematicsUpdateSystem(wi::jobsystem::context& ctx) { bool recompute_hierarchy = false; for (size_t i = 0; i < inverse_kinematics.GetCount(); ++i) @@ -2801,9 +2808,9 @@ namespace wiScene } } } - void Scene::RunArmatureUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunArmatureUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)armatures.GetCount(), 1, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)armatures.GetCount(), 1, [&](wi::jobsystem::JobArgs args) { ArmatureComponent& armature = armatures[args.jobIndex]; Entity entity = armatures.GetEntity(args.jobIndex); @@ -2846,8 +2853,8 @@ namespace wiScene XMFLOAT3 bonepos = bone.GetPosition(); AABB boneAABB; boneAABB.createFromHalfWidth(bonepos, XMFLOAT3(bone_radius, bone_radius, bone_radius)); - _min = wiMath::Min(_min, boneAABB._min); - _max = wiMath::Max(_max, boneAABB._max); + _min = wi::math::Min(_min, boneAABB._min); + _max = wi::math::Max(_max, boneAABB._max); } armature.aabb = AABB(_min, _max); @@ -2858,18 +2865,18 @@ namespace wiScene } }); } - void Scene::RunMeshUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunMeshUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)meshes.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)meshes.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { Entity entity = meshes.GetEntity(args.jobIndex); MeshComponent& mesh = meshes[args.jobIndex]; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); if (!mesh.vertexBuffer_PRE.IsValid()) { const SoftBodyPhysicsComponent* softbody = softbodies.GetComponent(entity); - if (softbody != nullptr && wiPhysicsEngine::IsSimulationEnabled()) + if (softbody != nullptr && wi::physics::IsSimulationEnabled()) { device->CreateBuffer(&mesh.vertexBuffer_POS.desc, nullptr, &mesh.streamoutBuffer_POS); device->CreateBuffer(&mesh.vertexBuffer_POS.desc, nullptr, &mesh.vertexBuffer_PRE); @@ -2971,8 +2978,8 @@ namespace wiScene XMStoreFloat3(&nor, XMVector3Normalize(XMLoadFloat3(&nor))); mesh.vertex_positions_morphed[i].FromFULL(pos, nor, wind); - _min = wiMath::Min(_min, pos); - _max = wiMath::Max(_max, pos); + _min = wi::math::Min(_min, pos); + _max = wi::math::Max(_max, pos); } mesh.aabb = AABB(_min, _max); @@ -2982,9 +2989,9 @@ namespace wiScene }); } - void Scene::RunMaterialUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunMaterialUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)materials.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)materials.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { MaterialComponent& material = materials[args.jobIndex]; Entity entity = materials.GetEntity(args.jobIndex); @@ -3019,11 +3026,11 @@ namespace wiScene }); } - void Scene::RunImpostorUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunImpostorUpdateSystem(wi::jobsystem::context& ctx) { if (impostors.GetCount() > 0 && !impostorArray.IsValid()) { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); TextureDesc desc; desc.width = impostorTextureDim; @@ -3073,7 +3080,7 @@ namespace wiScene } } - wiJobSystem::Dispatch(ctx, (uint32_t)impostors.GetCount(), 1, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)impostors.GetCount(), 1, [&](wi::jobsystem::JobArgs args) { ImpostorComponent& impostor = impostors[args.jobIndex]; impostor.aabb = AABB(); @@ -3086,20 +3093,20 @@ namespace wiScene } }); } - void Scene::RunObjectUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunObjectUpdateSystem(wi::jobsystem::context& ctx) { assert(objects.GetCount() == aabb_objects.GetCount()); parallel_bounds.clear(); - parallel_bounds.resize((size_t)wiJobSystem::DispatchGroupCount((uint32_t)objects.GetCount(), small_subtask_groupsize)); + parallel_bounds.resize((size_t)wi::jobsystem::DispatchGroupCount((uint32_t)objects.GetCount(), small_subtask_groupsize)); - wiJobSystem::Dispatch(ctx, (uint32_t)objects.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)objects.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { ObjectComponent& object = objects[args.jobIndex]; AABB& aabb = aabb_objects[args.jobIndex]; // Update occlusion culling status: - if (!wiRenderer::GetFreezeCullingCameraEnabled()) + if (!wi::renderer::GetFreezeCullingCameraEnabled()) { object.occlusionHistory <<= 1; // advance history by 1 frame int query_id = object.occlusionQueries[queryheap_idx]; @@ -3184,7 +3191,7 @@ namespace wiScene impostor->color = object.color; impostor->fadeThresholdRadius = object.impostorFadeThresholdRadius; - const SPHERE boundingsphere = mesh->GetBoundingSphere(); + const Sphere boundingsphere = mesh->GetBoundingSphere(); locker.lock(); impostor->instances.push_back(args.jobIndex); @@ -3214,8 +3221,8 @@ namespace wiScene } // Create GPU instance data: - const XMFLOAT4X4& worldMatrix = object.transform_index >= 0 ? transforms[object.transform_index].world : IDENTITYMATRIX; - const XMFLOAT4X4& worldMatrixPrev = object.prev_transform_index >= 0 ? prev_transforms[object.prev_transform_index].world_prev : IDENTITYMATRIX; + const XMFLOAT4X4& worldMatrix = object.transform_index >= 0 ? transforms[object.transform_index].world : wi::math::IDENTITY_MATRIX; + const XMFLOAT4X4& worldMatrixPrev = object.prev_transform_index >= 0 ? prev_transforms[object.prev_transform_index].world_prev : wi::math::IDENTITY_MATRIX; XMMATRIX worldMatrixInverseTranspose = XMLoadFloat4x4(&worldMatrix); worldMatrixInverseTranspose = XMMatrixInverse(nullptr, worldMatrixInverseTranspose); @@ -3223,7 +3230,7 @@ namespace wiScene XMFLOAT4X4 transformIT; XMStoreFloat4x4(&transformIT, worldMatrixInverseTranspose); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); ShaderMeshInstance& inst = instanceArrayMapped[args.jobIndex]; inst.init(); inst.transform.Create(worldMatrix); @@ -3234,8 +3241,8 @@ namespace wiScene inst.lightmap = device->GetDescriptorIndex(&object.lightmap, SubresourceType::SRV); } inst.uid = entity; - inst.color = wiMath::CompressColor(object.color); - inst.emissive = wiMath::Pack_R11G11B10_FLOAT(XMFLOAT3(object.emissiveColor.x * object.emissiveColor.w, object.emissiveColor.y * object.emissiveColor.w, object.emissiveColor.z * object.emissiveColor.w)); + inst.color = wi::math::CompressColor(object.color); + inst.emissive = wi::math::Pack_R11G11B10_FLOAT(XMFLOAT3(object.emissiveColor.x * object.emissiveColor.w, object.emissiveColor.y * object.emissiveColor.w, object.emissiveColor.z * object.emissiveColor.w)); inst.meshIndex = (uint)meshes.GetIndex(object.meshID); if (TLAS_instancesMapped != nullptr) @@ -3274,8 +3281,8 @@ namespace wiScene { if (!object.lightmap.IsValid()) { - object.lightmapWidth = wiMath::GetNextPowerOfTwo(object.lightmapWidth + 1) / 2; - object.lightmapHeight = wiMath::GetNextPowerOfTwo(object.lightmapHeight + 1) / 2; + object.lightmapWidth = wi::math::GetNextPowerOfTwo(object.lightmapWidth + 1) / 2; + object.lightmapHeight = wi::math::GetNextPowerOfTwo(object.lightmapHeight + 1) / 2; TextureDesc desc; desc.width = object.lightmapWidth; @@ -3306,7 +3313,7 @@ namespace wiScene { // Create a GPU-side per object lighmap if there is none yet, but the data exists already: object.lightmap.desc.format = Format::R11G11B10_FLOAT; - wiTextureHelper::CreateTexture(object.lightmap, object.lightmapTextureData.data(), object.lightmapWidth, object.lightmapHeight, object.lightmap.desc.format); + wi::texturehelper::CreateTexture(object.lightmap, object.lightmapTextureData.data(), object.lightmapWidth, object.lightmapHeight, object.lightmap.desc.format); device->SetName(&object.lightmap, "lightmap"); } } @@ -3339,9 +3346,9 @@ namespace wiScene }, sizeof(AABB)); } - void Scene::RunCameraUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunCameraUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)cameras.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)cameras.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { CameraComponent& camera = cameras[args.jobIndex]; Entity entity = cameras.GetEntity(args.jobIndex); @@ -3353,7 +3360,7 @@ namespace wiScene camera.UpdateCamera(); }); } - void Scene::RunDecalUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunDecalUpdateSystem(wi::jobsystem::context& ctx) { assert(decals.GetCount() == aabb_decals.GetCount()); @@ -3397,13 +3404,13 @@ namespace wiScene decal.normal = material.textures[MaterialComponent::NORMALMAP].resource; } } - void Scene::RunProbeUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunProbeUpdateSystem(wi::jobsystem::context& ctx) { assert(probes.GetCount() == aabb_probes.GetCount()); if (!envmapArray.IsValid()) // even when zero probes, this will be created, since sometimes only the sky will be rendered into it { - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); TextureDesc desc; desc.array_size = 6; @@ -3545,9 +3552,9 @@ namespace wiScene } } } - void Scene::RunForceUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunForceUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)forces.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)forces.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { ForceFieldComponent& force = forces[args.jobIndex]; Entity entity = forces.GetEntity(args.jobIndex); @@ -3563,11 +3570,11 @@ namespace wiScene force.range_global = force.range_local * std::max(XMVectorGetX(S), std::max(XMVectorGetY(S), XMVectorGetZ(S))); }); } - void Scene::RunLightUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunLightUpdateSystem(wi::jobsystem::context& ctx) { assert(lights.GetCount() == aabb_lights.GetCount()); - wiJobSystem::Dispatch(ctx, (uint32_t)lights.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)lights.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { LightComponent& light = lights[args.jobIndex]; Entity entity = lights.GetEntity(args.jobIndex); @@ -3622,11 +3629,11 @@ namespace wiScene }); } - void Scene::RunParticleUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunParticleUpdateSystem(wi::jobsystem::context& ctx) { - wiJobSystem::Dispatch(ctx, (uint32_t)hairs.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)hairs.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { - wiHairParticle& hair = hairs[args.jobIndex]; + HairParticleSystem& hair = hairs[args.jobIndex]; Entity entity = hairs.GetEntity(args.jobIndex); const LayerComponent* layer = layers.GetComponent(entity); @@ -3645,7 +3652,7 @@ namespace wiScene hair.UpdateCPU(transform, *mesh, dt); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); size_t meshIndex = meshes.GetCount() + args.jobIndex; ShaderMesh& mesh = meshArrayMapped[meshIndex]; @@ -3662,8 +3669,8 @@ namespace wiScene inst.init(); inst.uid = entity; // every vertex is pretransformed and simulated in worldspace for hair particle: - inst.transform.Create(IDENTITYMATRIX); - inst.transformPrev.Create(IDENTITYMATRIX); + inst.transform.Create(wi::math::IDENTITY_MATRIX); + inst.transformPrev.Create(wi::math::IDENTITY_MATRIX); inst.meshIndex = (uint)meshIndex; if (TLAS_instancesMapped != nullptr && hair.BLAS.IsValid()) @@ -3674,7 +3681,7 @@ namespace wiScene { for (int j = 0; j < arraysize(instance.transform[i]); ++j) { - instance.transform[i][j] = IDENTITYMATRIX.m[j][i]; + instance.transform[i][j] = wi::math::IDENTITY_MATRIX.m[j][i]; } } instance.instance_id = (uint32_t)instanceIndex; @@ -3690,9 +3697,9 @@ namespace wiScene }); - wiJobSystem::Dispatch(ctx, (uint32_t)emitters.GetCount(), small_subtask_groupsize, [&](wiJobArgs args) { + wi::jobsystem::Dispatch(ctx, (uint32_t)emitters.GetCount(), small_subtask_groupsize, [&](wi::jobsystem::JobArgs args) { - wiEmittedParticle& emitter = emitters[args.jobIndex]; + EmittedParticleSystem& emitter = emitters[args.jobIndex]; Entity entity = emitters.GetEntity(args.jobIndex); MaterialComponent* material = materials.GetComponent(entity); @@ -3702,7 +3709,7 @@ namespace wiScene { material->SetUseVertexColors(true); } - if (emitter.shaderType == wiEmittedParticle::PARTICLESHADERTYPE::SOFT_LIGHTING) + if (emitter.shaderType == EmittedParticleSystem::PARTICLESHADERTYPE::SOFT_LIGHTING) { material->shaderType = MaterialComponent::SHADERTYPE_PBR; } @@ -3721,7 +3728,7 @@ namespace wiScene const TransformComponent& transform = *transforms.GetComponent(entity); emitter.UpdateCPU(transform, dt); - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); size_t meshIndex = meshes.GetCount() + hairs.GetCount() + args.jobIndex; ShaderMesh& mesh = meshArrayMapped[meshIndex]; @@ -3739,8 +3746,8 @@ namespace wiScene inst.init(); inst.uid = entity; // every vertex is pretransformed and simulated in worldspace for emitted particle: - inst.transform.Create(IDENTITYMATRIX); - inst.transformPrev.Create(IDENTITYMATRIX); + inst.transform.Create(wi::math::IDENTITY_MATRIX); + inst.transformPrev.Create(wi::math::IDENTITY_MATRIX); inst.meshIndex = (uint)meshIndex; if (TLAS_instancesMapped != nullptr && emitter.BLAS.IsValid()) @@ -3751,7 +3758,7 @@ namespace wiScene { for (int j = 0; j < arraysize(instance.transform[i]); ++j) { - instance.transform[i][j] = IDENTITYMATRIX.m[j][i]; + instance.transform[i][j] = wi::math::IDENTITY_MATRIX.m[j][i]; } } instance.instance_id = (uint32_t)instanceIndex; @@ -3765,7 +3772,7 @@ namespace wiScene }); } - void Scene::RunWeatherUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunWeatherUpdateSystem(wi::jobsystem::context& ctx) { if (weathers.GetCount() > 0) { @@ -3778,10 +3785,10 @@ namespace wiScene } } } - void Scene::RunSoundUpdateSystem(wiJobSystem::context& ctx) + void Scene::RunSoundUpdateSystem(wi::jobsystem::context& ctx) { const CameraComponent& camera = GetCamera(); - wiAudio::SoundInstance3D instance3D; + wi::audio::SoundInstance3D instance3D; instance3D.listenerPos = camera.Eye; instance3D.listenerUp = camera.Up; instance3D.listenerFront = camera.At; @@ -3797,37 +3804,37 @@ namespace wiScene if (transform != nullptr) { instance3D.emitterPos = transform->GetPosition(); - wiAudio::Update3D(&sound.soundinstance, instance3D); + wi::audio::Update3D(&sound.soundinstance, instance3D); } } if (sound.IsPlaying()) { - wiAudio::Play(&sound.soundinstance); + wi::audio::Play(&sound.soundinstance); } else { - wiAudio::Stop(&sound.soundinstance); + wi::audio::Stop(&sound.soundinstance); } if (!sound.IsLooped()) { - wiAudio::ExitLoop(&sound.soundinstance); + wi::audio::ExitLoop(&sound.soundinstance); } - wiAudio::SetVolume(sound.volume, &sound.soundinstance); + wi::audio::SetVolume(sound.volume, &sound.soundinstance); } } void Scene::PutWaterRipple(const std::string& image, const XMFLOAT3& pos) { - wiSprite img(image); + wi::Sprite img(image); img.params.enableExtractNormalMap(); img.params.blendFlag = BLENDMODE_ADDITIVE; img.anim.fad = 0.01f; img.anim.scaleX = 0.2f; img.anim.scaleY = 0.2f; img.params.pos = pos; - img.params.rotation = (wiRandom::getRandom(0, 1000) * 0.001f) * 2 * 3.1415f; + img.params.rotation = (wi::random::GetRandom(0, 1000) * 0.001f) * 2 * 3.1415f; img.params.siz = XMFLOAT2(1, 1); - img.params.quality = QUALITY_ANISOTROPIC; + img.params.quality = wi::image::QUALITY_ANISOTROPIC; img.params.pivot = XMFLOAT2(0.5f, 0.5f); waterRipples.push_back(img); } @@ -3892,7 +3899,7 @@ namespace wiScene Entity LoadModel(Scene& scene, const std::string& fileName, const XMMATRIX& transformMatrix, bool attached) { - wiArchive archive(fileName, true); + wi::Archive archive(fileName, true); if (archive.IsOpen()) { // Serialize it from file: @@ -3937,7 +3944,7 @@ namespace wiScene return INVALID_ENTITY; } - PickResult Pick(const RAY& ray, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) + PickResult Pick(const Ray& ray, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) { PickResult result; @@ -4029,10 +4036,10 @@ namespace wiScene float distance; XMFLOAT2 bary; - if (wiMath::RayTriangleIntersects(rayOrigin_local, rayDirection_local, p0, p1, p2, distance, bary)) + if (wi::math::RayTriangleIntersects(rayOrigin_local, rayDirection_local, p0, p1, p2, distance, bary)) { const XMVECTOR pos = XMVector3Transform(XMVectorAdd(rayOrigin_local, rayDirection_local*distance), objectMat); - distance = wiMath::Distance(pos, rayOrigin); + distance = wi::math::Distance(pos, rayOrigin); if (distance < result.distance) { @@ -4068,7 +4075,7 @@ namespace wiScene return result; } - SceneIntersectSphereResult SceneIntersectSphere(const SPHERE& sphere, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) + SceneIntersectSphereResult SceneIntersectSphere(const Sphere& sphere, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) { SceneIntersectSphereResult result; XMVECTOR Center = XMLoadFloat3(&sphere.center); @@ -4269,7 +4276,7 @@ namespace wiScene return result; } - SceneIntersectSphereResult SceneIntersectCapsule(const CAPSULE& capsule, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) + SceneIntersectSphereResult SceneIntersectCapsule(const Capsule& capsule, uint32_t renderTypeMask, uint32_t layerMask, const Scene& scene) { SceneIntersectSphereResult result; XMVECTOR Base = XMLoadFloat3(&capsule.base); @@ -4409,13 +4416,13 @@ namespace wiScene // Find the nearest point on each edge. // Edge 0,1 - XMVECTOR Point1 = wiMath::ClosestPointOnLineSegment(p0, p1, LinePlaneIntersection); + XMVECTOR Point1 = wi::math::ClosestPointOnLineSegment(p0, p1, LinePlaneIntersection); // Edge 1,2 - XMVECTOR Point2 = wiMath::ClosestPointOnLineSegment(p1, p2, LinePlaneIntersection); + XMVECTOR Point2 = wi::math::ClosestPointOnLineSegment(p1, p2, LinePlaneIntersection); // Edge 2,0 - XMVECTOR Point3 = wiMath::ClosestPointOnLineSegment(p2, p0, LinePlaneIntersection); + XMVECTOR Point3 = wi::math::ClosestPointOnLineSegment(p2, p0, LinePlaneIntersection); ReferencePoint = Point1; float bestDist = XMVectorGetX(XMVector3LengthSq(Point1 - LinePlaneIntersection)); @@ -4437,7 +4444,7 @@ namespace wiScene } // Place a sphere on closest point on line segment to intersection: - XMVECTOR Center = wiMath::ClosestPointOnLineSegment(A, B, ReferencePoint); + XMVECTOR Center = wi::math::ClosestPointOnLineSegment(A, B, ReferencePoint); // Assert that the triangle is not degenerate. assert(!XMVector3Equal(N, XMVectorZero())); @@ -4483,21 +4490,21 @@ namespace wiScene // Find the nearest point on each edge. // Edge 0,1 - XMVECTOR Point1 = wiMath::ClosestPointOnLineSegment(p0, p1, Center); + XMVECTOR Point1 = wi::math::ClosestPointOnLineSegment(p0, p1, Center); // If the distance to the center of the sphere to the point is less than // the radius of the sphere then it must intersect. Intersection = XMVectorOrInt(Intersection, XMVectorLessOrEqual(XMVector3LengthSq(XMVectorSubtract(Center, Point1)), RadiusSq)); // Edge 1,2 - XMVECTOR Point2 = wiMath::ClosestPointOnLineSegment(p1, p2, Center); + XMVECTOR Point2 = wi::math::ClosestPointOnLineSegment(p1, p2, Center); // If the distance to the center of the sphere to the point is less than // the radius of the sphere then it must intersect. Intersection = XMVectorOrInt(Intersection, XMVectorLessOrEqual(XMVector3LengthSq(XMVectorSubtract(Center, Point2)), RadiusSq)); // Edge 2,0 - XMVECTOR Point3 = wiMath::ClosestPointOnLineSegment(p2, p0, Center); + XMVECTOR Point3 = wi::math::ClosestPointOnLineSegment(p2, p0, Center); // If the distance to the center of the sphere to the point is less than // the radius of the sphere then it must intersect. diff --git a/WickedEngine/wiScene.h b/WickedEngine/wiScene.h index 409096423..726433dd9 100644 --- a/WickedEngine/wiScene.h +++ b/WickedEngine/wiScene.h @@ -1,7 +1,7 @@ #pragma once #include "CommonInclude.h" #include "wiEnums.h" -#include "wiIntersect.h" +#include "wiPrimitive.h" #include "wiEmittedParticle.h" #include "wiHairParticle.h" #include "shaders/ShaderInterop_Renderer.h" @@ -14,16 +14,18 @@ #include "wiSprite.h" #include "wiMath.h" #include "wiECS.h" -#include "wiScene_Decl.h" #include "wiVector.h" #include #include #include -class wiArchive; +namespace wi +{ + class Archive; +} -namespace wiScene +namespace wi::scene { struct NameComponent { @@ -33,7 +35,7 @@ namespace wiScene inline void operator=(std::string&& str) { name = std::move(str); } inline bool operator==(const std::string& str) const { return name.compare(str) == 0; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct LayerComponent @@ -45,7 +47,7 @@ namespace wiScene inline uint32_t GetLayerMask() const { return layerMask & propagationMask; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct TransformComponent @@ -66,7 +68,7 @@ namespace wiScene // The world matrix can be computed from local scale, rotation, translation // - by calling UpdateTransform() // - or by calling SetDirty() and letting the TransformUpdateSystem handle the updating - XMFLOAT4X4 world = IDENTITYMATRIX; + XMFLOAT4X4 world = wi::math::IDENTITY_MATRIX; inline void SetDirty(bool value = true) { if (value) { _flags |= DIRTY; } else { _flags &= ~DIRTY; } } inline bool IsDirty() const { return _flags & DIRTY; } @@ -99,7 +101,7 @@ namespace wiScene void Lerp(const TransformComponent& a, const TransformComponent& b, float t); void CatmullRom(const TransformComponent& a, const TransformComponent& b, const TransformComponent& c, const TransformComponent& d, float t); - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct PreviousFrameTransformComponent @@ -107,15 +109,15 @@ namespace wiScene // Non-serialized attributes: XMFLOAT4X4 world_prev; - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct HierarchyComponent { - wiECS::Entity parentID = wiECS::INVALID_ENTITY; + wi::ecs::Entity parentID = wi::ecs::INVALID_ENTITY; uint32_t layerMask_bind; // saved child layermask at the time of binding - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct MaterialComponent @@ -153,9 +155,9 @@ namespace wiScene SHADERTYPE_COUNT } shaderType = SHADERTYPE_PBR; - STENCILREF engineStencilRef = STENCILREF_DEFAULT; + wi::enums::STENCILREF engineStencilRef = wi::enums::STENCILREF_DEFAULT; uint8_t userStencilRef = 0; - BLENDMODE userBlendMode = BLENDMODE_OPAQUE; + wi::enums::BLENDMODE userBlendMode = wi::enums::BLENDMODE_OPAQUE; XMFLOAT4 baseColor = XMFLOAT4(1, 1, 1, 1); XMFLOAT4 specularColor = XMFLOAT4(1, 1, 1, 1); @@ -177,7 +179,7 @@ namespace wiScene float clearcoat = 0; float clearcoatRoughness = 0; - wiGraphics::ShadingRate shadingRate = wiGraphics::ShadingRate::RATE_1X1; + wi::graphics::ShadingRate shadingRate = wi::graphics::ShadingRate::RATE_1X1; XMFLOAT2 texAnimDirection = XMFLOAT2(0, 0); float texAnimFrameRate = 0.0f; @@ -205,16 +207,16 @@ namespace wiScene { std::string name; uint32_t uvset = 0; - std::shared_ptr resource; - const wiGraphics::GPUResource* GetGPUResource() const + wi::Resource resource; + const wi::graphics::GPUResource* GetGPUResource() const { - if (resource == nullptr || !resource->texture.IsValid()) + if (!resource.IsValid() || !resource.GetTexture().IsValid()) return nullptr; - return &resource->texture; + return &resource.GetTexture(); } int GetUVSet() const { - if (resource == nullptr || !resource->texture.IsValid()) + if (!resource.IsValid() || !resource.GetTexture().IsValid()) return -1; return (int)uvset; } @@ -248,7 +250,7 @@ namespace wiScene inline void SetOcclusionEnabled_Primary(bool value) { SetDirty(); if (value) { _flags |= OCCLUSION_PRIMARY; } else { _flags &= ~OCCLUSION_PRIMARY; } } inline void SetOcclusionEnabled_Secondary(bool value) { SetDirty(); if (value) { _flags |= OCCLUSION_SECONDARY; } else { _flags &= ~OCCLUSION_SECONDARY; } } - inline BLENDMODE GetBlendMode() const { if (userBlendMode == BLENDMODE_OPAQUE && (GetRenderTypes() & RENDERTYPE_TRANSPARENT)) return BLENDMODE_ALPHA; else return userBlendMode; } + inline wi::enums::BLENDMODE GetBlendMode() const { if (userBlendMode == wi::enums::BLENDMODE_OPAQUE && (GetRenderTypes() & wi::enums::RENDERTYPE_TRANSPARENT)) return wi::enums::BLENDMODE_ALPHA; else return userBlendMode; } inline bool IsCastingShadow() const { return _flags & CAST_SHADOW; } inline bool IsAlphaTestEnabled() const { return alphaRef <= 1.0f - 1.0f / 256.0f; } inline bool IsUsingVertexColors() const { return _flags & USE_VERTEXCOLORS; } @@ -301,7 +303,7 @@ namespace wiScene void WriteShaderMaterial(ShaderMaterial* dest) const; // Retrieve the array of textures from the material - void WriteTextures(const wiGraphics::GPUResource** dest, int count) const; + void WriteTextures(const wi::graphics::GPUResource** dest, int count) const; // Returns the bitwise OR of all the RENDERTYPE flags applicable to this material uint32_t GetRenderTypes() const; @@ -309,7 +311,7 @@ namespace wiScene // Create constant buffer and texture resources for GPU void CreateRenderData(); - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct MeshComponent @@ -341,7 +343,7 @@ namespace wiScene struct MeshSubset { - wiECS::Entity materialID = wiECS::INVALID_ENTITY; + wi::ecs::Entity materialID = wi::ecs::INVALID_ENTITY; uint32_t indexOffset = 0; uint32_t indexCount = 0; @@ -351,16 +353,16 @@ namespace wiScene wi::vector subsets; float tessellationFactor = 0.0f; - wiECS::Entity armatureID = wiECS::INVALID_ENTITY; + wi::ecs::Entity armatureID = wi::ecs::INVALID_ENTITY; // Terrain blend materials: // There are 4 blend materials, the first one (default) being the subset material // Must have TERRAIN flag enabled // Must have vertex colors to blend between materials // extra materials that are not set will use the base subset material - wiECS::Entity terrain_material1 = wiECS::INVALID_ENTITY; - wiECS::Entity terrain_material2 = wiECS::INVALID_ENTITY; - wiECS::Entity terrain_material3 = wiECS::INVALID_ENTITY; + wi::ecs::Entity terrain_material1 = wi::ecs::INVALID_ENTITY; + wi::ecs::Entity terrain_material2 = wi::ecs::INVALID_ENTITY; + wi::ecs::Entity terrain_material3 = wi::ecs::INVALID_ENTITY; // Morph Targets struct MeshMorphTarget @@ -372,22 +374,22 @@ namespace wiScene wi::vector targets; // Non-serialized attributes: - AABB aabb; - wiGraphics::GPUBuffer indexBuffer; - wiGraphics::GPUBuffer vertexBuffer_POS; - wiGraphics::GPUBuffer vertexBuffer_TAN; - wiGraphics::GPUBuffer vertexBuffer_UV0; - wiGraphics::GPUBuffer vertexBuffer_UV1; - wiGraphics::GPUBuffer vertexBuffer_BON; - wiGraphics::GPUBuffer vertexBuffer_COL; - wiGraphics::GPUBuffer vertexBuffer_ATL; - wiGraphics::GPUBuffer vertexBuffer_PRE; - wiGraphics::GPUBuffer streamoutBuffer_POS; - wiGraphics::GPUBuffer streamoutBuffer_TAN; + wi::primitive::AABB aabb; + wi::graphics::GPUBuffer indexBuffer; + wi::graphics::GPUBuffer vertexBuffer_POS; + wi::graphics::GPUBuffer vertexBuffer_TAN; + wi::graphics::GPUBuffer vertexBuffer_UV0; + wi::graphics::GPUBuffer vertexBuffer_UV1; + wi::graphics::GPUBuffer vertexBuffer_BON; + wi::graphics::GPUBuffer vertexBuffer_COL; + wi::graphics::GPUBuffer vertexBuffer_ATL; + wi::graphics::GPUBuffer vertexBuffer_PRE; + wi::graphics::GPUBuffer streamoutBuffer_POS; + wi::graphics::GPUBuffer streamoutBuffer_TAN; wi::vector vertex_subsets; - wiGraphics::GPUBuffer subsetBuffer; + wi::graphics::GPUBuffer subsetBuffer; - wiGraphics::RaytracingAccelerationStructure BLAS; + wi::graphics::RaytracingAccelerationStructure BLAS; enum BLAS_STATE { BLAS_STATE_NEEDS_REBUILD, @@ -415,9 +417,9 @@ namespace wiScene inline bool IsTerrain() const { return _flags & TERRAIN; } inline float GetTessellationFactor() const { return tessellationFactor; } - inline wiGraphics::IndexBufferFormat GetIndexFormat() const { return vertex_positions.size() > 65535 ? wiGraphics::IndexBufferFormat::UINT32 : wiGraphics::IndexBufferFormat::UINT16; } - inline size_t GetIndexStride() const { return GetIndexFormat() == wiGraphics::IndexBufferFormat::UINT32 ? sizeof(uint32_t) : sizeof(uint16_t); } - inline bool IsSkinned() const { return armatureID != wiECS::INVALID_ENTITY; } + inline wi::graphics::IndexBufferFormat GetIndexFormat() const { return vertex_positions.size() > 65535 ? wi::graphics::IndexBufferFormat::UINT32 : wi::graphics::IndexBufferFormat::UINT16; } + inline size_t GetIndexStride() const { return GetIndexFormat() == wi::graphics::IndexBufferFormat::UINT32 ? sizeof(uint32_t) : sizeof(uint16_t); } + inline bool IsSkinned() const { return armatureID != wi::ecs::INVALID_ENTITY; } // Recreates GPU resources for index/vertex buffers void CreateRenderData(); @@ -434,9 +436,9 @@ namespace wiScene void FlipNormals(); void Recenter(); void RecenterToBottom(); - SPHERE GetBoundingSphere() const; + wi::primitive::Sphere GetBoundingSphere() const; - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); struct Vertex_POS @@ -492,7 +494,7 @@ namespace wiScene return (normal_wind >> 24) & 0x000000FF; } - static const wiGraphics::Format FORMAT = wiGraphics::Format::R32G32B32A32_FLOAT; + static const wi::graphics::Format FORMAT = wi::graphics::Format::R32G32B32A32_FLOAT; }; struct Vertex_TEX { @@ -503,7 +505,7 @@ namespace wiScene tex = XMHALF2(texcoords.x, texcoords.y); } - static const wiGraphics::Format FORMAT = wiGraphics::Format::R16G16_FLOAT; + static const wi::graphics::Format FORMAT = wi::graphics::Format::R16G16_FLOAT; }; struct Vertex_BON { @@ -551,7 +553,7 @@ namespace wiScene struct Vertex_COL { uint32_t color = 0; - static const wiGraphics::Format FORMAT = wiGraphics::Format::R8G8B8A8_UNORM; + static const wi::graphics::Format FORMAT = wi::graphics::Format::R8G8B8A8_UNORM; }; struct Vertex_TAN { @@ -571,7 +573,7 @@ namespace wiScene tangent |= (uint)((t.w * 0.5f + 0.5f) * 255.0f) << 24; } - static const wiGraphics::Format FORMAT = wiGraphics::Format::R8G8B8A8_UNORM; + static const wi::graphics::Format FORMAT = wi::graphics::Format::R8G8B8A8_UNORM; }; // Non serialized attributes: @@ -591,7 +593,7 @@ namespace wiScene float swapInDistance = 100.0f; // Non-serialized attributes: - AABB aabb; + wi::primitive::AABB aabb; XMFLOAT4 color; float fadeThresholdRadius; wi::vector instances; @@ -600,7 +602,7 @@ namespace wiScene inline void SetDirty(bool value = true) { if (value) { _flags |= DIRTY; } else { _flags &= ~DIRTY; } } inline bool IsDirty() const { return _flags & DIRTY; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct ObjectComponent @@ -617,7 +619,7 @@ namespace wiScene }; uint32_t _flags = RENDERABLE | CAST_SHADOW; - wiECS::Entity meshID = wiECS::INVALID_ENTITY; + wi::ecs::Entity meshID = wi::ecs::INVALID_ENTITY; uint32_t cascadeMask = 0; // which shadow cascades to skip from lowest detail to highest detail (0: skip none, 1: skip first, etc...) uint32_t rendertypeMask = 0; XMFLOAT4 color = XMFLOAT4(1, 1, 1, 1); @@ -631,9 +633,9 @@ namespace wiScene // Non-serialized attributes: - wiGraphics::Texture lightmap; - wiGraphics::RenderPass renderpass_lightmap_clear; - wiGraphics::RenderPass renderpass_lightmap_accumulate; + wi::graphics::Texture lightmap; + wi::graphics::RenderPass renderpass_lightmap_clear; + wi::graphics::RenderPass renderpass_lightmap_accumulate; mutable uint32_t lightmapIterationCount = 0; XMFLOAT3 center = XMFLOAT3(0, 0, 0); @@ -646,7 +648,7 @@ namespace wiScene // occlusion result history bitfield (32 bit->32 frame history) mutable uint32_t occlusionHistory = ~0; - mutable int occlusionQueries[wiGraphics::GraphicsDevice::GetBufferCount() + 1]; + mutable int occlusionQueries[wi::graphics::GraphicsDevice::GetBufferCount() + 1]; inline bool IsOccluded() const { @@ -686,7 +688,7 @@ namespace wiScene void SaveLightmap(); void CompressLightmap(); - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct RigidBodyPhysicsComponent @@ -738,7 +740,7 @@ namespace wiScene inline bool IsDisableDeactivation() const { return _flags & DISABLE_DEACTIVATION; } inline bool IsKinematic() const { return _flags & KINEMATIC; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct SoftBodyPhysicsComponent @@ -761,11 +763,11 @@ namespace wiScene // Non-serialized attributes: void* physicsobject = nullptr; - XMFLOAT4X4 worldMatrix = IDENTITYMATRIX; + XMFLOAT4X4 worldMatrix = wi::math::IDENTITY_MATRIX; wi::vector vertex_positions_simulation; // graphics vertices after simulation (world space) wi::vectorvertex_tangents_tmp; wi::vector vertex_tangents_simulation; - AABB aabb; + wi::primitive::AABB aabb; inline void SetDisableDeactivation(bool value) { if (value) { _flags |= DISABLE_DEACTIVATION; } else { _flags &= ~DISABLE_DEACTIVATION; } } @@ -774,7 +776,7 @@ namespace wiScene // Create physics represenation of graphics mesh void CreateFromMesh(const MeshComponent& mesh); - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct ArmatureComponent @@ -785,18 +787,18 @@ namespace wiScene }; uint32_t _flags = EMPTY; - wi::vector boneCollection; + wi::vector boneCollection; wi::vector inverseBindMatrices; // Non-serialized attributes: - AABB aabb; + wi::primitive::AABB aabb; wi::vector boneData; - wiGraphics::GPUBuffer boneBuffer; + wi::graphics::GPUBuffer boneBuffer; void CreateRenderData(); - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct LightComponent @@ -841,7 +843,7 @@ namespace wiScene XMFLOAT3 right; mutable int occlusionquery = -1; - wi::vector> lensFlareRimTextures; + wi::vector lensFlareRimTextures; inline void SetCastShadow(bool value) { if (value) { _flags |= CAST_SHADOW; } else { _flags &= ~CAST_SHADOW; } } inline void SetVolumetricsEnabled(bool value) { if (value) { _flags |= VOLUMETRICS; } else { _flags &= ~VOLUMETRICS; } } @@ -858,7 +860,7 @@ namespace wiScene inline void SetType(LightType val) { type = val; } inline LightType GetType() const { return type; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct CameraComponent @@ -886,11 +888,12 @@ namespace wiScene XMFLOAT3 Up = XMFLOAT3(0, 1, 0); XMFLOAT3X3 rotationMatrix; XMFLOAT4X4 View, Projection, VP; - Frustum frustum; + wi::primitive::Frustum frustum; XMFLOAT4X4 InvView, InvProjection, InvVP; XMFLOAT2 jitter; XMFLOAT4 clipPlane = XMFLOAT4(0, 0, 0, 0); // default: no clip plane - wiCanvas canvas; + wi::Canvas canvas; + uint32_t sample_count = 1; int texture_depth_index = -1; int texture_lineardepth_index = -1; int texture_gbuffer0_index = -1; @@ -926,7 +929,7 @@ namespace wiScene inline bool IsDirty() const { return _flags & DIRTY; } inline bool IsCustomProjectionEnabled() const { return _flags & CUSTOM_PROJECTION; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct EnvironmentProbeComponent @@ -952,7 +955,7 @@ namespace wiScene inline bool IsDirty() const { return _flags & DIRTY; } inline bool IsRealTime() const { return _flags & REALTIME; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct ForceFieldComponent @@ -974,7 +977,7 @@ namespace wiScene inline float GetRange() const { return range_global; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct DecalComponent @@ -993,12 +996,12 @@ namespace wiScene float range; XMFLOAT4X4 world; - std::shared_ptr texture; - std::shared_ptr normal; + wi::Resource texture; + wi::Resource normal; inline float GetOpacity() const { return color.w; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct AnimationDataComponent @@ -1012,7 +1015,7 @@ namespace wiScene wi::vector keyframe_times; wi::vector keyframe_data; - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct AnimationComponent @@ -1038,7 +1041,7 @@ namespace wiScene }; uint32_t _flags = LOOPED; - wiECS::Entity target = wiECS::INVALID_ENTITY; + wi::ecs::Entity target = wi::ecs::INVALID_ENTITY; int samplerIndex = -1; enum Path @@ -1059,7 +1062,7 @@ namespace wiScene }; uint32_t _flags = LOOPED; - wiECS::Entity data = wiECS::INVALID_ENTITY; + wi::ecs::Entity data = wi::ecs::INVALID_ENTITY; enum Mode { @@ -1088,7 +1091,7 @@ namespace wiScene inline void Stop() { Pause(); timer = 0.0f; } inline void SetLooped(bool value = true) { if (value) { _flags |= LOOPED; } else { _flags &= ~LOOPED; } } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct WeatherComponent @@ -1136,7 +1139,7 @@ namespace wiScene float windWaveSize = 1; float windSpeed = 1; - wiOcean::OceanParameters oceanParameters; + wi::Ocean::OceanParameters oceanParameters; AtmosphereParameters atmosphereParameters; VolumetricCloudParameters volumetricCloudParameters; @@ -1145,10 +1148,10 @@ namespace wiScene // Non-serialized attributes: uint32_t most_important_light_index = ~0; - std::shared_ptr skyMap; - std::shared_ptr colorGradingMap; + wi::Resource skyMap; + wi::Resource colorGradingMap; - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct SoundComponent @@ -1163,8 +1166,8 @@ namespace wiScene uint32_t _flags = LOOPED; std::string filename; - std::shared_ptr soundResource; - wiAudio::SoundInstance soundinstance; + wi::Resource soundResource; + wi::audio::SoundInstance soundinstance; float volume = 1; inline bool IsPlaying() const { return _flags & PLAYING; } @@ -1176,7 +1179,7 @@ namespace wiScene inline void SetLooped(bool value = true) { if (value) { _flags |= LOOPED; } else { _flags &= ~LOOPED; } } inline void SetDisable3D(bool value = true) { if (value) { _flags |= DISABLE_3D; } else { _flags &= ~DISABLE_3D; } } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct InverseKinematicsComponent @@ -1188,14 +1191,14 @@ namespace wiScene }; uint32_t _flags = EMPTY; - wiECS::Entity target = wiECS::INVALID_ENTITY; // which entity to follow (must have a transform component) + wi::ecs::Entity target = wi::ecs::INVALID_ENTITY; // which entity to follow (must have a transform component) uint32_t chain_length = ~0; // ~0 means: compute until the root uint32_t iteration_count = 1; inline void SetDisabled(bool value = true) { if (value) { _flags |= DISABLED; } else { _flags &= ~DISABLED; } } inline bool IsDisabled() const { return _flags & DISABLED; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct SpringComponent @@ -1228,40 +1231,40 @@ namespace wiScene inline bool IsStretchEnabled() const { return _flags & STRETCH_ENABLED; } inline bool IsGravityEnabled() const { return _flags & GRAVITY_ENABLED; } - void Serialize(wiArchive& archive, wiECS::EntitySerializer& seri); + void Serialize(wi::Archive& archive, wi::ecs::EntitySerializer& seri); }; struct Scene { - wiECS::ComponentManager names; - wiECS::ComponentManager layers; - wiECS::ComponentManager transforms; - wiECS::ComponentManager prev_transforms; - wiECS::ComponentManager hierarchy; - wiECS::ComponentManager materials; - wiECS::ComponentManager meshes; - wiECS::ComponentManager impostors; - wiECS::ComponentManager objects; - wiECS::ComponentManager aabb_objects; - wiECS::ComponentManager rigidbodies; - wiECS::ComponentManager softbodies; - wiECS::ComponentManager armatures; - wiECS::ComponentManager lights; - wiECS::ComponentManager aabb_lights; - wiECS::ComponentManager cameras; - wiECS::ComponentManager probes; - wiECS::ComponentManager aabb_probes; - wiECS::ComponentManager forces; - wiECS::ComponentManager decals; - wiECS::ComponentManager aabb_decals; - wiECS::ComponentManager animations; - wiECS::ComponentManager animation_datas; - wiECS::ComponentManager emitters; - wiECS::ComponentManager hairs; - wiECS::ComponentManager weathers; - wiECS::ComponentManager sounds; - wiECS::ComponentManager inverse_kinematics; - wiECS::ComponentManager springs; + wi::ecs::ComponentManager names; + wi::ecs::ComponentManager layers; + wi::ecs::ComponentManager transforms; + wi::ecs::ComponentManager prev_transforms; + wi::ecs::ComponentManager hierarchy; + wi::ecs::ComponentManager materials; + wi::ecs::ComponentManager meshes; + wi::ecs::ComponentManager impostors; + wi::ecs::ComponentManager objects; + wi::ecs::ComponentManager aabb_objects; + wi::ecs::ComponentManager rigidbodies; + wi::ecs::ComponentManager softbodies; + wi::ecs::ComponentManager armatures; + wi::ecs::ComponentManager lights; + wi::ecs::ComponentManager aabb_lights; + wi::ecs::ComponentManager cameras; + wi::ecs::ComponentManager probes; + wi::ecs::ComponentManager aabb_probes; + wi::ecs::ComponentManager forces; + wi::ecs::ComponentManager decals; + wi::ecs::ComponentManager aabb_decals; + wi::ecs::ComponentManager animations; + wi::ecs::ComponentManager animation_datas; + wi::ecs::ComponentManager emitters; + wi::ecs::ComponentManager hairs; + wi::ecs::ComponentManager weathers; + wi::ecs::ComponentManager sounds; + wi::ecs::ComponentManager inverse_kinematics; + wi::ecs::ComponentManager springs; // Non-serialized attributes: float dt = 0; @@ -1272,14 +1275,14 @@ namespace wiScene uint32_t flags = EMPTY; - wiSpinLock locker; - AABB bounds; - wi::vector parallel_bounds; + wi::SpinLock locker; + wi::primitive::AABB bounds; + wi::vector parallel_bounds; WeatherComponent weather; - wiGraphics::RaytracingAccelerationStructure TLAS; - wiGraphics::GPUBuffer TLAS_instancesUpload[wiGraphics::GraphicsDevice::GetBufferCount()]; + wi::graphics::RaytracingAccelerationStructure TLAS; + wi::graphics::GPUBuffer TLAS_instancesUpload[wi::graphics::GraphicsDevice::GetBufferCount()]; void* TLAS_instancesMapped = nullptr; - wiGPUBVH BVH; // this is for non-hardware accelerated raytracing + wi::GPUBVH BVH; // this is for non-hardware accelerated raytracing mutable bool acceleration_structure_update_requested = false; void SetAccelerationStructureUpdateRequested(bool value = true) { acceleration_structure_update_requested = value; } bool IsAccelerationStructureUpdateRequested() const { return acceleration_structure_update_requested; } @@ -1292,68 +1295,68 @@ namespace wiScene // 1) objects // 2) hair particles // 3) emitted particles - wiGraphics::GPUBuffer instanceUploadBuffer[wiGraphics::GraphicsDevice::GetBufferCount()]; + wi::graphics::GPUBuffer instanceUploadBuffer[wi::graphics::GraphicsDevice::GetBufferCount()]; ShaderMeshInstance* instanceArrayMapped = nullptr; size_t instanceArraySize = 0; - wiGraphics::GPUBuffer instanceBuffer; + wi::graphics::GPUBuffer instanceBuffer; // Meshes for bindless visiblity indexing: // contains in order: // 1) meshes // 2) hair particles // 3) emitted particles - wiGraphics::GPUBuffer meshUploadBuffer[wiGraphics::GraphicsDevice::GetBufferCount()]; + wi::graphics::GPUBuffer meshUploadBuffer[wi::graphics::GraphicsDevice::GetBufferCount()]; ShaderMesh* meshArrayMapped = nullptr; size_t meshArraySize = 0; - wiGraphics::GPUBuffer meshBuffer; + wi::graphics::GPUBuffer meshBuffer; // Materials for bindless visibility indexing: - wiGraphics::GPUBuffer materialUploadBuffer[wiGraphics::GraphicsDevice::GetBufferCount()]; + wi::graphics::GPUBuffer materialUploadBuffer[wi::graphics::GraphicsDevice::GetBufferCount()]; ShaderMaterial* materialArrayMapped = nullptr; size_t materialArraySize = 0; - wiGraphics::GPUBuffer materialBuffer; + wi::graphics::GPUBuffer materialBuffer; // Occlusion query state: - wiGraphics::GPUQueryHeap queryHeap; - wiGraphics::GPUBuffer queryResultBuffer[arraysize(ObjectComponent::occlusionQueries)]; - wiGraphics::GPUBuffer queryPredicationBuffer; + wi::graphics::GPUQueryHeap queryHeap; + wi::graphics::GPUBuffer queryResultBuffer[arraysize(ObjectComponent::occlusionQueries)]; + wi::graphics::GPUBuffer queryPredicationBuffer; int queryheap_idx = 0; mutable std::atomic queryAllocator{ 0 }; // Surfel GI resources: - wiGraphics::GPUBuffer surfelBuffer; - wiGraphics::GPUBuffer surfelDataBuffer; - wiGraphics::GPUBuffer surfelAliveBuffer[2]; - wiGraphics::GPUBuffer surfelDeadBuffer; - wiGraphics::GPUBuffer surfelStatsBuffer; - wiGraphics::GPUBuffer surfelGridBuffer; - wiGraphics::GPUBuffer surfelCellBuffer; - wiGraphics::Texture surfelMomentsTexture[2]; + wi::graphics::GPUBuffer surfelBuffer; + wi::graphics::GPUBuffer surfelDataBuffer; + wi::graphics::GPUBuffer surfelAliveBuffer[2]; + wi::graphics::GPUBuffer surfelDeadBuffer; + wi::graphics::GPUBuffer surfelStatsBuffer; + wi::graphics::GPUBuffer surfelGridBuffer; + wi::graphics::GPUBuffer surfelCellBuffer; + wi::graphics::Texture surfelMomentsTexture[2]; // Environment probe cubemap array state: static constexpr uint32_t envmapCount = 16; static constexpr uint32_t envmapRes = 128; static constexpr uint32_t envmapMIPs = 8; - wiGraphics::Texture envrenderingDepthBuffer; - wiGraphics::Texture envmapArray; - wi::vector renderpasses_envmap; + wi::graphics::Texture envrenderingDepthBuffer; + wi::graphics::Texture envmapArray; + wi::vector renderpasses_envmap; // Impostor texture array state: static constexpr uint32_t maxImpostorCount = 8; static constexpr uint32_t impostorTextureDim = 128; - wiGraphics::Texture impostorDepthStencil; - wiGraphics::Texture impostorArray; - wi::vector renderpasses_impostor; + wi::graphics::Texture impostorDepthStencil; + wi::graphics::Texture impostorArray; + wi::vector renderpasses_impostor; mutable std::atomic_bool lightmap_refresh_needed{ false }; // Ocean GPU state: - wiOcean ocean; + wi::Ocean ocean; void OceanRegenerate() { ocean.Create(weather.oceanParameters); } // Simple water ripple sprites: - mutable wi::vector waterRipples; + mutable wi::vector waterRipples; void PutWaterRipple(const std::string& image, const XMFLOAT3& pos); // Update all components by a given timestep (in seconds): @@ -1366,26 +1369,26 @@ namespace wiScene void Merge(Scene& other); // Removes a specific entity from the scene (if it exists): - void Entity_Remove(wiECS::Entity entity); + void Entity_Remove(wi::ecs::Entity entity); // Finds the first entity by the name (if it exists, otherwise returns INVALID_ENTITY): - wiECS::Entity Entity_FindByName(const std::string& name); + wi::ecs::Entity Entity_FindByName(const std::string& name); // Duplicates all of an entity's components and creates a new entity with them (recursively keeps hierarchy): - wiECS::Entity Entity_Duplicate(wiECS::Entity entity); + wi::ecs::Entity Entity_Duplicate(wi::ecs::Entity entity); // Serializes entity and all of its components to archive: // Returns either the new entity that was read, or the original entity that was written // This serialization is recursive and serializes entity hierarchy as well - wiECS::Entity Entity_Serialize(wiArchive& archive, wiECS::Entity entity = wiECS::INVALID_ENTITY); + wi::ecs::Entity Entity_Serialize(wi::Archive& archive, wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY); - wiECS::Entity Entity_CreateMaterial( + wi::ecs::Entity Entity_CreateMaterial( const std::string& name ); - wiECS::Entity Entity_CreateObject( + wi::ecs::Entity Entity_CreateObject( const std::string& name ); - wiECS::Entity Entity_CreateMesh( + wi::ecs::Entity Entity_CreateMesh( const std::string& name ); - wiECS::Entity Entity_CreateLight( + wi::ecs::Entity Entity_CreateLight( const std::string& name, const XMFLOAT3& position = XMFLOAT3(0, 0, 0), const XMFLOAT3& color = XMFLOAT3(1, 1, 1), @@ -1393,32 +1396,32 @@ namespace wiScene float range = 10, LightComponent::LightType type = LightComponent::POINT ); - wiECS::Entity Entity_CreateForce( + wi::ecs::Entity Entity_CreateForce( const std::string& name, const XMFLOAT3& position = XMFLOAT3(0, 0, 0) ); - wiECS::Entity Entity_CreateEnvironmentProbe( + wi::ecs::Entity Entity_CreateEnvironmentProbe( const std::string& name, const XMFLOAT3& position = XMFLOAT3(0, 0, 0) ); - wiECS::Entity Entity_CreateDecal( + wi::ecs::Entity Entity_CreateDecal( const std::string& name, const std::string& textureName, const std::string& normalMapName = "" ); - wiECS::Entity Entity_CreateCamera( + wi::ecs::Entity Entity_CreateCamera( const std::string& name, float width, float height, float nearPlane = 0.01f, float farPlane = 1000.0f, float fov = XM_PIDIV4 ); - wiECS::Entity Entity_CreateEmitter( + wi::ecs::Entity Entity_CreateEmitter( const std::string& name, const XMFLOAT3& position = XMFLOAT3(0, 0, 0) ); - wiECS::Entity Entity_CreateHair( + wi::ecs::Entity Entity_CreateHair( const std::string& name, const XMFLOAT3& position = XMFLOAT3(0, 0, 0) ); - wiECS::Entity Entity_CreateSound( + wi::ecs::Entity Entity_CreateSound( const std::string& name, const std::string& filename, const XMFLOAT3& position = XMFLOAT3(0, 0, 0) @@ -1426,33 +1429,33 @@ namespace wiScene // Attaches an entity to a parent: // child_already_in_local_space : child won't be transformed from world space to local space - void Component_Attach(wiECS::Entity entity, wiECS::Entity parent, bool child_already_in_local_space = false); + void Component_Attach(wi::ecs::Entity entity, wi::ecs::Entity parent, bool child_already_in_local_space = false); // Detaches the entity from its parent (if it is attached): - void Component_Detach(wiECS::Entity entity); + void Component_Detach(wi::ecs::Entity entity); // Detaches all children from an entity (if there are any): - void Component_DetachChildren(wiECS::Entity parent); + void Component_DetachChildren(wi::ecs::Entity parent); - void Serialize(wiArchive& archive); + void Serialize(wi::Archive& archive); - void RunPreviousFrameTransformUpdateSystem(wiJobSystem::context& ctx); - void RunAnimationUpdateSystem(wiJobSystem::context& ctx); - void RunTransformUpdateSystem(wiJobSystem::context& ctx); - void RunHierarchyUpdateSystem(wiJobSystem::context& ctx); - void RunSpringUpdateSystem(wiJobSystem::context& ctx); - void RunInverseKinematicsUpdateSystem(wiJobSystem::context& ctx); - void RunArmatureUpdateSystem(wiJobSystem::context& ctx); - void RunMeshUpdateSystem(wiJobSystem::context& ctx); - void RunMaterialUpdateSystem(wiJobSystem::context& ctx); - void RunImpostorUpdateSystem(wiJobSystem::context& ctx); - void RunObjectUpdateSystem(wiJobSystem::context& ctx); - void RunCameraUpdateSystem(wiJobSystem::context& ctx); - void RunDecalUpdateSystem(wiJobSystem::context& ctx); - void RunProbeUpdateSystem(wiJobSystem::context& ctx); - void RunForceUpdateSystem(wiJobSystem::context& ctx); - void RunLightUpdateSystem(wiJobSystem::context& ctx); - void RunParticleUpdateSystem(wiJobSystem::context& ctx); - void RunWeatherUpdateSystem(wiJobSystem::context& ctx); - void RunSoundUpdateSystem(wiJobSystem::context& ctx); + void RunPreviousFrameTransformUpdateSystem(wi::jobsystem::context& ctx); + void RunAnimationUpdateSystem(wi::jobsystem::context& ctx); + void RunTransformUpdateSystem(wi::jobsystem::context& ctx); + void RunHierarchyUpdateSystem(wi::jobsystem::context& ctx); + void RunSpringUpdateSystem(wi::jobsystem::context& ctx); + void RunInverseKinematicsUpdateSystem(wi::jobsystem::context& ctx); + void RunArmatureUpdateSystem(wi::jobsystem::context& ctx); + void RunMeshUpdateSystem(wi::jobsystem::context& ctx); + void RunMaterialUpdateSystem(wi::jobsystem::context& ctx); + void RunImpostorUpdateSystem(wi::jobsystem::context& ctx); + void RunObjectUpdateSystem(wi::jobsystem::context& ctx); + void RunCameraUpdateSystem(wi::jobsystem::context& ctx); + void RunDecalUpdateSystem(wi::jobsystem::context& ctx); + void RunProbeUpdateSystem(wi::jobsystem::context& ctx); + void RunForceUpdateSystem(wi::jobsystem::context& ctx); + void RunLightUpdateSystem(wi::jobsystem::context& ctx); + void RunParticleUpdateSystem(wi::jobsystem::context& ctx); + void RunWeatherUpdateSystem(wi::jobsystem::context& ctx); + void RunSoundUpdateSystem(wi::jobsystem::context& ctx); }; // Returns skinned vertex position in armature local space @@ -1480,7 +1483,7 @@ namespace wiScene // attached : everything will be attached to a base entity // // returns INVALID_ENTITY if attached argument was false, else it returns the base entity handle - wiECS::Entity LoadModel(const std::string& fileName, const XMMATRIX& transformMatrix = XMMatrixIdentity(), bool attached = false); + wi::ecs::Entity LoadModel(const std::string& fileName, const XMMATRIX& transformMatrix = XMMatrixIdentity(), bool attached = false); // Helper function to open a wiscene file and add the contents to the specified scene. This is thread safe as it doesn't modify global scene // scene : the scene that will contain the model @@ -1489,11 +1492,11 @@ namespace wiScene // attached : everything will be attached to a base entity // // returns INVALID_ENTITY if attached argument was false, else it returns the base entity handle - wiECS::Entity LoadModel(Scene& scene, const std::string& fileName, const XMMATRIX& transformMatrix = XMMatrixIdentity(), bool attached = false); + wi::ecs::Entity LoadModel(Scene& scene, const std::string& fileName, const XMMATRIX& transformMatrix = XMMatrixIdentity(), bool attached = false); struct PickResult { - wiECS::Entity entity = wiECS::INVALID_ENTITY; + wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY; XMFLOAT3 position = XMFLOAT3(0, 0, 0); XMFLOAT3 normal = XMFLOAT3(0, 0, 0); float distance = std::numeric_limits::max(); @@ -1502,7 +1505,7 @@ namespace wiScene int vertexID1 = -1; int vertexID2 = -1; XMFLOAT2 bary = XMFLOAT2(0, 0); - XMFLOAT4X4 orientation = IDENTITYMATRIX; + XMFLOAT4X4 orientation = wi::math::IDENTITY_MATRIX; bool operator==(const PickResult& other) { @@ -1514,17 +1517,16 @@ namespace wiScene // renderTypeMask : filter based on render type // layerMask : filter based on layer // scene : the scene that will be traced against the ray - PickResult Pick(const RAY& ray, uint32_t renderTypeMask = RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); + PickResult Pick(const wi::primitive::Ray& ray, uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); struct SceneIntersectSphereResult { - wiECS::Entity entity = wiECS::INVALID_ENTITY; + wi::ecs::Entity entity = wi::ecs::INVALID_ENTITY; XMFLOAT3 position = XMFLOAT3(0, 0, 0); XMFLOAT3 normal = XMFLOAT3(0, 0, 0); float depth = 0; }; - SceneIntersectSphereResult SceneIntersectSphere(const SPHERE& sphere, uint32_t renderTypeMask = RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); - SceneIntersectSphereResult SceneIntersectCapsule(const CAPSULE& capsule, uint32_t renderTypeMask = RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); + SceneIntersectSphereResult SceneIntersectSphere(const wi::primitive::Sphere& sphere, uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); + SceneIntersectSphereResult SceneIntersectCapsule(const wi::primitive::Capsule& capsule, uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE, uint32_t layerMask = ~0, const Scene& scene = GetScene()); } - diff --git a/WickedEngine/wiScene_BindLua.cpp b/WickedEngine/wiScene_BindLua.cpp index cbc23906f..e996a4297 100644 --- a/WickedEngine/wiScene_BindLua.cpp +++ b/WickedEngine/wiScene_BindLua.cpp @@ -1,38 +1,37 @@ #include "wiScene_BindLua.h" #include "wiScene.h" -#include "Vector_BindLua.h" -#include "Matrix_BindLua.h" +#include "wiMath_BindLua.h" #include "wiEmittedParticle.h" -#include "Texture_BindLua.h" -#include "wiIntersect_BindLua.h" +#include "wiTexture_BindLua.h" +#include "wiPrimitive_BindLua.h" -using namespace wiECS; -using namespace wiScene; -using namespace wiIntersect_BindLua; +using namespace wi::ecs; +using namespace wi::scene; +using namespace wi::lua::primitive; -namespace wiScene_BindLua +namespace wi::lua::scene { int CreateEntity_BindLua(lua_State* L) { Entity entity = CreateEntity(); - wiLua::SSetLongLong(L, entity); + wi::lua::SSetLongLong(L, entity); return 1; } int GetCamera(lua_State* L) { - Luna::push(L, new CameraComponent_BindLua(&wiScene::GetCamera())); + Luna::push(L, new CameraComponent_BindLua(&wi::scene::GetCamera())); return 1; } int GetScene(lua_State* L) { - Luna::push(L, new Scene_BindLua(&wiScene::GetScene())); + Luna::push(L, new Scene_BindLua(&wi::scene::GetScene())); return 1; } int LoadModel(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Scene_BindLua* custom_scene = Luna::lightcheck(L, 1); @@ -41,8 +40,8 @@ int LoadModel(lua_State* L) // Overload 1: thread safe version if (argc > 1) { - std::string fileName = wiLua::SGetString(L, 2); - fileName = wiLua::GetScriptPath() + fileName; + std::string fileName = wi::lua::SGetString(L, 2); + fileName = wi::lua::GetScriptPath() + fileName; XMMATRIX transform = XMMatrixIdentity(); if (argc > 2) { @@ -53,24 +52,24 @@ int LoadModel(lua_State* L) } else { - wiLua::SError(L, "LoadModel(Scene scene, string fileName, opt Matrix transform) argument is not a matrix!"); + wi::lua::SError(L, "LoadModel(Scene scene, string fileName, opt Matrix transform) argument is not a matrix!"); } } - Entity root = wiScene::LoadModel(*custom_scene->scene, fileName, transform, true); - wiLua::SSetLongLong(L, root); + Entity root = wi::scene::LoadModel(*custom_scene->scene, fileName, transform, true); + wi::lua::SSetLongLong(L, root); return 1; } else { - wiLua::SError(L, "LoadModel(Scene scene, string fileName, opt Matrix transform) not enough arguments!"); + wi::lua::SError(L, "LoadModel(Scene scene, string fileName, opt Matrix transform) not enough arguments!"); return 0; } } else { // Overload 2: global scene version - std::string fileName = wiLua::SGetString(L, 1); - fileName = wiLua::GetScriptPath() + fileName; + std::string fileName = wi::lua::SGetString(L, 1); + fileName = wi::lua::GetScriptPath() + fileName; XMMATRIX transform = XMMatrixIdentity(); if (argc > 1) { @@ -81,37 +80,37 @@ int LoadModel(lua_State* L) } else { - wiLua::SError(L, "LoadModel(string fileName, opt Matrix transform) argument is not a matrix!"); + wi::lua::SError(L, "LoadModel(string fileName, opt Matrix transform) argument is not a matrix!"); } } - Entity root = wiScene::LoadModel(fileName, transform, true); - wiLua::SSetLongLong(L, root); + Entity root = wi::scene::LoadModel(fileName, transform, true); + wi::lua::SSetLongLong(L, root); return 1; } } else { - wiLua::SError(L, "LoadModel(string fileName, opt Matrix transform) not enough arguments!"); + wi::lua::SError(L, "LoadModel(string fileName, opt Matrix transform) not enough arguments!"); } return 0; } int Pick(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Ray_BindLua* ray = Luna::lightcheck(L, 1); if (ray != nullptr) { - uint32_t renderTypeMask = RENDERTYPE_OPAQUE; + uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE; uint32_t layerMask = 0xFFFFFFFF; - Scene* scene = &wiScene::GetScene(); + Scene* scene = &wi::scene::GetScene(); if (argc > 1) { - renderTypeMask = (uint32_t)wiLua::SGetInt(L, 2); + renderTypeMask = (uint32_t)wi::lua::SGetInt(L, 2); if (argc > 2) { - int mask = wiLua::SGetInt(L, 3); + int mask = wi::lua::SGetInt(L, 3); layerMask = *reinterpret_cast(&mask); if (argc > 3) @@ -123,45 +122,45 @@ int Pick(lua_State* L) } else { - wiLua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); + wi::lua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); } } } } - auto pick = wiScene::Pick(ray->ray, renderTypeMask, layerMask, *scene); - wiLua::SSetLongLong(L, pick.entity); + auto pick = wi::scene::Pick(ray->ray, renderTypeMask, layerMask, *scene); + wi::lua::SSetLongLong(L, pick.entity); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.position))); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.normal))); - wiLua::SSetFloat(L, pick.distance); + wi::lua::SSetFloat(L, pick.distance); return 4; } - wiLua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Ray type!"); + wi::lua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Ray type!"); } else { - wiLua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); + wi::lua::SError(L, "Pick(Ray ray, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); } return 0; } int SceneIntersectSphere(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Sphere_BindLua* sphere = Luna::lightcheck(L, 1); if (sphere != nullptr) { - uint32_t renderTypeMask = RENDERTYPE_OPAQUE; + uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE; uint32_t layerMask = 0xFFFFFFFF; - Scene* scene = &wiScene::GetScene(); + Scene* scene = &wi::scene::GetScene(); if (argc > 1) { - renderTypeMask = (uint32_t)wiLua::SGetInt(L, 2); + renderTypeMask = (uint32_t)wi::lua::SGetInt(L, 2); if (argc > 2) { - int mask = wiLua::SGetInt(L, 3); + int mask = wi::lua::SGetInt(L, 3); layerMask = *reinterpret_cast(&mask); if (argc > 3) @@ -173,45 +172,45 @@ int SceneIntersectSphere(lua_State* L) } else { - wiLua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); + wi::lua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); } } } } - auto pick = wiScene::SceneIntersectSphere(sphere->sphere, renderTypeMask, layerMask, *scene); - wiLua::SSetLongLong(L, pick.entity); + auto pick = wi::scene::SceneIntersectSphere(sphere->sphere, renderTypeMask, layerMask, *scene); + wi::lua::SSetLongLong(L, pick.entity); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.position))); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.normal))); - wiLua::SSetFloat(L, pick.depth); + wi::lua::SSetFloat(L, pick.depth); return 4; } - wiLua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Sphere type!"); + wi::lua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Sphere type!"); } else { - wiLua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); + wi::lua::SError(L, "SceneIntersectSphere(Sphere sphere, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); } return 0; } int SceneIntersectCapsule(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Capsule_BindLua* capsule = Luna::lightcheck(L, 1); if (capsule != nullptr) { - uint32_t renderTypeMask = RENDERTYPE_OPAQUE; + uint32_t renderTypeMask = wi::enums::RENDERTYPE_OPAQUE; uint32_t layerMask = 0xFFFFFFFF; - Scene* scene = &wiScene::GetScene(); + Scene* scene = &wi::scene::GetScene(); if (argc > 1) { - renderTypeMask = (uint32_t)wiLua::SGetInt(L, 2); + renderTypeMask = (uint32_t)wi::lua::SGetInt(L, 2); if (argc > 2) { - int mask = wiLua::SGetInt(L, 3); + int mask = wi::lua::SGetInt(L, 3); layerMask = *reinterpret_cast(&mask); if (argc > 3) @@ -223,24 +222,24 @@ int SceneIntersectCapsule(lua_State* L) } else { - wiLua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); + wi::lua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) last argument is not of type Scene!"); } } } } - auto pick = wiScene::SceneIntersectCapsule(capsule->capsule, renderTypeMask, layerMask, *scene); - wiLua::SSetLongLong(L, pick.entity); + auto pick = wi::scene::SceneIntersectCapsule(capsule->capsule, renderTypeMask, layerMask, *scene); + wi::lua::SSetLongLong(L, pick.entity); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.position))); Luna::push(L, new Vector_BindLua(XMLoadFloat3(&pick.normal))); - wiLua::SSetFloat(L, pick.depth); + wi::lua::SSetFloat(L, pick.depth); return 4; } - wiLua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Capsule type!"); + wi::lua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) first argument must be of Capsule type!"); } else { - wiLua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); + wi::lua::SError(L, "SceneIntersectCapsule(Capsule capsule, opt PICKTYPE pickType, opt uint layerMask, opt Scene scene) not enough arguments!"); } return 0; @@ -253,31 +252,31 @@ void Bind() { initialized = true; - lua_State* L = wiLua::GetLuaState(); + lua_State* L = wi::lua::GetLuaState(); - wiLua::RegisterFunc("CreateEntity", CreateEntity_BindLua); - wiLua::RunText("INVALID_ENTITY = 0"); + wi::lua::RegisterFunc("CreateEntity", CreateEntity_BindLua); + wi::lua::RunText("INVALID_ENTITY = 0"); - wiLua::RunText("DIRECTIONAL = 0"); - wiLua::RunText("POINT = 1"); - wiLua::RunText("SPOT = 2"); - wiLua::RunText("SPHERE = 3"); - wiLua::RunText("DISC = 4"); - wiLua::RunText("RECTANGLE = 5"); - wiLua::RunText("TUBE = 6"); + wi::lua::RunText("DIRECTIONAL = 0"); + wi::lua::RunText("POINT = 1"); + wi::lua::RunText("SPOT = 2"); + wi::lua::RunText("SPHERE = 3"); + wi::lua::RunText("DISC = 4"); + wi::lua::RunText("RECTANGLE = 5"); + wi::lua::RunText("TUBE = 6"); - wiLua::RunText("STENCILREF_EMPTY = 0"); - wiLua::RunText("STENCILREF_DEFAULT = 1"); - wiLua::RunText("STENCILREF_CUSTOMSHADER = 2"); - wiLua::RunText("STENCILREF_SKIN = 3"); - wiLua::RunText("STENCILREF_SNOW = 4"); + wi::lua::RunText("STENCILREF_EMPTY = 0"); + wi::lua::RunText("STENCILREF_DEFAULT = 1"); + wi::lua::RunText("STENCILREF_CUSTOMSHADER = 2"); + wi::lua::RunText("STENCILREF_SKIN = 3"); + wi::lua::RunText("STENCILREF_SNOW = 4"); - wiLua::RegisterFunc("GetCamera", GetCamera); - wiLua::RegisterFunc("GetScene", GetScene); - wiLua::RegisterFunc("LoadModel", LoadModel); - wiLua::RegisterFunc("Pick", Pick); - wiLua::RegisterFunc("SceneIntersectSphere", SceneIntersectSphere); - wiLua::RegisterFunc("SceneIntersectCapsule", SceneIntersectCapsule); + wi::lua::RegisterFunc("GetCamera", GetCamera); + wi::lua::RegisterFunc("GetScene", GetScene); + wi::lua::RegisterFunc("LoadModel", LoadModel); + wi::lua::RegisterFunc("Pick", Pick); + wi::lua::RegisterFunc("SceneIntersectSphere", SceneIntersectSphere); + wi::lua::RegisterFunc("SceneIntersectCapsule", SceneIntersectCapsule); Luna::Register(L); Luna::Register(L); @@ -361,15 +360,15 @@ Luna::PropertyType Scene_BindLua::properties[] = { int Scene_BindLua::Update(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float dt = wiLua::SGetFloat(L, 1); + float dt = wi::lua::SGetFloat(L, 1); scene->Update(dt); } else { - wiLua::SError(L, "Scene::Update(float dt) not enough arguments!"); + wi::lua::SError(L, "Scene::Update(float dt) not enough arguments!"); } return 0; } @@ -380,7 +379,7 @@ int Scene_BindLua::Clear(lua_State* L) } int Scene_BindLua::Merge(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Scene_BindLua* other = Luna::lightcheck(L, 1); @@ -390,74 +389,74 @@ int Scene_BindLua::Merge(lua_State* L) } else { - wiLua::SError(L, "Scene::Merge(Scene other) argument is not of type Scene!"); + wi::lua::SError(L, "Scene::Merge(Scene other) argument is not of type Scene!"); } } else { - wiLua::SError(L, "Scene::Merge(Scene other) not enough arguments!"); + wi::lua::SError(L, "Scene::Merge(Scene other) not enough arguments!"); } return 0; } int Scene_BindLua::Entity_FindByName(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - std::string name = wiLua::SGetString(L, 1); + std::string name = wi::lua::SGetString(L, 1); Entity entity = scene->Entity_FindByName(name); - wiLua::SSetLongLong(L, entity); + wi::lua::SSetLongLong(L, entity); return 1; } else { - wiLua::SError(L, "Scene::Entity_FindByName(string name) not enough arguments!"); + wi::lua::SError(L, "Scene::Entity_FindByName(string name) not enough arguments!"); } return 0; } int Scene_BindLua::Entity_Remove(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); scene->Entity_Remove(entity); } else { - wiLua::SError(L, "Scene::Entity_Remove(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Entity_Remove(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Entity_Duplicate(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); Entity clone = scene->Entity_Duplicate(entity); - wiLua::SSetLongLong(L, clone); + wi::lua::SSetLongLong(L, clone); return 1; } else { - wiLua::SError(L, "Scene::Entity_Duplicate(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Entity_Duplicate(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateName(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); NameComponent& component = scene->names.Create(entity); Luna::push(L, new NameComponent_BindLua(&component)); @@ -465,16 +464,16 @@ int Scene_BindLua::Component_CreateName(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateName(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateName(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateLayer(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); LayerComponent& component = scene->layers.Create(entity); Luna::push(L, new LayerComponent_BindLua(&component)); @@ -482,16 +481,16 @@ int Scene_BindLua::Component_CreateLayer(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateLayer(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateLayer(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateTransform(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); TransformComponent& component = scene->transforms.Create(entity); Luna::push(L, new TransformComponent_BindLua(&component)); @@ -499,16 +498,16 @@ int Scene_BindLua::Component_CreateTransform(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateTransform(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateTransform(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateLight(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); scene->aabb_lights.Create(entity); @@ -518,16 +517,16 @@ int Scene_BindLua::Component_CreateLight(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateLight(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateLight(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateObject(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); scene->aabb_objects.Create(entity); @@ -537,16 +536,16 @@ int Scene_BindLua::Component_CreateObject(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateObject(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateObject(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateInverseKinematics(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); InverseKinematicsComponent& component = scene->inverse_kinematics.Create(entity); Luna::push(L, new InverseKinematicsComponent_BindLua(&component)); @@ -554,16 +553,16 @@ int Scene_BindLua::Component_CreateInverseKinematics(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateInverseKinematics(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateInverseKinematics(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_CreateSpring(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); SpringComponent& component = scene->springs.Create(entity); Luna::push(L, new SpringComponent_BindLua(&component)); @@ -571,17 +570,17 @@ int Scene_BindLua::Component_CreateSpring(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_CreateSpring(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_CreateSpring(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetName(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); NameComponent* component = scene->names.GetComponent(entity); if (component == nullptr) @@ -594,16 +593,16 @@ int Scene_BindLua::Component_GetName(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetName(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetName(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetLayer(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); LayerComponent* component = scene->layers.GetComponent(entity); if (component == nullptr) @@ -616,16 +615,16 @@ int Scene_BindLua::Component_GetLayer(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetLayer(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetLayer(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetTransform(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); TransformComponent* component = scene->transforms.GetComponent(entity); if (component == nullptr) @@ -638,16 +637,16 @@ int Scene_BindLua::Component_GetTransform(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetTransform(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetTransform(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetCamera(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); CameraComponent* component = scene->cameras.GetComponent(entity); if (component == nullptr) @@ -660,16 +659,16 @@ int Scene_BindLua::Component_GetCamera(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetCamera(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetCamera(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetAnimation(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); AnimationComponent* component = scene->animations.GetComponent(entity); if (component == nullptr) @@ -682,16 +681,16 @@ int Scene_BindLua::Component_GetAnimation(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetAnimation(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetAnimation(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetMaterial(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); MaterialComponent* component = scene->materials.GetComponent(entity); if (component == nullptr) @@ -704,18 +703,18 @@ int Scene_BindLua::Component_GetMaterial(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetMaterial(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetMaterial(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetEmitter(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); - wiEmittedParticle* component = scene->emitters.GetComponent(entity); + wi::EmittedParticleSystem* component = scene->emitters.GetComponent(entity); if (component == nullptr) { return 0; @@ -726,16 +725,16 @@ int Scene_BindLua::Component_GetEmitter(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetEmitter(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetEmitter(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetLight(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); LightComponent* component = scene->lights.GetComponent(entity); if (component == nullptr) @@ -748,16 +747,16 @@ int Scene_BindLua::Component_GetLight(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetLight(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetLight(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetObject(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); ObjectComponent* component = scene->objects.GetComponent(entity); if (component == nullptr) @@ -770,16 +769,16 @@ int Scene_BindLua::Component_GetObject(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetObject(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetObject(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetInverseKinematics(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); InverseKinematicsComponent* component = scene->inverse_kinematics.GetComponent(entity); if (component == nullptr) @@ -792,16 +791,16 @@ int Scene_BindLua::Component_GetInverseKinematics(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetInverseKinematics(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetInverseKinematics(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_GetSpring(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); SpringComponent* component = scene->springs.GetComponent(entity); if (component == nullptr) @@ -814,7 +813,7 @@ int Scene_BindLua::Component_GetSpring(lua_State* L) } else { - wiLua::SError(L, "Scene::Component_GetSpring(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_GetSpring(Entity entity) not enough arguments!"); } return 0; } @@ -947,7 +946,7 @@ int Scene_BindLua::Entity_GetNameArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->names.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->names.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->names.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -958,7 +957,7 @@ int Scene_BindLua::Entity_GetLayerArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->layers.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->layers.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->layers.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -969,7 +968,7 @@ int Scene_BindLua::Entity_GetTransformArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->transforms.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->transforms.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->transforms.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -980,7 +979,7 @@ int Scene_BindLua::Entity_GetCameraArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->cameras.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->cameras.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->cameras.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -991,7 +990,7 @@ int Scene_BindLua::Entity_GetAnimationArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->animations.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->animations.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->animations.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1002,7 +1001,7 @@ int Scene_BindLua::Entity_GetMaterialArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->materials.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->materials.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->materials.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1013,7 +1012,7 @@ int Scene_BindLua::Entity_GetEmitterArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->emitters.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->emitters.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->emitters.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1024,7 +1023,7 @@ int Scene_BindLua::Entity_GetLightArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->lights.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->lights.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->lights.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1035,7 +1034,7 @@ int Scene_BindLua::Entity_GetObjectArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->objects.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->objects.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->objects.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1046,7 +1045,7 @@ int Scene_BindLua::Entity_GetInverseKinematicsArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->inverse_kinematics.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->inverse_kinematics.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->inverse_kinematics.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1057,7 +1056,7 @@ int Scene_BindLua::Entity_GetSpringArray(lua_State* L) int newTable = lua_gettop(L); for (size_t i = 0; i < scene->springs.GetCount(); ++i) { - wiLua::SSetLongLong(L, scene->springs.GetEntity(i)); + wi::lua::SSetLongLong(L, scene->springs.GetEntity(i)); lua_rawseti(L, newTable, lua_Integer(i + 1)); } return 1; @@ -1065,47 +1064,47 @@ int Scene_BindLua::Entity_GetSpringArray(lua_State* L) int Scene_BindLua::Component_Attach(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 1) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); - Entity parent = (Entity)wiLua::SGetLongLong(L, 2); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); + Entity parent = (Entity)wi::lua::SGetLongLong(L, 2); scene->Component_Attach(entity, parent); } else { - wiLua::SError(L, "Scene::Component_Attach(Entity entity,parent) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_Attach(Entity entity,parent) not enough arguments!"); } return 0; } int Scene_BindLua::Component_Detach(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); scene->Component_Detach(entity); } else { - wiLua::SError(L, "Scene::Component_Detach(Entity entity) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_Detach(Entity entity) not enough arguments!"); } return 0; } int Scene_BindLua::Component_DetachChildren(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity parent = (Entity)wiLua::SGetLongLong(L, 1); + Entity parent = (Entity)wi::lua::SGetLongLong(L, 1); scene->Component_DetachChildren(parent); } else { - wiLua::SError(L, "Scene::Component_DetachChildren(Entity parent) not enough arguments!"); + wi::lua::SError(L, "Scene::Component_DetachChildren(Entity parent) not enough arguments!"); } return 0; } @@ -1141,21 +1140,21 @@ NameComponent_BindLua::~NameComponent_BindLua() int NameComponent_BindLua::SetName(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - std::string name = wiLua::SGetString(L, 1); + std::string name = wi::lua::SGetString(L, 1); *component = name; } else { - wiLua::SError(L, "SetName(string value) not enough arguments!"); + wi::lua::SError(L, "SetName(string value) not enough arguments!"); } return 0; } int NameComponent_BindLua::GetName(lua_State* L) { - wiLua::SSetString(L, component->name); + wi::lua::SSetString(L, component->name); return 1; } @@ -1189,21 +1188,21 @@ LayerComponent_BindLua::~LayerComponent_BindLua() int LayerComponent_BindLua::SetLayerMask(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - int mask = wiLua::SGetInt(L, 1); + int mask = wi::lua::SGetInt(L, 1); component->layerMask = *reinterpret_cast(&mask); } else { - wiLua::SError(L, "SetLayerMask(int value) not enough arguments!"); + wi::lua::SError(L, "SetLayerMask(int value) not enough arguments!"); } return 0; } int LayerComponent_BindLua::GetLayerMask(lua_State* L) { - wiLua::SSetInt(L, component->GetLayerMask()); + wi::lua::SSetInt(L, component->GetLayerMask()); return 1; } @@ -1248,7 +1247,7 @@ TransformComponent_BindLua::~TransformComponent_BindLua() int TransformComponent_BindLua::Scale(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* v = Luna::lightcheck(L, 1); @@ -1261,18 +1260,18 @@ int TransformComponent_BindLua::Scale(lua_State* L) } else { - wiLua::SError(L, "Scale(Vector vector) argument is not a vector!"); + wi::lua::SError(L, "Scale(Vector vector) argument is not a vector!"); } } else { - wiLua::SError(L, "Scale(Vector vector) not enough arguments!"); + wi::lua::SError(L, "Scale(Vector vector) not enough arguments!"); } return 0; } int TransformComponent_BindLua::Rotate(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* v = Luna::lightcheck(L, 1); @@ -1285,18 +1284,18 @@ int TransformComponent_BindLua::Rotate(lua_State* L) } else { - wiLua::SError(L, "Rotate(Vector vectorRollPitchYaw) argument is not a vector!"); + wi::lua::SError(L, "Rotate(Vector vectorRollPitchYaw) argument is not a vector!"); } } else { - wiLua::SError(L, "Rotate(Vector vectorRollPitchYaw) not enough arguments!"); + wi::lua::SError(L, "Rotate(Vector vectorRollPitchYaw) not enough arguments!"); } return 0; } int TransformComponent_BindLua::Translate(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* v = Luna::lightcheck(L, 1); @@ -1309,18 +1308,18 @@ int TransformComponent_BindLua::Translate(lua_State* L) } else { - wiLua::SError(L, "Translate(Vector vector) argument is not a vector!"); + wi::lua::SError(L, "Translate(Vector vector) argument is not a vector!"); } } else { - wiLua::SError(L, "Translate(Vector vector) not enough arguments!"); + wi::lua::SError(L, "Translate(Vector vector) not enough arguments!"); } return 0; } int TransformComponent_BindLua::Lerp(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 2) { TransformComponent_BindLua* a = Luna::lightcheck(L, 1); @@ -1330,29 +1329,29 @@ int TransformComponent_BindLua::Lerp(lua_State* L) if (b != nullptr) { - float t = wiLua::SGetFloat(L, 3); + float t = wi::lua::SGetFloat(L, 3); component->Lerp(*a->component, *b->component, t); } else { - wiLua::SError(L, "Lerp(TransformComponent a,b, float t) argument (b) is not a Transform!"); + wi::lua::SError(L, "Lerp(TransformComponent a,b, float t) argument (b) is not a Transform!"); } } else { - wiLua::SError(L, "Lerp(TransformComponent a,b, float t) argument (a) is not a Transform!"); + wi::lua::SError(L, "Lerp(TransformComponent a,b, float t) argument (a) is not a Transform!"); } } else { - wiLua::SError(L, "Lerp(TransformComponent a,b, float t) not enough arguments!"); + wi::lua::SError(L, "Lerp(TransformComponent a,b, float t) not enough arguments!"); } return 0; } int TransformComponent_BindLua::CatmullRom(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 4) { TransformComponent_BindLua* a = Luna::lightcheck(L, 1); @@ -1370,39 +1369,39 @@ int TransformComponent_BindLua::CatmullRom(lua_State* L) if (d != nullptr) { - float t = wiLua::SGetFloat(L, 5); + float t = wi::lua::SGetFloat(L, 5); component->CatmullRom(*a->component, *b->component, *c->component, *d->component, t); } else { - wiLua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (d) is not a Transform!"); + wi::lua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (d) is not a Transform!"); } } else { - wiLua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (c) is not a Transform!"); + wi::lua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (c) is not a Transform!"); } } else { - wiLua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (b) is not a Transform!"); + wi::lua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (b) is not a Transform!"); } } else { - wiLua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (a) is not a Transform!"); + wi::lua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) argument (a) is not a Transform!"); } } else { - wiLua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) not enough arguments!"); + wi::lua::SError(L, "CatmullRom(TransformComponent a,b,c,d, float t) not enough arguments!"); } return 0; } int TransformComponent_BindLua::MatrixTransform(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Matrix_BindLua* m = Luna::lightcheck(L, 1); @@ -1412,12 +1411,12 @@ int TransformComponent_BindLua::MatrixTransform(lua_State* L) } else { - wiLua::SError(L, "MatrixTransform(Matrix matrix) argument is not a matrix!"); + wi::lua::SError(L, "MatrixTransform(Matrix matrix) argument is not a matrix!"); } } else { - wiLua::SError(L, "MatrixTransform(Matrix matrix) not enough arguments!"); + wi::lua::SError(L, "MatrixTransform(Matrix matrix) not enough arguments!"); } return 0; } @@ -1514,7 +1513,7 @@ int CameraComponent_BindLua::UpdateCamera(lua_State* L) } int CameraComponent_BindLua::TransformCamera(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { TransformComponent_BindLua* transform = Luna::lightcheck(L, 1); @@ -1525,102 +1524,102 @@ int CameraComponent_BindLua::TransformCamera(lua_State* L) } else { - wiLua::SError(L, "TransformCamera(TransformComponent transform) invalid argument!"); + wi::lua::SError(L, "TransformCamera(TransformComponent transform) invalid argument!"); } } else { - wiLua::SError(L, "TransformCamera(TransformComponent transform) not enough arguments!"); + wi::lua::SError(L, "TransformCamera(TransformComponent transform) not enough arguments!"); } return 0; } int CameraComponent_BindLua::GetFOV(lua_State* L) { - wiLua::SSetFloat(L, component->fov); + wi::lua::SSetFloat(L, component->fov); return 1; } int CameraComponent_BindLua::SetFOV(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->fov = wiLua::SGetFloat(L, 1); + component->fov = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetFOV(float value) not enough arguments!"); + wi::lua::SError(L, "SetFOV(float value) not enough arguments!"); } return 0; } int CameraComponent_BindLua::GetNearPlane(lua_State* L) { - wiLua::SSetFloat(L, component->zNearP); + wi::lua::SSetFloat(L, component->zNearP); return 1; } int CameraComponent_BindLua::SetNearPlane(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->zNearP = wiLua::SGetFloat(L, 1); + component->zNearP = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetNearPlane(float value) not enough arguments!"); + wi::lua::SError(L, "SetNearPlane(float value) not enough arguments!"); } return 0; } int CameraComponent_BindLua::GetFarPlane(lua_State* L) { - wiLua::SSetFloat(L, component->zFarP); + wi::lua::SSetFloat(L, component->zFarP); return 1; } int CameraComponent_BindLua::SetFarPlane(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->zFarP = wiLua::SGetFloat(L, 1); + component->zFarP = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetFarPlane(float value) not enough arguments!"); + wi::lua::SError(L, "SetFarPlane(float value) not enough arguments!"); } return 0; } int CameraComponent_BindLua::GetFocalLength(lua_State* L) { - wiLua::SSetFloat(L, component->focal_length); + wi::lua::SSetFloat(L, component->focal_length); return 1; } int CameraComponent_BindLua::SetFocalLength(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->focal_length = wiLua::SGetFloat(L, 1); + component->focal_length = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetFocalLength(float value) not enough arguments!"); + wi::lua::SError(L, "SetFocalLength(float value) not enough arguments!"); } return 0; } int CameraComponent_BindLua::GetApertureSize(lua_State* L) { - wiLua::SSetFloat(L, component->aperture_size); + wi::lua::SSetFloat(L, component->aperture_size); return 1; } int CameraComponent_BindLua::SetApertureSize(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->aperture_size = wiLua::SGetFloat(L, 1); + component->aperture_size = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetApertureSize(float value) not enough arguments!"); + wi::lua::SError(L, "SetApertureSize(float value) not enough arguments!"); } return 0; } @@ -1631,7 +1630,7 @@ int CameraComponent_BindLua::GetApertureShape(lua_State* L) } int CameraComponent_BindLua::SetApertureShape(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* param = Luna::lightcheck(L, 1); @@ -1642,7 +1641,7 @@ int CameraComponent_BindLua::SetApertureShape(lua_State* L) } else { - wiLua::SError(L, "SetApertureShape(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetApertureShape(Vector value) not enough arguments!"); } return 0; } @@ -1736,69 +1735,69 @@ int AnimationComponent_BindLua::Stop(lua_State* L) } int AnimationComponent_BindLua::SetLooped(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - bool looped = wiLua::SGetBool(L, 1); + bool looped = wi::lua::SGetBool(L, 1); component->SetLooped(looped); } else { - wiLua::SError(L, "SetLooped(bool value) not enough arguments!"); + wi::lua::SError(L, "SetLooped(bool value) not enough arguments!"); } return 0; } int AnimationComponent_BindLua::IsLooped(lua_State* L) { - wiLua::SSetBool(L, component->IsLooped()); + wi::lua::SSetBool(L, component->IsLooped()); return 1; } int AnimationComponent_BindLua::IsPlaying(lua_State* L) { - wiLua::SSetBool(L, component->IsPlaying()); + wi::lua::SSetBool(L, component->IsPlaying()); return 1; } int AnimationComponent_BindLua::IsEnded(lua_State* L) { - wiLua::SSetBool(L, component->IsEnded()); + wi::lua::SSetBool(L, component->IsEnded()); return 1; } int AnimationComponent_BindLua::SetTimer(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->timer = value; } else { - wiLua::SError(L, "SetTimer(float value) not enough arguments!"); + wi::lua::SError(L, "SetTimer(float value) not enough arguments!"); } return 0; } int AnimationComponent_BindLua::GetTimer(lua_State* L) { - wiLua::SSetFloat(L, component->timer); + wi::lua::SSetFloat(L, component->timer); return 1; } int AnimationComponent_BindLua::SetAmount(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->amount = value; } else { - wiLua::SError(L, "SetAmount(float value) not enough arguments!"); + wi::lua::SError(L, "SetAmount(float value) not enough arguments!"); } return 0; } int AnimationComponent_BindLua::GetAmount(lua_State* L) { - wiLua::SSetFloat(L, component->amount); + wi::lua::SSetFloat(L, component->amount); return 1; } @@ -1840,7 +1839,7 @@ MaterialComponent_BindLua::~MaterialComponent_BindLua() int MaterialComponent_BindLua::SetBaseColor(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* _color = Luna::lightcheck(L, 1); @@ -1852,19 +1851,19 @@ int MaterialComponent_BindLua::SetBaseColor(lua_State* L) } else { - wiLua::SError(L, "SetBaseColor(Vector color) first argument must be of Vector type!"); + wi::lua::SError(L, "SetBaseColor(Vector color) first argument must be of Vector type!"); } } else { - wiLua::SError(L, "SetBaseColor(Vector color) not enough arguments!"); + wi::lua::SError(L, "SetBaseColor(Vector color) not enough arguments!"); } return 0; } int MaterialComponent_BindLua::SetEmissiveColor(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* _color = Luna::lightcheck(L, 1); @@ -1876,48 +1875,48 @@ int MaterialComponent_BindLua::SetEmissiveColor(lua_State* L) } else { - wiLua::SError(L, "SetEmissiveColor(Vector color) first argument must be of Vector type!"); + wi::lua::SError(L, "SetEmissiveColor(Vector color) first argument must be of Vector type!"); } } else { - wiLua::SError(L, "SetEmissiveColor(Vector color) not enough arguments!"); + wi::lua::SError(L, "SetEmissiveColor(Vector color) not enough arguments!"); } return 0; } int MaterialComponent_BindLua::SetEngineStencilRef(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->engineStencilRef = (STENCILREF)wiLua::SGetInt(L, 1); + component->engineStencilRef = (wi::enums::STENCILREF)wi::lua::SGetInt(L, 1); } else { - wiLua::SError(L, "SetEngineStencilRef(int value) not enough arguments!"); + wi::lua::SError(L, "SetEngineStencilRef(int value) not enough arguments!"); } return 0; } int MaterialComponent_BindLua::SetUserStencilRef(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - uint8_t value = (uint8_t)wiLua::SGetInt(L, 1); + uint8_t value = (uint8_t)wi::lua::SGetInt(L, 1); component->SetUserStencilRef(value); } else { - wiLua::SError(L, "SetUserStencilRef(int value) not enough arguments!"); + wi::lua::SError(L, "SetUserStencilRef(int value) not enough arguments!"); } return 0; } int MaterialComponent_BindLua::GetStencilRef(lua_State* L) { - wiLua::SSetInt(L, (int)component->GetStencilRef()); + wi::lua::SSetInt(L, (int)component->GetStencilRef()); return 1; } @@ -1953,7 +1952,7 @@ Luna::PropertyType EmitterComponent_BindLua::propertie EmitterComponent_BindLua::EmitterComponent_BindLua(lua_State *L) { owning = true; - component = new wiEmittedParticle; + component = new wi::EmittedParticleSystem; } EmitterComponent_BindLua::~EmitterComponent_BindLua() { @@ -1965,154 +1964,154 @@ EmitterComponent_BindLua::~EmitterComponent_BindLua() int EmitterComponent_BindLua::Burst(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->Burst(wiLua::SGetInt(L, 1)); + component->Burst(wi::lua::SGetInt(L, 1)); } else { - wiLua::SError(L, "Burst(int value) not enough arguments!"); + wi::lua::SError(L, "Burst(int value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetEmitCount(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->count = wiLua::SGetFloat(L, 1); + component->count = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetEmitCount(float value) not enough arguments!"); + wi::lua::SError(L, "SetEmitCount(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetSize(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->size = wiLua::SGetFloat(L, 1); + component->size = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetSize(float value) not enough arguments!"); + wi::lua::SError(L, "SetSize(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetLife(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->life = wiLua::SGetFloat(L, 1); + component->life = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetLife(float value) not enough arguments!"); + wi::lua::SError(L, "SetLife(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetNormalFactor(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->normal_factor = wiLua::SGetFloat(L, 1); + component->normal_factor = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetNormalFactor(float value) not enough arguments!"); + wi::lua::SError(L, "SetNormalFactor(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetRandomness(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->random_factor = wiLua::SGetFloat(L, 1); + component->random_factor = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetRandomness(float value) not enough arguments!"); + wi::lua::SError(L, "SetRandomness(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetLifeRandomness(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->random_life = wiLua::SGetFloat(L, 1); + component->random_life = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetLifeRandomness(float value) not enough arguments!"); + wi::lua::SError(L, "SetLifeRandomness(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetScaleX(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->scaleX = wiLua::SGetFloat(L, 1); + component->scaleX = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetScaleX(float value) not enough arguments!"); + wi::lua::SError(L, "SetScaleX(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetScaleY(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->scaleY = wiLua::SGetFloat(L, 1); + component->scaleY = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetScaleY(float value) not enough arguments!"); + wi::lua::SError(L, "SetScaleY(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetRotation(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->rotation = wiLua::SGetFloat(L, 1); + component->rotation = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetRotation(float value) not enough arguments!"); + wi::lua::SError(L, "SetRotation(float value) not enough arguments!"); } return 0; } int EmitterComponent_BindLua::SetMotionBlurAmount(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->motionBlurAmount = wiLua::SGetFloat(L, 1); + component->motionBlurAmount = wi::lua::SGetFloat(L, 1); } else { - wiLua::SError(L, "SetMotionBlurAmount(float value) not enough arguments!"); + wi::lua::SError(L, "SetMotionBlurAmount(float value) not enough arguments!"); } return 0; @@ -2157,52 +2156,52 @@ LightComponent_BindLua::~LightComponent_BindLua() int LightComponent_BindLua::SetType(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - int value = wiLua::SGetInt(L, 1); + int value = wi::lua::SGetInt(L, 1); component->SetType((LightComponent::LightType)value); } else { - wiLua::SError(L, "SetType(int value) not enough arguments!"); + wi::lua::SError(L, "SetType(int value) not enough arguments!"); } return 0; } int LightComponent_BindLua::SetRange(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->range_local = value; } else { - wiLua::SError(L, "SetRange(float value) not enough arguments!"); + wi::lua::SError(L, "SetRange(float value) not enough arguments!"); } return 0; } int LightComponent_BindLua::SetEnergy(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->energy = value; } else { - wiLua::SError(L, "SetEnergy(float value) not enough arguments!"); + wi::lua::SError(L, "SetEnergy(float value) not enough arguments!"); } return 0; } int LightComponent_BindLua::SetColor(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* value = Luna::lightcheck(L, 1); @@ -2212,26 +2211,26 @@ int LightComponent_BindLua::SetColor(lua_State* L) } else { - wiLua::SError(L, "SetColor(Vector value) argument must be Vector type!"); + wi::lua::SError(L, "SetColor(Vector value) argument must be Vector type!"); } } else { - wiLua::SError(L, "SetColor(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetColor(Vector value) not enough arguments!"); } return 0; } int LightComponent_BindLua::SetCastShadow(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - component->SetCastShadow(wiLua::SGetBool(L, 1)); + component->SetCastShadow(wi::lua::SGetBool(L, 1)); } else { - wiLua::SError(L, "SetCastShadow(bool value) not enough arguments!"); + wi::lua::SError(L, "SetCastShadow(bool value) not enough arguments!"); } return 0; @@ -2239,7 +2238,7 @@ int LightComponent_BindLua::SetCastShadow(lua_State* L) int LightComponent_BindLua::GetType(lua_State* L) { - wiLua::SSetInt(L, (int)component->GetType()); + wi::lua::SSetInt(L, (int)component->GetType()); return 1; } @@ -2284,7 +2283,7 @@ ObjectComponent_BindLua::~ObjectComponent_BindLua() int ObjectComponent_BindLua::GetMeshID(lua_State* L) { - wiLua::SSetLongLong(L, component->meshID); + wi::lua::SSetLongLong(L, component->meshID); return 1; } int ObjectComponent_BindLua::GetColor(lua_State* L) @@ -2294,28 +2293,28 @@ int ObjectComponent_BindLua::GetColor(lua_State* L) } int ObjectComponent_BindLua::GetUserStencilRef(lua_State* L) { - wiLua::SSetInt(L, (int)component->userStencilRef); + wi::lua::SSetInt(L, (int)component->userStencilRef); return 1; } int ObjectComponent_BindLua::SetMeshID(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity meshID = (Entity)wiLua::SGetLongLong(L, 1); + Entity meshID = (Entity)wi::lua::SGetLongLong(L, 1); component->meshID = meshID; } else { - wiLua::SError(L, "SetMeshID(Entity entity) not enough arguments!"); + wi::lua::SError(L, "SetMeshID(Entity entity) not enough arguments!"); } return 0; } int ObjectComponent_BindLua::SetColor(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { Vector_BindLua* value = Luna::lightcheck(L, 1); @@ -2325,27 +2324,27 @@ int ObjectComponent_BindLua::SetColor(lua_State* L) } else { - wiLua::SError(L, "SetColor(Vector value) argument must be Vector type!"); + wi::lua::SError(L, "SetColor(Vector value) argument must be Vector type!"); } } else { - wiLua::SError(L, "SetColor(Vector value) not enough arguments!"); + wi::lua::SError(L, "SetColor(Vector value) not enough arguments!"); } return 0; } int ObjectComponent_BindLua::SetUserStencilRef(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - int value = wiLua::SGetInt(L, 1); + int value = wi::lua::SGetInt(L, 1); component->SetUserStencilRef((uint8_t)value); } else { - wiLua::SError(L, "SetUserStencilRef(int value) not enough arguments!"); + wi::lua::SError(L, "SetUserStencilRef(int value) not enough arguments!"); } return 0; @@ -2388,43 +2387,43 @@ InverseKinematicsComponent_BindLua::~InverseKinematicsComponent_BindLua() int InverseKinematicsComponent_BindLua::SetTarget(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - Entity entity = (Entity)wiLua::SGetLongLong(L, 1); + Entity entity = (Entity)wi::lua::SGetLongLong(L, 1); component->target = entity; } else { - wiLua::SError(L, "SetTarget(Entity entity) not enough arguments!"); + wi::lua::SError(L, "SetTarget(Entity entity) not enough arguments!"); } return 0; } int InverseKinematicsComponent_BindLua::SetChainLength(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - uint32_t value = (uint32_t)wiLua::SGetInt(L, 1); + uint32_t value = (uint32_t)wi::lua::SGetInt(L, 1); component->chain_length = value; } else { - wiLua::SError(L, "SetChainLength(int value) not enough arguments!"); + wi::lua::SError(L, "SetChainLength(int value) not enough arguments!"); } return 0; } int InverseKinematicsComponent_BindLua::SetIterationCount(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - uint32_t value = (uint32_t)wiLua::SGetInt(L, 1); + uint32_t value = (uint32_t)wi::lua::SGetInt(L, 1); component->iteration_count = value; } else { - wiLua::SError(L, "SetIterationCount(int value) not enough arguments!"); + wi::lua::SError(L, "SetIterationCount(int value) not enough arguments!"); } return 0; } @@ -2432,10 +2431,10 @@ int InverseKinematicsComponent_BindLua::SetDisabled(lua_State* L) { bool value = true; - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - value = wiLua::SGetBool(L, 1); + value = wi::lua::SGetBool(L, 1); } component->SetDisabled(value); @@ -2444,22 +2443,22 @@ int InverseKinematicsComponent_BindLua::SetDisabled(lua_State* L) } int InverseKinematicsComponent_BindLua::GetTarget(lua_State* L) { - wiLua::SSetLongLong(L, component->target); + wi::lua::SSetLongLong(L, component->target); return 1; } int InverseKinematicsComponent_BindLua::GetChainLength(lua_State* L) { - wiLua::SSetInt(L, (int)component->chain_length); + wi::lua::SSetInt(L, (int)component->chain_length); return 1; } int InverseKinematicsComponent_BindLua::GetIterationCount(lua_State* L) { - wiLua::SSetInt(L, (int)component->iteration_count); + wi::lua::SSetInt(L, (int)component->iteration_count); return 1; } int InverseKinematicsComponent_BindLua::IsDisabled(lua_State* L) { - wiLua::SSetBool(L, component->IsDisabled()); + wi::lua::SSetBool(L, component->IsDisabled()); return 1; } @@ -2495,43 +2494,43 @@ SpringComponent_BindLua::~SpringComponent_BindLua() int SpringComponent_BindLua::SetStiffness(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->stiffness = value; } else { - wiLua::SError(L, "SetStiffness(float value) not enough arguments!"); + wi::lua::SError(L, "SetStiffness(float value) not enough arguments!"); } return 0; } int SpringComponent_BindLua::SetDamping(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->damping = value; } else { - wiLua::SError(L, "SetDamping(float value) not enough arguments!"); + wi::lua::SError(L, "SetDamping(float value) not enough arguments!"); } return 0; } int SpringComponent_BindLua::SetWindAffection(lua_State* L) { - int argc = wiLua::SGetArgCount(L); + int argc = wi::lua::SGetArgCount(L); if (argc > 0) { - float value = wiLua::SGetFloat(L, 1); + float value = wi::lua::SGetFloat(L, 1); component->wind_affection = value; } else { - wiLua::SError(L, "SetWindAffection(float value) not enough arguments!"); + wi::lua::SError(L, "SetWindAffection(float value) not enough arguments!"); } return 0; } diff --git a/WickedEngine/wiScene_BindLua.h b/WickedEngine/wiScene_BindLua.h index a8685cdf5..1d5ba445f 100644 --- a/WickedEngine/wiScene_BindLua.h +++ b/WickedEngine/wiScene_BindLua.h @@ -3,22 +3,22 @@ #include "wiLuna.h" #include "wiScene.h" -namespace wiScene_BindLua +namespace wi::lua::scene { void Bind(); class Scene_BindLua { private: - wiScene::Scene customScene; + wi::scene::Scene customScene; public: - wiScene::Scene* scene = nullptr; + wi::scene::Scene* scene = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - Scene_BindLua(wiScene::Scene* scene) :scene(scene) {} + Scene_BindLua(wi::scene::Scene* scene) :scene(scene) {} Scene_BindLua(lua_State* L) { this->scene = &customScene; @@ -85,13 +85,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::NameComponent* component = nullptr; + wi::scene::NameComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - NameComponent_BindLua(wiScene::NameComponent* component) :component(component) {} + NameComponent_BindLua(wi::scene::NameComponent* component) :component(component) {} NameComponent_BindLua(lua_State *L); ~NameComponent_BindLua(); @@ -103,13 +103,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::LayerComponent* component = nullptr; + wi::scene::LayerComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - LayerComponent_BindLua(wiScene::LayerComponent* component) :component(component) {} + LayerComponent_BindLua(wi::scene::LayerComponent* component) :component(component) {} LayerComponent_BindLua(lua_State *L); ~LayerComponent_BindLua(); @@ -121,13 +121,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::TransformComponent* component = nullptr; + wi::scene::TransformComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - TransformComponent_BindLua(wiScene::TransformComponent* component) :component(component) {} + TransformComponent_BindLua(wi::scene::TransformComponent* component) :component(component) {} TransformComponent_BindLua(lua_State *L); ~TransformComponent_BindLua(); @@ -149,13 +149,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::CameraComponent* component = nullptr; + wi::scene::CameraComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - CameraComponent_BindLua(wiScene::CameraComponent* component) :component(component) {} + CameraComponent_BindLua(wi::scene::CameraComponent* component) :component(component) {} CameraComponent_BindLua(lua_State *L); ~CameraComponent_BindLua(); @@ -185,13 +185,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::AnimationComponent* component = nullptr; + wi::scene::AnimationComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - AnimationComponent_BindLua(wiScene::AnimationComponent* component) :component(component) {} + AnimationComponent_BindLua(wi::scene::AnimationComponent* component) :component(component) {} AnimationComponent_BindLua(lua_State *L); ~AnimationComponent_BindLua(); @@ -212,13 +212,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::MaterialComponent* component = nullptr; + wi::scene::MaterialComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - MaterialComponent_BindLua(wiScene::MaterialComponent* component) :component(component) {} + MaterialComponent_BindLua(wi::scene::MaterialComponent* component) :component(component) {} MaterialComponent_BindLua(lua_State *L); ~MaterialComponent_BindLua(); @@ -233,13 +233,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::wiEmittedParticle* component = nullptr; + wi::EmittedParticleSystem* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - EmitterComponent_BindLua(wiScene::wiEmittedParticle* component) :component(component) {} + EmitterComponent_BindLua(wi::EmittedParticleSystem* component) :component(component) {} EmitterComponent_BindLua(lua_State *L); ~EmitterComponent_BindLua(); @@ -260,13 +260,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::LightComponent* component = nullptr; + wi::scene::LightComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - LightComponent_BindLua(wiScene::LightComponent* component) :component(component) {} + LightComponent_BindLua(wi::scene::LightComponent* component) :component(component) {} LightComponent_BindLua(lua_State *L); ~LightComponent_BindLua(); @@ -283,13 +283,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::ObjectComponent* component = nullptr; + wi::scene::ObjectComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - ObjectComponent_BindLua(wiScene::ObjectComponent* component) :component(component) {} + ObjectComponent_BindLua(wi::scene::ObjectComponent* component) :component(component) {} ObjectComponent_BindLua(lua_State* L); ~ObjectComponent_BindLua(); @@ -306,13 +306,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::InverseKinematicsComponent* component = nullptr; + wi::scene::InverseKinematicsComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - InverseKinematicsComponent_BindLua(wiScene::InverseKinematicsComponent* component) :component(component) {} + InverseKinematicsComponent_BindLua(wi::scene::InverseKinematicsComponent* component) :component(component) {} InverseKinematicsComponent_BindLua(lua_State* L); ~InverseKinematicsComponent_BindLua(); @@ -330,13 +330,13 @@ namespace wiScene_BindLua { public: bool owning = false; - wiScene::SpringComponent* component = nullptr; + wi::scene::SpringComponent* component = nullptr; static const char className[]; static Luna::FunctionType methods[]; static Luna::PropertyType properties[]; - SpringComponent_BindLua(wiScene::SpringComponent* component) :component(component) {} + SpringComponent_BindLua(wi::scene::SpringComponent* component) :component(component) {} SpringComponent_BindLua(lua_State* L); ~SpringComponent_BindLua(); diff --git a/WickedEngine/wiScene_Decl.h b/WickedEngine/wiScene_Decl.h index ecf59a451..6616f8434 100644 --- a/WickedEngine/wiScene_Decl.h +++ b/WickedEngine/wiScene_Decl.h @@ -1,7 +1,6 @@ #pragma once - -namespace wiScene +namespace wi::scene { struct NameComponent; struct LayerComponent; @@ -27,7 +26,4 @@ namespace wiScene struct InverseKinematicsComponent; struct SpringComponent; struct Scene; - - class wiEmittedParticle; // todo: rename - class wiHairParticle; // todo: rename } diff --git a/WickedEngine/wiScene_Serializers.cpp b/WickedEngine/wiScene_Serializers.cpp index ca42a31b8..8936bc9a7 100644 --- a/WickedEngine/wiScene_Serializers.cpp +++ b/WickedEngine/wiScene_Serializers.cpp @@ -3,16 +3,16 @@ #include "wiArchive.h" #include "wiRandom.h" #include "wiHelper.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiTimer.h" #include "wiVector.h" -using namespace wiECS; +using namespace wi::ecs; -namespace wiScene +namespace wi::scene { - void NameComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void NameComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -23,7 +23,7 @@ namespace wiScene archive << name; } } - void LayerComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void LayerComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -34,7 +34,7 @@ namespace wiScene archive << layerMask; } } - void TransformComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void TransformComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -54,12 +54,12 @@ namespace wiScene archive << translation_local; } } - void PreviousFrameTransformComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void PreviousFrameTransformComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { // NOTHING! We just need a serialize function for this to be able serialize with ComponentManager! // This structure has no persistent state! } - void HierarchyComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void HierarchyComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { SerializeEntity(archive, parentID, seri); @@ -77,7 +77,7 @@ namespace wiScene archive << layerMask_bind; } } - void MaterialComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void MaterialComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { const std::string& dir = archive.GetSourceDirectory(); @@ -222,7 +222,7 @@ namespace wiScene } } - wiJobSystem::Execute(seri.ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(seri.ctx, [&](wi::jobsystem::JobArgs args) { CreateRenderData(); }); } @@ -260,7 +260,7 @@ namespace wiScene for (auto& x : textures) { - wiHelper::MakePathRelative(dir, x.name); + wi::helper::MakePathRelative(dir, x.name); } archive << textures[BASECOLORMAP].name; @@ -341,7 +341,7 @@ namespace wiScene } } } - void MeshComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void MeshComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) @@ -404,7 +404,7 @@ namespace wiScene } } - wiJobSystem::Execute(seri.ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(seri.ctx, [&](wi::jobsystem::JobArgs args) { CreateRenderData(); }); } @@ -466,7 +466,7 @@ namespace wiScene } } - void ImpostorComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void ImpostorComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -481,7 +481,7 @@ namespace wiScene archive << swapInDistance; } } - void ObjectComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void ObjectComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -503,7 +503,7 @@ namespace wiScene if (expected_datasize != lightmapTextureData.size()) { // This means it's from an old version, when lightmap data was stored in raw format, so compress it... - wiJobSystem::Execute(seri.ctx, [this](wiJobArgs args) { + wi::jobsystem::Execute(seri.ctx, [this](wi::jobsystem::JobArgs args) { CompressLightmap(); }); } @@ -542,7 +542,7 @@ namespace wiScene } } } - void RigidBodyPhysicsComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void RigidBodyPhysicsComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -596,7 +596,7 @@ namespace wiScene } } } - void SoftBodyPhysicsComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void SoftBodyPhysicsComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -640,7 +640,7 @@ namespace wiScene } } } - void ArmatureComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void ArmatureComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -688,7 +688,7 @@ namespace wiScene } } } - void LightComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void LightComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { const std::string& dir = archive.GetSourceDirectory(); @@ -718,14 +718,14 @@ namespace wiScene archive >> lensFlareNames; - wiJobSystem::Execute(seri.ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(seri.ctx, [&](wi::jobsystem::JobArgs args) { lensFlareRimTextures.resize(lensFlareNames.size()); for (size_t i = 0; i < lensFlareNames.size(); ++i) { if (!lensFlareNames[i].empty()) { lensFlareNames[i] = dir + lensFlareNames[i]; - lensFlareRimTextures[i] = wiResourceManager::Load(lensFlareNames[i], wiResourceManager::IMPORT_RETAIN_FILEDATA); + lensFlareRimTextures[i] = wi::resourcemanager::Load(lensFlareNames[i], wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); } } }); @@ -755,13 +755,13 @@ namespace wiScene { for (size_t i = 0; i < lensFlareNames.size(); ++i) { - wiHelper::MakePathRelative(dir, lensFlareNames[i]); + wi::helper::MakePathRelative(dir, lensFlareNames[i]); } } archive << lensFlareNames; } } - void CameraComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void CameraComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -798,7 +798,7 @@ namespace wiScene } } } - void EnvironmentProbeComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void EnvironmentProbeComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -811,7 +811,7 @@ namespace wiScene archive << _flags; } } - void ForceFieldComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void ForceFieldComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -828,7 +828,7 @@ namespace wiScene archive << range_local; } } - void DecalComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void DecalComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -839,7 +839,7 @@ namespace wiScene archive << _flags; } } - void AnimationComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void AnimationComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -921,7 +921,7 @@ namespace wiScene } } } - void AnimationDataComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void AnimationDataComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -936,7 +936,7 @@ namespace wiScene archive << keyframe_data; } } - void WeatherComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void WeatherComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { std::string dir = archive.GetSourceDirectory(); @@ -988,7 +988,7 @@ namespace wiScene if (!skyMapName.empty()) { skyMapName = dir + skyMapName; - skyMap = wiResourceManager::Load(skyMapName, wiResourceManager::IMPORT_RETAIN_FILEDATA); + skyMap = wi::resourcemanager::Load(skyMapName, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); } } if (archive.GetVersion() >= 40) @@ -1001,7 +1001,7 @@ namespace wiScene if (!colorGradingMapName.empty()) { colorGradingMapName = dir + colorGradingMapName; - colorGradingMap = wiResourceManager::Load(colorGradingMapName, wiResourceManager::IMPORT_COLORGRADINGLUT | wiResourceManager::IMPORT_RETAIN_FILEDATA); + colorGradingMap = wi::resourcemanager::Load(colorGradingMapName, wi::resourcemanager::Flags::IMPORT_COLORGRADINGLUT | wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); } } @@ -1122,8 +1122,8 @@ namespace wiScene archive << oceanParameters.surfaceDetail; archive << oceanParameters.surfaceDisplacementTolerance; - wiHelper::MakePathRelative(dir, skyMapName); - wiHelper::MakePathRelative(dir, colorGradingMapName); + wi::helper::MakePathRelative(dir, skyMapName); + wi::helper::MakePathRelative(dir, colorGradingMapName); if (archive.GetVersion() >= 32) { @@ -1225,7 +1225,7 @@ namespace wiScene } } } - void SoundComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void SoundComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { const std::string& dir = archive.GetSourceDirectory(); @@ -1236,18 +1236,18 @@ namespace wiScene archive >> volume; archive >> (uint32_t&)soundinstance.type; - wiJobSystem::Execute(seri.ctx, [&](wiJobArgs args) { + wi::jobsystem::Execute(seri.ctx, [&](wi::jobsystem::JobArgs args) { if (!filename.empty()) { filename = dir + filename; - soundResource = wiResourceManager::Load(filename, wiResourceManager::IMPORT_RETAIN_FILEDATA); - wiAudio::CreateSoundInstance(&soundResource->sound, &soundinstance); + soundResource = wi::resourcemanager::Load(filename, wi::resourcemanager::Flags::IMPORT_RETAIN_FILEDATA); + wi::audio::CreateSoundInstance(&soundResource.GetSound(), &soundinstance); } }); } else { - wiHelper::MakePathRelative(dir, filename); + wi::helper::MakePathRelative(dir, filename); archive << _flags; archive << filename; @@ -1255,7 +1255,7 @@ namespace wiScene archive << soundinstance.type; } } - void InverseKinematicsComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void InverseKinematicsComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { SerializeEntity(archive, target, seri); @@ -1272,7 +1272,7 @@ namespace wiScene archive << iteration_count; } } - void SpringComponent::Serialize(wiArchive& archive, EntitySerializer& seri) + void SpringComponent::Serialize(wi::Archive& archive, EntitySerializer& seri) { if (archive.IsReadMode()) { @@ -1292,9 +1292,9 @@ namespace wiScene } } - void Scene::Serialize(wiArchive& archive) + void Scene::Serialize(wi::Archive& archive) { - wiTimer timer; + wi::Timer timer; if (archive.IsReadMode()) { @@ -1308,10 +1308,10 @@ namespace wiScene } // Keeping this alive to keep serialized resources alive until entity serialization ends: - wiResourceManager::ResourceSerializer resource_seri; + wi::resourcemanager::ResourceSerializer resource_seri; if (archive.GetVersion() >= 63) { - wiResourceManager::Serialize(archive, resource_seri); + wi::resourcemanager::Serialize(archive, resource_seri); } // With this we will ensure that serialized entities are unique and persistent across the scene: @@ -1359,10 +1359,10 @@ namespace wiScene animation_datas.Serialize(archive, seri); } - wiBackLog::post("Scene serialize took " + std::to_string(timer.elapsed_seconds()) + " sec"); + wi::backlog::post("Scene serialize took " + std::to_string(timer.elapsed_seconds()) + " sec"); } - Entity Scene::Entity_Serialize(wiArchive& archive, Entity entity) + Entity Scene::Entity_Serialize(wi::Archive& archive, Entity entity) { EntitySerializer seri; diff --git a/WickedEngine/wiShaderCompiler.cpp b/WickedEngine/wiShaderCompiler.cpp index ce28bbfb1..19413775a 100644 --- a/WickedEngine/wiShaderCompiler.cpp +++ b/WickedEngine/wiShaderCompiler.cpp @@ -1,5 +1,5 @@ #include "wiShaderCompiler.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiPlatform.h" #include "wiHelper.h" #include "wiArchive.h" @@ -29,11 +29,9 @@ #include #endif // SHADERCOMPILER_ENABLED_D3DCOMPILER -using wiGraphics::ShaderFormat; -using wiGraphics::ShaderStage; -using wiGraphics::ShaderModel; +using namespace wi::graphics; -namespace wiShaderCompiler +namespace wi::shadercompiler { #ifdef SHADERCOMPILER_ENABLED_DXCOMPILER CComPtr dxcUtils; @@ -48,7 +46,7 @@ namespace wiShaderCompiler } wi::vector shadersourcedata; - if (!wiHelper::FileRead(input.shadersourcefilename, shadersourcedata)) + if (!wi::helper::FileRead(input.shadersourcefilename, shadersourcedata)) { return; } @@ -67,7 +65,7 @@ namespace wiShaderCompiler //L"-O0", // Optimization Level 0 }; - if (input.flags & FLAG_DISABLE_OPTIMIZATION) + if (has_flag(input.flags, Flags::DISABLE_OPTIMIZATION)) { args.push_back(L"-Od"); } @@ -323,7 +321,7 @@ namespace wiShaderCompiler for (auto& x : input.defines) { std::wstring& wstr = wstrings.emplace_back(); - wiHelper::StringConvert(x, wstr); + wi::helper::StringConvert(x, wstr); args.push_back(L"-D"); args.push_back(wstr.c_str()); } @@ -331,20 +329,20 @@ namespace wiShaderCompiler for (auto& x : input.include_directories) { std::wstring& wstr = wstrings.emplace_back(); - wiHelper::StringConvert(x, wstr); + wi::helper::StringConvert(x, wstr); args.push_back(L"-I"); args.push_back(wstr.c_str()); } // Entry point parameter: std::wstring wentry; - wiHelper::StringConvert(input.entrypoint, wentry); + wi::helper::StringConvert(input.entrypoint, wentry); args.push_back(L"-E"); args.push_back(wentry.c_str()); // Add source file name as last parameter. This will be displayed in error messages std::wstring wsource; - wiHelper::StringConvert(wiHelper::GetFileNameFromPath(input.shadersourcefilename), wsource); + wi::helper::StringConvert(wi::helper::GetFileNameFromPath(input.shadersourcefilename), wsource); args.push_back(wsource.c_str()); DxcBuffer Source; @@ -366,7 +364,7 @@ namespace wiShaderCompiler if (SUCCEEDED(hr)) { std::string& filename = output->dependencies.emplace_back(); - wiHelper::StringConvert(pFilename, filename); + wi::helper::StringConvert(pFilename, filename); } return hr; } @@ -464,7 +462,7 @@ namespace wiShaderCompiler } wi::vector shadersourcedata; - if (!wiHelper::FileRead(input.shadersourcefilename, shadersourcedata)) + if (!wi::helper::FileRead(input.shadersourcefilename, shadersourcedata)) { return; } @@ -479,27 +477,27 @@ namespace wiShaderCompiler switch (input.stage) { default: - case wiGraphics::MS: - case wiGraphics::AS: - case wiGraphics::LIB: + case ShaderStage::MS: + case ShaderStage::AS: + case ShaderStage::LIB: // not applicable return; - case wiGraphics::VS: + case ShaderStage::VS: target = "vs_5_0"; break; - case wiGraphics::HS: + case ShaderStage::HS: target = "hs_5_0"; break; - case wiGraphics::DS: + case ShaderStage::DS: target = "ds_5_0"; break; - case wiGraphics::GS: + case ShaderStage::GS: target = "gs_5_0"; break; - case wiGraphics::PS: + case ShaderStage::PS: target = "ps_5_0"; break; - case wiGraphics::CS: + case ShaderStage::CS: target = "cs_5_0"; break; } @@ -515,10 +513,10 @@ namespace wiShaderCompiler for (auto& x : input->include_directories) { std::string filename = x + pFileName; - if (!wiHelper::FileExists(filename)) + if (!wi::helper::FileExists(filename)) continue; wi::vector& filedata = filedatas.emplace_back(); - if (wiHelper::FileRead(filename, filedata)) + if (wi::helper::FileRead(filename, filedata)) { output->dependencies.push_back(filename); *ppData = filedata.data(); @@ -606,12 +604,12 @@ namespace wiShaderCompiler assert(SUCCEEDED(hr)); hr = dxcUtils->CreateDefaultIncludeHandler(&dxcIncludeHandler); assert(SUCCEEDED(hr)); - wiBackLog::post("wiShaderCompiler: loaded " LIBDXCOMPILER); + wi::backlog::post("wi::shadercompiler: loaded " LIBDXCOMPILER); } } else { - wiBackLog::post("wiShaderCompiler: could not load library " LIBDXCOMPILER); + wi::backlog::post("wi::shadercompiler: could not load library " LIBDXCOMPILER); } #endif // SHADERCOMPILER_ENABLED_DXCOMPILER @@ -627,7 +625,7 @@ namespace wiShaderCompiler D3DCompile = (PFN_D3DCOMPILE)wiGetProcAddress(d3dcompiler, "D3DCompile"); if (D3DCompile != nullptr) { - wiBackLog::post("wiShaderCompiler: loaded d3dcompiler_47.dll"); + wi::backlog::post("wi::shadercompiler: loaded d3dcompiler_47.dll"); } } #endif // SHADERCOMPILER_ENABLED_D3DCOMPILER @@ -652,7 +650,7 @@ namespace wiShaderCompiler #endif // SHADERCOMPILER_ENABLED_DXCOMPILER #ifdef SHADERCOMPILER_ENABLED_D3DCOMPILER - case wiGraphics::SHADERFORMAT_HLSL5: + case ShaderFormat::HLSL5: Compile_D3DCompiler(input, output); break; #endif // SHADERCOMPILER_ENABLED_D3DCOMPILER @@ -665,21 +663,21 @@ namespace wiShaderCompiler bool SaveShaderAndMetadata(const std::string& shaderfilename, const CompilerOutput& output) { #ifdef SHADERCOMPILER_ENABLED - wiHelper::DirectoryCreate(wiHelper::GetDirectoryFromPath(shaderfilename)); + wi::helper::DirectoryCreate(wi::helper::GetDirectoryFromPath(shaderfilename)); - wiArchive dependencyLibrary(wiHelper::ReplaceExtension(shaderfilename, shadermetaextension), false); + wi::Archive dependencyLibrary(wi::helper::ReplaceExtension(shaderfilename, shadermetaextension), false); if (dependencyLibrary.IsOpen()) { std::string rootdir = dependencyLibrary.GetSourceDirectory(); wi::vector dependencies = output.dependencies; for (auto& x : dependencies) { - wiHelper::MakePathRelative(rootdir, x); + wi::helper::MakePathRelative(rootdir, x); } dependencyLibrary << dependencies; } - if (wiHelper::FileWrite(shaderfilename, output.shaderdata, output.shadersize)) + if (wi::helper::FileWrite(shaderfilename, output.shaderdata, output.shadersize)) { return true; } @@ -691,20 +689,20 @@ namespace wiShaderCompiler { #ifdef SHADERCOMPILER_ENABLED std::string filepath = shaderfilename; - wiHelper::MakePathAbsolute(filepath); - if (!wiHelper::FileExists(filepath)) + wi::helper::MakePathAbsolute(filepath); + if (!wi::helper::FileExists(filepath)) { return true; // no shader file = outdated shader, apps can attempt to rebuild it } - std::string dependencylibrarypath = wiHelper::ReplaceExtension(shaderfilename, shadermetaextension); - if (!wiHelper::FileExists(dependencylibrarypath)) + std::string dependencylibrarypath = wi::helper::ReplaceExtension(shaderfilename, shadermetaextension); + if (!wi::helper::FileExists(dependencylibrarypath)) { return false; // no metadata file = no dependency, up to date (for example packaged builds) } const auto tim = std::filesystem::last_write_time(filepath); - wiArchive dependencyLibrary(dependencylibrarypath); + wi::Archive dependencyLibrary(dependencylibrarypath); if (dependencyLibrary.IsOpen()) { std::string rootdir = dependencyLibrary.GetSourceDirectory(); @@ -714,8 +712,8 @@ namespace wiShaderCompiler for (auto& x : dependencies) { std::string dependencypath = rootdir + x; - wiHelper::MakePathAbsolute(dependencypath); - if (wiHelper::FileExists(dependencypath)) + wi::helper::MakePathAbsolute(dependencypath); + if (wi::helper::FileExists(dependencypath)) { const auto dep_tim = std::filesystem::last_write_time(dependencypath); diff --git a/WickedEngine/wiShaderCompiler.h b/WickedEngine/wiShaderCompiler.h index 0728a15e3..c7f1b0005 100644 --- a/WickedEngine/wiShaderCompiler.h +++ b/WickedEngine/wiShaderCompiler.h @@ -4,23 +4,23 @@ #include -namespace wiShaderCompiler +namespace wi::shadercompiler { void Initialize(); - enum FLAGS + enum class Flags { - FLAG_NONE = 0, - FLAG_DISABLE_OPTIMIZATION = 1 << 0, + NONE = 0, + DISABLE_OPTIMIZATION = 1 << 0, }; struct CompilerInput { - uint64_t flags = FLAG_NONE; - wiGraphics::ShaderFormat format = wiGraphics::ShaderFormat::NONE; - wiGraphics::ShaderStage stage = wiGraphics::ShaderStage::Count; + Flags flags = Flags::NONE; + wi::graphics::ShaderFormat format = wi::graphics::ShaderFormat::NONE; + wi::graphics::ShaderStage stage = wi::graphics::ShaderStage::Count; // if the shader relies on a higher shader model feature, it must be declared here. // But the compiler can also choose a higher one internally, if needed - wiGraphics::ShaderModel minshadermodel = wiGraphics::ShaderModel::SM_5_0; + wi::graphics::ShaderModel minshadermodel = wi::graphics::ShaderModel::SM_5_0; std::string shadersourcefilename; std::string entrypoint = "main"; wi::vector include_directories; @@ -46,3 +46,8 @@ namespace wiShaderCompiler size_t GetRegisteredShaderCount(); bool CheckRegisteredShadersOutdated(); } + +template<> +struct enable_bitmask_operators { + static const bool enable = true; +}; diff --git a/WickedEngine/wiSpinLock.h b/WickedEngine/wiSpinLock.h index a0ec27e82..0d3c1ffcc 100644 --- a/WickedEngine/wiSpinLock.h +++ b/WickedEngine/wiSpinLock.h @@ -1,22 +1,25 @@ #pragma once #include -class wiSpinLock +namespace wi { -private: - std::atomic_flag lck = ATOMIC_FLAG_INIT; -public: - void lock() + class SpinLock { - while (!try_lock()){} - } - bool try_lock() - { - return !lck.test_and_set(std::memory_order_acquire); - } + private: + std::atomic_flag lck = ATOMIC_FLAG_INIT; + public: + void lock() + { + while (!try_lock()) {} + } + bool try_lock() + { + return !lck.test_and_set(std::memory_order_acquire); + } - void unlock() - { - lck.clear(std::memory_order_release); - } -}; + void unlock() + { + lck.clear(std::memory_order_release); + } + }; +} diff --git a/WickedEngine/wiSprite.cpp b/WickedEngine/wiSprite.cpp index 9eae07154..9eda8a276 100644 --- a/WickedEngine/wiSprite.cpp +++ b/WickedEngine/wiSprite.cpp @@ -3,129 +3,134 @@ #include "wiRandom.h" #include "wiTextureHelper.h" -using namespace wiGraphics; +using namespace wi::graphics; -wiSprite::wiSprite(const std::string& newTexture, const std::string& newMask) +namespace wi { - if (!newTexture.empty()) + + Sprite::Sprite(const std::string& newTexture, const std::string& newMask) { - textureName = newTexture; - textureResource = wiResourceManager::Load(newTexture); - } - if (!newMask.empty()) - { - maskName = newMask; - maskResource = wiResourceManager::Load(newMask); - params.setMaskMap(&maskResource->texture); - } -} - -void wiSprite::Draw(CommandList cmd) const -{ - if (IsHidden()) - return; - wiImage::Draw(textureResource != nullptr ? &textureResource->texture : wiTextureHelper::getWhite(), params, cmd); -} - -void wiSprite::FixedUpdate() -{ - if (IsDisableUpdate()) - return; -} - -void wiSprite::Update(float dt) -{ - if (IsDisableUpdate()) - return; - params.pos.x += anim.vel.x*dt; - params.pos.y += anim.vel.y*dt; - params.pos.z += anim.vel.z*dt; - params.rotation += anim.rot*dt; - params.scale.x += anim.scaleX*dt; - params.scale.y += anim.scaleY*dt; - params.opacity += anim.opa*dt; - if (params.opacity >= 1) { - if (anim.repeatable) { params.opacity = 0.99f; anim.opa *= -1; } - else params.opacity = 1; - } - else if (params.opacity <= 0) { - if (anim.repeatable) { params.opacity = 0.01f; anim.opa *= -1; } - else params.opacity = 0; - } - params.fade += anim.fad*dt; - if (params.fade >= 1) { - if (anim.repeatable) { params.fade = 0.99f; anim.fad *= -1; } - else params.fade = 1; - } - else if (params.fade <= 0) { - if (anim.repeatable) { params.fade = 0.01f; anim.fad *= -1; } - else params.fade = 0; - } - - params.texOffset.x += anim.movingTexAnim.speedX*dt; - params.texOffset.y += anim.movingTexAnim.speedY*dt; - - // Draw rect anim: - if (anim.drawRectAnim.frameCount > 0) - { - anim.drawRectAnim._elapsedTime += dt * anim.drawRectAnim.frameRate; - if (anim.drawRectAnim._elapsedTime >= 1.0f) + if (!newTexture.empty()) { - // Reset timer: - anim.drawRectAnim._elapsedTime = 0; + textureName = newTexture; + textureResource = wi::resourcemanager::Load(newTexture); + } + if (!newMask.empty()) + { + maskName = newMask; + maskResource = wi::resourcemanager::Load(newMask); + params.setMaskMap(&maskResource.GetTexture()); + } + } - if (anim.drawRectAnim.horizontalFrameCount == 0) + void Sprite::Draw(CommandList cmd) const + { + if (IsHidden()) + return; + wi::image::Draw(textureResource.IsValid() ? &textureResource.GetTexture() : wi::texturehelper::getWhite(), params, cmd); + } + + void Sprite::FixedUpdate() + { + if (IsDisableUpdate()) + return; + } + + void Sprite::Update(float dt) + { + if (IsDisableUpdate()) + return; + params.pos.x += anim.vel.x * dt; + params.pos.y += anim.vel.y * dt; + params.pos.z += anim.vel.z * dt; + params.rotation += anim.rot * dt; + params.scale.x += anim.scaleX * dt; + params.scale.y += anim.scaleY * dt; + params.opacity += anim.opa * dt; + if (params.opacity >= 1) { + if (anim.repeatable) { params.opacity = 0.99f; anim.opa *= -1; } + else params.opacity = 1; + } + else if (params.opacity <= 0) { + if (anim.repeatable) { params.opacity = 0.01f; anim.opa *= -1; } + else params.opacity = 0; + } + params.fade += anim.fad * dt; + if (params.fade >= 1) { + if (anim.repeatable) { params.fade = 0.99f; anim.fad *= -1; } + else params.fade = 1; + } + else if (params.fade <= 0) { + if (anim.repeatable) { params.fade = 0.01f; anim.fad *= -1; } + else params.fade = 0; + } + + params.texOffset.x += anim.movingTexAnim.speedX * dt; + params.texOffset.y += anim.movingTexAnim.speedY * dt; + + // Draw rect anim: + if (anim.drawRectAnim.frameCount > 0) + { + anim.drawRectAnim._elapsedTime += dt * anim.drawRectAnim.frameRate; + if (anim.drawRectAnim._elapsedTime >= 1.0f) { - // If no horizontal frame count was specified, it means that all the frames are horizontal: - anim.drawRectAnim.horizontalFrameCount = anim.drawRectAnim.frameCount; - } + // Reset timer: + anim.drawRectAnim._elapsedTime = 0; - // Advance frame counter: - anim.drawRectAnim._currentFrame++; - - if (anim.drawRectAnim._currentFrame < anim.drawRectAnim.frameCount) - { - // Step one frame horizontally if animation is still playing: - params.drawRect.x += params.drawRect.z; - - if (anim.drawRectAnim._currentFrame > 0 && - anim.drawRectAnim._currentFrame % anim.drawRectAnim.horizontalFrameCount == 0) + if (anim.drawRectAnim.horizontalFrameCount == 0) { - // if the animation is multiline, we reset horizontally and step downwards: - params.drawRect.x -= params.drawRect.z * anim.drawRectAnim.horizontalFrameCount; - params.drawRect.y += params.drawRect.w; + // If no horizontal frame count was specified, it means that all the frames are horizontal: + anim.drawRectAnim.horizontalFrameCount = anim.drawRectAnim.frameCount; } - } - else if (anim.repeatable) - { - // restart if repeatable: - const int rewind_X = (anim.drawRectAnim.frameCount - 1) % anim.drawRectAnim.horizontalFrameCount; - const int rewind_Y = (anim.drawRectAnim.frameCount - 1) / anim.drawRectAnim.horizontalFrameCount; - params.drawRect.x -= params.drawRect.z * rewind_X; - params.drawRect.y -= params.drawRect.w * rewind_Y; - anim.drawRectAnim._currentFrame = 0; - } + // Advance frame counter: + anim.drawRectAnim._currentFrame++; + + if (anim.drawRectAnim._currentFrame < anim.drawRectAnim.frameCount) + { + // Step one frame horizontally if animation is still playing: + params.drawRect.x += params.drawRect.z; + + if (anim.drawRectAnim._currentFrame > 0 && + anim.drawRectAnim._currentFrame % anim.drawRectAnim.horizontalFrameCount == 0) + { + // if the animation is multiline, we reset horizontally and step downwards: + params.drawRect.x -= params.drawRect.z * anim.drawRectAnim.horizontalFrameCount; + params.drawRect.y += params.drawRect.w; + } + } + else if (anim.repeatable) + { + // restart if repeatable: + const int rewind_X = (anim.drawRectAnim.frameCount - 1) % anim.drawRectAnim.horizontalFrameCount; + const int rewind_Y = (anim.drawRectAnim.frameCount - 1) / anim.drawRectAnim.horizontalFrameCount; + params.drawRect.x -= params.drawRect.z * rewind_X; + params.drawRect.y -= params.drawRect.w * rewind_Y; + anim.drawRectAnim._currentFrame = 0; + } + + } } - } - // Wobble anim: - if (anim.wobbleAnim.amount.x > 0 || anim.wobbleAnim.amount.y > 0) - { - // Rotate each corner on a scaled circle (ellipsoid): - // Since the rotations are randomized, it will look like a wobble effect - // Also use two circles on each other to achieve more random look - wiImageParams default_params; // contains corners in idle positions - for (int i = 0; i < 4; ++i) + // Wobble anim: + if (anim.wobbleAnim.amount.x > 0 || anim.wobbleAnim.amount.y > 0) { - anim.wobbleAnim.corner_angles[i] += XM_2PI * anim.wobbleAnim.speed * anim.wobbleAnim.corner_speeds[i] * dt; - anim.wobbleAnim.corner_angles2[i] += XM_2PI * anim.wobbleAnim.speed * anim.wobbleAnim.corner_speeds2[i] * dt; - default_params.corners[i].x += std::sin(anim.wobbleAnim.corner_angles[i]) * anim.wobbleAnim.amount.x * 0.5f; - default_params.corners[i].y += std::cos(anim.wobbleAnim.corner_angles[i]) * anim.wobbleAnim.amount.y * 0.5f; - default_params.corners[i].x += std::sin(anim.wobbleAnim.corner_angles2[i]) * anim.wobbleAnim.amount.x * 0.25f; - default_params.corners[i].y += std::cos(anim.wobbleAnim.corner_angles2[i]) * anim.wobbleAnim.amount.y * 0.25f; - params.corners[i] = default_params.corners[i]; + // Rotate each corner on a scaled circle (ellipsoid): + // Since the rotations are randomized, it will look like a wobble effect + // Also use two circles on each other to achieve more random look + wi::image::Params default_params; // contains corners in idle positions + for (int i = 0; i < 4; ++i) + { + anim.wobbleAnim.corner_angles[i] += XM_2PI * anim.wobbleAnim.speed * anim.wobbleAnim.corner_speeds[i] * dt; + anim.wobbleAnim.corner_angles2[i] += XM_2PI * anim.wobbleAnim.speed * anim.wobbleAnim.corner_speeds2[i] * dt; + default_params.corners[i].x += std::sin(anim.wobbleAnim.corner_angles[i]) * anim.wobbleAnim.amount.x * 0.5f; + default_params.corners[i].y += std::cos(anim.wobbleAnim.corner_angles[i]) * anim.wobbleAnim.amount.y * 0.5f; + default_params.corners[i].x += std::sin(anim.wobbleAnim.corner_angles2[i]) * anim.wobbleAnim.amount.x * 0.25f; + default_params.corners[i].y += std::cos(anim.wobbleAnim.corner_angles2[i]) * anim.wobbleAnim.amount.y * 0.25f; + params.corners[i] = default_params.corners[i]; + } } + } } diff --git a/WickedEngine/wiSprite.h b/WickedEngine/wiSprite.h index 5bf27c68a..d72664ce2 100644 --- a/WickedEngine/wiSprite.h +++ b/WickedEngine/wiSprite.h @@ -7,97 +7,101 @@ #include #include -class wiSprite +namespace wi { -private: - enum FLAGS + class Sprite { - EMPTY = 0, - HIDDEN = 1 << 0, - DISABLE_UPDATE = 1 << 1, - }; - uint32_t _flags = EMPTY; - - std::string textureName, maskName; -public: - wiSprite(const std::string& newTexture = "", const std::string& newMask = ""); - - virtual void FixedUpdate(); - virtual void Update(float dt); - virtual void Draw(wiGraphics::CommandList cmd) const; - - constexpr void SetHidden(bool value = true) { if (value) { _flags |= HIDDEN; } else { _flags &= ~HIDDEN; } } - constexpr bool IsHidden() const { return _flags & HIDDEN; } - constexpr void SetDisableUpdate(bool value = true) { if (value) { _flags |= DISABLE_UPDATE; } else { _flags &= ~DISABLE_UPDATE; } } - constexpr bool IsDisableUpdate() const { return _flags & DISABLE_UPDATE; } - - wiImageParams params; - std::shared_ptr textureResource; - std::shared_ptr maskResource; - - struct Anim - { - struct MovingTexAnim + private: + enum FLAGS { - float speedX = 0; // the speed of texture scrolling animation in horizontal direction - float speedY = 0; // the speed of texture scrolling animation in vertical direction + EMPTY = 0, + HIDDEN = 1 << 0, + DISABLE_UPDATE = 1 << 1, }; - struct DrawRectAnim - { - float frameRate = 30; // target frame rate of the spritesheet animation (eg. 30, 60, etc.) - int frameCount = 1; // how many frames are in the animation in total - int horizontalFrameCount = 0; // how many horizontal frames there are (optional, use if the spritesheet contains multiple rows) + uint32_t _flags = EMPTY; - float _elapsedTime = 0; // internal use; you don't need to initialize - int _currentFrame = 0; // internal use; you don't need to initialize - }; - struct WobbleAnim - { - XMFLOAT2 amount = XMFLOAT2(0, 0); // how much the sprite wobbles in X and Y direction - float speed = 1; // how fast the sprite wobbles + std::string textureName, maskName; + public: + Sprite(const std::string& newTexture = "", const std::string& newMask = ""); - float corner_angles[4]; // internal use; you don't need to initialize - float corner_speeds[4]; // internal use; you don't need to initialize - float corner_angles2[4]; // internal use; you don't need to initialize - float corner_speeds2[4]; // internal use; you don't need to initialize - WobbleAnim() + virtual void FixedUpdate(); + virtual void Update(float dt); + virtual void Draw(wi::graphics::CommandList cmd) const; + + constexpr void SetHidden(bool value = true) { if (value) { _flags |= HIDDEN; } else { _flags &= ~HIDDEN; } } + constexpr bool IsHidden() const { return _flags & HIDDEN; } + constexpr void SetDisableUpdate(bool value = true) { if (value) { _flags |= DISABLE_UPDATE; } else { _flags &= ~DISABLE_UPDATE; } } + constexpr bool IsDisableUpdate() const { return _flags & DISABLE_UPDATE; } + + wi::image::Params params; + wi::Resource textureResource; + wi::Resource maskResource; + + struct Anim + { + struct MovingTexAnim { - for (int i = 0; i < 4; ++i) + float speedX = 0; // the speed of texture scrolling animation in horizontal direction + float speedY = 0; // the speed of texture scrolling animation in vertical direction + }; + struct DrawRectAnim + { + float frameRate = 30; // target frame rate of the spritesheet animation (eg. 30, 60, etc.) + int frameCount = 1; // how many frames are in the animation in total + int horizontalFrameCount = 0; // how many horizontal frames there are (optional, use if the spritesheet contains multiple rows) + + float _elapsedTime = 0; // internal use; you don't need to initialize + int _currentFrame = 0; // internal use; you don't need to initialize + }; + struct WobbleAnim + { + XMFLOAT2 amount = XMFLOAT2(0, 0); // how much the sprite wobbles in X and Y direction + float speed = 1; // how fast the sprite wobbles + + float corner_angles[4]; // internal use; you don't need to initialize + float corner_speeds[4]; // internal use; you don't need to initialize + float corner_angles2[4]; // internal use; you don't need to initialize + float corner_speeds2[4]; // internal use; you don't need to initialize + WobbleAnim() { - corner_angles[i] = wiRandom::getRandom(0, 1000) / 1000.0f * XM_2PI; - corner_speeds[i] = wiRandom::getRandom(500, 1000) / 1000.0f; - if (wiRandom::getRandom(0, 1) == 0) + for (int i = 0; i < 4; ++i) { - corner_speeds[i] *= -1; - } - corner_angles2[i] = wiRandom::getRandom(0, 1000) / 1000.0f * XM_2PI; - corner_speeds2[i] = wiRandom::getRandom(500, 1000) / 1000.0f; - if (wiRandom::getRandom(0, 1) == 0) - { - corner_speeds2[i] *= -1; + corner_angles[i] = wi::random::GetRandom(0, 1000) / 1000.0f * XM_2PI; + corner_speeds[i] = wi::random::GetRandom(500, 1000) / 1000.0f; + if (wi::random::GetRandom(0, 1) == 0) + { + corner_speeds[i] *= -1; + } + corner_angles2[i] = wi::random::GetRandom(0, 1000) / 1000.0f * XM_2PI; + corner_speeds2[i] = wi::random::GetRandom(500, 1000) / 1000.0f; + if (wi::random::GetRandom(0, 1) == 0) + { + corner_speeds2[i] *= -1; + } } } - } + }; + + bool repeatable = false; + XMFLOAT3 vel = XMFLOAT3(0, 0, 0); + float rot = 0; + float scaleX = 0; + float scaleY = 0; + float opa = 0; + float fad = 0; + MovingTexAnim movingTexAnim; + DrawRectAnim drawRectAnim; + WobbleAnim wobbleAnim; }; + Anim anim; - bool repeatable = false; - XMFLOAT3 vel = XMFLOAT3(0, 0, 0); - float rot = 0; - float scaleX = 0; - float scaleY = 0; - float opa = 0; - float fad = 0; - MovingTexAnim movingTexAnim; - DrawRectAnim drawRectAnim; - WobbleAnim wobbleAnim; + const wi::graphics::Texture* getTexture() const + { + if (textureResource.IsValid()) + { + return &textureResource.GetTexture(); + } + return nullptr; + } }; - Anim anim; - - const wiGraphics::Texture* getTexture() const - { - if(textureResource != nullptr) - return &textureResource->texture; - return nullptr; - } -}; - +} diff --git a/WickedEngine/wiSpriteAnim_BindLua.cpp b/WickedEngine/wiSpriteAnim_BindLua.cpp new file mode 100644 index 000000000..1ed20be72 --- /dev/null +++ b/WickedEngine/wiSpriteAnim_BindLua.cpp @@ -0,0 +1,420 @@ +#include "wiSpriteAnim_BindLua.h" +#include "wiMath_BindLua.h" + +namespace wi::lua +{ + + const char SpriteAnim_BindLua::className[] = "SpriteAnim"; + + Luna::FunctionType SpriteAnim_BindLua::methods[] = { + lunamethod(SpriteAnim_BindLua, SetRot), + lunamethod(SpriteAnim_BindLua, SetRotation), + lunamethod(SpriteAnim_BindLua, SetOpacity), + lunamethod(SpriteAnim_BindLua, SetFade), + lunamethod(SpriteAnim_BindLua, SetRepeatable), + lunamethod(SpriteAnim_BindLua, SetVelocity), + lunamethod(SpriteAnim_BindLua, SetScaleX), + lunamethod(SpriteAnim_BindLua, SetScaleY), + lunamethod(SpriteAnim_BindLua, SetMovingTexAnim), + lunamethod(SpriteAnim_BindLua, SetDrawRecAnim), + + lunamethod(SpriteAnim_BindLua, GetRot), + lunamethod(SpriteAnim_BindLua, GetRotation), + lunamethod(SpriteAnim_BindLua, GetOpacity), + lunamethod(SpriteAnim_BindLua, GetFade), + lunamethod(SpriteAnim_BindLua, GetRepeatable), + lunamethod(SpriteAnim_BindLua, GetVelocity), + lunamethod(SpriteAnim_BindLua, GetScaleX), + lunamethod(SpriteAnim_BindLua, GetScaleY), + lunamethod(SpriteAnim_BindLua, GetMovingTexAnim), + lunamethod(SpriteAnim_BindLua, GetDrawRecAnim), + { NULL, NULL } + }; + Luna::PropertyType SpriteAnim_BindLua::properties[] = { + { NULL, NULL } + }; + + SpriteAnim_BindLua::SpriteAnim_BindLua(const wi::Sprite::Anim& anim) :anim(anim) + { + } + + SpriteAnim_BindLua::SpriteAnim_BindLua(lua_State* L) + { + anim = wi::Sprite::Anim(); + } + + + + int SpriteAnim_BindLua::SetRot(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.rot = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetRot(float rot) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetRotation(lua_State* L) + { + return SetRot(L); + } + int SpriteAnim_BindLua::SetOpacity(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.opa = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetOpacity(float val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetFade(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.fad = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetFade(float val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetRepeatable(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.repeatable = wi::lua::SGetBool(L, 1); + } + else + { + wi::lua::SError(L, "SetRepeatable(float val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetVelocity(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* vec = Luna::lightcheck(L, 1); + if (vec != nullptr) + { + XMStoreFloat3(&anim.vel, XMLoadFloat4(vec)); + } + else + { + wi::lua::SError(L, "SetVelocity(Vector val) argument is not a Vector!"); + } + } + else + { + wi::lua::SError(L, "SetVelocity(Vector val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetScaleX(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.scaleX = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetScaleX(float val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetScaleY(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.scaleY = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetScaleY(float val) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetMovingTexAnim(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + MovingTexAnim_BindLua* data = Luna::lightcheck(L, 1); + if (data != nullptr) + { + anim.movingTexAnim = data->anim; + } + else + { + wi::lua::SError(L, "SetMovingTexAnim(MovingTexAnim data) argument is not a MovingTexAnim!"); + } + } + else + { + wi::lua::SError(L, "SetMovingTexAnim(MovingTexAnim data) not enough arguments!"); + } + return 0; + } + int SpriteAnim_BindLua::SetDrawRecAnim(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + DrawRectAnim_BindLua* data = Luna::lightcheck(L, 1); + if (data != nullptr) + { + anim.drawRectAnim = data->anim; + } + else + { + wi::lua::SError(L, "SetDrawRecAnim(DrawRecAnim data) argument is not a DrawRecAnim!"); + } + } + else + { + wi::lua::SError(L, "SetDrawRecAnim(DrawRecAnim data) not enough arguments!"); + } + return 0; + } + + int SpriteAnim_BindLua::GetRot(lua_State* L) + { + wi::lua::SSetFloat(L, anim.rot); + return 1; + } + int SpriteAnim_BindLua::GetRotation(lua_State* L) + { + return GetRot(L); + } + int SpriteAnim_BindLua::GetOpacity(lua_State* L) + { + wi::lua::SSetFloat(L, anim.opa); + return 1; + } + int SpriteAnim_BindLua::GetFade(lua_State* L) + { + wi::lua::SSetFloat(L, anim.fad); + return 1; + } + int SpriteAnim_BindLua::GetRepeatable(lua_State* L) + { + wi::lua::SSetBool(L, anim.repeatable); + return 1; + } + int SpriteAnim_BindLua::GetVelocity(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMLoadFloat3(&anim.vel))); + return 1; + } + int SpriteAnim_BindLua::GetScaleX(lua_State* L) + { + wi::lua::SSetFloat(L, anim.scaleX); + return 1; + } + int SpriteAnim_BindLua::GetScaleY(lua_State* L) + { + wi::lua::SSetFloat(L, anim.scaleY); + return 1; + } + int SpriteAnim_BindLua::GetMovingTexAnim(lua_State* L) + { + Luna::push(L, new MovingTexAnim_BindLua(anim.movingTexAnim)); + return 1; + } + int SpriteAnim_BindLua::GetDrawRecAnim(lua_State* L) + { + Luna::push(L, new DrawRectAnim_BindLua(anim.drawRectAnim)); + return 1; + } + + void SpriteAnim_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + Luna::Register(wi::lua::GetLuaState()); + Luna::Register(wi::lua::GetLuaState()); + } + } + + + + + const char MovingTexAnim_BindLua::className[] = "MovingTexAnim"; + + Luna::FunctionType MovingTexAnim_BindLua::methods[] = { + lunamethod(MovingTexAnim_BindLua, SetSpeedX), + lunamethod(MovingTexAnim_BindLua, SetSpeedY), + + lunamethod(MovingTexAnim_BindLua, GetSpeedX), + lunamethod(MovingTexAnim_BindLua, GetSpeedY), + { NULL, NULL } + }; + Luna::PropertyType MovingTexAnim_BindLua::properties[] = { + { NULL, NULL } + }; + + MovingTexAnim_BindLua::MovingTexAnim_BindLua(const wi::Sprite::Anim::MovingTexAnim& anim) :anim(anim) + { + } + + MovingTexAnim_BindLua::MovingTexAnim_BindLua(lua_State* L) + { + anim = wi::Sprite::Anim::MovingTexAnim(); + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.speedX = wi::lua::SGetFloat(L, 1); + if (argc > 1) + { + anim.speedY = wi::lua::SGetFloat(L, 2); + } + } + } + + MovingTexAnim_BindLua::~MovingTexAnim_BindLua() + { + } + + int MovingTexAnim_BindLua::SetSpeedX(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.speedX = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetSpeedX(float val) not enough arguments!"); + } + return 0; + } + int MovingTexAnim_BindLua::SetSpeedY(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.speedY = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetSpeedY(float val) not enough arguments!"); + } + return 0; + } + + int MovingTexAnim_BindLua::GetSpeedX(lua_State* L) + { + wi::lua::SSetFloat(L, anim.speedX); + return 1; + } + int MovingTexAnim_BindLua::GetSpeedY(lua_State* L) + { + wi::lua::SSetFloat(L, anim.speedY); + return 1; + } + + + + const char DrawRectAnim_BindLua::className[] = "DrawRecAnim"; + + Luna::FunctionType DrawRectAnim_BindLua::methods[] = { + lunamethod(DrawRectAnim_BindLua, SetFrameRate), + lunamethod(DrawRectAnim_BindLua, SetFrameCount), + lunamethod(DrawRectAnim_BindLua, SetHorizontalFrameCount), + + lunamethod(DrawRectAnim_BindLua, GetFrameRate), + lunamethod(DrawRectAnim_BindLua, GetFrameCount), + lunamethod(DrawRectAnim_BindLua, GetHorizontalFrameCount), + { NULL, NULL } + }; + Luna::PropertyType DrawRectAnim_BindLua::properties[] = { + { NULL, NULL } + }; + + DrawRectAnim_BindLua::DrawRectAnim_BindLua(const wi::Sprite::Anim::DrawRectAnim& data) :anim(anim) + { + } + + DrawRectAnim_BindLua::DrawRectAnim_BindLua(lua_State* L) + { + anim = wi::Sprite::Anim::DrawRectAnim(); + } + + DrawRectAnim_BindLua::~DrawRectAnim_BindLua() + { + } + + int DrawRectAnim_BindLua::SetFrameRate(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.frameRate = wi::lua::SGetFloat(L, 1); + } + else + { + wi::lua::SError(L, "SetFrameRate(float val) not enough arguments!"); + } + return 0; + } + int DrawRectAnim_BindLua::SetFrameCount(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.frameCount = wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetFrameCount(int val) not enough arguments!"); + } + return 0; + } + int DrawRectAnim_BindLua::SetHorizontalFrameCount(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + anim.horizontalFrameCount = wi::lua::SGetInt(L, 1); + } + else + { + wi::lua::SError(L, "SetHorizontalFrameCount(int val) not enough arguments!"); + } + return 0; + } + + int DrawRectAnim_BindLua::GetFrameRate(lua_State* L) + { + wi::lua::SSetFloat(L, anim.frameRate); + return 1; + } + int DrawRectAnim_BindLua::GetFrameCount(lua_State* L) + { + wi::lua::SSetInt(L, anim.frameCount); + return 1; + } + int DrawRectAnim_BindLua::GetHorizontalFrameCount(lua_State* L) + { + wi::lua::SSetInt(L, anim.horizontalFrameCount); + return 1; + } + +} diff --git a/WickedEngine/wiSpriteAnim_BindLua.h b/WickedEngine/wiSpriteAnim_BindLua.h new file mode 100644 index 000000000..9355697f5 --- /dev/null +++ b/WickedEngine/wiSpriteAnim_BindLua.h @@ -0,0 +1,89 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiSprite.h" + +namespace wi::lua +{ + + class SpriteAnim_BindLua + { + public: + wi::Sprite::Anim anim; + + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + SpriteAnim_BindLua(const wi::Sprite::Anim& anim); + SpriteAnim_BindLua(lua_State* L); + + int SetRot(lua_State* L); + int SetRotation(lua_State* L); + int SetOpacity(lua_State* L); + int SetFade(lua_State* L); + int SetRepeatable(lua_State* L); + int SetVelocity(lua_State* L); + int SetScaleX(lua_State* L); + int SetScaleY(lua_State* L); + int SetMovingTexAnim(lua_State* L); + int SetDrawRecAnim(lua_State* L); + + int GetRot(lua_State* L); + int GetRotation(lua_State* L); + int GetOpacity(lua_State* L); + int GetFade(lua_State* L); + int GetRepeatable(lua_State* L); + int GetVelocity(lua_State* L); + int GetScaleX(lua_State* L); + int GetScaleY(lua_State* L); + int GetMovingTexAnim(lua_State* L); + int GetDrawRecAnim(lua_State* L); + + + static void Bind(); + }; + + class MovingTexAnim_BindLua + { + public: + wi::Sprite::Anim::MovingTexAnim anim; + + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + MovingTexAnim_BindLua(const wi::Sprite::Anim::MovingTexAnim& anim); + MovingTexAnim_BindLua(lua_State* L); + ~MovingTexAnim_BindLua(); + + int SetSpeedX(lua_State* L); + int SetSpeedY(lua_State* L); + + int GetSpeedX(lua_State* L); + int GetSpeedY(lua_State* L); + }; + + class DrawRectAnim_BindLua + { + public: + wi::Sprite::Anim::DrawRectAnim anim; + + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + DrawRectAnim_BindLua(const wi::Sprite::Anim::DrawRectAnim& anim); + DrawRectAnim_BindLua(lua_State* L); + ~DrawRectAnim_BindLua(); + + int SetFrameRate(lua_State* L); + int SetFrameCount(lua_State* L); + int SetHorizontalFrameCount(lua_State* L); + + int GetFrameRate(lua_State* L); + int GetFrameCount(lua_State* L); + int GetHorizontalFrameCount(lua_State* L); + }; + +} diff --git a/WickedEngine/wiSpriteFont.cpp b/WickedEngine/wiSpriteFont.cpp index 6f37dae8e..803ed5133 100644 --- a/WickedEngine/wiSpriteFont.cpp +++ b/WickedEngine/wiSpriteFont.cpp @@ -1,59 +1,64 @@ #include "wiSpriteFont.h" #include "wiHelper.h" -using namespace wiGraphics; +using namespace wi::graphics; -void wiSpriteFont::FixedUpdate() +namespace wi { - if (IsDisableUpdate()) - return; -} -void wiSpriteFont::Update(float dt) -{ - if (IsDisableUpdate()) - return; -} -void wiSpriteFont::Draw(CommandList cmd) const -{ - if (IsHidden()) - return; - wiFont::Draw(text, params, cmd); -} + void SpriteFont::FixedUpdate() + { + if (IsDisableUpdate()) + return; + } + void SpriteFont::Update(float dt) + { + if (IsDisableUpdate()) + return; + } -float wiSpriteFont::textWidth() const -{ - return wiFont::textWidth(text, params); -} -float wiSpriteFont::textHeight() const -{ - return wiFont::textHeight(text, params); -} + void SpriteFont::Draw(CommandList cmd) const + { + if (IsHidden()) + return; + wi::font::Draw(text, params, cmd); + } -void wiSpriteFont::SetText(const std::string& value) -{ - wiHelper::StringConvert(value, text); -} -void wiSpriteFont::SetText(std::string&& value) -{ - wiHelper::StringConvert(value, text); -} -void wiSpriteFont::SetText(const std::wstring& value) -{ - text = value; -} -void wiSpriteFont::SetText(std::wstring&& value) -{ - text = value; -} + float SpriteFont::TextWidth() const + { + return wi::font::TextWidth(text, params); + } + float SpriteFont::TextHeight() const + { + return wi::font::TextHeight(text, params); + } + + void SpriteFont::SetText(const std::string& value) + { + wi::helper::StringConvert(value, text); + } + void SpriteFont::SetText(std::string&& value) + { + wi::helper::StringConvert(value, text); + } + void SpriteFont::SetText(const std::wstring& value) + { + text = value; + } + void SpriteFont::SetText(std::wstring&& value) + { + text = value; + } + + std::string SpriteFont::GetTextA() const + { + std::string retVal; + wi::helper::StringConvert(text, retVal); + return retVal; + } + const std::wstring& SpriteFont::GetText() const + { + return text; + } -std::string wiSpriteFont::GetTextA() const -{ - std::string retVal; - wiHelper::StringConvert(text, retVal); - return retVal; -} -const std::wstring& wiSpriteFont::GetText() const -{ - return text; } diff --git a/WickedEngine/wiSpriteFont.h b/WickedEngine/wiSpriteFont.h index 2aace38bb..e2d479bce 100644 --- a/WickedEngine/wiSpriteFont.h +++ b/WickedEngine/wiSpriteFont.h @@ -3,43 +3,46 @@ #include -class wiSpriteFont +namespace wi { -private: - enum FLAGS + class SpriteFont { - EMPTY = 0, - HIDDEN = 1 << 0, - DISABLE_UPDATE = 1 << 1, + private: + enum FLAGS + { + EMPTY = 0, + HIDDEN = 1 << 0, + DISABLE_UPDATE = 1 << 1, + }; + uint32_t _flags = EMPTY; + public: + std::wstring text; + wi::font::Params params; + + SpriteFont() = default; + SpriteFont(const std::string& value, const wi::font::Params& params = wi::font::Params()) :params(params) + { + SetText(value); + } + + virtual void FixedUpdate(); + virtual void Update(float dt); + virtual void Draw(wi::graphics::CommandList cmd) const; + + constexpr void SetHidden(bool value = true) { if (value) { _flags |= HIDDEN; } else { _flags &= ~HIDDEN; } } + constexpr bool IsHidden() const { return _flags & HIDDEN; } + constexpr void SetDisableUpdate(bool value = true) { if (value) { _flags |= DISABLE_UPDATE; } else { _flags &= ~DISABLE_UPDATE; } } + constexpr bool IsDisableUpdate() const { return _flags & DISABLE_UPDATE; } + + float TextWidth() const; + float TextHeight() const; + + void SetText(const std::string& value); + void SetText(std::string&& value); + void SetText(const std::wstring& value); + void SetText(std::wstring&& value); + + std::string GetTextA() const; + const std::wstring& GetText() const; }; - uint32_t _flags = EMPTY; -public: - std::wstring text; - wiFontParams params; - - wiSpriteFont() = default; - wiSpriteFont(const std::string& value, const wiFontParams& params = wiFontParams()) :params(params) - { - SetText(value); - } - - virtual void FixedUpdate(); - virtual void Update(float dt); - virtual void Draw(wiGraphics::CommandList cmd) const; - - constexpr void SetHidden(bool value = true) { if (value) { _flags |= HIDDEN; } else { _flags &= ~HIDDEN; } } - constexpr bool IsHidden() const { return _flags & HIDDEN; } - constexpr void SetDisableUpdate(bool value = true) { if (value) { _flags |= DISABLE_UPDATE; } else { _flags &= ~DISABLE_UPDATE; } } - constexpr bool IsDisableUpdate() const { return _flags & DISABLE_UPDATE; } - - float textWidth() const; - float textHeight() const; - - void SetText(const std::string& value); - void SetText(std::string&& value); - void SetText(const std::wstring& value); - void SetText(std::wstring&& value); - - std::string GetTextA() const; - const std::wstring& GetText() const; -}; +} diff --git a/WickedEngine/wiSpriteFont_BindLua.cpp b/WickedEngine/wiSpriteFont_BindLua.cpp index 7b55fec03..c78768565 100644 --- a/WickedEngine/wiSpriteFont_BindLua.cpp +++ b/WickedEngine/wiSpriteFont_BindLua.cpp @@ -1,226 +1,230 @@ #include "wiSpriteFont_BindLua.h" #include "wiFont.h" -#include "CommonInclude.h" -#include "Vector_BindLua.h" +#include "wiMath_BindLua.h" -const char wiSpriteFont_BindLua::className[] = "SpriteFont"; - -Luna::FunctionType wiSpriteFont_BindLua::methods[] = { - lunamethod(wiSpriteFont_BindLua, GetText), - lunamethod(wiSpriteFont_BindLua, SetSize), - lunamethod(wiSpriteFont_BindLua, SetPos), - lunamethod(wiSpriteFont_BindLua, SetSpacing), - lunamethod(wiSpriteFont_BindLua, SetAlign), - lunamethod(wiSpriteFont_BindLua, SetColor), - lunamethod(wiSpriteFont_BindLua, SetShadowColor), - - lunamethod(wiSpriteFont_BindLua, SetStyle), - lunamethod(wiSpriteFont_BindLua, SetText), - lunamethod(wiSpriteFont_BindLua, GetSize), - lunamethod(wiSpriteFont_BindLua, GetPos), - lunamethod(wiSpriteFont_BindLua, GetSpacing), - lunamethod(wiSpriteFont_BindLua, GetAlign), - lunamethod(wiSpriteFont_BindLua, GetColor), - lunamethod(wiSpriteFont_BindLua, GetShadowColor), - - { NULL, NULL } -}; -Luna::PropertyType wiSpriteFont_BindLua::properties[] = { - { NULL, NULL } -}; - -wiSpriteFont_BindLua::wiSpriteFont_BindLua(const wiSpriteFont& font) : font(font) +namespace wi::lua { -} -wiSpriteFont_BindLua::wiSpriteFont_BindLua(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + + const char SpriteFont_BindLua::className[] = "SpriteFont"; + + Luna::FunctionType SpriteFont_BindLua::methods[] = { + lunamethod(SpriteFont_BindLua, GetText), + lunamethod(SpriteFont_BindLua, SetSize), + lunamethod(SpriteFont_BindLua, SetPos), + lunamethod(SpriteFont_BindLua, SetSpacing), + lunamethod(SpriteFont_BindLua, SetAlign), + lunamethod(SpriteFont_BindLua, SetColor), + lunamethod(SpriteFont_BindLua, SetShadowColor), + + lunamethod(SpriteFont_BindLua, SetStyle), + lunamethod(SpriteFont_BindLua, SetText), + lunamethod(SpriteFont_BindLua, GetSize), + lunamethod(SpriteFont_BindLua, GetPos), + lunamethod(SpriteFont_BindLua, GetSpacing), + lunamethod(SpriteFont_BindLua, GetAlign), + lunamethod(SpriteFont_BindLua, GetColor), + lunamethod(SpriteFont_BindLua, GetShadowColor), + + { NULL, NULL } + }; + Luna::PropertyType SpriteFont_BindLua::properties[] = { + { NULL, NULL } + }; + + SpriteFont_BindLua::SpriteFont_BindLua(const wi::SpriteFont& font) : font(font) { - std::string text = wiLua::SGetString(L, 1); - font.SetText(text); } -} - - -int wiSpriteFont_BindLua::SetStyle(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + SpriteFont_BindLua::SpriteFont_BindLua(lua_State* L) { - std::string name = wiLua::SGetString(L, 1); - font.params.style = wiFont::AddFontStyle(name.c_str()); - } - else - { - wiLua::SError(L, "SetStyle(string style, opt int size = 16) not enough arguments!"); - } - return 0; -} -int wiSpriteFont_BindLua::SetText(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - font.SetText(wiLua::SGetString(L, 1)); - else - font.SetText(""); - return 0; -} -int wiSpriteFont_BindLua::SetSize(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - font.params.size = wiLua::SGetInt(L, 1); - } - else - wiLua::SError(L, "SetSize(int size) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::SetPos(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* param = Luna::lightcheck(L, 1); - if (param != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - font.params.posX = param->x; - font.params.posY = param->y; - } - else - wiLua::SError(L, "SetPos(Vector pos) argument is not a vector!"); - } - else - wiLua::SError(L, "SetPos(Vector pos) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::SetSpacing(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - Vector_BindLua* param = Luna::lightcheck(L, 1); - if (param != nullptr) - { - font.params.spacingX = param->x; - font.params.spacingY = param->y; - } - else - wiLua::SError(L, "SetSpacing(Vector spacing) argument is not a vector!"); - } - else - wiLua::SError(L, "SetSpacing(Vector spacing) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::SetAlign(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - font.params.h_align = (wiFontAlign)wiLua::SGetInt(L, 1); - if (argc > 1) - { - font.params.v_align = (wiFontAlign)wiLua::SGetInt(L, 2); + std::string text = wi::lua::SGetString(L, 1); + font.SetText(text); } } - else - wiLua::SError(L, "SetAlign(WIFALIGN Halign, opt WIFALIGN Valign) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::SetColor(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + + + int SpriteFont_BindLua::SetStyle(lua_State* L) { - Vector_BindLua* param = Luna::lightcheck(L, 1); - if (param != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - font.params.color = wiColor::fromFloat4(*param); + std::string name = wi::lua::SGetString(L, 1); + font.params.style = wi::font::AddFontStyle(name.c_str()); } else { - int code = wiLua::SGetInt(L, 1); - font.params.color.rgba = (uint32_t)code; + wi::lua::SError(L, "SetStyle(string style, opt int size = 16) not enough arguments!"); } + return 0; } - else - wiLua::SError(L, "SetColor(Vector value) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::SetShadowColor(lua_State* L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + int SpriteFont_BindLua::SetText(lua_State* L) { - Vector_BindLua* param = Luna::lightcheck(L, 1); - if (param != nullptr) + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + font.SetText(wi::lua::SGetString(L, 1)); + else + font.SetText(""); + return 0; + } + int SpriteFont_BindLua::SetSize(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - font.params.shadowColor = wiColor::fromFloat4(*param); + font.params.size = wi::lua::SGetInt(L, 1); } else + wi::lua::SError(L, "SetSize(int size) not enough arguments!"); + return 0; + } + int SpriteFont_BindLua::SetPos(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - int code = wiLua::SGetInt(L, 1); - font.params.shadowColor.rgba = (uint32_t)code; + Vector_BindLua* param = Luna::lightcheck(L, 1); + if (param != nullptr) + { + font.params.posX = param->x; + font.params.posY = param->y; + } + else + wi::lua::SError(L, "SetPos(Vector pos) argument is not a vector!"); + } + else + wi::lua::SError(L, "SetPos(Vector pos) not enough arguments!"); + return 0; + } + int SpriteFont_BindLua::SetSpacing(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* param = Luna::lightcheck(L, 1); + if (param != nullptr) + { + font.params.spacingX = param->x; + font.params.spacingY = param->y; + } + else + wi::lua::SError(L, "SetSpacing(Vector spacing) argument is not a vector!"); + } + else + wi::lua::SError(L, "SetSpacing(Vector spacing) not enough arguments!"); + return 0; + } + int SpriteFont_BindLua::SetAlign(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + font.params.h_align = (wi::font::Alignment)wi::lua::SGetInt(L, 1); + if (argc > 1) + { + font.params.v_align = (wi::font::Alignment)wi::lua::SGetInt(L, 2); + } + } + else + wi::lua::SError(L, "SetAlign(WIFALIGN Halign, opt WIFALIGN Valign) not enough arguments!"); + return 0; + } + int SpriteFont_BindLua::SetColor(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* param = Luna::lightcheck(L, 1); + if (param != nullptr) + { + font.params.color = wi::Color::fromFloat4(*param); + } + else + { + int code = wi::lua::SGetInt(L, 1); + font.params.color.rgba = (uint32_t)code; + } + } + else + wi::lua::SError(L, "SetColor(Vector value) not enough arguments!"); + return 0; + } + int SpriteFont_BindLua::SetShadowColor(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + Vector_BindLua* param = Luna::lightcheck(L, 1); + if (param != nullptr) + { + font.params.shadowColor = wi::Color::fromFloat4(*param); + } + else + { + int code = wi::lua::SGetInt(L, 1); + font.params.shadowColor.rgba = (uint32_t)code; + } + } + else + wi::lua::SError(L, "SetShadowColor(Vector value) not enough arguments!"); + return 0; + } + + int SpriteFont_BindLua::GetText(lua_State* L) + { + wi::lua::SSetString(L, font.GetTextA()); + return 1; + } + int SpriteFont_BindLua::GetSize(lua_State* L) + { + wi::lua::SSetInt(L, font.params.size); + return 1; + } + int SpriteFont_BindLua::GetPos(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMVectorSet((float)font.params.posX, (float)font.params.posY, 0, 0))); + return 1; + } + int SpriteFont_BindLua::GetSpacing(lua_State* L) + { + Luna::push(L, new Vector_BindLua(XMVectorSet((float)font.params.spacingX, (float)font.params.spacingY, 0, 0))); + return 1; + } + int SpriteFont_BindLua::GetAlign(lua_State* L) + { + wi::lua::SSetInt(L, font.params.h_align); + wi::lua::SSetInt(L, font.params.v_align); + return 2; + } + int SpriteFont_BindLua::GetColor(lua_State* L) + { + XMFLOAT4 C = font.params.color.toFloat4(); + Luna::push(L, new Vector_BindLua(XMLoadFloat4(&C))); + return 1; + } + int SpriteFont_BindLua::GetShadowColor(lua_State* L) + { + XMFLOAT4 C = font.params.color.toFloat4(); + Luna::push(L, new Vector_BindLua(XMLoadFloat4(&C))); + return 1; + } + + void SpriteFont_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); + + + wi::lua::RunText("WIFALIGN_LEFT = 0"); + wi::lua::RunText("WIFALIGN_CENTER = 1"); + wi::lua::RunText("WIFALIGN_RIGHT = 2"); + wi::lua::RunText("WIFALIGN_TOP = 3"); + wi::lua::RunText("WIFALIGN_BOTTOM = 4"); } } - else - wiLua::SError(L, "SetShadowColor(Vector value) not enough arguments!"); - return 0; -} -int wiSpriteFont_BindLua::GetText(lua_State* L) -{ - wiLua::SSetString(L, font.GetTextA()); - return 1; -} -int wiSpriteFont_BindLua::GetSize(lua_State* L) -{ - wiLua::SSetInt(L, font.params.size); - return 1; -} -int wiSpriteFont_BindLua::GetPos(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMVectorSet((float)font.params.posX, (float)font.params.posY, 0, 0))); - return 1; -} -int wiSpriteFont_BindLua::GetSpacing(lua_State* L) -{ - Luna::push(L, new Vector_BindLua(XMVectorSet((float)font.params.spacingX, (float)font.params.spacingY, 0, 0))); - return 1; -} -int wiSpriteFont_BindLua::GetAlign(lua_State* L) -{ - wiLua::SSetInt(L, font.params.h_align); - wiLua::SSetInt(L, font.params.v_align); - return 2; -} -int wiSpriteFont_BindLua::GetColor(lua_State* L) -{ - XMFLOAT4 C = font.params.color.toFloat4(); - Luna::push(L, new Vector_BindLua(XMLoadFloat4(&C))); - return 1; -} -int wiSpriteFont_BindLua::GetShadowColor(lua_State* L) -{ - XMFLOAT4 C = font.params.color.toFloat4(); - Luna::push(L, new Vector_BindLua(XMLoadFloat4(&C))); - return 1; -} - -void wiSpriteFont_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - - - wiLua::RunText("WIFALIGN_LEFT = 0"); - wiLua::RunText("WIFALIGN_CENTER = 1"); - wiLua::RunText("WIFALIGN_RIGHT = 2"); - wiLua::RunText("WIFALIGN_TOP = 3"); - wiLua::RunText("WIFALIGN_BOTTOM = 4"); - } } diff --git a/WickedEngine/wiSpriteFont_BindLua.h b/WickedEngine/wiSpriteFont_BindLua.h index cdf520f99..e26b29f57 100644 --- a/WickedEngine/wiSpriteFont_BindLua.h +++ b/WickedEngine/wiSpriteFont_BindLua.h @@ -3,35 +3,37 @@ #include "wiLuna.h" #include "wiSpriteFont.h" -class wiSpriteFont_BindLua +namespace wi::lua { -public: - wiSpriteFont font; + class SpriteFont_BindLua + { + public: + wi::SpriteFont font; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiSpriteFont_BindLua(const wiSpriteFont& font); - wiSpriteFont_BindLua(lua_State* L); + SpriteFont_BindLua(const wi::SpriteFont& font); + SpriteFont_BindLua(lua_State* L); - int SetStyle(lua_State* L); - int SetText(lua_State* L); - int SetSize(lua_State* L); - int SetPos(lua_State* L); - int SetSpacing(lua_State* L); - int SetAlign(lua_State* L); - int SetColor(lua_State* L); - int SetShadowColor(lua_State* L); + int SetStyle(lua_State* L); + int SetText(lua_State* L); + int SetSize(lua_State* L); + int SetPos(lua_State* L); + int SetSpacing(lua_State* L); + int SetAlign(lua_State* L); + int SetColor(lua_State* L); + int SetShadowColor(lua_State* L); - int GetText(lua_State* L); - int GetSize(lua_State* L); - int GetPos(lua_State* L); - int GetSpacing(lua_State* L); - int GetAlign(lua_State* L); - int GetColor(lua_State* L); - int GetShadowColor(lua_State* L); - - static void Bind(); -}; + int GetText(lua_State* L); + int GetSize(lua_State* L); + int GetPos(lua_State* L); + int GetSpacing(lua_State* L); + int GetAlign(lua_State* L); + int GetColor(lua_State* L); + int GetShadowColor(lua_State* L); + static void Bind(); + }; +} diff --git a/WickedEngine/wiSprite_BindLua.cpp b/WickedEngine/wiSprite_BindLua.cpp index 2cec73adb..9aad8b4ec 100644 --- a/WickedEngine/wiSprite_BindLua.cpp +++ b/WickedEngine/wiSprite_BindLua.cpp @@ -1,94 +1,98 @@ #include "wiSprite_BindLua.h" #include "wiImageParams_BindLua.h" -#include "SpriteAnim_BindLua.h" +#include "wiSpriteAnim_BindLua.h" -const char wiSprite_BindLua::className[] = "Sprite"; - -Luna::FunctionType wiSprite_BindLua::methods[] = { - lunamethod(wiSprite_BindLua, SetParams), - lunamethod(wiSprite_BindLua, GetParams), - lunamethod(wiSprite_BindLua, SetAnim), - lunamethod(wiSprite_BindLua, GetAnim), - - { NULL, NULL } -}; -Luna::PropertyType wiSprite_BindLua::properties[] = { - { NULL, NULL } -}; - -wiSprite_BindLua::wiSprite_BindLua(const wiSprite& sprite) :sprite(sprite) +namespace wi::lua { -} -wiSprite_BindLua::wiSprite_BindLua(lua_State *L) -{ - std::string name = "", mask = ""; - int argc = wiLua::SGetArgCount(L); - if (argc > 0) + const char Sprite_BindLua::className[] = "Sprite"; + + Luna::FunctionType Sprite_BindLua::methods[] = { + lunamethod(Sprite_BindLua, SetParams), + lunamethod(Sprite_BindLua, GetParams), + lunamethod(Sprite_BindLua, SetAnim), + lunamethod(Sprite_BindLua, GetAnim), + + { NULL, NULL } + }; + Luna::PropertyType Sprite_BindLua::properties[] = { + { NULL, NULL } + }; + + Sprite_BindLua::Sprite_BindLua(const wi::Sprite& sprite) :sprite(sprite) { - name = wiLua::SGetString(L, 1); - name = wiLua::GetScriptPath() + name; - if (argc > 1) + } + + Sprite_BindLua::Sprite_BindLua(lua_State* L) + { + std::string name = "", mask = ""; + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) { - mask = wiLua::SGetString(L, 2); - mask = wiLua::GetScriptPath() + mask; + name = wi::lua::SGetString(L, 1); + name = wi::lua::GetScriptPath() + name; + if (argc > 1) + { + mask = wi::lua::SGetString(L, 2); + mask = wi::lua::GetScriptPath() + mask; + } + } + sprite = wi::Sprite(name, mask); + } + + int Sprite_BindLua::SetParams(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + wi::lua::ImageParams_BindLua* params = Luna::check(L, 1); + if (params != nullptr) + { + sprite.params = params->params; + } + } + else + { + wi::lua::SError(L, "SetParams(ImageEffects effects) not enough arguments!"); + } + return 0; + } + int Sprite_BindLua::GetParams(lua_State* L) + { + Luna::push(L, new wi::lua::ImageParams_BindLua(sprite.params)); + return 1; + } + int Sprite_BindLua::SetAnim(lua_State* L) + { + int argc = wi::lua::SGetArgCount(L); + if (argc > 0) + { + SpriteAnim_BindLua* anim = Luna::check(L, 1); + if (anim != nullptr) + { + sprite.anim = anim->anim; + } + } + else + { + wi::lua::SError(L, "SetAnim(SpriteAnim anim) not enough arguments!"); + } + return 0; + } + int Sprite_BindLua::GetAnim(lua_State* L) + { + Luna::push(L, new SpriteAnim_BindLua(sprite.anim)); + return 1; + } + + void Sprite_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + initialized = true; + Luna::Register(wi::lua::GetLuaState()); } } - sprite = wiSprite(name, mask); -} -int wiSprite_BindLua::SetParams(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - wiImageParams_BindLua* params = Luna::check(L, 1); - if (params != nullptr) - { - sprite.params = params->params; - } - } - else - { - wiLua::SError(L, "SetParams(ImageEffects effects) not enough arguments!"); - } - return 0; } -int wiSprite_BindLua::GetParams(lua_State *L) -{ - Luna::push(L, new wiImageParams_BindLua(sprite.params)); - return 1; -} -int wiSprite_BindLua::SetAnim(lua_State *L) -{ - int argc = wiLua::SGetArgCount(L); - if (argc > 0) - { - SpriteAnim_BindLua* anim = Luna::check(L, 1); - if (anim != nullptr) - { - sprite.anim = anim->anim; - } - } - else - { - wiLua::SError(L, "SetAnim(SpriteAnim anim) not enough arguments!"); - } - return 0; -} -int wiSprite_BindLua::GetAnim(lua_State *L) -{ - Luna::push(L, new SpriteAnim_BindLua(sprite.anim)); - return 1; -} - -void wiSprite_BindLua::Bind() -{ - static bool initialized = false; - if (!initialized) - { - initialized = true; - Luna::Register(wiLua::GetLuaState()); - } -} - diff --git a/WickedEngine/wiSprite_BindLua.h b/WickedEngine/wiSprite_BindLua.h index 54140048b..2ae39e8d6 100644 --- a/WickedEngine/wiSprite_BindLua.h +++ b/WickedEngine/wiSprite_BindLua.h @@ -3,23 +3,25 @@ #include "wiLuna.h" #include "wiSprite.h" -class wiSprite_BindLua +namespace wi::lua { -public: - wiSprite sprite; + class Sprite_BindLua + { + public: + wi::Sprite sprite; - static const char className[]; - static Luna::FunctionType methods[]; - static Luna::PropertyType properties[]; + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; - wiSprite_BindLua(const wiSprite& sprite); - wiSprite_BindLua(lua_State *L); + Sprite_BindLua(const wi::Sprite& sprite); + Sprite_BindLua(lua_State* L); - int SetParams(lua_State *L); - int GetParams(lua_State *L); - int SetAnim(lua_State *L); - int GetAnim(lua_State *L); - - static void Bind(); -}; + int SetParams(lua_State* L); + int GetParams(lua_State* L); + int SetAnim(lua_State* L); + int GetAnim(lua_State* L); + static void Bind(); + }; +} diff --git a/WickedEngine/wiTextureHelper.cpp b/WickedEngine/wiTextureHelper.cpp index b6474024f..645509763 100644 --- a/WickedEngine/wiTextureHelper.cpp +++ b/WickedEngine/wiTextureHelper.cpp @@ -1,17 +1,17 @@ #include "wiTextureHelper.h" #include "wiRandom.h" #include "wiColor.h" -#include "wiBackLog.h" +#include "wiBacklog.h" #include "wiSpinLock.h" #include "wiTimer.h" #include "wiUnorderedMap.h" -using namespace wiGraphics; +using namespace wi::graphics; // from Utility/samplerBlueNoiseErrorDistribution_128x128_OptimizedFor_2d2d2d2d_1spp.cpp extern float samplerBlueNoiseErrorDistribution_128x128_OptimizedFor_2d2d2d2d_1spp(int pixel_i, int pixel_j, int sampleIndex, int sampleDimension); -namespace wiTextureHelper +namespace wi::texturehelper { enum HELPERTEXTURES @@ -24,25 +24,25 @@ namespace wiTextureHelper HELPERTEXTURE_BLUENOISE, HELPERTEXTURE_COUNT }; - wiGraphics::Texture helperTextures[HELPERTEXTURE_COUNT]; - wi::unordered_map colorTextures; - wiSpinLock colorlock; + wi::graphics::Texture helperTextures[HELPERTEXTURE_COUNT]; + wi::unordered_map colorTextures; + wi::SpinLock colorlock; void Initialize() { - wiTimer timer; + wi::Timer timer; - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); // Random64x64 { uint8_t data[64 * 64 * 4]; for (int i = 0; i < arraysize(data); i += 4) { - data[i] = wiRandom::getRandom(0, 255); - data[i + 1] = wiRandom::getRandom(0, 255); - data[i + 2] = wiRandom::getRandom(0, 255); - data[i + 3] = wiRandom::getRandom(0, 255); + data[i] = wi::random::GetRandom(0, 255); + data[i + 1] = wi::random::GetRandom(0, 255); + data[i + 2] = wi::random::GetRandom(0, 255); + data[i + 3] = wi::random::GetRandom(0, 255); } CreateTexture(helperTextures[HELPERTEXTURE_RANDOM64X64], data, 64, 64); @@ -152,7 +152,7 @@ namespace wiTextureHelper device->SetName(&helperTextures[HELPERTEXTURE_BLUENOISE], "HELPERTEXTURE_BLUENOISE"); } - wiBackLog::post("wiTextureHelper Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); + wi::backlog::post("wi::texturehelper Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } const Texture* getRandom64x64() @@ -167,7 +167,7 @@ namespace wiTextureHelper const Texture* getNormalMapDefault() { - return getColor(wiColor(127, 127, 255, 255)); + return getColor(wi::Color(127, 127, 255, 255)); } const Texture* getBlackCubeMap() @@ -187,20 +187,20 @@ namespace wiTextureHelper const Texture* getWhite() { - return getColor(wiColor(255, 255, 255, 255)); + return getColor(wi::Color(255, 255, 255, 255)); } const Texture* getBlack() { - return getColor(wiColor(0, 0, 0, 255)); + return getColor(wi::Color(0, 0, 0, 255)); } const Texture* getTransparent() { - return getColor(wiColor(0, 0, 0, 0)); + return getColor(wi::Color(0, 0, 0, 0)); } - const Texture* getColor(wiColor color) + const Texture* getColor(wi::Color color) { colorlock.lock(); auto it = colorTextures.find(color.rgba); @@ -212,7 +212,7 @@ namespace wiTextureHelper return &it->second; } - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); static const int dim = 1; static const int dataLength = dim * dim * 4; @@ -240,13 +240,13 @@ namespace wiTextureHelper } - bool CreateTexture(wiGraphics::Texture& texture, const uint8_t* data, uint32_t width, uint32_t height, Format format) + bool CreateTexture(wi::graphics::Texture& texture, const uint8_t* data, uint32_t width, uint32_t height, Format format) { if (data == nullptr) { return false; } - GraphicsDevice* device = wiGraphics::GetDevice(); + GraphicsDevice* device = wi::graphics::GetDevice(); TextureDesc textureDesc; textureDesc.width = width; diff --git a/WickedEngine/wiTextureHelper.h b/WickedEngine/wiTextureHelper.h index e5f0c2fe1..f361829a0 100644 --- a/WickedEngine/wiTextureHelper.h +++ b/WickedEngine/wiTextureHelper.h @@ -3,22 +3,22 @@ #include "wiGraphicsDevice.h" #include "wiColor.h" -namespace wiTextureHelper +namespace wi::texturehelper { void Initialize(); - const wiGraphics::Texture* getRandom64x64(); - const wiGraphics::Texture* getColorGradeDefault(); - const wiGraphics::Texture* getNormalMapDefault(); - const wiGraphics::Texture* getBlackCubeMap(); - const wiGraphics::Texture* getUINT4(); - const wiGraphics::Texture* getBlueNoise(); + const wi::graphics::Texture* getRandom64x64(); + const wi::graphics::Texture* getColorGradeDefault(); + const wi::graphics::Texture* getNormalMapDefault(); + const wi::graphics::Texture* getBlackCubeMap(); + const wi::graphics::Texture* getUINT4(); + const wi::graphics::Texture* getBlueNoise(); - const wiGraphics::Texture* getWhite(); - const wiGraphics::Texture* getBlack(); - const wiGraphics::Texture* getTransparent(); - const wiGraphics::Texture* getColor(wiColor color); + const wi::graphics::Texture* getWhite(); + const wi::graphics::Texture* getBlack(); + const wi::graphics::Texture* getTransparent(); + const wi::graphics::Texture* getColor(wi::Color color); - bool CreateTexture(wiGraphics::Texture& texture, const uint8_t* data, uint32_t width, uint32_t height, wiGraphics::Format format = wiGraphics::Format::R8G8B8A8_UNORM); + bool CreateTexture(wi::graphics::Texture& texture, const uint8_t* data, uint32_t width, uint32_t height, wi::graphics::Format format = wi::graphics::Format::R8G8B8A8_UNORM); }; diff --git a/WickedEngine/wiTexture_BindLua.cpp b/WickedEngine/wiTexture_BindLua.cpp new file mode 100644 index 000000000..1dd10a158 --- /dev/null +++ b/WickedEngine/wiTexture_BindLua.cpp @@ -0,0 +1,34 @@ +#include "wiTexture_BindLua.h" + +using namespace wi::graphics; + +namespace wi::lua +{ + + const char Texture_BindLua::className[] = "Texture"; + + Luna::FunctionType Texture_BindLua::methods[] = { + { NULL, NULL } + }; + Luna::PropertyType Texture_BindLua::properties[] = { + { NULL, NULL } + }; + + Texture_BindLua::Texture_BindLua(Texture texture) :texture(texture) + { + } + Texture_BindLua::Texture_BindLua(lua_State* L) + { + } + + void Texture_BindLua::Bind() + { + static bool initialized = false; + if (!initialized) + { + Luna::Register(wi::lua::GetLuaState()); + initialized = true; + } + } + +} diff --git a/WickedEngine/wiTexture_BindLua.h b/WickedEngine/wiTexture_BindLua.h new file mode 100644 index 000000000..7e65c1fcd --- /dev/null +++ b/WickedEngine/wiTexture_BindLua.h @@ -0,0 +1,25 @@ +#pragma once +#include "wiLua.h" +#include "wiLuna.h" +#include "wiGraphics.h" + +namespace wi::lua +{ + + class Texture_BindLua + { + public: + wi::graphics::Texture texture; + + static const char className[]; + static Luna::FunctionType methods[]; + static Luna::PropertyType properties[]; + + Texture_BindLua() = default; + Texture_BindLua(wi::graphics::Texture texture); + Texture_BindLua(lua_State* L); + + static void Bind(); + }; + +} diff --git a/WickedEngine/wiTimer.h b/WickedEngine/wiTimer.h index d1cb4a838..e27373a1e 100644 --- a/WickedEngine/wiTimer.h +++ b/WickedEngine/wiTimer.h @@ -3,33 +3,36 @@ #include -struct wiTimer +namespace wi { - std::chrono::high_resolution_clock::time_point timestamp = std::chrono::high_resolution_clock::now(); - - // Record a reference timestamp - inline void record() + struct Timer { - timestamp = std::chrono::high_resolution_clock::now(); - } + std::chrono::high_resolution_clock::time_point timestamp = std::chrono::high_resolution_clock::now(); - // Elapsed time in seconds since the wiTimer creation or last call to record() - inline double elapsed_seconds() - { - auto timestamp2 = std::chrono::high_resolution_clock::now(); - std::chrono::duration time_span = std::chrono::duration_cast>(timestamp2 - timestamp); - return time_span.count(); - } + // Record a reference timestamp + inline void record() + { + timestamp = std::chrono::high_resolution_clock::now(); + } - // Elapsed time in milliseconds since the wiTimer creation or last call to record() - inline double elapsed_milliseconds() - { - return elapsed_seconds() * 1000.0; - } + // Elapsed time in seconds since the wi::Timer creation or last call to record() + inline double elapsed_seconds() + { + auto timestamp2 = std::chrono::high_resolution_clock::now(); + std::chrono::duration time_span = std::chrono::duration_cast>(timestamp2 - timestamp); + return time_span.count(); + } - // Elapsed time in milliseconds since the wiTimer creation or last call to record() - inline double elapsed() - { - return elapsed_milliseconds(); - } -}; + // Elapsed time in milliseconds since the wi::Timer creation or last call to record() + inline double elapsed_milliseconds() + { + return elapsed_seconds() * 1000.0; + } + + // Elapsed time in milliseconds since the wi::Timer creation or last call to record() + inline double elapsed() + { + return elapsed_milliseconds(); + } + }; +} diff --git a/WickedEngine/wiVersion.cpp b/WickedEngine/wiVersion.cpp index 2e762968b..0c6cf59ed 100644 --- a/WickedEngine/wiVersion.cpp +++ b/WickedEngine/wiVersion.cpp @@ -2,14 +2,14 @@ #include -namespace wiVersion +namespace wi::version { // main engine core const int major = 0; // minor features, major updates, breaking compatibility changes - const int minor = 59; + const int minor = 60; // minor bug fixes, alterations, refactors, updates - const int revision = 11; + const int revision = 0; const std::string version_string = std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(revision); diff --git a/WickedEngine/wiVersion.h b/WickedEngine/wiVersion.h index 6c07033f4..09077c401 100644 --- a/WickedEngine/wiVersion.h +++ b/WickedEngine/wiVersion.h @@ -1,8 +1,7 @@ #ifndef WICKEDENGINE_VERSION_DEFINED #define WICKEDENGINE_VERSION_DEFINED -#include "CommonInclude.h" -namespace wiVersion +namespace wi::version { long GetVersion(); // major features diff --git a/WickedEngine/wiWidget.cpp b/WickedEngine/wiWidget.cpp deleted file mode 100644 index dab5f1442..000000000 --- a/WickedEngine/wiWidget.cpp +++ /dev/null @@ -1,3035 +0,0 @@ -#include "wiWidget.h" -#include "wiImage.h" -#include "wiTextureHelper.h" -#include "wiHelper.h" -#include "wiInput.h" -#include "wiRenderer.h" -#include "shaders/ShaderInterop_Renderer.h" -#include "wiEvent.h" -#include "wiBackLog.h" -#include "wiTimer.h" - -#include -#include - -using namespace wiGraphics; -using namespace wiScene; - -static wiGraphics::PipelineState PSO_colored; - -wiWidget::wiWidget() -{ - sprites[IDLE].params.color = wiColor::Booger(); - sprites[FOCUS].params.color = wiColor::Gray(); - sprites[ACTIVE].params.color = wiColor::White(); - sprites[DEACTIVATING].params.color = wiColor::Gray(); - font.params.shadowColor = wiColor::Black(); - - for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].params.blendFlag = BLENDMODE_OPAQUE; - sprites[i].params.enableBackground(); - } -} - -void wiWidget::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - if (force_disable) - { - state = IDLE; - } - - hitBox = Hitbox2D(XMFLOAT2(translation.x, translation.y), XMFLOAT2(scale.x, scale.y)); - - if (!force_disable && GetState() != WIDGETSTATE::ACTIVE && !tooltip.empty() && GetPointerHitbox().intersects(hitBox)) - { - tooltipTimer++; - } - else - { - tooltipTimer = 0; - } - - UpdateTransform(); - - if (parent != nullptr) - { - this->UpdateTransform_Parented(*parent); - } - - XMVECTOR S, R, T; - XMMatrixDecompose(&S, &R, &T, XMLoadFloat4x4(&world)); - XMStoreFloat3(&translation, T); - XMStoreFloat3(&scale, S); - - scissorRect.bottom = (int32_t)(translation.y + scale.y); - scissorRect.left = (int32_t)(translation.x); - scissorRect.right = (int32_t)(translation.x + scale.x); - scissorRect.top = (int32_t)(translation.y); - - // default sprite and font placement: - for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].params.pos.x = translation.x; - sprites[i].params.pos.y = translation.y; - sprites[i].params.siz.x = scale.x; - sprites[i].params.siz.y = scale.y; - sprites[i].params.fade = enabled ? 0.0f : 0.5f; - } - font.params.posX = translation.x; - font.params.posY = translation.y; -} -void wiWidget::RenderTooltip(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - if (tooltipTimer > 25) - { - float screenwidth = canvas.GetLogicalWidth(); - float screenheight = canvas.GetLogicalHeight(); - - wiFontParams fontProps = wiFontParams(0, 0, WIFONTSIZE_DEFAULT, WIFALIGN_LEFT, WIFALIGN_TOP); - fontProps.color = wiColor(25, 25, 25, 255); - wiSpriteFont tooltipFont = wiSpriteFont(tooltip, fontProps); - if (!scriptTip.empty()) - { - tooltipFont.SetText(tooltip + "\n" + scriptTip); - } - - static const float _border = 2; - float textWidth = tooltipFont.textWidth() + _border * 2; - float textHeight = tooltipFont.textHeight() + _border * 2; - - XMFLOAT2 pointer = GetPointerHitbox().pos; - tooltipFont.params.posX = pointer.x; - tooltipFont.params.posY = pointer.y; - - if (tooltipFont.params.posX + textWidth > screenwidth) - { - tooltipFont.params.posX -= tooltipFont.params.posX + textWidth - screenwidth; - } - if (tooltipFont.params.posX < 0) - { - tooltipFont.params.posX = 0; - } - - if (tooltipFont.params.posY > screenheight * 0.8f) - { - tooltipFont.params.posY -= 30; - } - else - { - tooltipFont.params.posY += 40; - } - - wiImage::Draw(wiTextureHelper::getWhite(), - wiImageParams(tooltipFont.params.posX - _border, tooltipFont.params.posY - _border, - textWidth, textHeight, wiColor(255, 234, 165)), cmd); - tooltipFont.SetText(tooltip); - tooltipFont.Draw(cmd); - if (!scriptTip.empty()) - { - tooltipFont.SetText(scriptTip); - tooltipFont.params.posY += (int)(textHeight / 2); - tooltipFont.params.color = wiColor(25, 25, 25, 110); - tooltipFont.Draw(cmd); - } - } -} -const std::string& wiWidget::GetName() const -{ - return name; -} -void wiWidget::SetName(const std::string& value) -{ - if (value.length() <= 0) - { - static std::atomic widgetID{ 0 }; - name = "widget_" + std::to_string(widgetID.fetch_add(1)); - } - else - { - name = value; - } -} -const std::string wiWidget::GetText() const -{ - return font.GetTextA(); -} -void wiWidget::SetText(const std::string& value) -{ - font.SetText(value); -} -void wiWidget::SetText(std::string&& value) -{ - font.SetText(value); -} -void wiWidget::SetTooltip(const std::string& value) -{ - tooltip = value; -} -void wiWidget::SetTooltip(std::string&& value) -{ - tooltip = value; -} -void wiWidget::SetScriptTip(const std::string& value) -{ - scriptTip = value; -} -void wiWidget::SetScriptTip(std::string&& value) -{ - scriptTip = value; -} -void wiWidget::SetPos(const XMFLOAT2& value) -{ - SetDirty(); - translation_local.x = value.x; - translation_local.y = value.y; - UpdateTransform(); - - translation = translation_local; -} -void wiWidget::SetSize(const XMFLOAT2& value) -{ - SetDirty(); - scale_local.x = value.x; - scale_local.y = value.y; - UpdateTransform(); - - scale = scale_local; -} -wiWidget::WIDGETSTATE wiWidget::GetState() const -{ - return state; -} -void wiWidget::SetEnabled(bool val) -{ - if (enabled != val) - { - priority_change = val; - enabled = val; - } -} -bool wiWidget::IsEnabled() const -{ - return enabled && visible && !force_disable; -} -void wiWidget::SetVisible(bool val) -{ - if (visible != val) - { - priority_change |= val; - visible = val; - } -} -bool wiWidget::IsVisible() const -{ - return visible; -} -void wiWidget::Activate() -{ - priority_change = true; - state = ACTIVE; - tooltipTimer = 0; -} -void wiWidget::Deactivate() -{ - state = DEACTIVATING; - tooltipTimer = 0; -} -void wiWidget::SetColor(wiColor color, WIDGETSTATE state) -{ - if (state == WIDGETSTATE_COUNT) - { - for (int i = 0; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].params.color = color; - } - } - else - { - sprites[state].params.color = color; - } -} -wiColor wiWidget::GetColor() const -{ - return wiColor::fromFloat4(sprites[GetState()].params.color); -} -void wiWidget::SetImage(std::shared_ptr textureResource, WIDGETSTATE state) -{ - if (state == WIDGETSTATE_COUNT) - { - for (int i = 0; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].textureResource = textureResource; - } - } - else - { - sprites[state].textureResource = textureResource; - } -} - -void wiWidget::AttachTo(wiWidget* parent) -{ - this->parent = parent; - - if (parent != nullptr) - { - parent->UpdateTransform(); - XMMATRIX B = XMMatrixInverse(nullptr, XMLoadFloat4x4(&parent->world)); - MatrixTransform(B); - } - - UpdateTransform(); - - if (parent != nullptr) - { - UpdateTransform_Parented(*parent); - } -} -void wiWidget::Detach() -{ - if (parent != nullptr) - { - parent = nullptr; - ApplyTransform(); - } -} -void wiWidget::ApplyScissor(const wiCanvas& canvas, const Rect rect, CommandList cmd, bool constrain_to_parent) const -{ - Rect scissor = rect; - - if (constrain_to_parent && parent != nullptr) - { - wiWidget* recurse_parent = parent; - while (recurse_parent != nullptr) - { - scissor.bottom = std::min(scissor.bottom, recurse_parent->scissorRect.bottom); - scissor.top = std::max(scissor.top, recurse_parent->scissorRect.top); - scissor.left = std::max(scissor.left, recurse_parent->scissorRect.left); - scissor.right = std::min(scissor.right, recurse_parent->scissorRect.right); - - recurse_parent = recurse_parent->parent; - } - } - - if (scissor.left > scissor.right) - { - scissor.left = scissor.right; - } - if (scissor.top > scissor.bottom) - { - scissor.top = scissor.bottom; - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - float scale = canvas.GetDPIScaling(); - scissor.bottom = int32_t((float)scissor.bottom * scale); - scissor.top = int32_t((float)scissor.top * scale); - scissor.left = int32_t((float)scissor.left * scale); - scissor.right = int32_t((float)scissor.right * scale); - device->BindScissorRects(1, &scissor, cmd); -} -Hitbox2D wiWidget::GetPointerHitbox() const -{ - XMFLOAT4 pointer = wiInput::GetPointer(); - return Hitbox2D(XMFLOAT2(pointer.x, pointer.y), XMFLOAT2(1, 1)); -} - -namespace wiWidget_Internal -{ - void LoadShaders() - { - PipelineStateDesc desc; - desc.vs = wiRenderer::GetShader(VSTYPE_VERTEXCOLOR); - desc.ps = wiRenderer::GetShader(PSTYPE_VERTEXCOLOR); - desc.il = wiRenderer::GetInputLayout(ILTYPE_VERTEXCOLOR); - desc.dss = wiRenderer::GetDepthStencilState(DSSTYPE_DEPTHDISABLED); - desc.bs = wiRenderer::GetBlendState(BSTYPE_TRANSPARENT); - desc.rs = wiRenderer::GetRasterizerState(RSTYPE_DOUBLESIDED); - desc.pt = PrimitiveTopology::TRIANGLESTRIP; - wiGraphics::GetDevice()->CreatePipelineState(&desc, &PSO_colored); - } -} - -void wiWidget::Initialize() -{ - wiTimer timer; - - static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiWidget_Internal::LoadShaders(); }); - wiWidget_Internal::LoadShaders(); - - wiBackLog::post("wiWidget Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); -} - - -void wiButton::Create(const std::string& name) -{ - SetName(name); - SetText(name); - OnClick([](wiEventArgs args) {}); - OnDragStart([](wiEventArgs args) {}); - OnDrag([](wiEventArgs args) {}); - OnDragEnd([](wiEventArgs args) {}); - SetSize(XMFLOAT2(100, 30)); - - font.params.h_align = WIFALIGN_CENTER; - font.params.v_align = WIFALIGN_CENTER; -} -void wiButton::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - if (IsEnabled()) - { - hitBox.pos.x = translation.x; - hitBox.pos.y = translation.y; - hitBox.siz.x = scale.x; - hitBox.siz.y = scale.y; - - Hitbox2D pointerHitbox = GetPointerHitbox(); - - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - wiEventArgs args; - args.clickPos = pointerHitbox.pos; - onDragEnd(args); - - if (pointerHitbox.intersects(hitBox)) - { - // Click occurs when the button is released within the bounds - onClick(args); - } - - state = IDLE; - } - if (state == ACTIVE) - { - Deactivate(); - } - - bool clicked = false; - // hover the button - if (pointerHitbox.intersects(hitBox)) - { - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == FOCUS) - { - // activate - clicked = true; - } - } - - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == DEACTIVATING) - { - // Keep pressed until mouse is released - Activate(); - - wiEventArgs args; - args.clickPos = pointerHitbox.pos; - XMFLOAT3 posDelta; - posDelta.x = pointerHitbox.pos.x - prevPos.x; - posDelta.y = pointerHitbox.pos.y - prevPos.y; - posDelta.z = 0; - args.deltaPos = XMFLOAT2(posDelta.x, posDelta.y); - onDrag(args); - } - } - - if (clicked) - { - wiEventArgs args; - args.clickPos = pointerHitbox.pos; - dragStart = args.clickPos; - args.startPos = dragStart; - onDragStart(args); - Activate(); - } - - prevPos.x = pointerHitbox.pos.x; - prevPos.y = pointerHitbox.pos.y; - } - - switch (font.params.h_align) - { - case WIFALIGN_LEFT: - font.params.posX = translation.x + 2; - break; - case WIFALIGN_RIGHT: - font.params.posX = translation.x + scale.x - 2; - break; - case WIFALIGN_CENTER: - default: - font.params.posX = translation.x + scale.x * 0.5f; - break; - } - switch (font.params.v_align) - { - case WIFALIGN_TOP: - font.params.posY = translation.y + 2; - break; - case WIFALIGN_BOTTOM: - font.params.posY = translation.y + scale.y - 2; - break; - case WIFALIGN_CENTER: - default: - font.params.posY = translation.y + scale.y * 0.5f; - break; - } -} -void wiButton::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - wiColor color = GetColor(); - - ApplyScissor(canvas, scissorRect, cmd); - - sprites[state].Draw(cmd); - font.Draw(cmd); -} -void wiButton::OnClick(std::function func) -{ - onClick = move(func); -} -void wiButton::OnDragStart(std::function func) -{ - onDragStart = move(func); -} -void wiButton::OnDrag(std::function func) -{ - onDrag = move(func); -} -void wiButton::OnDragEnd(std::function func) -{ - onDragEnd = move(func); -} - - - - -void wiLabel::Create(const std::string& name) -{ - SetName(name); - SetText(name); - SetSize(XMFLOAT2(100, 20)); -} -void wiLabel::Update(const wiCanvas& canvas, float dt) -{ - wiWidget::Update(canvas, dt); - - font.params.h_wrap = scale.x; - - switch (font.params.h_align) - { - case WIFALIGN_LEFT: - font.params.posX = translation.x + 2; - break; - case WIFALIGN_RIGHT: - font.params.posX = translation.x + scale.x - 2; - break; - case WIFALIGN_CENTER: - default: - font.params.posX = translation.x + scale.x * 0.5f; - break; - } - switch (font.params.v_align) - { - case WIFALIGN_TOP: - font.params.posY = translation.y + 2; - break; - case WIFALIGN_BOTTOM: - font.params.posY = translation.y + scale.y - 2; - break; - case WIFALIGN_CENTER: - default: - font.params.posY = translation.y + scale.y * 0.5f; - break; - } -} -void wiLabel::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - wiColor color = GetColor(); - - ApplyScissor(canvas, scissorRect, cmd); - - sprites[state].Draw(cmd); - font.Draw(cmd); -} - - - - -wiSpriteFont wiTextInputField::font_input; -void wiTextInputField::Create(const std::string& name) -{ - SetName(name); - SetText(name); - OnInputAccepted([](wiEventArgs args) {}); - SetSize(XMFLOAT2(100, 30)); - - font.params.v_align = WIFALIGN_CENTER; - - font_description.params = font.params; - font_description.params.h_align = WIFALIGN_RIGHT; -} -void wiTextInputField::SetValue(const std::string& newValue) -{ - font.SetText(newValue); -} -void wiTextInputField::SetValue(int newValue) -{ - std::stringstream ss(""); - ss << newValue; - font.SetText(ss.str()); -} -void wiTextInputField::SetValue(float newValue) -{ - std::stringstream ss(""); - ss << newValue; - font.SetText(ss.str()); -} -const std::string wiTextInputField::GetValue() -{ - return font.GetTextA(); -} -void wiTextInputField::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - if (IsEnabled()) - { - hitBox.pos.x = translation.x; - hitBox.pos.y = translation.y; - hitBox.siz.x = scale.x; - hitBox.siz.y = scale.y; - - Hitbox2D pointerHitbox = GetPointerHitbox(); - bool intersectsPointer = pointerHitbox.intersects(hitBox); - - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - - bool clicked = false; - // hover the button - if (intersectsPointer) - { - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == FOCUS) - { - // activate - clicked = true; - } - } - - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == DEACTIVATING) - { - // Keep pressed until mouse is released - Activate(); - } - } - - if (clicked) - { - Activate(); - - font_input.SetText(font.GetText()); - } - - if (state == ACTIVE) - { - if (wiInput::Press(wiInput::KEYBOARD_BUTTON_ENTER)) - { - // accept input... - - font.SetText(font_input.GetText()); - font_input.text.clear(); - - wiEventArgs args; - args.sValue = font.GetTextA(); - args.iValue = atoi(args.sValue.c_str()); - args.fValue = (float)atof(args.sValue.c_str()); - onInputAccepted(args); - - Deactivate(); - } - else if ((wiInput::Press(wiInput::MOUSE_BUTTON_LEFT) && !intersectsPointer) || - wiInput::Press(wiInput::KEYBOARD_BUTTON_ESCAPE)) - { - // cancel input - font_input.text.clear(); - Deactivate(); - } - - } - } - - font.params.posX = translation.x + 2; - font.params.posY = translation.y + scale.y * 0.5f; - font_description.params.posX = translation.x - 2; - font_description.params.posY = translation.y + scale.y * 0.5f; - - if (state == ACTIVE) - { - font_input.params = font.params; - } -} -void wiTextInputField::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - wiColor color = GetColor(); - - font_description.Draw(cmd); - - ApplyScissor(canvas, scissorRect, cmd); - - sprites[state].Draw(cmd); - - if (state == ACTIVE) - { - font_input.Draw(cmd); - } - else - { - font.Draw(cmd); - } - -} -void wiTextInputField::OnInputAccepted(std::function func) -{ - onInputAccepted = move(func); -} -void wiTextInputField::AddInput(const char inputChar) -{ - std::string value_new = font_input.GetTextA(); - value_new.push_back(inputChar); - font_input.SetText(value_new); -} -void wiTextInputField::DeleteFromInput() -{ - std::string value_new = font_input.GetTextA(); - if (!value_new.empty()) - { - value_new.pop_back(); - } - font_input.SetText(value_new); -} - - - - - -void wiSlider::Create(float start, float end, float defaultValue, float step, const std::string& name) -{ - this->start = start; - this->end = end; - this->value = defaultValue; - this->step = std::max(step, 1.0f); - - SetName(name); - SetText(name); - OnSlide([](wiEventArgs args) {}); - SetSize(XMFLOAT2(200, 40)); - - valueInputField.Create(name + "_endInputField"); - valueInputField.SetTooltip("Enter number to modify value even outside slider limits. Enter \"reset\" to reset slider to initial state."); - valueInputField.SetValue(end); - valueInputField.OnInputAccepted([this, start, end, defaultValue](wiEventArgs args) { - if (args.sValue.compare("reset") != std::string::npos) - { - this->value = defaultValue; - this->start = start; - this->end = end; - args.fValue = this->value; - args.iValue = (int)this->value; - } - else - { - this->value = args.fValue; - this->start = std::min(this->start, args.fValue); - this->end = std::max(this->end, args.fValue); - } - onSlide(args); - }); - - for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) - { - sprites_knob[i].params = sprites[i].params; - } - - sprites[IDLE].params.color = wiColor(60, 60, 60, 200); - sprites[FOCUS].params.color = wiColor(50, 50, 50, 200); - sprites[ACTIVE].params.color = wiColor(50, 50, 50, 200); - sprites[DEACTIVATING].params.color = wiColor(60, 60, 60, 200); - - font.params.h_align = WIFALIGN_RIGHT; - font.params.v_align = WIFALIGN_CENTER; -} -void wiSlider::SetValue(float value) -{ - this->value = value; -} -float wiSlider::GetValue() const -{ - return value; -} -void wiSlider::SetRange(float start, float end) -{ - this->start = start; - this->end = end; - this->value = wiMath::Clamp(this->value, start, end); -} -void wiSlider::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - valueInputField.Detach(); - valueInputField.SetSize(XMFLOAT2(std::max(scale.y * 2, wiFont::textWidth(valueInputField.GetText(), valueInputField.font.params) + 4), scale.y)); - valueInputField.SetPos(XMFLOAT2(translation.x + scale.x + 2, translation.y)); - valueInputField.AttachTo(this); - - scissorRect.bottom = (int32_t)(translation.y + scale.y); - scissorRect.left = (int32_t)(translation.x); - scissorRect.right = (int32_t)(translation.x + scale.x + 20 + scale.y * 2); // include the valueInputField - scissorRect.top = (int32_t)(translation.y); - - for (int i = 0; i < WIDGETSTATE_COUNT; ++i) - { - sprites_knob[i].params.siz.x = 16.0f; - valueInputField.SetColor(wiColor::fromFloat4(this->sprites_knob[i].params.color), (WIDGETSTATE)i); - } - valueInputField.font.params.color = this->font.params.color; - valueInputField.font.params.shadowColor = this->font.params.shadowColor; - valueInputField.SetEnabled(enabled); - valueInputField.force_disable = force_disable; - valueInputField.Update(canvas, dt); - - if (IsEnabled()) - { - bool dragged = false; - - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - if (state == ACTIVE) - { - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == ACTIVE) - { - // continue drag if already grabbed wheter it is intersecting or not - dragged = true; - } - } - else - { - Deactivate(); - } - } - - const float knobWidth = sprites_knob[state].params.siz.x; - hitBox.pos.x = translation.x - knobWidth * 0.5f; - hitBox.pos.y = translation.y; - hitBox.siz.x = scale.x + knobWidth; - hitBox.siz.y = scale.y; - - Hitbox2D pointerHitbox = GetPointerHitbox(); - - - if (pointerHitbox.intersects(hitBox)) - { - // hover the slider - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == FOCUS) - { - // activate - dragged = true; - } - } - - - if (dragged) - { - wiEventArgs args; - args.clickPos = pointerHitbox.pos; - value = wiMath::InverseLerp(translation.x, translation.x + scale.x, args.clickPos.x); - value = wiMath::Clamp(value, 0, 1); - value *= step; - value = std::floor(value); - value /= step; - value = wiMath::Lerp(start, end, value); - args.fValue = value; - args.iValue = (int)value; - onSlide(args); - Activate(); - } - - valueInputField.SetValue(value); - } - - font.params.posY = translation.y + scale.y * 0.5f; - - const float knobWidth = sprites_knob[state].params.siz.x; - const float knobWidthHalf = knobWidth * 0.5f; - sprites_knob[state].params.pos.x = wiMath::Lerp(translation.x + knobWidthHalf + 2, translation.x + scale.x - knobWidthHalf - 2, wiMath::Clamp(wiMath::InverseLerp(start, end, value), 0, 1)); - sprites_knob[state].params.pos.y = translation.y + 2; - sprites_knob[state].params.siz.y = scale.y - 4; - sprites_knob[state].params.pivot = XMFLOAT2(0.5f, 0); - sprites_knob[state].params.fade = sprites[state].params.fade; -} -void wiSlider::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - font.Draw(cmd); - - ApplyScissor(canvas, scissorRect, cmd); - - // base - sprites[state].Draw(cmd); - - // knob - sprites_knob[state].Draw(cmd); - - valueInputField.Render(canvas, cmd); -} -void wiSlider::RenderTooltip(const wiCanvas& canvas, wiGraphics::CommandList cmd) const -{ - wiWidget::RenderTooltip(canvas, cmd); - valueInputField.RenderTooltip(canvas, cmd); -} -void wiSlider::OnSlide(std::function func) -{ - onSlide = move(func); -} - - - - - -void wiCheckBox::Create(const std::string& name) -{ - SetName(name); - SetText(name); - OnClick([](wiEventArgs args) {}); - SetSize(XMFLOAT2(20, 20)); - - font.params.h_align = WIFALIGN_RIGHT; - font.params.v_align = WIFALIGN_CENTER; - - for (int i = IDLE; i < WIDGETSTATE_COUNT; ++i) - { - sprites_check[i].params = sprites[i].params; - sprites_check[i].params.color = wiMath::Lerp(sprites[i].params.color, wiColor::White().toFloat4(), 0.8f); - } -} -void wiCheckBox::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - if (IsEnabled()) - { - - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - if (state == ACTIVE) - { - Deactivate(); - } - - hitBox.pos.x = translation.x; - hitBox.pos.y = translation.y; - hitBox.siz.x = scale.x; - hitBox.siz.y = scale.y; - - Hitbox2D pointerHitbox = GetPointerHitbox(); - - // hover the button - if (pointerHitbox.intersects(hitBox)) - { - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == FOCUS) - { - Activate(); - } - } - - if (state == DEACTIVATING) - { - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - // Keep pressed until mouse is released - Activate(); - } - else - { - // Deactivation event - SetCheck(!GetCheck()); - wiEventArgs args; - args.clickPos = pointerHitbox.pos; - args.bValue = GetCheck(); - onClick(args); - } - } - } - - font.params.posY = translation.y + scale.y * 0.5f; - - sprites_check[state].params.pos.x = translation.x + scale.x * 0.25f; - sprites_check[state].params.pos.y = translation.y + scale.y * 0.25f; - sprites_check[state].params.siz = XMFLOAT2(scale.x * 0.5f, scale.y * 0.5f); -} -void wiCheckBox::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - font.Draw(cmd); - - ApplyScissor(canvas, scissorRect, cmd); - - // control - sprites[state].Draw(cmd); - - // check - if (GetCheck()) - { - sprites_check[state].Draw(cmd); - } - -} -void wiCheckBox::OnClick(std::function func) -{ - onClick = move(func); -} -void wiCheckBox::SetCheck(bool value) -{ - checked = value; -} -bool wiCheckBox::GetCheck() const -{ - return checked; -} - - - - - -void wiComboBox::Create(const std::string& name) -{ - SetName(name); - SetText(name); - OnSelect([](wiEventArgs args) {}); - SetSize(XMFLOAT2(100, 20)); - - font.params.h_align = WIFALIGN_RIGHT; - font.params.v_align = WIFALIGN_CENTER; -} -float wiComboBox::GetItemOffset(int index) const -{ - index = std::max(firstItemVisible, index) - firstItemVisible; - return scale.y * (index + 1) + 1; -} -bool wiComboBox::HasScrollbar() const -{ - return maxVisibleItemCount < (int)items.size(); -} -void wiComboBox::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - if (IsEnabled()) - { - - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - if (state == ACTIVE && combostate == COMBOSTATE_SELECTING) - { - hovered = -1; - Deactivate(); - } - if (state == IDLE) - { - combostate = COMBOSTATE_INACTIVE; - } - - hitBox.pos.x = translation.x; - hitBox.pos.y = translation.y; - hitBox.siz.x = scale.x + scale.y + 1; // + drop-down indicator arrow + little offset - hitBox.siz.y = scale.y; - - Hitbox2D pointerHitbox = GetPointerHitbox(); - - bool clicked = false; - // hover the button - if (pointerHitbox.intersects(hitBox)) - { - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - // activate - clicked = true; - } - - bool click_down = false; - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - click_down = true; - if (state == DEACTIVATING) - { - // Keep pressed until mouse is released - Activate(); - } - } - - - if (clicked && state == FOCUS) - { - Activate(); - } - - const float scrollbar_begin = translation.y + scale.y + 1 + scale.y * 0.5f; - const float scrollbar_end = scrollbar_begin + std::max(0.0f, (float)std::min(maxVisibleItemCount, (int)items.size()) - 1) * scale.y; - - if (state == ACTIVE) - { - if (HasScrollbar()) - { - if (combostate != COMBOSTATE_SELECTING && combostate != COMBOSTATE_INACTIVE) - { - if (combostate == COMBOSTATE_SCROLLBAR_GRABBED || pointerHitbox.intersects(Hitbox2D(XMFLOAT2(translation.x + scale.x + 1, translation.y + scale.y + 1), XMFLOAT2(scale.y, (float)std::min(maxVisibleItemCount, (int)items.size()) * scale.y)))) - { - if (click_down) - { - combostate = COMBOSTATE_SCROLLBAR_GRABBED; - scrollbar_delta = wiMath::Clamp(pointerHitbox.pos.y, scrollbar_begin, scrollbar_end) - scrollbar_begin; - const float scrollbar_value = wiMath::InverseLerp(scrollbar_begin, scrollbar_end, scrollbar_begin + scrollbar_delta); - firstItemVisible = int(float(std::max(0, (int)items.size() - maxVisibleItemCount)) * scrollbar_value + 0.5f); - firstItemVisible = std::max(0, std::min((int)items.size() - maxVisibleItemCount, firstItemVisible)); - } - else - { - combostate = COMBOSTATE_SCROLLBAR_HOVER; - } - } - else if (!click_down) - { - combostate = COMBOSTATE_HOVER; - } - } - } - - if (combostate == COMBOSTATE_INACTIVE) - { - combostate = COMBOSTATE_HOVER; - } - else if (combostate == COMBOSTATE_SELECTING) - { - Deactivate(); - combostate = COMBOSTATE_INACTIVE; - } - else if (combostate == COMBOSTATE_HOVER) - { - int scroll = (int)wiInput::GetPointer().z; - firstItemVisible -= scroll; - firstItemVisible = std::max(0, std::min((int)items.size() - maxVisibleItemCount, firstItemVisible)); - if (scroll) - { - const float scrollbar_value = wiMath::InverseLerp(0, float(std::max(0, (int)items.size() - maxVisibleItemCount)), float(firstItemVisible)); - scrollbar_delta = wiMath::Lerp(scrollbar_begin, scrollbar_end, scrollbar_value) - scrollbar_begin; - } - - hovered = -1; - for (int i = firstItemVisible; i < (firstItemVisible + std::min(maxVisibleItemCount, (int)items.size())); ++i) - { - Hitbox2D itembox; - itembox.pos.x = translation.x; - itembox.pos.y = translation.y + GetItemOffset(i); - itembox.siz.x = scale.x; - itembox.siz.y = scale.y; - if (pointerHitbox.intersects(itembox)) - { - hovered = i; - break; - } - } - - if (clicked) - { - combostate = COMBOSTATE_SELECTING; - if (hovered >= 0) - { - SetSelected(hovered); - } - } - } - } - } - - font.params.posY = translation.y + sprites[state].params.siz.y * 0.5f; -} -void wiComboBox::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - GraphicsDevice* device = wiGraphics::GetDevice(); - - wiColor color = GetColor(); - if (combostate != COMBOSTATE_INACTIVE) - { - color = wiColor::fromFloat4(sprites[FOCUS].params.color); - } - - font.Draw(cmd); - - struct Vertex - { - XMFLOAT4 pos; - XMFLOAT4 col; - }; - static GPUBuffer vb_triangle; - if (!vb_triangle.IsValid()) - { - Vertex vertices[3]; - vertices[0].col = XMFLOAT4(1, 1, 1, 1); - vertices[1].col = XMFLOAT4(1, 1, 1, 1); - vertices[2].col = XMFLOAT4(1, 1, 1, 1); - wiMath::ConstructTriangleEquilateral(1, vertices[0].pos, vertices[1].pos, vertices[2].pos); - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = sizeof(vertices); - device->CreateBuffer(&desc, &vertices, &vb_triangle); - } - const XMMATRIX Projection = canvas.GetProjection(); - - // control-arrow-background - wiImageParams fx = sprites[state].params; - fx.pos = XMFLOAT3(translation.x + scale.x + 1, translation.y, 0); - fx.siz = XMFLOAT2(scale.y, scale.y); - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); - - // control-arrow-triangle - { - device->BindPipelineState(&PSO_colored, cmd); - - MiscCB cb; - cb.g_xColor = sprites[ACTIVE].params.color; - XMStoreFloat4x4(&cb.g_xTransform, XMMatrixScaling(scale.y * 0.25f, scale.y * 0.25f, 1) * - XMMatrixRotationZ(XM_PIDIV2) * - XMMatrixTranslation(translation.x + scale.x + 1 + scale.y * 0.5f, translation.y + scale.y * 0.5f, 0) * - Projection - ); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_triangle, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - - device->Draw(3, 0, cmd); - } - - ApplyScissor(canvas, scissorRect, cmd); - - // control-base - sprites[state].Draw(cmd); - - if (selected >= 0) - { - wiFont::Draw(items[selected].name, wiFontParams(translation.x + scale.x * 0.5f, translation.y + scale.y * 0.5f, WIFONTSIZE_DEFAULT, WIFALIGN_CENTER, WIFALIGN_CENTER, - font.params.color, font.params.shadowColor), cmd); - } - - // drop-down - if (state == ACTIVE) - { - if (HasScrollbar()) - { - Rect rect; - rect.left = int(translation.x + scale.x + 1); - rect.right = int(translation.x + scale.x + 1 + scale.y); - rect.top = int(translation.y + scale.y + 1); - rect.bottom = int(translation.y + scale.y + 1 + scale.y * maxVisibleItemCount); - ApplyScissor(canvas, rect, cmd, false); - - // control-scrollbar-base - { - fx = sprites[state].params; - fx.pos = XMFLOAT3(translation.x + scale.x + 1, translation.y + scale.y + 1, 0); - fx.siz = XMFLOAT2(scale.y, scale.y * maxVisibleItemCount); - fx.color = wiMath::Lerp(wiColor::Transparent(), sprites[IDLE].params.color, 0.5f); - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); - } - - // control-scrollbar-grab - { - wiColor col = wiColor::fromFloat4(sprites[IDLE].params.color); - if (combostate == COMBOSTATE_SCROLLBAR_HOVER) - { - col = wiColor::fromFloat4(sprites[FOCUS].params.color); - } - else if (combostate == COMBOSTATE_SCROLLBAR_GRABBED) - { - col = wiColor::fromFloat4(sprites[ACTIVE].params.color); - } - wiImage::Draw(wiTextureHelper::getWhite() - , wiImageParams(translation.x + scale.x + 1, translation.y + scale.y + 1 + scrollbar_delta, scale.y, scale.y, col), cmd); - } - } - - Rect rect; - rect.left = int(translation.x); - rect.right = rect.left + int(scale.x); - rect.top = int(translation.y + scale.y + 1); - rect.bottom = rect.top + int(scale.y * maxVisibleItemCount); - ApplyScissor(canvas, rect, cmd, false); - - // control-list - for (int i = firstItemVisible; i < (firstItemVisible + std::min(maxVisibleItemCount, (int)items.size())); ++i) - { - fx = sprites[state].params; - fx.pos = XMFLOAT3(translation.x, translation.y + GetItemOffset(i), 0); - fx.siz = XMFLOAT2(scale.x, scale.y); - fx.color = wiMath::Lerp(wiColor::Transparent(), sprites[IDLE].params.color, 0.5f); - if (hovered == i) - { - if (combostate == COMBOSTATE_HOVER) - { - fx.color = sprites[FOCUS].params.color; - } - else if (combostate == COMBOSTATE_SELECTING) - { - fx.color = sprites[ACTIVE].params.color; - } - } - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); - wiFont::Draw(items[i].name, wiFontParams(translation.x + scale.x * 0.5f, translation.y + scale.y * 0.5f + GetItemOffset(i), WIFONTSIZE_DEFAULT, WIFALIGN_CENTER, WIFALIGN_CENTER, - font.params.color, font.params.shadowColor), cmd); - } - } -} -void wiComboBox::OnSelect(std::function func) -{ - onSelect = move(func); -} -void wiComboBox::AddItem(const std::string& name, uint64_t userdata) -{ - items.emplace_back(); - items.back().name = name; - items.back().userdata = userdata; - - if (selected < 0) - { - selected = 0; - } -} -void wiComboBox::RemoveItem(int index) -{ - wi::vector newItems(0); - newItems.reserve(items.size()); - for (size_t i = 0; i < items.size(); ++i) - { - if (i != index) - { - newItems.push_back(items[i]); - } - } - items = newItems; - - if (items.empty()) - { - selected = -1; - } - else if (selected > index) - { - selected--; - } -} -void wiComboBox::ClearItems() -{ - items.clear(); - - selected = -1; -} -void wiComboBox::SetMaxVisibleItemCount(int value) -{ - maxVisibleItemCount = value; -} -void wiComboBox::SetSelected(int index) -{ - selected = index; - - if (onSelect != nullptr) - { - wiEventArgs args; - args.iValue = selected; - args.sValue = GetItemText(selected); - args.userdata = GetItemUserData(selected); - onSelect(args); - } -} -void wiComboBox::SetSelectedByUserdata(uint64_t userdata) -{ - for (int i = 0; i < GetItemCount(); ++i) - { - if (userdata == GetItemUserData(i)) - { - SetSelected(i); - return; - } - } -} -std::string wiComboBox::GetItemText(int index) const -{ - if (index >= 0) - { - return items[index].name; - } - return ""; -} -uint64_t wiComboBox::GetItemUserData(int index) const -{ - if (index >= 0) - { - return items[index].userdata; - } - return 0; -} -int wiComboBox::GetSelected() const -{ - return selected; -} - - - - - - -static const float windowcontrolSize = 20.0f; -void wiWindow::Create(const std::string& name, bool window_controls) -{ - SetColor(wiColor::Ghost()); - - SetName(name); - SetText(name); - SetSize(XMFLOAT2(640, 480)); - - for (int i = IDLE + 1; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].params.color = sprites[IDLE].params.color; - } - - // Add controls - if (window_controls) - { - // Add a resizer control to the upperleft corner - resizeDragger_UpperLeft.Create(name + "_resize_dragger_upper_left"); - resizeDragger_UpperLeft.SetText(""); - resizeDragger_UpperLeft.OnDrag([this](wiEventArgs args) { - auto saved_parent = this->parent; - this->Detach(); - XMFLOAT2 scaleDiff; - scaleDiff.x = (scale.x - args.deltaPos.x) / scale.x; - scaleDiff.y = (scale.y - args.deltaPos.y) / scale.y; - this->Translate(XMFLOAT3(args.deltaPos.x, args.deltaPos.y, 0)); - this->Scale(XMFLOAT3(scaleDiff.x, scaleDiff.y, 1)); - this->scale_local = wiMath::Max(this->scale_local, XMFLOAT3(windowcontrolSize * 3, windowcontrolSize * 2, 1)); // don't allow resize to negative or too small - this->AttachTo(saved_parent); - }); - AddWidget(&resizeDragger_UpperLeft); - - // Add a resizer control to the bottom right corner - resizeDragger_BottomRight.Create(name + "_resize_dragger_bottom_right"); - resizeDragger_BottomRight.SetText(""); - resizeDragger_BottomRight.OnDrag([this](wiEventArgs args) { - auto saved_parent = this->parent; - this->Detach(); - XMFLOAT2 scaleDiff; - scaleDiff.x = (scale.x + args.deltaPos.x) / scale.x; - scaleDiff.y = (scale.y + args.deltaPos.y) / scale.y; - this->Scale(XMFLOAT3(scaleDiff.x, scaleDiff.y, 1)); - this->scale_local = wiMath::Max(this->scale_local, XMFLOAT3(windowcontrolSize * 3, windowcontrolSize * 2, 1)); // don't allow resize to negative or too small - this->AttachTo(saved_parent); - }); - AddWidget(&resizeDragger_BottomRight); - - // Add a grabber onto the title bar - moveDragger.Create(name + "_move_dragger"); - moveDragger.SetText(name); - moveDragger.font.params.h_align = WIFALIGN_LEFT; - moveDragger.OnDrag([this](wiEventArgs args) { - auto saved_parent = this->parent; - this->Detach(); - this->Translate(XMFLOAT3(args.deltaPos.x, args.deltaPos.y, 0)); - this->AttachTo(saved_parent); - }); - AddWidget(&moveDragger); - - // Add close button to the top right corner - closeButton.Create(name + "_close_button"); - closeButton.SetText("x"); - closeButton.OnClick([this](wiEventArgs args) { - this->SetVisible(false); - }); - closeButton.SetTooltip("Close window"); - AddWidget(&closeButton); - - // Add minimize button to the top right corner - minimizeButton.Create(name + "_minimize_button"); - minimizeButton.SetText("-"); - minimizeButton.OnClick([this](wiEventArgs args) { - this->SetMinimized(!this->IsMinimized()); - }); - minimizeButton.SetTooltip("Minimize window"); - AddWidget(&minimizeButton); - } - else - { - // Simple title bar - label.Create(name); - label.SetText(name); - label.font.params.h_align = WIFALIGN_LEFT; - AddWidget(&label); - } - - - SetEnabled(true); - SetVisible(true); - SetMinimized(false); -} -void wiWindow::AddWidget(wiWidget* widget) -{ - widget->SetEnabled(this->IsEnabled()); - widget->SetVisible(this->IsVisible()); - widget->AttachTo(this); - - widgets.push_back(widget); -} -void wiWindow::RemoveWidget(wiWidget* widget) -{ - for (auto& x : widgets) - { - if (x == widget) - { - x = widgets.back(); - widgets.pop_back(); - break; - } - } -} -void wiWindow::RemoveWidgets() -{ - widgets.clear(); -} -void wiWindow::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - moveDragger.force_disable = force_disable; - resizeDragger_UpperLeft.force_disable = force_disable; - resizeDragger_BottomRight.force_disable = force_disable; - - moveDragger.Update(canvas, dt); - resizeDragger_UpperLeft.Update(canvas, dt); - resizeDragger_BottomRight.Update(canvas, dt); - - // Don't allow moving outside of screen: - if(parent == nullptr) - { - translation_local.x = wiMath::Clamp(translation_local.x, 0, canvas.GetLogicalWidth() - scale_local.x); - translation_local.y = wiMath::Clamp(translation_local.y, 0, canvas.GetLogicalHeight() - windowcontrolSize); - SetDirty(); - } - - wiWidget::Update(canvas, dt); - - if (moveDragger.parent != nullptr) - { - moveDragger.Detach(); - moveDragger.SetSize(XMFLOAT2(scale.x - windowcontrolSize * 3, windowcontrolSize)); - moveDragger.SetPos(XMFLOAT2(translation.x + windowcontrolSize, translation.y)); - moveDragger.AttachTo(this); - } - if (closeButton.parent != nullptr) - { - closeButton.Detach(); - closeButton.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); - closeButton.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize, translation.y)); - closeButton.AttachTo(this); - } - if (minimizeButton.parent != nullptr) - { - minimizeButton.Detach(); - minimizeButton.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); - minimizeButton.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize * 2, translation.y)); - minimizeButton.AttachTo(this); - } - if (resizeDragger_UpperLeft.parent != nullptr) - { - resizeDragger_UpperLeft.Detach(); - resizeDragger_UpperLeft.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); - resizeDragger_UpperLeft.SetPos(XMFLOAT2(translation.x, translation.y)); - resizeDragger_UpperLeft.AttachTo(this); - } - if (resizeDragger_BottomRight.parent != nullptr) - { - resizeDragger_BottomRight.Detach(); - resizeDragger_BottomRight.SetSize(XMFLOAT2(windowcontrolSize, windowcontrolSize)); - resizeDragger_BottomRight.SetPos(XMFLOAT2(translation.x + scale.x - windowcontrolSize, translation.y + scale.y - windowcontrolSize)); - resizeDragger_BottomRight.AttachTo(this); - } - if (label.parent != nullptr) - { - label.Detach(); - label.SetSize(XMFLOAT2(scale.x, windowcontrolSize)); - label.SetPos(XMFLOAT2(translation.x, translation.y)); - label.AttachTo(this); - } - - Hitbox2D pointerHitbox = GetPointerHitbox(); - - uint32_t priority = 0; - - bool focus = false; - for (auto& widget : widgets) - { - widget->force_disable = force_disable || focus; - widget->Update(canvas, dt); - widget->force_disable = false; - - if (widget->priority_change) - { - widget->priority_change = false; - widget->priority = priority++; - } - else - { - widget->priority = ~0u; - } - - if (widget->IsVisible() && widget->hitBox.intersects(pointerHitbox)) - { - focus = true; - } - if (widget->GetState() > wiWidget::IDLE) - { - focus = true; - } - } - - if(priority > 0) //Sort only if there are priority changes - //Use std::stable_sort instead of std::sort to preserve UI element order with equal priorities - std::stable_sort(widgets.begin(), widgets.end(), [](const wiWidget* a, const wiWidget* b) { - return a->priority < b->priority; - }); - - if (IsMinimized()) - { - hitBox.siz.y = windowcontrolSize; - } - - if (IsEnabled() && !IsMinimized()) - { - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - if (state == ACTIVE) - { - Deactivate(); - } - - - bool clicked = false; - if (pointerHitbox.intersects(hitBox)) - { - if (state == IDLE) - { - state = FOCUS; - } - } - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == FOCUS) - { - // activate - clicked = true; - } - } - - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - if (state == DEACTIVATING) - { - // Keep pressed until mouse is released - Activate(); - } - } - - if (clicked) - { - Activate(); - } - } - else - { - state = IDLE; - } -} -void wiWindow::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - - wiColor color = GetColor(); - - // body - wiImageParams fx(translation.x - 2, translation.y - 2, scale.x + 4, scale.y + 4, wiColor(0, 0, 0, 100)); - if (IsMinimized()) - { - fx.siz.y = windowcontrolSize + 4; - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); // shadow - } - else - { - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); // shadow - sprites[state].Draw(cmd); - } - - for (auto it = widgets.rbegin(); it != widgets.rend(); ++it) - { - const wiWidget* widget = (*it); - ApplyScissor(canvas, scissorRect, cmd); - widget->Render(canvas, cmd); - } - -} -void wiWindow::RenderTooltip(const wiCanvas& canvas, wiGraphics::CommandList cmd) const -{ - wiWidget::RenderTooltip(canvas, cmd); - for (auto& x : widgets) - { - x->RenderTooltip(canvas, cmd); - } -} -void wiWindow::SetVisible(bool value) -{ - wiWidget::SetVisible(value); - SetMinimized(!value); - for (auto& x : widgets) - { - x->SetVisible(value); - } -} -void wiWindow::SetEnabled(bool value) -{ - wiWidget::SetEnabled(value); - for (auto& x : widgets) - { - if (x == &moveDragger) - continue; - if (x == &minimizeButton) - continue; - if (x == &closeButton) - continue; - if (x == &resizeDragger_UpperLeft) - continue; - if (x == &resizeDragger_BottomRight) - continue; - x->SetEnabled(value); - } -} -void wiWindow::SetMinimized(bool value) -{ - minimized = value; - - if (resizeDragger_BottomRight.parent != nullptr) - { - resizeDragger_BottomRight.SetVisible(!value); - } - for (auto& x : widgets) - { - if (x == &moveDragger) - continue; - if (x == &minimizeButton) - continue; - if (x == &closeButton) - continue; - if (x == &resizeDragger_UpperLeft) - continue; - x->SetVisible(!value); - } -} -bool wiWindow::IsMinimized() const -{ - return minimized; -} - - - - -struct rgb { - float r; // a fraction between 0 and 1 - float g; // a fraction between 0 and 1 - float b; // a fraction between 0 and 1 -}; -struct hsv { - float h; // angle in degrees - float s; // a fraction between 0 and 1 - float v; // a fraction between 0 and 1 -}; -hsv rgb2hsv(rgb in) -{ - hsv out; - float min, max, delta; - - min = in.r < in.g ? in.r : in.g; - min = min < in.b ? min : in.b; - - max = in.r > in.g ? in.r : in.g; - max = max > in.b ? max : in.b; - - out.v = max; // v - delta = max - min; - if (delta < 0.00001f) - { - out.s = 0; - out.h = 0; // undefined, maybe nan? - return out; - } - if (max > 0.0f) { // NOTE: if Max is == 0, this divide would cause a crash - out.s = (delta / max); // s - } - else { - // if max is 0, then r = g = b = 0 - // s = 0, h is undefined - out.s = 0.0f; - out.h = NAN; // its now undefined - return out; - } - if (in.r >= max) // > is bogus, just keeps compilor happy - out.h = (in.g - in.b) / delta; // between yellow & magenta - else - if (in.g >= max) - out.h = 2.0f + (in.b - in.r) / delta; // between cyan & yellow - else - out.h = 4.0f + (in.r - in.g) / delta; // between magenta & cyan - - out.h *= 60.0f; // degrees - - if (out.h < 0.0f) - out.h += 360.0f; - - return out; -} -rgb hsv2rgb(hsv in) -{ - float hh, p, q, t, ff; - long i; - rgb out; - - if (in.s <= 0.0f) { // < is bogus, just shuts up warnings - out.r = in.v; - out.g = in.v; - out.b = in.v; - return out; - } - hh = in.h; - if (hh >= 360.0f) hh = 0.0f; - hh /= 60.0f; - i = (long)hh; - ff = hh - i; - p = in.v * (1.0f - in.s); - q = in.v * (1.0f - (in.s * ff)); - t = in.v * (1.0f - (in.s * (1.0f - ff))); - - switch (i) { - case 0: - out.r = in.v; - out.g = t; - out.b = p; - break; - case 1: - out.r = q; - out.g = in.v; - out.b = p; - break; - case 2: - out.r = p; - out.g = in.v; - out.b = t; - break; - - case 3: - out.r = p; - out.g = q; - out.b = in.v; - break; - case 4: - out.r = t; - out.g = p; - out.b = in.v; - break; - case 5: - default: - out.r = in.v; - out.g = p; - out.b = q; - break; - } - return out; -} - -static const float cp_width = 300; -static const float cp_height = 260; -void wiColorPicker::Create(const std::string& name, bool window_controls) -{ - wiWindow::Create(name, window_controls); - - SetSize(XMFLOAT2(cp_width, cp_height)); - SetColor(wiColor(100, 100, 100, 100)); - - float x = 250; - float y = 110; - float step = 20; - - text_R.Create("R"); - text_R.SetPos(XMFLOAT2(x, y += step)); - text_R.SetSize(XMFLOAT2(40, 18)); - text_R.SetText(""); - text_R.SetTooltip("Enter value for RED channel (0-255)"); - text_R.SetDescription("R: "); - text_R.OnInputAccepted([this](wiEventArgs args) { - wiColor color = GetPickColor(); - color.setR((uint8_t)args.iValue); - SetPickColor(color); - FireEvents(); - }); - AddWidget(&text_R); - - text_G.Create("G"); - text_G.SetPos(XMFLOAT2(x, y += step)); - text_G.SetSize(XMFLOAT2(40, 18)); - text_G.SetText(""); - text_G.SetTooltip("Enter value for GREEN channel (0-255)"); - text_G.SetDescription("G: "); - text_G.OnInputAccepted([this](wiEventArgs args) { - wiColor color = GetPickColor(); - color.setG((uint8_t)args.iValue); - SetPickColor(color); - FireEvents(); - }); - AddWidget(&text_G); - - text_B.Create("B"); - text_B.SetPos(XMFLOAT2(x, y += step)); - text_B.SetSize(XMFLOAT2(40, 18)); - text_B.SetText(""); - text_B.SetTooltip("Enter value for BLUE channel (0-255)"); - text_B.SetDescription("B: "); - text_B.OnInputAccepted([this](wiEventArgs args) { - wiColor color = GetPickColor(); - color.setB((uint8_t)args.iValue); - SetPickColor(color); - FireEvents(); - }); - AddWidget(&text_B); - - - text_H.Create("H"); - text_H.SetPos(XMFLOAT2(x, y += step)); - text_H.SetSize(XMFLOAT2(40, 18)); - text_H.SetText(""); - text_H.SetTooltip("Enter value for HUE channel (0-360)"); - text_H.SetDescription("H: "); - text_H.OnInputAccepted([this](wiEventArgs args) { - hue = wiMath::Clamp(args.fValue, 0, 360.0f); - FireEvents(); - }); - AddWidget(&text_H); - - text_S.Create("S"); - text_S.SetPos(XMFLOAT2(x, y += step)); - text_S.SetSize(XMFLOAT2(40, 18)); - text_S.SetText(""); - text_S.SetTooltip("Enter value for SATURATION channel (0-100)"); - text_S.SetDescription("S: "); - text_S.OnInputAccepted([this](wiEventArgs args) { - saturation = wiMath::Clamp(args.fValue / 100.0f, 0, 1); - FireEvents(); - }); - AddWidget(&text_S); - - text_V.Create("V"); - text_V.SetPos(XMFLOAT2(x, y += step)); - text_V.SetSize(XMFLOAT2(40, 18)); - text_V.SetText(""); - text_V.SetTooltip("Enter value for LUMINANCE channel (0-100)"); - text_V.SetDescription("V: "); - text_V.OnInputAccepted([this](wiEventArgs args) { - luminance = wiMath::Clamp(args.fValue / 100.0f, 0, 1); - FireEvents(); - }); - AddWidget(&text_V); - - alphaSlider.Create(0, 255, 255, 255, ""); - alphaSlider.SetPos(XMFLOAT2(20, 230)); - alphaSlider.SetSize(XMFLOAT2(150, 18)); - alphaSlider.SetText("A: "); - alphaSlider.SetTooltip("Value for ALPHA - TRANSPARENCY channel (0-255)"); - alphaSlider.OnSlide([this](wiEventArgs args) { - FireEvents(); - }); - AddWidget(&alphaSlider); -} -static const float colorpicker_radius_triangle = 68; -static const float colorpicker_radius = 75; -static const float colorpicker_width = 22; -void wiColorPicker::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWindow::Update(canvas, dt); - - if (IsEnabled()) - { - - if (state == DEACTIVATING) - { - state = IDLE; - } - - float sca = std::min(scale.x / cp_width, scale.y / cp_height); - - XMMATRIX W = - XMMatrixScaling(sca, sca, 1) * - XMMatrixTranslation(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f, 0) - ; - - XMFLOAT2 center = XMFLOAT2(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f); - XMFLOAT2 pointer = GetPointerHitbox().pos; - float distance = wiMath::Distance(center, pointer); - bool hover_hue = (distance > colorpicker_radius * sca) && (distance < (colorpicker_radius + colorpicker_width)* sca); - - float distTri = 0; - XMFLOAT4 A, B, C; - wiMath::ConstructTriangleEquilateral(colorpicker_radius_triangle, A, B, C); - XMVECTOR _A = XMLoadFloat4(&A); - XMVECTOR _B = XMLoadFloat4(&B); - XMVECTOR _C = XMLoadFloat4(&C); - XMMATRIX _triTransform = XMMatrixRotationZ(-hue / 360.0f * XM_2PI) * W; - _A = XMVector4Transform(_A, _triTransform); - _B = XMVector4Transform(_B, _triTransform); - _C = XMVector4Transform(_C, _triTransform); - XMVECTOR O = XMVectorSet(pointer.x, pointer.y, 0, 0); - XMVECTOR D = XMVectorSet(0, 0, 1, 0); - bool hover_saturation = TriangleTests::Intersects(O, D, _A, _B, _C, distTri); - - bool dragged = false; - - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - if (hover_hue) - { - colorpickerstate = CPS_HUE; - dragged = true; - } - else if (hover_saturation) - { - colorpickerstate = CPS_SATURATION; - dragged = true; - } - } - - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - if (colorpickerstate > CPS_IDLE) - { - // continue drag if already grabbed whether it is intersecting or not - dragged = true; - } - } - else - { - colorpickerstate = CPS_IDLE; - } - - dragged = dragged; - if (colorpickerstate == CPS_HUE && dragged) - { - //hue pick - const float angle = wiMath::GetAngle(XMFLOAT2(pointer.x - center.x, pointer.y - center.y), XMFLOAT2(colorpicker_radius, 0)); - hue = angle / XM_2PI * 360.0f; - Activate(); - } - else if (colorpickerstate == CPS_SATURATION && dragged) - { - // saturation pick - float u, v, w; - wiMath::GetBarycentric(O, _A, _B, _C, u, v, w, true); - // u = saturated corner (color) - // v = desaturated corner (white) - // w = no luminosity corner (black) - - hsv source; - source.h = hue; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - - XMVECTOR color_corner = XMVectorSet(result.r, result.g, result.b, 1); - XMVECTOR white_corner = XMVectorSet(1, 1, 1, 1); - XMVECTOR black_corner = XMVectorSet(0, 0, 0, 1); - XMVECTOR inner_point = u * color_corner + v * white_corner + w * black_corner; - - result.r = XMVectorGetX(inner_point); - result.g = XMVectorGetY(inner_point); - result.b = XMVectorGetZ(inner_point); - source = rgb2hsv(result); - - saturation = source.s; - luminance = source.v; - - Activate(); - } - else if (state != IDLE) - { - Deactivate(); - } - - wiColor color = GetPickColor(); - text_R.SetValue((int)color.getR()); - text_G.SetValue((int)color.getG()); - text_B.SetValue((int)color.getB()); - text_H.SetValue(int(hue)); - text_S.SetValue(int(saturation * 100)); - text_V.SetValue(int(luminance * 100)); - - if (dragged) - { - FireEvents(); - } - } -} -void wiColorPicker::Render(const wiCanvas& canvas, CommandList cmd) const -{ - wiWindow::Render(canvas, cmd); - - if (!IsVisible() || IsMinimized()) - { - return; - } - - GraphicsDevice* device = wiGraphics::GetDevice(); - - struct Vertex - { - XMFLOAT4 pos; - XMFLOAT4 col; - }; - static wiGraphics::GPUBuffer vb_hue; - static wiGraphics::GPUBuffer vb_picker_saturation; - static wiGraphics::GPUBuffer vb_picker_hue; - static wiGraphics::GPUBuffer vb_preview; - - static wi::vector vertices_saturation; - - static bool buffersComplete = false; - if (!buffersComplete) - { - buffersComplete = true; - - // saturation - { - vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(1,0,0,1) }); // hue - vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(1,1,1,1) }); // white - vertices_saturation.push_back({ XMFLOAT4(0,0,0,0),XMFLOAT4(0,0,0,1) }); // black - wiMath::ConstructTriangleEquilateral(colorpicker_radius_triangle, vertices_saturation[0].pos, vertices_saturation[1].pos, vertices_saturation[2].pos); - - // create alpha blended edge: - vertices_saturation.push_back(vertices_saturation[0]); // outer - vertices_saturation.push_back(vertices_saturation[0]); // inner - vertices_saturation.push_back(vertices_saturation[1]); // outer - vertices_saturation.push_back(vertices_saturation[1]); // inner - vertices_saturation.push_back(vertices_saturation[2]); // outer - vertices_saturation.push_back(vertices_saturation[2]); // inner - vertices_saturation.push_back(vertices_saturation[0]); // outer - vertices_saturation.push_back(vertices_saturation[0]); // inner - wiMath::ConstructTriangleEquilateral(colorpicker_radius_triangle + 4, vertices_saturation[3].pos, vertices_saturation[5].pos, vertices_saturation[7].pos); // extrude outer - vertices_saturation[9].pos = vertices_saturation[3].pos; // last outer - } - // hue - { - const float edge = 2.0f; - wi::vector vertices; - uint32_t segment_count = 100; - // inner alpha blended edge - for (uint32_t i = 0; i <= segment_count; ++i) - { - float p = float(i) / segment_count; - float t = p * XM_2PI; - float x = cos(t); - float y = -sin(t); - hsv source; - source.h = p * 360.0f; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); - XMFLOAT4 coloralpha = XMFLOAT4(result.r, result.g, result.b, 0); - vertices.push_back({ XMFLOAT4((colorpicker_radius - edge) * x, (colorpicker_radius - edge) * y, 0, 1), coloralpha }); - vertices.push_back({ XMFLOAT4(colorpicker_radius * x, colorpicker_radius * y, 0, 1), color }); - } - // middle hue - for (uint32_t i = 0; i <= segment_count; ++i) - { - float p = float(i) / segment_count; - float t = p * XM_2PI; - float x = cos(t); - float y = -sin(t); - hsv source; - source.h = p * 360.0f; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); - vertices.push_back({ XMFLOAT4(colorpicker_radius * x, colorpicker_radius * y, 0, 1), color }); - vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width) * x, (colorpicker_radius + colorpicker_width) * y, 0, 1), color }); - } - // outer alpha blended edge - for (uint32_t i = 0; i <= segment_count; ++i) - { - float p = float(i) / segment_count; - float t = p * XM_2PI; - float x = cos(t); - float y = -sin(t); - hsv source; - source.h = p * 360.0f; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - XMFLOAT4 color = XMFLOAT4(result.r, result.g, result.b, 1); - XMFLOAT4 coloralpha = XMFLOAT4(result.r, result.g, result.b, 0); - vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width) * x, (colorpicker_radius + colorpicker_width) * y, 0, 1), color }); - vertices.push_back({ XMFLOAT4((colorpicker_radius + colorpicker_width + edge) * x, (colorpicker_radius + colorpicker_width + edge) * y, 0, 1), coloralpha }); - } - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = vertices.size() * sizeof(Vertex); - desc.stride = 0; - device->CreateBuffer(&desc, vertices.data(), &vb_hue); - } - // saturation picker (small circle) - { - float _radius = 3; - float _width = 3; - wi::vector vertices; - uint32_t segment_count = 100; - for (uint32_t i = 0; i <= segment_count; ++i) - { - float p = float(i) / 100; - float t = p * XM_2PI; - float x = cos(t); - float y = -sin(t); - vertices.push_back({ XMFLOAT4(_radius * x, _radius * y, 0, 1), XMFLOAT4(1,1,1,1) }); - vertices.push_back({ XMFLOAT4((_radius + _width) * x, (_radius + _width) * y, 0, 1), XMFLOAT4(1,1,1,1) }); - } - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = vertices.size() * sizeof(Vertex); - desc.stride = 0; - device->CreateBuffer(&desc, vertices.data(), &vb_picker_saturation); - } - // hue picker (rectangle) - { - float boldness = 4.0f; - float halfheight = 8.0f; - Vertex vertices[] = { - // left side: - { XMFLOAT4(colorpicker_radius - boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius - boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - - // bottom side: - { XMFLOAT4(colorpicker_radius - boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius - boldness, halfheight - boldness, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight - boldness, 0, 1),XMFLOAT4(1,1,1,1) }, - - // right side: - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width, halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - - // top side: - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius + colorpicker_width + boldness, -halfheight + boldness, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius - boldness, -halfheight, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(colorpicker_radius - boldness, -halfheight + boldness, 0, 1),XMFLOAT4(1,1,1,1) }, - }; - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = sizeof(vertices); - desc.stride = 0; - device->CreateBuffer(&desc, vertices, &vb_picker_hue); - } - // preview - { - float _width = 20; - Vertex vertices[] = { - { XMFLOAT4(-_width, -_width, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(_width, -_width, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(-_width, _width, 0, 1),XMFLOAT4(1,1,1,1) }, - { XMFLOAT4(_width, _width, 0, 1),XMFLOAT4(1,1,1,1) }, - }; - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = sizeof(vertices); - device->CreateBuffer(&desc, vertices, &vb_preview); - } - - } - - const wiColor final_color = GetPickColor(); - const float angle = hue / 360.0f * XM_2PI; - - const XMMATRIX Projection = canvas.GetProjection(); - - device->BindPipelineState(&PSO_colored, cmd); - - ApplyScissor(canvas, scissorRect, cmd); - - float sca = std::min(scale.x / cp_width, scale.y / cp_height); - - XMMATRIX W = - XMMatrixScaling(sca, sca, 1) * - XMMatrixTranslation(translation.x + scale.x * 0.4f, translation.y + scale.y * 0.5f, 0) - ; - - MiscCB cb; - - // render saturation triangle - { - hsv source; - source.h = hue; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - vertices_saturation[0].col = XMFLOAT4(result.r, result.g, result.b, 1); - - vertices_saturation[3].col = vertices_saturation[0].col; vertices_saturation[3].col.w = 0; - vertices_saturation[4].col = vertices_saturation[0].col; - vertices_saturation[5].col = vertices_saturation[1].col; vertices_saturation[5].col.w = 0; - vertices_saturation[6].col = vertices_saturation[1].col; - vertices_saturation[7].col = vertices_saturation[2].col; vertices_saturation[7].col.w = 0; - vertices_saturation[8].col = vertices_saturation[2].col; - vertices_saturation[9].col = vertices_saturation[0].col; vertices_saturation[9].col.w = 0; - vertices_saturation[10].col = vertices_saturation[0].col; - - size_t alloc_size = sizeof(Vertex) * vertices_saturation.size(); - GraphicsDevice::GPUAllocation vb_saturation = device->AllocateGPU(alloc_size, cmd); - memcpy(vb_saturation.data, vertices_saturation.data(), alloc_size); - - XMStoreFloat4x4(&cb.g_xTransform, - XMMatrixRotationZ(-angle) * - W * - Projection - ); - cb.g_xColor = IsEnabled() ? float4(1, 1, 1, 1) : float4(0.5f, 0.5f, 0.5f, 1); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_saturation.buffer, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - const uint64_t offsets[] = { - vb_saturation.offset, - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, offsets, cmd); - device->Draw((uint32_t)vertices_saturation.size(), 0, cmd); - } - - // render hue circle - { - XMStoreFloat4x4(&cb.g_xTransform, - W * - Projection - ); - cb.g_xColor = IsEnabled() ? float4(1, 1, 1, 1) : float4(0.5f, 0.5f, 0.5f, 1); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_hue, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - device->Draw((uint32_t)(vb_hue.GetDesc().size / sizeof(Vertex)), 0, cmd); - } - - // render hue picker - if (IsEnabled()) - { - XMStoreFloat4x4(&cb.g_xTransform, - XMMatrixRotationZ(-hue / 360.0f * XM_2PI) * - W * - Projection - ); - - hsv source; - source.h = hue; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - cb.g_xColor = float4(1 - result.r, 1 - result.g, 1 - result.b, 1); - - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_picker_hue, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - device->Draw((uint32_t)(vb_picker_hue.GetDesc().size / sizeof(Vertex)), 0, cmd); - } - - // render saturation picker - if (IsEnabled()) - { - XMFLOAT4 A, B, C; - wiMath::ConstructTriangleEquilateral(colorpicker_radius_triangle, A, B, C); - XMVECTOR _A = XMLoadFloat4(&A); - XMVECTOR _B = XMLoadFloat4(&B); - XMVECTOR _C = XMLoadFloat4(&C); - XMMATRIX _triTransform = XMMatrixRotationZ(-hue / 360.0f * XM_2PI); - _A = XMVector4Transform(_A, _triTransform); - _B = XMVector4Transform(_B, _triTransform); - _C = XMVector4Transform(_C, _triTransform); - - hsv source; - source.h = hue; - source.s = 1; - source.v = 1; - rgb result = hsv2rgb(source); - - XMVECTOR color_corner = XMVectorSet(result.r, result.g, result.b, 1); - XMVECTOR white_corner = XMVectorSet(1, 1, 1, 1); - XMVECTOR black_corner = XMVectorSet(0, 0, 0, 1); - - source.h = hue; - source.s = saturation; - source.v = luminance; - result = hsv2rgb(source); - XMVECTOR inner_point = XMVectorSet(result.r, result.g, result.b, 1); - - float u, v, w; - wiMath::GetBarycentric(inner_point, color_corner, white_corner, black_corner, u, v, w, true); - - XMVECTOR picker_center = u * _A + v * _B + w * _C; - - XMStoreFloat4x4(&cb.g_xTransform, - XMMatrixTranslationFromVector(picker_center) * - W * - Projection - ); - cb.g_xColor = float4(1 - final_color.toFloat3().x, 1 - final_color.toFloat3().y, 1 - final_color.toFloat3().z, 1); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_picker_saturation, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - device->Draw((uint32_t)(vb_picker_saturation.GetDesc().size / sizeof(Vertex)), 0, cmd); - } - - // render preview - { - XMStoreFloat4x4(&cb.g_xTransform, - XMMatrixScaling(sca, sca, 1) * - XMMatrixTranslation(translation.x + scale.x - 40 * sca, translation.y + 40, 0) * - Projection - ); - cb.g_xColor = final_color.toFloat4(); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_preview, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - device->Draw((uint32_t)(vb_preview.GetDesc().size / sizeof(Vertex)), 0, cmd); - } -} -wiColor wiColorPicker::GetPickColor() const -{ - hsv source; - source.h = hue; - source.s = saturation; - source.v = luminance; - rgb result = hsv2rgb(source); - return wiColor::fromFloat4(XMFLOAT4(result.r, result.g, result.b, alphaSlider.GetValue() / 255.0f)); -} -void wiColorPicker::SetPickColor(wiColor value) -{ - if (colorpickerstate != CPS_IDLE) - { - // Only allow setting the pick color when picking is not active, the RGB and HSV precision combat each other - return; - } - - rgb source; - source.r = value.toFloat3().x; - source.g = value.toFloat3().y; - source.b = value.toFloat3().z; - hsv result = rgb2hsv(source); - if (value.getR() != value.getG() || value.getG() != value.getB() || value.getR() != value.getB()) - { - hue = result.h; // only change the hue when not pure greyscale because those don't retain the saturation value - } - saturation = result.s; - luminance = result.v; - alphaSlider.SetValue((float)value.getA()); -} -void wiColorPicker::FireEvents() -{ - if (onColorChanged == nullptr) - return; - wiEventArgs args; - args.color = GetPickColor(); - onColorChanged(args); -} -void wiColorPicker::OnColorChanged(std::function func) -{ - onColorChanged = move(func); -} - - - - - - -inline float item_height() { return 20.0f; } -inline float tree_scrollbar_width() { return 12.0f; } -void wiTreeList::Create(const std::string& name) -{ - SetName(name); - SetText(name); - OnSelect([](wiEventArgs args) {}); - SetSize(XMFLOAT2(100, 20)); - - for (int i = FOCUS + 1; i < WIDGETSTATE_COUNT; ++i) - { - sprites[i].params.color = sprites[FOCUS].params.color; - } - font.params.v_align = WIFALIGN_CENTER; -} -float wiTreeList::GetItemOffset(int index) const -{ - return 2 + list_offset + index * item_height(); -} -Hitbox2D wiTreeList::GetHitbox_ListArea() const -{ - return Hitbox2D(XMFLOAT2(translation.x, translation.y + item_height() + 1), XMFLOAT2(scale.x - tree_scrollbar_width() - 1, scale.y - item_height() - 1)); -} -Hitbox2D wiTreeList::GetHitbox_Item(int visible_count, int level) const -{ - XMFLOAT2 pos = XMFLOAT2(translation.x + 2 + level * item_height(), translation.y + GetItemOffset(visible_count) + item_height() * 0.5f); - Hitbox2D hitbox; - hitbox.pos = XMFLOAT2(pos.x + item_height() * 0.5f + 2, pos.y - item_height() * 0.5f); - hitbox.siz = XMFLOAT2(scale.x - 2 - item_height() * 0.5f - 2 - level * item_height() - tree_scrollbar_width() - 2, item_height()); - return hitbox; -} -Hitbox2D wiTreeList::GetHitbox_ItemOpener(int visible_count, int level) const -{ - XMFLOAT2 pos = XMFLOAT2(translation.x + 2 + level * item_height(), translation.y + GetItemOffset(visible_count) + item_height() * 0.5f); - return Hitbox2D(XMFLOAT2(pos.x, pos.y - item_height() * 0.25f), XMFLOAT2(item_height() * 0.5f, item_height() * 0.5f)); -} -bool wiTreeList::HasScrollbar() const -{ - return scale.y < (int)items.size()* item_height(); -} -void wiTreeList::Update(const wiCanvas& canvas, float dt) -{ - if (!IsVisible()) - { - return; - } - - wiWidget::Update(canvas, dt); - - if (IsEnabled()) - { - if (state == FOCUS) - { - state = IDLE; - } - if (state == DEACTIVATING) - { - state = IDLE; - } - if (state == ACTIVE) - { - Deactivate(); - } - - Hitbox2D hitbox = Hitbox2D(XMFLOAT2(translation.x, translation.y), XMFLOAT2(scale.x, scale.y)); - Hitbox2D pointerHitbox = GetPointerHitbox(); - - if (state == IDLE && hitbox.intersects(pointerHitbox)) - { - state = FOCUS; - } - - bool clicked = false; - if (wiInput::Press(wiInput::MOUSE_BUTTON_LEFT)) - { - clicked = true; - } - - bool click_down = false; - if (wiInput::Down(wiInput::MOUSE_BUTTON_LEFT)) - { - click_down = true; - if (state == FOCUS || state == DEACTIVATING) - { - // Keep pressed until mouse is released - Activate(); - } - } - - // compute control-list height - list_height = 0; - { - int visible_count = 0; - int parent_level = 0; - bool parent_open = true; - for (const Item& item : items) - { - if (!parent_open && item.level > parent_level) - { - continue; - } - visible_count++; - parent_open = item.open; - parent_level = item.level; - list_height += item_height(); - } - } - - const float scrollbar_begin = translation.y + item_height(); - const float scrollbar_end = scrollbar_begin + scale.y - item_height(); - const float scrollbar_size = scrollbar_end - scrollbar_begin; - const float scrollbar_granularity = std::min(1.0f, scrollbar_size / list_height); - scrollbar_height = std::max(tree_scrollbar_width(), scrollbar_size * scrollbar_granularity); - - if (!click_down) - { - scrollbar_state = SCROLLBAR_INACTIVE; - } - - Hitbox2D scroll_box; - scroll_box.pos = XMFLOAT2(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1); - scroll_box.siz = XMFLOAT2(tree_scrollbar_width(), scale.y - item_height() - 1); - if (scroll_box.intersects(pointerHitbox)) - { - if (clicked) - { - scrollbar_state = SCROLLBAR_GRABBED; - } - else if (!click_down) - { - scrollbar_state = SCROLLBAR_HOVER; - state = FOCUS; - } - } - - if (scrollbar_state == SCROLLBAR_GRABBED) - { - Activate(); - scrollbar_delta = pointerHitbox.pos.y - scrollbar_height * 0.5f - scrollbar_begin; - } - - if (state == FOCUS) - { - scrollbar_delta -= wiInput::GetPointer().z * 10; - } - scrollbar_delta = wiMath::Clamp(scrollbar_delta, 0, scrollbar_size - scrollbar_height); - scrollbar_value = wiMath::InverseLerp(scrollbar_begin, scrollbar_end, scrollbar_begin + scrollbar_delta); - - list_offset = -scrollbar_value * list_height; - - Hitbox2D itemlist_box = GetHitbox_ListArea(); - - // control-list - item_highlight = -1; - opener_highlight = -1; - if (scrollbar_state == SCROLLBAR_INACTIVE) - { - int i = -1; - int visible_count = 0; - int parent_level = 0; - bool parent_open = true; - for (Item& item : items) - { - i++; - if (!parent_open && item.level > parent_level) - { - continue; - } - visible_count++; - parent_open = item.open; - parent_level = item.level; - - Hitbox2D open_box = GetHitbox_ItemOpener(visible_count, item.level); - if (!open_box.intersects(itemlist_box)) - { - continue; - } - - if (open_box.intersects(pointerHitbox)) - { - // Opened flag box: - opener_highlight = i; - if (clicked) - { - item.open = !item.open; - Activate(); - } - } - else - { - // Item name box: - Hitbox2D name_box = GetHitbox_Item(visible_count, item.level); - if (name_box.intersects(pointerHitbox)) - { - item_highlight = i; - if (clicked) - { - if (!wiInput::Down(wiInput::KEYBOARD_BUTTON_LCONTROL) && !wiInput::Down(wiInput::KEYBOARD_BUTTON_RCONTROL) - && !wiInput::Down(wiInput::KEYBOARD_BUTTON_LSHIFT) && !wiInput::Down(wiInput::KEYBOARD_BUTTON_RSHIFT)) - { - ClearSelection(); - } - Select(i); - Activate(); - } - } - } - } - } - } - - sprites[state].params.siz.y = item_height(); - font.params.posX = translation.x + 2; - font.params.posY = translation.y + sprites[state].params.siz.y * 0.5f; -} -void wiTreeList::Render(const wiCanvas& canvas, CommandList cmd) const -{ - if (!IsVisible()) - { - return; - } - GraphicsDevice* device = wiGraphics::GetDevice(); - - // control-base - sprites[state].Draw(cmd); - - ApplyScissor(canvas, scissorRect, cmd); - - font.Draw(cmd); - - // scrollbar background - wiImageParams fx = sprites[state].params; - fx.pos = XMFLOAT3(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1, 0); - fx.siz = XMFLOAT2(tree_scrollbar_width(), scale.y - item_height() - 1); - fx.color = sprites[IDLE].params.color; - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); - - // scrollbar - wiColor scrollbar_color = wiColor::fromFloat4(sprites[IDLE].params.color); - if (scrollbar_state == SCROLLBAR_HOVER) - { - scrollbar_color = wiColor::fromFloat4(sprites[FOCUS].params.color); - } - else if (scrollbar_state == SCROLLBAR_GRABBED) - { - scrollbar_color = wiColor::White(); - } - wiImage::Draw(wiTextureHelper::getWhite() - , wiImageParams(translation.x + scale.x - tree_scrollbar_width(), translation.y + item_height() + 1 + scrollbar_delta, tree_scrollbar_width(), scrollbar_height, scrollbar_color), cmd); - - // list background - Hitbox2D itemlist_box = GetHitbox_ListArea(); - fx.pos = XMFLOAT3(itemlist_box.pos.x, itemlist_box.pos.y, 0); - fx.siz = XMFLOAT2(itemlist_box.siz.x, itemlist_box.siz.y); - wiImage::Draw(wiTextureHelper::getWhite(), fx, cmd); - - Rect rect_without_scrollbar; - rect_without_scrollbar.left = (int)itemlist_box.pos.x; - rect_without_scrollbar.right = (int)(itemlist_box.pos.x + itemlist_box.siz.x); - rect_without_scrollbar.top = (int)itemlist_box.pos.y; - rect_without_scrollbar.bottom = (int)(itemlist_box.pos.y + itemlist_box.siz.y); - ApplyScissor(canvas, rect_without_scrollbar, cmd); - - struct Vertex - { - XMFLOAT4 pos; - XMFLOAT4 col; - }; - static GPUBuffer vb_triangle; - if (!vb_triangle.IsValid()) - { - Vertex vertices[3]; - vertices[0].col = XMFLOAT4(1, 1, 1, 1); - vertices[1].col = XMFLOAT4(1, 1, 1, 1); - vertices[2].col = XMFLOAT4(1, 1, 1, 1); - wiMath::ConstructTriangleEquilateral(1, vertices[0].pos, vertices[1].pos, vertices[2].pos); - - GPUBufferDesc desc; - desc.bind_flags = BindFlag::VERTEX_BUFFER; - desc.size = sizeof(vertices); - device->CreateBuffer(&desc, vertices, &vb_triangle); - } - const XMMATRIX Projection = canvas.GetProjection(); - - // control-list - int i = -1; - int visible_count = 0; - int parent_level = 0; - bool parent_open = true; - for (const Item& item : items) - { - i++; - if (!parent_open && item.level > parent_level) - { - continue; - } - visible_count++; - parent_open = item.open; - parent_level = item.level; - - Hitbox2D open_box = GetHitbox_ItemOpener(visible_count, item.level); - if (!open_box.intersects(itemlist_box)) - { - continue; - } - - Hitbox2D name_box = GetHitbox_Item(visible_count, item.level); - - // selected box: - if (item.selected || item_highlight == i) - { - wiImage::Draw(wiTextureHelper::getWhite() - , wiImageParams(name_box.pos.x, name_box.pos.y, name_box.siz.x, name_box.siz.y, - sprites[item.selected ? FOCUS : IDLE].params.color), cmd); - } - - // opened flag triangle: - { - device->BindPipelineState(&PSO_colored, cmd); - - MiscCB cb; - cb.g_xColor = opener_highlight == i ? wiColor::White().toFloat4() : sprites[FOCUS].params.color; - XMStoreFloat4x4(&cb.g_xTransform, XMMatrixScaling(item_height() * 0.3f, item_height() * 0.3f, 1) * - XMMatrixRotationZ(item.open ? XM_PIDIV2 : 0) * - XMMatrixTranslation(open_box.pos.x + open_box.siz.x * 0.5f, open_box.pos.y + open_box.siz.y * 0.25f, 0) * - Projection - ); - device->BindDynamicConstantBuffer(cb, CBSLOT_RENDERER_MISC, cmd); - const GPUBuffer* vbs[] = { - &vb_triangle, - }; - const uint32_t strides[] = { - sizeof(Vertex), - }; - device->BindVertexBuffers(vbs, 0, arraysize(vbs), strides, nullptr, cmd); - - device->Draw(3, 0, cmd); - } - - // Item name text: - wiFont::Draw(item.name, wiFontParams(name_box.pos.x + 1, name_box.pos.y + name_box.siz.y * 0.5f, WIFONTSIZE_DEFAULT, WIFALIGN_LEFT, WIFALIGN_CENTER, - font.params.color, font.params.shadowColor), cmd); - } -} -void wiTreeList::OnSelect(std::function func) -{ - onSelect = move(func); -} -void wiTreeList::AddItem(const Item& item) -{ - items.push_back(item); -} -void wiTreeList::ClearItems() -{ - items.clear(); -} -void wiTreeList::ClearSelection() -{ - for (Item& item : items) - { - item.selected = false; - } - - wiEventArgs args; - args.iValue = -1; - onSelect(args); -} -void wiTreeList::Select(int index) -{ - items[index].selected = true; - - wiEventArgs args; - args.iValue = index; - args.sValue = items[index].name; - args.userdata = items[index].userdata; - onSelect(args); -} -const wiTreeList::Item& wiTreeList::GetItem(int index) const -{ - return items[index]; -} diff --git a/WickedEngine/wiWidget.h b/WickedEngine/wiWidget.h deleted file mode 100644 index d720fd80f..000000000 --- a/WickedEngine/wiWidget.h +++ /dev/null @@ -1,392 +0,0 @@ -#pragma once -#include "CommonInclude.h" -#include "wiColor.h" -#include "wiGraphicsDevice.h" -#include "wiIntersect.h" -#include "wiScene.h" -#include "wiSprite.h" -#include "wiSpriteFont.h" -#include "wiMath.h" -#include "wiVector.h" - -#include -#include - -struct wiEventArgs -{ - XMFLOAT2 clickPos; - XMFLOAT2 startPos; - XMFLOAT2 deltaPos; - XMFLOAT2 endPos; - float fValue; - bool bValue; - int iValue; - wiColor color; - std::string sValue; - uint64_t userdata; -}; - -class wiWidget : public wiScene::TransformComponent -{ -public: - enum WIDGETSTATE - { - IDLE, // widget is doing nothing - FOCUS, // widget got pointer dragged on or selected - ACTIVE, // widget is interacted with right now - DEACTIVATING, // widget has last been active but no more interactions are occuring - WIDGETSTATE_COUNT, - }; -private: - int tooltipTimer = 0; -protected: - std::string name; - std::string tooltip; - std::string scriptTip; - bool enabled = true; - bool visible = true; - WIDGETSTATE state = IDLE; - -public: - wiWidget(); - virtual ~wiWidget() = default; - - const std::string& GetName() const; - void SetName(const std::string& value); - const std::string GetText() const; - void SetText(const std::string& value); - void SetText(std::string&& value); - void SetTooltip(const std::string& value); - void SetTooltip(std::string&& value); - void SetScriptTip(const std::string& value); - void SetScriptTip(std::string&& value); - void SetPos(const XMFLOAT2& value); - void SetSize(const XMFLOAT2& value); - WIDGETSTATE GetState() const; - virtual void SetEnabled(bool val); - bool IsEnabled() const; - virtual void SetVisible(bool val); - bool IsVisible() const; - // last param default: set color for all states - void SetColor(wiColor color, WIDGETSTATE state = WIDGETSTATE_COUNT); - wiColor GetColor() const; - // last param default: set color for all states - void SetImage(std::shared_ptr textureResource, WIDGETSTATE state = WIDGETSTATE_COUNT); - - virtual void Update(const wiCanvas& canvas, float dt); - virtual void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const = 0; - virtual void RenderTooltip(const wiCanvas& canvas, wiGraphics::CommandList cmd) const; - - wiSprite sprites[WIDGETSTATE_COUNT]; - wiSpriteFont font; - - XMFLOAT3 translation = XMFLOAT3(0, 0, 0); - XMFLOAT3 scale = XMFLOAT3(1, 1, 1); - - Hitbox2D hitBox; - wiGraphics::Rect scissorRect; - - wiWidget* parent = nullptr; - void AttachTo(wiWidget* parent); - void Detach(); - - void Activate(); - void Deactivate(); - - void ApplyScissor(const wiCanvas& canvas, const wiGraphics::Rect rect, wiGraphics::CommandList cmd, bool constrain_to_parent = true) const; - Hitbox2D GetPointerHitbox() const; - - static void Initialize(); - - bool priority_change = true; - uint32_t priority = 0; - bool force_disable = false; -}; - -// Clickable, draggable box -class wiButton : public wiWidget -{ -protected: - std::function onClick; - std::function onDragStart; - std::function onDrag; - std::function onDragEnd; - XMFLOAT2 dragStart = XMFLOAT2(0, 0); - XMFLOAT2 prevPos = XMFLOAT2(0, 0); -public: - void Create(const std::string& name); - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnClick(std::function func); - void OnDragStart(std::function func); - void OnDrag(std::function func); - void OnDragEnd(std::function func); -}; - -// Static box that holds text -class wiLabel : public wiWidget -{ -protected: -public: - void Create(const std::string& name); - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; -}; - -// Text input box -class wiTextInputField : public wiWidget -{ -protected: - std::function onInputAccepted; - static wiSpriteFont font_input; - -public: - void Create(const std::string& name); - - wiSpriteFont font_description; - - void SetValue(const std::string& newValue); - void SetValue(int newValue); - void SetValue(float newValue); - const std::string GetValue(); - void SetDescription(const std::string& desc) { font_description.SetText(desc); } - const std::string GetDescription() const { return font_description.GetTextA(); } - - // There can only be ONE active text input field, so these methods modify the active one - static void AddInput(const char inputChar); - static void DeleteFromInput(); - - void Update(const wiCanvas& canvas, float dt) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnInputAccepted(std::function func); -}; - -// Define an interval and slide the control along it -class wiSlider : public wiWidget -{ -protected: - std::function onSlide; - float start = 0, end = 1; - float step = 1000; - float value = 0; - - wiTextInputField valueInputField; -public: - // start : slider minimum value - // end : slider maximum value - // defaultValue : slider default Value - // step : slider step size - void Create(float start, float end, float defaultValue, float step, const std::string& name); - - wiSprite sprites_knob[WIDGETSTATE_COUNT]; - - void SetValue(float value); - float GetValue() const; - void SetRange(float start, float end); - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - void RenderTooltip(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnSlide(std::function func); -}; - -// Two-state clickable box -class wiCheckBox :public wiWidget -{ -protected: - std::function onClick; - bool checked = false; -public: - void Create(const std::string& name); - - wiSprite sprites_check[WIDGETSTATE_COUNT]; - - void SetCheck(bool value); - bool GetCheck() const; - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnClick(std::function func); -}; - -// Drop-down list -class wiComboBox :public wiWidget -{ -protected: - std::function onSelect; - int selected = -1; - int maxVisibleItemCount = 8; - int firstItemVisible = 0; - - // While the widget is active (rolled down) these are the inner states that control behaviour - enum COMBOSTATE - { - COMBOSTATE_INACTIVE, // When the list is just being dropped down, or the widget is not active - COMBOSTATE_HOVER, // The widget is in drop-down state with the last item hovered highlited - COMBOSTATE_SELECTING, // The hovered item is clicked - COMBOSTATE_SCROLLBAR_HOVER, // scrollbar is to be selected - COMBOSTATE_SCROLLBAR_GRABBED, // scrollbar is moved - COMBOSTATE_COUNT, - } combostate = COMBOSTATE_INACTIVE; - int hovered = -1; - - float scrollbar_delta = 0; - - struct Item - { - std::string name; - uint64_t userdata = 0; - }; - wi::vector items; - - float GetItemOffset(int index) const; -public: - void Create(const std::string& name); - - void AddItem(const std::string& name, uint64_t userdata = 0); - void RemoveItem(int index); - void ClearItems(); - void SetMaxVisibleItemCount(int value); - bool HasScrollbar() const; - - void SetSelected(int index); - void SetSelectedByUserdata(uint64_t userdata); - int GetSelected() const; - std::string GetItemText(int index) const; - uint64_t GetItemUserData(int index) const; - size_t GetItemCount() const { return items.size(); } - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnSelect(std::function func); -}; - -// Widget container -class wiWindow :public wiWidget -{ -protected: - wiButton closeButton; - wiButton minimizeButton; - wiButton resizeDragger_UpperLeft; - wiButton resizeDragger_BottomRight; - wiButton moveDragger; - wiLabel label; - wi::vector widgets; - bool minimized = false; -public: - void Create(const std::string& name, bool window_controls = true); - - void AddWidget(wiWidget* widget); - void RemoveWidget(wiWidget* widget); - void RemoveWidgets(); - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - void RenderTooltip(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void SetVisible(bool value) override; - void SetEnabled(bool value) override; - void SetMinimized(bool value); - bool IsMinimized() const; -}; - -// HSV-Color Picker -class wiColorPicker : public wiWindow -{ -protected: - std::function onColorChanged; - enum COLORPICKERSTATE - { - CPS_IDLE, - CPS_HUE, - CPS_SATURATION, - } colorpickerstate = CPS_IDLE; - float hue = 0.0f; // [0, 360] degrees - float saturation = 0.0f; // [0, 1] - float luminance = 1.0f; // [0, 1] - - wiTextInputField text_R; - wiTextInputField text_G; - wiTextInputField text_B; - wiTextInputField text_H; - wiTextInputField text_S; - wiTextInputField text_V; - wiSlider alphaSlider; - - void FireEvents(); -public: - void Create(const std::string& name, bool window_controls = true); - - void Update(const wiCanvas& canvas, float dt ) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - wiColor GetPickColor() const; - void SetPickColor(wiColor value); - - void OnColorChanged(std::function func); -}; - -// List of items in a tree (parent-child relationships) -class wiTreeList :public wiWidget -{ -public: - struct Item - { - std::string name; - int level = 0; - uint64_t userdata = 0; - bool open = false; - bool selected = false; - }; -protected: - std::function onSelect; - float list_height = 0; - float list_offset = 0; - int item_highlight = -1; - int opener_highlight = -1; - - enum SCROLLBAR_STATE - { - SCROLLBAR_INACTIVE, - SCROLLBAR_HOVER, - SCROLLBAR_GRABBED, - TREESTATE_COUNT, - } scrollbar_state = SCROLLBAR_INACTIVE; - - float scrollbar_delta = 0; - float scrollbar_height = 0; - float scrollbar_value = 0; - - Hitbox2D GetHitbox_ListArea() const; - Hitbox2D GetHitbox_Item(int visible_count, int level) const; - Hitbox2D GetHitbox_ItemOpener(int visible_count, int level) const; - - wi::vector items; - - float GetItemOffset(int index) const; -public: - void Create(const std::string& name); - - void AddItem(const Item& item); - void ClearItems(); - bool HasScrollbar() const; - - void ClearSelection(); - void Select(int index); - - int GetItemCount() const { return (int)items.size(); } - const Item& GetItem(int index) const; - - void Update(const wiCanvas& canvas, float dt) override; - void Render(const wiCanvas& canvas, wiGraphics::CommandList cmd) const override; - - void OnSelect(std::function func); -}; - diff --git a/WickedEngine/wiXInput.cpp b/WickedEngine/wiXInput.cpp index f2b293239..ba162ddba 100644 --- a/WickedEngine/wiXInput.cpp +++ b/WickedEngine/wiXInput.cpp @@ -8,7 +8,7 @@ #pragma comment(lib,"xinput.lib") -namespace wiXInput +namespace wi::input::xinput { XINPUT_STATE controllers[4] = {}; bool connected[arraysize(controllers)] = {}; @@ -45,7 +45,7 @@ namespace wiXInput x = 1.0f; return x; } - bool GetControllerState(wiInput::ControllerState* state, int index) + bool GetControllerState(wi::input::ControllerState* state, int index) { if (index < arraysize(controllers)) { @@ -53,34 +53,34 @@ namespace wiXInput { if (state != nullptr) { - *state = wiInput::ControllerState(); + *state = wi::input::ControllerState(); const XINPUT_STATE& xinput_state = controllers[index]; // Retrieve buttons: - for (int button = wiInput::GAMEPAD_RANGE_START + 1; button < wiInput::GAMEPAD_RANGE_END; ++button) + for (int button = wi::input::GAMEPAD_RANGE_START + 1; button < wi::input::GAMEPAD_RANGE_END; ++button) { bool down = false; switch (button) { - case wiInput::GAMEPAD_BUTTON_UP: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP; break; - case wiInput::GAMEPAD_BUTTON_LEFT: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT; break; - case wiInput::GAMEPAD_BUTTON_DOWN: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN; break; - case wiInput::GAMEPAD_BUTTON_RIGHT: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT; break; - case wiInput::GAMEPAD_BUTTON_1: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_X; break; - case wiInput::GAMEPAD_BUTTON_2: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_A; break; - case wiInput::GAMEPAD_BUTTON_3: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_B; break; - case wiInput::GAMEPAD_BUTTON_4: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_Y; break; - case wiInput::GAMEPAD_BUTTON_5: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER; break; - case wiInput::GAMEPAD_BUTTON_6: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER; break; - case wiInput::GAMEPAD_BUTTON_7: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB; break; - case wiInput::GAMEPAD_BUTTON_8: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB; break; - case wiInput::GAMEPAD_BUTTON_9: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK; break; - case wiInput::GAMEPAD_BUTTON_10: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_START; break; + case wi::input::GAMEPAD_BUTTON_UP: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP; break; + case wi::input::GAMEPAD_BUTTON_LEFT: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT; break; + case wi::input::GAMEPAD_BUTTON_DOWN: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN; break; + case wi::input::GAMEPAD_BUTTON_RIGHT: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT; break; + case wi::input::GAMEPAD_BUTTON_1: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_X; break; + case wi::input::GAMEPAD_BUTTON_2: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_A; break; + case wi::input::GAMEPAD_BUTTON_3: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_B; break; + case wi::input::GAMEPAD_BUTTON_4: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_Y; break; + case wi::input::GAMEPAD_BUTTON_5: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER; break; + case wi::input::GAMEPAD_BUTTON_6: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER; break; + case wi::input::GAMEPAD_BUTTON_7: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB; break; + case wi::input::GAMEPAD_BUTTON_8: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB; break; + case wi::input::GAMEPAD_BUTTON_9: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK; break; + case wi::input::GAMEPAD_BUTTON_10: down = xinput_state.Gamepad.wButtons & XINPUT_GAMEPAD_START; break; } if (down) { - state->buttons |= 1 << (button - wiInput::GAMEPAD_RANGE_START - 1); + state->buttons |= 1 << (button - wi::input::GAMEPAD_RANGE_START - 1); } } @@ -97,7 +97,7 @@ namespace wiXInput } return false; } - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index) + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index) { if (index < arraysize(controllers)) { @@ -110,11 +110,11 @@ namespace wiXInput } #else -namespace wiXInput +namespace wi::input::xinput { void Update() {} int GetMaxControllerCount() { return 0; } - bool GetControllerState(wiInput::ControllerState* state, int index) { return false; } - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index) {} + bool GetControllerState(wi::input::ControllerState* state, int index) { return false; } + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index) {} } #endif // __has_include("xinput.h") diff --git a/WickedEngine/wiXInput.h b/WickedEngine/wiXInput.h index 81d8b82d8..2fc9b7ec5 100644 --- a/WickedEngine/wiXInput.h +++ b/WickedEngine/wiXInput.h @@ -2,7 +2,7 @@ #include "CommonInclude.h" #include "wiInput.h" -namespace wiXInput +namespace wi::input::xinput { // Call once per frame to read and update controller states void Update(); @@ -12,8 +12,8 @@ namespace wiXInput // Returns whether the controller identified by index parameter is available or not. // Id state parameter is not nullptr, and the controller is available, the state will be written into it - bool GetControllerState(wiInput::ControllerState* state, int index); + bool GetControllerState(wi::input::ControllerState* state, int index); // Sends feedback data for the controller identified by index parameter to output - void SetControllerFeedback(const wiInput::ControllerFeedback& data, int index); + void SetControllerFeedback(const wi::input::ControllerFeedback& data, int index); } diff --git a/credits.txt b/credits.txt index d12a9706d..a91543aa4 100644 --- a/credits.txt +++ b/credits.txt @@ -47,3 +47,4 @@ Patreon supporters: - Sergey K - Yukawa Kanta - Dragon Josh +- John