# UI Workflow Guide: full documentation > Every page, as sections of at most ~1,600 characters separated by `---`. Each section starts > with a SOURCE tag naming its page URL and heading anchor; a section split into parts is headed `(i/n)`. --- [SOURCE: https://guide.coherent-labs.com/] ## Mastering Gameface 1 Getting Started An introduction to the guide and the Gameface Player, showcasing how to test data-binding and debug your UI without a C++ backend. 2 Planning & Setup Configuring your development environment, establishing your recommended tech stack, and understanding core UI concepts within Gameface. Introduction to prototyping with Gameface UI. 3 Building with AI Set up a coding agent that understands Gameface: the MCP server, the documentation corpus, the negative ruleset and the spec-first skill we maintain. Plus what we learned building three real UIs with them. 4 Layout, Assets & Styling Learn best practices for building clean, fast and scalable game UIs with Gameface. We cover layouts, styling, animations, and asset management to help you translate designs into polished interfaces that scale across different aspect ratios. 5 Logic & Interactions Bridge the gap between static designs and dynamic interfaces. Learn how to mock game data, bind UI state, and manage complex user inputs like gamepad and spatial navigation. 6 Polishing The final steps to make your UI production-ready. Master native localization, accessibility features, and deep performance profiling while utilizing Gameface-exclusive rendering effects. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/] ## Design First An agent with a design system implements well, and an agent without one designs badly . Define your palette, type scale, and spacing rules before the first UI prompt. Without them, each screen invents a new visual language. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/#consistency-rather-than-quality] ## Design First: Consistency Rather Than Quality Individual components look polished, making drift hard to spot until comparing whole screens side by side. Five kinds of drift account for most problems: - **Color.** Multiple shades of “the accent color”, each chosen independently. - **Hierarchy.** Panels with identical weight, or everything competing equally. - **Spacing.** `12px` in one panel, `0.8rem` in the next, `14px` in the third. - **Semantics.** Red meaning danger on one screen, decoration on another. - **Type.** Five sizes two pixels apart, set to suit each component in isolation. An agent without design constraints invents both the component and its visual language. The second invention is where drift originates. **The Agent Is Following Instructions:** A “settings panel” request without a design system asks for two deliverables: the panel itself, and the visual language to render it. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/#encoding-the-rules] ## Design First: Encoding the Rules (1/2) Settle the decisions that should not be left to an agent before the first UI prompt, so that its judgment applies to layout and behavior rather than to taste. #### Color, Type, Spacing, and Layout **Color With Semantics.** A palette needs rules attached. Each color must have a defined purpose. Agents apply rules reliably and never originate them. For example: vermilion = danger; ultramarine = sacred; verdigris = alive; gold = earned. Encode these in `_variables.scss` with semantic comments: ```scss // Accent: emphasis, "give this importance" $accent: #90E8F1; // Interactive: controls the player can operate $interactive: #4B9FFF; // States $error: #E05C72; $warning: #E8A84A; $success: #59F46B; // Backgrounds, deepest to nearest $bg-deep: #06090F; $bg-surface: #0C1522; $bg-elevated: #0f1e30; $bg-overlay: #192C3E; ``` A token named `$accent` with “give this importance” is used correctly. A token named `$blue2` is used at random. **Typography as Roles.** Define what each typeface is for before sizing. Agents told “Cinzel for carved or titled text, EB Garamond for body, IM Fell for labels” place all three correctly in components never described to them. Set a minimum size and floor below which body copy may never drop. See Importing Fonts and Styling Text. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/#encoding-the-rules] ## Design First: Encoding the Rules (2/2) **Spacing, Radius, Borders, and Shadow.** These four need closed sets, not guidance. Spacing needs a scale covering panel gaps, row padding, and margins. Radius: *“0 everywhere except circles”*. Borders: 1px hairlines, 2px panels, 3px frames. Shadow: exactly two kinds, no colored glows except in one case. These constraints prevent drift better than per-component review. **Unit and Resolution.** Settle fixed canvas or fluid layout, and the unit, before anything is built. Retrofitting is a rewrite. See Building Responsive Game UI. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/#storing-the-system-in-the-repository] ## Design First: Storing the System in the Repository A design system described in a chat message survives until the context is trimmed. Written into `_variables.scss`, it is read fresh every time the agent opens the file, and it provides something concrete to reference in the instruction “use the existing tokens”. Keep it where the project already keeps such files and reference it from the project instructions. See Managing Variables and Writing Maintainable CSS. **Token Systems Walk Straight Into the var() Shorthand Trap:** A token-driven system is precisely the code that tends to produce `padding: var(--space-md) var(--space-lg)` and `border: 1px solid var(--color-border)`. Gameface does not resolve `var()` inside a shorthand and drops the whole declaration. Use the longhands, or use a preprocessor variable substituted at build time rather than resolved at runtime. The negative ruleset carries this rule for that reason. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/design-first/#starting-without-a-design] ## Design First: Starting Without a Design Four options remain, ordered by how well each performed. **A real design with a written token list** outperforms the rest. Use [Claude Design ](https://claude.com/product/design)or equivalent, with a handoff document covering the palette, semantic rules, type roles, spacing, and recurring ornaments. This reduces the agent’s task to translation rather than invention. **An existing screen to match** performs nearly as well. Name it explicitly and point at the file. Agents extrapolate an existing system far more reliably than they originate one. **A reference image** conveys layout and hierarchy accurately. Fine visual detail does not transfer. **Asking the agent to propose a system** works only as a separate step before any component work. Have it produce a token file, review it, correct it, and commit it. Starting from nothing and expecting coherence to emerge reliably fails. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/] ## Three UIs Built with an Agent We ran the toolchain from this chapter against three jobs of very different shapes: one screen added to a project that already existed, a family of chart components, and a finished design turned into a complete interface. The results came out uneven in the same direction every time. Structure and behavior arrived in far better shape than visual judgment. **Scope of the Experiments Section:** Experiments is where we write up what we try internally. None of the three builds below is available to download. Two are prototypes, and the third is a screen in a Gameface sample we intend to distribute once it is finished. We publish these for their specifics rather than as a promise about outcomes, since results depend mostly on the design handed to the agent. More entries will follow. The next one on our list places the Gameface MCP server alongside other MCP servers in the same session to observe how they interact. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#the-three-builds] ## Three UIs Built with an Agent: The Three Builds (1/4) The three jobs stress different things. Adding one screen to a live project places the agent inside constraints somebody else set. A component family is large enough that early decisions bind everything built afterwards, across many separate sessions that each start with no memory of the last. A whole interface tests whether a visual language holds across screens, and that was where we expected the most trouble. #### Match Tactics: A Screen in an Existing Dashboard Match Tactics is a positional tactics board that had to fit a fixed 2x2 tile of a manager-game dashboard, next to a Roster screen already living there. Players are dragged between pitch positions, a bench, and a scrolling squad list. We picked it because the conditions were close to ideal. A design system was already in place: a variables file with named colors, a radius scale, and a shared glow-border style used across the dashboard. The neighboring screen was available to imitate. We drew a mockup ourselves and ran a Conductor pass, so the interactions, empty states, and squad-list size were written down and signed off before any code existed. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#the-three-builds] ## Three UIs Built with an Agent: The Three Builds (2/4) The first pass produced a working board. Twenty-five named role slots sit banded across the pitch, eleven occupied at a time, and the rest light up as drop targets only during a drag. A drop lands in the nearest slot, and dragging a defender over an attacking position styles that slot differently from a natural fit, so the mismatch is visible before release. The agent also derived the formation label from the filled positions rather than storing it separately, which was its own decision and a sound one. A second pass fixed the visual details, along with something we had not thought to check: the new screen had broken the dashboard around it. #### Chart: A Component Family The Chart work covers six types (pie, donut, bar, line, area, and spider) that share one data format, one default palette, and the same underlying code, so every type behaves identically when the data changes. We picked it because it is the opposite of a single screen. The six types are not six separate components. They sit on shared files, so a decision about how animation works, or how hovering resolves to a data point, applies to all of them at once and is expensive to revisit. Each session starts without the reasoning behind the existing code, so we wanted to establish what it takes to stop an agent reversing a settled decision without noticing. Our answer was a specification kept in the repository at `.specs/components/chart.md`, reviewed by a person, and updated whenever reality disagreed with it. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#the-three-builds] ## Three UIs Built with an Agent: The Three Builds (3/4) All six types landed across six delivery phases. Each phase ended with a complete component rather than a layer of scaffolding, and with the automated tests passing. That test suite grew from 29 checks to 52, and it supplied the discipline, because a phase counted as done when the tests passed rather than when the agent reported the feature working. **Chart Components Are Not Yet Released:** The Chart components are still in development for the Gameface UI library. See the [component library ](https://gameface-ui.coherent-labs.com/components/)for what is available today. #### RPG Interface: Eight Screens From a Design The third test was eight screens of an RPG interface, art-directed as an illuminated manuscript where every panel is a page of the same book: title, HUD, character and inventory, quest journal, world map, skill tree, settings, and bestiary. The design came out of [Claude Design ](https://claude.com/product/design)as a set of 1920x1080 artboards, with a written handoff covering colors, typography, spacing and geometry, six recurring decorative elements, and a specification per screen. An agent then built all eight screens as one view on the Gameface UI boilerplate. We ran it to answer one question: does a visual language survive across eight screens when an agent does the work? It survived. A title page and a constellation skill tree have almost nothing in common, and both still read as pages of the same book. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#the-three-builds] ## Three UIs Built with an Agent: The Three Builds (4/4) The boundaries matter here. Every illustration is a deliberate placeholder sized for real art. The decorative elements are drawn by the engine at runtime rather than authored as images, which suits a prototype and is not what we would recommend for a shipping build. Nothing was profiled under game load or localized. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#findings] ## Three UIs Built with an Agent: Findings (1/4) #### Design Input Determines the Visual Outcome This was the strongest signal across all three builds, and the reason Design First sits where it does in this chapter. The RPG interface held together over eight screens because a document made the decisions first, and because those decisions were closed rather than open. Corners are square everywhere except circles. Exactly two kinds of shadow, with no colored glows except gold on unlocked skill nodes. Vermilion means danger, gold means earned, and gold never appears as decoration. Rules that specific leave nothing to drift toward. Match Tactics had a design system but only a mockup for the screen itself, and that is precisely where it needed a second pass. The Chart work had no visual design at all and did not suffer for it, since charts are geometry rather than art direction. #### Behavior Against Appearance Match Tactics shows this most clearly, since it is the one we handed a mockup rather than a finished design. Drag and drop, drop-target highlighting, and derived values all came back reasonable on the first attempt, and the layout, structure and hierarchy of the mockup transferred well. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#findings] ## Three UIs Built with an Agent: Findings (2/4) Precision was the weak point. The center circle on the tactics pitch was sized as a percentage of its container, so it rendered as an oval. Rows in the squad list placed the name, the condition bar and the percentage as three separately positioned elements instead of one row sharing a baseline. Both fixes took a minute, and no automated check could have caught either, because “this oval was supposed to be a circle” is not a measurable property. Budget a visual pass as a normal step and treat the first result as a structurally correct draft. #### Token Use Drops Off for Trim The main styling in Match Tactics followed the project’s design tokens. The scrollbar arrived at its default appearance while everything around it followed the dashboard’s visual language, and when the second pass styled it, the agent wrote the color as a raw hex value. That exact color already had a name in the same project’s token file. An agent that treats a detail as incidental writes a literal value rather than using the token for it, even with the token file present in the same project. Search for raw hex colors before accepting a screen. #### Agent Checks Only Look Inward Our most instructive failure occurred outside the screen entirely. The agent added a setting to the Match Tactics board that blocked mouse input from reaching the dashboard underneath, so the tile could no longer be dragged or resized. Every check it ran passed, because every check examined only the screen it had just built. The fix was to pass input through by default and swallow it only on the player tokens being dragged. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#findings] ## Three UIs Built with an Agent: Findings (3/4) Automated checks examine the thing under construction. None of them detect that something which used to work has stopped. Drive the surrounding application by hand after any addition to it. #### The Documents Outlasted the Code We have reused two artifacts from these builds more than anything else, and both are documents rather than code. The first is a table in the Chart spec recording how the engine behaved when the agent tested it directly, rather than what the documentation states. It records that querying the size of a shape inside an SVG returns zero, that simulated mouse events arrive without coordinates attached, and that the usual method of triggering a click from code does not exist. None of that appears in any documentation, ours included. The second is the RPG project’s table of substitutions, listing every piece of CSS the design called for that Gameface does not support, alongside its replacement. Modern color notation converted to plain RGB. Inner shadows rebuilt as an extra element behind the frame. Repeating stripe patterns rebuilt as a single repeating tile. Grid layouts rebuilt as wrapping rows. Both exist because an agent was instructed to verify rather than assume, and because somebody recorded the results where the next session would read them. Request this explicitly on any work large enough to span several sessions. #### Confident and Persistent Misdiagnosis --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/experiments/three-uis-with-an-agent/#findings] ## Three UIs Built with an Agent: Findings (4/4) The Chart work lost most of a delivery phase to an invisible layer that collapsed to nothing, but only in the packaged build rather than during development. The tool that compresses CSS for release had rewritten four separate position values into a single shorthand that Gameface does not support. The agent blamed scrolling, then coordinate timing, then event dispatch, each plausible, and wrote the failing test off as a problem with the test itself. Running the tests against the packaged build instead of the development server ended it. No amount of further reasoning would have reached the cause, because the evidence did not exist in the version under test. See Verifying What the Agent Builds for where this fits in the checking order. #### Numeric Budgets Rather Than Adjectives The Chart spec set a performance budget before the first chart existed. A **mark** is one drawn shape in a chart: one slice of a pie, one bar in a bar chart, one point on a line. The budget allowed 200 of them, warned above 500, required the animation to update the chart once per frame regardless of mark count, and permitted measuring the chart’s size only when its container resizes rather than during drawing. An agent holds itself to figures of that kind. An instruction to make the component fast produces agreement and nothing else. The same pattern appears in the design rules and in the spec decisions. Closed rules outperformed open guidance in every case we tried. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/] ## Setting up the MCP Server The [Gameface MCP server ](https://github.com/CoherentLabs/Gameface-MCP)connects a coding agent to a running Gameface Player through the Chrome DevTools Protocol . Once connected, the agent reads Gameface’s own warnings, inspects the DOM it produced, captures screenshots, and checks that text fits inside its box, rather than describing what it expects to have built. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#why-a-live-engine-is-required] ## Setting up the MCP Server: Why a Live Engine Is Required Without a connection, every iteration routes through a person. The agent writes markup, someone runs the Player or Game, someone describes what looks wrong, and the agent revises. What the agent never observes is what Gameface did with its code—the information that settles the question. The console is the clearest signal. Gameface warns about CSS it cannot resolve, diagnosing Gameface-specific bugs faster than any other available feedback. That warning means nothing while it sits unread. **Designed for the Gameface Player:** The server connects to any engine running the Gameface SDK through the Chrome DevTools Protocol. However, it was developed with the Gameface Player in mind, so other engines may not behave as expected. Every connection is verified over CDP, and `navigator.userAgent` must contain `cohtml`. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#prerequisites] ## Setting up the MCP Server: Prerequisites - **Node.js 18+**, since the server uses the global `fetch` API. - **A local Gameface SDK with a Player executable.** The repository does not ship one, so a Gameface licence and SDK are required. On Windows the executable normally sits at `.../Player/Player.exe`. Note that `Player.exe` lives in a `Player` subfolder under the SDK root rather than at the root itself. - **Gameface 3.1.2 or newer**, for the reasons covered in Version Awareness. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#installing] ## Setting up the MCP Server: Installing (1/2) 1. ##### Install the server {#install-the-server} [add-mcp ](https://www.npmjs.com/package/add-mcp)detects the installed agents and writes the server into each one’s config. **Global (recommended):** Available in every project on the machine: ```bash npx add-mcp "npx -y gameface-mcp@latest" --name gameface -g ``` **Project only:** Run from the project folder: ```bash npx add-mcp "npx -y gameface-mcp@latest" --name gameface ``` **Install Once, Not Both:** A project `gameface` MCP entry and a global gameface MCP entry compete instead of merging, and only one runs. 2. ##### Set up the Player {#set-up-the-player} Start the agent and ask it to launch the Gameface Player. On first launch it asks for the Player path (`Player.exe`, its folder, or the SDK folder) or offers to search the machine. The path is saved to `~/.gameface-mcp/config.json` and reused by every project. **Disable Player Chrome Before Measuring:** The Player’s toolbar and bookmark bar take an inconsistent part of the requested height, so screenshots and layout assertions measure the wrong canvas. Add `"browserArgs": ["--enable-gui=false"]` to `~/.gameface-mcp/config.json` to remove them. If you let the agent launch the player and write the config, it will automatically add the `"browserArgs": ["--enable-gui=false"]` entry for you. 3. ##### Install the Conductor skill (optional) {#install-the-conductor-skill-optional} The Gameface UI Conductor skill clarifies requirements, gets sign-off on a spec, then implements and validates with the MCP tools: --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#installing] ## Setting up the MCP Server: Installing (2/2) ```bash npx skills add CoherentLabs/Gameface-MCP --agent claude-code -g ``` Drop `-g` to install into the current project only. Start a new session afterwards. **Specify the Client:** Use the `--agent` flag to specify which client should use the skill. For example, `--agent claude-code` installs the skill for the Claude Code client. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#client-configuration] ## Setting up the MCP Server: Client Configuration `add-mcp` writes the following entry for each detected client. No manual editing is needed. **Claude Code:** Global: `~/.claude.json`. Project: `.mcp.json`. ```json { "mcpServers": { "gameface": { "command": "npx", "args": ["-y", "gameface-mcp@latest"] } } } ``` **VS Code / Copilot:** Global: user `mcp.json`. Project: `.vscode/mcp.json`. ```json { "servers": { "gameface": { "command": "npx", "args": ["-y", "gameface-mcp@latest"] } } } ``` VS Code uses `servers` instead of `mcpServers`. **Gemini CLI:** Global: `~/.gemini/settings.json`. Project: `.gemini/settings.json`. ```json { "mcpServers": { "gameface": { "command": "npx", "args": ["-y", "gameface-mcp@latest"] } } } ``` **Raise the Timeout:** The automatic Player search can take up to a minute plus prompt time, all in one tool call. Add `"timeout": 90000` to the entry. **Claude Desktop:** `%APPDATA%/Claude/claude_desktop_config.json` on Windows, `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS. ```json { "mcpServers": { "gameface": { "command": "npx", "args": ["-y", "gameface-mcp@latest"] } } } ``` **Server Flags:** Flags go inside the quoted command, after the package name, for example `npx add-mcp "npx -y gameface-mcp@latest --port 9445" --name gameface -g`. Flags override `~/.gameface-mcp/config.json`. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#available-capabilities] ## Setting up the MCP Server: Available Capabilities (1/3) #### Managing Players with Commands Commands are shortcuts for launching and managing Players mid development. They appear as slash commands, in Claude Code as `/mcp__gameface__`. Arguments are positional, and `true`, `yes`, `y` and `1` all count as yes. ##### Launching **Default Player:** ```text /mcp__gameface__launch-player /mcp__gameface__launch-player http://localhost:3000 ``` Launches the default Player, optionally opening a URL. **Pick a Player:** ```text /mcp__gameface__launch-player true ``` Lists every configured Player, sorted by version, and launches the selected one. Useful for testing a UI against several Gameface versions. ##### Adding Players **Scan the machine:** ```text /mcp__gameface__scan-players ``` Runs a search script inside the server and adds every Player found. The agent only sees the resulting list, not your files. The default Player is unchanged. **Add a folder:** ```text /mcp__gameface__add-player ``` Skips the scan. Provide a `Player.exe` or a folder of Players, and every Player inside is added. The default Player is unchanged. ##### Changing the Default `/mcp__gameface__change-player-path` asks for a new default Player path. Pass `true` to search the machine instead. **Listing the Commands:** Most clients list every available command after typing `/gameface`. The prefix matches the `--name` used at install time. #### Tools These tools are rarely invoked by hand. Knowing what exists establishes what can reasonably be requested, and what to demand evidence of. #### Reading What Gameface Did --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#available-capabilities] ## Setting up the MCP Server: Available Capabilities (2/3) Tool | Function `get_console_logs` | Buffered console output plus Log-domain entries, including unsupported-feature warnings `get_computed_styles` | Computed CSS for a node, meaning what Gameface kept rather than what was written `get_dom_tree` / `search_dom` | Snapshot of the DOM, or nodes matching a text or XPath query `take_screenshot` | Full page, viewport, or a custom clip rect `eval_js` | Runs JavaScript in the connected page `interact_element` | Click, type, hover, focus, scroll into view, or touch #### Checking Layout Assertion | Check performed `assert_text_fits` | Whether an element’s content overflows its own box `assert_no_overlap` | Whether two elements’ rendered boxes intersect `assert_within_parent` | Whether an element stays inside its parent, an ancestor, or the viewport #### Measuring Cost `perf_lint` is a static check for expensive layout patterns like `align-items: stretch`, unsized flex items, and misuse of `display: simple`. No timing involved, so it does not flake. `perf_measure` runs a fixed frame-timing scenario and reports p50, p95, and p99 against a recorded baseline. **What a perf_measure Number Compares Against:** The baseline is a noise floor recorded at 1920x1080 across five runs of 600 frames, with the Player restarted between runs. Treat a result as a signal that a screen is unusually expensive rather than as a substitute for profiling a real UI under real game load. See Performance and Memory Profiling for that. #### Reading the Documentation --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#available-capabilities] ## Setting up the MCP Server: Available Capabilities (3/3) Alongside the tools, the server exposes the documentation corpus and the engine constraints as MCP resources, `gameface://code-instructions` and `gameface://rag/.md`. The next article covers both. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#version-awareness] ## Setting up the MCP Server: Version Awareness Gameface 3.1.2 or newer is required. This version introduced CDP protocol support, including engine logs through the Chrome DevTools Protocol. The minimum version is verified at connection time via `cohtmlVersion`. Some older versions have CDP quirks that the server works around, but a tool returning unexpected output may indicate an engine-side gap. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/gameface-mcp-server/#confirming-the-connection] ## Setting up the MCP Server: Confirming the Connection Ask the agent to launch the Player and screenshot the current view. An image and a `cohtmlVersion` returning together confirm a live connection. A description of what the agent *expects* the screen to look like means the server is not connected. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/] ## Grounding the Agent Grounding reduces mistakes by giving the agent the right context before it writes code. Two components: a documentation corpus answers questions on demand, and a negative ruleset sits always-on and enforces constraints. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#why-the-negative-half-carries-more-weight] ## Grounding the Agent: Why the Negative Half Carries More Weight Ask a model to center cards and it will often choose `display: grid`. In a Gameface project, that default is wrong. A negative rule is stronger than a warning. “Never use CSS Grid, Gameface has no grid layout” gives the model something to reject while generating code. - | Documentation corpus | Negative ruleset Answers | “How do I do X in Gameface?” | “Is this line allowed at all?” Delivery | Retrieved on demand, per query | Always in context Content | Patterns, concepts, examples, trade-offs | A flat list of what the engine refuses Written from | This guide | Engine feature detection Both matter: the ruleset blocks bad code, and the corpus supplies the right code. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#the-documentation-corpus] ## Grounding the Agent: The Documentation Corpus (1/2) The corpus is this guide, rewritten for retrieval. Agents read in chunks, not in order, so each chunk has to stand on its own. Each chunk carries metadata so retrieval can rank by more than keyword overlap: ```markdown [TOPIC: layout] [TYPE: concept] [SEVERITY: critical] [SOURCE: laying-out-the-screen.mdx] ## Flexbox-Only: Gameface Has No CSS Grid Gameface's layout engine relies exclusively on the Flexbox model, powered by the Yoga layout engine. CSS Grid is entirely absent, and all `grid-*` properties are rejected by the parser... > GAMEFACE CONSTRAINT: `display: grid`, `display: inline-block`, `display: contents` > and `display: inline-grid` are rejected by the engine. Use `display: flex` exclusively. ``` `SEVERITY: critical` is the key field. A search for “flexbox layout” should surface a breaking constraint before stylistic advice. #### Corpus Contents - **Directoryprompts/rag** - 01-engine-bridge.md - 02-layout.md - 03-scalability.md - 04-interactions.md - 05-graphics.md - 06-fonts-and-text.md - 07-performance.md - 08-gameface-ui.md - 09_1-components-basic.md - 09_2-components-complex.md - 09_3-components-feedback.md - 09_4-components-layout.md - 09_5-components-media.md - 09_6-components-utility.md - 10-live-views.md - 11-localization.md - 12-custom-effects.md - 13-accessibility.md - 14-animations.md - 15-tooling.md --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#the-documentation-corpus] ## Grounding the Agent: The Documentation Corpus (2/2) The six `09_*` files cover the Gameface UI component library by category. They help most in daily work because they push the agent toward existing components such as `Slider`, `Navigation`, and `ScrollView` instead of rebuilding them. #### Retrieval Routes With the MCP server connected, there are two access paths. `search_gameface_docs` returns the relevant chunks for a query, and server instructions should tell the agent to call it before writing markup, CSS, or JavaScript. Each topic file is also exposed at `gameface://rag/.md`, with `gameface://rag/index` listing them, when a full topic is more useful than a short answer. **A Confident Agent Will Skip the Search:** The tool being available is not enough. A project instruction like *“call `search_gameface_docs` before writing any CSS”* materially changes behaviour. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#the-negative-ruleset] ## Grounding the Agent: The Negative Ruleset (1/2) The ruleset is a single file, `prompts/negative-rules/negative-rules-injection.md`, exposed by the MCP server as `gameface://code-instructions`. It comes from feature detection run against the engine , not documentation, so it captures edge cases that rarely get written down. It starts with a short “supported, use freely” section. The rest is prohibitions: Section | Example rule CSS, forbidden property families | Never use CSS Grid, multi-column, container queries, logical properties, scroll-snap, or view transitions CSS, forbidden functions | Never use `oklch`, `lab`, or `color-mix`; never use `clamp`, `min`, or `max`; never use `repeating-linear-gradient` CSS, partial-value restrictions | `border-style` rejects `dashed` and `dotted`, `box-shadow` rejects `inset`, `border-radius` rejects percentages CSS, selector restrictions | `:has()`, `:checked`, `:disabled`, and `:focus-visible` parse but never match HTML, forbidden tags and attributes | `` is coerced to `type="text"`, `` has no table layout, `` does not navigate JavaScript, missing or stubbed APIs | No `fetch`, no `localStorage`, no `IntersectionObserver`, no Workers, no `AbortController` Two rules cause most of the stylesheet breakage. First, `var()` does not resolve inside shorthands. `border: 1px solid var(--c)` drops the entire declaration, and the same applies to `padding: var(--a) var(--b)` and `transition: opacity var(--d) var(--e)`. Longhands work. This matters because agents tend to generate shorthand-heavy, token-driven CSS. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#the-negative-ruleset] ## Grounding the Agent: The Negative Ruleset (2/2) Second, some selectors parse but never match. `:checked` and `:disabled` fail silently, so markup that looks correct in source still renders incorrectly. **Treat the Ruleset as a Snapshot of One Engine Version:** The file reflects the engine versions that were tested. Several entries are marked “unverified”, including `url()`, `image-set()`, and `cross-fade()`, because they could not be probed safely. Re-check it against the [Gameface documentation ](https://docs.coherent-labs.com/cpp-gameface/)after an upgrade. If a rule conflicts with observed behaviour, suspect the rule before the code. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/grounding-the-agent/#using-both-without-the-mcp-server] ## Grounding the Agent: Using Both Without the MCP Server Neither component requires the server. Both are plain Markdown in the repository, and every agent supports some form of always-loaded project instructions: Client | Location Claude Code | `CLAUDE.md` at the project root GitHub Copilot | `.github/copilot-instructions.md` Gemini CLI | `GEMINI.md` at the project root Cursor | `.cursor/rules/` Paste the negative ruleset in as-is, since it is meant to be injected verbatim, and reference the corpus files by path so the agent can open them directly. You lose on-demand retrieval for the corpus, which matters because it is large. You lose nothing for the ruleset, because it belongs in permanent context. **Store It With the Project Rather Than in Personal Configuration:** The ruleset describes the target engine, so new teammates inherit it automatically when they clone the repository. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/overview/] ## Overview Coding agents write CSS for the browser they were trained on. Gameface implements a subset of the web platform , so a substantial share of that CSS reaches the engine, gets flagged in the console, and never renders. This chapter documents four tools that close the gap: an MCP server, a documentation corpus, a negative ruleset, and a skill that produces a signed-off specification before any code is written. The final article reports three interfaces built with them. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/overview/#the-problem] ## Overview: The Problem Agents write CSS for the browser they were trained on. Gameface implements only a subset of the web platform, so many modern CSS features are not supported. When an agent writes unsupported CSS, the engine silently drops it—no build errors, no linter warnings, just silent failures that appear only when code runs. The knowledge of what works exists, but it’s not accessible to the agent while writing. Constraints are discovered in review comments, not prevented during generation. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/overview/#the-toolchain] ## Overview: The Toolchain Each tool works independently, and they compose. Tool | Function | Article **Gameface MCP server** | Drives a live Player over the Chrome DevTools Protocol, so the agent can read the console, inspect the DOM, capture screenshots, assert on layout, and measure frame timing | Setting up the MCP Server **Documentation corpus** | This guide, restructured for an agent to search while writing | Grounding the Agent **Negative ruleset** | An explicit “never emit this” list generated from engine feature detection | Grounding the Agent **Game UI Conductor skill** | Extracts requirements and produces a written specification, signed off before any code | The Conductor Skill All four live in one repository, [github.com/CoherentLabs/Gameface-MCP ](https://github.com/CoherentLabs/Gameface-MCP). The skill files are shared across Claude Code, GitHub Copilot, and Gemini CLI rather than duplicated per client. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/overview/#limitations] ## Overview: Limitations This toolchain catches runtime errors but doesn’t prevent design issues. An agent without a defined palette and type scale produces competent but incoherent work. See Design First to settle design before prompting. The toolchain also checks in isolation—an agent can complete a screen correctly while breaking the dashboard hosting it. And assertions report what the agent believes it ran, not what actually ran. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/overview/#reading-order] ## Overview: Reading Order The second and third articles set up the toolchain. The fourth covers the work that precedes any UI request. The last two cover the loop of specifying, building, and checking the result. Read them in order on a first pass. **Experiments** collects internal write-ups. The first entry documents three UIs built with this toolchain: a screen added to an existing dashboard, a reusable component family, and a complete eight-screen interface. **Nothing in Experiments is a Product:** Those write-ups exist for their specifics, and because the failures are more instructive than the successes. Results vary with the model, the prompt, and above all the design handed to the agent. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/] ## The Conductor Skill Well-built code for the wrong feature is expensive. The Game UI Conductor clarifies requirements and obtains sign-off on a written specification before writing any UI code. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#the-problem-it-solves] ## The Conductor Skill: The Problem It Solves Agents fill gaps in vague requests with typical answers and build hundreds of lines on assumptions. When those assumptions are wrong, restarting costs less than fixing. The Conductor clarifies requirements upfront, produces a readable specification, and writes no code until it’s accepted. **Not Every Request Needs This Treatment:** This applies to rough ideas only. Bug fixes, copy changes, style adjustments, and requests that already specify interactions and data shape are out of scope—they’re already specifications. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#the-six-stages] ## The Conductor Skill: The Six Stages (1/2) 1. ##### Reason about the relevant dimensions {#reason-about-the-relevant-dimensions} The skill consults a checklist of game UI design dimensions covering interaction, animation and feedback, data and state, scale, accessibility, localization, sort and filter, and lifecycle. It then determines which apply. Not every dimension applies to every feature, and the purpose is to catch the ones the request did not mention. 2. ##### Clarify in rounds {#clarify-in-rounds} Three rounds at most, stopping earlier once nothing new surfaces. Round one asks everything relevant as a single batch rather than as a sequence of separate messages, and every question carries a sensible default, so “use your judgment” is a valid answer. Round two follows what round one opened up, so a yes to drag-and-drop leads to “what is the gamepad equivalent?” and “what happens when an item is dropped outside the panel?”. Round three occurs only when a genuine open question remains. Anything still unresolved becomes a stated assumption in the specification rather than a further question. 3. ##### Draft the specification and obtain sign-off {#draft-the-specification-and-obtain-sign-off} A short document under fixed headings: Goals, Interactions, Data and state, Scale, Accessibility, Localization, Assumptions. It closes with a direct question asking whether this is what should be built. This stage is a hard gate . No code is written until the specification is accepted in the conversation. Rejecting it loops back with the correction, repeating as required. 4. ##### Implement {#implement} --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#the-six-stages] ## The Conductor Skill: The Six Stages (2/2) Normal rules apply from this point. The agent follows `gameface://code-instructions` and calls `search_gameface_docs` while writing CSS and JavaScript, as covered in Grounding the Agent. 5. ##### Validate {#validate} Given a Gameface MCP connection, the agent runs the layout assertions, `perf_lint`, and, where the view is dominant, `perf_measure` against what it built. Failures are fixed and the specific check re-run. Without a connection it reports that fact rather than skipping silently. Verifying What the Agent Builds covers interpreting the results. 6. ##### Report {#report} What was asked against what was assumed, what was accepted at sign-off, what was built, and which checks passed or could not run. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#running-it] ## The Conductor Skill: Running It One set of files serves every client. The trigger differs. Client | Invocation **Claude Code** | Automatic, matching the skill’s description against the request. Direct invocation with `/gameface-conductor` also works. **GitHub Copilot (VS Code)** | Automatic. Copilot’s Agent Skills scans `.claude/skills/` alongside `.github/skills/`, so the file is picked up unmodified. **Gemini CLI** | Explicit only, since Gemini CLI has no auto-triggered skill concept. `/gameface-conductor ` injects the same skill content rather than duplicating it. Copy `.claude/skills/gameface-conductor/` into the project to use it, plus `.gemini/commands/gameface-conductor.toml` for Gemini CLI. Both live in the [Gameface-MCP repository ](https://github.com/CoherentLabs/Gameface-MCP). --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#why-the-questions-matter-more-than-the-specification] ## The Conductor Skill: Why the Questions Matter More Than the Specification The questions surface decisions early—what the empty state says, whether the panel pauses the game, whether the list holds 500 rows. Answering them in advance costs less than answering them later, under pressure, with code already written against a different answer. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/the-conductor-skill/#limits] ## The Conductor Skill: Limits Answering every question with the default produces a specification full of reasonable-sounding assumptions, which the build then follows precisely. The dimensions checklist covers behavior only. Nothing in it asks what the panel should look like, which is why Design First is a separate step. Sign-off is also not review. Accepting a specification confirms the plan and says nothing about the code produced from it. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/] ## Working in Unreal Engine Unreal Engine 5.8 includes an MCP server that lets a coding agent inspect and edit a project in the Unreal Editor. Pair it with the Gameface MCP server and the agent can work on both the UI and implementation tasks in a Gameface project : changing the Unreal project and checking the page Gameface renders. This guide walks through connecting the servers, the kinds of UI work they support, and how to check the result in the game. **Note:** The built-in Unreal MCP server is available in **Unreal Engine 5.8**. If your studio uses an earlier version, you can still use Gameface MCP to inspect the rendered UI, but you’ll need another integration to let your agent inspect and edit the Unreal project. Check whether your Unreal version or studio tooling provides an MCP server before following the Unreal setup below. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#what-each-server-does] ## Working in Unreal Engine: What Each Server Does The servers give the agent access to different parts of your workflow: - | Unreal MCP | Gameface MCP **Runs in** | The Unreal Editor | A Node.js process that connects to the Gameface Player **Lets the agent** | Inspect and edit UMG widgets, Blueprints, assets, and levels; start Play-In-Editor; read the output log | Read the Gameface console; inspect the DOM and styles; take screenshots; check layout **Helps answer** | What is in the project? | What did Gameface actually render? With only Unreal MCP, the agent can change project files but cannot inspect the rendered Gameface page. With only Gameface MCP, it can inspect the page but cannot edit Unreal assets. With both connected, it can make a change, run the UI, and use the console and page inspection tools to find problems. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#quick-setup] ## Working in Unreal Engine: Quick Setup (1/2) 1. ##### Enable the Unreal plugins {#enable-the-unreal-plugins} In Unreal, open **Edit > Plugins**, enable **Model Context Protocol**, **Editor Toolset**, and **UMG Toolset**, then restart the editor. 2. ##### Start the Unreal MCP server {#start-the-unreal-mcp-server} Open **Editor Preferences > Model Context Protocol**. Turn on **Auto Start Server** and **Enable Tool Search**, and keep the default address: `http://127.0.0.1:8000/mcp`. 3. ##### Install the Gameface MCP server {#install-the-gameface-mcp-server} Follow Setting up the MCP Server if you haven’t already. 4. ##### Add the Unreal server to your agent {#add-the-unreal-server-to-your-agent} Create the configuration file in the Unreal project folder, beside the `.uproject` file. It only needs the Unreal entry. The `gameface` entry comes from the Gameface MCP install; if your agent doesn’t have it yet, see Client Configuration. **Claude Code:** ```json { "mcpServers": { "unreal-mcp": { "type": "http", "url": "http://127.0.0.1:8000/mcp" } } } ``` **VS Code / Copilot:** ```json { "servers": { "unreal-mcp": { "type": "http", "url": "http://127.0.0.1:8000/mcp" } } } ``` 5. ##### Check that it works {#check-that-it-works} Start the Unreal Editor, then ask the agent: > List the Unreal MCP toolsets, then launch the Gameface Player and take a screenshot. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#quick-setup] ## Working in Unreal Engine: Quick Setup (2/2) The agent should return a list of Unreal toolsets and an actual screenshot from the Player. If it only describes what it expects the screen to look like, the Gameface server is not connected to the Player. **Keep the Unreal Editor open:** The Unreal MCP server runs inside the editor and is available only while the editor is open. The server is experimental, so tool names may change between Unreal versions. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#common-ui-tasks] ## Working in Unreal Engine: Common UI Tasks (1/2) With both servers connected, an agent can help with several parts of a Gameface UI workflow. These examples show what to ask for and what to check afterward. #### Convert a UMG screen to Gameface To recreate a UMG screen in Gameface, the agent reads the widget tree and builds a matching page with HTML, CSS, and JavaScript. It can keep the original UMG widget, load the Gameface page from your HUD and switch between the two versions as needed. Keeping the UMG screen gives you a reference and lets you repeat the conversion if the design changes. For example, ask: > Convert `WBP_HUD` into a Gameface UI and load it from the level’s Gameface HUD. Keep the original UMG widget unchanged. #### Connect the page to game data For values that change during play, such as health, ammunition, and nameplate positions, the agent can add C++ data models and bind them to the page. Gameface then updates the UI as the game state changes. For example, ask: > Add nameplates for the five players in the level. Bind each player’s name and health from C++, and show the health bar in green, yellow, or red based on its value. #### Use Gameface UI components For a settings screen with sliders, dropdowns, scrolling lists, or key bindings, the agent can use components from the [Gameface UI](https://github.com/CoherentLabs/Gameface-UI) library instead of building each control from scratch. For example, ask: > Rebuild the settings menu with Gameface UI. Keep the same C++ models and events. #### Check the result in the game Check the work in three places, from quickest to most representative: --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#common-ui-tasks] ## Working in Unreal Engine: Common UI Tasks (2/2) 1. **The Gameface Player:** Check layout and basic interactions quickly. 2. **The Play-In-Editor output log:** Look for JavaScript errors and Gameface warnings from the running game. 3. **The in-game view:** Connect Gameface MCP to the inspector port shown in the editor’s output log. This lets the agent inspect the page with real game data. For example, ask: > Start Play-In-Editor, open the settings menu, and check the log for Gameface errors. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/unreal-engine/#tips] ## Working in Unreal Engine: Tips - **Ask for evidence.** Request a screenshot, console output, or relevant log lines rather than relying on a claim that the change works. - **Avoid desktop capture and simulated key presses.** They act on whichever window has focus and may affect the wrong application. - **Test the controls yourself.** The agent can check that a menu appears and its data is present, but it cannot judge whether the controls feel right during play. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/] ## Verifying What the Agent Builds Agent-written code can appear complete before it has been validated. Validate it with five checks, from cheapest to most expensive, and include a production build in the Player to catch build-time failures. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#why-verification-needs-multiple-layers] ## Verifying What the Agent Builds: Why Verification Needs Multiple Layers Code review and a running dev server are not enough to validate agent-written UI. The code may look coherent while still relying on unsupported APIs, invalid CSS, or untested assumptions about layout and interaction. Use two review habits consistently. Treat the agent’s summary as a claim, not evidence. If it says a change was verified, check which commands, assertions, or screenshots support that claim. Ask for artifacts rather than confirmation. Screenshots, console output, and assertion results are more useful than a plain success statement. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#layer-1-lint-the-source] ## Verifying What the Agent Builds: Layer 1: Lint the Source This is the cheapest check and requires no running Player. [eslint-plugin-gameface ](https://frontend-tools.coherent-labs.com/eslint-plugin-gameface/getting-started/)flags unsupported patterns and data-binding mistakes across CSS, SCSS, HTML, JSX/TSX and JavaScript. It ships pre-wired in the Gameface UI boilerplate and in every framework template. Run it in CI, not only in the editor. Editor diagnostics are easy to miss during agent-driven edits. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#layer-2-read-the-gameface-console] ## Verifying What the Agent Builds: Layer 2: Read the Gameface Console This is the cheapest check that requires a running Player. Gameface logs unsupported stylesheet properties by name, which identifies exactly what was discarded. This check is only useful if the console is read. Builds can succeed and dev servers can remain quiet while the Player reports rejected declarations. With the MCP server connected, `get_console_logs` exposes that output to the agent. After styling work, a prompt like the following is usually enough: > Load the view and show me `get_console_logs`. Any unsupported-property warnings? If the console names a property present in the source, treat it as a confirmed bug. The declaration did not survive. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#layer-3-assert-against-the-running-engine] ## Verifying What the Agent Builds: Layer 3: Assert Against the Running Engine The console reports rejected declarations. Separate checks are still needed to confirm that the remaining layout behaves correctly. Three assertions cover most layout failures. Assertion | Catches `assert_text_fits` | Clipped labels, overflowing values, text that fits in English and not in German `assert_no_overlap` | A tooltip covering the number it explains, a badge sitting on a name `assert_within_parent` | A panel running off the bottom at 21:9, a dropdown escaping its container `perf_lint` sits alongside them as a static check for layout patterns the Gameface documentation identifies as expensive. It does no timing, so it does not flake. The Conductor skill runs these automatically as its validation stage. Without the skill, request them explicitly. **Assertions Beat Screenshots for Measurable Failures:** Use assertions for measurable failures and screenshots for visual judgment. Minor clipping or overlap is easy to miss in a screenshot and unambiguous in an assertion. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#layer-4-direct-inspection] ## Verifying What the Agent Builds: Layer 4: Direct Inspection Tooling does not evaluate visual quality. Review these four areas directly. - **Visual coherence.** Check that the screen matches the surrounding interface. See Design First. - **Hierarchy.** Check that the most important element reads as the most important element. - **Feel.** Review transitions, timing, and press feedback directly. - **Focus order.** Check that gamepad navigation follows a sensible path. See Spatial Navigation and Focus. Request a screenshot at the target resolution and worst-case aspect ratio, then compare it with an existing screen instead of reviewing it in isolation. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#layer-5-test-the-production-build] ## Verifying What the Agent Builds: Layer 5: Test the Production Build This layer is easy to skip, but it is required for catching build-time rewrites. One common failure mode appears only after the production build step. In one Chart component, an overlay collapsed to `0x0` only in the built page. The source used `left: 0; top: 0; right: 0; bottom: 0`. The CSS minifier collapsed those declarations into `inset`, which Gameface does not support, so all four sides became `auto` and the element disappeared. Everything upstream still passed. The source was valid. Lint had nothing to flag because `inset` never appeared in the source, and the dev server served unminified CSS, so the issue did not appear there either. The missing step was loading the production build in the Player and reading its console. Layer 2 only protects the artifact that is actually tested. End-to-end coverage caught the issue because it ran against `vite preview`, not the dev server. Apply two rules to any UI that will ship. Verify shipped UI in a production build inside the Player, not only against a dev server. Source linting cannot catch build-time rewrites. Prefer source patterns that do not encourage unsupported rewrites. Four zero offsets on a stretched element invite the minifier to emit `inset`. The version below cannot be folded into that shorthand: ```css /* Four zero offsets invite the minifier to emit `inset: 0`, which Gameface drops. */ .hit-overlay { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } ``` See UI Testing for the end-to-end setup, and Layout Debugging for diagnosing an unexpected collapse. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#performance-as-a-separate-pass] ## Verifying What the Agent Builds: Performance as a Separate Pass `perf_lint` and `perf_measure` indicate whether a screen is structurally expensive or unusually slow against a recorded baseline. Neither reports the full runtime cost inside the game under real load. Treat them as early warnings during development and use the profiler for real measurement. See Performance and Memory Profiling. --- [SOURCE: https://guide.coherent-labs.com/building-with-ai/verifying-ai-output/#acceptance-checklist] ## Verifying What the Agent Builds: Acceptance Checklist Before accepting a screen built by an agent: - Lint passes in CI. - The Gameface console is clean, with no unsupported-property warnings naming anything in the source. - Layout assertions ran, and their output has been read. - A screenshot exists at target resolution and at the worst-case aspect ratio. - The screen has been compared against an existing one. - It has been opened from a production build in the Player. - Gamepad or keyboard navigation has been driven by hand rather than declared present. - Every color, size and spacing value traces back to a named entry in the design system. --- [SOURCE: https://guide.coherent-labs.com/getting-started/core-concepts-and-information-flow/] ## Core Concepts & Information Flow Transitioning from standard web development to game UI requires a fundamental shift in how you think about data and structure. In this article, we will cover how data flows between the game engine and your interface, why your UI should stay as “dumb” as possible, and how to structure your HTML documents into optimized “Views”. --- [SOURCE: https://guide.coherent-labs.com/getting-started/core-concepts-and-information-flow/#the-push-philosophy-how-data-works-in-games] ## Core Concepts & Information Flow: The “Push” Philosophy: How Data Works in Games If you are coming from a traditional web development background, you are likely used to the Fetch model. In a standard web app, the frontend asks a server for data, waits for a network response, displays a loading spinner, and then parses a JSON payload. Game UIs operate entirely differently. There are rarely any loading spinners or network requests to a backend API. Instead, Gameface operates on a Push model. The game engine is constantly running at 60 or more frames per second. Every single frame, the C++ engine uses data-binding to synchronize data between the UI and the engine. When data in the engine changes, the corresponding UI elements are automatically updated to reflect those changes. #### Keep Your UI “Dumb” Because the game engine is pushing state updates continuously, your frontend should hold as little state as possible. The game engine is the ultimate source of truth. Your UI should remain “dumb.” It shouldn’t calculate how much damage a player took, nor should it sort a massive inventory array. The engine handles the heavy computational logic and pushes the finalized data, allowing your interface to simply react and render the result. **Tip:** Always rely on the engine for logic and math. Your JavaScript should be reserved for managing pure UI interactions, like opening a dropdown panel or triggering an animation. --- [SOURCE: https://guide.coherent-labs.com/getting-started/core-concepts-and-information-flow/#what-is-a-view] ## Core Concepts & Information Flow: What is a “View”? In Gameface terminology, each loaded HTML page within your game is referred to as a View . When planning your development workflow, you essentially have to decide how to split the UI into these views, which dictates how many distinct HTML pages your project will have. Generally, game UIs can be categorized into a few major screen types: - **Menu:** The main navigational hubs, like the Start screen, Settings, or Inventory. - **HUD (Heads-Up Display):** The persistent, on-screen elements like health bars, minimaps, and crosshairs. - **Spatial / Diegetic:** Elements that exist within the 3D game world itself, such as interactable computer terminals or floating nameplates above characters. - **Meta:** 2D overlays that relate to the story but sit on top of the game, like subtitles or cinematic pop-ups. --- [SOURCE: https://guide.coherent-labs.com/getting-started/core-concepts-and-information-flow/#best-practices-minimizing-views] ## Core Concepts & Information Flow: Best Practices: Minimizing Views While it might be tempting to create a separate HTML file for every single menu screen in your game, it is highly advisable to minimize the number of views created. Loading new views entirely from scratch is much heavier than updating an existing one. Instead of swapping between separate HTML documents, you should leverage tabs or routing components to consolidate multiple elements onto a single view to enhance performance. #### Routing vs. Separate Views Treat your complex screens like a Single Page Application (SPA). By using a frontend router, you can swap out panels and widgets instantly without asking the engine to spin up a brand-new HTML document. Here is a common, optimized approach to structuring a game: - **The Main Menu SPA:** Build your main menu as a Single Page Application. When the player clicks from “Play” to “Settings”, use routing to swap the content dynamically within the same view. - **The HUD Static Page:** Keep your HUD as a highly optimized, single HTML file without any complex routing. Hide and show widgets strictly through data-binding triggers. **Caution:** Avoid using complex routing or heavy state-management libraries for simple Spatial or HUD views. Keep your active DOM tree small, and rely on `data-bind-if` to add or remove elements only when they are explicitly needed by the player. Splitting the UI into views is one of several architectural decisions that are cheap to make early and expensive to reverse later. Performance Defaults covers the rest of them. --- [SOURCE: https://guide.coherent-labs.com/getting-started/hello-world/] ## Hello World: Your First Gameface UI You have seen how the Player works and how data flows between the engine and the UI. This article bridges you into the rest of the guide: the recommended tech stack, what the next section covers, and where to start if you want to get building immediately. --- [SOURCE: https://guide.coherent-labs.com/getting-started/hello-world/#what-comes-next-planning--setup] ## Hello World: Your First Gameface UI: What Comes Next: Planning & Setup The **Planning & Setup** section is where you go from understanding Gameface to actively building with it. It covers: - **Recommended Tech Stack** - which tools and frameworks work best with Gameface and why. - **Setting Up** - scaffolding a real project, connecting it to the Player, and getting HMR running. - **Prototyping & Developing** - a tour of the official Gameface UI component library and boilerplate. - **The Prototyping Workflow** - a hands-on walkthrough that builds a complete inventory screen from scratch. - **Design Work** - tools like the Figma Exporter that bridge your design files to the engine. --- [SOURCE: https://guide.coherent-labs.com/getting-started/hello-world/#the-recommended-tech-stack] ## Hello World: Your First Gameface UI: The Recommended Tech Stack For most Gameface projects we recommend: Layer | Tool | Why **Bundler** | [Vite](https://vite.dev/) | Fast dev server, native HMR, simple config, great ecosystem **Framework** | [SolidJS](https://www.solidjs.com/) | Fine-grained reactivity with minimal runtime overhead - ideal for a game engine environment **Component Library** | [Gameface UI](https://gameface-ui.coherent-labs.com/) | Official boilerplate with game-ready components pre-configured for Vite + SolidJS **Styling** | SCSS | Nesting, variables, and mixins with zero runtime cost This stack is covered in depth in Recommended Tech Stack Overview, including alternatives and the rationale behind each choice. --- [SOURCE: https://guide.coherent-labs.com/getting-started/hello-world/#start-building-now] ## Hello World: Your First Gameface UI: Start Building Now The fastest path to hands-on development is the **Prototyping Workflow** series. It walks you through building a real inventory screen step-by-step using the Gameface UI boilerplate - covering layout, components, styling, and interactivity. Start here: **Section Overview: Prototyping an Inventory** If you prefer to understand the tooling and project setup first, begin with Recommended Tech Stack Overview and follow the Planning & Setup articles in order. --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/] ## Introduction: Welcome to the UI workflow guide Welcome to the Gameface UI workflow guide ! This guide is designed to take you from zero to hero in Gameface development, covering everything from the basics of setting up your environment to advanced performance optimization techniques. Whether you’re a seasoned front-end developer, a game designer, or a gameplay programmer stepping into the UI world, this guide will provide you with the exact knowledge and tools you need to create stunning, high-performance interfaces for games. --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/#what-to-expect-in-this-guide] ## Introduction: Welcome to the UI workflow guide: What to Expect in This Guide (1/2) This guide is structured chronologically to match the typical sections of the development process. Each section builds on the previous one, so it’s recommended to follow along in order. Here’s a brief overview of what we’ll cover in each section: 1. ##### Getting Started {#getting-started} Introduction to the guide and Gameface. Learn how to load, preview, and debug your UI in the Gameface Player - the primary tool for running and testing your UI without needing to compile a game engine. 2. ##### Planning & Setup {#planning--setup} Configuring your development environment, establishing your recommended tech stack (like SolidJS and Vite), and understanding how data flows between the game and the UI. This section covers core concepts like “push vs. fetch”, how to organize your views, and bridging the gap between design and development using tools like the [Figma Exporter ](https://www.figma.com/community/plugin/1595556380268929590/coherent-gameface-exporter). We also bridge to prototyping by introducing [Gameface UI ](https://gameface-ui.coherent-labs.com/)- our component library that makes prototyping fast and easy. 3. ##### Building with AI {#building-with-ai} Setting up a coding agent that understands Gameface. We cover the MCP server that connects an agent to a running Player, the documentation corpus and negative ruleset that stop it writing browser CSS the engine cannot render, and the skill that pins a feature down before any code gets written. We also write up the UIs we have built this way ourselves, including the parts that went badly. --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/#what-to-expect-in-this-guide] ## Introduction: Welcome to the UI workflow guide: What to Expect in This Guide (2/2) 4. ##### Layout, Assets & Styling {#layout-assets--styling} The fun part! We cover how to translate designs into clean, scalable game UIs. You will learn when to use absolute versus flex layouts, write maintainable and performant CSS using BEM & SCSS, and build interfaces that scale perfectly across different aspect ratios . We also explore best practices for handling complex typography, rendering vector graphics and assets, and bringing your UI to life with high-performance animations . 5. ##### Logic & Interactions {#logic--interactions} Now that you have a beautiful UI, it’s time to make it interactive! In this section, we bridge the gap between static UI and information-rich, dynamic interfaces. We cover how to mock real game data to test your UI independently, manage local versus game state using data-binding , and handle complex user inputs like gamepad, touch support, and spatial navigation using the [Interaction Manager ](https://frontend-tools.coherent-labs.com/interaction-manager/getting-started/). 6. ##### Polishing {#polishing} The final 10%. We cover how to polish your UI to make it feel smooth, accessible, bug-free, and most importantly, performant. Learn how to implement native localization and accessibility features, master the performance profiler, and write high-performance CSS. We also deep-dive into advanced, Gameface-exclusive rendering features like Live Views, Compositor effects, and backdrop filters . --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/#what-you-wont-find-in-this-guide] ## Introduction: Welcome to the UI workflow guide: What You Won’t Find in This Guide To keep this guide lean and focused on UI creation, we have intentionally excluded backend development. You will not find: - C++ tutorials or engine-specific integration steps (Unreal, Unity, or custom engines). - Deep dives into the Gameface API. - Instructions on how to compile or initialize the Gameface library within your game. *If you are a backend programmer looking for engine integration, please refer to the [official Gameface technical documentation ](https://docs.coherent-labs.com/cpp-gameface/).* --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/#your-content-creation-reference] ## Introduction: Welcome to the UI workflow guide: Your Content Creation Reference Think of this guide as your long-term UI playbook. While it is structured as a chronological course for beginners, it is ultimately designed to be your daily reference manual . Want to localize your UI? Jump straight to the *Localization* section. Trying to remember how to handle ultrawide monitors? Check the *Scalability* page. Need to set up a new animation library? Head over to *Animations*. Keep this guide bookmarked and refer back to it whenever you hit a UI roadblock. **Structure is not mandatory:** While the guide is structured in a way that builds on previous knowledge, feel free to jump around and explore the sections that interest you the most. Each section is designed to be self-contained, so you can pick and choose the topics that are most relevant to your current project’s progress or just for quick reference. --- [SOURCE: https://guide.coherent-labs.com/getting-started/introduction/#who-is-this-guide-for] ## Introduction: Welcome to the UI workflow guide: Who Is This Guide For? **Short answer**: Everyone working with Gameface! Because team structures vary wildly, we built this guide for a wide range of skill sets. Whether you are a seasoned front-end developer using Gameface for the first time, a UI/UX designer looking to understand the engine’s capabilities, or a Unity/Unreal gameplay programmer who has never worked with web technologies before - this guide has something for you. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/] ## The Gameface Player The Gameface Player is a standalone desktop application that lets you preview and test your game UI as you develop it. It loads HTML pages, handles input, and gives you access to profiling and debugging tools - all without needing to integrate your UI into a game engine first. The biggest bottleneck in traditional game UI development is the engine. Waiting for Unreal or Unity to compile just to see if a widget is centered or a health bar updates ruins iteration speed. The Player removes that bottleneck: drag and drop your HTML files and see them render exactly as they would in the game. #### Running the Player The Player ships with your Gameface package. Run it with the provided launcher for your platform: - **Windows:** `Player.bat` - **macOS:** `Player.sh` --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#the-player-gui] ## The Gameface Player: The Player GUI (1/2) The Player provides its own window controls, live statistics and a console, so most day-to-day work does not require an external tool. #### Statistics Strip The title bar reports frame time, FPS, memory used, allocation count, allocations and time in the last frame, and GPU memory. These update continuously, which makes rising frame time visible during editing without opening a profiler. #### Toolbar The toolbar provides navigation and reload, plus four Player-specific controls: - **Address bar** - loads a local file path or an `http://` address. `Ctrl+L` focuses it. - **Bookmarks** - the star bookmarks the current page, and the bookmark bar holds frequently used views. Bookmarks are stored in `CohtmlBookmarks.html` next to the Player executable, in the standard HTML bookmarks format, so a file exported from any browser can be imported. - **Aspect ratio** - defaults to Fill , which uses the whole window. Selecting a fixed ratio letterboxes the view, which tests a 21:9 or 4:3 layout without resizing the window or changing display resolution. - **Console toggle** - shows and hides the console panel. `Ctrl+F11` hides the entire GUI. The toolbar occupies space the game will not, so hide it before evaluating a layout or capturing a screenshot. #### Console Panel The console docks to the bottom of the window and carries timestamped Gameface and JavaScript output, with **Clear**, **Copy All**, **Auto-scroll** and **Hide Console** controls. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#the-player-gui] ## The Gameface Player: The Player GUI (2/2) Gameface reports unsupported CSS properties here, which makes this the first place to check when a rule parses but produces no visible effect. These warnings are not forwarded to Chrome DevTools, so the Player’s console is the only place they appear. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#loading-ui] ## The Gameface Player: Loading UI The Player supports several ways to load your HTML pages: - **Drag and drop** - drag an HTML file from your file system directly onto the Player window. - **Address bar** - type a URL (local file path or `http://` address) directly into the toolbar. - **Bookmarks** - saved pages from the bookmark bar and manager. - **HTTP and WebSockets** - the Player supports loading from a local HTTP server, which enables Hot Module Replacement (HMR) with tools like Vite and Webpack. See Setting up the Gameface Stack for the full HMR setup. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#input-handling] ## The Gameface Player: Input Handling The Player forwards mouse and keyboard input to your view. On Windows, gamepad and touch input are also supported. **Gamepad Support:** The Player currently only supports Microsoft Xbox controllers on Windows. To use a Sony PlayStation DualShock controller, use third-party software such as DS4Windows to emulate it as an Xbox controller. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#keyboard-shortcuts] ## The Gameface Player: Keyboard Shortcuts Shortcut | Action F1 | Opens the Player documentation in your browser F5 | Reloads the current view Ctrl+L | Focuses the address bar Ctrl+F11 | Toggles the Player GUI F12 | Opens DevTools in Chrome (see below) Ctrl+F12 | Toggles internal profiling at level 1 Ctrl+Shift+F12 | Toggles internal profiling at level 2 --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#command-line-options] ## The Gameface Player: Command-Line Options You can pass options to the Player at launch to control the initial URL, window size, renderer, and more: ```plaintext Player.exe [OPTIONS] [positional_url...] --url TEXT Initial URL(s) to load (comma-separated for multiple views) --root TEXT Sets the root directory for "coui://" --width INT Sets the window width in pixels (default: 1280) --height INT Sets the window height in pixels (default: 720) --renderer ENUM Graphics renderer: dx11, dx12, opengl (default: dx11) --remote-debugging-port INT Port for DevTools access (default: 9444); set to -1 to disable --input ENUM Input event type: mouse or touch (default: mouse) --default-font TEXT Sets the default font family (default: Droid Sans) --redraw-all Repaints views every frame (useful for debugging) --config TEXT Path to a configuration file (default: Config.toml) ``` Run `Player.exe --help` for the full option list. #### Configuration File Instead of passing all options on the command line, you can use a `Config.toml` file. The Player looks for it in the following locations, in order of priority: 1. The path specified by `--config` 2. The current working directory 3. The directory containing the Player executable Any command-line argument can also be set in `Config.toml`. Command-line flags always override the file. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#font-loading] ## The Gameface Player: Font Loading The recommended way to load fonts is via `@font-face` in your CSS. You can also register fonts in `Config.toml`: ```toml default-font = "MyFont" [register-font] path = "URL or path to a font" family = "" sdf = "auto" style = "auto" weight = "auto" ``` Run `Player.exe register-font --help` for all available font registration options. **Note:** The Player previously used a `Config.json` file with a limited set of options (`coui-root`, `register-fonts`). That format is deprecated. Update any existing config files to `Config.toml`. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#devtools-and-debugging] ## The Gameface Player: DevTools and Debugging (1/3) Check the Player’s console first, since it carries Gameface’s own warnings alongside JavaScript output and some of those warnings never reach Chrome. DevTools then covers what the console cannot: the live DOM tree, computed styles, registered data-binding models, performance traces and the GPU debugging overlays. Press **F12** while the Player is running to open DevTools. The Player starts an HTTP server on port **9444** by default, and Chrome connects to it as a remote debugging target. **To connect:** 1. Start the Player with your UI loaded. 2. Open **Google Chrome** (required - other browsers are not supported) and navigate to: ```plaintext http://localhost:9444 ``` 3. A list of available views appears. Click the view you want to inspect. From there, DevTools gives you: --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#devtools-and-debugging] ## The Gameface Player: DevTools and Debugging (2/3) - **Elements panel** - inspect and modify the DOM tree, view computed styles, and use the **Data Binding tab** to inspect `data-bind-*` attributes and their evaluated values. - **Console** - JavaScript logs and errors, plus an interactive prompt for evaluating expressions against the running view. It does not receive everything the Player’s own console shows. Warnings raised by Gameface itself, such as reports of unsupported CSS properties, appear only in the Player. - **Sources** - debug JavaScript and set breakpoints. - **Performance** - profile rendering: style recalculations, layout, script execution, GPU time, and paint. - **Network** - inspect resource requests and WebSocket messages. - **Data Binding Models** - access via More Tools (⋮) → Data Binding Models to view, edit, and export all registered data-binding models live. - **Cohtml panel** - access via More Tools (⋮) → Cohtml to toggle GPU debugging options: Paint Flashing (highlights dirty regions re-evaluated each frame), Redraw Flashing (highlights elements physically repainted), Emit Rendering Metadata (links DOM nodes to GPU draw calls), and Rendering Caches configuration. These are the fastest tools for isolating rendering overhead during a debugging session. **Source Maps:** The DevTools inspector does not understand the `coui://` protocol, so source maps must be embedded. See the [InlineSourceMaps ](https://github.com/CoherentLabs/InlineSourceMaps)tool for embedding source maps, and configure `build.sourcemap: 'inline'` in your Vite config for development builds. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#devtools-and-debugging] ## The Gameface Player: DevTools and Debugging (3/3) If your UI uses absolute URLs (for example, URLs generated by Webpack or Vite), set the `coui://` root via `--root` at startup, or convert the absolute URLs to relative ones. For deeper coverage of profiling, layout debugging, and the Gameface-specific DevTools panels, see the Debugging, Profiling & Testing articles. --- [SOURCE: https://guide.coherent-labs.com/getting-started/the-gameface-player/#player-overrides] ## The Gameface Player: Player Overrides The Player supports customization through a PlayerOverrides.dll . This is useful for testing features that require engine-side implementation - such as localization callbacks - without building the full game. **To set up Player Overrides:** 1. Open `PlayerOverrides.sln` located in `Player/PlayerOverrides/` inside your Gameface directory. 2. Implement your desired behavior using the `CohtmlOverrides` interface in `PlayerOverrides.cpp`. 3. Build the solution. The compiled `PlayerOverrides.dll` is placed automatically in the same folder as `Player.exe`. If the overrides loaded successfully, the message `"Player Overrides Initialized"` appears in the console when the Player starts. If it does not, verify that `PlayerOverrides.dll` is in the same folder as `Player.exe` and that the build completed without errors. To preserve or switch between different override configurations, keep multiple `PlayerOverrides.dll` files and place the one you need next to `Player.exe` before launching. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animated-assets/] ## Animated Assets: GIFs & Videos Motion brings a UI to life, but using the wrong asset type can put significant pressure on your game’s memory and performance budget. This article covers the constraints of GIF animations, how to implement WebM video playback correctly, and why you should prioritize alternatives like Sprite Sheets and Live Views for most use cases. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animated-assets/#the-reality-of-gifs] ## Animated Assets: GIFs & Videos: The Reality of GIFs While GIFs are common on the traditional web, the format is generally not recommended for game UI. It carries several technical limitations that make it a poor fit for production use in Gameface. - **Compression and file size.** GIF animations rely on an older compression algorithm. For the same animation, a GIF file tends to be 5 to 10 times larger than an equivalent efficiently encoded video. This translates directly into larger asset bundles and longer load times. - **Visual quality.** The GIF standard supports only 256 colors per frame and provides no support for semi-transparency. Every pixel is either fully opaque or fully transparent. Artwork with gradients or soft alpha edges will show visible color banding and rough outlines compared to formats like PNG. - **Memory consumption.** Gameface optimizes GIF playback by preloading all frames to avoid decoding them at runtime. While this prevents per-frame CPU spikes during animation, it means the entire animation is unpacked into memory up front. High-resolution or high-framerate GIFs will have a notable impact on your game’s memory consumption. **Preloading Memory Behavior:** Because Gameface preloads every GIF frame into RAM, a single high-resolution GIF with many frames can consume a disproportionate amount of memory relative to its visual value. Always keep GIF assets small and short to avoid unexpected memory pressure. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animated-assets/#safe-gif-usage] ## Animated Assets: GIFs & Videos: Safe GIF Usage If your design requires GIF animations, they remain practical for one specific use case: small animated emojis . GIFs are currently supported as a source for `` elements. To keep memory consumption manageable, follow these limits: - Keep the resolution at or below 128x128 pixels . - Keep the frame count at or below 30 frames per animation. #### How to Use GIFs The only supported way to render GIF animations in Gameface is through standard HTML `` tags. The following example places a small animated emoji inline within a chat message: ```html
Great shot! Thumbs Up
``` **Why Only \?:** Gameface’s GIF preloading pipeline is built around the `` element rendering path. Other rendering paths (CSS backgrounds, masks) do not go through this pipeline, so GIF animation will not work through those properties. #### Unsupported GIF Usage GIFs are not supported as values for `background-image`, `border-image`, or `mask-image`. Further support and enhancements for these CSS properties **are not planned**. The following patterns **will not** produce an animated result in Gameface: ```css /* Unsupported: GIF as a CSS background will not animate */ .chat-reaction-button { width: 64px; height: 64px; background-image: url("spinning_star.gif"); } /* Unsupported: GIF as a CSS mask will not animate */ .avatar-mask { mask-image: url("animated_mask.gif"); } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animated-assets/#playing-videos-video] ## Animated Assets: GIFs & Videos: Playing Videos (
` elements stacked on top of each other. Each one is just a mask combined with a flat color, so the GPU only sees about five texture samples per frame and the whole effect stays fully recolorable through CSS variables. #### The HTML Skeleton Five divs, all absolutely positioned inside a 300 by 300 container: **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; const SpiralEffect = () => ( ); ``` **HTML:** ```html
``` The `.green` class on the wrapper carries the entire color palette as CSS custom properties. ```css .green { --color: #83e597; --secondaryColor: #5a9ba6; --ternaryColor: #d8fadf; --gradientColor: #b2faf5; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/sprite-sheet-animations/#breaking-down-a-layered-vfx] ## Sprite Sheet Animations: Building High-Performance VFX: Breaking Down a Layered VFX (2/6) DOM order determines the z-stack: `.spiral-3` sits at the back, `.particles` on top, with the background and cross icon anchored in the middle. Three of those layers (`.spiral`, `.spiral-2`, `.particles`) are driven by sprite strips. All three use the same 15-frame layout at 300px per frame (4500 by 300 pixels total). The remaining two layers (`.spiral-3` and the background/cross) use static images instead. #### Step 1: The Anchor We start with the ability-slot icon, a dark square background with a cross-shaped icon on top. The background is a plain static image. The cross uses an SVG mask filled with a striped gradient that scrolls vertically, producing a subtle scanning-line effect. ```css .container { position: relative; width: 300px; height: 300px; } .background { position: absolute; width: 100%; height: 100%; background-image: url(./item-background.png); background-position: center; background-repeat: no-repeat; background-size: contain; } .cross { position: absolute; width: 100%; height: 100%; mask-image: url(./cross.svg); mask-repeat: no-repeat; mask-position: center; background-image: linear-gradient(to bottom, var(--color), var(--color) 50%, var(--gradientColor) 50%, var(--gradientColor)); background-size: 100% 8px; animation: backgroundAnimation 20s linear infinite; } @keyframes backgroundAnimation { from { background-position: 0% 0%; } to { background-position: 0% 100%; } } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/sprite-sheet-animations/#breaking-down-a-layered-vfx] ## Sprite Sheet Animations: Building High-Performance VFX: Breaking Down a Layered VFX (3/6) **Not everything needs to be a sprite sheet:** Some effects can’t be achieved with CSS only, which is always the preferred approach. This is a good example of that. The two-color gradient on the cross is set to `background-size: 100% 8px`, which tiles it vertically into 4px-tall stripes. The `backgroundAnimation` keyframe slowly scrolls those stripes upward through the cross-shaped SVG mask, giving the icon a calm scanning-line texture without any sprite work. #### Step 2: Ambient Glow Behind the cross we slip in a slowly rotating jagged silhouette. This layer is **not** a sprite sheet - it’s a single static silhouette image, rotated continuously. Its job is to add a soft, organic pulse of motion beneath everything else. ```css .spiral-3 { position: absolute; background-color: var(--ternaryColor); mask-image: url(./spiral-effect-3.png); animation: rotate 1.2s infinite linear; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ``` `linear` timing keeps the rotation speed constant, and the irregular silhouette edge creates organic motion as it spins. The result is a quiet ambient layer that the louder sprite animations will sit on top of. #### Step 3: Main Spiral Now we add the first sprite-sheet layer, `.spiral`. This is where the `steps()` and `mask-position` mechanics from earlier in this article finally come into play in context. Here is the spiral effect strip that we will use for this layer. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/sprite-sheet-animations/#breaking-down-a-layered-vfx] ## Sprite Sheet Animations: Building High-Performance VFX: Breaking Down a Layered VFX (4/6) ```css .spiral { position: absolute; background-color: var(--color); mask-image: url(./spiral-effect.png); mask-repeat: no-repeat; animation: spriteAnimation 0.8s steps(15) infinite; } @keyframes spriteAnimation { from { mask-position: 0px 0px; } to { mask-position: -4500px 0px; } } ``` The `-4500px` end position is 15 frames multiplied by the 300px frame width, and `steps(15)` makes the playback advance in exactly 15 discrete jumps - one per frame. This same keyframe will be reused by another sprite layer in the next step. #### Step 4: Secondary Spiral A second sprite-animated spiral with a different mask and a cooler color. It inherits everything from `.spiral`, so we only need to override the two things that actually change: ```css .spiral-2 { background-color: var(--secondaryColor); mask-image: url(./spiral-effect-2.png); } ``` Because `.spiral-2` shares the same `spriteAnimation` keyframes and timing as `.spiral`, both spirals play in sync. The visual overlap between two independently shaped spirals creates depth that neither could produce on its own. #### Step 5: Particles The final layer on top - a sprite strip of glowing particles drifting over everything else. ```css .particles { position: absolute; width: 100%; height: 100%; background-color: var(--gradientColor); mask-image: url(./particles.png); mask-repeat: no-repeat; animation: spriteAnimation 1s steps(15) infinite; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/sprite-sheet-animations/#breaking-down-a-layered-vfx] ## Sprite Sheet Animations: Building High-Performance VFX: Breaking Down a Layered VFX (5/6) Notice the duration is `1s` instead of the spirals’ `0.8s`. That tiny mismatch keeps the layers from feeling mechanically locked together and gives the particles their own rhythm. With this layer in place, the effect is complete: #### Recoloring with Palette Classes The whole effect is wired through four CSS custom properties defined on the container. Every animated layer pulls its color from one of them, which means swapping the palette class on the wrapper recolors every layer at once. The inner DOM doesn’t change at all: ```css .green { --color: #83e597; --secondaryColor: #5a9ba6; --ternaryColor: #d8fadf; --gradientColor: #b2faf5; } .red { --color: #e58383; --secondaryColor: #a65a5a; --ternaryColor: #fad8d8; --gradientColor: #fab2b2; } .blue { --color: #8397e5; --secondaryColor: #5a6da6; --ternaryColor: #d8dffa; --gradientColor: #b2c0fa; } ``` **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; const SpiralVariants = () => ( <> ); ``` **HTML:** ```html
...
...
...
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/sprite-sheet-animations/#breaking-down-a-layered-vfx] ## Sprite Sheet Animations: Building High-Performance VFX: Breaking Down a Layered VFX (6/6) **The Core Advantage:** No new sprite sheets, no new keyframes, no duplicated CSS rules. This is the core advantage of the `mask-image` approach: the same set of assets can serve every rarity tier, element type, or faction color in your game. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/svg-animations/] ## SVG Animations: Vector Motion and Effects This article picks up where SVG UI Tricks left off. We already covered how to change fills and strokes with class toggles and how to reveal paths with stroke-dashoffset . Here we will briefly cover how to turn those same techniques into CSS keyframe animations and find all SVG-specific animation constraints in Gameface collected in one place. Inline SVGs are part of the DOM, so every animation technique from the UI Animations article (transitions, `@keyframes`, the Web Animations API) applies to SVG elements exactly the same way it applies to a `
` or a `
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-transitions] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Transitions (2/4) The transition is declared on the base class. This tells the engine which properties to watch and how to interpolate them whenever their computed values change: ```css .action-btn { background: rgba(255, 255, 255, 0.06); color: #8a939c; padding: 1.2vh 3vh; border: 0.15vh solid rgba(255, 255, 255, 0.1); font-size: 2vh; cursor: pointer; transition: background 200ms ease, color 200ms ease, border-color 200ms ease; } .action-btn:hover { background: rgba(78, 205, 196, 0.15); color: #ffffff; border-color: rgba(78, 205, 196, 0.5); } .action-btn--active, .action-btn--active:hover { background: rgba(78, 205, 196, 0.25); color: #ffffff; border-color: #4ecdc4; } ``` When the user hovers over a button, the engine detects that `background`, `color`, and `border-color` have new target values and smoothly interpolates from the old values to the new ones over 200 milliseconds . Removing the hover state reverses the animation automatically because the target values revert to their base rule values. A JavaScript toggle can apply the same effect programmatically: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-transitions] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Transitions (3/4) ```tsx import { createSignal } from 'solid-js'; import Flex from '@components/Layout/Flex/Flex'; import Button from '@components/Basic/Button/Button'; const ACTIONS = ['Equip', 'Drop', 'Use']; const HudActions = () => { const [activeAction, setActiveAction] = createSignal('Use'); return ( {ACTIONS.map((action) => ( ))} ); }; ``` **Vanilla JS:** ```js const buttons = document.querySelectorAll(".action-btn"); buttons.forEach((btn) => { btn.addEventListener("click", () => { buttons.forEach((b) => b.classList.remove("action-btn--active")); btn.classList.add("action-btn--active"); }); }); ``` The result of the above code will look like this: #### Transition Behavior in Gameface There are a few engine-specific behaviors to be aware of when working with transitions: **No Transitions on Mount:** Transitions do not fire in the frame when an element is first added to the DOM or when its `display` property changes. The engine needs an existing computed style to interpolate from . If there is no “before” state, the transition is skipped and the element snaps to its final state immediately. The `@starting-style` rule (covered later in this article) solves this problem. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-transitions] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Transitions (4/4) **Keyframes Override Transitions:** If a CSS `@keyframes` animation is active on a property, any transition targeting that same property is ignored . The keyframe animation takes full control of the property’s value for its duration. This means you cannot layer a transition on top of an active keyframe effect for the same property. **Mid-Flight Configuration Changes:** If you change a transition’s `duration`, `easing`, or `delay` while a transition is already running, the active transition finishes with its original configuration. The updated values only take effect on the next transition trigger . This prevents jarring mid-animation snaps. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-keyframe-animations] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Keyframe Animations (1/4) While transitions handle simple A-to-B changes, some UI effects require multiple intermediate steps, looping behavior, or automatic playback without a trigger. These are the cases where CSS `@keyframes` animations are the right tool. The key differences from transitions are: - **Multi-step control.** Keyframes define an arbitrary number of intermediate states using percentage stops or `from`/`to` shorthand. - **Auto-play.** A keyframe animation starts as soon as its rule is applied to an element. It does not need a property change to trigger it. - **Looping.** The `animation-iteration-count` property supports `infinite` repetition, which is common for ambient UI effects. - **Fill behavior.** The `animation-fill-mode` property controls whether animated values persist after the animation ends (`forwards`), apply before it starts (`backwards`), or both. The `animation` shorthand follows this order: ```css animation: ; ``` #### Looping Pulse Animation A common game UI pattern is an ability slot that pulses or glows when the ability is ready. The glow loops continuously until the player activates it, at which point the animation class is removed. **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-keyframe-animations] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Keyframe Animations (2/4) ```tsx import { createSignal } from 'solid-js'; import Flex from '@components/Layout/Flex/Flex'; import Block from '@components/Layout/Block/Block'; const AbilityBar = () => { const [abilityReady, setAbilityReady] = createSignal(true); return ( ); }; ``` **HTML:** ```html
⚔
🛡
``` ```js const ability = document.getElementById("ability-secondary"); function onAbilityUsed() { ability.classList.remove("ability-slot--ready"); } function onAbilityCooldownComplete() { ability.classList.add("ability-slot--ready"); } ``` The keyframe animation defines three stops that create a continuous pulse cycle: start dim, peak bright, return to dim. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-keyframe-animations] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Keyframe Animations (3/4) ```css @keyframes pulse-glow { 0% { box-shadow: 0 0 0.8vh rgba(78, 205, 196, 0.2); border-color: rgba(78, 205, 196, 0.3); } 50% { box-shadow: 0 0 2.5vh rgba(78, 205, 196, 0.6); border-color: rgba(78, 205, 196, 0.9); } 100% { box-shadow: 0 0 0.8vh rgba(78, 205, 196, 0.2); border-color: rgba(78, 205, 196, 0.3); } } .ability-slot { width: 8vh; height: 8vh; display: flex; align-items: center; justify-content: center; background: rgba(0, 0, 0, 0.5); border: 0.2vh solid rgba(255, 255, 255, 0.1); border-radius: 0.8vh; font-size: 3.5vh; } .ability-slot--ready { /* Loops forever with a smooth breathing effect */ animation: pulse-glow 2s ease-in-out infinite; } ``` The animation starts as soon as the `ability-slot--ready` class is applied and loops with `infinite`. The `ease-in-out` easing produces a smooth breathing rhythm. To stop the glow when the player uses the ability, remove the class. To restart it after a cooldown, add it back: The result of the above code will look like this: #### Multi-Step Entrance Animation Keyframes also handle entrance effects that need more than two states. A notification badge that scales up with an overshoot, then settles to its final size, is a classic three-step pattern: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#css-keyframe-animations] ## UI Animations: Transitions, Keyframes, and JS Control: CSS Keyframe Animations (4/4) ```tsx import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const NotificationBadge = () => ( Quest Complete! ); ``` **HTML:** ```html
Quest Complete!
``` ```css @keyframes badge-entrance { 0% { opacity: 0; transform: scale(0.5); } 60% { opacity: 1; transform: scale(1.08); /* Slight overshoot past the target size */ } 100% { opacity: 1; transform: scale(1); /* Settle to the final size */ } } .hud-notification { background: rgba(78, 205, 196, 0.15); border: 0.15vh solid #4ecdc4; border-radius: 0.6vh; padding: 1vh 2.5vh; color: #ffffff; font-size: 1.8vh; animation: badge-entrance 400ms ease-out forwards; } ``` The `forwards` fill mode keeps the final keyframe values applied after the animation ends. Without it, the element would snap back to its pre-animation state. The result of the above code will look like this: **Transitions vs. Keyframes: When to Pick Which:** Use transitions when the animation is a direct response to a state change (hover, focus, class toggle) and only involves two states (start and end). Use keyframes when the animation needs multiple intermediate steps, should loop indefinitely, or must auto-play without waiting for a property change to trigger it. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#mounting-animations-with-starting-style] ## UI Animations: Transitions, Keyframes, and JS Control: Mounting Animations with @starting-style (1/3) As noted in the transitions section, standard CSS transitions fail to trigger when an element is newly inserted into the DOM or when its `display` property changes from `none` to a visible value. The engine skips the transition because there is no prior computed style to interpolate from. Before `@starting-style`, the standard workaround required a two-step JavaScript approach: insert the element with its initial styles, force a layout recalculation, then apply the target styles in a separate step. This works, but it adds JavaScript complexity and introduces a layout flush. `@starting-style` solves this entirely in CSS. It defines a set of property values that the engine treats as the “from” state specifically when an element first appears. Combined with a `transition` on those properties, the element animates from the starting values to its declared state with zero JavaScript animation logic. #### How @starting-style Works The rule has a straightforward structure. Inside the `@starting-style` block, you write selectors and properties just like a normal stylesheet. These values are only applied once, at the moment the element first matches the selector (on DOM insertion or a `display` change). After that initial frame, the regular styles take over and the declared `transition` animates between the two states. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#mounting-animations-with-starting-style] ## UI Animations: Transitions, Keyframes, and JS Control: Mounting Animations with @starting-style (2/3) ```css /* The element's final (visible) state */ .modal { opacity: 1; transform: translateY(0); transition: opacity 300ms ease, transform 300ms ease; } /* Applied only on first appearance, then immediately overridden by the rules above */ @starting-style { .modal { opacity: 0; transform: translateY(2vh); } } ``` When the engine encounters `.modal` for the first time, it reads the `@starting-style` values as the initial computed style and the regular `.modal` rule as the target. Because `transition` is declared on both `opacity` and `transform`, the engine interpolates between them. To trigger the animation, simply insert the element into the DOM. No JavaScript animation logic is needed: ```js const modal = document.getElementById("quest-modal"); function showQuestModal() { document.body.appendChild(modal); } function hideQuestModal() { modal.remove(); } document.getElementById("accept-btn").addEventListener("click", hideQuestModal); document.getElementById("decline-btn").addEventListener("click", hideQuestModal); ``` A full example of the starting style modal looks like this: **Why It Works:** When the `modal` element is appended, the engine encounters `.quest-modal` for the first time. It checks `@starting-style`, finds matching rules, and uses those values (`opacity: 0; transform: translateY(2vh)`) as the initial computed style. In the same frame, it resolves the regular `.quest-modal` rules (`opacity: 1; transform: translateY(0)`). Because a `transition` is declared on both properties, the engine --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#mounting-animations-with-starting-style] ## UI Animations: Transitions, Keyframes, and JS Control: Mounting Animations with @starting-style (3/3) interpolates between them , producing a smooth fade and slide with no JavaScript animation code. You can also use `@starting-style` to transition toward the initial (default) value of a property. In this case, you do not need to explicitly set the target in the element’s regular rule, because the engine uses the property’s initial value as the target: ```css .fade-element { /* opacity defaults to 1, so no explicit declaration is needed */ transition: opacity 300ms ease; } @starting-style { .fade-element { opacity: 0; } } ``` #### Limitations in Gameface There are a few constraints to keep in mind when using `@starting-style`: **No Nested Syntax:** Gameface does not currently support the selector-scoped (nested) form of `@starting-style`. The `@starting-style` block must be written at the top level of your stylesheet, not nested inside another rule. ```css /* This will NOT work in Gameface */ .quest-modal { opacity: 1; @starting-style { opacity: 0; } } /* Use this top-level form instead */ .quest-modal { opacity: 1; transition: opacity 300ms ease; } @starting-style { .quest-modal { opacity: 0; } } ``` **Other Limitations:** - `@starting-style` does not work with out-of-line SVGs. - Custom expressions are not supported inside `@starting-style` rules. ::: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (1/6) CSS handles the majority of game UI animation needs, but there are scenarios where you need runtime playback control. Pausing all UI animations when the game menu opens, seeking to a specific point in a progress-driven animation, or synchronizing a timeline to a game event all require JavaScript intervention. Gameface supports a subset of the Web Animations API , which gives programmatic access to CSS animations already running on DOM elements. The key principle is that you define the animation in CSS (where it benefits from native performance) and use JavaScript only to control its playback state. #### Accessing Animations with getAnimations() The `Node.getAnimations()` method returns an array of all resolved animations on a given element. This includes both CSS `@keyframes` animations and CSS transitions that are currently active. Here is a charging status bar with a multi-phase keyframe animation that we will control from JavaScript: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (2/6) ```tsx import { onMount } from 'solid-js'; import Block from '@components/Layout/Block/Block'; import Button from '@components/Basic/Button/Button'; const ChargeBar = () => { let fillRef!: HTMLElement; onMount(() => { // Web Animations API: fillRef.getAnimations()[0].play() etc. }); return ( <> ); }; ``` **HTML:** ```html
Idle
``` The keyframe animation defines the full charging sequence as a single timeline. The bar fills in phases, with the color shifting at each stage: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (3/6) **Animating width triggers a full layout solve every frame:** Changing `width` inside a `@keyframes` animation causes Gameface to run a full **Yoga flex layout solve** on every animation frame - one of the most expensive operations in the pipeline. This is the straightforward approach and works fine for infrequent or short-lived animations. For bars that animate continuously or at high frequency, prefer the `transform: scaleX()` pattern instead (see the alternative below). **Option A - `width` (used in this example):** simpler to understand; triggers `SolveFlexLayout` every frame. **Option B - `transform: scaleX()` (recommended for performance):** set the fill to `width: 100%` and `transform-origin: left center`, then animate `scaleX` from `0` to `1`. The bar track must use `overflow: hidden`. This keeps animation on the cheaper `Update Node Transforms` path and never touches Yoga. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (4/6) ```css @keyframes charge-sequence { 0% { width: 0%; background: #3a3a4a; } 50% { width: 50%; background: #4ecdc4; } 80% { width: 80%; background: #f2a34e; } 100% { width: 100%; background: #4ef28b; } } .charge-bar__track { width: 30vh; height: 3vh; background: rgba(255, 255, 255, 0.08); border-radius: 0.4vh; overflow: hidden; } .charge-bar__fill { height: 100%; border-radius: 0.4vh; animation: charge-sequence 4s ease-in-out forwards paused; /* Start paused for JS control */ } .charge-bar__label { color: #a0aab4; font-size: 1.4vh; margin-top: 0.5vh; display: block; } ``` **Paused Animation:** Notice the `paused` keyword in the animation shorthand. This prevents the animation from auto-playing, giving JavaScript full control over when it starts. #### Basic Playback: Play, Pause, and Seek With the animation defined in CSS, use `getAnimations()` to retrieve the animation object and control it: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (5/6) ```js const fill = document.getElementById("charge-fill"); const label = document.getElementById("charge-label"); const animations = fill.getAnimations(); const chargeAnim = animations[0]; // PLAY document.getElementById("play-btn").addEventListener("click", () => { chargeAnim.play(); label.textContent = "Charging..."; }); // PAUSE document.getElementById("pause-btn").addEventListener("click", () => { chargeAnim.pause(); label.textContent = "Paused"; }); // RESET document.getElementById("reset-btn").addEventListener("click", () => { chargeAnim.currentTime = 0; chargeAnim.pause(); label.textContent = "Idle"; }); // SEEK TO 50% document.getElementById("seek-half-btn").addEventListener("click", () => { chargeAnim.currentTime = DURATION / 2; label.textContent = "Seeked to 50%"; }); ``` The `currentTime` property accepts a value in milliseconds measured from the start of the animation. Setting it directly jumps the animation to that point in the timeline without interpolation , which is useful for syncing a UI animation to an external game state. #### Gameface’s playFromTo() Method Gameface extends the standard Web Animations API with a custom method: `playFromTo(startTimeMs, pauseTimeMs)` . When called, the animation seeks to `startTimeMs` and automatically pauses when it reaches `pauseTimeMs`. Both values are in milliseconds, counted from the beginning of the animation. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/ui-animations/#controlling-animations-with-javascript] ## UI Animations: Transitions, Keyframes, and JS Control: Controlling Animations with JavaScript (6/6) This is particularly useful for animations that represent multiple logical phases within a single timeline. Instead of splitting the animation into separate keyframe definitions, you define one continuous timeline and use `playFromTo()` to play specific segments on demand. Using the same charging bar, the 4-second animation can be divided into logical phases: ```js const fill = document.getElementById("charge-fill"); const chargeAnim = fill.getAnimations()[0]; /* Phase 1: 0% to 50% fill (0ms to 2000ms in the 4s timeline) */ function playPhaseOne() { chargeAnim.playFromTo(0, 2000); } /* Phase 2: 50% to 80% fill (2000ms to 3200ms) */ function playPhaseTwo() { chargeAnim.playFromTo(2000, 3200); } /* Phase 3: 80% to 100% fill (3200ms to 4000ms) */ function playFinalPhase() { chargeAnim.playFromTo(3200, 4000); } ``` Each call plays only the specified segment and pauses at the endpoint. The game logic can decide which phase to trigger based on player actions, quest progress, or any other external state. **Cancelling a Scheduled Pause:** Calling `play()`, `pause()`, or any other control method while the animation has not yet reached its scheduled `pauseTimeMs` will cancel the scheduled pause. The animation will then continue playing (or stop, depending on which method was called) without respecting the original `pauseTimeMs` boundary. This gives you full override capability at any point during playback. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/] ## Web Animations API (WAAPI) This article extends the WAAPI introduction in UI Animations. It documents the rest of the supported methods & properties in Gameface, the parts of the standard API that are not exposed , and the practical patterns that combine these methods into common game UI behaviors. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#gamefaces-waapi-subset] ## Web Animations API (WAAPI): Gameface’s WAAPI Subset (1/2) WAAPI in Gameface is a deliberate subset focused on controlling CSS-defined animations from JavaScript . The imperative constructors that let standard browsers create animations directly in JavaScript - `element.animate()`, `new Animation()`, `new KeyframeEffect()` - are not available. Knowing the boundary up front saves a lot of debugging time when porting browser code. #### Supported Name | Type | Purpose `element.getAnimations()` | Method | Retrieve all `Animation` objects active on an element. The only entry point. `play()`, `pause()` | Method | Start, resume, or pause playback. `reverse()` | Method | Flip the playback direction. `finish()` | Method | Jump immediately to the end state. `cancel()` | Method | Stop playback and remove the animation effect. `commitStyles()` | Method | Write the current animated values into the element’s inline style. `persist()` | Method | Prevent automatic removal when a filling animation is replaced. See note. `playFromTo(start, end)` | Method | Gameface extension. Play a specific timeline segment, then auto-pause. `currentTime` | Property | Get or set the current timeline position in milliseconds. `playbackRate` | Property | Get or set the playback speed and direction. #### Not Supported Anything not in the table above is not exposed. In practice, the standard-API gaps that come up most often when porting browser code have a direct alternative in Gameface: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#gamefaces-waapi-subset] ## Web Animations API (WAAPI): Gameface’s WAAPI Subset (2/2) **The Big One: No element.animate():** The most common WAAPI pattern in MDN tutorials and Stack Overflow answers - `element.animate([{...}, {...}], { duration: 500 })` - does not work in Gameface. You must always author the motion in a `@keyframes` rule and retrieve it through `getAnimations()`. This is also the recommended approach for performance, since CSS-authored keyframes evaluate in the engine’s native rendering pipeline. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#look-up-the-animation-once] ## Web Animations API (WAAPI): Look Up the Animation Once Every call to `getAnimations()` walks the element’s resolved animation list and allocates a fresh array. In a HUD that reacts to gameplay events many times per second, calling it inside an event handler or a game-loop callback is unnecessary work. Avoid looking the animation up every time you need to control it: ```js function showWarning() { const warningPulse = warningIcon.getAnimations()[0]; warningPulse.currentTime = 0; warningPulse.play(); } ``` Retrieve it once during setup and keep the reference around. All later playback calls go through the stored variable: ```js const warningPulse = warningIcon.getAnimations()[0]; function showWarning() { warningPulse.currentTime = 0; warningPulse.play(); } function hideWarning() { warningPulse.reverse(); } ``` CSS-declared animations stay attached to the element for as long as the CSS rule applies, so a stored reference remains valid across any number of play/pause/reverse cycles. There is no need to call `persist()` here - that method solves a different problem specific to imperative `element.animate()` calls. See `persist()` for details. **The Performance Win:** Looking the animation up once keeps JavaScript out of the per-frame value computation path. Your code only signals when playback should start, stop, or reverse. The engine’s animation system advances the CSS timeline natively. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#playback-control] ## Web Animations API (WAAPI): Playback Control (1/3) `play()` and `pause()` cover the basic start/stop case (see the UI Animations article). The three methods below extend that with reversing, jumping to the end, and discarding an animation entirely. #### reverse() `reverse()` flips the sign of the playback direction and continues playing from the current timeline position. It is functionally equivalent to assigning `playbackRate = -1` and then calling `play()`. The method is the cleanest way to implement open/close panels with a single keyframe definition. Define the “open” animation in CSS, play it forward to open the panel, and call `reverse()` to close it from wherever the open animation got to. ```css @keyframes quest-panel-open { from { opacity: 0; transform: translateX(-4vh); } to { opacity: 1; transform: translateX(0); } } .quest-panel { animation: quest-panel-open 280ms ease-out both paused; } ``` ```js const panel = document.getElementById("quest-panel"); const openAnim = panel.getAnimations()[0]; function openPanel() { openAnim.playbackRate = 1; openAnim.play(); } function closePanel() { openAnim.reverse(); } ``` **Preserve the Visual State:** The `both` fill mode keeps the element at the first keyframe before playback and at the last keyframe afterward, so the panel does not snap back to its underlying CSS values when the animation is not actively driving them. #### finish() --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#playback-control] ## Web Animations API (WAAPI): Playback Control (2/3) `finish()` jumps the animation to its end state and stops playback. Use it for skip-to-end behaviors: a “skip cinematic” button, a HUD that should snap to its final state when the player presses any key, or a delayed-reveal animation that should complete instantly on a state change. ```js const introCard = document.getElementById("intro-card"); const introAnim = introCard.getAnimations()[0]; document.getElementById("skip-btn").addEventListener("click", () => { introAnim.finish(); }); ``` After `finish()`, the animation is in its end state but is still attached to the element. The next `play()` call restarts it from the beginning. #### cancel() vs pause() `pause()` and `cancel()` look similar at first glance - both stop the animation - but they have very different effects on the element’s visual state. - `pause()` freezes the animation at the current timeline position. The animated values keep being applied, so the element holds its current visual state. - `cancel()` aborts the animation entirely and removes its effect from the element. The element snaps back to its underlying CSS values from the regular stylesheet. ```js const panel = document.getElementById("status-panel"); const fadeAnim = panel.getAnimations()[0]; function holdCurrentState() { fadeAnim.pause(); } function discardAnimation() { fadeAnim.cancel(); } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#playback-control] ## Web Animations API (WAAPI): Playback Control (3/3) **Cancelling a Faded-In Element Makes It Disappear:** If your CSS rule has `opacity: 0` as the underlying value and the keyframe animates it to `1`, calling `cancel()` will revert the element to `opacity: 0`. To preserve the visual state before discarding the animation, call `commitStyles()` first. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#preserving-the-visual-state] ## Web Animations API (WAAPI): Preserving the Visual State (1/2) By default, an animation’s effect on an element only lasts as long as the animation is alive. Once it is cancelled or its effect is otherwise removed, the element returns to its underlying CSS values. The two methods below let you decide how that visual state is handled when the timeline ends. #### commitStyles() `commitStyles()` writes the animation’s currently computed values into the element’s inline `style` attribute. Pair it with `cancel()` when you want to freeze the element at an arbitrary point in the timeline and discard the animation entirely. For end-state persistence after the animation finishes, you usually do not need `commitStyles()` at all - the CSS `animation-fill-mode: forwards` declaration already keeps the final keyframe applied. `commitStyles()` is the right tool when you need an intermediate state to persist, for example a charging bar that should freeze at whatever fill level it had reached when the player released the trigger. ```js const fill = document.getElementById("charge-fill"); const chargeAnim = fill.getAnimations()[0]; function startCharging() { chargeAnim.currentTime = 0; chargeAnim.play(); } function releaseTrigger() { chargeAnim.pause(); chargeAnim.commitStyles(); chargeAnim.cancel(); } ``` After `releaseTrigger()` runs, the bar’s current fill width and color are written to the element’s inline `style` and the animation is gone from `getAnimations()`. The element will hold that visual indefinitely without an animation actively driving it. #### persist() --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#preserving-the-visual-state] ## Web Animations API (WAAPI): Preserving the Visual State (2/2) In Gameface, `persist()` is effectively a no-op exposed only for API completeness. In standard browsers, this method prevents the automatic removal of overlapping animations created imperatively via `element.animate()`. Because Gameface relies exclusively on CSS-declared animations and does not support `element.animate()`, the auto-removal scenario that `persist()` guards against cannot occur. You do not need to use persist() in your setup code. If you want to learn more about how this memory management feature works in standard web browsers, check out the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations). --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#speed-and-direction-with-playbackrate] ## Web Animations API (WAAPI): Speed and Direction with playbackRate The `playbackRate` property gets or sets the speed at which the animation timeline advances. Common values: - `1` - normal speed (default). - `2` - double speed. - `0.5` - half speed. - `-1` - full speed in reverse. Negative values play the animation backward from the current timeline position. `playbackRate = -1` followed by `play()` is functionally the same as calling `reverse()`, but assigning `playbackRate` directly also lets you control the speed of the reverse playback (for example, `-2` for a fast rewind or `-0.5` for a slow one). ```js const fill = document.getElementById("charge-bar-fill"); const chargeAnim = fill.getAnimations()[0]; function normalCharge() { chargeAnim.playbackRate = 1; chargeAnim.play(); } function slowMotionCharge() { chargeAnim.playbackRate = 0.25; chargeAnim.play(); } function rapidCharge() { chargeAnim.playbackRate = 4; chargeAnim.play(); } ``` This is a clean way to implement bullet-time effects, “fast-forward” through a long animation when the player is impatient, or expose a debug speed toggle without authoring multiple keyframe variants. **updatePlaybackRate() Is Not Available:** The standard browser variant `updatePlaybackRate()` - which transitions to a new rate smoothly while preserving apparent visual position - is not exposed in Gameface. Direct assignment to `playbackRate` is the only path, and it can produce a small visual jump if currentTime is mid-flight. For UI animations the jump is usually imperceptible. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#detecting-completion] ## Web Animations API (WAAPI): Detecting Completion The standard way to react when an animation finishes is `animation.finished.then(...)` (a Promise) or `animation.addEventListener('finish', ...)`. Neither is available in Gameface. The supported alternative is the CSS animation event , dispatched on the element itself rather than on the Animation object: ```js const card = document.getElementById("reward-card"); const cardAnim = card.getAnimations()[0]; card.addEventListener("animationend", (event) => { if (event.animationName === "reward-intro") { unlockNextStep(); } }); cardAnim.play(); ``` The `event.animationName` matches the CSS `@keyframes` name, which is essential when an element has multiple animations and you need to react to a specific one. Two related events are also supported: - `animationstart` - fires when the animation begins playing (after any `animation-delay`). - `animationiteration` - fires once per loop for animations with `animation-iteration-count > 1`. **Why animationName Matters:** A single element can have several CSS animations layered on top of each other, all firing `animationend` independently. Filtering on `event.animationName` is the only way to identify which one just ended. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/animations/waapi/#practical-patterns] ## Web Animations API (WAAPI): Practical Patterns A few combinations of the methods above cover most real game UI scenarios: #### Replay-On-Demand Reveal A reveal animation that the game can replay any number of times, for example a “new item received” badge that re-appears every time a pickup event fires. ```js const badge = document.getElementById("pickup-badge"); const revealAnim = badge.getAnimations()[0]; function showPickup() { revealAnim.currentTime = 0; revealAnim.play(); } ``` #### Reversible Toggle A panel that opens and closes from a single keyframe definition, regardless of how quickly the player toggles the button. ```js const panel = document.getElementById("inventory-panel"); const toggleAnim = panel.getAnimations()[0]; let isOpen = false; function togglePanel() { if (isOpen) { toggleAnim.reverse(); } else { toggleAnim.playbackRate = 1; toggleAnim.play(); } isOpen = !isOpen; } ``` #### Bullet-Time Overlay An ambient animation that runs at normal speed during gameplay and slows down when an ability triggers a bullet-time effect. ```js const overlay = document.getElementById("ambient-glow"); const glowAnim = overlay.getAnimations()[0]; function enterBulletTime() { glowAnim.playbackRate = 0.2; } function exitBulletTime() { glowAnim.playbackRate = 1; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions Updating UI styles dynamically at 60 frames per second requires strict performance management. In a game engine environment, standard web development habits can accidentally trigger massive layout recalculations or flood the system with memory garbage. This guide explores the performance cost of inline string styles and details the high-performance alternatives. We will cover toggling pre-compiled classes for discrete states, using the CSS Typed Object Model for continuous values, and leveraging proprietary Gameface DOM Extensions for ultimate frame-rate performance. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#the-cost-of-inline-string-styles] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: The Cost of Inline String Styles When building a standard web application, developers frequently update dynamic styles by manipulating the DOM `style` object and concatenating strings. ```javascript // The standard vanilla JS way (Avoid doing this every frame!) let newPos = 150; myNode.style.left = newPos + "px"; ``` In a standard desktop browser, this overhead often goes unnoticed. However, in a game UI running at 60 frames per second, doing this for multiple elements (like tracking moving player icons on a minimap) is a severe performance killer. Here is the hidden pipeline that executes every single frame when you concatenate a string style: 1. JavaScript takes your raw number (`newPos`), converts it to a string, and appends `"px"`. 2. This creates a brand new string in memory. Doing this every frame generates a massive amount of “JavaScript garbage” that the engine must eventually pause your game to clean up. 3. This newly created string is handed over to the underlying layout engine. 4. The layout engine is forced to parse that string *back* into a raw number in order to mathematically update the element’s position on the screen. **The Performance Pitfall:** This unnecessary round-trip wastes critical CPU cycles. To keep your UI rendering lightning-fast, you must eliminate string concatenation . --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#allocations-in-per-frame-code] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Allocations in Per-Frame Code Strings are not the only allocation in a per-frame path. An arrow function written inline allocates a new function object every time the surrounding code runs. The handler below creates its callback on each call, and nothing reuses it: ```javascript // ❌ A new closure is allocated on every call const onWeaponFired = () => { setTimeout(() => setRecoilActive(false), 500); }; ``` Hoisting the callback out of the handler allocates it once: ```javascript // ✅ Allocated once, reused on every call const clearRecoil = () => setRecoilActive(false); const onWeaponFired = () => { setTimeout(clearRecoil, 500); }; ``` Object and array literals behave the same way. A vector constructed inside a per-frame update, an options object passed to the same call each frame, and an array assembled to be iterated once all allocate at frame rate. **Scope: Per-Frame Code Only:** This applies to code whose execution frequency justifies it: `requestAnimationFrame` callbacks, continuously firing Gameface event handlers, `data-bind` handlers, and anything reached from a per-frame update. Closures in code that runs on a menu opening or a button click carry no measurable cost. Hoisting every callback in a codebase reduces readability without a performance return. The relevant question is how many times per second the line executes. Garbage collection cost does not appear in average frame times. It arrives as an occasional stall, so a profile reporting healthy median frame times can still contain collector pauses. Inspect worst-frame numbers to find it. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#state-changes-the-classes-first-method] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: State Changes: The Classes-First Method For discrete UI state changes (such as opening a menu, hiding a tooltip, or marking an inventory slot as active), you should completely avoid inline JavaScript styles. Instead, prioritize toggling simple, pre-defined CSS classes . **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; import { createSignal } from 'solid-js'; const WeaponSlot = () => { const [active, setActive] = createSignal(false); return setActive(a => !a)} />; }; ``` **HTML:** ```html
``` ```javascript const weaponSlot = document.getElementById('weapon-slot'); function equipWeapon() { // Instantly applies the new pre-compiled styles without string parsing weaponSlot.classList.add('is-active'); } ``` ```css .slot { border: 2px solid gray; opacity: 0.5; } /* The pre-compiled state class */ .is-active { border: 2px solid gold; opacity: 1.0; } ``` **The Performance Win:** This method is highly performant because the engine has already compiled the `is-active` CSS rules at startup. Toggling a class keeps your JavaScript incredibly clean and entirely avoids runtime string generation. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (1/6) While classes are perfect for static states, they cannot help you if you need to update a continuous, highly dynamic value (such as enemy position on a minimap). To solve the string parsing problem for continuous data, Gameface supports the CSS Typed Object Model (CSSTOM) . The CSS Typed Object Model is part of the Houdini APIs. It allows the manipulation of CSS styles through objects, reducing the number **of** strings and strings concatenations required. This can lead to improved performance, lower memory cost and less time spent on GC (Garbage Collection). #### Understanding the Core API Before diving into the code, it is important to understand the three main components of the CSSTOM API: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (2/6) - **`attributeStyleMap`:** This is a property available on DOM elements that represents the inline styles of the element as an accessible map. It replaces the traditional `element.style` object, allowing you to manipulate styles using `get`, `set`, or `delete`. - **`CSSStyleValue.parse(property, value)`:** This factory method takes a standard CSS property and its string value, parsing it into a structured CSSTOM object. For simple properties like width, it creates a `CSSUnitValue`, which internally separates the numeric value from its string unit (like “px”). - **Component Objects:** When parsing complex properties like transforms, the API returns a structured list (a `CSSTransformValue` ). This list contains individual component members, such as `CSSTranslate` , `CSSScale` , or `CSSRotate` - which themselves contain `CSSUnitValue` properties for their specific values (e.g., `x`, `y`, `angle`). **Performance Best Practices:** The key to using CSSTOM successfully is separating your initialization logic from your update loop. Instead of feeding the engine a new string every frame, you create a dedicated CSS object once and continually update its numeric value inside your game loop. ```html
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (3/6) ```javascript const hpFill = document.getElementById('health-fill'); // --- INITIALIZATION (Run Once) --- // 1. Cache the attributeStyleMap to avoid fetching it every frame. const hpStyleMap = hpFill.attributeStyleMap; // 2. Parse and create the CSSTOM object ONCE. // This creates a CSSUnitValue that internally separates the number from the "px" unit. let widthObj = CSSStyleValue.parse("width", "100px"); // --- GAME LOOP (Run Every Frame) --- function updateHUD() { // Assume getPlayerHealth() fetches the current HP number from the engine let currentHP = getPlayerHealth(); // 3. Update the raw numeric value directly. There is no string concatenation! widthObj.value = currentHP; // 4. Apply the reused object to the cached style map. hpStyleMap.set("width", widthObj); requestAnimationFrame(updateHUD); } requestAnimationFrame(updateHUD); ``` #### Where CSSTOM Really Shines: Complex Transforms While using CSSTOM for a single width property is great, the place where this API really shines is when you need to update a transformation of multiple elements on the screen very often. Imagine you are tracking 10 enemy blips on a radar. Each blip needs to update its X position, Y position, scale, and rotation every single frame. Using modern vanilla JavaScript, you would likely write a template literal like this: ``element.style.transform = `translate(${x}px, ${y}px) scale(${sX}, ${sY}) rotate(${angle}deg)`;`` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (4/6) Even though template literals look clean to a frontend developer, JavaScript still evaluates them into brand new strings under the hood. Doing that for 10 elements at 60 FPS generates hundreds of new string allocations per second. ##### Anatomy of a Parsed Transform With CSSTOM, you parse the initial transform string once. When you parse a complex string like `"translate(...) scale(...) rotate(...)"`, the API returns a `CSSTransformValue` object. This object acts like an array containing each operation in the exact order you wrote them: - **Index 0 (`transformObj[0]`):** Becomes a `CSSTranslate` object with `x`, `y`, and `z` properties. - **Index 1 (`transformObj[1]`):** Becomes a `CSSScale` object with `x`, `y`, and `z` properties. - **Index 2 (`transformObj[2]`):** Becomes a `CSSRotate` object, which has an `angle` property. Each of these properties (like `x` or `angle`) is itself a `CSSUnitValue` object that holds a numeric `value` and a string unit. This is why you must access `transformObj[0].x.value` to update the actual number. Here is how you use this structure to update the radar without a single string allocation: ```html
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (5/6) ```javascript // --- INITIALIZATION (Run Once) --- // 1. Create our CSSTransform object ONCE. // Parsing here is fine since we do it only once during initialization. let transformObj = CSSStyleValue.parse("transform", "translate(0px, 0px) scale(1, 1) rotate(0deg)"); let elements = document.querySelectorAll(".enemy-blip"); let attributeStyleMaps = []; // 2. Save the attributeStyleMaps that will get reused often for significantly improved performance. for(let i = 0; i < elements.length; i++) { attributeStyleMaps.push(elements[i].attributeStyleMap); } // --- GAME LOOP (Run Every Frame) --- // Assume updateValues is a 2D array of raw numbers: [[x, y, scaleX, scaleY, angle], ...] function updateRadar(updateValues) { for(let i = 0; i < attributeStyleMaps.length; i++) { // 3. Update the CSSTransformComponent members directly using raw floats. // If done with regular CSSOM, this would require 10 string concatenations. // Update the CSSTranslate component transformObj[0].x.value = updateValues[i][0]; transformObj[0].y.value = updateValues[i][1]; // Update the CSSScale component transformObj[1].x.value = updateValues[i][2]; transformObj[1].y.value = updateValues[i][3]; // Update the CSSRotate component transformObj[2].angle.value = updateValues[i][4]; // 4. Apply the updated object to the specific element's cached map. attributeStyleMaps[i].set("transform", transformObj); } requestAnimationFrame(() => updateRadar(getNewEngineData())); } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#continuous-updates-css-typed-object-model] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Continuous Updates: CSS Typed Object Model (6/6) **Common CSSTOM Pitfalls:** To actually see the performance gains from CSSTOM and avoid flooding the garbage collector, you must strictly avoid these three common mistakes inside your game loop: 1. **Not saving the `attributeStyleMap`:** Always cache the map in an array or variable during setup instead of looking up `element.attributeStyleMap` every frame. 2. **Recreating objects:** Avoid creating new CSSTOM objects on every update, instead of reusing CSSTOM objects and only setting their values. 3. **Sharing objects across properties:** Never use one CSSTOM object for DIFFERENT CSS properties. For example, do not use your `width` object to update `left-padding`. They could have different internal representations which would slightly reduce performance. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#direct-dom-communication-gameface-dom-extensions] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Direct DOM Communication: Gameface DOM Extensions (1/3) While CSSTOM is incredibly powerful for complex properties like `transform`, setting up parsed objects and caching style maps can feel like overkill if you just need to update a simple `left` position or a `width` property. For these simpler dimensional updates, it is often better to skip the CSSTOM structure entirely. Gameface provides a proprietary shortcut that bypasses standard DOM limitations: the `StylePositioningAttributes` extensions directly on the DOM node. These extensions expose unit-specific properties like `leftPX`, `topVW`, `heightVMAX`, and `widthREM`. This allows you to directly inject raw numbers into the layout engine without any string parsing or object creation overhead. ```html
``` ```javascript const playerBlip = document.getElementById('player-blip'); // --- GAME LOOP (Run Every Frame) --- function updateMinimapPosition() { // Assume getPlayerCoordinates() fetches the current X/Y from the game engine let coords = getPlayerCoordinates(); // We assign raw floats directly to the engine's custom extensions. // There are no strings, no parsing, and no JS objects required. // This is perfectly safe and highly performant to execute every single frame. playerBlip.leftPX = coords.x; playerBlip.topPX = coords.y; // Schedule the next frame update requestAnimationFrame(updateMinimapPosition); } // Start the continuous update loop requestAnimationFrame(updateMinimapPosition); ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#direct-dom-communication-gameface-dom-extensions] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Direct DOM Communication: Gameface DOM Extensions (2/3) **When to use Extensions:** This is the absolute fastest and most efficient way to update an element’s dimensions or position. Use these extensions whenever you need to tightly couple a UI element to high-frequency game data (such as a custom cursor, a tracked 3D world marker, or an interactive drag-and-drop element). #### Supported Gameface DOM Extensions Reference To help you maximize performance without guessing which properties have custom DOM extensions, here is the complete reference list of supported Gameface dimension and positioning attributes. Instead of concatenating strings like `element.style.width = value + "px"`, you can append the unit directly to the property name and pass a raw numeric value. The supported suffix units are **PX**, **VW**, **VH**, **REM**, and **PERCENT**. ##### Positioning Extensions - `topPX`, `topVW`, `topVH`, `topREM`, `topPERCENT` - `bottomPX`, `bottomVW`, `bottomVH`, `bottomREM`, `bottomPERCENT` - `leftPX`, `leftVW`, `leftVH`, `leftREM`, `leftPERCENT` - `rightPX`, `rightVW`, `rightVH`, `rightREM`, `rightPERCENT` ##### Sizing Extensions - `widthPX`, `widthVW`, `widthVH`, `widthREM`, `widthPERCENT` - `heightPX`, `heightVW`, `heightVH`, `heightREM`, `heightPERCENT` - `minWidthPX`, `minWidthVW`, `minWidthVH`, `minWidthREM`, `minWidthPERCENT` - `minHeightPX`, `minHeightVW`, `minHeightVH`, `minHeightREM`, `minHeightPERCENT` - `maxWidthPX`, `maxWidthVW`, `maxWidthVH`, `maxWidthREM`, `maxWidthPERCENT` - `maxHeightPX`, `maxHeightVW`, `maxHeightVH`, `maxHeightREM`, `maxHeightPERCENT` ##### Text Decoration Extensions --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/dynamic-styling-in-javascript/#direct-dom-communication-gameface-dom-extensions] ## Dynamic Styling in JavaScript: Classes, Typed OM, and Extensions: Direct DOM Communication: Gameface DOM Extensions (3/3) Gameface also supports dynamic scaling of text decorations using the following extensions: - `textUnderlineOffsetPX`, `textUnderlineOffsetVW`, `textUnderlineOffsetVH`, `textUnderlineOffsetREM`, `textUnderlineOffsetPERCENT` - `textDecorationThicknessPX`, `textDecorationThicknessVW`, `textDecorationThicknessVH`, `textDecorationThicknessREM`, `textDecorationThicknessPERCENT` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/] ## Managing Variables: CSS Custom Properties vs. SCSS Maintaining a consistent design system across a massive game UI requires variables for colors, typography, and spacing. However, standard web development practices for managing these variables can introduce hidden frame-rate penalties and run into specific engine constraints. This guide explores the mechanical differences between runtime and build-time variables. We will examine the hidden costs of global CSS Custom Properties , explore advanced SCSS techniques for zero-cost design tokens, and establish the correct architectural pattern for safely scoping dynamic variables. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-reality-of-native-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: The Reality of Native CSS Variables (1/4) In modern web development, it is common practice to define global design tokens using CSS Custom Properties (variables) attached to the `:root` pseudo-class. This allows you to update a single variable via JavaScript and instantly change the theme of the entire application. Here is what a standard web-first implementation looks like: **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const HudPanel = () => ( Health ); ``` **HTML:** ```html

Health

``` ```css /* The standard web approach: defining global variables */ :root { --primary-color: #ff0000; } .title { color: var(--primary-color); } ``` Then, updating the variable with JavaScript is as simple as: **SolidJS:** ```tsx import { createSignal, createEffect } from 'solid-js'; const [themeColor, setThemeColor] = createSignal('#ff0000'); createEffect(() => { document.documentElement.style.setProperty('--primary-color', themeColor()); }); ``` **Vanilla JS:** ```javascript const root = document.documentElement; function updateThemeColor(newColor) { root.style.setProperty('--primary-color', newColor); } ``` Or by toggling CSS classes that switch between different variable values: ```css .light-theme { --primary-color: #e62e3a; } ``` While this looks clean, it is highly dangerous in a game environment **when updated frequently**. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-reality-of-native-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: The Reality of Native CSS Variables (2/4) Native CSS variables are resolved at **runtime**. Because the variable is attached to the `:root` element, the CSS engine assumes that every single element on the page might rely on it. Whenever you update a `:root` variable, you force the engine to traverse the entire Document Object Model (DOM) and recalculate the styles for every single element, regardless of whether they actually use the variable or not. **The Global Recalculation Penalty:** Updating a `:root` variable can trigger a massive global style recalculation . To be highly precise, the variable isn’t inherently slow just because of where it is defined. The true performance bottleneck is determined by **how many elements actually reference that variable**. If a root variable is only used by three specific buttons, updating it is relatively fast. However, if a global variable is applied to thousands of UI nodes, changing it forces the engine to recalculate the layout and paint for every single one of those nodes simultaneously. **Crucially, it does not matter how you trigger the update.** Whether you use JavaScript (`setProperty`) or toggle a CSS class on the root element, changing a variable that thousands of nodes rely on will cause severe layout thrashing and destroy your frame rate. For high-frequency updates, always scope your variables as tightly as possible. **Unsupported Features:** Beyond the performance penalty, there are three critical Gameface constraints you must remember when using native CSS variables. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-reality-of-native-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: The Reality of Native CSS Variables (3/4) Gameface **does not support** CSS variables inside of `@keyframes` definitions, it **does not support** variable fallback values, and it **does not support** CSS variables inside shorthand properties — including sub-shorthands. If you attempt to write animation logic using variables like you would in a standard browser environment, the engine will fail to parse the rules. ```css /* ❌ AVOID: This will NOT work in Gameface */ /* 1. Fallback values are not supported */ .health-bar { background-color: var(--hp-color, #ff0000); } /* 2. Variables inside keyframes are not supported */ @keyframes damage-pulse { 0% { background-color: var(--pulse-color); } 100% { background-color: transparent; } } /* 3. Variables inside shorthand properties are not supported */ /* This applies to true shorthands like border, background, font … */ .card-border { border: 2px solid var(--accent-color); /* ❌ shorthand — fails */ } /* … and also to sub-shorthands like border-color, border-width, */ /* background-position, etc. */ .card-border { border-color: var(--accent-color); /* ❌ sub-shorthand — also fails */ } ``` For shorthand properties, always expand to per-side or per-property longhands: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-reality-of-native-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: The Reality of Native CSS Variables (4/4) ```css /* ✅ Use individual longhand properties instead */ .card-border { border-width: 2px; border-style: solid; border-color: transparent; /* hardcoded default */ } /* ✅ Override with a scoped variable on the longhand that accepts it */ .card-border--accented { border-left-color: var(--accent-color); border-right-color: var(--accent-color); border-top-color: var(--accent-color); border-bottom-color: var(--accent-color); } ``` To create robust animations and reliable default styles, you must rely on hardcoded values or build-time preprocessors. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-zero-cost-alternative-scss-preprocessing] ## Managing Variables: CSS Custom Properties vs. SCSS: The Zero-Cost Alternative: SCSS Preprocessing (1/3) For static design tokens that do not change during gameplay (such as your game’s core theme, base typography sizes, or margins & padding), you should **completely avoid** native CSS variables. Instead, you should use a CSS preprocessor like **SASS/SCSS**. Because SCSS variables are resolved at **build-time** , the compiler generates standard CSS with hardcoded values. The layout engine does zero variable resolution math at runtime, costing you zero performance. At its most basic level, you can define and use an SCSS variable directly within the same stylesheet. ```scss /* Define the SCSS variables locally */ $brand-primary: #ff0000; $spacing-large: 2rem; .hud-panel { padding: $spacing-large; } .title { color: $brand-primary; } ``` When your UI is built for production, the SCSS compiler strips away the variables entirely. The engine only ever receives and parses the final, hardcoded CSS: ```css /* The final output the layout engine actually reads */ .hud-panel { padding: 2rem; } .title { color: #ff0000; } ``` #### Scaling to Global Variables While defining a local variable is useful, a massive game UI requires a centralized design system. You need variables that act globally, similar to how the `:root` selector is used for CSS variables. To achieve this global reach in SCSS, there are two primary architectural approaches. ##### Method 1: Manual Imports The most standard approach is to extract all your design tokens into a dedicated file and manually import them into every component stylesheet that needs them. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-zero-cost-alternative-scss-preprocessing] ## Managing Variables: CSS Custom Properties vs. SCSS: The Zero-Cost Alternative: SCSS Preprocessing (2/3) ```scss /* Define your central SCSS variables in one master file */ $brand-primary: #ff0000; $spacing-large: 2rem; ``` ```scss /* Import the variables specifically for this component */ @use "variables" as *; .hud-panel { padding: $spacing-large; } .title { color: $brand-primary; } ``` ##### Method 2: Global Variable Injection (Bundlers) A common complaint about manual imports is having to write the `@use` statement at the top of every single component file across a massive project. If you are using a modern frontend bundler like Vite, you can configure it to automatically inject your global variables into every SCSS file. Here is how you set up Vite to handle your design tokens globally: ```javascript import { defineConfig } from 'vite'; export default defineConfig({ css: { preprocessorOptions: { scss: { // Automatically injects your variables file into every SCSS component additionalData: `@use "@/styles/global-variables.scss" as *;` } } } }); ``` **The Memory Tradeoff:** While global injection is incredibly convenient for your developers, you must use it carefully. The bundler physically appends the contents of `global-variables.scss` to the top of every single SCSS file during the build process. If you put heavy mixins or large chunks of standard CSS in that global file, it will be duplicated hundreds of times in memory. This will significantly bloat your compilation time and memory usage. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#the-zero-cost-alternative-scss-preprocessing] ## Managing Variables: CSS Custom Properties vs. SCSS: The Zero-Cost Alternative: SCSS Preprocessing (3/3) **Our recommendation:** Use global injection only for lightweight design tokens that are truly universal across the entire UI, such as your core color palette and base typography sizes. Avoid putting large mixins, complex functions, or component-specific styles in the global file. **Tokens are the best input you can give a coding agent:** A global SCSS token file also happens to be the most useful thing you can hand an AI assistant. Given named colors, a spacing scale, and a type scale, an agent applies them consistently across every component it touches. Given none, it invents a new visual language every few screens. See Design First. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#safe-usage-tightly-scoped-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: Safe Usage: Tightly Scoped CSS Variables (1/2) SCSS is perfect for static values, but game UIs still require dynamic theming. For example, imagine a multiplayer scoreboard where each player’s card needs to be dynamically accented with their specific “Team Color” assigned by the server. For these dynamic features, you cannot use SCSS because the values are decided at runtime. While you *could* use standard inline JavaScript styles (`element.style.color`), that becomes incredibly inefficient if the color needs to affect the card’s background, its borders, and its pseudo-elements all at once (since JavaScript cannot target `::before` or `::after` directly). Native CSS variables *are* the perfect tool here, but they must be architected safely. To avoid the global recalculation penalty discussed earlier, you must **tightly scope** your CSS variables to the specific UI component that needs them. By applying the variable directly to the component’s container, you tell the layout engine to only recalculate the styles for that specific container and its internal children, rather than the entire document. Here is how you safely scope a dynamic CSS variable for a Player Card: ```html
Player One
...
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/dynamic-styling--variables/managing-variables/#safe-usage-tightly-scoped-css-variables] ## Managing Variables: CSS Custom Properties vs. SCSS: Safe Usage: Tightly Scoped CSS Variables (2/2) ```css /* 1. We set a safe default directly on the component, not the root */ .player-card { --player-accent: #cccccc; position: relative; } /* 2. Multiple children inherit the same dynamic variable */ .card-bg { background-color: var(--player-accent); opacity: 0.2; } .card-border { border-width: 2px; border-style: solid; border-color: var(--player-accent); } /* 3. The variable works on pseudo-elements, which JS cannot easily reach! */ .player-card::after { content: ""; position: absolute; box-shadow: 0 0 15px var(--player-accent); } ``` ```javascript const playerCard = document.getElementById('player-1-card'); // When the engine assigns the team color, we update the specific node function updatePlayerColor(hexColor) { // This instantly updates the bg, border, and pseudo-element glow! playerCard.style.setProperty('--player-accent', hexColor); } ``` **The Tradeoffs:** This hybrid approach requires careful architectural planning. You lose the convenience of a global catch-all variable file. However, the performance savings are immense. When `updatePlayerColor` fires, the engine only recalculates the styles for `#player-1-card` and its internal children, leaving the rest of your heavy HUD completely untouched. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/] ## Gameface CSS: Simple Layout & Opacity Beyond standard CSS performance practices, Gameface provides two proprietary properties that skip expensive rendering operations entirely. display: simple bypasses the Yoga layout solver for containers where all children are absolutely positioned, eliminating the layout calculation cost on every frame. coh-simple-opacity eliminates the intermediate GPU texture that standard CSS `opacity` forces the engine to allocate before compositing. Both are narrow-purpose tools with clear performance wins and specific trade-offs that make them the wrong choice in the wrong context. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/#simple-layout-display-simple] ## Gameface CSS: Simple Layout & Opacity: Simple Layout (display: simple) (1/3) The previous article covered how to minimize the cost of a Full Layout Solve. For certain UI views, a different approach is possible: eliminate the layout solve entirely. Every flex container runs through Yoga, which distributes space, resolves wrapping, calculates flex basis, and handles cross-axis alignment. For many screens, this computation is necessary. But a subset of game UIs - HUDs, floating nameplates, minimap overlays, tooltip hosts - have one thing in common: every element sits at a declared, absolute position. Nothing in those views flows. Nothing wraps. Yoga’s calculations produce the same result as not running them at all. `display: simple` is a Gameface-proprietary `display` value for exactly this situation. A container set to `display: simple` has Yoga’s layout solve disabled entirely. The engine skips main-axis distribution, cross-axis alignment, and flex-line calculations. Direct children are expected to declare their own position using `position: absolute`, and the engine places them at those coordinates without involving the layout tree. The following shows a dedicated HUD view where every element is anchored to a corner or edge of the screen: ```html
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/#simple-layout-display-simple] ## Gameface CSS: Simple Layout & Opacity: Simple Layout (display: simple) (2/3) ```css /* display: simple bypasses Yoga for the body entirely */ body { display: simple; width: 100vw; height: 100vh; } /* Each direct child must declare its own absolute position */ .health-bar { position: absolute; bottom: 2rem; left: 2rem; width: 20rem; height: 1.5rem; } .minimap { position: absolute; top: 2rem; right: 2rem; width: 18rem; height: 18rem; } ``` The constraint applies only to direct children of the `display: simple` container. Elements at any depth below it can use `display: flex` freely. A health bar that is absolutely positioned on screen can still lay out its internal fill bar and label using flexbox: ```css /* flex is valid inside a display: simple subtree */ .health-bar { position: absolute; bottom: 2rem; left: 2rem; display: flex; /* Internal flex layout of the bar is fine */ align-items: center; gap: 0.5rem; width: 20rem; height: 1.5rem; } .health-bar__fill { flex-basis: 60%; /* flex rules apply normally inside this subtree */ height: 100%; background-color: #e84040; } ``` **Direct Children Must Be Absolutely Positioned:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/#simple-layout-display-simple] ## Gameface CSS: Simple Layout & Opacity: Simple Layout (display: simple) (3/3) `display: simple` removes Yoga’s flow calculation for that container. A direct child without `position: absolute` or `position: fixed` will not be positioned by any layout algorithm and will stack at the origin (0, 0) by default. Reserve `display: simple` for containers where you are certain every direct child carries an explicit absolute position. The safest application is `` in a dedicated HUD view, not a mixed-layout screen where some children participate in document flow. #### When to Use display: simple `display: simple` fits well on views that are entirely overlay-based: HUD screens, floating nameplate containers, tooltip layers, and notification overlays. These views share the property that positions are declared in CSS, elements do not respond to each other’s dimensions, and the visual structure is driven by absolute coordinates rather than flex distribution. It is the wrong choice for any screen where content flows: inventory grids, settings panels, menu screens, character creation screens, or any view where elements stack, wrap, or react to their siblings’ sizes. On those screens, using `display: simple` breaks the layout. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/#simple-opacity-coh-simple-opacity] ## Gameface CSS: Simple Layout & Opacity: Simple Opacity (coh-simple-opacity) (1/2) Standard CSS `opacity` creates a compositing layer . The engine renders the element and all of its children to a temporary off-screen GPU texture at full opacity, then composites that texture onto the scene at the declared opacity value. This guarantees that children blend correctly relative to each other before the group’s combined opacity is applied to the background. That temporary texture carries a real cost. The engine allocates GPU memory for the intermediate surface, renders to it, and then performs an additional compositing pass. A pause menu, a damage flash overlay, and a notification panel each fading in and out on every relevant event each trigger this allocation on every frame they are visible. `coh-simple-opacity` is a Gameface-proprietary property that changes this rendering path. A container with `coh-simple-opacity: on` skips the intermediate texture. The engine applies the opacity value directly to each child’s color during the primary render pass, blending them individually into the scene without a separate compositing layer. The property and the standard `opacity` value work together - `coh-simple-opacity: on` changes how the opacity is applied at the GPU level, while the `opacity` property still controls the actual value and drives any transitions: ```html
New Objective Added
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/gameface-css/#simple-opacity-coh-simple-opacity] ## Gameface CSS: Simple Layout & Opacity: Simple Opacity (coh-simple-opacity) (2/2) ```css .notification-panel { coh-simple-opacity: on; /* Skip the intermediate GPU texture */ opacity: 0; /* Still use opacity to control the visible value */ transition: opacity 0.3s ease-in-out; position: absolute; top: 4rem; right: 2rem; } .notification-panel.is-visible { opacity: 1; } ``` #### The Visual Trade-off The GPU memory saving is the win. The cost is a change in how overlapping children composite. With standard `opacity`, children render into a group first. Their overlapping regions look correct because the children share the same compositing surface before the group opacity is applied to the scene. With `coh-simple-opacity`, each child blends directly into the scene independently. If two children overlap and the parent has `opacity: 0.5`, the overlapping region appears brighter than the surrounding area because both children contribute their color to the same background pixel without being grouped first. **Choosing Between opacity and coh-simple-opacity:** `coh-simple-opacity: on` is the right choice when: - Children within the group do not visually overlap each other. - The entire group needs to fade in or out as a unit (a HUD panel, a screen overlay, a score counter). - GPU memory is a constraint, particularly on console targets where VRAM is tightly budgeted. Stick with standard `opacity` when children overlap visually and the grouped compositing matters - tooltips with icon layers, character portraits with overlaid rarity badges, or any element using stacked decorative pieces. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking Game UI panels often need to resize, cut into angled silhouettes, or blend into the scene without exporting a separate transparent image for every possible size. This article covers three practical CSS techniques for that work: 9-slice scaling with border-image , hard geometric cuts with clip-path , and soft blending with mask-image . --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#why-shape-techniques-matter-in-game-ui] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Why Shape Techniques Matter in Game UI Many game UI screens are built from panels that cannot stay at one fixed size. A tooltip grows with item stats, a dialogue box expands for localized text, a quest card changes height depending on objectives, and HUD elements may need different proportions on ultrawide or compact layouts. The direct asset approach is to export a separate PNG for every panel size and every shape variation. That is simple at first, but it creates three problems: - The asset list grows quickly as the UI gains more states and sizes. - Designers must re-export artwork for small layout changes. - The UI can spend memory on large transparent areas that exist only to preserve a shape. The better approach is to separate the visual rule from the final size of the element. 9-slice scaling keeps decorative corners intact while edges stretch. `clip-path` cuts a rectangular element into a hard geometric shape. `mask-image` uses a stencil image or gradient to reveal, hide, or fade parts of an element with soft edges. They give you more control over how a small number of authored assets adapt to real UI layouts. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (1/8) 9-slice scaling is used when a frame has important corners but flexible edges. Think of an item tooltip with ornate corners, a fantasy dialogue frame, or a sci-fi panel border. The corners should not stretch, because stretching them distorts the artwork. The top, bottom, left, and right edges can stretch because they are usually decorative strips. *This example is taken from the Player’s Playground example* In CSS, you implement 9-slice scaling with border-image . You point at one frame image and tell the renderer where to cut it, which turns the bitmap into a 3×3 grid. Each cell of that grid is painted onto the matching part of the element border: - Four corners, which are preserved at their original aspect. - Four edges, which stretch, repeat, or round to fill the available space. - One center region, which can be left empty or filled depending on your needs. Here is a minimal tooltip structure that uses a 9-slice frame: **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const ItemTooltip = () => ( Legendary

Voidheart Scepter

Two-Handed Staff, Arcane
); ``` **HTML:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (2/8) ```html
Legendary

Voidheart Scepter

Two-Handed Staff, Arcane

``` The tooltip frame should scale with the content inside it. The CSS below shows the complete `border-image` setup. This is what the Player’s Playground example is demonstrating when you switch frame styles and adjust the slice value: ```css .item-tooltip { width: 420px; padding: 24px; background: #0d0d1a; border: 24px solid transparent; border-image-source: url("/assets/ui/fantasy-border.png"); border-image-slice: 500; border-image-width: 24px; border-image-repeat: stretch; } ``` #### Breaking Down the Properties The rest of this section breaks down each property, explains what it controls, and covers the practical questions that come up when tuning a 9-slice frame for game UI. ##### border-image-source This property points to the frame artwork. It accepts a `url()` to a raster image (PNG, WebP) or an SVG. In most game UI workflows this is a single authored frame asset exported by the art team. ```css border-image-source: url("/assets/ui/fantasy-border.png"); ``` ##### border-image-slice This is the property that makes the 9-slice work. It defines how far inward, from each edge of the source image, the renderer should cut before splitting the image into the nine regions. For raster images, the value is in source-image pixels (unitless). For SVG sources, you can use percentages. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (3/8) ```css /* Cut 500 source-image pixels from each side. */ border-image-slice: 500; /* Different insets per side: top, right, bottom, left. */ border-image-slice: 64 48 64 48; ``` The slice value is not a design guess. It should match the way the frame image was authored. If the decorative corner occupies the outer 64 pixels of the source image, the slice should be `64`. If the corner detail extends 96 pixels, use `96`. Getting this wrong either clips the corner art or includes edge pixels in the corner region, producing visible seams. ##### The fill keyword By default the center slice (the ninth region) is discarded and the element interior is controlled by `background`. Adding the `fill` keyword draws the center slice into the element interior: ```css border-image-slice: 64 fill; ``` This can be useful when the frame texture should continue seamlessly into the panel center. In most game UI workflows, however, the frame and the panel background are authored separately, so you typically omit `fill` and let the `background` property handle the interior. ##### border-image-width This property controls how thick the rendered border-image appears on the element. It determines the area into which the nine slices are drawn on screen. ```css border-image-width: 24px; ``` A common question is how `border-image-width` relates to the element’s own `border` width. They serve different roles: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (4/8) - The element’s border (e.g. `border: 24px solid transparent`) reserves layout space. It pushes padding and content inward, just like any CSS border. Without this, the content sits flush against the element edge and there is no room for the frame artwork to appear. - border-image-width tells the renderer how large the border-image drawing area should be. It can match the border width, but it does not have to. When the two values match (both `24px` in the example above), the image fills exactly the space the border reserved. If `border-image-width` is larger than the element border, the image overflows inward and may overlap padding or content. If it is smaller, the image renders thinner than the reserved border area and a gap becomes visible. For most 9-slice panels, keeping the two values equal is the safest starting point. ```css .tooltip--safe { /* Both match: the image fills the layout space exactly. */ border: 24px solid transparent; border-image-width: 24px; } .tooltip--overflow { /* border-image-width is larger: the frame renders thicker than the reserved space. */ border: 16px solid transparent; border-image-width: 32px; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (5/8) **Why It Works:** Think of the element border as the “hole” in the layout, and `border-image-width` as the “canvas” the nine slices are painted onto. When the canvas matches the hole, the frame fits cleanly. When they differ, the frame either bleeds inward or leaves empty space. If you are seeing your content overlapping the frame or a visible gap between the frame and the content, check whether these two values are in sync. ##### border-image-outset `border-image-outset` pushes the rendered border image outward, beyond the element’s border box, without affecting layout. The element itself does not grow and surrounding elements do not reflow. ```css border-image-outset: 8px; ``` This is useful when a frame has a glow, dropshadow, or decorative flourish that should extend past the panel edge. Without outset, that detail would be clipped at the border box. With an outset of `8px`, the rendered frame extends 8 pixels outward on all sides, letting the outer detail remain visible. **Outset Collisions:** Be careful with outset in tight layouts. Because it does not affect the element’s box model, the extended frame can overlap neighboring elements. If you use outset, leave enough margin or gap around the panel so the overflow does not collide with adjacent UI. ##### border-image-repeat This property controls how the four edge strips (top, right, bottom, left) are handled when they need to fill more space than the source slice provides. The three useful values are: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (6/8) - stretch scales the edge strip to fill the available length. This is the most common choice for game UI frames because it produces a smooth result with any panel size. - round tiles the edge strip, but rescales it so that a whole number of tiles fit without clipping. This works well when the edge art has a visible repeating pattern (chain links, rivets, runic symbols) and you want clean repetition without partial tiles. - repeat tiles the edge strip at its natural size. If the available space is not an exact multiple of the tile, the last tile is clipped. This can produce visible cut-off artifacts at the panel edges, so it is rarely the right default for game UI. ```css .tooltip--stretched { border-image-repeat: stretch; } .tooltip--rounded { /* Good for chain-link or rivet borders where the pattern should tile cleanly. */ border-image-repeat: round; } .tooltip--tiled { /* Tiles at natural size; may clip the last tile if the panel is not an exact multiple. */ border-image-repeat: repeat; } ``` For most 9-slice panels in game UI, `stretch` is the safe default. Switch to `round` when the art team has designed an edge strip with a visible repeating motif and clean tiling matters more than uniform scaling. ##### The Shorthand All five properties can be combined into a single `border-image` shorthand. The syntax packs source, slice, width, outset, and repeat into one declaration: ```css /* source / slice / width / outset / repeat */ border-image: url("/assets/ui/fantasy-border.png") 500 / 24px / 0 stretch; ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (7/8) The shorthand is convenient once you are comfortable with the individual properties, but during development it is often easier to keep the longhand forms so each value is easy to find and adjust independently. #### Caveats and Practical Guidelines 9-slice with `border-image` is a good fit for rectangular panels that need decorative frames and dynamic content. It lets one frame asset support many panel sizes without re-exporting. There are a few things to keep in mind when working with it: - **The shape is always a rectangle.** The element border, and therefore the 9-slice frame, is fundamentally rectangular. If the final silhouette needs angled corners, hexagons, or soft fades, combine the panel with `clip-path` or `mask-image` instead of forcing the frame artwork to handle the shape. - **Keep the panel background separate from the frame.** Let `background` handle the inner fill and let `border-image` handle the edge artwork. This makes the frame reusable across tooltips, cards, and modal windows without coupling interior styling to the border asset. - **Match `border-image-width` to the element border.** Unless you have a specific reason to mismatch, set both to the same value. Mismatches are one of the most common sources of unexpected gaps or content overlap when first setting up a 9-slice panel. - **Watch for outset collisions.** If you use `border-image-outset` for glow or shadow overflow, add enough margin around the element so the extended frame does not overlap neighboring UI. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#9-slice-scaling-with-border-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: 9-Slice Scaling with border-image (8/8) For a full production-style walkthrough, check our: [Nine slice modal tutorial ](https://coherent-labs.com/blog/uitutorials/nine-slice-modal/). **Border-image Generator:** If you want a visual helper while tuning values, MDN provides a [border-image generator](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Backgrounds_and_borders/Border-image_generator) that lets you upload your frame asset and experiment with different slice, width, and repeat values to preview the result in real time. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (1/6) `clip-path` cuts the visible area of an element. The element can still be a normal `div`, `button`, or component in your layout, but only the area inside the clipping shape is rendered. The element keeps its full rectangular box for layout purposes - click areas, padding, and flex behavior all stay the same - while the renderer discards every pixel outside the clipping region. This is useful for rigid, geometric UI shapes: - Hexagonal skill tree nodes. - Slanted health or energy bars. - Angled sci-fi panels. - Diamond-shaped markers. - Pie-slice segments in radial menus. The most common form is clip-path: polygon(…) . Each point in the polygon is written as an `x y` coordinate pair. Percentages are relative to the element’s own box, so the same shape can scale with the element. Besides `polygon()`, the property also accepts `circle()`, `ellipse()`, and `inset()` for simpler shapes. #### Simple UI Shapes This section covers some common simple UI shapes that can be created with `clip-path`. ##### Hexagonal Skill Nodes Here is a basic skill node. The HTML remains simple, which keeps the component easy to wire into interaction and state logic: **SolidJS:** ```tsx import Button from '@components/Basic/Button/Button'; const SkillNode = () => ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (2/6) The polygon below cuts the button into a hexagon. The left and right points sit halfway down the element, while the other points create the angled top and bottom edges: ```css .skill-node { width: 96px; height: 84px; display: flex; align-items: center; justify-content: center; background: linear-gradient(180deg, #2b3546 0%, #111722 100%); border: 0; /* Six points: top-left, top-right, right, bottom-right, bottom-left, left. */ clip-path: polygon(25% 0, 75% 0, 100% 50%, 75% 100%, 25% 100%, 0 50%); } .skill-node--unlocked { background: linear-gradient(180deg, #4a8fd6 0%, #1d3f68 100%); } ``` **Why It Works:** The element still has a rectangular layout box, but the renderer only shows the pixels inside the polygon. That means you can keep normal CSS layout, sizing, and state classes while changing only the visible shape. ##### Slanted Health Bars For HUD bars, `clip-path` is often enough to create a more authored look without adding a new image asset. The structure can be a track with a fill inside it: **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; const SlantedStatusBar = (props: { percent: number }) => ( ); ``` **HTML:** ```html
``` Both the track and the fill use the same polygon. This keeps the slanted right edge aligned as the fill changes width: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (3/6) ```css .status-bar { width: 420px; height: 28px; padding: 3px; background: rgba(255, 255, 255, 0.12); clip-path: polygon(0 0, 100% 0, 94% 100%, 0 100%); } .status-bar__fill { height: 100%; background: linear-gradient(90deg, #4fd6ff 0%, #1a6fff 100%); clip-path: polygon(0 0, 100% 0, 94% 100%, 0 100%); } ``` #### Composing Complex Shapes: Radial Menu Simple polygons and circles are enough for individual elements, but `clip-path` becomes especially powerful when you combine it with CSS transforms to compose larger, non-trivial shapes out of simpler pieces. A good example is the Gameface UI **Radial Menu** component. The menu is a full circle divided into even pie-slice segments. Each segment is a separate element that the player can hover or select independently. Building this with a single complex polygon would be fragile and difficult to maintain. Instead, the component uses a combination of clipped circles and rotations . The idea is straightforward: every segment starts as a full circle, clipped to a wedge shape using `clip-path`, and then rotated into its position around the center. The result is a seamless radial layout where each segment is still an independent, interactive element. Use the slider below to compare the radial menu with and without `clip-path` applied.\ Slide to see how the overlapping circles (unstyled) become seamlessly clipped and rotated wedge segments (styled): --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (4/6) The technique follows a repeatable pattern. Each segment is a circular element clipped to a pie slice via `polygon()`, then rotated by an increment based on the total number of segments. For a six-segment wheel, each slice spans 60 degrees: ```css .radial-segment { position: absolute; width: 100%; height: 100%; border-radius: 50%; clip-path: polygon(50% 50%, 50% 0%, 100% 0%); } .radial-segment:nth-child(2) { transform: rotate(60deg); } .radial-segment:nth-child(3) { transform: rotate(120deg); } .radial-segment:nth-child(4) { transform: rotate(180deg); } .radial-segment:nth-child(5) { transform: rotate(240deg); } .radial-segment:nth-child(6) { transform: rotate(300deg); } ``` **Why It Works:** Each segment is still a normal element with its own hover state, click handler, and class logic. The `clip-path` only controls what the player sees, not what the element can do. This keeps the component easy to extend - adding or removing segments means adjusting the polygon angle and the rotation increment, not rewriting the layout. #### Caveats and Practical Guidelines `clip-path` is a strong choice for clean geometric silhouettes. It is straightforward to scale because the polygon points can use percentages, and it works on any element type. There are a few things to keep in mind when working with it: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (5/6) - **The cut is always hard.** `clip-path` creates a binary visible/invisible boundary. It does not feather, blur, erode, or support partial transparency. If the art direction needs soft edges, smoke-like fades, or painterly alpha detail, use `mask-image` instead. - **Borders and box-shadows are clipped too.** The clip applies to the entire element rendering, including its borders and shadows. If the design requires a visible border that follows the clipped shape, you typically need a wrapper element or a layered approach where the border lives on a slightly larger element behind the clipped one. - **Hit areas remain rectangular.** The element’s pointer-hit area is still its full rectangular box unless you also apply a matching shape on the interaction side. In most game UI engines this is not an issue because interaction areas are handled separately, but it is worth verifying click and hover behavior on clipped elements during development. - **Animate with matching point counts.** CSS transitions and animations work between two `clip-path` values as long as both shapes use the same function type and the same number of points. This is useful for reveal effects, expanding shapes, or transitioning between states. **Clip-path Generator:** If you want a visual helper while designing polygon shapes, [Clippy ](https://bennettfeely.com/clippy/)lets you drag points on a live preview and copy the resulting `clip-path` value directly into your CSS. It supports polygons, circles, ellipses, and insets. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#hard-cuts-with-clip-path] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Hard Cuts with clip-path (6/6) **shape-rendering:** The `shape-rendering` CSS property controls the anti-aliasing behaviour applied to clipped geometry. Changing its value can visibly affect the crispness of `clip-path` edges, particularly for diagonal or curved polygon cuts. For full details on supported values and their rendering trade-offs in Gameface, refer to the [Gameface documentation ](https://docs.coherent-labs.com/cpp-gameface/integration/optional_features/aaclipping/). --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#soft-blending-with-mask-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Soft Blending with mask-image (1/5) `mask-image` works like a stencil. You provide a grayscale image (or a CSS gradient), and the renderer uses its alpha channel to dictate what stays visible. White areas in the mask show the element (100% opacity), black areas hide it (0% opacity), and gray areas partially fade it. Unlike `clip-path`, which only cuts a binary, hard edge, `mask-image` can produce soft fades, highly detailed silhouettes, and patterned reveals. This makes it the right tool for: - Minimap edges that fade smoothly into the HUD background. - Character portraits that dissolve into a panel frame. - Worn or battle-damaged overlays applied through grunge textures. The mask never shows up on screen itself - it only controls which parts of the element are visible and how much. The actual visuals come from the element’s own background, children, or content. This separation means the same element can look completely different just by swapping the mask. #### Shaping UI with Image Masks The most direct use of `mask-image` is pointing it at a PNG or SVG asset. This is perfect for when you need a silhouette that is too organic or detailed for a polygon, such as a faction emblem or a shaped portrait frame. Let’s build a faction emblem step-by-step to see how this works in practice. Our goal is to create a complex crest shape filled with a rich, metallic texture. ##### Step 1: Create the Material (Without the Mask) First, we define our structure: a wrapper element, and a child element that provides the visible pattern. **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#soft-blending-with-mask-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Soft Blending with mask-image (2/5) ```tsx import MaskImage from '@components/Media/MaskImage/MaskImage'; const FactionEmblem = () => (
); ``` **HTML:** ```html
``` We will give the inner `.faction-emblem__fill` a metallic look by stacking a texture image over a gold gradient. ```css .faction-emblem { width: 256px; height: 256px; } .faction-emblem__fill { width: 100%; height: 100%; /* Stack a scratchy texture over a gold gradient */ background-image: url("./iron-grip.png"), linear-gradient(135deg, #c9a84c 0%, #7a5e1e 70%); } ``` At this point, if you load the UI, you will just see a hard, rectangular 256x256 square filled with gold and iron textures. It has the right material, but the wrong shape. ##### Step 2: Apply the Stencil (With Mask) To carve this square into an emblem, we apply the `mask-image` to the wrapper element. We will point it to an alpha-transparent image of a crest. ```css .faction-emblem { width: 256px; height: 256px; /* 1. Define the stencil shape */ mask-image: url("./crest-mask.png"); /* 2. Control how the stencil is applied */ mask-repeat: no-repeat; mask-size: 100%; mask-position: center; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#soft-blending-with-mask-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Soft Blending with mask-image (3/5) **What just happened?** The engine takes the `crest-mask.png` and overlays it on the 256x256 box. Wherever the mask image is fully opaque, the gold texture inside `.faction-emblem__fill` shines through. Wherever the mask is fully transparent, the renderer clips the gold texture away entirely. **Repeating Patterns:** Because mask positioning properties (`mask-size`, `mask-repeat`, `mask-position`) mirror standard background properties, you can drastically change the result with just a few tweaks. If we wanted to turn this single emblem into a repeating textured wallpaper (e.g., for a loading screen background), we could simply shrink the mask and tell it to repeat: ```css .faction-emblem-pattern { /* Shrink the stencil to 64px */ mask-size: 64px 64px; /* Tile the stencil across the entire element */ mask-repeat: repeat; } ``` With the exact same HTML and texture fill, the element transforms from a single crest into a repeating grid of small crests! #### Feathering with a Gradient Mask You do not always need to load an external image asset. CSS gradients work perfectly as mask sources, which is incredibly useful for soft edges that do not depend on authored art. A minimap, for instance, can be feathered with a radial gradient that is fully visible at the center and fades out toward the edges: **SolidJS:** ```tsx import MaskImage from '@components/Media/MaskImage/MaskImage'; const MinimapFade = () => (
); ``` With CSS: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#soft-blending-with-mask-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Soft Blending with mask-image (4/5) ```css .minimap-container { /* Radial gradient mask stays in CSS as MaskImage renders a div */ mask-image: radial-gradient(circle, black 60%, transparent 100%); mask-size: 100%; } ``` **HTML:** ```html
``` ```css .minimap-container { width: 400px; height: 400px; /* Opaque center, then a controlled fade toward the edges. */ mask-image: radial-gradient(circle at center, black 0%, black 55%, transparent 80%); } .minimap { width: 100%; height: 100%; border-radius: 50%; background: url("./minimap.jpg") no-repeat center center; background-size: cover; } ``` **Breaking down the gradient math:** The engine generates this mask on the fly. From `0%` to `55%` from the center, the mask is solid black, meaning the minimap is fully opaque and visible. From `55%` to `80%`, the mask transitions from black to transparent. This creates a beautifully calculated 25% “blur” zone where the minimap slowly fades into the HUD. #### Caveats and Practical Guidelines `mask-image` is the right tool when the shape needs soft edges, detailed silhouettes, or gradual fades that `clip-path` cannot produce. Keep these rules in mind: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#soft-blending-with-mask-image] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Soft Blending with mask-image (5/5) - **The mask needs material to reveal:** If the masked element has no background, content, or children that produce visible pixels, the mask has nothing to show and the result is an empty space. Always verify your content renders *before* debugging a broken mask. - **Match the tool to the edge:** Use image masks for highly detailed silhouettes where the art team needs pixel-perfect control. Use CSS gradients for simple, geometric fades (like vignettes) to save on asset loading. - **Watch your compositing costs:** Each masked element requires the renderer to composite the mask against the element content. A few masked HUD elements are perfectly fine, but stacking dozens of full-screen masks can add measurable GPU rendering overhead. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/advanced-ui-shapes/#choosing-the-right-technique] ## Advanced UI Shapes: 9-Slice, Clipping, and Masking: Choosing the Right Technique Use the shape technique that matches the visual problem: - Use 9-slice scaling when the UI is still rectangular, but the frame artwork must resize without distorting its corners. Tooltips, dialogue boxes, modal frames, and item cards are common fits. - Use clip-path when the shape has a hard geometric silhouette. Hex nodes, slanted bars, diamond markers, and angled sci-fi panels are good examples. - Use mask-image when the shape needs soft edges, gradual fades, or detailed silhouettes. Feathered portraits, soft minimap edges, worn emblems, and patterned shapes are better handled as masks. These techniques can also be combined. A tooltip can use `border-image` for its ornate frame, a clipped header for an angled title plate, and a masked portrait inside the content area. The important part is to keep each technique responsible for one visual job. **Practical Rule:** Start with the simplest shape rule that satisfies the design. Use 9-slice for scalable frames, `clip-path` for hard cuts, and `mask-image` when the shape needs soft edges or a detailed silhouette that a polygon cannot express. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/] ## Image Assets: SVGs vs. Rasters Image assets in Gameface should be selected based on the shape of the artwork and the amount of runtime control the UI needs. Use SVGs for simple scalable graphics, such as icons, logos, dividers, and HUD frames. Use raster images , such as PNGs, for detailed painted artwork, portraits, screenshots, and textures where vector path evaluation would add unnecessary work. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#the-asset-format-problem] ## Image Assets: SVGs vs. Rasters: The Asset Format Problem In a browser prototype, it is common to pick an image format based mainly on visual quality and file size. In a gameface UI, that decision also affects how much work the UI layer performs during layout, rendering, and invalidation. SVGs and raster images solve different problems: - **SVGs** describe shapes mathematically. They stay sharp at different sizes because the renderer draws paths, fills, and strokes at the requested scale. - **Raster images** store a fixed grid of pixels. They are better for detailed artwork because the expensive visual detail is already baked into the image file. The important distinction is that SVG detail is evaluated by the UI renderer, while raster detail is decoded into pixels and then drawn as an image. A simple SVG icon is usually cheap and flexible. A complex SVG illustration with many paths, filters, gradients, or nested groups can become more expensive than a PNG that already contains the same final pixels. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#choosing-between-svgs-and-raster-images] ## Image Assets: SVGs vs. Rasters: Choosing Between SVGs and Raster Images (1/3) Use SVGs for artwork that is mostly geometric : Icons, flat logos, simple button borders, arrows, separators, and HUD outlines usually benefit from SVG because they scale cleanly across different resolutions and aspect ratios. Use raster images for artwork that is visually dense : Character portraits, item illustrations, painted backgrounds, screenshots, and textured panels usually belong in PNG, JPEG, or another raster format. These assets contain color variation and detail that would require many vector paths to reproduce. **SolidJS:** ```tsx import Block from '@components/Layout/Block/Block'; import Image from '@components/Media/Image/Image'; const InventoryCard = () => { return ( ); }; ``` **HTML:** ```html
Dragon armor Legendary item
``` **The Tradeoffs:** SVGs are easier to scale and recolor, but the renderer still has to process their vector structure. Raster images are less flexible at runtime, but detailed art is usually cheaper to render as a pre-baked pixel image than as a large collection of SVG paths. #### Practical Format Rules --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#choosing-between-svgs-and-raster-images] ## Image Assets: SVGs vs. Rasters: Choosing Between SVGs and Raster Images (2/3) For most Gameface UI work, the format decision can be made with a few direct rules: - Use **SVG** for icons, simple logos, flat badges, line art, corner decorations, borders, and scalable HUD shapes. And when you need to manipulate the asset at runtime. - Use **PNG** for transparent high-fidelity UI art, painted panels, portraits, item art, and alpha-heavy textures. - Use **JPEG** only when the asset does not need transparency and compression artifacts are acceptable, such as some large background images (although the use case is very rare). **SVG Usage Gotcha:** Avoid converting complex painted art into SVG only to make it scalable. If the SVG contains many paths, the visual flexibility may not justify the rendering cost #### Mip-Maps (DDS and Engine Textures) When images are displayed at a significantly smaller size than their source resolution — for example a downscaled map icon or a UI element rendered in a 3D viewport — the GPU must sample the full-resolution texture down to fewer pixels. Without pre-generated mip-maps, this produces aliasing and sharp edges that look incorrect. Gameface supports DDS textures with pre-baked mip-maps. If your project integrates Gameface through Unreal Engine, textures exported from Unreal already carry mip-maps natively. Use DDS for any raster asset that will be displayed at variable scale or as part of a 3D UI surface. Standard PNG and JPEG assets do not carry mip-map data; the engine generates a single mip level at load time. For most HUD and menu assets that are displayed at a fixed size, this is fine. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#choosing-between-svgs-and-raster-images] ## Image Assets: SVGs vs. Rasters: Choosing Between SVGs and Raster Images (3/3) **Engine-integration dependent:** DDS mip-map support depends on how Gameface is integrated into your engine. Confirm the supported texture formats with your engine-specific Gameface integration documentation before committing to DDS assets. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#working-with-svg-assets-external-vs-inline] ## Image Assets: SVGs vs. Rasters: Working with SVG Assets: External vs. Inline (1/3) When using SVGs in Gameface or modern web UIs, you should decide **how** to load them based on your use case. There are two primary strategies for SVG assets: **external SVGs** and **inline SVGs**. Understanding when to use each will help you balance performance, maintainability, and flexibility. #### When to Use External SVGs If your SVG does **not** need to be manipulated at runtime (for example, recolored or animated by the UI), keep it **external**. This approach minimizes DOM complexity and keeps your structure clean. There are two common external SVG patterns: ##### element Use when the SVG is meaningful to the content or needs to participate in layout like an image. For example, as a button with an Xbox A glyph icon. **SolidJS:** ```tsx import Button from '@components/Basic/Button/Button'; import Image from '@components/Media/Image/Image'; const NavButton = () => { return ( ); }; ``` **HTML:** ```html ``` ```css .nav-button { display: flex; align-items: center; gap: 10px; height: 56px; padding: 0 18px; } .nav-button__icon { width: 24px; height: 24px; } ``` ##### CSS background-image --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#working-with-svg-assets-external-vs-inline] ## Image Assets: SVGs vs. Rasters: Working with SVG Assets: External vs. Inline (2/3) Use when the SVG is purely decorative and part of the component’s styles. For example, a panel frame with a border. **SolidJS:** ```tsx import Image from '@components/Media/Image/Image'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const QuestPanel = () => { return (
Active Quest
Reach the old watchtower before nightfall. ); }; ``` **HTML:** ```html

Active Quest

Reach the old watchtower before nightfall.

``` ```css .quest-panel { width: 520px; padding: 32px; background-image: url("/assets/ui/panel-frame.svg"); background-repeat: no-repeat; background-size: 100% 100%; } ``` **Performance:** External SVGs keep the DOM small and focused. For example, a menu with 20 icons should use `` or `background-image` - not 20 inline SVGs, each with a heavy node tree. #### When to Use Inline SVGs Use **inline SVG** (putting `` markup directly in your HTML) only if you need fine-grained control over the SVG’s internal structure at runtime. This is essential for: - Per-part styling (e.g., recoloring specific paths or elements) - State-based visuals (e.g., changing only one element within the SVG) - Adding JavaScript logic to specific parts of the SVG --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#working-with-svg-assets-external-vs-inline] ## Image Assets: SVGs vs. Rasters: Working with SVG Assets: External vs. Inline (3/3) **Example:** The canonical inline SVG example - a weapon icon with per-rarity path coloring using CSS custom properties and modifier classes - is covered in full detail in SVG UI Tricks: ViewBox, Strokes, and Fills. **DOM Cost:** Every SVG shape and group adds nodes to your DOM. Inline SVG is best reserved for dynamic, interactive, or variant-heavy icons - not for large numbers of identical decorative UI elements. #### Comparing Approaches The following table summarizes when to use each SVG loading method: Approach | Best For | Main Benefit | Main Cost `` | Static, meaningful icons | Small DOM, simple layout | Can’t style SVG internals CSS `background-image` | Decorative frames & separators | Keeps decoration in CSS | Not semantic, not accessible Inline SVG | Dynamic or stateful vector elements | Rich runtime control | Adds nodes & complexity to DOM **Guideline:** Default to external SVGs for static graphics, and only inline SVGs when you specifically need to access or manipulate their internal parts via CSS or JavaScript. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#gameface-svg-support] ## Image Assets: SVGs vs. Rasters: Gameface SVG Support (1/3) Gameface supports SVGs in the most common frontend scenarios: - Inline in the DOM. - As a CSS `background-image`. - As the source of an `` element. - As a border through `border-image-source`. The supported feature set is a subset of SVG 2.0. Standard CSS styling and CSS animations are supported for inline SVG elements. #### What is supported Feature | Notes Inline SVG in the DOM | Full CSS styling and CSS/WAAPI animations CSS `background-image` | Cached when content size ≤ 1024×1024 `` | Always cached `border-image-source` | Separate surface per 9-slice section `@keyframes` on SVG properties | Units required for shared CSS/SVG property names (e.g. `width`) CSS transitions | Supported on all animatable SVG properties `` element | Deprecated in SVG 2.0 but still supported #### What is not supported Category | Details SMIL animation | ``, ``, `` - convert to CSS keyframes Scripting & interactivity | No script execution inside SVG elements `` | Embedded HTML inside SVG is ignored `pattern` paint server | SVG `` fills are not supported `vector-effects`, `paint-order`, `color-interpolation`, `
` and `` linking elements, Multimedia, Conditional processing, metadata, WAI-ARIA | Not supported Full SVG text | Only basic `` support; `` ignored, `` text treated as part of parent #### stroke-dasharray and stroke-dashoffset --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#gameface-svg-support] ## Image Assets: SVGs vs. Rasters: Gameface SVG Support (2/3) These properties only work on **`` elements**. They do not work on ``, ``, ``, or other SVG shape primitives. If you need a circular or rectangular progress shape, draw it as a ``. #### CSS vs. SVG property names Several properties share names between CSS and SVG but follow different rules. In SVG attributes, `width`, `height`, and `font-size` may be unitless. In CSS keyframes targeting SVG elements, these values must include units (`px`, `em`, etc.) even when the SVG attribute normally does not. SVG-only attributes like `x`, `y`, `cx`, and `cy` remain unitless. Here is a practical example of markup that should be avoided in Gameface because it relies on unsupported SVG features: ```html
Embedded HTML in SVG
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#gameface-svg-support] ## Image Assets: SVGs vs. Rasters: Gameface SVG Support (3/3) Before relying on a less common SVG element or attribute, check the [official Gameface SVG support table ](https://docs.coherent-labs.com/cpp-gameface/content_development/supported_features_tables/svgsupport/). This is especially important when importing SVGs exported from design tools, because those files can include metadata, masks, clip paths, text nodes, grouped effects, or unsupported paint features that are not visible at first glance. **Asset Export Checklist:** Before committing SVG assets, open the exported file and remove unnecessary metadata, hidden layers, editor-specific attributes, and unused groups. Cleaner SVGs are easier to inspect, cheaper to parse, and less likely to depend on unsupported SVG features. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/image-assets/#recommended-workflow] ## Image Assets: SVGs vs. Rasters: Recommended Workflow Instead of treating this as a single checklist, make the decision in three short passes: asset type, loading mode, then compatibility validation. #### Pass 1: Identify the Asset Type Start by asking what visual problem the asset solves: - If it is high-detail artwork (portraits, painted panels, item art), use a raster format. - If it is geometric UI structure (icons, borders, separators, symbols), use SVG. #### Pass 2: Pick the Loading Mode Once the asset is SVG, decide how it enters the DOM: - Use external loading (`` or CSS `background-image`) for static visuals. - Use inline SVG only when you must target internal nodes (for example per-path color states, stroke progression, or viewBox-driven effects). #### Pass 3: Validate Engine Compatibility Before integrating exported SVGs from design tools: - Open the SVG and remove editor metadata, hidden groups, and unused nodes. - Check for unsupported features (for example ``, SMIL tags, scripting blocks). - Cross-check uncommon elements and attributes against the official support table. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/] ## SVG UI Tricks: ViewBox, Strokes, and Fills This article focuses on three practical inline SVG techniques used in game UI: dynamic visual variants through fill and stroke , camera-like minimap control through viewBox , and progress/connection effects through stroke dashing . The key principle is to keep SVGs inline only when you need internal node control. For static artwork, keep using external SVGs as covered in the previous article. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#why-inline-svg-matters-for-stateful-ui] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Why Inline SVG Matters for Stateful UI When the same icon or shape appears in multiple gameplay states, exporting a new image for each state quickly creates asset duplication. Inline SVG lets you keep one geometry definition and apply different visual states with classes, variables, and data attributes. This is valuable for: - Rarity tiers, locked/unlocked states, cooldown overlays, and quest-state highlights. - Reusable widgets, such as minimaps and radial meters, where geometry remains constant but appearance changes each frame. - UI systems that need rapid iteration without re-exporting large icon sets. **The Tradeoff:** Inline SVG gives precise control over internal paths, but every inline node is still part of the DOM tree. Use this pattern for stateful graphics, not for every decorative icon in large repeated lists. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#generating-variations-with-fills-and-strokes] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Generating Variations with Fills and Strokes (1/3) A typical use case for inline SVG is handling item rarity. For example, in a game’s UI, you may need the same weapon icon to appear in several different states depending on gameplay needs: - neutral (common) - colored (rare) - colored and emphasized (legendary) - disabled (locked) Exporting separate images for each variation is possible, but leads to more files to manage and slows down future updates. Inline SVG gives you a more maintainable option: keep the geometry in the markup, then let CSS classes control the visual state. The important part is that each meaningful SVG shape has a class. In this example, the blade, guard, and spark can all be styled independently. ```html ``` The SVG itself does not know what rarity it represents. It only exposes named pieces of geometry. The base `.weapon-button` class defines the default variables, and the SVG paths read from those variables. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#generating-variations-with-fills-and-strokes] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Generating Variations with Fills and Strokes (2/3) ```css .weapon-button { --blade-fill: #8b8b8b; /* The main blade color (default: neutral weapon) */ --blade-stroke: transparent; /* Optional outline for blade (invisible in base state) */ --guard-fill: #373330; /* The color of the sword guard */ --spark-fill: transparent; /* Spark highlight (revealed for legendary, hidden by default) */ --spark-opacity: 0; /* Spark visibility */ } .weapon-icon { width: 58px; height: 58px; } .weapon-icon__blade { fill: var(--blade-fill); stroke: var(--blade-stroke); stroke-width: 1.5; transition: fill 140ms ease, stroke 140ms ease; } .weapon-icon__guard { fill: var(--guard-fill); transition: fill 140ms ease; } .weapon-icon__spark { fill: var(--spark-fill); opacity: var(--spark-opacity); transition: fill 140ms ease, opacity 140ms ease; } ``` **Why It Works:** CSS variables set on the button are passed down to the SVG inside it. This means each SVG path can use those variables for its colors and styles. So, you can change the whole icon’s look just by updating the class or variables on the button, without repeating code inside the SVG. Once the base styles exist, rarity variations only need to apply classes that override variables: In this example, there are three modifier states beyond the base style: - The rare state changes the blade color and adds a stroke. - The legendary state keeps the stronger blade treatment and reveals the spark path. - The disabled state desaturates the icon by changing the blade and guard values. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#generating-variations-with-fills-and-strokes] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Generating Variations with Fills and Strokes (3/3) ```css .weapon-button--rare { /* Only change blade and add a stroke to simulate shine */ --blade-fill: #f2a34e; --blade-stroke: #ffd89d; } .weapon-button--legendary { /* Keep the stronger blade treatment and reveal the spark path */ --blade-fill: #4ef2d9; --blade-stroke: #c8fff6; --spark-fill: #c8fff6; --spark-opacity: 1; } .weapon-button--disabled { /* Desaturate the icon by changing the blade and guard values */ --blade-fill: #3f3f3f; --guard-fill: #2a2a2a; } ``` Applying a variation is then just a class change on the base element. The SVG paths update automatically because their `fill`, `stroke`, and `opacity` are connected to the variables. An example change of the state could look like this: ```js const button = document.getElementById("preview-button"); function applyRarity(rarityClass) { button.classList.remove("weapon-button--rare", "weapon-button--legendary", "weapon-button--disabled"); if (rarityClass) { button.classList.add(rarityClass); } } applyRarity("weapon-button--legendary"); applyRarity(""); /* Return to the base/common state */ ``` **The Performance Win:** A single SVG structure with class-driven variables scales cleanly across many states. You avoid creating separate icon files for each visual variant while keeping the state system easy to audit and extend. The entire example looks like this: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (1/6) Another useful inline SVG pattern is using `viewBox` as a camera for maps and minimaps. Instead of moving every map path individually, the SVG keeps the same UI size and you change which part of its internal coordinate system is visible. The important distinction is that the SVG has two different sizes: - The **CSS size**, which controls how large the map appears in your UI. - The **`viewBox` size**, which controls which internal SVG coordinates are currently visible. The `viewBox` attribute is made of four numbers: ```html viewBox="x y width height" ``` - `x` and `y` define the top-left position of the visible window inside the SVG map. - `width` and `height` define how much of the SVG map is visible. - Increasing `x` or `y` pans across the map. - Reducing `width` and `height` zooms in because the same screen area now shows a smaller part of the SVG coordinate space. #### Defining the Map Coordinate Space Set up an SVG with a `viewBox` so we can define the coordinate space and the initial visible area. This gives us a baseline before we pan and zoom by changing the `viewBox` values: ```html
``` From here, all map movement and zooming comes from updating `viewBox`. The `viewBox="0 0 400 400"` value means: - Start viewing the SVG from coordinate `0, 0`. - Show `400` units horizontally. - Show `400` units vertically. **Match the authored coordinate space:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (2/6) `viewBox` values should match the coordinate space your SVG was authored in. If your paths were drawn in a `0..400` by `0..400` space, use `viewBox="0 0 400 400"` as the baseline. This also sets camera bounds. With a `400x400` authored map, the camera’s max top-left position is computed from `MAP_WIDTH - visibleWidth` and `MAP_HEIGHT - visibleHeight`, where `MAP_WIDTH` and `MAP_HEIGHT` are both `400`. Aspect ratio still matters, but ratio alone is not enough. The coordinate range must align with how the SVG content is authored. ```css .map-frame { width: 56vh; height: 56vh; border: 0.12vh solid #2a3b49; border-radius: 0.8vh; overflow: hidden; background: #0f151c; } .world-map { width: 100%; height: 100%; } ``` Here the map is sized with `vh` so it scales with the game viewport. You could use `px`, `vh`, `vmax`, or a layout-specific variable. The `viewBox` logic would stay the same because `viewBox` does not use CSS units. It uses the SVG’s internal coordinate system. In other words, `width: 56vh` and `height: 56vh` only define the final UI box on screen. The internal map is still `400x400` SVG units, and every point, road, marker, and region is interpreted inside that coordinate space. When the UI box grows or shrinks, the SVG content scales proportionally to fit that box. #### Building the viewBox Camera Treat the `viewBox` as a rectangular camera window moving over the SVG map: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (3/6) - `panX` controls the camera’s left edge. - `panY` controls the camera’s top edge. - `visibleWidth` controls how much of the map is visible horizontally. - `visibleHeight` controls how much of the map is visible vertically. Start by storing the full map size and the current camera state: ```js const map = document.getElementById("world-map"); const MAP_WIDTH = 400; const MAP_HEIGHT = 400; let zoom = 1; let panX = 0; let panY = 0; ``` The zoom value does not scale the SVG element directly. Instead, it changes how large the visible window is. At `zoom = 1`, the visible window is the full `400x400` map. At `zoom = 2`, the visible window becomes `200x200`, so the same UI area displays a smaller portion of the map and appears zoomed in. Notice that this calculation never reads the CSS size of `.map-frame`. Whether the map is rendered as `56vh`, or any other responsive size, the camera math still operates in `400x400` SVG coordinates. ```js const visibleWidth = MAP_WIDTH / zoom; const visibleHeight = MAP_HEIGHT / zoom; ``` After calculating the camera size, clamp its position (bounds check). Without this clamp, the camera could move past the edge of the SVG and reveal empty space. ```js const x = Math.max(0, Math.min(panX, MAP_WIDTH - visibleWidth)); const y = Math.max(0, Math.min(panY, MAP_HEIGHT - visibleHeight)); ``` Finally, write the four camera values back into the SVG: ```js map.setAttribute("viewBox", `${x} ${y} ${visibleWidth} ${visibleHeight}`); ``` Combined into a function, the camera update looks like this: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (4/6) ```js function applyViewBox() { const visibleWidth = MAP_WIDTH / zoom; const visibleHeight = MAP_HEIGHT / zoom; const x = Math.max(0, Math.min(panX, MAP_WIDTH - visibleWidth)); const y = Math.max(0, Math.min(panY, MAP_HEIGHT - visibleHeight)); map.setAttribute("viewBox", `${x} ${y} ${visibleWidth} ${visibleHeight}`); } applyViewBox(); ``` #### Moving the camera with mouse input A common pattern is to use mouse input to move the camera. This is done by tracking the mouse position and converting it into SVG coordinates. For mouse-based map navigation, connect dragging to `panX` / `panY` and the mouse wheel to `zoom`. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (5/6) ```js let isDragging = false; let lastMouseX = 0; let lastMouseY = 0; map.addEventListener("mousedown", (event) => { isDragging = true; lastMouseX = event.clientX; lastMouseY = event.clientY; }); map.addEventListener("mousemove", (event) => { if (!isDragging) return; const visibleWidth = MAP_WIDTH / zoom; const visibleHeight = MAP_HEIGHT / zoom; const deltaX = event.clientX - lastMouseX; const deltaY = event.clientY - lastMouseY; // Convert screen movement into SVG coordinate movement. panX -= deltaX * (visibleWidth / map.clientWidth); panY -= deltaY * (visibleHeight / map.clientHeight); lastMouseX = event.clientX; lastMouseY = event.clientY; applyViewBox(); }); map.addEventListener("mouseup", () => { isDragging = false; }); map.addEventListener("wheel", (event) => { event.preventDefault(); zoom += event.deltaY < 0 ? 0.2 : -0.2; zoom = Math.max(1, Math.min(zoom, 8)); applyViewBox(); }); ``` The end result looks like this: **Why It Works:** The drag calculation is the bridge between the two coordinate systems. `deltaX` and `deltaY` come from the mouse in screen pixels, while `panX` and `panY` are SVG coordinates. Dividing the visible SVG window by the rendered element size converts one screen pixel into the correct amount of SVG map movement. This is why the same interaction continues to work regardless of the map’s UI size. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#minimap-panning-with-viewbox] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Minimap Panning with viewBox (6/6) You are not scaling or translating the DOM node itself. You are changing the visible coordinate window inside the SVG. The map can remain a fixed-size UI component while the internal vector coordinate system handles the camera movement. This also avoids maintaining multiple raster map resolutions for different zoom levels. The SVG paths remain vector data, so the map stays resolution-independent compared to texture-based minimap images. **Complex SVG Cost:** Changing `viewBox` on a complex SVG can still trigger redraw work. This is usually appropriate for controlled interactions, such as opening a map screen or dragging a minimap, but you should avoid unnecessary **per-frame** updates on very large SVG maps. If the SVG contains many moving paths, labels, and decorative layers, profile the interaction in the target UI . --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#progress-bars-and-connections-with-stroke-dashing] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Progress Bars and Connections with Stroke Dashing (1/5) Some UI elements need to show partial progress along a fixed shape. A loading bar can fill from left to right, a circular meter can reveal around its rim, or a skill-tree connector can light up as the next node unlocks. Exporting separate images for each step is not practical, because the geometry is the same and only the visible portion changes. Before explaining the progress logic, let’s overview the SVG properties involved: - `d` defines the shape of the path element . For a straight progress bar, this can be a simple move-and-line command such as `M 24 40 L 276 40`. - `pathLength` defines a normalized length for the path. In this example, `pathLength="100"` lets the dash values behave like percentages instead of using the path’s authored coordinate length. - `stroke` defines the visible color of the path outline. In this pattern, the track usually uses a dim color and the fill path uses the active color. - `stroke-width` defines how thick the outlined path appears. - stroke-dasharray defines the dash pattern used to draw the stroke. If you set it to the same value as the path length, the path becomes one long dash. - stroke-dashoffset shifts that dash along the path. This is the value you change to hide or reveal the colored stroke. **\ elements only:** `stroke-dasharray` and `stroke-dashoffset` only work on `` elements in Gameface. They do not function on ``, ``, ``, or other SVG shape elements. If you need a circular or rectangular progress shape, draw it as a `` rather than using a native SVG shape element. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#progress-bars-and-connections-with-stroke-dashing] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Progress Bars and Connections with Stroke Dashing (2/5) These properties work together by turning one path into a controllable reveal. The foreground path is still fully present in the SVG, but the dash offset hides part of its stroke. At `progress = 0`, the offset equals the full path length and the colored stroke is hidden. At `progress = 1`, the offset is `0` and the full stroke is visible. **Explicit PathLength:** Without `pathLength`, the full length of this straight path would come from its coordinates. In the example below, `276 - 24` gives a length of `252`, which is correct but reads like a magic number in code. Setting `pathLength="100"` gives the path a predictable progress scale. The full dash becomes `100`, then `stroke-dashoffset: 100` hides it, `stroke-dashoffset: 50` reveals half of it, and `stroke-dashoffset: 0` reveals all of it. #### Creating a progress bar Start with two paths using the same `d` value. The first path is the dim track. The second path is the colored fill that will be revealed by changing its dash offset: ```html ``` The CSS keeps both shapes visually aligned. The foreground path uses the same geometry as the track, but its visible length is controlled by the dash properties: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#progress-bars-and-connections-with-stroke-dashing] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Progress Bars and Connections with Stroke Dashing (3/5) ```css .energy-meter { width: 300px; height: 80px; } .meter__track, .meter__fill { fill: none; stroke-width: 10; stroke-linecap: round; } .meter__track { stroke: rgba(255, 255, 255, 0.12); } .meter__fill { stroke: #60c8ff; stroke-dasharray: 100; /* Match the normalized path length. */ stroke-dashoffset: 100; /* Start fully hidden. */ } ``` Once the SVG structure exists, the update code only needs to convert a normalized progress value into a dash offset. This is also where the stroke can switch from an idle color to an active color: ```js const fillPath = document.getElementById("energy-fill"); const pathLength = 100; const activeColor = "#60c8ff"; const idleColor = "rgba(255, 255, 255, 0.12)"; function setProgress(value) { const progress = Math.max(0, Math.min(value, 1)); const offset = pathLength * (1 - progress); fillPath.setAttribute("stroke-dashoffset", String(offset)); fillPath.setAttribute("stroke", progress > 0 ? activeColor : idleColor); } setProgress(0.65); ``` **Why It Works:** The core method is to set `stroke-dasharray` to the same value as `pathLength`, then change `stroke-dashoffset` to reveal or hide the stroke. `pathLength` does not resize or reshape the SVG path. It normalizes the measurement scale used by dash calculations, so the example can use `100` instead of carrying the authored coordinate length through the CSS and JavaScript. #### Creating a skill tree node connection --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#progress-bars-and-connections-with-stroke-dashing] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Progress Bars and Connections with Stroke Dashing (4/5) The same idea scales to a skill tree without changing the rendering technique. Each connection can store a path definition and a length, or normalize the connector with `pathLength="100"` if you want to keep the progress math percentage-based: ```js const edge = { d: "M 200 50 L 90 155", length: 100, }; ``` Render a dim ghost path underneath, then render a second path with the same `d` value on top. The game UI logic decides whether a node is locked, unlocking, or complete, but the SVG layer still only needs the same two values: ```js const dashOffset = edge.length * (1 - progress); edgePath.setAttribute("stroke-dasharray", String(edge.length)); edgePath.setAttribute("stroke-dashoffset", String(dashOffset)); edgePath.setAttribute("stroke", progress > 0 ? nodeColor : "rgba(255,255,255,0.07)"); ``` The end result can look like this: #### Creating a circular progress bar This dash pattern is most useful when the shape is not a plain rectangle. A circular health meter, a curved cast bar, a route line on a map can all use the same offset logic. The geometry can be straight, curved, or circular, while the progress value remains a single number. As a matter of fact, this is exactly how our `` component in Gameface UI works. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/svg-ui-tricks/#progress-bars-and-connections-with-stroke-dashing] ## SVG UI Tricks: ViewBox, Strokes, and Fills: Progress Bars and Connections with Stroke Dashing (5/5) ```tsx {/* The outline path is the same as the fill path, but it is not filled. */} ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/] ## Texture Atlases A texture atlas packs many images into one sheet, so the engine creates one texture instead of one per image. Its value in Gameface is in preloading : a few sheets can be loaded before a view opens, so the view shows its images without creating any textures. The first half of this article covers when an atlas is worth it. The second half covers the tooling for Gameface UI projects, which builds the sheets for you. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#what-an-atlas-changes] ## Texture Atlases: What an Atlas Changes An atlas combines images into a sheet that Gameface loads as one GPU texture. It is most useful when a view has many images that can be loaded before the view opens. Atlases make resource loading straightforward and predictable: preload a few sheets, and the view’s images are ready together instead of creating many textures as they appear. Sprites cost about the same to draw, and a sheet can use somewhat more GPU memory because it includes transparent space. That modest cost is often worthwhile for simpler preloading and predictable performance. See Asset and Resource Cost for broader performance guidance. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#when-an-atlas-pays-off] ## Texture Atlases: When an Atlas Pays Off For an inventory with many icons across tabs, preload their atlas before opening the inventory. Loading the whole sheet on first use can cause a larger hitch than loading individual icons as needed, but preloading moves that work out of the interaction. The atlas then keeps the icons ready together for the inventory’s lifetime; individual textures can be released when no longer needed. Situation | Atlas? Many images used by a view, with time to preload before it opens | **Yes.** Preload the atlas so loading does not interrupt the view. The atlas is first loaded when the view opens | **Preload it earlier.** Loading the whole sheet on demand can cause a larger hitch. A few images used briefly from a much larger sheet | **No.** Use individual files to avoid keeping unused atlas content loaded. **Profile before and after:** Compare texture memory and the frames when images appear, both with and without the atlas. See Performance & Memory Profiling for recording a trace. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (1/7) Everything above applies to any stack: pack the images with a sprite-sheet tool, draw each sprite with `background-position` and `background-size`, and preload the sheets. Gameface UI projects automate this. The boilerplate includes an images plugin that works together with the [`Image` ](https://gameface-ui.coherent-labs.com/components/media/image/)component. At build time, the plugin finds which images each view uses, packs them into sheets, and tells `Image` where each sprite sits. Your code does not change: `` renders the sprite in a build and the plain file in development. The rest of this article covers that tooling. The full option reference is in the [Images and texture atlases ](https://gameface-ui.coherent-labs.com/docs/concepts/images-and-atlases/)documentation. #### Setup The plugin packs `.png`, `.jpg`, `.jpeg` and `.webp` files in `src/assets` referenced as dot paths, such as ``. Images passed through `src`, rendered with `options` props, SVGs and CSS `url()` references remain as plain files. Packed originals are removed from the build unless the group sets `keepOriginals`. Atlasing is off by default. Each group creates one or more sheets per view; unmatched images stay as files: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (2/7) ```ts gamefaceImages({ assets: resolve(__dirname, 'src/assets'), types: resolve(__dirname, 'src/components/Media/Image/ImageTypes.ts'), atlasDefaults: { padding: 4 }, atlas: [ { include: 'icons/gamepad/xbox', name: 'glyphs-xbox', squareCells: true }, { include: 'icons/gamepad/ps5', name: 'glyphs-ps5', squareCells: true }, { include: 'items', exclude: 'items/portraits', maxSpriteSize: 512, maxWidth: 4096, maxHeight: 4096, }, ], }), ``` **Building the sheets:** Running `npm run build` generates the sheets and prints a build report. Only the images each view actually uses are atlassed, not every image in the folders a group matches. The dev server does not build sheets. #### Choosing Groups A group defines a sheet, which will be both preloaded and kept in memory as a unit. Group images that are needed together; leave unrelated images out. The config follows these rules: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (3/7) Config | Why `atlasDefaults: { padding: 4 }` | Padding prevents neighboring sprites bleeding through at fractional UI scales. The default applies to every group. One glyph group per platform | Players use one controller, so separate sheets let you preload only that platform’s glyphs. `squareCells` on glyphs | Square element slots would squash non-square glyphs in the atlas without this setting. `items` as one group | Preload the inventory icons together before the inventory opens. `maxWidth` / `maxHeight: 4096` | Keeps `items` on one sheet rather than splitting it across multiple sheets. Check `% used` to see how much of the sheet is occupied. `exclude: 'items/portraits'` | The inspector shows one portrait at a time. Excluding portraits avoids keeping the whole set in memory; `maxSpriteSize` would not exclude them by usage. `maxSpriteSize: 512` | Keeps larger artwork added to `items` as separate files. No `icons/hud` group | HUD icons stay visible all the time so adding them to an atlas would only add transparent space. **Group order:** Images go to the first matching group. Put specific patterns before broad ones: ```ts atlas: ['icons/hud', 'icons'] // HUD icons on their own sheet, the rest on 'icons' atlas: ['icons', 'icons/hud'] // 'icons' takes everything, 'icons/hud' warns: matched no image ``` **Sheets and views:** Each view gets its own sheets. An image used by two views is packed into both views’ sheets, so if both views are open at the same time, that image is loaded twice. #### Preloading the Sheets --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (4/7) Sheets are written to `dist/assets` as `atlas-{view}-{group}.png`; use the build report’s paths when registering them with the engine. Register those paths with your engine integration, as described in Asset Preloading & Bundler Config. Preloading registers files by path, so sheet names carry no content hash. Adding or removing a sprite keeps the path. These changes rename a sheet: Change | Before | After Group outgrows one sheet | `atlas-menu-items.png` | `atlas-menu-items-0.png`, `atlas-menu-items-1.png` Group renamed | `atlas-menu-items.png` | `atlas-menu-loot.png` View folder renamed | `atlas-menu-items.png` | `atlas-pause-items.png` #### Reading the Build Report Each build reports the sheets generated for each view, their sizes, and any images left out. Use the report to decide whether a group needs adjustment. ```txt 2 sheet(s), 86 sprite(s) · 86 files 1790.9 KB -> 2 files 1935.2 KB · GPU 9.5 MB -> 17.0 MB Menu glyphs-xbox 512x512 95.2 KB (1.0 MB) 22 sprites 81% used was 88.6 KB (0.8 MB) dist/assets/atlas-menu-glyphs-xbox.png items 2048x2048 1840.0 KB (16.0 MB) 64 sprites 52% used was 1702.3 KB (8.7 MB) dist/assets/atlas-menu-items.png skipped legendary-sword.png 1024x1024 > maxSpriteSize 512 ("items") spread sword.png packed ("items"), but rendered with {...props} - ... ``` ##### Sheets Each sheet entry shows its group, dimensions, disk and GPU memory sizes, sprite count, space used, and the separate-file size. The line below gives its output path. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (5/7) GPU memory (in brackets) is calculated as width x height x 4. In this example, the `items` sheet is 52% used: its 16 MB texture holds 8.7 MB of sprites. ##### Skipped Images `skipped` lists images left as files and why: no matching group, `options`, a `src` prop, or exceeding `maxSpriteSize`. ##### Spread `spread` flags a packed image used with spread props, which the plugin cannot inspect. If the spread carries `options`, the image needs its original file, which the build removed: ```tsx const ItemSlot = (props) => ; // fine // blank in the build ``` ```ts { include: 'items', keepOriginals: true } // ships the original next to the sheet ``` **Caution:** `keepOriginals` fixes the blank image, but `sword.png` stays on the sheet as well. If it does not belong there, exclude it instead: `exclude: 'items/sword.png'`. ##### Warnings The plugin prints a Vite warning when the build gives a different result from what the config asks for. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (6/7) - **`atlas "items" matched no image in any view`**: no sheet is built for the group. Usually a path mistake, since patterns are relative to `src/assets`: `'icons/hud'`, not `'hud'`. - **`pot is on and maxWidth is 3000, which is not a power of two`**: sheets are capped at 2048, not 3000. `pot` rounds a sheet up first, then rejects it if it passes the limit. - **`... is atlassed in "Menu" but used outside Image in "Hud" - shipping both`**: Hud still needs the plain file, so the original cannot be removed and the image ships twice, as a sprite and as a file. The build still succeeds in all three cases. #### Tuning The intended usage of the plugin includes adjusting the configuration settings based on the exported sheet and the build report. Therefore, for the best results, review the symptoms in the report and apply the recommended changes accordingly. Symptom | Change Low `% used` | `pot: false`, or split the group. `pot` is on by default because GPUs handle power-of-two textures best; turning it off saves texture memory but may cost rendering performance. Profile before and after. A group creates several numbered sheets | Raise `maxWidth` / `maxHeight`, or split the group. Large artwork packed into a sheet | Lower `maxSpriteSize` or exclude the image from the atlas. Non-square images appear stretched | Set `squareCells: true`. Neighboring sprites bleed when scaled | Increase `padding`. An image is also referenced from CSS | Set `keepOriginals: true`. **Defaults for every group:** `atlasDefaults` sets these for every group; a group’s own settings override it. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/graphics--shapes/texture-atlases/#atlases-in-gameface-ui] ## Texture Atlases: Atlases in Gameface UI (7/7) **Stretched sprites:** Without `squareCells`, a non-square image looks right in dev and squashed in the build, because a sprite stretches to fill its element while a plain `Image` fits and centres. ```ts { include: 'icons/gamepad/xbox', squareCells: true } ``` For cases the plugin cannot detect, such as `options` passed through spread props or images also used from CSS, see the [Images and texture atlases ](https://gameface-ui.coherent-labs.com/docs/concepts/images-and-atlases/)documentation. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/] ## Laying out the screen In game UI, layout isn’t just about making things look good - it is about predictability and respecting the strict frame budget. This article covers the Gameface Flexbox-only layout model, how to architect your screen using absolute anchors versus flexbox flows, how the engine classifies CSS changes as cheap or expensive layout work, and the two CSS rules that eliminate the worst-case performance cliff in deep DOM trees. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#how-layout-works-in-gameface] ## Laying out the screen: How Layout Works in Gameface If you are coming from traditional web development, the biggest mental shift when authoring for Gameface is understanding the layout engine. In a standard browser, you have multiple layout algorithms: `block`, `inline`, `grid`, `flex`, and `table`. Gameface uses the Yoga layout engine (developed by Meta/Facebook) as its sole layout algorithm. `display: grid` is entirely absent - all `grid-*` properties are silently ignored. Display values like `inline-block`, `inline-flex`, `contents`, and `inline-grid` are unsupported. The only valid display values are `flex` and `none`. Even elements that default to block in a browser are internally treated as flex containers by Gameface. Every layout calculation goes through Yoga. Because everything is flex-based, every time an element’s size, position, or content changes, the engine evaluates how that change affects the surrounding document. This is called a layout pass . Because flexbox distributes space dynamically, elements are highly dependent on their siblings and parents. Gameface’s layout engine is fast, but the environment is extremely demanding. A game targeting 60 FPS has exactly 16.6 milliseconds per frame. The UI is usually allocated only 1–2ms of that. A 15ms layout recalculation that goes unnoticed in a browser blows the entire frame budget in a game engine. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#transforms-vs-full-layout-solves] ## Laying out the screen: Transforms vs. Full Layout Solves (1/2) The engine classifies every CSS change as one of two types of layout work: A Full Layout Solve runs whenever a property that affects document flow changes - `width`, `height`, `margin`, `padding`, `flex-basis`, `flex-grow`, `flex-shrink`, `left`, `right`, `top`, `bottom`. Yoga traverses the affected subtree and recalculates positions and sizes from scratch. A Transform Update runs when only `transform` or `opacity` has changed. Untransformed positions have not shifted, so Yoga is skipped entirely. The engine runs a lighter pass without touching the layout tree. The CPU cost difference is significant. Floating damage numbers are a clear illustration: **SolidJS:** ```tsx import Absolute from '@components/Layout/Absolute/Absolute'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const DamageNumber = (props: { value: number }) => ( -{props.value} ); ``` **HTML:** ```html
-245
``` ```css /* ❌ Animating 'top' - triggers a full layout solve every frame */ @keyframes float-bad { from { top: 0; opacity: 1; } to { top: -5rem; opacity: 0; } } /* ✅ Animating 'transform' - Yoga is skipped entirely */ @keyframes float-good { from { transform: translateY(0); opacity: 1; } to { transform: translateY(-5rem); opacity: 0; } } .damage-number { position: absolute; animation: float-good 0.8s ease-out forwards; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#transforms-vs-full-layout-solves] ## Laying out the screen: Transforms vs. Full Layout Solves (2/2) **Rule: Always animate with `transform` and `opacity`. Never animate `top`, `left`, `width`, or `height`.** This applies to CSS keyframes and JavaScript-driven animations alike. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#the-layout-performance-cliff] ## Laying out the screen: The Layout Performance Cliff Yoga’s algorithm has O(4^Depth) worst-case complexity. A tree with 8 nodes at depth 4 produces 172 layout calls in the worst case and only 9 in the best case. Real shipped Gameface UIs have DOM depths between 14 and 28 nodes, where unoptimized subtrees can generate thousands of redundant calls per frame. The worst case requires all three conditions to be true simultaneously: 1. **No defined flex dimensions.** Children without `flex-basis`, `width`, or `height` force Yoga to recurse into their subtree to measure natural size. 2. **Cross-axis stretching.** `align-items: stretch` (the CSS *default*) forces Yoga to re-enter each child after measuring to grow it to fill the cross-axis. 3. **Wrapping enabled.** `flex-wrap: wrap` causes repeated line re-evaluation. ```css /* ❌ All three worst-case conditions active - inventory-grid with unsized slots */ .inventory-grid { display: flex; flex-wrap: wrap; /* Condition 3 */ /* align-items defaults to 'stretch' - condition 2 is active silently */ } .item-slot { display: flex; flex-direction: column; /* No flex-basis, no width - condition 1: Yoga must recurse to measure each slot */ } ``` **align-items: stretch Is the CSS Default:** You do not need to write `align-items: stretch` to trigger it - any flex container without an explicit `align-items` declaration is already using it. A deep, wrapping UI tree can be silently running in worst-case performance mode. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#how-to-optimize-layouts] ## Laying out the screen: How to Optimize Layouts (1/2) Two fixes eliminate the worst-case conditions. Both can be applied independently and their effects are cumulative. #### Define Dimensions on Flex Items A defined `flex-basis` (or explicit `width`/`height`) on every flex item eliminates the recursive `measure` call. Gameface’s own internal stress tests show this reduces layout time from \~2,000ms to \~17ms on a realistic 4,400-node UI tree - a 99%+ reduction for the same visual output. ```css /* ✅ Defined dimensions eliminate the measure call at every level */ .inventory-grid { display: flex; flex-wrap: wrap; align-items: flex-start; } .item-slot { display: flex; flex-direction: column; align-items: flex-start; flex-basis: 8rem; /* Defined - Yoga skips the measure pass for this subtree */ height: 10rem; } .item-slot__icon { width: 6rem; /* Leaf node sized - no recursive measure needed */ height: 6rem; } ``` #### Use align-items Sparingly Each `align-items: stretch` on a flex container adds two extra layout calls per line per frame. Replace `stretch` with explicit `flex-start`, `flex-end`, or `center` on containers where children do not need to fill the cross-axis: --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#how-to-optimize-layouts] ## Laying out the screen: How to Optimize Layouts (2/2) ```css /* ❌ 'stretch' is default - three containers silently trigger cross-axis traversals */ .inventory-grid { display: flex; flex-wrap: wrap; } .item-slot { display: flex; flex-direction: column; } .item-slot__info { display: flex; } /* ✅ Explicit non-stretch values - cross-axis recursive calls eliminated */ .inventory-grid { display: flex; flex-wrap: wrap; align-items: flex-start; } .item-slot { display: flex; flex-direction: column; align-items: flex-start; } .item-slot__info { display: flex; align-items: center; } ``` **The Combined Effect:** Both fixes together reduce Yoga’s traversal from O(4^Depth) to O(N) - a single pass. For the 8-node reference tree, call count drops from 172 to 9. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#high-performance-layout-patterns] ## Laying out the screen: High-Performance Layout Patterns (1/4) With the performance rules established, here are the practical “Do’s and Don’ts” for structuring your screens. #### Use Absolute Positioning for Top-Level Widgets `position: absolute` removes the element from the normal flow and is computed separately. If an absolutely positioned widget changes its internal size, it never pushes siblings around. Use it for all top-level HUD widgets. ##### Centering a Crosshair **SolidJS:** ```tsx import Absolute from '@components/Layout/Absolute/Absolute'; import Image from '@components/Media/Image/Image'; const Crosshair = () => ( ); ``` **HTML:** ```html
Crosshair
``` ```css .crosshair-wrapper { position: absolute; width: 2rem; height: 2rem; left: 50%; top: 50%; transform: translate(-50%, -50%); } .crosshair { transition: transform 0.1s ease-out; width: 100%; height: 100%; } ``` When the crosshair scales using `transform`, the layout engine ignores it entirely - it repaints independently, preserving your frame budget. ##### Anchoring to a 3D Object (Nameplates) Nameplates receive updated screen coordinates from the engine every frame as the camera moves. Using an absolutely positioned element means those constant `left`/`top` updates only affect that specific node: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#high-performance-layout-patterns] ## Laying out the screen: High-Performance Layout Patterns (2/4) ```tsx import Absolute from '@components/Layout/Absolute/Absolute'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const Nameplate = (props: { name: string }) => ( {props.name} ); ``` **HTML:** ```html
Player 1
``` ```css .nameplate { position: absolute; width: 15rem; height: 3rem; left: 0; /* Updated via JS every frame */ top: 0; } ``` If this nameplate were inside a flex container, updating its position 60 times per second would force continuous, heavy layout recalculations. #### Use Flexbox for Internal Content Absolute positioning is impractical for elements that relate to each other (lists, rows, grids). Use `display: flex` for internal widget layout, and always define explicit dimensions on flex children. ##### Centering within a Control **SolidJS:** ```tsx import Button from '@components/Basic/Button/Button'; import Flex from '@components/Layout/Flex/Flex'; import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const ActionButton = () => ( ); ``` **HTML:** ```html
Attack
``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#high-performance-layout-patterns] ## Laying out the screen: High-Performance Layout Patterns (3/4) ```css .action-button { display: flex; width: 15rem; height: 4rem; justify-content: center; align-items: center; gap: 1rem; } .action-icon { width: 2rem; height: 2rem; } ``` ##### Mixing Both: Notification Badge on an Inventory Slot Setting the parent to `position: relative` creates a local coordinate system that lets a badge use `position: absolute` while remaining visually anchored to the item: **SolidJS:** ```tsx import Relative from '@components/Layout/Relative/Relative'; import Absolute from '@components/Layout/Absolute/Absolute'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const InventorySlot = (props: { badgeCount?: number }) => ( {/* item icon goes here */} {props.badgeCount && ( {props.badgeCount} )} ); ``` **HTML:** ```html
3
``` ```css .inventory-slot { display: flex; width: 5rem; height: 5rem; position: relative; /* Creates local anchor for the badge */ } .notification-badge { position: absolute; width: 1.5rem; height: 1.5rem; top: -0.5rem; right: -0.5rem; } ``` Notification badges toggle frequently. Because the badge is absolutely positioned, hiding or showing it does not force the surrounding inventory grid to recalculate its flex spacing. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/laying-out-the-screen/#high-performance-layout-patterns] ## Laying out the screen: High-Performance Layout Patterns (4/4) #### Advanced: Gameface Proprietary Display Modes For views where *every* direct child is absolutely positioned (pure HUD views, floating nameplate containers, tooltip layers), Gameface provides `display: simple` on the parent element. This bypasses Yoga’s layout solve entirely for that container, eliminating layout calculation cost on every frame. See Gameface CSS: Simple Layout & Opacity for the full guide. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/] ## Building Scalable & Responsive Game UIs A scalable UI is a UI that can dynamically scale up or down to fit bigger or smaller screens. A well-designed responsive interface ensures that components are not distorted or malformed from the scaling, and allows adjustments to fit the screen even if the aspect ratio changes. This guide explores the mechanics of scalable layouts in Gameface. We will cover the pitfalls of hardcoded pixels, how to leverage viewport units and REM scaling , and alternative approaches like calculating and applying dynamic scale factors based on a reference resolution. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#the-problem-with-hardcoded-pixels] ## Building Scalable & Responsive Game UIs: The Problem with Hardcoded Pixels When building a UI, it is tempting to measure and position elements using strict pixel (`px`) values based on a single target screen dimension. The screen size for which the UI was originally designed is known as the reference resolution . However, pixels are absolute units. If your reference resolution is 1080p (1920x1080), a hardcoded `300px` minimap will look perfectly sized. But when the game is rendered on a 4K screen (3840x2160), the screen has exactly twice the number of pixels in both width and height. Because the minimap remains strictly `300px`, it will appear physically half the size on the 4K screen, making it incredibly difficult for the player to read. **The 4K Pixel Trap:** If a UI element needs to retain a constant physical size despite the screen resolution , or if it needs to increase or decrease its size proportionally based on the screen size, you must abandon absolute units in favor of relative sizing . --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#viewport-units-for-layouts] ## Building Scalable & Responsive Game UIs: Viewport Units for Layouts The most direct way to scale layout containers proportionally is by using **Viewport Units**: vw (viewport width) and vh (viewport height). - `1vw` is equal to 1% of the total screen width. - `1vh` is equal to 1% of the total screen height. Because these units are intrinsically tied to the screen’s actual dimensions, an element sized with `vw` or `vh` will always occupy the exact same relative physical space on the screen, whether it is running on a 720p handheld or a 4K monitor. ```css /* This container will always take up exactly 30% of the screen's width and 100% of its height, regardless of the user's resolution. */ .inventory-panel { width: 30vw; height: 100vh; background: rgba(0, 0, 0, 0.8); } /* Margins and spacing can also use viewport units to maintain consistent relative spacing from the edge of the screen. */ .minimap { width: 15vw; height: 15vw; /* Using vw for both ensures the map stays a perfect square */ margin-top: 2vh; margin-right: 2vw; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#global-layout-scaling-with-rem-units] ## Building Scalable & Responsive Game UIs: Global Layout Scaling with REM Units (1/3) While viewport units (`vw` and `vh`) are excellent for massive layout blocks, using them for every single padding, margin, border, and font size can become tedious and hard to maintain. Instead, the most robust way to build a scalable UI is to author your internal component dimensions using rem units. The `rem` unit is a size unit used in CSS that is tied directly to the root (`html`) element’s font size. If you set the size of all UI elements using `rem` units, you can easily resize them globally by changing the font size of the HTML element. By scaling this single root value, the entire UI-text, buttons, margins, and containers-scales up or down in perfect unison. ```css /* If the root font-size is 10px, this button is 200px wide. If the root font-size changes to 20px, this button dynamically grows to 400px wide. */ .action-button { width: 20rem; height: 5rem; padding: 1rem; font-size: 1.5rem; } ``` To make this actually responsive to the screen, we need a way to automatically adjust that root font size based on the player’s resolution. There are two main ways to achieve this: dynamically via JavaScript , or statically via CSS . #### The Dynamic Scale Factor Method (JavaScript) The industry standard for game UI is to design the interface for a specific **reference resolution** (e.g., 1920x1080). A user interface is scaled using a scale factor, which is a numeric value that determines how the size of the UI element will be affected. Comparing the current resolution to the reference resolution gives the scale factor. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#global-layout-scaling-with-rem-units] ## Building Scalable & Responsive Game UIs: Global Layout Scaling with REM Units (2/3) When calculating the scale factor, the sides which are used determine the end result of the scaling. You can compare only the width, only the height, or both. For standard widescreen games, scaling based on the screen’s **height** is often preferred to ensure vertical UI panels don’t get cut off. Here is how you can use JavaScript to dynamically calculate this scale factor and apply it to the root element. ```javascript // Grab the root HTML element to apply our dynamic font-size const rootElement = document.getElementsByTagName('html')[0]; function resize() { // Get the current physical height of the screen const windowHeight = window.innerHeight; // Compare the current height to our reference height of 1080 // If the player is on a 2160p (4K) screen, the factor is 2.0 const scaleFactorY = windowHeight / 1080; // Multiply our base CSS design size (e.g., 16px) by the scale factor const fontSize = 16 * scaleFactorY; // Apply the newly calculated font size to the root element rootElement.style.fontSize = `${fontSize}px`; } // Run once on initialization to set the initial scale resize(); // Update the scale dynamically whenever the window resizes window.addEventListener('resize', resize); ``` **The Tradeoffs:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#global-layout-scaling-with-rem-units] ## Building Scalable & Responsive Game UIs: Global Layout Scaling with REM Units (3/3) - **Pros:** This approach gives you absolute precision. It also makes developer handoff incredibly easy: if your UI designer builds a screen in Figma at 1080p, you can translate a `24px` Figma value directly to `1.5rem` (assuming a 16px base) in your CSS without any complex mental math. - **Cons:** It requires a JavaScript execution and a layout recalculation every time the window resizes. #### The CSS-Only Method (vh Math) If you want to avoid the JavaScript bottleneck entirely, you can manually calculate the Viewport Height (vh) equivalent of your base pixel size and apply it directly to your CSS. Assuming our reference wireframe was designed at 1920x1080, and we want our base `1rem` to equal `16px` at that resolution, we calculate the viewport height percentage: `(16px / 1080px) * 100 = 1.4814vh`. Root font size applies to the whole project, so this rule belongs in a global stylesheet rather than a scoped one. In the Gameface UI boilerplate that is `src/views/global.scss`, which loads ahead of every view: ```scss html { font-size: 1.4814vh; } ``` With this single rule applied, an element with `width: 2rem` will render at exactly 32px on a 1080p screen, but will dynamically scale up on a 1440p or 4K screen, maintaining its relative proportion to the height of the window. **The Tradeoffs:** - **Pros:** Extremely fast and avoids JS execution overhead during window resizing. Excellent for rapid prototyping. - **Cons:** Lacks the explicit control of a JavaScript scale manager and can behave unpredictably on extreme ultrawide monitors without additional constraints. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#finding-the-balance] ## Building Scalable & Responsive Game UIs: Finding the Balance There is no “one-size-fits-all” solution when it comes to building a responsive game UI. All of the aforementioned approaches have their benefits depending on your UI’s specific needs. Using viewport units (`vh` and `vw`) is a fantastic way to ensure that your layout containers and margins scale proportionally to the screen size. However, relying solely on viewport units for every single UI element can become unwieldy and difficult to maintain, especially for typography and smaller components or when trying to match the design 1:1. If you are prototyping quickly and want an easily scalable and responsive layout, the **CSS-only `vh` method** is incredibly efficient. However, it can be somewhat vulnerable for a final production build when confronted with extreme edge cases, like super-ultrawide displays. The **Dynamic Scale Factor via JavaScript** method is highly consistent and provides precise control over how your UI scales. While it does come with a slight performance trade-off whenever the window gets resized, it is worth noting that in a compiled game environment, players rarely resize their windows mid-gameplay. Our general recommendation is to evaluate these trade-offs and find the balance that best fits your project’s technical requirements and production timeline. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#player-controlled-ui-scaling] ## Building Scalable & Responsive Game UIs: Player-Controlled UI Scaling (1/2) Beyond automatic resolution scaling, many players - particularly those with accessibility needs - rely on a **UI Scale** setting to increase the size of menus and HUDs. The technique is the same root-em approach, but driven by a player preference rather than a screen resolution. Expose a CSS custom property `--scale` on the root element, and calculate the root `font-size` from it: ```css :root { --scale: 1; font-size: calc(16px * var(--scale)); } ``` A scale of `1.5` enlarges the full UI by 50% - one property change, entire UI scales. #### Applying Scale from Game Settings ```js function applyUIScale(factor) { document.documentElement.style.setProperty('--scale', factor); } // Called when the player adjusts the "UI Scale" slider in settings engine.on('UIScaleChanged', (factor) => { applyUIScale(factor); }); // On UI load, restore saved scale preference const savedScale = engine.call('GetSavedUIScale') ?? 1; applyUIScale(savedScale); ``` Sensible default scale steps for a game are `0.75`, `1.0`, `1.25`, `1.5`, and `2.0`. Avoid allowing arbitrarily large values without testing your layout at those extremes. #### Named Scale Steps (Alternative) Instead of a float slider, named steps give you explicit control over which scale values your layout has been tested with: ```css :root { font-size: 14px; } /* small */ :root.scale-normal { font-size: 16px; } :root.scale-large { font-size: 20px; } :root.scale-xlarge { font-size: 24px; } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/building-responsive-game-ui/#player-controlled-ui-scaling] ## Building Scalable & Responsive Game UIs: Player-Controlled UI Scaling (2/2) ```js const SCALE_CLASSES = ['scale-small', 'scale-normal', 'scale-large', 'scale-xlarge']; function applyUIScaleClass(level) { SCALE_CLASSES.forEach(cls => document.documentElement.classList.remove(cls)); document.documentElement.classList.add(`scale-${level}`); } engine.on('UIScaleChanged', (level) => applyUIScaleClass(level)); ``` Named steps reduce the risk of untested layout breakage compared to continuous scaling. #### Testing Layout Integrity at Scale Extremes Changing the root font size can expose latent layout issues. Test explicitly at your defined scale extremes from the Inspector console: ```js document.documentElement.style.fontSize = '24px'; // Test at XL scale document.documentElement.style.fontSize = '12px'; // Test at minimum scale ``` Check for: text overflow in fixed-height containers, flex row items wrapping unexpectedly, icon-to-text misalignment where the icon size was set in `px` but the text is in `rem`, and scroll areas becoming unreachable because their parent grew beyond the viewport. #### Mixing px and rem Intentionally Not every measurement should scale. Border widths, box shadows, and fine outlines typically look better at a fixed pixel value regardless of scale: ```css .menu-button { font-size: 1rem; padding: 0.75rem 1.5rem; border: 1px solid rgba(255, 255, 255, 0.3); /* intentional px */ border-radius: 4px; /* intentional px */ } ``` Document these intentional `px` values with a comment so contributors don’t convert them unnecessarily. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/] ## DOM Size Management & Hiding Elements A large DOM tree taxes every part of Gameface’s rendering pipeline: layout calculation, style matching, data-binding synchronization, and draw call preparation. Four strategies address this at different levels. Hiding techniques trade resting overhead for toggle cost - picking the wrong one for a given element compounds that cost across every frame the element is invisible. Deferred rendering keeps heavy DOM branches out of the layout tree until the player actually needs them. Node pooling eliminates garbage collection spikes from high-frequency element creation. Update throttling keeps the layout tree quiet by batching DOM mutations to intervals the player cannot perceive. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#controlling-visibility-hiding-vs-removing] ## DOM Size Management & Hiding Elements: Controlling Visibility: Hiding vs. Removing (1/5) Every technique for hiding a UI element carries two costs: the overhead it imposes while the element is invisible, and the cost of making it visible again. These two costs trade against each other. Picking the right technique is a function of how often the element toggles and how expensive its resting overhead is. Technique | Resting Overhead | Toggle Cost `opacity: 0` / `visibility: hidden` | High (layout + data-binding) | Lowest (no reflow) `display: none` | Medium (no layout, no draw) | Medium (layout reflow on show) `remove()` / `data-bind-if` | None | Highest (DOM mutation + layout reflow) #### CSS Hiding: opacity and visibility `opacity: 0` makes an element invisible but leaves it fully active in the layout tree. The engine still runs layout calculations for it on every frame, still synchronizes its data bindings, and still processes it in the style-matching pass. Only paint commands are skipped. `visibility: hidden` behaves identically from a layout and binding perspective: the element occupies its box, participates in flex distribution, and keeps its data bindings alive. The advantage is toggle cost. Switching `opacity` from `0` to `1` triggers no layout reflow. The element was already in the tree; only its visibility state changes. The following shows a HUD widget that toggles frequently during gameplay, where the zero-reflow toggle cost justifies the resting overhead: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#controlling-visibility-hiding-vs-removing] ## DOM Size Management & Hiding Elements: Controlling Visibility: Hiding vs. Removing (2/5) ```tsx import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const ObjectiveTracker = () => { return ( Reach the extraction zone ); }; ``` **HTML:** ```html
Reach the extraction zone
``` ```css /* ✅ Fast toggle - element stays in the layout tree, no reflow on show */ .objective-tracker { opacity: 0; pointer-events: none; transition: opacity 0.2s ease-out; } .objective-tracker.is-visible { opacity: 1; pointer-events: auto; } ``` The resting overhead is the trade-off. An `opacity: 0` element with active data bindings still synchronizes all its bound properties on every frame. A complex panel kept permanently invisible but fully data-bound contributes layout cost and binding overhead for no visible output. #### Display None `display: none` detaches the element from the layout tree entirely. Yoga skips it during layout calculation. No draw commands are generated. The element still exists in the DOM and its data bindings stay registered, but the layout solve cost drops to zero. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#controlling-visibility-hiding-vs-removing] ## DOM Size Management & Hiding Elements: Controlling Visibility: Hiding vs. Removing (3/5) The toggle cost is the trade-off. When the engine transitions an element from `display: none` to any visible display value, it reintegrates the element into the layout tree and runs a full layout solve over the affected subtree. The following compares the two approaches on a pause menu that is hidden for most of a gameplay session: **SolidJS:** ```tsx import { createSignal } from 'solid-js'; import { Show } from 'solid-js'; import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const PauseMenu = () => { const [isOpen, setIsOpen] = createSignal(false); return ( Paused {/* option rows */} ); }; ``` **HTML:** ```html
Paused
``` ```css /* ❌ Pause menu hidden with opacity: 0 - layout computed for hundreds of nodes every frame */ .pause-menu { opacity: 0; pointer-events: none; } /* ✅ Pause menu hidden with display: none - Yoga skips the entire subtree */ .pause-menu { display: none; } .pause-menu.is-open { display: flex; /* Full layout reflow on open - paid once, not every frame */ } ``` --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#controlling-visibility-hiding-vs-removing] ## DOM Size Management & Hiding Elements: Controlling Visibility: Hiding vs. Removing (4/5) `display: none` suits elements that are hidden for large portions of a session: pause menus, inventory screens, character customization panels. The one-time reflow on open is acceptable when weighed against the frame-by-frame layout savings over the session. **Data Bindings Stay Active Under display: none:** `display: none` removes an element from the layout tree but does not unregister its data bindings. A pause menu with 30 bound properties still synchronizes all 30 on every frame while hidden. If a subtree has many active bindings and is hidden for long periods, combine `display: none` with a conditional `data-bind-if` on the outer wrapper to fully suspend binding overhead while the view is closed. #### Structural Removal: remove() and data-bind-if Fully removing a node from the DOM eliminates every form of resting overhead. The element is absent from the layout tree, the style-matching pass, and the data-binding system. Nothing computes for it while it is detached. The toggle cost is the highest of any option. Adding or removing a node from the DOM triggers a main-thread operation that must synchronize with the layout thread. When the node is re-added, the engine runs a full layout solve for the reattached subtree. Gameface’s `data-bind-if` attribute applies this mechanism through the data-binding system. An element with `data-bind-if` is physically mounted or unmounted from the DOM as the bound value changes. The following shows a full inventory screen that should only exist in the layout tree when the player has it open: **SolidJS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#controlling-visibility-hiding-vs-removing] ## DOM Size Management & Hiding Elements: Controlling Visibility: Hiding vs. Removing (5/5) ```tsx import Block from '@components/Layout/Block/Block'; import TextBlock from '@components/Basic/TextBlock/TextBlock'; const InventoryScreen = () => { return ( Inventory {/* item slots */} ); }; ``` **HTML:** ```html
Inventory
``` `data-bind-if` is the right choice for full-screen overlays, game-state-specific views (character select, post-match results), and any screen the player visits infrequently. The mount cost is paid once on open. Zero resting overhead is maintained for the entire time the view is closed. **Choosing the Right Hiding Technique:** `opacity: 0` and `visibility: hidden` suit elements that toggle multiple times per engagement: tooltips, damage flash overlays, notification banners. `display: none` suits elements hidden for minutes at a time where data bindings must stay registered. `data-bind-if` and `remove()` suit full screens and heavy subtrees that the player visits occasionally - their zero resting overhead outweighs the one-time mount cost at those usage frequencies. --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#deferred--partial-rendering] ## DOM Size Management & Hiding Elements: Deferred & Partial Rendering (1/4) A large DOM tree at startup has two costs: the time to parse and attach every node, and the first-frame layout solve over all of them. Both costs can be eliminated for content the player does not see at startup. #### Lazy Component Loading A skill tree, a full character loadout panel, or a crafting screen each contain hundreds or thousands of nodes. The engine creates their DOM nodes at startup, meaning the player pays the full creation and layout cost before ever opening those screens. JavaScript dynamic imports defer both costs: the component module and its DOM nodes are not created until the first time the player actually navigates to that screen. **SolidJS:** ```tsx import { lazy, Suspense, createSignal } from 'solid-js'; import Block from '@components/Layout/Block/Block'; // Lazy-loaded screens const SettingsPanel = lazy(() => import('./SettingsPanel')); const SkillTree = lazy(() => import('./SkillTree')); const App = () => { const [activeScreen, setActiveScreen] = createSignal<'settings' | 'skill-tree' | null>(null); return ( {activeScreen() === 'settings' && } {activeScreen() === 'skill-tree' && } ); }; ``` **Vanilla JS:** --- [SOURCE: https://guide.coherent-labs.com/layout-assets-and-styling/styling--scalability/dom-management/#deferred--partial-rendering] ## DOM Size Management & Hiding Elements: Deferred & Partial Rendering (2/4) ```js // ❌ Both modules load at startup - all DOM nodes created immediately, before needed import SettingsPanel from './settings-panel.js'; import SkillTree from './skill-tree.js'; // ✅ Each module and its DOM nodes are created only when the player opens that screen async function openSettings() { const { default: SettingsPanel } = await import('./settings-panel.js'); const panel = new SettingsPanel(); panel.mount(document.getElementById('overlay-root')); } async function openSkillTree() { const { default: SkillTree } = await import('./skill-tree.js'); const tree = new SkillTree(); tree.mount(document.getElementById('overlay-root')); } ``` Structure components so they can be mounted and unmounted cleanly without rebuilding their internal state from scratch on every open. Caching the component instance after its first creation eliminates the module-load cost on subsequent opens. #### The template Element The `