forked from Dynamitos/Seele
Adding agents.md, fixing long-broken initializer list constructor
This commit is contained in:
1 parent
6a6294c67d
commit
ff2e4e642d
12 files changed
+484
-526
No files matched your search
@@ -0,0 +1,227 @@
|
|||||||
|
# AGENTS.md — Seele Engine
|
||||||
|
|
||||||
|
Guidance for AI agents (and humans) working in this repository. Read this first, then
|
||||||
|
`README.md` and `OPTIMIZATIONS.md` for deeper design detail.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
**Seele** is a general-purpose 3D game/render engine. C++ (C++23), **Vulkan** as the primary
|
||||||
|
graphics backend (a Metal backend exists; the `Graphics` API is designed so other backends
|
||||||
|
like OpenGL could be added). It is a proof-of-concept engine but is built to be extensible.
|
||||||
|
|
||||||
|
- **Engine** — shared library, the core (`src/Engine`).
|
||||||
|
- **Editor** — executable, the content/inspector tool (`src/Editor`).
|
||||||
|
- **AssetViewer** — executable (`src/AssetViewer`).
|
||||||
|
- **Benchmark** — executable (`src/Benchmark`).
|
||||||
|
- **SeeleUnitTests** — GTest executable (`tests/`).
|
||||||
|
|
||||||
|
> Note: an earlier design used a coroutine-based Job system (`Job`/`MainJob`/`Event` and
|
||||||
|
> templated `RenderPass<T>`). It was dropped (MSVC memory-leak issues + forcing everything
|
||||||
|
> async). The shipped job system is a plain `ThreadPool` (`src/Engine/ThreadPool.{h,cpp}`,
|
||||||
|
> `getThreadPool()`). Do not assume the coroutine API is present.
|
||||||
|
|
||||||
|
## Repo layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
Engine/ # the engine shared library (one CMake target: Engine)
|
||||||
|
Graphics/ # graphics API abstraction + Vulkan + Metal + RenderPass impls
|
||||||
|
Vulkan/ # Vulkan backend (Graphics.h is the abstract base in Graphics/)
|
||||||
|
Metal/ # Metal backend
|
||||||
|
RenderPass/ # concrete render passes (BasePass, DepthCulling, LightCulling,
|
||||||
|
# Shadow, RayTracing, ToneMapping, UI, Visibility, Fluid, ...)
|
||||||
|
CBT/ # command buffer tracking
|
||||||
|
Containers/ # custom containers (Array, StaticArray, Map, List, Set, Tree, ...)
|
||||||
|
Math/ # math (glm-backed typedefs: Vector, Vector3→Vector, Matrix4, etc.)
|
||||||
|
Asset/ # asset registry, loaders (mesh, texture, font, material, env, SVG, level)
|
||||||
|
Material/ # material / BRDF system (Slang-generated)
|
||||||
|
Actor/ # Entity + concrete actors (mesh, light, camera) — EnTT-based
|
||||||
|
Component/ # components (Transform, Mesh, Camera, lights, colliders, ...)
|
||||||
|
Scene/ # scene, event manager, light environment
|
||||||
|
System/ # per-frame systems: SystemGraph, ComponentSystem, updaters (mesh,
|
||||||
|
# light, fluid, camera), executor
|
||||||
|
Physics/ # physics: BVH, collision system, physics system
|
||||||
|
Serialization/ # ArchiveBuffer + Serialization.h
|
||||||
|
UI/ # custom UI framework (Element, FlexLayout, Style)
|
||||||
|
Window/ # WindowManager, View (GameView, etc.)
|
||||||
|
Platform/ # per-OS: Linux/, Mac/, Windows/ (GameInterface)
|
||||||
|
Editor/ # Editor executable (main.cpp, Asset/ importers, Window/ views)
|
||||||
|
AssetViewer/ # AssetViewer executable
|
||||||
|
Benchmark/ # Benchmark executable
|
||||||
|
tests/
|
||||||
|
Engine/ # GTest suite, mirrored under Engine/<Subsystem>/
|
||||||
|
res/
|
||||||
|
shaders/ # Slang shader sources (.slang)
|
||||||
|
fonts/ textures/ cmake/
|
||||||
|
cmake/ # SuperBuild.cmake, EngineConfig.cmake.in
|
||||||
|
external/ # submodules: vcpkg, CRCpp, metal-cpp (do not edit)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
Standard CMake, **C++23**. Deps come from **vcpkg** (manifest mode, `vcpkg.json`) plus the
|
||||||
|
`external/` submodules. Prereq on Linux: the X11 dev libs for GLFW
|
||||||
|
(`libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev`).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# one-time: pull dependencies (vcpkg submodule + everything)
|
||||||
|
git submodule update --init --recursive
|
||||||
|
|
||||||
|
# configure + build (use a preset)
|
||||||
|
cmake --preset debug
|
||||||
|
cmake --build --preset debug --config Debug
|
||||||
|
```
|
||||||
|
|
||||||
|
Presets (`CMakePresets.json`): `debug`, `release`, `debug-asan`, `release-asan`,
|
||||||
|
`debug-mac` (Xcode). Binary dir is the in-tree `build/` (gitignored). The vcpkg toolchain
|
||||||
|
is hard-wired in the top-level `CMakeLists.txt`
|
||||||
|
(`CMAKE_TOOLCHAIN_FILE=${EXTERNAL_ROOT}/vcpkg/scripts/buildsystems/vcpkg.cmake`).
|
||||||
|
|
||||||
|
- The engine is a **SHARED** lib (`add_library(Engine SHARED)`) — all four binaries link it.
|
||||||
|
- `Editor` is compiled with `EDITOR=1` and includes `src/Editor` + the Stb includes.
|
||||||
|
- On non-Apple, the `slang-glslang` **plugin** is a MODULE library and is **copied** next to
|
||||||
|
the `Engine` binary at post-build (do not try to link it). On Windows the runtime DLLs are
|
||||||
|
likewise copied next to `Editor`.
|
||||||
|
- Windows defines `USE_EXTENSIONS` and adds `WIN32`; MSVC builds with `/W4`, GCC/Clang with
|
||||||
|
`-Wall -Wextra -Wno-error -pedantic`. Warnings are **not** fatal, but keep the build clean.
|
||||||
|
- There is **no CI** and no `test` preset. Run tests manually (below).
|
||||||
|
|
||||||
|
`OPTIMIZATIONS.md` is a scratch list of optimization ideas (LTO, PGO, attributes, copy-avoidance
|
||||||
|
guidelines) — it is reference material, not a build requirement.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
GTest. `tests/` builds a single `SeeleUnitTests` binary and registers with CTest via
|
||||||
|
`gtest_discover_tests`. Tests are organized to mirror the engine tree
|
||||||
|
(`tests/Engine/Containers/Array.cpp`, `tests/Engine/Math/Vector.cpp`,
|
||||||
|
`tests/Engine/System/ComponentSystem.cpp`, `tests/Engine/Serialization/ArchiveBuffer.cpp`,
|
||||||
|
`tests/Engine/ThreadPool.cpp`, `tests/Engine/UI/...`, `tests/Engine/Graphics/...`).
|
||||||
|
|
||||||
|
- Every test file includes `tests/Engine/EngineTest.h` (which pulls in `<gtest/gtest.h>` +
|
||||||
|
`MinimalEngine.h` + `using namespace Seele;`).
|
||||||
|
- Add a new test: create `tests/Engine/<Subsystem>/Foo.cpp` and **add it to that
|
||||||
|
subdirectory's `tests/Engine/<Subsystem>/CMakeLists.txt`** (the subdirs `add_subdirectory`
|
||||||
|
into `tests/Engine/CMakeLists.txt`). Forgetting the CMake registration is the #1 way a new
|
||||||
|
test silently never compiles or runs.
|
||||||
|
- Run: `cd build && ctest --test-dir . -R <TestNamePattern> --output-on-failure` (or run the
|
||||||
|
`SeeleUnitTests` binary directly). Use a `debug`/`debug-asan` preset for test development.
|
||||||
|
|
||||||
|
## Core architecture (read before touching Graphics/RenderPass)
|
||||||
|
|
||||||
|
The invariants that are **actual in the code**:
|
||||||
|
|
||||||
|
- **`Gfx::Graphics`** (`src/Engine/Graphics/Graphics.h`) is the abstract backend interface.
|
||||||
|
`Vulkan::Graphics` (`Graphics/Vulkan/Graphics.h`) and `Metal::Graphics` (`Graphics/Metal/`)
|
||||||
|
implement it. All GPU work goes through this interface; render passes must not touch
|
||||||
|
Vulkan or Metal handles directly. `ENABLE_VALIDATION` is defined in `Graphics.h`.
|
||||||
|
- **Window → View → RenderPass.** A `WindowManager` owns `Graphics` + `Window`s; each
|
||||||
|
`Window` holds `View`s (a viewport; e.g. `Editor::InspectorView`, `GameView`). Rendering of
|
||||||
|
all viewports in a window is synchronized, but per-`View` logic runs on its own thread.
|
||||||
|
The thread handshake is the lock-protected `commitUpdate()` (logic side) → `prepareRender()`
|
||||||
|
(render side); a `View` pushes a concrete `RenderPassDataType` packet to each pass it uses.
|
||||||
|
- **Render passes** are plain (non-template) `RenderPass` subclasses in
|
||||||
|
`src/Engine/Graphics/RenderPass/` (`beginFrame`/`render`/`endFrame`/`publishOutputs`/
|
||||||
|
`createRenderPass`). All passes share one `PRenderGraphResources` object; a pass
|
||||||
|
**publishes** the GPU outputs it produces (`publishOutputs()`) and other passes **consume**
|
||||||
|
them by name — so pass *init order does not matter*. If you add a pass that produces or
|
||||||
|
consumes shared resources, you must wire both the publish and the consume.
|
||||||
|
- **Descriptor sets** for pass-shared data (camera, lights, view params) are managed per
|
||||||
|
render pass; because Vulkan pipeline layouts cannot have empty set indices, each pass has a
|
||||||
|
static `modifyRenderPassMacros` that `#define`s the correct descriptor-set indices for shared
|
||||||
|
layouts. Keep that in sync if you add/remove descriptor sets.
|
||||||
|
- **`getGlobals()`** (`MinimalEngine.h`) is the global feature/flags struct (e.g.
|
||||||
|
`useRayTracing`, `useDepthCulling`, `running`, …). It controls which passes run. Treat it as
|
||||||
|
global mutable state — do not add per-frame logic to it.
|
||||||
|
|
||||||
|
### Entities / scenes / systems (EnTT)
|
||||||
|
|
||||||
|
- `Actor`/`Entity` (`src/Engine/Actor/`) wrap an **EnTT** entity ID + a `PScene`. Components
|
||||||
|
live in `src/Engine/Component/`; attach via `scene->attachComponent<C>(...)` /
|
||||||
|
`entity.accessComponent<C>()`.
|
||||||
|
- Per-frame update is driven by `SystemGraph` / `ComponentSystem` in `src/Engine/System/`.
|
||||||
|
A `Component` can declare dependencies on other components (the `Dependencies` /
|
||||||
|
`has_dependencies` / `REQUIRE_COMPONENT` mechanism in `Component.h`). The concrete updaters
|
||||||
|
(`MeshUpdater`, `LightGather`, `FluidUpdater`, `CameraUpdater`, …) are the per-frame work
|
||||||
|
and must be registered in the system graph.
|
||||||
|
|
||||||
|
### Materials (Slang-generated)
|
||||||
|
|
||||||
|
- A material is a JSON doc: a `profile` (BRDF, e.g. `BlinnPhong`), typed `params` (HLSL
|
||||||
|
types + defaults), and a `code` section with one string-array per BRDF output. On load,
|
||||||
|
the engine generates the descriptor layout and compiles a Slang `IMaterial` type (see
|
||||||
|
`src/Engine/Material/`, `Graphics/slang-compile.cpp`).
|
||||||
|
Shared Slang lives in `res/shaders/*.slang`; per-material pipeline variants are generated
|
||||||
|
from a render pass's base `.slang` via `#define`s. **If you change the set of BRDF outputs
|
||||||
|
or a shared Slang input, the generated material code and the `prepare()`/`get*` accessors
|
||||||
|
must stay consistent** — they are produced from the JSON profile, not hand-written.
|
||||||
|
|
||||||
|
## Code conventions (match the surrounding code)
|
||||||
|
|
||||||
|
- **C++23.** The build sets `CMAKE_CXX_STANDARD 23`; C++20/23 features are in active use
|
||||||
|
(concepts, `std::span`, designated initializers, `<=>` spaceship, `[[unlikely]]`, etc.).
|
||||||
|
- **Formatting: `.clang-format`** — `BasedOnStyle: LLVM`, `IndentWidth: 4`, `ColumnLimit: 140`,
|
||||||
|
left-aligned pointers (`P*`, not `P *`), 2-space class-member indent in practice (see
|
||||||
|
`Graphics.h`/`RenderPass.h`). Headers use `#pragma once`. Keep to it; do not reformat
|
||||||
|
untouched code.
|
||||||
|
- **Namespaces.** Engine code lives in `namespace Seele`; the graphics backend in
|
||||||
|
`namespace Seele::Gfx` (Vulkan impl in `Seele::Vulkan`, Metal in `Seele::Metal`).
|
||||||
|
- **Types.**
|
||||||
|
- Fixed-width scalars come from `EngineTypes.h`: `uint8/16/32/64`, `int8/16/32/64`.
|
||||||
|
Prefer these over `std::uint32_t` for consistency with the codebase.
|
||||||
|
- Math types are **glm typedefs** in `Math/Math.h`/`Vector.h`/`Matrix.h`: `Vector` is
|
||||||
|
`glm::vec3`, `Vector2`/`Vector4`/`UVector`(`uvec3`)/`IVector`/`Quaternion`
|
||||||
|
(`glm::quat`)/`Matrix4`, etc. Use these, not raw `glm::vec*`. `Math.h` re-exports glm.
|
||||||
|
- `Matrix` types: `Matrix4` etc. — `Matrix.h`.
|
||||||
|
- **Smart pointers / ownership** (the most important idiom — defined in `MinimalEngine.h`):
|
||||||
|
- `DEFINE_REF(ClassName)` at the end of a class's header typedefs `P<Name>`, `UP<Name>`,
|
||||||
|
`O<Name>`. `DECLARE_REF(ClassName)` is the same but only forward-declares (for
|
||||||
|
headers that need the typedefs but not the class). `DECLARE_NAME_REF(nmsp, Name)`
|
||||||
|
is the namespaced variant (used heavily in `Gfx`, e.g. `DECLARE_NAME_REF(Gfx, Viewport)`).
|
||||||
|
- **`P<T>`** = `RefPtr<T>` — a *non-owning* strong reference (shared, `dynamic_cast`
|
||||||
|
`cast()`, `<=>`-comparable). Use as the default "have a reference" type (members,
|
||||||
|
parameters, return of non-owning lookups).
|
||||||
|
- **`O<T>`** = `OwningPtr<T>` — the *owning* pointer (move-only, deletes on scope exit,
|
||||||
|
implicitly converts to `P<T>`). Use it for the **result of factories/creators** —
|
||||||
|
e.g. `Graphics::createWindow(...) -> OWindow`, `createTexture2D(...) -> OTexture2D`.
|
||||||
|
A factory returns `O<T>`; anything storing it should keep it as `P<T>` (or pass the
|
||||||
|
`O<T>` into a `P<T>` conversion).
|
||||||
|
- **`UP<T>`** = `UniquePtr<T>` — move-only, deletes on scope exit.
|
||||||
|
- You will rarely `new` explicitly: `P<Foo> p = new Foo();` is the pattern used in
|
||||||
|
`main.cpp` / tests because `RefPtr` has a raw-pointer constructor. For factories,
|
||||||
|
return `O<T>`.
|
||||||
|
- Do **not** introduce `std::shared_ptr`/`std::unique_ptr` for engine objects — use the
|
||||||
|
`P/O/UP` types.
|
||||||
|
- **Containers:** use the engine's own in `Containers/` (`Array<T>` = heap `std::vector`-like
|
||||||
|
with `add`/`resize`/`remove`/`removeAt`/`find`/`clear`; `StaticArray<T,N>`; `Map`, `List`,
|
||||||
|
`Set`, `Tree`, `Pair`). There is a `MemoryResource` (pool) too. Prefer these over
|
||||||
|
`std::vector`/`std::map` for engine data (they are what serialization etc. integrate with).
|
||||||
|
- **Errors / asserts:** `assert()` from `<assert.h>` (see `MinimalEngine.h`). `fmt`
|
||||||
|
(`fmt::format`) is used for string building (linked via vcpkg); `nlohmann_json` for JSON
|
||||||
|
(see `Serialization.h`). There is no exception-based error API to follow — match local style.
|
||||||
|
- **Per-subsystem `CMakeLists.txt`** only calls `target_sources(Engine PRIVATE ... .cpp)` and
|
||||||
|
`target_sources(Engine PUBLIC FILE_SET HEADERS FILES ... .h)`. When you add a `.cpp`,
|
||||||
|
add it to the `PRIVATE` list of the **nearest** `CMakeLists.txt`; when you add a public
|
||||||
|
header, add it to `FILE_SET HEADERS` too (or it won't install/export and other targets
|
||||||
|
can't find it).
|
||||||
|
|
||||||
|
## Workflow & gotchas
|
||||||
|
|
||||||
|
- **No CI, no `test` preset.** Nothing runs the test suite for you. Configure a `debug`/
|
||||||
|
`debug-asan` preset, build, then `cd build && ctest --test-dir . --output-on-failure`.
|
||||||
|
- **`src/Editor/main.cpp` hard-codes `/home/dynamitos/...` paths** (lines 26–27). The Editor
|
||||||
|
will not run on any other machine without editing those two lines to your checkout path.
|
||||||
|
The `if (true)` branch is the live one; the else-branch (cmake `ExportProject.cmake`
|
||||||
|
export flow) is dead code that only worked with the original author's paths.
|
||||||
|
- **Coroutines are not in the code.** An earlier design described a coroutine `Job`/`MainJob`
|
||||||
|
/`Event` system and templated `RenderPass<T>`; none of it is implemented (MSVC memory leaks
|
||||||
|
+ forcing everything async). The real job system is `ThreadPool`
|
||||||
|
(`src/Engine/ThreadPool.{h,cpp}`, `getThreadPool()`).
|
||||||
|
- **Render passes must not touch backend handles.** All GPU work goes through `Gfx::Graphics`.
|
||||||
|
Adding a pass that produces or consumes a shared `RenderGraphResources` resource requires
|
||||||
|
wiring **both** the `publishOutputs()` side and the consume-by-name side, and keeping the
|
||||||
|
`modifyRenderPassMacros` descriptor-set index `#define`s in sync.
|
||||||
|
- **New `.cpp`/`.h` files must be registered in CMake** — both the nearest `CMakeLists.txt`
|
||||||
|
(`target_sources ... PRIVATE` for `.cpp`, `FILE_SET HEADERS` for public headers) and, for
|
||||||
|
tests, the test subdirectory's `CMakeLists.txt`. An unregistered file silently never
|
||||||
|
compiles.
|
||||||
|
|
||||||
-324
@@ -1,324 +0,0 @@
|
|||||||
# Seele Engine
|
|
||||||
|
|
||||||
Seele is a Proof-of-Concept 3D render engine using Vulkan as it's primary graphics API, but other APIs could also be implemented. Due to this, a lot of terminology will be Vulkan-related, but it can be translated to other APIs.
|
|
||||||
It is designed to support multithreading for more recent APIs, like DX12 or Vulkan, while still providing an interface that could be implemented by an
|
|
||||||
API that doesn't support it, like OpenGL. These APIs would suffer a significant performance loss, but would still work correctly.
|
|
||||||
|
|
||||||
## Custom containers and other utilities
|
|
||||||
|
|
||||||
Some of the basic containers are reimplemented, mostly not for any particular feature, but because that makes them more customizable and extendable for future uses and
|
|
||||||
performance optimizations, like serialization for example. Due to some of them occuring in the code samples later, they will be quickly mentioned here.
|
|
||||||
|
|
||||||
- `Array`: A heap-array backed dynamically resizable container, like `std::vector`
|
|
||||||
- `StaticArray`: A static-array backed non-resizable container, like `std::array`
|
|
||||||
- `Map`: A key-value splay-tree associative container, like `std::map`
|
|
||||||
- `UniquePtr`: A smart pointer claiming ownership of an object, like `std::unique_pointer`
|
|
||||||
- `RefPtr`: A reference counting smart pointer, similar to `std::shared_pointer`, with a few differences:
|
|
||||||
- global pointer-based reference counting
|
|
||||||
- this means a `RefPtr` can be constructed from a raw pointer and will retain its reference count correctly
|
|
||||||
- for example if you construct `RefPtr<HelloWorld> ptr = new HelloWorld();`, and in the constructor of HelloWorld create `RefPtr<HelloWorld ptr = this;`, both would have a reference count of 2.
|
|
||||||
- `DEFINE_REF`/`DECLARE_REF`: Macros to automatically typedef different types of smart pointer for convenience, for example DEFINE_REF(HelloWorld) would typedef:
|
|
||||||
- `PHelloWorld`, the same as `RefPtr<HelloWorld>`
|
|
||||||
- `UPHelloWorld`, the same as `UniquePtr<HelloWorld>`
|
|
||||||
|
|
||||||
## Basic Architecture
|
|
||||||
|
|
||||||
The first piece to the puzzle is the `WindowManager`, a container that manages a `Graphics` object, which is the interface for the graphics API, as well as all `Window`s that are active. Each `Window` represents, well, a window, and contains several `View`s. A `View` represents a viewport in the window. For an analogy to Unity, a `View` would be the Inspector, the Asset Browser or the Hierarchy.
|
|
||||||
|
|
||||||
Since all viewports in a window are backed by the same image and can only be presented together, the rendering for all viewports is synchronized, while the logic for each `View` runs in a separate thread.
|
|
||||||
|
|
||||||
The interactions between logic and rendering are modelled through two parts of the interface: `beginUpdate()`, `update()` and `commitUpdate()` for the logic side, and `prepareRender()` and `render()` for the rendering side. The views use a set of concrete `RenderPass` objects to render a new frame, depending on what kind of content should be displayed. In order to draw a frame, a `RenderPass` needs an "update packet" in form of a struct, but the contents of that packet is dependent on the render pass itself. A depth prepass for example might only need a mesh list, while a light culling pass needs the dynamic lights or a base pass might need both.
|
|
||||||
|
|
||||||
In order to avoid inheritance and casting for these update packets, each `RenderPass` needs to be updated individually by the view that uses it, so the thread interactions are not enforced in the `View` base class, instead `commitUpdate()` is called from a locked context from the logic thread, so that the view can copy the packet to a shared storage, while `prepareRender()` is locked and called from the render thread, so that it can be passed to the render passes.
|
|
||||||
|
|
||||||
## RenderPass
|
|
||||||
|
|
||||||
To better illustrate how render passes work, here is part of the `RenderPass` base class:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
template<typename RenderPassDataType>
|
|
||||||
class RenderPass
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
RenderPass(Gfx::PGraphics graphics, Gfx::PViewport viewport)
|
|
||||||
: graphics(graphics)
|
|
||||||
, viewport(viewport)
|
|
||||||
{}
|
|
||||||
virtual ~RenderPass()
|
|
||||||
{}
|
|
||||||
void updateViewFrame(RenderPassDataType viewFrame) {
|
|
||||||
passData = std::move(viewFrame);
|
|
||||||
}
|
|
||||||
virtual void beginFrame() = 0;
|
|
||||||
virtual void render() = 0;
|
|
||||||
virtual void endFrame() = 0;
|
|
||||||
virtual void publishOutputs() = 0;
|
|
||||||
virtual void createRenderPass() = 0;
|
|
||||||
//....
|
|
||||||
private:
|
|
||||||
PRenderGraphResources resources;
|
|
||||||
RenderPassDataType passData;
|
|
||||||
Gfx::PGraphics graphics;
|
|
||||||
//....
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
All render passes in a `View` share a `RenderGraphResources` object, which is used to share outputs between the different passes. During initialization, every render pass "publishes" any outputs that it produces in `publishOutputs()`, so that they can be consumed by other render passes. For example the output of a depth prepass is the depth buffer, for a light culling pass it is the culled light indices. Next the render passes get any resources that they require and have been registered by other passes to create the render pass in `createRenderPass()`. This is split into two parts, so that the order of initialization of different renderpasses doesn't matter, as all outputs are available before any are requested.
|
|
||||||
|
|
||||||
## Materials
|
|
||||||
|
|
||||||
The material system fully embraced a Vulkan-style descriptor system, abstracted by the `Graphics` API. A material is a file stored on disk in form of a JSON document, here is an example:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"name": "Placeholder",
|
|
||||||
"profile": "BlinnPhong",
|
|
||||||
"params": {
|
|
||||||
"diffuseTexture": {
|
|
||||||
"type": "Texture2D"
|
|
||||||
},
|
|
||||||
"specularTexture": {
|
|
||||||
"type": "Texture2D"
|
|
||||||
},
|
|
||||||
"normalTexture": {
|
|
||||||
"type": "Texture2D"
|
|
||||||
},
|
|
||||||
"uvScale": {
|
|
||||||
"type": "float",
|
|
||||||
"default": "0.0f"
|
|
||||||
},
|
|
||||||
"metallic": {
|
|
||||||
"type": "float",
|
|
||||||
"default": "0.0f"
|
|
||||||
},
|
|
||||||
"roughness": {
|
|
||||||
"type": "float",
|
|
||||||
"default": "0.5f"
|
|
||||||
},
|
|
||||||
"sheen": {
|
|
||||||
"type": "float",
|
|
||||||
"default": "0.0f"
|
|
||||||
},
|
|
||||||
"worldOffset": {
|
|
||||||
"type": "float3",
|
|
||||||
"default": "float3(0, 0, 0)"
|
|
||||||
},
|
|
||||||
"textureSampler": {
|
|
||||||
"type": "SamplerState"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"code": {
|
|
||||||
"baseColor": [
|
|
||||||
"return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
|
||||||
],
|
|
||||||
"metallic": [
|
|
||||||
"return metallic;"
|
|
||||||
],
|
|
||||||
"normal": [
|
|
||||||
"return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;"
|
|
||||||
],
|
|
||||||
"specular": [
|
|
||||||
"return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;"
|
|
||||||
],
|
|
||||||
"roughness": [
|
|
||||||
"return roughness;"
|
|
||||||
],
|
|
||||||
"sheen": [
|
|
||||||
"return sheen;"
|
|
||||||
],
|
|
||||||
"worldOffset": [
|
|
||||||
"return worldOffset;"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The document starts with the asset `name`, followed by the `profile`, which tells the engine which BRDF function it uses, and thus what outputs it can expect from the material. Next are the parameters, which are the inputs that need to get passed to the shader later. The `type` field must be a valid HLSL datatype and `default` a valid value for that datatype. In the `code` section, there must be an entry for every output required by the `profile`, each of which is a string array for each line of shader code to compute that value and ends by `return`ing that value.
|
|
||||||
|
|
||||||
### MaterialAsset
|
|
||||||
|
|
||||||
A `MaterialAsset` represents such a JSON document on disk, as well as the GPU resources needed to render a mesh with the material. When loading the file, the a descriptor layout is generated to fit the `slang` code that will be generated later by consolidating the plain variables (`float`, `double`, etc.) into a single uniform buffer. The parameters are stored in an array of `ShaderParameter`s, which contain the current parameter value, like texture references or plain data, as well as information on how to update the GPU resources.
|
|
||||||
|
|
||||||
At the same time a slang-compilable shader is generated, which matches the parameters provided by the descriptor layout. The generated shader is a `Material`, which is an interface that "prepares" a BRDF by initializing its input values, similar to official slang example. How each input value is calculated is read from the `code` section of the JSON document, and wrapped in an accessor to allow for multi line calculations.
|
|
||||||
|
|
||||||
Here is the material generated from the above JSON example:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
import VERTEX_INPUT_IMPORT;
|
|
||||||
import Material;
|
|
||||||
import MaterialParameter;
|
|
||||||
|
|
||||||
struct Placeholder: IMaterial {
|
|
||||||
layout(offset = 0)float anisotropic;
|
|
||||||
layout(offset = 4)float clearCoat;
|
|
||||||
layout(offset = 8)float clearCoatGloss;
|
|
||||||
Texture2D diffuseTexture;
|
|
||||||
layout(offset = 12)float metallic;
|
|
||||||
Texture2D normalTexture;
|
|
||||||
layout(offset = 16)float roughness;
|
|
||||||
layout(offset = 20)float sheen;
|
|
||||||
layout(offset = 24)float sheenTint;
|
|
||||||
Texture2D specularTexture;
|
|
||||||
layout(offset = 28)float specularTint;
|
|
||||||
layout(offset = 32)float subsurface;
|
|
||||||
SamplerState textureSampler;
|
|
||||||
layout(offset = 36)float uvScale;
|
|
||||||
layout(offset = 40)float3 worldOffset;
|
|
||||||
|
|
||||||
float3 getBaseColor(MaterialFragmentParameter input) {
|
|
||||||
return diffuseTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
|
||||||
}
|
|
||||||
float getMetallic(MaterialFragmentParameter input) {
|
|
||||||
return 0;;
|
|
||||||
}
|
|
||||||
float3 getNormal(MaterialFragmentParameter input) {
|
|
||||||
return normalTexture.Sample(textureSampler, input.texCoords[0] * uvScale).xyz;;
|
|
||||||
}
|
|
||||||
float getSpecular(MaterialFragmentParameter input) {
|
|
||||||
return specularTexture.Sample(textureSampler, input.texCoords[0] * uvScale).x;;
|
|
||||||
}
|
|
||||||
float getRoughness(MaterialFragmentParameter input) {
|
|
||||||
return roughness;;
|
|
||||||
}
|
|
||||||
float getSheen(MaterialFragmentParameter input) {
|
|
||||||
return sheen;;
|
|
||||||
}
|
|
||||||
float3 getWorldOffset() {
|
|
||||||
return worldOffset;;
|
|
||||||
}
|
|
||||||
typedef BlinnPhong BRDF;
|
|
||||||
BlinnPhong prepare(MaterialFragmentParameter geometry){
|
|
||||||
BlinnPhong result;
|
|
||||||
result.baseColor = getBaseColor(geometry);
|
|
||||||
result.metallic = getMetallic(geometry);
|
|
||||||
result.normal = getNormal(geometry);
|
|
||||||
result.specular = getSpecular(geometry);
|
|
||||||
result.roughness = getRoughness(geometry);
|
|
||||||
result.sheen = getSheen(geometry);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
### Renderpass interaction
|
|
||||||
|
|
||||||
Each render pass has a "base file" containing the vertex and fragment stages. From that base file a variant is generated for each material that will be used with that render pass using `#define` macros to change the material import, and a `type_param` to update the `ParameterBlock` containing the material itself. Other renderpass dependent data like camera parameter or lights are stored in separate descriptor sets, and to avoid code duplication, they parts that are used by more than one render pass are implemented in separate slang files. But since in Vulkan pipeline layouts cannot have empty indices, the descriptor set indices sometimes need to change. This is done using the static `modifyRenderPassMacros` function in each renderpass to `#define` the correct set indices for each shared descriptor layout.
|
|
||||||
|
|
||||||
## Job System
|
|
||||||
|
|
||||||
The Job System is based on C++20 coroutines, running on a thread pool with 1 main thread and as many worker threads as the native CPU has. This is so that when the main thread needs to block for some thread pool work, the CPU can utilize all its resources. Synchronization is done using `Event`s, which are awaitable wrappers for atomic flags.
|
|
||||||
|
|
||||||
### Creating Jobs
|
|
||||||
|
|
||||||
In order to run a function as a Job, its return type must simply be either `Job` or `MainJob`. Also, any `Job` must contain either a `co_await` or `co_return` statement. As the names suggest, `MainJob`s will always run on the main thread, while `Job`s can run on any thread. Some graphics operations, especially regarding windowing, can only occur on the main thread, which is the reason for the separation. Due to the specification for [coroutines](https://en.cppreference.com/w/cpp/language/coroutines) being incredibly complicated and non-intuitive, a detailed description will be neglected for some code snippets.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
Job doSomething()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingElse()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something else" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingAfterwards()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something afterwards" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job startHere()
|
|
||||||
{
|
|
||||||
Job job1 = doSomething();
|
|
||||||
Job job2 = doSomethingElse();
|
|
||||||
co_await job1;
|
|
||||||
co_await job2;
|
|
||||||
co_await doSomethingAfterwards();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This example will execute the first two functions in an undefined order, while the last one will always be executed last. This is because the jobs are launched as soon as the functions are called, while the co_await operator waits for them to finish. Keeping the return value of every job launched is a bit inconvenient, so there is are some helper functions to help with that. `Job::all()` takes a variable amount of `Job`s which it 'combines' into one. This reduces the previous example into this:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
Job doSomething()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingElse()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something else" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingAfterwards()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something afterwards" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job startHere()
|
|
||||||
{
|
|
||||||
co_await Job::all(
|
|
||||||
doSomething(),
|
|
||||||
doSomethingElse());
|
|
||||||
co_await doSomethingAfterwards();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Any Job can also be continued with `then()`, taking in another `Job` or anything that evaluates to a `Job` if called. This further simplifies the example:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
Job doSomething()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingElse()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something else" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job doSomethingAfterwards()
|
|
||||||
{
|
|
||||||
std::cout << "Doing something afterwards" << std::endl;
|
|
||||||
co_return;
|
|
||||||
}
|
|
||||||
Job startHere()
|
|
||||||
{
|
|
||||||
co_await Job::all(
|
|
||||||
doSomething(),
|
|
||||||
doSomethingElse())
|
|
||||||
.then(doSomethingAfterwards());
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Events
|
|
||||||
|
|
||||||
Aside from `Job`s, `Event`s can also be used to synchronize functions. They are constructed with an optional name for easier debugging, and can be `co_await`ed. For the waiting job to continue, `raise()` must be called, after which one of the waiting jobs should `reset()` the event to make it reusable.
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
Event updateFinished;
|
|
||||||
std::mutex dataLock;
|
|
||||||
uint64 data = 0;
|
|
||||||
|
|
||||||
Job updateSomething()
|
|
||||||
{
|
|
||||||
{
|
|
||||||
std::scoped_lock lock(dataLock);
|
|
||||||
data++;
|
|
||||||
}
|
|
||||||
updateFinished.raise();
|
|
||||||
updateSomething(); // if we call the function again it behaves like a loop
|
|
||||||
}
|
|
||||||
|
|
||||||
Job processUpdates()
|
|
||||||
{
|
|
||||||
co_await updateFinished;
|
|
||||||
updateFinished.reset();
|
|
||||||
{
|
|
||||||
std::scoped_lock lock(dataLock);
|
|
||||||
std::cout << data << std::endl;
|
|
||||||
}
|
|
||||||
processUpdates();
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -63,7 +63,7 @@ VertexOutput vertexMain(uint vertexId : SV_VertexID, uint instanceId : SV_Instan
|
|||||||
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
|
coordinates[vertexId].x * pViewParams.invScreenDimensions.x * 2.0 - 1.0,
|
||||||
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
|
1.0 - coordinates[vertexId].y * pViewParams.invScreenDimensions.y * 2.0
|
||||||
);
|
);
|
||||||
output.position = float4(ndc, style.z, 1.0);
|
output.position = float4(ndc, 1 - style.z, 1.0);
|
||||||
output.texCoords = coordinates[vertexId].zw; // quad-local uv, interpolated per-fragment
|
output.texCoords = coordinates[vertexId].zw; // quad-local uv, interpolated per-fragment
|
||||||
output.instanceId = instanceId; // uint varying: exact per-fragment (not interpolated)
|
output.instanceId = instanceId; // uint varying: exact per-fragment (not interpolated)
|
||||||
return output;
|
return output;
|
||||||
|
|||||||
@@ -103,6 +103,10 @@ template <typename T> struct Array {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// initializer_list elements are const, so they can only be copied, never moved.
|
||||||
|
// For move-only T (e.g. OwningPtr) this ctor is deleted — construct such arrays
|
||||||
|
// with the default ctor + add()/emplace() instead (those move).
|
||||||
|
template <typename U = T, typename = std::enable_if_t<std::is_copy_constructible_v<U>>>
|
||||||
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
|
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
|
||||||
: arraySize(init.size()), allocated(init.size()), allocator(alloc) {
|
: arraySize(init.size()), allocated(init.size()), allocator(alloc) {
|
||||||
_data = allocateArray(init.size());
|
_data = allocateArray(init.size());
|
||||||
@@ -276,7 +280,12 @@ template <typename T> struct Array {
|
|||||||
T* tempArray = allocateArray(allocated);
|
T* tempArray = allocateArray(allocated);
|
||||||
assert(tempArray != nullptr);
|
assert(tempArray != nullptr);
|
||||||
|
|
||||||
std::uninitialized_move(begin(), end(), Iterator(tempArray));
|
// begin()/end() yield lvalue iterators, so uninitialized_move would
|
||||||
|
// degrade to a copy — invalid for move-only T (e.g. OwningPtr). Move
|
||||||
|
// each element explicitly instead.
|
||||||
|
for (size_type i = 0; i < arraySize; ++i) {
|
||||||
|
std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::move(_data[i]));
|
||||||
|
}
|
||||||
deallocateArray(_data, arraySize);
|
deallocateArray(_data, arraySize);
|
||||||
_data = tempArray;
|
_data = tempArray;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,12 +32,12 @@ void Queue::submitCommandBuffer(PCommand command, const Array<VkSemaphore>& sign
|
|||||||
// is also signalled in this same submit.
|
// is also signalled in this same submit.
|
||||||
for (VkSemaphore waitHandle : command->waitHandles) {
|
for (VkSemaphore waitHandle : command->waitHandles) {
|
||||||
waitSemaphores.add(waitHandle);
|
waitSemaphores.add(waitHandle);
|
||||||
std::cout << "Semaphore " << waitHandle << " waited on by cmd " << command->getHandle() << std::endl;
|
// std::cout << "Semaphore " << waitHandle << " waited on by cmd " << command->getHandle() << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (VkSemaphore signalSemaphore : signalSemaphores) {
|
// for (VkSemaphore signalSemaphore : signalSemaphores) {
|
||||||
std::cout << "Semaphore " << signalSemaphore << " is signalled by cmd " << command->getHandle() << std::endl;
|
// std::cout << "Semaphore " << signalSemaphore << " is signalled by cmd " << command->getHandle() << std::endl;
|
||||||
}
|
// }
|
||||||
|
|
||||||
VkSubmitInfo submitInfo = {
|
VkSubmitInfo submitInfo = {
|
||||||
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ void Seele::Vulkan::Window::endFrame() {
|
|||||||
.pResults = &swapChainResult,
|
.pResults = &swapChainResult,
|
||||||
};
|
};
|
||||||
VkResult r = vkQueuePresentKHR(graphics->getGraphicsCommands()->getQueue()->getHandle(), &presentInfo);
|
VkResult r = vkQueuePresentKHR(graphics->getGraphicsCommands()->getQueue()->getHandle(), &presentInfo);
|
||||||
std::cout << "Semaphore " << renderDoneHandle << " signals present for image index " << currentImageIndex << std::endl;
|
// std::cout << "Semaphore " << renderDoneHandle << " signals present for image index " << currentImageIndex << std::endl;
|
||||||
if (swapChainResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainResult == VK_SUBOPTIMAL_KHR || r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) {
|
if (swapChainResult == VK_ERROR_OUT_OF_DATE_KHR || swapChainResult == VK_SUBOPTIMAL_KHR || r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR) {
|
||||||
createSwapChain();
|
createSwapChain();
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+14
-11
@@ -26,6 +26,7 @@ struct UIRender {
|
|||||||
Vector2 uvOffset = Vector2(0);
|
Vector2 uvOffset = Vector2(0);
|
||||||
Vector2 uvSize = Vector2(1);
|
Vector2 uvSize = Vector2(1);
|
||||||
};
|
};
|
||||||
|
DECLARE_REF(Element)
|
||||||
class Element {
|
class Element {
|
||||||
public:
|
public:
|
||||||
// the System walks the retained tree (style/layout/input/render) and needs to read
|
// the System walks the retained tree (style/layout/input/render) and needs to read
|
||||||
@@ -36,16 +37,19 @@ class Element {
|
|||||||
// yields the pointer; ownership/lifetime for the demo is the caller's concern (the
|
// yields the pointer; ownership/lifetime for the demo is the caller's concern (the
|
||||||
// engine does not free them here).
|
// engine does not free them here).
|
||||||
explicit Element(Attributes attr) : attr(attr) {}
|
explicit Element(Attributes attr) : attr(attr) {}
|
||||||
Element(Attributes attr, std::initializer_list<Element*> children_) : attr(attr) {
|
Element(Attributes attr, std::initializer_list<OElement> children_) : attr(attr) {
|
||||||
for (auto c : children_) {
|
// children is Array<OElement> (move-only), so it can't be move-constructed
|
||||||
|
// from the initializer list (initializer_list elements are const). Add each
|
||||||
|
// child explicitly — add() moves the OwningPtr in, transferring ownership.
|
||||||
|
for (const OElement& c : children_) {
|
||||||
if (c != nullptr) {
|
if (c != nullptr) {
|
||||||
c->setParent(this);
|
children.add(std::move(const_cast<OElement&>(c)));
|
||||||
children.add(c);
|
children.back()->setParent(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
virtual ~Element();
|
virtual ~Element();
|
||||||
void setParent(Element* p) { parent = p; }
|
void setParent(PElement p) { parent = p; }
|
||||||
|
|
||||||
// resolves the inherited style + this element's static template classes against the theme.
|
// resolves the inherited style + this element's static template classes against the theme.
|
||||||
// only re-run for this element when style.dirty or the theme changed.
|
// only re-run for this element when style.dirty or the theme changed.
|
||||||
@@ -63,7 +67,7 @@ class Element {
|
|||||||
// explicit mutation entry point: applies runtime overrides, then re-styles the dirty subtree
|
// explicit mutation entry point: applies runtime overrides, then re-styles the dirty subtree
|
||||||
void markDirty() {
|
void markDirty() {
|
||||||
style.dirty = true;
|
style.dirty = true;
|
||||||
if (parent) {
|
if (parent != nullptr) {
|
||||||
parent->markDirty();
|
parent->markDirty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,7 +91,7 @@ class Element {
|
|||||||
// CPU unit tests need to read/write `position`+`dimensions` and read `children`
|
// CPU unit tests need to read/write `position`+`dimensions` and read `children`
|
||||||
// without a friend declaration (FlexLayout is a namespace, not a class, and the
|
// without a friend declaration (FlexLayout is a namespace, not a class, and the
|
||||||
// tests are a separate TU).
|
// tests are a separate TU).
|
||||||
const Array<Element*>& getChildren() const { return children; }
|
const Array<OElement>& getChildren() const { return children; }
|
||||||
void setLayout(const Vector2& pos, const Vector2& dims) {
|
void setLayout(const Vector2& pos, const Vector2& dims) {
|
||||||
position = pos;
|
position = pos;
|
||||||
dimensions = dims;
|
dimensions = dims;
|
||||||
@@ -103,7 +107,7 @@ class Element {
|
|||||||
// (min/max, position, display) before re-resolving; the .cpp only reads it.
|
// (min/max, position, display) before re-resolving; the .cpp only reads it.
|
||||||
Style& getStyle() { return style; }
|
Style& getStyle() { return style; }
|
||||||
const Style& getStyle() const { return style; }
|
const Style& getStyle() const { return style; }
|
||||||
Element* getParent() const { return parent; }
|
PElement getParent() const { return parent; }
|
||||||
float getIntrinsicW() const { return intrinsicW; }
|
float getIntrinsicW() const { return intrinsicW; }
|
||||||
float getIntrinsicH() const { return intrinsicH; }
|
float getIntrinsicH() const { return intrinsicH; }
|
||||||
|
|
||||||
@@ -146,9 +150,8 @@ class Element {
|
|||||||
|
|
||||||
protected:
|
protected:
|
||||||
Attributes attr;
|
Attributes attr;
|
||||||
Element* parent = nullptr;
|
PElement parent = nullptr;
|
||||||
// raw, non-owning (see the ctor comment); matches the pre-existing call sites
|
Array<OElement> children;
|
||||||
Array<Element*> children;
|
|
||||||
// set by the System when the theme changed; forces a one-time full re-style
|
// set by the System when the theme changed; forces a one-time full re-style
|
||||||
bool themeChanged = false;
|
bool themeChanged = false;
|
||||||
// the theme this element was last styled against. the System sets it before
|
// the theme this element was last styled against. the System sets it before
|
||||||
|
|||||||
@@ -40,12 +40,12 @@ namespace {
|
|||||||
struct Flow {
|
struct Flow {
|
||||||
std::vector<size_t> idx;
|
std::vector<size_t> idx;
|
||||||
std::vector<int32> order;
|
std::vector<int32> order;
|
||||||
static void build(Element* parent, Flow& f) {
|
static void build(PElement parent, Flow& f) {
|
||||||
f.idx.clear();
|
f.idx.clear();
|
||||||
f.order.clear();
|
f.order.clear();
|
||||||
const auto& kids = parent->getChildren();
|
const auto& kids = parent->getChildren();
|
||||||
for (size_t i = 0; i < kids.size(); i++) {
|
for (size_t i = 0; i < kids.size(); i++) {
|
||||||
Element* c = kids[i];
|
PElement c = kids[i];
|
||||||
if (c == nullptr || c->getStyle().display == Display::Hidden) {
|
if (c == nullptr || c->getStyle().display == Display::Hidden) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -92,7 +92,7 @@ static float resolvePx(DimensionType t, float v, float cont) {
|
|||||||
// (px/%) size resolves against the parent's content box; an Auto (or nested-container)
|
// (px/%) size resolves against the parent's content box; an Auto (or nested-container)
|
||||||
// child contributes its intrinsic size (0 for a container, since its real size is
|
// child contributes its intrinsic size (0 for a container, since its real size is
|
||||||
// finalized when the place phase recurses into it). Includes main-axis margins.
|
// finalized when the place phase recurses into it). Includes main-axis margins.
|
||||||
static float childMainFootprint(Element* c, const FlexLayout::Axis& axis, float parentContentMain) {
|
static float childMainFootprint(PElement c, const FlexLayout::Axis& axis, float parentContentMain) {
|
||||||
const Style& s = c->getStyle();
|
const Style& s = c->getStyle();
|
||||||
bool isX = axis.mainIsX;
|
bool isX = axis.mainIsX;
|
||||||
float size;
|
float size;
|
||||||
@@ -120,7 +120,7 @@ static float childMainFootprint(Element* c, const FlexLayout::Axis& axis, float
|
|||||||
// flow children of their footprints (resolved against the element's *content* box on
|
// flow children of their footprints (resolved against the element's *content* box on
|
||||||
// that axis) + gaps, or the element's intrinsic size for a leaf. This is the Auto
|
// that axis) + gaps, or the element's intrinsic size for a leaf. This is the Auto
|
||||||
// fallback for the element's own size.
|
// fallback for the element's own size.
|
||||||
static float contentAxis(bool isX, Element* el, const Flow& flow, const Array<Element*>& kids) {
|
static float contentAxis(bool isX, PElement el, const Flow& flow, const Array<OElement>& kids) {
|
||||||
if (flow.size() == 0) {
|
if (flow.size() == 0) {
|
||||||
return isX ? el->getIntrinsicW() : el->getIntrinsicH();
|
return isX ? el->getIntrinsicW() : el->getIntrinsicH();
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ static float contentAxis(bool isX, Element* el, const Flow& flow, const Array<El
|
|||||||
// parent), the reference is 0 (percent sizes on a root with no containing box
|
// parent), the reference is 0 (percent sizes on a root with no containing box
|
||||||
// are degenerate; the caller should use px).
|
// are degenerate; the caller should use px).
|
||||||
float parentContent = 0.0f;
|
float parentContent = 0.0f;
|
||||||
Element* parent = el->getParent();
|
PElement parent = el->getParent();
|
||||||
if (parent != nullptr) {
|
if (parent != nullptr) {
|
||||||
if (isX) {
|
if (isX) {
|
||||||
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
|
parentContent = std::max(0.0f, (float)parent->getLayoutDimensions().x - (float)(parent->getStyle().paddingLeft + parent->getStyle().paddingRight));
|
||||||
@@ -140,7 +140,7 @@ static float contentAxis(bool isX, Element* el, const Flow& flow, const Array<El
|
|||||||
}
|
}
|
||||||
float m = 0.0f;
|
float m = 0.0f;
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
m = std::max(m, childMainFootprint(c, isX ? Axis{true, false} : Axis{false, false}, parentContent));
|
m = std::max(m, childMainFootprint(c, isX ? Axis{true, false} : Axis{false, false}, parentContent));
|
||||||
}
|
}
|
||||||
float gap = (float)el->getStyle().gap;
|
float gap = (float)el->getStyle().gap;
|
||||||
@@ -152,7 +152,7 @@ static float contentAxis(bool isX, Element* el, const Flow& flow, const Array<El
|
|||||||
|
|
||||||
// resolve one concrete axis of the element's own size: explicit wins; Auto falls back
|
// resolve one concrete axis of the element's own size: explicit wins; Auto falls back
|
||||||
// to the content measurement; min/max then clamp. Returns the final axis size.
|
// to the content measurement; min/max then clamp. Returns the final axis size.
|
||||||
static float resolveAxisSize(bool isX, Element* el, float content, const Style& s) {
|
static float resolveAxisSize(bool isX, PElement el, float content, const Style& s) {
|
||||||
// the percent reference for this element's own size is its *parent's* box (the
|
// the percent reference for this element's own size is its *parent's* box (the
|
||||||
// containing block). the element's own dimensions are finalized before this is
|
// containing block). the element's own dimensions are finalized before this is
|
||||||
// called (layoutElement sets them before recursing into placeFlowChildren), so
|
// called (layoutElement sets them before recursing into placeFlowChildren), so
|
||||||
@@ -183,7 +183,7 @@ static float resolveAxisSize(bool isX, Element* el, float content, const Style&
|
|||||||
// resolves against the parent's content box on the cross axis; Auto falls back to the
|
// resolves against the parent's content box on the cross axis; Auto falls back to the
|
||||||
// element's intrinsic cross size. includes cross-axis margins. used for the parent's
|
// element's intrinsic cross size. includes cross-axis margins. used for the parent's
|
||||||
// Auto cross measurement (max over children) and for non-stretch item sizing.
|
// Auto cross measurement (max over children) and for non-stretch item sizing.
|
||||||
static float childCrossFootprint(Element* c, const FlexLayout::Axis& axis, float parentContentCross) {
|
static float childCrossFootprint(PElement c, const FlexLayout::Axis& axis, float parentContentCross) {
|
||||||
const Style& s = c->getStyle();
|
const Style& s = c->getStyle();
|
||||||
bool isX = axis.mainIsX; // cross axis is the other one
|
bool isX = axis.mainIsX; // cross axis is the other one
|
||||||
float size;
|
float size;
|
||||||
@@ -214,7 +214,7 @@ static float childCrossFootprint(Element* c, const FlexLayout::Axis& axis, float
|
|||||||
// resolve the child's main-axis basis for flex distribution: explicit (px/%) resolves
|
// resolve the child's main-axis basis for flex distribution: explicit (px/%) resolves
|
||||||
// against the parent's content main; Auto falls back to the child's intrinsic main.
|
// against the parent's content main; Auto falls back to the child's intrinsic main.
|
||||||
// does NOT include margins (those are handled separately in the layout loop).
|
// does NOT include margins (those are handled separately in the layout loop).
|
||||||
static float childMainBasis(Element* c, const FlexLayout::Axis& axis, float parentContentMain) {
|
static float childMainBasis(PElement c, const FlexLayout::Axis& axis, float parentContentMain) {
|
||||||
const Style& s = c->getStyle();
|
const Style& s = c->getStyle();
|
||||||
bool isX = axis.mainIsX;
|
bool isX = axis.mainIsX;
|
||||||
// explicit basis (flex-basis) wins over size
|
// explicit basis (flex-basis) wins over size
|
||||||
@@ -265,7 +265,7 @@ static float childMainBasis(Element* c, const FlexLayout::Axis& axis, float pare
|
|||||||
// apply justify (main) and align (cross), write positions. this is the core of the
|
// apply justify (main) and align (cross), write positions. this is the core of the
|
||||||
// flexbox algorithm. the element's own size is already resolved (by the caller); this
|
// flexbox algorithm. the element's own size is already resolved (by the caller); this
|
||||||
// function only positions the children.
|
// function only positions the children.
|
||||||
static void placeFlowChildren(Element* el, const Axis& axis, const Flow& flow, const Array<Element*>& kids) {
|
static void placeFlowChildren(PElement el, const Axis& axis, const Flow& flow, const Array<OElement>& kids) {
|
||||||
if (flow.size() == 0) return;
|
if (flow.size() == 0) return;
|
||||||
const Style& s = el->getStyle();
|
const Style& s = el->getStyle();
|
||||||
// the element's content box (in the element's own coordinate space, before
|
// the element's content box (in the element's own coordinate space, before
|
||||||
@@ -307,7 +307,7 @@ static void placeFlowChildren(Element* el, const Axis& axis, const Flow& flow, c
|
|||||||
std::vector<Placed> placed;
|
std::vector<Placed> placed;
|
||||||
placed.reserve(flow.size());
|
placed.reserve(flow.size());
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
const Style& cs = c->getStyle();
|
const Style& cs = c->getStyle();
|
||||||
Placed p{};
|
Placed p{};
|
||||||
p.idx = flow[k];
|
p.idx = flow[k];
|
||||||
@@ -482,7 +482,7 @@ static void placeFlowChildren(Element* el, const Axis& axis, const Flow& flow, c
|
|||||||
for (size_t k = 0; k < placed.size(); k++) {
|
for (size_t k = 0; k < placed.size(); k++) {
|
||||||
if (placed[k].line != ln) continue;
|
if (placed[k].line != ln) continue;
|
||||||
Placed& p = placed[k];
|
Placed& p = placed[k];
|
||||||
Element* c = kids[p.idx];
|
PElement c = kids[p.idx];
|
||||||
// main position: line start + item offset within line.
|
// main position: line start + item offset within line.
|
||||||
float itemMain;
|
float itemMain;
|
||||||
if (firstOnLine) {
|
if (firstOnLine) {
|
||||||
@@ -565,8 +565,8 @@ static void placeFlowChildren(Element* el, const Axis& axis, const Flow& flow, c
|
|||||||
// layout one element: measure (resolve its own size + recurse to measure children),
|
// layout one element: measure (resolve its own size + recurse to measure children),
|
||||||
// then place (position flow children in the content box, handle absolute children).
|
// then place (position flow children in the content box, handle absolute children).
|
||||||
// writes `position` and `dimensions` in PARENT space (excluding margins).
|
// writes `position` and `dimensions` in PARENT space (excluding margins).
|
||||||
void layoutElement(Element* el, const Axis& axis) {
|
void layoutElement(PElement el, const Axis& axis) {
|
||||||
const Array<Element*>& kids = el->getChildren();
|
const Array<OElement>& kids = el->getChildren();
|
||||||
if (el->getStyle().display == Display::Hidden) {
|
if (el->getStyle().display == Display::Hidden) {
|
||||||
el->setLayout(Vector2(0), Vector2(0));
|
el->setLayout(Vector2(0), Vector2(0));
|
||||||
return;
|
return;
|
||||||
@@ -585,7 +585,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
// prior layout run). for a root element (no parent), the reference is 0.
|
// prior layout run). for a root element (no parent), the reference is 0.
|
||||||
float parentContentCross = 0.0f;
|
float parentContentCross = 0.0f;
|
||||||
{
|
{
|
||||||
Element* parent = el->getParent();
|
PElement parent = el->getParent();
|
||||||
if (parent != nullptr) {
|
if (parent != nullptr) {
|
||||||
parentContentCross = axis.mainIsX
|
parentContentCross = axis.mainIsX
|
||||||
? std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom))
|
? std::max(0.0f, (float)parent->getLayoutDimensions().y - (float)(parent->getStyle().paddingTop + parent->getStyle().paddingBottom))
|
||||||
@@ -594,7 +594,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
}
|
}
|
||||||
float crossContent = 0.0f;
|
float crossContent = 0.0f;
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
crossContent = std::max(crossContent, childCrossFootprint(c, axis, parentContentCross));
|
crossContent = std::max(crossContent, childCrossFootprint(c, axis, parentContentCross));
|
||||||
}
|
}
|
||||||
// if there are no flow children, the cross content is the element's intrinsic cross.
|
// if there are no flow children, the cross content is the element's intrinsic cross.
|
||||||
@@ -621,7 +621,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
// direction to determine its axis (a Row child of a Column parent has mainIsX=true
|
// direction to determine its axis (a Row child of a Column parent has mainIsX=true
|
||||||
// even though the parent has mainIsX=false).
|
// even though the parent has mainIsX=false).
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||||
@@ -631,7 +631,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
// content-box corner. measure them (so their own children are laid out), then
|
// content-box corner. measure them (so their own children are laid out), then
|
||||||
// position by left/top offsets (right/bottom are not supported).
|
// position by left/top offsets (right/bottom are not supported).
|
||||||
for (size_t i = 0; i < kids.size(); i++) {
|
for (size_t i = 0; i < kids.size(); i++) {
|
||||||
Element* c = kids[i];
|
PElement c = kids[i];
|
||||||
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
||||||
if (c->getStyle().position != Position::Absolute) continue;
|
if (c->getStyle().position != Position::Absolute) continue;
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
@@ -655,7 +655,10 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
for (size_t i = 0; i < kids.size(); i++) {
|
for (size_t i = 0; i < kids.size(); i++) {
|
||||||
if (kids[i] == nullptr) continue;
|
if (kids[i] == nullptr) continue;
|
||||||
if (kids[i]->getStyle().display == Display::Hidden) {
|
if (kids[i]->getStyle().display == Display::Hidden) {
|
||||||
kids[i]->setLayout(Vector2(0), Vector2(0));
|
// raw pointers can be modified inside a const Array<>&, but RefPtr imposes const-ness also for the elements
|
||||||
|
// this side-steps the issue by creating a non-const RefPtr copy
|
||||||
|
PElement kid = kids[i];
|
||||||
|
kid->setLayout(Vector2(0), Vector2(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// place flow children in the content box: compute per-line packing, apply
|
// place flow children in the content box: compute per-line packing, apply
|
||||||
@@ -666,7 +669,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
// here, so its own grandchildren were laid out relative to a stale position.
|
// here, so its own grandchildren were laid out relative to a stale position.
|
||||||
// Re-run each container child's placement now that the parent position is final.
|
// Re-run each container child's placement now that the parent position is final.
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
if (c->getChildren().size() == 0) continue;
|
if (c->getChildren().size() == 0) continue;
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
if (css.position == Position::Absolute) continue;
|
if (css.position == Position::Absolute) continue;
|
||||||
@@ -674,7 +677,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||||
Flow cf;
|
Flow cf;
|
||||||
Flow::build(c, cf);
|
Flow::build(c, cf);
|
||||||
const Array<Element*>& cKids = c->getChildren();
|
const Array<OElement>& cKids = c->getChildren();
|
||||||
placeFlowChildren(c, childAxis, cf, cKids);
|
placeFlowChildren(c, childAxis, cf, cKids);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -682,7 +685,7 @@ void layoutElement(Element* el, const Axis& axis) {
|
|||||||
// the public entry point: set the root's dimensions to the viewport, then run the
|
// the public entry point: set the root's dimensions to the viewport, then run the
|
||||||
// full layout. the root has no parent, so its percent sizes are degenerate (0) —
|
// full layout. the root has no parent, so its percent sizes are degenerate (0) —
|
||||||
// the root should use explicit (px) or Auto sizes.
|
// the root should use explicit (px) or Auto sizes.
|
||||||
void layoutRoot(Element* root, UVector2 viewport) {
|
void layoutRoot(PElement root, UVector2 viewport) {
|
||||||
if (root == nullptr) return;
|
if (root == nullptr) return;
|
||||||
// the root's dimensions are the viewport (the root IS the viewport's content).
|
// the root's dimensions are the viewport (the root IS the viewport's content).
|
||||||
// the root has no parent, so resolveAxisSize will treat its percent sizes as 0
|
// the root has no parent, so resolveAxisSize will treat its percent sizes as 0
|
||||||
@@ -739,7 +742,7 @@ void layoutRoot(Element* root, UVector2 viewport) {
|
|||||||
// does *except* re-resolving the root's own size (which would use a null parent
|
// does *except* re-resolving the root's own size (which would use a null parent
|
||||||
// and a 0 percent reference, wrong for the root).
|
// and a 0 percent reference, wrong for the root).
|
||||||
Axis axis{isX, isX ? (s.direction == FlexDirection::RowReverse) : (s.direction == FlexDirection::ColumnReverse)};
|
Axis axis{isX, isX ? (s.direction == FlexDirection::RowReverse) : (s.direction == FlexDirection::ColumnReverse)};
|
||||||
const Array<Element*>& kids = root->getChildren();
|
const Array<OElement>& kids = root->getChildren();
|
||||||
if (root->getStyle().display == Display::Hidden) {
|
if (root->getStyle().display == Display::Hidden) {
|
||||||
root->setLayout(Vector2(0), Vector2(0));
|
root->setLayout(Vector2(0), Vector2(0));
|
||||||
return;
|
return;
|
||||||
@@ -750,19 +753,21 @@ void layoutRoot(Element* root, UVector2 viewport) {
|
|||||||
for (size_t i = 0; i < kids.size(); i++) {
|
for (size_t i = 0; i < kids.size(); i++) {
|
||||||
if (kids[i] == nullptr) continue;
|
if (kids[i] == nullptr) continue;
|
||||||
if (kids[i]->getStyle().display == Display::Hidden) {
|
if (kids[i]->getStyle().display == Display::Hidden) {
|
||||||
kids[i]->setLayout(Vector2(0), Vector2(0));
|
// modifyable copyied refptr, something you can do with raw pointers natively
|
||||||
|
PElement kid = kids[i];
|
||||||
|
kid->setLayout(Vector2(0), Vector2(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// measure the flow children (recursively) and the absolute children.
|
// measure the flow children (recursively) and the absolute children.
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
bool cIsX = (css.direction == FlexDirection::Row || css.direction == FlexDirection::RowReverse);
|
||||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||||
layoutElement(c, childAxis);
|
layoutElement(c, childAxis);
|
||||||
}
|
}
|
||||||
for (size_t i = 0; i < kids.size(); i++) {
|
for (size_t i = 0; i < kids.size(); i++) {
|
||||||
Element* c = kids[i];
|
PElement c = kids[i];
|
||||||
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
if (c == nullptr || c->getStyle().display == Display::Hidden) continue;
|
||||||
if (c->getStyle().position != Position::Absolute) continue;
|
if (c->getStyle().position != Position::Absolute) continue;
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
@@ -779,7 +784,7 @@ void layoutRoot(Element* root, UVector2 viewport) {
|
|||||||
// Same fix as in layoutElement: container children were measured before their
|
// Same fix as in layoutElement: container children were measured before their
|
||||||
// position was set, so re-run their placement with the now-final position.
|
// position was set, so re-run their placement with the now-final position.
|
||||||
for (size_t k = 0; k < flow.size(); k++) {
|
for (size_t k = 0; k < flow.size(); k++) {
|
||||||
Element* c = kids[flow[k]];
|
PElement c = kids[flow[k]];
|
||||||
if (c->getChildren().size() == 0) continue;
|
if (c->getChildren().size() == 0) continue;
|
||||||
const Style& css = c->getStyle();
|
const Style& css = c->getStyle();
|
||||||
if (css.position == Position::Absolute) continue;
|
if (css.position == Position::Absolute) continue;
|
||||||
@@ -787,7 +792,7 @@ void layoutRoot(Element* root, UVector2 viewport) {
|
|||||||
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
Axis childAxis{cIsX, cIsX ? (css.direction == FlexDirection::RowReverse) : (css.direction == FlexDirection::ColumnReverse)};
|
||||||
Flow cf;
|
Flow cf;
|
||||||
Flow::build(c, cf);
|
Flow::build(c, cf);
|
||||||
const Array<Element*>& cKids = c->getChildren();
|
const Array<OElement>& cKids = c->getChildren();
|
||||||
placeFlowChildren(c, childAxis, cf, cKids);
|
placeFlowChildren(c, childAxis, cf, cKids);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ namespace Seele {
|
|||||||
namespace UI {
|
namespace UI {
|
||||||
// forward decl: the full class lives in `UI/Element.h` (which includes this header).
|
// forward decl: the full class lives in `UI/Element.h` (which includes this header).
|
||||||
// only used as a pointer/reference here, so the forward decl is sufficient.
|
// only used as a pointer/reference here, so the forward decl is sufficient.
|
||||||
class Element;
|
DECLARE_REF(Element)
|
||||||
namespace FlexLayout {
|
namespace FlexLayout {
|
||||||
// one flex container's resolved main/cross geometry, passed down the recursion.
|
// one flex container's resolved main/cross geometry, passed down the recursion.
|
||||||
// `mainIsX` is true for row/row-reverse (main axis = x). `cMain`/`cCross` are the
|
// `mainIsX` is true for row/row-reverse (main axis = x). `cMain`/`cCross` are the
|
||||||
@@ -62,7 +62,7 @@ struct Axis {
|
|||||||
|
|
||||||
// per-item scratch, indexed by position in `items` (the order-sorted flow list).
|
// per-item scratch, indexed by position in `items` (the order-sorted flow list).
|
||||||
struct Item {
|
struct Item {
|
||||||
Element* el = nullptr;
|
PElement el = nullptr;
|
||||||
int32 order = 0;
|
int32 order = 0;
|
||||||
float basis = 0.f; // main size before grow/shrink (min/max clamped)
|
float basis = 0.f; // main size before grow/shrink (min/max clamped)
|
||||||
float grow = 0.f, shrink = 1.f;
|
float grow = 0.f, shrink = 1.f;
|
||||||
@@ -82,7 +82,7 @@ struct Item {
|
|||||||
// viewport at the root). Resolves the element's own main/cross size (measure), then
|
// viewport at the root). Resolves the element's own main/cross size (measure), then
|
||||||
// lays out its children (place), recursing into each flow child with the child's
|
// lays out its children (place), recursing into each flow child with the child's
|
||||||
// *own* resolved size as its containing box.
|
// *own* resolved size as its containing box.
|
||||||
void layoutElement(Element* el, const Axis& axis);
|
void layoutElement(PElement el, const Axis& axis);
|
||||||
|
|
||||||
// public entry: lay out the whole tree. `root` is the viewport's only child; the
|
// public entry: lay out the whole tree. `root` is the viewport's only child; the
|
||||||
// viewport's dimensions are `viewport`. `root->position` is left untouched (the
|
// viewport's dimensions are `viewport`. `root->position` is left untouched (the
|
||||||
@@ -91,7 +91,7 @@ void layoutElement(Element* el, const Axis& axis);
|
|||||||
// declared here, defined in FlexLayout.cpp (the body dereferences `root->style`,
|
// declared here, defined in FlexLayout.cpp (the body dereferences `root->style`,
|
||||||
// which needs the complete Element type — not available in this header, which only
|
// which needs the complete Element type — not available in this header, which only
|
||||||
// forward-declares Element to avoid a circular include with Element.h).
|
// forward-declares Element to avoid a circular include with Element.h).
|
||||||
void layoutRoot(Element* root, UVector2 viewport);
|
void layoutRoot(PElement root, UVector2 viewport);
|
||||||
} // namespace FlexLayout
|
} // namespace FlexLayout
|
||||||
} // namespace UI
|
} // namespace UI
|
||||||
} // namespace Seele
|
} // namespace Seele
|
||||||
+15
-15
@@ -6,7 +6,7 @@
|
|||||||
using namespace Seele;
|
using namespace Seele;
|
||||||
using namespace Seele::UI;
|
using namespace Seele::UI;
|
||||||
|
|
||||||
void System::markAllDirty(Element* element) {
|
void System::markAllDirty(PElement element) {
|
||||||
if (element == nullptr) {
|
if (element == nullptr) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ void System::markAllDirty(Element* element) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void System::styleRec(Element* element) {
|
void System::styleRec(PElement element) {
|
||||||
if (element == nullptr) {
|
if (element == nullptr) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ void System::styleRec(Element* element) {
|
|||||||
// theme change (fonts are per-theme) without a friend declaration.
|
// theme change (fonts are per-theme) without a friend declaration.
|
||||||
element->setTheme(theme);
|
element->setTheme(theme);
|
||||||
// runtime interaction state overrides the static style (data, not template args)
|
// runtime interaction state overrides the static style (data, not template args)
|
||||||
if (auto* button = dynamic_cast<Button<>* >(element)) {
|
if (auto* button = dynamic_cast<Button<>*>(element.getHandle())) {
|
||||||
if (button->isFocused()) {
|
if (button->isFocused()) {
|
||||||
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
||||||
}
|
}
|
||||||
@@ -41,7 +41,7 @@ void System::styleRec(Element* element) {
|
|||||||
element->themeChanged = false;
|
element->themeChanged = false;
|
||||||
element->applyStyle({}, theme);
|
element->applyStyle({}, theme);
|
||||||
// interaction state is a per-frame override; re-apply it after the static resolve
|
// interaction state is a per-frame override; re-apply it after the static resolve
|
||||||
if (auto* button = dynamic_cast<Button<>* >(element)) {
|
if (auto* button = dynamic_cast<Button<>* >(element.getHandle())) {
|
||||||
if (button->isFocused()) {
|
if (button->isFocused()) {
|
||||||
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
element->style.backgroundColor = theme.color(ColorToken::Gray700);
|
||||||
}
|
}
|
||||||
@@ -59,23 +59,23 @@ void System::styleRec(Element* element) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Element* System::hitTest(Vector2 position) {
|
PElement System::hitTest(Vector2 position) {
|
||||||
// walk the last rendered list; later entries are drawn on top, so the last
|
// walk the last rendered list; later entries are drawn on top, so the last
|
||||||
// hit is the top-most element
|
// hit is the top-most element
|
||||||
Element* result = nullptr;
|
PElement result = nullptr;
|
||||||
for (auto& render : renderElements) {
|
for (auto& render : renderElements) {
|
||||||
if (render.element == nullptr) {
|
if (render.element == nullptr) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (position.x >= render.position.x && position.x < render.position.x + render.dimensions.x &&
|
if (position.x >= render.position.x && position.x < render.position.x + render.dimensions.x &&
|
||||||
position.y >= render.position.y && position.y < render.position.y + render.dimensions.y) {
|
position.y >= render.position.y && position.y < render.position.y + render.dimensions.y) {
|
||||||
result = render.element.operator->();
|
result = render.element;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
void System::collectFocusable(Element* element, Array<Element*>& out) {
|
void System::collectFocusable(PElement element, Array<PElement>& out) {
|
||||||
if (element == nullptr || element->style.display == Display::Hidden) {
|
if (element == nullptr || element->style.display == Display::Hidden) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -89,13 +89,13 @@ void System::collectFocusable(Element* element, Array<Element*>& out) {
|
|||||||
|
|
||||||
void System::processInput() {
|
void System::processInput() {
|
||||||
// hover transitions: the virtual setHovered keeps this free of dynamic_cast
|
// hover transitions: the virtual setHovered keeps this free of dynamic_cast
|
||||||
Element* under = hitTest(mousePos);
|
PElement under = hitTest(mousePos);
|
||||||
if (under != hovered) {
|
if (under != hovered) {
|
||||||
if (hovered) {
|
if (hovered != nullptr) {
|
||||||
hovered->setHovered(false);
|
hovered->setHovered(false);
|
||||||
}
|
}
|
||||||
hovered = under;
|
hovered = under;
|
||||||
if (hovered) {
|
if (hovered != nullptr) {
|
||||||
hovered->setHovered(true);
|
hovered->setHovered(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -107,7 +107,7 @@ void System::mouseMove(Vector2 position) {
|
|||||||
|
|
||||||
void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Vector2 position) {
|
void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Vector2 position) {
|
||||||
mousePos = position;
|
mousePos = position;
|
||||||
Element* under = hitTest(position);
|
PElement under = hitTest(position);
|
||||||
if (under == nullptr) {
|
if (under == nullptr) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -115,7 +115,7 @@ void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Ve
|
|||||||
Vector2 local = position;
|
Vector2 local = position;
|
||||||
{
|
{
|
||||||
// walk up from the hit element, subtracting each parent's position
|
// walk up from the hit element, subtracting each parent's position
|
||||||
auto* walk = under;
|
auto walk = under;
|
||||||
while (walk != nullptr) {
|
while (walk != nullptr) {
|
||||||
local.x -= walk->position.x;
|
local.x -= walk->position.x;
|
||||||
local.y -= walk->position.y;
|
local.y -= walk->position.y;
|
||||||
@@ -131,7 +131,7 @@ void System::mouseButton(MouseButton button, InputAction action, KeyModifier, Ve
|
|||||||
}
|
}
|
||||||
|
|
||||||
void System::scroll(Vector2 delta) {
|
void System::scroll(Vector2 delta) {
|
||||||
Element* under = hitTest(mousePos);
|
PElement under = hitTest(mousePos);
|
||||||
if (under == nullptr) {
|
if (under == nullptr) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ void System::key(KeyCode code, InputAction action, KeyModifier modifier, char te
|
|||||||
if (action == InputAction::PRESS && code == KeyCode::KEY_TAB) {
|
if (action == InputAction::PRESS && code == KeyCode::KEY_TAB) {
|
||||||
// cycle focus among focusable elements (buttons); the virtual setFocused
|
// cycle focus among focusable elements (buttons); the virtual setFocused
|
||||||
// keeps this free of dynamic_cast to a concrete template type
|
// keeps this free of dynamic_cast to a concrete template type
|
||||||
Array<Element*> focusable;
|
Array<PElement> focusable;
|
||||||
collectFocusable(rootElement.operator->(), focusable);
|
collectFocusable(rootElement.operator->(), focusable);
|
||||||
if (focusable.size() > 0) {
|
if (focusable.size() > 0) {
|
||||||
int32 index = -1;
|
int32 index = -1;
|
||||||
|
|||||||
@@ -39,12 +39,12 @@ class System {
|
|||||||
PElement getRoot() { return rootElement; }
|
PElement getRoot() { return rootElement; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void styleRec(Element* element);
|
void styleRec(PElement element);
|
||||||
static void markAllDirty(Element* element);
|
static void markAllDirty(PElement element);
|
||||||
// hit-test the last rendered list, top-most wins; returns the element under `position`
|
// hit-test the last rendered list, top-most wins; returns the element under `position`
|
||||||
Element* hitTest(Vector2 position);
|
PElement hitTest(Vector2 position);
|
||||||
// walks the tree in layout order, collecting focusable elements (for tab navigation)
|
// walks the tree in layout order, collecting focusable elements (for tab navigation)
|
||||||
void collectFocusable(Element* element, Array<Element*>& out);
|
void collectFocusable(PElement element, Array<PElement>& out);
|
||||||
|
|
||||||
OElement rootElement;
|
OElement rootElement;
|
||||||
Theme theme;
|
Theme theme;
|
||||||
@@ -52,8 +52,8 @@ class System {
|
|||||||
bool layoutDirty = true;
|
bool layoutDirty = true;
|
||||||
// input state
|
// input state
|
||||||
Vector2 mousePos = Vector2(0);
|
Vector2 mousePos = Vector2(0);
|
||||||
Element* hovered = nullptr;
|
PElement hovered = nullptr;
|
||||||
Element* focused = nullptr;
|
PElement focused = nullptr;
|
||||||
Array<UIRender> renderElements;
|
Array<UIRender> renderElements;
|
||||||
};
|
};
|
||||||
DEFINE_REF(System)
|
DEFINE_REF(System)
|
||||||
|
|||||||
+169
-131
@@ -3,7 +3,6 @@
|
|||||||
#include "gtest/gtest.h"
|
#include "gtest/gtest.h"
|
||||||
#include "UI/Element.h"
|
#include "UI/Element.h"
|
||||||
#include "UI/Element/Div.h"
|
#include "UI/Element/Div.h"
|
||||||
#include "UI/Element/Text.h"
|
|
||||||
#include "UI/FlexLayout.h"
|
#include "UI/FlexLayout.h"
|
||||||
#include "UI/Style/Class.h"
|
#include "UI/Style/Class.h"
|
||||||
#include "UI/Style/Theme.h"
|
#include "UI/Style/Theme.h"
|
||||||
@@ -15,315 +14,354 @@ using namespace Seele::UI;
|
|||||||
// mark the whole subtree dirty first so the Div template classes (applied in
|
// mark the whole subtree dirty first so the Div template classes (applied in
|
||||||
// applyStyle, gated on style.dirty/themeChanged) actually run — a freshly built tree
|
// applyStyle, gated on style.dirty/themeChanged) actually run — a freshly built tree
|
||||||
// has neither flag set. tests use explicit sizes, so the font is never shaped.
|
// has neither flag set. tests use explicit sizes, so the font is never shaped.
|
||||||
static void markAllDirtyRec(Element* el) {
|
static void markAllDirtyRec(PElement el) {
|
||||||
if (el == nullptr) return;
|
if (el == nullptr) return;
|
||||||
el->markDirty();
|
el->markDirty();
|
||||||
for (auto* c : el->getChildren()) markAllDirtyRec(c);
|
// children are OwningPtr (move-only) — iterate by const ref, never copy.
|
||||||
|
for (const auto& c : el->getChildren()) markAllDirtyRec(c);
|
||||||
}
|
}
|
||||||
static void resolveStyles(Element* root) {
|
static void resolveStyles(PElement root) {
|
||||||
markAllDirtyRec(root);
|
markAllDirtyRec(root);
|
||||||
Theme theme{};
|
Theme theme{};
|
||||||
root->calcStyle(Style{}, theme);
|
root->calcStyle(Style{}, theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
// layout a caller-owned tree against `viewport` (the tree is never deleted here).
|
// layout a caller-owned tree against `viewport` (the tree is never deleted here).
|
||||||
static void layout(Element* root, int vw, int vh) {
|
static void layout(PElement root, int vw, int vh) {
|
||||||
FlexLayout::layoutRoot(root, UVector2(vw, vh));
|
FlexLayout::layoutRoot(root, UVector2(vw, vh));
|
||||||
}
|
}
|
||||||
|
|
||||||
// (a) row, fixed sizes, gap, justify start/end/center
|
// (a) row, fixed sizes, gap, justify start/end/center
|
||||||
TEST(FlexLayout, RowGapJustify) {
|
TEST(FlexLayout, RowGapJustify) {
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* b = new Div<W_64, H_32>(Attributes{});
|
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// two 64px items + 8px gap, start-justified: x=0 and x=72, y=0, cross stretch?
|
// two 64px items + 8px gap, start-justified: x=0 and x=72, y=0, cross stretch?
|
||||||
// items have explicit H_32, so no stretch (explicit wins); align default = stretch
|
// items have explicit H_32, so no stretch (explicit wins); align default = stretch
|
||||||
// but explicit size wins -> y=0, h=32.
|
// but explicit size wins -> y=0, h=32.
|
||||||
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 72.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutDimensions().y, 32.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutDimensions().y, 32.0f, 0.01f);
|
||||||
|
|
||||||
// end-justified: last item flush to the right edge
|
// end-justified: last item flush to the right edge
|
||||||
Element* c = new Div<W_64, H_32>(Attributes{});
|
OElement c = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* d = new Div<W_64, H_32>(Attributes{});
|
OElement d = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* end = new Div<FlexRow, G_8, Justify_End, W_Full, H_Full>({Attributes{}}, {c, d});
|
PElement cRef = c;
|
||||||
|
PElement dRef = d;
|
||||||
|
OElement end = new Div<FlexRow, G_8, Justify_End, W_Full, H_Full>({Attributes{}}, {std::move(c), std::move(d)});
|
||||||
resolveStyles(end);
|
resolveStyles(end);
|
||||||
layout(end, 300, 100);
|
layout(end, 300, 100);
|
||||||
// total = 64 + 8 + 64 = 136; start at 300 - 136 = 164
|
// total = 64 + 8 + 64 = 136; start at 300 - 136 = 164
|
||||||
EXPECT_NEAR(c->getLayoutPosition().x, 164.0f, 0.01f);
|
EXPECT_NEAR(cRef->getLayoutPosition().x, 164.0f, 0.01f);
|
||||||
EXPECT_NEAR(d->getLayoutPosition().x, 164.0f + 72.0f, 0.01f);
|
EXPECT_NEAR(dRef->getLayoutPosition().x, 164.0f + 72.0f, 0.01f);
|
||||||
|
|
||||||
// center-justified
|
// center-justified
|
||||||
Element* e = new Div<W_64, H_32>(Attributes{});
|
OElement e = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* f = new Div<W_64, H_32>(Attributes{});
|
OElement f = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* center = new Div<FlexRow, G_8, Justify_Center, W_Full, H_Full>({Attributes{}}, {e, f});
|
PElement eRef = e;
|
||||||
|
PElement fRef = f;
|
||||||
|
OElement center = new Div<FlexRow, G_8, Justify_Center, W_Full, H_Full>({Attributes{}}, {std::move(e), std::move(f)});
|
||||||
resolveStyles(center);
|
resolveStyles(center);
|
||||||
layout(center, 300, 100);
|
layout(center, 300, 100);
|
||||||
// free = 300 - 136 = 164; center offset = 82
|
// free = 300 - 136 = 164; center offset = 82
|
||||||
EXPECT_NEAR(e->getLayoutPosition().x, 82.0f, 0.01f);
|
EXPECT_NEAR(eRef->getLayoutPosition().x, 82.0f, 0.01f);
|
||||||
EXPECT_NEAR(f->getLayoutPosition().x, 82.0f + 72.0f, 0.01f);
|
EXPECT_NEAR(fRef->getLayoutPosition().x, 82.0f + 72.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (b) column: default direction stacks top-to-bottom
|
// (b) column: default direction stacks top-to-bottom
|
||||||
TEST(FlexLayout, ColumnDefault) {
|
TEST(FlexLayout, ColumnDefault) {
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* b = new Div<W_64, H_32>(Attributes{});
|
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().y, 32.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().y, 32.0f, 0.01f);
|
||||||
// stretch is the default: a W_64 item stays 64 wide (explicit wins); y is packed
|
// stretch is the default: a W_64 item stays 64 wide (explicit wins); y is packed
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (c) one child with Grow absorbs all the free space
|
// (c) one child with Grow absorbs all the free space
|
||||||
TEST(FlexLayout, GrowAbsorbsFreeSpace) {
|
TEST(FlexLayout, GrowAbsorbsFreeSpace) {
|
||||||
Element* fixed = new Div<W_48, H_32>(Attributes{});
|
OElement fixed = new Div<W_48, H_32>(Attributes{});
|
||||||
auto* grow = new Div<Grow, H_32>(Attributes{});
|
OElement grow = new Div<Grow, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {fixed, grow});
|
PElement fixedRef = fixed;
|
||||||
|
PElement growRef = grow;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(fixed), std::move(grow)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 200, 100);
|
layout(root, 200, 100);
|
||||||
EXPECT_NEAR(fixed->getLayoutDimensions().x, 48.0f, 0.01f);
|
EXPECT_NEAR(fixedRef->getLayoutDimensions().x, 48.0f, 0.01f);
|
||||||
EXPECT_NEAR(grow->getLayoutPosition().x, 48.0f, 0.01f);
|
EXPECT_NEAR(growRef->getLayoutPosition().x, 48.0f, 0.01f);
|
||||||
// 200 - 48 free goes to the grower
|
// 200 - 48 free goes to the grower
|
||||||
EXPECT_NEAR(grow->getLayoutDimensions().x, 152.0f, 0.01f);
|
EXPECT_NEAR(growRef->getLayoutDimensions().x, 152.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (d) two growers split free space proportionally
|
// (d) two growers split free space proportionally
|
||||||
TEST(FlexLayout, GrowSplitsProportionally) {
|
TEST(FlexLayout, GrowSplitsProportionally) {
|
||||||
auto* g1 = new Div<Grow, H_32>(Attributes{}); // weight 1
|
OElement g1 = new Div<Grow, H_32>(Attributes{}); // weight 1
|
||||||
auto* g2 = new Div<Grow_2, H_32>(Attributes{}); // weight 2
|
OElement g2 = new Div<Grow_2, H_32>(Attributes{}); // weight 2
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {g1, g2});
|
PElement g1Ref = g1;
|
||||||
|
PElement g2Ref = g2;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(g1), std::move(g2)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// 300 total, weights 1:2 -> 100 / 200
|
// 300 total, weights 1:2 -> 100 / 200
|
||||||
EXPECT_NEAR(g1->getLayoutDimensions().x, 100.0f, 0.01f);
|
EXPECT_NEAR(g1Ref->getLayoutDimensions().x, 100.0f, 0.01f);
|
||||||
EXPECT_NEAR(g2->getLayoutPosition().x, 100.0f, 0.01f);
|
EXPECT_NEAR(g2Ref->getLayoutPosition().x, 100.0f, 0.01f);
|
||||||
EXPECT_NEAR(g2->getLayoutDimensions().x, 200.0f, 0.01f);
|
EXPECT_NEAR(g2Ref->getLayoutDimensions().x, 200.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (e) overflow: a Shrink_0 item keeps its basis; the default-shrink item absorbs the deficit
|
// (e) overflow: a Shrink_0 item keeps its basis; the default-shrink item absorbs the deficit
|
||||||
TEST(FlexLayout, ShrinkDeficit) {
|
TEST(FlexLayout, ShrinkDeficit) {
|
||||||
auto* keep = new Div<Shrink_0, H_32>(Attributes{}); // refuses to shrink
|
OElement keep = new Div<Shrink_0, H_32>(Attributes{}); // refuses to shrink
|
||||||
keep->setIntrinsicSize(150.0f, 32.0f); // natural main size 150
|
keep->setIntrinsicSize(150.0f, 32.0f); // natural main size 150
|
||||||
auto* shrink = new Div<H_32>(Attributes{}); // default shrink=1
|
OElement shrink = new Div<H_32>(Attributes{}); // default shrink=1
|
||||||
shrink->setIntrinsicSize(150.0f, 32.0f);
|
shrink->setIntrinsicSize(150.0f, 32.0f);
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {keep, shrink});
|
PElement keepRef = keep;
|
||||||
|
PElement shrinkRef = shrink;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(keep), std::move(shrink)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 180, 100);
|
layout(root, 180, 100);
|
||||||
// total basis 300 in a 180 box: deficit 120 falls entirely on the shrinker (weight 1 vs 0)
|
// total basis 300 in a 180 box: deficit 120 falls entirely on the shrinker (weight 1 vs 0)
|
||||||
EXPECT_NEAR(keep->getLayoutDimensions().x, 150.0f, 0.01f);
|
EXPECT_NEAR(keepRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||||
EXPECT_NEAR(keep->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(keepRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(shrink->getLayoutPosition().x, 150.0f, 0.01f);
|
EXPECT_NEAR(shrinkRef->getLayoutPosition().x, 150.0f, 0.01f);
|
||||||
EXPECT_NEAR(shrink->getLayoutDimensions().x, 30.0f, 0.01f);
|
EXPECT_NEAR(shrinkRef->getLayoutDimensions().x, 30.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (f) wrap: items that don't fit the line flow onto the next line
|
// (f) wrap: items that don't fit the line flow onto the next line
|
||||||
TEST(FlexLayout, Wrap) {
|
TEST(FlexLayout, Wrap) {
|
||||||
// 150px items in a 200px row with wrap: item 2 can't share line 0 (150+8+150 > 200)
|
// 150px items in a 200px row with wrap: item 2 can't share line 0 (150+8+150 > 200)
|
||||||
Element* a = new Div<W_150, H_32>(Attributes{});
|
OElement a = new Div<W_150, H_32>(Attributes{});
|
||||||
Element* b = new Div<W_150, H_32>(Attributes{});
|
OElement b = new Div<W_150, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, Wrap, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<FlexRow, Wrap, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 200, 300);
|
layout(root, 200, 300);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||||
// line 1 starts below line 0: line0 cross = 32, + gap 8 -> y = 40
|
// line 1 starts below line 0: line0 cross = 32, + gap 8 -> y = 40
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().y, 40.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().y, 40.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (g) align-items: start/center/end on the cross axis (items keep their explicit cross size)
|
// (g) align-items: start/center/end on the cross axis (items keep their explicit cross size)
|
||||||
TEST(FlexLayout, AlignItems) {
|
TEST(FlexLayout, AlignItems) {
|
||||||
// start: item at the top of a 200px-tall row
|
// start: item at the top of a 200px-tall row
|
||||||
{
|
{
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().y, 32.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().y, 32.0f, 0.01f);
|
||||||
}
|
}
|
||||||
// center: item vertically centered
|
// center: item vertically centered
|
||||||
{
|
{
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, Items_Center, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, Items_Center, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
||||||
}
|
}
|
||||||
// end: item at the bottom
|
// end: item at the bottom
|
||||||
{
|
{
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, Items_End, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, Items_End, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 200.0f - 32.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 200.0f - 32.0f, 0.01f);
|
||||||
}
|
}
|
||||||
// stretch: an Auto-height item fills the cross axis (default items is stretch,
|
// stretch: an Auto-height item fills the cross axis (default items is stretch,
|
||||||
// so a bare container already does this; assert it explicitly)
|
// so a bare container already does this; assert it explicitly)
|
||||||
{
|
{
|
||||||
auto* a = new Div<W_64>(Attributes{});
|
OElement a = new Div<W_64>(Attributes{});
|
||||||
a->setIntrinsicSize(64.0f, 32.0f);
|
a->setIntrinsicSize(64.0f, 32.0f);
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().y, 200.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().y, 200.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 0.0f, 0.01f);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// (h) order reorders flow items (layout order, not DOM order)
|
// (h) order reorders flow items (layout order, not DOM order)
|
||||||
TEST(FlexLayout, Order) {
|
TEST(FlexLayout, Order) {
|
||||||
Element* a = new Div<W_64, H_32, Order_2>(Attributes{});
|
OElement a = new Div<W_64, H_32, Order_2>(Attributes{});
|
||||||
Element* b = new Div<W_64, H_32, Order_1>(Attributes{});
|
OElement b = new Div<W_64, H_32, Order_1>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// b (order 1) comes before a (order 2)
|
// b (order 1) comes before a (order 2)
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().x, 72.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// align-self override: the item's own align beats the container's
|
// align-self override: the item's own align beats the container's
|
||||||
TEST(FlexLayout, AlignSelfOverride) {
|
TEST(FlexLayout, AlignSelfOverride) {
|
||||||
Element* a = new Div<W_64, H_32, Self_Center>(Attributes{});
|
OElement a = new Div<W_64, H_32, Self_Center>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, Items_Start, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 200);
|
layout(root, 300, 200);
|
||||||
// container says start (y=0), the item overrides to center
|
// container says start (y=0), the item overrides to center
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, (200.0f - 32.0f) * 0.5f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (i) percent basis: Basis_50Percent resolves against the container's content main
|
// (i) percent basis: Basis_50Percent resolves against the container's content main
|
||||||
TEST(FlexLayout, PercentBasis) {
|
TEST(FlexLayout, PercentBasis) {
|
||||||
auto* a = new Div<Basis_50Percent, H_32>(Attributes{});
|
OElement a = new Div<Basis_50Percent, H_32>(Attributes{});
|
||||||
auto* b = new Div<Basis_50Percent, H_32>(Attributes{});
|
OElement b = new Div<Basis_50Percent, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// each item's basis = 50% of 300 = 150; no free space, no grow -> stays 150
|
// each item's basis = 50% of 300 = 150; no free space, no grow -> stays 150
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().x, 150.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 150.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 150.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutDimensions().x, 150.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutDimensions().x, 150.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (j) min/max clamps: an explicit size is clamped to [min, max]
|
// (j) min/max clamps: an explicit size is clamped to [min, max]
|
||||||
TEST(FlexLayout, MinMaxClamp) {
|
TEST(FlexLayout, MinMaxClamp) {
|
||||||
// maxWidth 64 clamps a 100px explicit width down to 64
|
// maxWidth 64 clamps a 100px explicit width down to 64
|
||||||
{
|
{
|
||||||
Element* a = new Div<W_100, MaxWidthClass<64, DimensionType::Pixel>, H_32>(Attributes{});
|
OElement a = new Div<W_100, MaxWidthClass<64, DimensionType::Pixel>, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().x, 64.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().x, 64.0f, 0.01f);
|
||||||
}
|
}
|
||||||
// minWidth 80 clamps a 40px explicit width up to 80. set AFTER resolveStyles:
|
// minWidth 80 clamps a 40px explicit width up to 80. set AFTER resolveStyles:
|
||||||
// applyStyle resets non-inherited fields (minWidth etc) to defaults, so a
|
// applyStyle resets non-inherited fields (minWidth etc) to defaults, so a
|
||||||
// pre-set minWidth would be clobbered by the re-style. layout reads the style
|
// pre-set minWidth would be clobbered by the re-style. layout reads the style
|
||||||
// at layout time, so a post-resolve mutation is honored.
|
// at layout time, so a post-resolve mutation is honored.
|
||||||
{
|
{
|
||||||
auto* a = new Div<W_40, H_32>(Attributes{});
|
OElement a = new Div<W_40, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {a});
|
PElement aRef = a;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(a)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
a->getStyle().minWidth = 80;
|
aRef->getStyle().minWidth = 80;
|
||||||
a->getStyle().minWidthType = DimensionType::Pixel;
|
aRef->getStyle().minWidthType = DimensionType::Pixel;
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
EXPECT_NEAR(a->getLayoutDimensions().x, 80.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutDimensions().x, 80.0f, 0.01f);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// (k) position:relative: offset applied on top of the flow position
|
// (k) position:relative: offset applied on top of the flow position
|
||||||
TEST(FlexLayout, RelativeOffset) {
|
TEST(FlexLayout, RelativeOffset) {
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* b = new Div<W_64, H_32>(Attributes{});
|
OElement b = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, b});
|
PElement aRef = a;
|
||||||
|
PElement bRef = b;
|
||||||
|
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(b)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
||||||
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
||||||
// reads the style at layout time, so a post-resolve mutation is honored.
|
// reads the style at layout time, so a post-resolve mutation is honored.
|
||||||
a->getStyle().position = Position::Relative;
|
aRef->getStyle().position = Position::Relative;
|
||||||
a->getStyle().left = 10;
|
aRef->getStyle().left = 10;
|
||||||
a->getStyle().top = 5;
|
aRef->getStyle().top = 5;
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// a is still in the flow at x=0 but drawn offset by (10, 5); b is unaffected
|
// a is still in the flow at x=0 but drawn offset by (10, 5); b is unaffected
|
||||||
EXPECT_NEAR(a->getLayoutPosition().x, 10.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().x, 10.0f, 0.01f);
|
||||||
EXPECT_NEAR(a->getLayoutPosition().y, 5.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().y, 5.0f, 0.01f);
|
||||||
EXPECT_NEAR(b->getLayoutPosition().x, 72.0f, 0.01f);
|
EXPECT_NEAR(bRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (l) position:absolute: removed from the flow, positioned from the container's content corner
|
// (l) position:absolute: removed from the flow, positioned from the container's content corner
|
||||||
TEST(FlexLayout, AbsolutePosition) {
|
TEST(FlexLayout, AbsolutePosition) {
|
||||||
auto* abs = new Div<W_32, H_32>(Attributes{});
|
OElement abs = new Div<W_32, H_32>(Attributes{});
|
||||||
Element* flow = new Div<W_64, H_32>(Attributes{});
|
OElement flow = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {abs, flow});
|
PElement absRef = abs;
|
||||||
|
PElement flowRef = flow;
|
||||||
|
OElement root = new Div<FlexRow, W_Full, H_Full>({Attributes{}}, {std::move(abs), std::move(flow)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
// set position/left/top AFTER resolveStyles: applyStyle resets position to
|
||||||
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
// Static and left/top to 0, so pre-set values would be clobbered. layout
|
||||||
// reads the style at layout time, so a post-resolve mutation is honored.
|
// reads the style at layout time, so a post-resolve mutation is honored.
|
||||||
abs->getStyle().position = Position::Absolute;
|
absRef->getStyle().position = Position::Absolute;
|
||||||
abs->getStyle().left = 12;
|
absRef->getStyle().left = 12;
|
||||||
abs->getStyle().top = 7;
|
absRef->getStyle().top = 7;
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// the absolute item is out of the flow: the flow item takes the full line
|
// the absolute item is out of the flow: the flow item takes the full line
|
||||||
EXPECT_NEAR(flow->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(flowRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
// absolute is at the container's content corner + (left, top); the container has
|
// absolute is at the container's content corner + (left, top); the container has
|
||||||
// no padding, so it's exactly (12, 7) in the container's parent space.
|
// no padding, so it's exactly (12, 7) in the container's parent space.
|
||||||
EXPECT_NEAR(abs->getLayoutPosition().x, 12.0f, 0.01f);
|
EXPECT_NEAR(absRef->getLayoutPosition().x, 12.0f, 0.01f);
|
||||||
EXPECT_NEAR(abs->getLayoutPosition().y, 7.0f, 0.01f);
|
EXPECT_NEAR(absRef->getLayoutPosition().y, 7.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (m) nested flex: a Div-in-Div with its own children lays out correctly at both levels
|
// (m) nested flex: a Div-in-Div with its own children lays out correctly at both levels
|
||||||
TEST(FlexLayout, NestedFlex) {
|
TEST(FlexLayout, NestedFlex) {
|
||||||
// inner row of two 32px items; outer column stacks it with a sibling
|
// inner row of two 32px items; outer column stacks it with a sibling
|
||||||
Element* in1 = new Div<W_32, H_16>(Attributes{});
|
OElement in1 = new Div<W_32, H_16>(Attributes{});
|
||||||
Element* in2 = new Div<W_32, H_16>(Attributes{});
|
OElement in2 = new Div<W_32, H_16>(Attributes{});
|
||||||
|
PElement in1Ref = in1;
|
||||||
|
PElement in2Ref = in2;
|
||||||
// inner is W_Full (fills the outer's content width) but Auto height:
|
// inner is W_Full (fills the outer's content width) but Auto height:
|
||||||
// its cross size falls back to the content measurement (max child = 16).
|
// its cross size falls back to the content measurement (max child = 16).
|
||||||
// an explicit H_Full would resolve to 100% of the outer's 100px height,
|
// an explicit H_Full would resolve to 100% of the outer's 100px height,
|
||||||
// which is wrong for this test — the inner should size to its children.
|
// which is wrong for this test — the inner should size to its children.
|
||||||
auto* inner = new Div<FlexRow, W_Full>({Attributes{}}, {in1, in2});
|
OElement inner = new Div<FlexRow, W_Full>({Attributes{}}, {std::move(in1), std::move(in2)});
|
||||||
auto* sibling = new Div<W_Full, H_24>(Attributes{});
|
PElement innerRef = inner;
|
||||||
auto* outer = new Div<W_Full, H_Full, P_4>({Attributes{}}, {inner, sibling});
|
OElement sibling = new Div<W_Full, H_24>(Attributes{});
|
||||||
|
PElement siblingRef = sibling;
|
||||||
|
OElement outer = new Div<W_Full, H_Full, P_4>({Attributes{}}, {std::move(inner), std::move(sibling)});
|
||||||
resolveStyles(outer);
|
resolveStyles(outer);
|
||||||
layout(outer, 200, 100);
|
layout(outer, 200, 100);
|
||||||
// outer has P_4 padding: content origin at (4, 4). inner is W_Full -> fills
|
// outer has P_4 padding: content origin at (4, 4). inner is W_Full -> fills
|
||||||
// the 200-8=192 wide content; its H is Auto -> content height = max child = 16.
|
// the 200-8=192 wide content; its H is Auto -> content height = max child = 16.
|
||||||
EXPECT_NEAR(inner->getLayoutPosition().x, 4.0f, 0.01f);
|
EXPECT_NEAR(innerRef->getLayoutPosition().x, 4.0f, 0.01f);
|
||||||
EXPECT_NEAR(inner->getLayoutPosition().y, 4.0f, 0.01f);
|
EXPECT_NEAR(innerRef->getLayoutPosition().y, 4.0f, 0.01f);
|
||||||
EXPECT_NEAR(inner->getLayoutDimensions().x, 192.0f, 0.01f);
|
EXPECT_NEAR(innerRef->getLayoutDimensions().x, 192.0f, 0.01f);
|
||||||
EXPECT_NEAR(inner->getLayoutDimensions().y, 16.0f, 0.01f);
|
EXPECT_NEAR(innerRef->getLayoutDimensions().y, 16.0f, 0.01f);
|
||||||
// sibling stacks below inner: y = 4 + 16 + 0 (no gap) = 20
|
// sibling stacks below inner: y = 4 + 16 + 0 (no gap) = 20
|
||||||
EXPECT_NEAR(sibling->getLayoutPosition().y, 20.0f, 0.01f);
|
EXPECT_NEAR(siblingRef->getLayoutPosition().y, 20.0f, 0.01f);
|
||||||
// inner row: in1 at x=4+0, in2 at x=4+32
|
// inner row: in1 at x=4+0, in2 at x=4+32
|
||||||
EXPECT_NEAR(in1->getLayoutPosition().x, 4.0f, 0.01f);
|
EXPECT_NEAR(in1Ref->getLayoutPosition().x, 4.0f, 0.01f);
|
||||||
EXPECT_NEAR(in2->getLayoutPosition().x, 36.0f, 0.01f);
|
EXPECT_NEAR(in2Ref->getLayoutPosition().x, 36.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
// (n) hidden: a Hidden element is not laid out and its siblings are not pushed by it
|
// (n) hidden: a Hidden element is not laid out and its siblings are not pushed by it
|
||||||
TEST(FlexLayout, HiddenSkipsLayout) {
|
TEST(FlexLayout, HiddenSkipsLayout) {
|
||||||
Element* a = new Div<W_64, H_32>(Attributes{});
|
OElement a = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* hidden = new Div<W_64, H_32>(Attributes{});
|
OElement hidden = new Div<W_64, H_32>(Attributes{});
|
||||||
Element* c = new Div<W_64, H_32>(Attributes{});
|
OElement c = new Div<W_64, H_32>(Attributes{});
|
||||||
auto* root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {a, hidden, c});
|
PElement aRef = a;
|
||||||
|
PElement hiddenRef = hidden;
|
||||||
|
PElement cRef = c;
|
||||||
|
OElement root = new Div<FlexRow, G_8, W_Full, H_Full>({Attributes{}}, {std::move(a), std::move(hidden), std::move(c)});
|
||||||
resolveStyles(root);
|
resolveStyles(root);
|
||||||
// set Hidden AFTER resolveStyles: applyStyle resets style=parentStyle, which
|
// set Hidden AFTER resolveStyles: applyStyle resets style=parentStyle, which
|
||||||
// would clobber a pre-set display=Hidden. the runtime mutation path is
|
// would clobber a pre-set display=Hidden. the runtime mutation path is
|
||||||
// set-style-field + markDirty, but markDirty triggers a re-style that resets
|
// set-style-field + markDirty, but markDirty triggers a re-style that resets
|
||||||
// from parent. so set it after the final re-style, before layout.
|
// from parent. so set it after the final re-style, before layout.
|
||||||
hidden->getStyle().display = Display::Hidden;
|
hiddenRef->getStyle().display = Display::Hidden;
|
||||||
layout(root, 300, 100);
|
layout(root, 300, 100);
|
||||||
// a at x=0; the hidden item contributes no footprint and no gap; c at x=72
|
// a at x=0; the hidden item contributes no footprint and no gap; c at x=72
|
||||||
EXPECT_NEAR(a->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(aRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(c->getLayoutPosition().x, 72.0f, 0.01f);
|
EXPECT_NEAR(cRef->getLayoutPosition().x, 72.0f, 0.01f);
|
||||||
// the hidden element itself is zeroed
|
// the hidden element itself is zeroed
|
||||||
EXPECT_NEAR(hidden->getLayoutPosition().x, 0.0f, 0.01f);
|
EXPECT_NEAR(hiddenRef->getLayoutPosition().x, 0.0f, 0.01f);
|
||||||
EXPECT_NEAR(hidden->getLayoutDimensions().x, 0.0f, 0.01f);
|
EXPECT_NEAR(hiddenRef->getLayoutDimensions().x, 0.0f, 0.01f);
|
||||||
}
|
}
|
||||||
|
|
||||||
Reference in new issue
Block a user