6 Commits

40 changed files with 1329 additions and 504 deletions

View File

@@ -6,8 +6,7 @@ Config files use the TOML format. The following config files drive game paramete
- **world.toml** — world dimensions, region widths, expansion amounts, building refund percentage, building deconstruction time, wave timing, boss wave timing, belt speed, starting building blocks, departure interval, ship orbit factor, rally orbit radius, scrap-per-threat conversion, combat target-selection parameters (target score formula, overclaim penalty formula, target hysteresis), artifact chance formula, artifact win count, view pan speeds (slow and fast horizontal pan speed and pan ramp band width), an optional building blocks tooltip string (shown as the header bar's building blocks stock hover tooltip, REQ-UI-BLOCKS-TOOLTIP; omitted when unset), and an optional artifact tooltip string (shown as the header bar's artifact count hover tooltip, REQ-UI-ARTIFACTS-TOOLTIP; omitted when unset).
- **buildings.toml** — building block cost and construction time per building type, plus an optional tooltip description string per building type (shown as the build button's hover tooltip, REQ-UI-BUILD-TOOLTIP; omitted when unset). Whether a building type is available from game start or must be unlocked during play is not defined here but in **unlocks.toml** (REQ-LOCK-EXPLICIT): a building type granted by an unlock group starts locked and is hidden from the build menu until its group is awarded (REQ-LOCK-BUILDING).
- **recipes.toml** — crafting recipes: inputs, outputs, quantities, durations, and reprocessing plant probabilities. Assembler recipe entries may optionally define `unlocked_at_start` (boolean, default false): when true the recipe is available from game start regardless of the implicit item graph — used for base recipes that no schematic's materials reach (such as building blocks; see REQ-LOCK-IMPLICIT). Which assembler recipes must instead be awarded during play (explicitly gated) is defined in **unlocks.toml**, not here (REQ-LOCK-EXPLICIT); every remaining assembler recipe is implicitly unlocked through the item graph (REQ-LOCK-IMPLICIT). Any recipe entry may optionally define `icon` (string): the id of an item whose icon represents the recipe in the recipe-selection dialog (REQ-UI-RECIPE-ICON); when omitted, the recipe's first output item is used.
- **ships.toml** — per schematic: a human-readable display name (used in the UI), hull stats (HP, max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, max rotation speed) as plain values, required build materials, a layout grid defining the ship's module slots, and a `default_modules` list used for enemy wave ships (see REQ-WAV-DEFAULT-MODULES). Whether a ship schematic is available from game start or must be unlocked during play is defined in **unlocks.toml** (REQ-LOCK-EXPLICIT), not here.
- **recipes.toml** — crafting recipes: inputs, outputs, quantities, durations, and reprocessing plant probabilities. Assembler recipe entries may optionally define `unlocked_at_start` (boolean, default false): when true the recipe is available from game start regardless of the implicit item graph — used for base recipes that no schematic's materials reach (such as building blocks; see REQ-LOCK-IMPLICIT). Which assembler recipes must instead be awarded during play (explicitly gated) is defined in **unlocks.toml**, not here (REQ-LOCK-EXPLICIT); every remaining assembler recipe is implicitly unlocked through the item graph (REQ-LOCK-IMPLICIT).- **ships.toml** — per schematic: a human-readable display name (used in the UI), hull stats (HP, max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, max rotation speed) as plain values, required build materials, a layout grid defining the ship's module slots, and a `default_modules` list used for enemy wave ships (see REQ-WAV-DEFAULT-MODULES). Whether a ship schematic is available from game start or must be unlocked during play is defined in **unlocks.toml** (REQ-LOCK-EXPLICIT), not here.
- **modules.toml** — per module type: id, surface mask, materials list, production time, fill color, glyph, an optional tooltip description string (shown as the module selection button's hover tooltip, REQ-MOD-UI-MODULE-TOOLTIP; omitted when unset), and an optional capability section and/or stat modifier formulas. Whether a module schematic is available from game start or must be unlocked during play is defined in **unlocks.toml** (REQ-LOCK-EXPLICIT), not here. A module with a capability section (`[module.weapon]`, `[module.salvage]`, or `[module.repair]`) containing base stat formulas is a **capability module** that grants the ship a weapon, salvage bay, or repair tool per instance (see REQ-MOD-CONFIG for the full list of formulas per capability type). A module with only `added_*`/`multiplied_*` formulas is a **passive module** that modifies stats on the ship or on capability module instances (see REQ-MOD-STAT-CALC).
- **unlocks.toml** — unlock groups: each `[[unlock]]` entry names a group of ship schematics, module schematics, building types, and/or assembler recipes that are awarded together from a single defence station drop (see Unlock Group Format, REQ-LOCK-EXPLICIT, REQ-DEF-SCHEMATIC-DROP). Anything not granted by any unlock group is available from game start.
- **stations.toml** — HP, damage, range, fire rate, and scrap drop for player and enemy defence stations, defined as formulas of station level.
@@ -306,13 +305,13 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
### Module UI
- REQ-MOD-UI-PREVIEW: For a selected shipyard (operational building or construction site), the selection panel always shows a small non-interactive **ship layout preview** widget below the schematic selection button (REQ-UI-SELECT-BUTTON) and a "Configure" button below the preview. Both are **disabled while no schematic is selected**, and enabled once one is; the preview then shows an empty placeholder in place of a layout grid. When a schematic is selected, the preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` with the module's `glyph` character. For non-shipyard buildings, neither the preview nor the "Configure" button is shown.
- REQ-MOD-UI-DIALOG: Clicking the "Configure" button opens the **layout configuration dialog** as a modal. While the dialog is open, the game is paused (speed set to 0×). On close, the game speed is restored to what it was before the dialog was opened.
- REQ-MOD-UI-PREVIEW: For a selected shipyard (operational building or construction site), the selection panel always shows a small non-interactive **ship layout preview** widget below the schematic selection button (REQ-UI-SELECT-BUTTON) and a "Configure" button below the preview. Both are **disabled while no schematic is selected**, and enabled once one is; the preview then shows an empty placeholder in place of a layout grid. When a schematic is selected, the preview renders the ship's layout grid at a reduced scale: buildable cells without a module are shown as white, non-buildable cells are shown as black, and cells occupied by a module are shown in that module's `fill_color` alone — no glyph, which at this scale would not be legible anyway; the layout configuration dialog's full-scale grid is where a module is identified by its glyph (REQ-MOD-UI-DIALOG). For non-shipyard buildings, neither the preview nor the "Configure" button is shown.
- REQ-MOD-UI-DIALOG: Clicking the "Configure" button opens the **layout configuration dialog** as a modal, centered on the selection panel it was opened from (REQ-UI-PANEL-MODAL). While the dialog is open, the game is paused (speed set to 0×). On close, the game speed is restored to what it was before the dialog was opened.
The dialog contains:
- **Top**: The ship's layout grid rendered at full scale. Buildable cells are white; non-buildable cells are black. Placed modules are rendered with their `fill_color` and `glyph`. The ghost of the currently selected module is shown at the cursor position when in placement mode.
- **Left** (below the grid): The ship stats panel (see REQ-MOD-UI-STATS-PANEL).
- **Center** (below the grid): A grid of module selection buttons (one per **unlocked** module type; see REQ-DEF-SCHEMATIC-DROP) plus a "Remove" button. Each module button shows the module id and its glyph.
- **Left** (below the grid): The ship stats panel (see REQ-MOD-UI-STATS-PANEL), and beneath it the layout's **build cost**, so the price of a configuration is visible while it is being assembled rather than only once it has been confirmed: the total materials required for the ship — the union of the schematic's base materials and those of every placed module, summed per item type (REQ-MOD-MATERIALS) — drawn as item icons on their colored squares with their amounts (REQ-UI-ITEM-ICON), and beside them the total production time (REQ-MOD-PRODUCTION-TIME). Both update in real time as modules are placed and removed. The cost sits beside the stats panel rather than within it because a build cost belongs to a ship being configured: the same panel serves an existing ship (REQ-UI-SHIP-STATS-PANEL) and the balancing tool, neither of which costs anything.
- **Center** (below the grid): A grid of module selection buttons (one per **unlocked** module type; see REQ-DEF-SCHEMATIC-DROP) plus a "Remove" button. A module button shows the module's name — its `id` under the usual display convention — on its first line, and beneath it what the module costs: the icons of its `materials` items on their colored squares with their amounts (REQ-UI-ITEM-ICON) and the production time it adds, as `+<n> s` (REQ-MOD-MATERIALS, REQ-MOD-PRODUCTION-TIME). This is the same form a recipe option button uses to state what it makes (REQ-UI-SELECT-OPTIONS), and it puts the price of a module in front of the player before it is placed. The "Remove" button costs nothing and shows its caption alone.
- **Right** (below the grid): The layout blueprint panel (see REQ-MOD-UI-BLUEPRINT-PANEL through REQ-MOD-UI-BLUEPRINT-FILE-LOAD).
- **Bottom**: A "Confirm" button and a "Cancel" button. Cancel discards all changes made in this dialog session and closes the dialog. Confirm applies the changes: the shipyard's configured layout is updated, the required materials and cycle time displayed in the selection panel are recalculated, and the ship layout preview is refreshed.
@@ -372,9 +371,9 @@ Any ship, module, building, or assembler recipe id that appears in no unlock gro
Each option in the dialog displays the unlock group's display name — derived from its `id` (same display convention as building, module, and recipe ids) — and the list of items it would grant: its ship, module, building, and assembler-recipe ids (each shown with the same display convention as its respective selection dialog). The artifact option (if present) is displayed as a distinct entry with the name "Artifact".
Each option additionally displays a vertical list of recipe names labeled "Unlocks recipes:", showing which miner and assembler recipes would newly become implicitly unlocked (REQ-LOCK-IMPLICIT) if this option were selected — specifically, the miner recipes and implicitly-gated assembler recipes that are not currently implicitly unlocked but would become so after applying this option's effect. To compute this, all `materials` of the group's granted ship and module schematics are added to the base set per REQ-LOCK-IMPLICIT step 1a, and the output items of the group's granted assembler recipes are added per step 1b, before recomputation.
Each option additionally displays a vertical list of recipe lines labeled "Unlocks recipes:", showing which miner and assembler recipes would newly become implicitly unlocked (REQ-LOCK-IMPLICIT) if this option were selected — specifically, the miner recipes and implicitly-gated assembler recipes that are not currently implicitly unlocked but would become so after applying this option's effect. To compute this, all `materials` of the group's granted ship and module schematics are added to the base set per REQ-LOCK-IMPLICIT step 1a, and the output items of the group's granted assembler recipes are added per step 1b, before recomputation.
Each recipe is listed by its `id` (using the same display convention as the assembler recipe-selection dialog), sorted alphabetically. Hovering a recipe in this list displays the recipe info tooltip described for a recipe in REQ-UI-SELECT-TOOLTIP (the recipe name; the name and quantity of each input item; the completion time; and the name and quantity of the produced output item). If no recipes would be newly unlocked, the list shows "None".
Each recipe is shown as a **recipe line** of the same two-row card the item production tooltip uses (REQ-UI-ITEM-TOOLTIP): the icon of the building that runs it (REQ-UI-BUILD-ICON) and the recipe's name — by its `id`, using the same display convention as the assembler recipe-selection dialog — on the first row, and the recipe drawn as the recipe summary draws it (REQ-UI-RECIPE-SUMMARY) on the second. The lines are sorted alphabetically by recipe name. The line says everything there is to say about the recipe, so nothing in this list carries a tooltip, as in the selection dialog (REQ-UI-SELECT-OPTIONS). If no recipes would be newly unlocked, the list shows "None".
The player selects one option by clicking it. If the player selects the artifact option, the player's artifact count is incremented by 1 (REQ-WIN-ARTIFACT-COUNT) and the dialog closes; no unlock is applied. Otherwise the selected unlock group is awarded and the dialog closes: every ship, module, building, and assembler recipe the group grants becomes unlocked at once — ship schematics unlock the corresponding shipyard selection; module schematics unlock the module type for placement in the layout configuration dialog (REQ-MOD-UI-DIALOG); building types become available in the build menu (REQ-LOCK-BUILDING); assembler recipes become available in the assembler recipe-selection dialog (subject to REQ-LOCK-UI-RECIPE). The unlock group is removed from the pool permanently (REQ-LOCK-EXPLICIT), and the implicit unlock set is recomputed (REQ-LOCK-IMPLICIT).
@@ -472,6 +471,12 @@ The screen is a single column: a header bar across the top and the game world vi
- **Scope: the current selection.** The desired position lasts as long as the selection it was set in — across the panel's own resizing, view resizes, and view scrolling (REQ-UI-SELECTION-PANEL), and across the selection being expanded or reduced (REQ-UI-MULTI-SELECT). Starting a **new** selection discards it: the panel is placed anew against the new anchor rectangle (REQ-UI-SELECTION-PANEL), and the player drags it again if they want it elsewhere.
- **Input.** The drag consumes its mouse events like every other event over the panel (REQ-UI-SELECTION-PANEL): the press, the movement, and the release never reach the game world, so dragging the header neither box-selects (REQ-UI-MULTI-SELECT) nor places belts (REQ-BLD-BELT-DRAG). The drag continues while the cursor moves outside the panel or outside the view, and ends when the left button is released, wherever that happens. A press and release on the header without movement moves nothing and has no other effect.
- **Presentation only.** Moving the panel is not a player command: it never enters the replay stream and has no effect on the simulation, consistent with the controls panel's collapsed state (REQ-UI-CONTROLS-PANEL). The desired position is not saved to disk.
- REQ-UI-PANEL-MODAL: **A modal opened from the selection panel opens on the panel.** A modal the player opens from a control inside the selection panel is placed **centered on the panel's current rectangle** rather than centered on the game window, so it appears where the player is already looking and under the cursor that just clicked the control. This is the same reason the panel itself is placed beside the selection instead of at a fixed corner (REQ-UI-SELECTION-PANEL): a modal centered on the window sends the cursor back across the view and then back again. Two modals are opened from the panel — the recipe/schematic selection dialog (REQ-UI-SELECT-BUTTON), from the selection button; and the layout configuration dialog (REQ-MOD-UI-DIALOG), both from the "Configure" button (REQ-MOD-UI-PREVIEW) and when it opens automatically after a schematic change (REQ-MOD-UI-AUTO-DIALOG).
- **The panel's rectangle as it currently stands.** The modal is centered on where the panel actually is when the modal opens: the position resolved from the anchor rectangle (REQ-UI-SELECTION-PANEL) or, once the player has dragged the panel, the position they dragged it to (REQ-UI-SELECTION-PANEL-DRAG). The panel is always shown when one of these modals opens, since the modal is opened from a control within it (REQ-UI-EMPTY-SELECTION).
- **Kept inside the game window.** Should the modal, centered that way, extend past an edge of the game window, it is pushed back inside; its size is never changed to make it fit. A modal larger than the window in a dimension is instead aligned with the window's top or left edge in that dimension, so the part read first stays visible.
- **Placement is all that changes.** The modal is modal as before, pauses the game and restores the speed on close as before (REQ-UI-SELECT-BUTTON, REQ-MOD-UI-DIALOG), shows the dim over the entire window including the panel it sits on (REQ-UI-MODAL-DIM), and is dismissed the same way. That it covers the panel costs nothing: while it is open the panel is dimmed and takes no input anyway.
- **Only these modals.** Every other modal is placed as before, centered on the game window: the escape menu (REQ-UI-GAME-MENU), the blueprint save and selection dialogs (REQ-UI-BLUEPRINT-CREATE, REQ-UI-BLUEPRINT-DIALOG), and the schematic choice dialog (REQ-DEF-SCHEMATIC-DROP), none of which is opened from the panel. So is a modal opened from another modal rather than from the panel — the Create Blueprint name dialog within the layout configuration dialog (REQ-MOD-UI-BLUEPRINT-CREATE) — which is placed against the modal that opened it.
- **Presentation only.** The placement is computed once, when the modal opens, and is not revisited while it is open; the panel cannot move meanwhile, being behind the modal and receiving no input. It is not a player command, never enters the replay stream, and has no effect on the simulation.
- REQ-UI-MODAL-DIM: While a modal dialog, menu, or full-screen state screen is open on top of the game, a transparent black overlay (a dim/scrim) is drawn over the **entire game window** — the header bar, the game world view, and the widgets floating over it (the build button bar, REQ-UI-BUILD-BAR, the selection panel, REQ-UI-SELECTION-PANEL, and the controls panel, REQ-UI-CONTROLS-PANEL) — behind that modal, so the game reads as inactive while the modal holds focus. The overlay is shown for every modal that auto-pauses the simulation — the escape menu (REQ-UI-GAME-MENU), the recipe/schematic selection dialog (REQ-UI-SELECT-BUTTON), the layout configuration dialog (REQ-MOD-UI-DIALOG), the schematic choice dialog (REQ-DEF-SCHEMATIC-DROP), the blueprint save dialog (REQ-UI-BLUEPRINT-CREATE), and the blueprint selection dialog (REQ-UI-BLUEPRINT-DIALOG) — as well as the game-over screen (REQ-HQ-GAME-OVER) and the win screen (REQ-WIN-SCREEN), which end rather than pause the game. When modals are nested (for example the Create Blueprint name dialog (REQ-MOD-UI-BLUEPRINT-CREATE) opened from the layout configuration dialog), only a single dim is shown over the game window; nested modals do not stack additional overlays. The same applies when one modal hands directly off to another — the blueprint save dialog opening the blueprint selection dialog on confirm (REQ-UI-BLUEPRINT-CREATE): the dim persists across the handoff rather than flickering off and back on, and the simulation is not resumed in between. The dim color and opacity are read from `visuals.toml [overlays]` (a semi-transparent black modal-dim color), consistent with the other overlay colors. The overlay is presentation-only and has no effect on the simulation.
### Game World
@@ -484,7 +489,7 @@ The screen is a single column: a header bar across the top and the game world vi
Because the contest-zone boundaries shift as the scrollable area grows with each push (REQ-GW-PUSH-EXPAND, REQ-GW-SCROLL-LIMIT), the ramp bands are recomputed from the current contest-zone boundaries. This is a presentation-only concern and does not affect the simulation, consistent with REQ-UI-NO-ZOOM.
- REQ-UI-WORLD-ICON: In the game world, a building is drawn with an icon's glyph symbol centered on its footprint, in place of the letter identity glyph. The icon is an SVG loaded from `data/icons/buildings/`; only the icon's glyph is drawn in the world — in a contrasting ink (white over dark fills, dark over light fills) so it stays legible — and its colored chip background is omitted, because the footprint is already filled with the building's `visuals.toml` fill color. This applies to the production buildings (Miner, Smelter, Assembler, Reprocessing Plant, Shipyard, Salvage Bay), the HQ, and the player and enemy defence stations, wherever the identity label appears: operational buildings, construction sites (REQ-UI-CONSTRUCTION-PROGRESS), and the builder-mode and blueprint-placement ghosts. **Belts, splitters, and tunnels are excluded** — they keep their existing tile rendering so their orientation and flow stay readable (a centered icon would obscure direction). Their build-menu buttons still use icons (REQ-UI-BUILD-ICON); in particular the shared Tunnel button's `tunnel_entry.svg` is a build-button icon only, not a world icon. The directional output-port glyphs (REQ-UI-PORT-GLYPH, REQ-UI-PORT-TARGET-GLYPH) are a separate indicator and are unaffected. A building or station with no icon file falls back to its `visuals.toml` text glyph; a type with neither icon nor glyph shows no identity label. A missing icon is not an error, consistent with REQ-UI-BUILD-ICON.
- REQ-UI-ITEM-ICON: In the game world, an item is drawn as its `visuals.toml` colored square (`fill` + `outline`, the square of REQ-GW-TILE-SIZE) carrying its **item icon** on top. The square is drawn for every item, with or without an icon: it is what gives the item contrast against the tile beneath it, and its outline is what separates neighbouring items where they overlap on a belt. The icon is a self-contained, full-color SVG (rendered as-is, unlike the glyph-only building icons of REQ-UI-WORLD-ICON), loaded at runtime from `data/icons/items/` — a sibling of the config directory, read the same way as the building icons (REQ-UI-BUILD-ICON) — one file per item type named after the item's id (e.g. `iron_ore.svg`). The square fills the item's half-tile rect, keeping the size, spacing, and draw-order rules of REQ-GW-TILE-SIZE; the icon is drawn **inset** within that rect so a frame of the square's color stays visible all around it — required because each icon's viewBox is cropped tight to its artwork, so an icon drawn at the full rect would cover the square entirely. This applies wherever an item is drawn: on belts, splitters, and tunnel ends, and while emerging from or sinking into a building port (REQ-MAT-OUTPUT-EMERGE, REQ-MAT-INPUT-INTAKE). An item type with no icon file shows the colored square alone; a missing icon is not an error, consistent with REQ-UI-BUILD-ICON. The colored square is a game-world treatment only: the item chips and selection dialogs of the UI panels (REQ-UI-SINGLE-SELECTION, REQ-UI-SELECT-BUTTON) show the icon without it. For performance, each item icon is rasterized to a pixmap cached per target pixel size — re-rasterized only when the tile pixel size changes (e.g. on view resize) — rather than re-rendered from vector every frame.
- REQ-UI-ITEM-ICON: In the game world, an item is drawn as its `visuals.toml` colored square (`fill` + `outline`, the square of REQ-GW-TILE-SIZE) carrying its **item icon** on top. The square is drawn for every item, with or without an icon: it is what gives the item contrast against the tile beneath it, and its outline is what separates neighbouring items where they overlap on a belt. The icon is a self-contained, full-color SVG (rendered as-is, unlike the glyph-only building icons of REQ-UI-WORLD-ICON), loaded at runtime from `data/icons/items/` — a sibling of the config directory, read the same way as the building icons (REQ-UI-BUILD-ICON) — one file per item type named after the item's id (e.g. `iron_ore.svg`). The square fills the item's half-tile rect, keeping the size, spacing, and draw-order rules of REQ-GW-TILE-SIZE; the icon is drawn **inset** within that rect so a frame of the square's color stays visible all around it — required because each icon's viewBox is cropped tight to its artwork, so an icon drawn at the full rect would cover the square entirely. This applies wherever an item is drawn: on belts, splitters, and tunnel ends, and while emerging from or sinking into a building port (REQ-MAT-OUTPUT-EMERGE, REQ-MAT-INPUT-INTAKE). An item type with no icon file shows the colored square alone; a missing icon is not an error, consistent with REQ-UI-BUILD-ICON. **The colored square travels with the icon into the UI.** Wherever the UI displays an item *as an item* — the selection panel's item chips (REQ-UI-SINGLE-SELECTION, REQ-UI-HQ-PANEL), the recipe summary's input and output icons (REQ-UI-RECIPE-SUMMARY), and those same icons wherever a recipe is drawn in that form: on the selection dialog's option buttons (REQ-UI-SELECT-OPTIONS), in the item production tooltip (REQ-UI-ITEM-TOOLTIP), and in the unlock-choice dialog's recipe lines (REQ-DEF-SCHEMATIC-DROP) — the icon is drawn on that same square, by the same rules: the item's `fill` and `outline` from `visuals.toml`, the icon inset within the square so a frame of the square's color stays visible all around it, and the square alone when the item has no icon file. The square fills the rect the display allots to the icon, as it fills the half-tile rect in the world. One item therefore reads the same in a panel as it does on a belt. The one exception is the inline `building_block` icon that stands in for the word `Blocks` beside a number (REQ-UI-BLOCKS-ICON, REQ-UI-EXPAND-BUTTON, REQ-UI-BUILD-COST, REQ-UI-MULTI-SELECTION, REQ-UI-BLUEPRINT-CARD): there the icon is a decoration on a line of text rather than an item display, and it is drawn bare, without the square. For performance, each item icon is rasterized to a pixmap cached per target pixel size — re-rasterized only when the tile pixel size changes (e.g. on view resize) — rather than re-rendered from vector every frame.
- REQ-UI-CONSTRUCTION-PROGRESS: Construction sites display the building's identity symbol centered on the footprint (same as an operational building) — its icon glyph, or the text glyph as a fallback (REQ-UI-WORLD-ICON). Below the symbol — or centered on the footprint if the building has neither an icon nor a glyph — a construction progress percentage is shown (integer, e.g. `42%`), increasing from 0% to 100% as construction completes.
- REQ-UI-PORT-GLYPH: Every output port of every building is indicated by a directional glyph drawn on the port's tile. The glyph is a `>` rotated to face the port's exit direction (`>` for East, `^` for North, `<` for West, `v` for South). It is drawn at the midpoint between the tile center and the tile edge that the port exits through (i.e. halfway from center toward the exit edge). The indicator is rendered for all building states: operational buildings, construction sites, and the builder-mode ghost. Buildings with multiple output ports (e.g. splitters) show one indicator per port.
- REQ-UI-PORT-TARGET-GLYPH: While in builder mode (REQ-BLD-BUILDER-MODE), the builder-mode ghost additionally shows, for each of the building's output ports, a directional glyph drawn centered in the port's **target cell** — the cell immediately outside the footprint that the port pushes into, i.e. the cell the surface-mask output-port indicator occupies (see Surface Mask Format). As in REQ-UI-PORT-GLYPH the glyph is a `>` rotated to face the port's exit direction (`>` East, `^` North, `<` West, `v` South), previewing where the port's output will go before placement. This is in addition to the on-tile port glyph of REQ-UI-PORT-GLYPH, and — unlike that indicator — is shown only for the builder-mode ghost, not for operational buildings, construction sites, or the blueprint-placement ghost (REQ-UI-BLUEPRINT-PLACE). A building with multiple output ports (e.g. a splitter) shows one target-cell glyph per port. The target-cell glyph is drawn larger than the on-tile port glyph so it stands out as the flow-direction preview. Exceptions: the Tunnel Entry shows no target-cell glyph, because it receives items (which may arrive from any of its non-mouth edges, REQ-BLD-TUNNEL-ENTRY) rather than emitting into a single adjacent cell; the Shipyard shows none either, because its output port is a ship-spawn point (REQ-SHP-SPAWN-PLAYER) rather than a belt-item output (REQ-MAT-OUTPUT-EMERGE).
@@ -574,7 +579,7 @@ The panel shows exactly one **content** at a time, picked from the catalog in RE
- **Debris** — several pieces of debris and nothing else. Their remaining scrap sums into one value (REQ-UI-DEBRIS-PANEL).
Every other multi-selection falls back to the count summary. In particular a selection mixing a splitter with belts does not aggregate (a splitter carries per-object output filters, which have no aggregate), and neither do several production buildings of one type (per-building buffers and cycle progress have no aggregate).
- REQ-UI-SINGLE-SELECTION: When one building is selected, the panel shows its symbol and name in the header (REQ-UI-SELECTION-CARD), its current recipe or schematic selection (REQ-UI-SELECT-BUTTON) and recipe summary (REQ-UI-RECIPE-SUMMARY) in the configuration group, and its input and output buffer contents in the runtime group. Each buffered item is shown as an **item chip** bearing that item's icon (REQ-UI-ITEM-ICON) and its current count:
- REQ-UI-SINGLE-SELECTION: When one building is selected, the panel shows its symbol and name in the header (REQ-UI-SELECTION-CARD), its current recipe or schematic selection (REQ-UI-SELECT-BUTTON) and recipe summary (REQ-UI-RECIPE-SUMMARY) in the configuration group, and its input and output buffer contents in the runtime group. Each buffered item is shown as an **item chip** bearing that item's icon on its colored square (REQ-UI-ITEM-ICON) and its current count, and hovering a chip shows that item's production tooltip (REQ-UI-ITEM-TOOLTIP):
- an **input** chip shows the per-cycle amount below the count (the items consumed per run, e.g. `/ 2 per cycle`), or the count alone when the building has no selected recipe or schematic to give one;
- an **output** chip shows the count against the output buffer's capacity as `a / b` (REQ-MAT-OUTPUT-BUFFER), with the item's name below.
@@ -583,18 +588,27 @@ The panel shows exactly one **content** at a time, picked from the catalog in RE
**Only unlocked items are listed.** A building's buffers may carry entries for items the player cannot make yet — an auto-recipe building's buffers are sized over *every* recipe of its type (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING), including recipes that are still locked. Those entries are left out of both sections, consistent with the rest of the UI hiding what is not unlocked yet (REQ-LOCK-UI-RECIPE, REQ-LOCK-UI-SPLITTER), so a Smelter shows the ores it can actually smelt rather than every ore in the game.
**An idle auto-recipe building still shows what it handles.** Having no selected recipe (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING), it would otherwise show empty sections whenever it happens to be between cycles. Its input and output sections instead list the unlocked items of every recipe of its type — the same union its buffers were sized over — with a count and no per-cycle denominator, since no one recipe is in force. While a cycle is running, that cycle's recipe supplies the denominators as for any other building.
- REQ-UI-RECIPE-SUMMARY: Below the recipe/schematic selection control, a building running a recipe or schematic shows a one-line **recipe summary**: each input item's icon with its per-cycle amount, an arrow, each output item's icon with its per-cycle amount, and the cycle time in seconds. It restates what the building will do without opening the selection dialog, and it is the panel's only display of the cycle time. For a Shipyard the summary is built from the schematic's materials and production time including the placed modules' contributions (REQ-BLD-SHIPYARD, REQ-MOD-STAT-CALC), matching the buffers beneath it. Auto-recipe buildings (Smelter, Reprocessing Plant — REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) have no player-selected recipe and so show no selection control; they show the summary of the recipe currently in production and, while between cycles, of the one they ran last. They keep it rather than dropping it, because a summary that came and went with each cycle would resize the card in step with the building's status (REQ-UI-SELECTION-STATUS), which is the one thing the panel must not do while the player is reading it (REQ-UI-SELECTION-PANEL). Such a building shows no summary only until it has run its first cycle. A building with no recipe or schematic selected shows no summary.
- REQ-UI-RECIPE-SUMMARY: Below the recipe/schematic selection control, a building running a recipe or schematic shows a one-line **recipe summary**: each input item's icon on its colored square (REQ-UI-ITEM-ICON) with its per-cycle amount and the inputs separated by `+`, an arrow, each output item's icon on its colored square with its per-cycle amount, and the cycle time in seconds. It restates what the building will do without opening the selection dialog, and it is the panel's only display of the cycle time. For a Shipyard the summary is built from the schematic's materials and production time including the placed modules' contributions (REQ-BLD-SHIPYARD, REQ-MOD-STAT-CALC), matching the buffers beneath it. Auto-recipe buildings (Smelter, Reprocessing Plant — REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) have no player-selected recipe and so show no selection control; they show the summary of the recipe currently in production and, while between cycles, of the one they ran last. They keep it rather than dropping it, because a summary that came and went with each cycle would resize the card in step with the building's status (REQ-UI-SELECTION-STATUS), which is the one thing the panel must not do while the player is reading it (REQ-UI-SELECTION-PANEL). Such a building shows no summary only until it has run its first cycle. A building with no recipe or schematic selected shows no summary.
- REQ-UI-PRODUCTION-PROGRESS: For buildings that produce items or ships (miner, smelter, assembler, reprocessing plant, shipyard), the panel's runtime group shows a captioned **production section** between the input and output buffer sections (REQ-UI-SINGLE-SELECTION): a horizontal progress bar filled to the completion of the active production cycle, with that completion beside the caption as an integer percentage (e.g. `72%`), or the text `idle` in place of the percentage and an empty bar when no production cycle is active. The cycle time is shown in the recipe summary (REQ-UI-RECIPE-SUMMARY) rather than repeated here. When no recipe or schematic is selected, the production section is not shown at all.
- REQ-UI-MULTI-SELECT: The player selects multiple objects by box-drag or by Ctrl+clicking individual objects to add or remove them from the selection. Multi-select operates within a single category (REQ-UI-SELECTION-CATEGORIES). A box-drag that covers at least one building selects buildings (any field objects within the box are ignored — buildings win); a box-drag that covers no building but does cover ships, defence stations, or debris selects all of those field objects together (REQ-UI-ENTITY-CLICK-SELECT, REQ-UI-DEBRIS-MULTI-SELECT).
- REQ-UI-MULTI-SELECTION: When multiple buildings are selected and the selection does not aggregate (REQ-UI-SELECTION-AGGREGATE), the panel shows a count summary. Its header names the size of the selection as `<n> buildings` in place of an object name, and carries no symbol and nothing in its right slot. Below it is one row per selected building type — the type's symbol, its name, and the number selected as `x<count>` — one type per row, and no per-building detail. A final row shows the **total building block cost** of the selection, captioned `Total cost` with the value followed by the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON): the sum of each selected building's placement cost (`buildings.toml [[building]].cost`, per REQ-BLD-COST), counting only player-placeable buildings (buildings with a button in the build button bar); non-player-placeable buildings (the HQ and defence stations) are excluded from the total, consistent with the blueprint total (REQ-UI-BLUEPRINT-CARD). Construction sites count at their building type's full placement cost regardless of construction progress.
- REQ-UI-CONFIG-INLINE: Recipe and schematic configuration for a selected building is shown within this panel, in its configuration group (REQ-UI-SELECTION-CARD). Recipe selection (miner, assembler) and schematic selection (shipyard) use the selection button and dialog (REQ-UI-SELECT-BUTTON) rather than an inline control. For shipyards, the panel additionally shows the ship layout preview and "Configure" button below the schematic selection button (REQ-MOD-UI-PREVIEW).
- REQ-UI-SELECT-BUTTON: **Recipe and schematic selection control.** Recipe selection (Miner ore type, Assembler recipe) and schematic selection (Shipyard) are each presented in the selection panel as a single **selection button** whose caption is the name of the currently selected recipe or schematic, or a placeholder ("Select recipe" / "Select schematic") when none is selected. Clicking the button opens a modal **selection dialog** that pauses the game (speed set to 0×; on close, the speed is restored to what it was before the dialog was opened). The dialog contains a grid of option buttons, one per selectable option — only options that are currently unlocked are shown (REQ-LOCK-UI-RECIPE for recipes, REQ-LOCK-UI-SCHEMATIC for schematics). Hovering an option button shows the selection info tooltip (REQ-UI-SELECT-TOOLTIP). Clicking an option button selects that recipe/schematic, closes the dialog, and updates the selection button's caption in the selection panel. The dialog can be dismissed without changing the current selection (e.g. closing it without clicking an option). Selecting a new recipe or schematic has the same effects as before (REQ-MAT-INPUT-BUFFER, REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD).
- REQ-UI-SELECT-TOOLTIP: **Selection info tooltip.** Hovering an option button in the selection dialog (REQ-UI-SELECT-BUTTON), and hovering the selection button in the selection panel when a selection is set, displays an info tooltip:
- For a **recipe** (Miner or Assembler): the recipe name; the name and quantity of each input item (no inputs are listed for miner recipes, which consume nothing); the completion time (`duration_seconds`); and the name and quantity of the produced output item.
- For a **ship schematic** (Shipyard): the ship's `display_name`; the name and quantity of each base required material (`[ship.schematic].materials`, excluding any module contributions); the base production time (`[ship.schematic].production_time_seconds`); and "Produces: 1 <ship display name>".
- REQ-UI-RECIPE-ICON: In the recipe-selection dialog (REQ-UI-SELECT-BUTTON) for a Miner or Assembler, each recipe option button shows the icon of the recipe's produced item **instead of** its name caption (icon-only). The item shown is the recipe's `icon` field if set, otherwise its first output item; the icon is that item's icon per REQ-UI-ITEM-ICON. When the item has no icon file, the button falls back to the recipe/item name caption. The recipe name and details remain available on hover via the selection info tooltip (REQ-UI-SELECT-TOOLTIP). The `(None)` option keeps its text caption. This applies only to recipe options; the Shipyard schematic-selection dialog is unaffected and continues to show ship name captions.
- REQ-UI-SELECT-BUTTON: **Recipe and schematic selection control.** Recipe selection (Miner ore type, Assembler recipe) and schematic selection (Shipyard) are each presented in the selection panel as a single **selection button** whose caption is the name of the currently selected recipe or schematic, or a placeholder ("Select recipe" / "Select schematic") when none is selected. Clicking the button opens a modal **selection dialog** that pauses the game (speed set to 0×; on close, the speed is restored to what it was before the dialog was opened) and that opens centered on the selection panel, as every modal opened from the panel does (REQ-UI-PANEL-MODAL). The dialog contains a vertical list of option buttons, one per selectable option, each describing itself (REQ-UI-SELECT-OPTIONS) — only options that are currently unlocked are shown (REQ-LOCK-UI-RECIPE for recipes, REQ-LOCK-UI-SCHEMATIC for schematics). Neither the option buttons nor the selection button carries a tooltip: an option button states what it makes on its own face, and what the building has selected is drawn beneath the selection button as the recipe summary (REQ-UI-RECIPE-SUMMARY), with the production paths of the items involved reachable by hovering the card's item chips (REQ-UI-ITEM-TOOLTIP). Clicking an option button selects that recipe/schematic, closes the dialog, and updates the selection button's caption in the selection panel. The dialog can be dismissed without changing the current selection (e.g. closing it without clicking an option). Selecting a new recipe or schematic has the same effects as before (REQ-MAT-INPUT-BUFFER, REQ-MAT-OUTPUT-BUFFER, REQ-BLD-SHIPYARD).
- REQ-UI-SELECT-OPTIONS: **Option list of the selection dialog.** The selection dialog (REQ-UI-SELECT-BUTTON) lists its options as a **single vertical column** of buttons, one per option, rather than a grid: each button is as wide as the dialog and states what the option does, which needs a line of its own. No option button carries a tooltip — the button face is the whole description, so the player reads every option's inputs, product, and time from the list itself without hovering anything. Should the column be taller than the space the window leaves the dialog — a fully unlocked Assembler offers more options than any window can hold, and a modal is never resized to fit (REQ-UI-PANEL-MODAL) — the list **scrolls** within the dialog rather than the dialog growing past the window.
- A **recipe** option (Miner, Assembler) shows the **recipe name** on its first line and, beneath it, that recipe drawn as the recipe summary line draws it (REQ-UI-RECIPE-SUMMARY): each input item's icon on its colored square with its per-cycle amount, an arrow, each output item's icon with its amount, and the cycle time. A miner recipe consumes nothing, so its line begins at the arrow.
- A **ship schematic** option (Shipyard) shows the ship's `display_name` on its first line and, beneath it, the icons and quantities of its base required materials (`[ship.schematic].materials`, excluding any module contributions) with the base production time (`[ship.schematic].production_time_seconds`). A ship is not an item and has no icon of its own, so this line names no output: the button's caption is what it produces.
- The `(None)` option shows its text caption alone.
- REQ-UI-ITEM-TOOLTIP: **Item production tooltip.** Hovering an item chip in the selection panel — an input or output buffer chip (REQ-UI-SINGLE-SELECTION) or the HQ's block stock chip (REQ-UI-HQ-PANEL) — shows a tooltip telling the player where that item comes from. It has a heading and a body:
- the heading is the **hovered item's name**. For an input chip this is the only place the item is named at all, since such a chip carries a count and no name (REQ-UI-SINGLE-SELECTION).
- the body is the caption `Produced by` followed by one **recipe line** per unlocked recipe that produces the item. A recipe line is a small **card** of two rows: the icon of the building that runs the recipe (REQ-UI-BUILD-ICON) and the recipe's name on the first, and the recipe itself on the second, drawn as the recipe summary draws it (REQ-UI-RECIPE-SUMMARY) — each input item's icon on its colored square with its per-cycle amount, the inputs separated by `+`, an arrow, each output item's icon with its amount, and the cycle time. Two rows rather than one because an identity and a cycle read as different things, and a single row of icons, names and numbers runs too long to scan; a card around each because several producers stacked as bare lines read as one field of icons and numbers rather than as separate recipes. A line drawn where its surroundings already frame it — on an option button (REQ-UI-SELECT-OPTIONS), or as the panel's recipe summary — takes no card of its own. An item may have several producers — an iron ingot is smelted from ore, smelted from scrap, and recovered by reprocessing — and the building icon and recipe name are what tell those lines apart and tell the player which building to place for which path.
**Only recipes the player can run are listed**, consistent with the rest of the UI hiding what the player cannot make yet. What that means differs by building, because only Miner and Assembler recipes are unlocked individually (REQ-LOCK-UI-RECIPE): those are listed once unlocked, while a Smelter's or Reprocessing Plant's implicit recipes (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) are listed once **their building** is unlocked (REQ-LOCK-BUILDING) — there is no sense in naming a path through a plant the player cannot place. Two cases have no recipe line to show, and each says so in place of the list rather than leaving the tooltip bare:
- **An item no recipe produces at all.** Scrap is salvaged from debris (REQ-RES-DEBRIS-DROP) rather than crafted, so its tooltip reads `Salvaged from debris` in place of the `Produced by` caption and lists nothing beneath it.
- **An item whose every producing recipe is still locked.** The caption stays `Produced by`, and the single line beneath it reads `Undiscovered`: the player is told the item is made somehow, without being shown a path they have not unlocked yet.
The tooltip belongs to item chips only. The selection dialog shows no tooltips at all, its buttons describing themselves (REQ-UI-SELECT-OPTIONS), and the icons of the recipe summary line (REQ-UI-RECIPE-SUMMARY) show none either: they are parts of one line that already describes one recipe, rather than standalone item displays.
- REQ-UI-BELT-CLEAR: When one or more belt, splitter, tunnel entry, or tunnel exit tiles are selected, the panel's runtime group shows a **"Clear stuck items"** button that removes all items from the selected tiles. Clearing a tunnel entry or exit also discards all items currently in transit through that tunnel (REQ-BLD-TUNNEL-TRANSIT). This can be used to resolve stalled belts, splitters, and tunnels. The button acts on every selected tile, which is why a selection of belts and tunnel ends aggregates into one content rather than a count summary (REQ-UI-SELECTION-AGGREGATE).
- REQ-UI-HQ-PANEL: When the HQ is selected, the panel shows the HQ's **HP** as a bar labelled `current / maximum` (REQ-HQ-STATS, REQ-UI-HP-BARS) and, beneath it, the **global building blocks stock** — the same value as the header bar's stock display (REQ-UI-BLOCKS-ICON), rendered as an item chip (REQ-UI-SINGLE-SELECTION) carrying the `building_block` icon. The HP comes first, as it does on every card that has it (REQ-UI-SELECTION-CARD). The HQ has no input or output buffers of its own: building blocks delivered by belt go straight into the global stock (REQ-HQ-BELT-INPUT), and showing that stock on the HQ is what tells the player to route blocks there. The HQ has no configuration group and no status indicator (REQ-UI-SELECTION-STATUS), and it is never a construction site.
- REQ-UI-HQ-PANEL: When the HQ is selected, the panel shows the HQ's **HP** as a bar labelled `current / maximum` (REQ-HQ-STATS, REQ-UI-HP-BARS) and, beneath it, the **global building blocks stock** — the same value as the header bar's stock display (REQ-UI-BLOCKS-ICON), rendered as an item chip (REQ-UI-SINGLE-SELECTION) carrying the `building_block` icon on its colored square — a chip is an item display, so it takes the square even though the header bar's inline block icon does not (REQ-UI-ITEM-ICON, REQ-UI-BLOCKS-ICON), and hovering it shows the item production tooltip as any other chip does (REQ-UI-ITEM-TOOLTIP). The HP comes first, as it does on every card that has it (REQ-UI-SELECTION-CARD). The HQ has no input or output buffers of its own: building blocks delivered by belt go straight into the global stock (REQ-HQ-BELT-INPUT), and showing that stock on the HQ is what tells the player to route blocks there. The HQ has no configuration group and no status indicator (REQ-UI-SELECTION-STATUS), and it is never a construction site.
- REQ-UI-ENTITY-CLICK-SELECT: The player can click any ship (player or enemy) or any defence station (player or enemy) in the game world to select it. A plain click on a ship or defence station makes it the sole selection, clearing any previous selection. Ships and defence stations can be multi-selected — by Ctrl+clicking individual actors to add or remove them, or by box-drag (REQ-UI-MULTI-SELECT) — and can be selected together with debris and with one another in a single field selection (REQ-UI-SELECTION-CATEGORIES), freely mixing player and enemy actors. Actors cannot be selected together with buildings: selecting a ship or defence station clears any building selection, and selecting a building clears the actors (buildings win). Clicking a piece of debris adds to or establishes a field selection (REQ-UI-DEBRIS-CLICK-SELECT). Clicking empty world space (no building, ship, defence station, or piece of debris) clears the selection.
- REQ-UI-SHIP-STATS-PANEL: When exactly one ship is selected (REQ-UI-ENTITY-CLICK-SELECT) and no debris is selected, the selection panel shows a **ship stats panel**. (If debris is also selected, the panel shows the compact count summary instead, per REQ-UI-FIELD-MULTI-SELECTION.) The panel structure mirrors REQ-MOD-UI-STATS-PANEL but reflects the ship's actual live state: stats are computed from its installed modules per REQ-MOD-STAT-CALC. Its header (REQ-UI-SELECTION-CARD) carries the schematic's color swatch and display name, with the ship's current behavior in the right slot (REQ-UI-SHIP-BEHAVIOR). The panel always shows all hull stats: HP (current / maximum) as a **bar** with the two values beside its caption, then max linear speed, sensor range, main acceleration, maneuvering acceleration, angular acceleration, and max rotation speed as label/value rows. In addition, capability module summaries are shown below the hull stats, each as its own outlined row, conditioned on which module types are installed and using the same aggregation rules as REQ-MOD-UI-STATS-PANEL: weapons (combined DPS, maximum range), salvage (combined collection rate, maximum range), and repair (combined repair rate, maximum range), each appearing only if at least one instance of that module type is installed. While debug draw mode is active (REQ-UI-DEBUG-DRAW), the panel additionally shows the ship's derived threat cost (REQ-MOD-THREAT).
- REQ-UI-SHIP-BEHAVIOR: The ship stats panel (REQ-UI-SHIP-STATS-PANEL) additionally displays the selected ship's **current behavior** in its header's right slot (REQ-UI-SELECTION-CARD) — a single label naming the top-priority behavior currently governing the ship's navigation, as resolved by the fixed-priority behavior arbitration. Only the winning behavior is named; lower-priority behaviors that are suppressed are not shown, and neither are the salvage/repair cycles that run regardless of the active behavior (REQ-SHP-SALVAGE, REQ-SHP-REPAIR). The label updates live as the ship's behavior changes, and it is always shown (independent of debug draw mode, unlike the threat-cost line of REQ-UI-SHIP-STATS-PANEL). This applies to both player and enemy ships (REQ-UI-ENTITY-CLICK-SELECT); enemy ships only ever show **Engaging** or **Advancing**. The behavior labels (all wrapped in `tr()`) are:
@@ -620,7 +634,7 @@ The panel shows exactly one **content** at a time, picked from the catalog in RE
- REQ-UI-BUILD-COST: Each button is **icon-only with a cost**, its face composed of three elements: the button's **hotkey badge** in the top-left corner, the building's icon (REQ-UI-BUILD-ICON) centered below it, and the building block cost centered under the icon, shown with the `building_block` item icon (REQ-UI-BLOCKS-ICON, REQ-UI-ITEM-ICON) to the right of the number in place of the trailing `Blocks` word, e.g. `2` then a small block icon. The building name is not shown on the button; it is shown in the button's hover tooltip instead (REQ-UI-BUILD-TOOLTIP). When no icon file exists for `building_block`, the cost is shown as the bare number. The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) has no cost and shows its name as a text caption in the cost's place.
- **Hotkey badge.** The badge names the build hotkey that activates the button (REQ-UI-HOTKEYS), so the player can learn the shortcuts from the bar itself. It is rendered dimmer than the cost so it reads as secondary, but at the same size and in bold, because a smaller badge is not legible. A plain-digit hotkey is shown as the bare digit (`1`, `2`, `3`); a Shift+digit hotkey is shown with an upwards arrow prefixed and no separator (`↑1``↑6`); the Deconstruct button shows `Q`. A button whose building type has no build hotkey shows no badge and keeps the same face size, so the row stays even.
- REQ-UI-BUILD-ICON: Each build button shows an icon. Icons are SVG files loaded at runtime from `data/icons/buildings/` (a sibling of the config directory, read the same way as `visuals.toml`), one file per button named after the building's id (e.g. `belt.svg`, `reprocessing_plant.svg`). The shared Tunnel button (REQ-UI-BUILD-BAR) uses `tunnel_entry.svg`; the Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) uses `deconstruct.svg`. Each icon is a rounded colored "chip" bearing a white line glyph, the chip color following the building's fill color in `visuals.toml`. A missing icon file leaves the button showing its building name as a text caption in place of the icon, so the button stays identifiable in the icon-only bar (REQ-UI-BUILD-COST); it is not an error.
- REQ-UI-BUILD-TOOLTIP: Each building-type button shows a hover tooltip consisting of the building name followed by the descriptive text defined for that building type in `buildings.toml` (the optional per-building tooltip field). Because the button caption is icon-only (REQ-UI-BUILD-COST), the name is always part of the tooltip; if a building type defines no tooltip text, the tooltip shows the name alone. This tooltip is distinct from the recipe/schematic selection tooltip (REQ-UI-SELECT-TOOLTIP). The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) is not a building type and so has no config-defined tooltip; it instead shows its own refund tooltip defined in REQ-UI-DECONSTRUCT-BUTTON.
- REQ-UI-BUILD-TOOLTIP: Each building-type button shows a hover tooltip consisting of the building name followed by the descriptive text defined for that building type in `buildings.toml` (the optional per-building tooltip field). Because the button caption is icon-only (REQ-UI-BUILD-COST), the name is always part of the tooltip; if a building type defines no tooltip text, the tooltip shows the name alone. This tooltip is distinct from the item production tooltip of the selection panel's item chips (REQ-UI-ITEM-TOOLTIP); the recipe/schematic selection dialog has no tooltip at all (REQ-UI-SELECT-OPTIONS). The Deconstruct button (REQ-UI-DECONSTRUCT-BUTTON) is not a building type and so has no config-defined tooltip; it instead shows its own refund tooltip defined in REQ-UI-DECONSTRUCT-BUTTON.
- REQ-UI-BUILD-DISABLED: Buttons for buildings the player cannot currently afford are shown as disabled. A disabled button's icon (REQ-UI-BUILD-ICON) is rendered in a greyed variant, with its colored chip background recolored grey while the white glyph is retained.
- REQ-UI-DECONSTRUCT-BUTTON: A dedicated **Deconstruct** button is shown in the build button bar (REQ-UI-BUILD-BAR), as the last entry of the row and **visually separated** from the building-type buttons by a gap (not a divider line), because it toggles a mode rather than selecting a building type. Its face follows REQ-UI-BUILD-COST with two differences: its hotkey badge reads `Q`, and because it has no building block cost it shows its **Deconstruct** name as a text caption where the building-type buttons show their cost — so it is the one labelled button in the bar. It is therefore wider than the building-type buttons, which share a uniform width. Clicking it toggles deconstruct mode on and off, equivalent to the Q deconstruct toggle (REQ-UI-HOTKEYS). The button is shown in a visually active/pressed state while deconstruct mode is active. The button shows a hover tooltip stating the deconstruction refund (REQ-BLD-DECONSTRUCT): that deconstructing a fully-built building returns `world.toml [world].refund_percentage` percent of its building block cost once deconstruction completes, and that a construction site removed before it finishes building is refunded in full. When `refund_percentage` is 100% both cases yield the same refund, and the tooltip is simplified to state the single refund percentage without distinguishing the two cases. Unlike the building-type button tooltips (REQ-UI-BUILD-TOOLTIP), this tooltip is not config-defined text but is composed from the refund percentage.

View File

@@ -94,14 +94,6 @@ RecipesConfig ConfigLoader::loadRecipes(const std::string& path)
const toml::array& outputs = utility::requireArray(mt["outputs"], file, elemPath + ".outputs");
def.outputs = parseRecipeOutputs(outputs, file, elemPath + ".outputs");
// Optional icon item id (REQ-UI-RECIPE-ICON); defaults to the first output
// in the UI when unset. Not validated against known items here — a missing
// icon is not an error (REQ-UI-ITEM-ICON).
if (mt.contains("icon"))
{
def.icon = utility::requireString(mt["icon"], file, elemPath + ".icon");
}
cfg.recipes.push_back(std::move(def));
}

View File

@@ -32,10 +32,6 @@ struct RecipeDef
std::vector<RecipeIngredient> inputs;
std::vector<RecipeOutput> outputs;
double durationSeconds;
// Optional id of the item whose icon represents this recipe in the recipe-
// selection dialog (REQ-UI-RECIPE-ICON). When unset, the first output item is
// used. A missing icon file for that item is not an error (REQ-UI-ITEM-ICON).
std::optional<std::string> icon;
// Assembler only. When true, this recipe is available from game start
// regardless of the implicit item graph — used for base recipes that no
// schematic's materials reach (e.g. building blocks). See REQ-LOCK-IMPLICIT.

View File

@@ -81,6 +81,33 @@ computeShipyardRequiredMaterials(const GameConfig& config,
}
return requiredMaterials;
}
double computeShipyardProductionTimeSeconds(
const GameConfig& config, const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout)
{
const ShipDef* shipDef = config.ships.findShipDef(recipeId);
if (!shipDef)
{
return 0.0;
}
double seconds = shipDef->schematic.productionTimeSeconds;
if (shipLayout.has_value())
{
for (const PlacedModule& pm : shipLayout->placedModules)
{
const ModuleDef* modDef = config.modules.findModuleDef(pm.moduleId);
if (!modDef)
{
continue;
}
seconds += modDef->productionTimeSeconds;
}
}
return seconds;
}
bool hasInputsToStart(const GameConfig& config, const Building& b)
{
if (b.type == BuildingType::Shipyard)

View File

@@ -44,6 +44,12 @@ std::map<std::string, int> computeShipyardRequiredMaterials(
const GameConfig& config, const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout);
// The ship's base production time plus that of every module in the configured layout
// (REQ-MOD-PRODUCTION-TIME), over a stored configuration as above.
double computeShipyardProductionTimeSeconds(
const GameConfig& config, const std::string& recipeId,
const std::optional<ShipLayoutConfig>& shipLayout);
// True when a production cycle could start right now, ignoring output-buffer space.
bool hasInputsToStart(const GameConfig& config, const Building& b);

View File

@@ -390,39 +390,6 @@ duration_seconds = 1.0
std::runtime_error);
}
TEST_CASE("Optional recipe icon field parses; absent leaves it unset", "[config]")
{
TempConfigDir dir;
writeFile(dir.path() / "recipes.toml", R"(
[[recipe]]
id = "with_icon"
building = "assembler"
inputs = [{item = "iron_ingot", amount = 1}]
outputs = [{item = "steel_plate", amount = 1}]
duration_seconds = 1.0
icon = "hardened_steel"
[[recipe]]
id = "without_icon"
building = "assembler"
inputs = [{item = "iron_ingot", amount = 1}]
outputs = [{item = "copper_wire", amount = 1}]
duration_seconds = 1.0
)");
const RecipesConfig cfg =
ConfigLoader::loadRecipes((dir.path() / "recipes.toml").string());
const RecipeDef& withIcon = cfg.recipes.at(0);
REQUIRE(withIcon.id == "with_icon");
REQUIRE(withIcon.icon.has_value());
REQUIRE(*withIcon.icon == "hardened_steel");
const RecipeDef& withoutIcon = cfg.recipes.at(1);
REQUIRE(withoutIcon.id == "without_icon");
REQUIRE_FALSE(withoutIcon.icon.has_value());
}
// --- unlock_requires (REQ-LOCK-PREREQ) ------------------------------------
namespace

View File

@@ -25,7 +25,9 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/ShipStatsPanel.h
${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoiceDialog.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeLineRow.h
${CMAKE_CURRENT_SOURCE_DIR}/OptionButton.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemProducers.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.h
${CMAKE_CURRENT_SOURCE_DIR}/BuildingIconCache.h
${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.h
@@ -59,7 +61,9 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/ShipStatsPanel.cpp
${CMAKE_CURRENT_SOURCE_DIR}/SchematicChoiceDialog.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionDialog.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeTooltip.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeLineRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/OptionButton.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemProducers.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemIconCache.cpp
${CMAKE_CURRENT_SOURCE_DIR}/BuildingIconCache.cpp
${CMAKE_CURRENT_SOURCE_DIR}/IconCaption.cpp

View File

@@ -2,10 +2,26 @@
#include <QFile>
#include <QPainter>
#include <QRectF>
#include <QSvgRenderer>
ItemIconCache::ItemIconCache(const QString& iconDir)
#include "VisualsConfig.h"
namespace
{
// How far the icon is inset within the item's colored square, as a fraction of the
// square's size on each side (REQ-UI-ITEM-ICON). The inset is what keeps a frame of the
// square's color visible all around the icon: each icon's viewBox is cropped tight to
// its artwork, so an icon drawn at the full rect would cover the square entirely.
const double kIconInsetFraction = 0.15;
} // namespace
ItemIconCache::ItemIconCache(const QString& iconDir, const VisualsConfig* visuals)
: m_iconDir(iconDir)
, m_visuals(visuals)
{
}
@@ -34,14 +50,59 @@ bool ItemIconCache::hasIcon(const std::string& itemId)
return !getSvg(itemId).isEmpty();
}
void ItemIconCache::paintItem(QPainter& painter, const QRectF& rect,
const std::string& itemId)
{
// The colored square from visuals.toml backs every item, icon or not: it is what
// gives the item contrast against the tile beneath it in the world, and its outline
// is what separates neighbouring items where they overlap on a belt (REQ-GW-TILE-SIZE,
// REQ-UI-ITEM-ICON).
if (m_visuals != nullptr)
{
const std::map<std::string, ItemVisuals>::const_iterator it =
m_visuals->items.find(itemId);
if (it != m_visuals->items.end())
{
painter.fillRect(rect, it->second.fill);
painter.setPen(QPen(it->second.outline, 1));
painter.setBrush(Qt::NoBrush);
painter.drawRect(rect);
}
}
if (!hasIcon(itemId)) { return; }
// The icon goes on top, inset so a frame of the square's color stays visible all
// around it. It is rasterized once at the inset pixel size and cached, so this is a
// plain pixmap blit per frame.
const double inset = kIconInsetFraction * rect.width();
const QRectF iconRect = rect.adjusted(inset, inset, -inset, -inset);
int sizePx = qRound(iconRect.width());
if (sizePx < 1) { sizePx = 1; }
painter.drawPixmap(iconRect, getPixmap(itemId, sizePx),
QRectF(0, 0, sizePx, sizePx));
}
QPixmap ItemIconCache::getSquarePixmap(const std::string& itemId, int sizePx)
{
return getPixmap("square:" + itemId, itemId, sizePx, true);
}
QPixmap ItemIconCache::getPixmap(const std::string& itemId, int sizePx)
{
return getPixmap(itemId, itemId, sizePx, false);
}
QPixmap ItemIconCache::getPixmap(const std::string& cacheKey, const std::string& itemId,
int sizePx, bool withSquare)
{
if (sizePx <= 0)
{
return QPixmap();
}
const std::pair<std::string, int> key(itemId, sizePx);
const std::pair<std::string, int> key(cacheKey, sizePx);
const std::map<std::pair<std::string, int>, QPixmap>::const_iterator cached =
m_pixmapCache.find(key);
if (cached != m_pixmapCache.end())
@@ -49,16 +110,45 @@ QPixmap ItemIconCache::getPixmap(const std::string& itemId, int sizePx)
return cached->second;
}
const QByteArray& svg = getSvg(itemId);
QPixmap pixmap;
if (!svg.isEmpty())
if (withSquare)
{
QSvgRenderer renderer(svg);
pixmap = QPixmap(sizePx, sizePx);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
renderer.render(&painter);
// Null unless the item has something to draw -- a square, an icon, or both --
// so a caller with nothing to show can fall back to text (REQ-UI-ITEM-ICON).
const bool hasSquare = m_visuals != nullptr
&& m_visuals->items.find(itemId) != m_visuals->items.end();
if (hasSquare || hasIcon(itemId))
{
pixmap = QPixmap(sizePx, sizePx);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
// No antialiasing: the square's edges are axis-aligned and land on pixel
// boundaries, and smoothing a 1-pixel outline only blurs it. The icon is
// blitted into a slightly smaller rect than it was rasterized at, which is
// what the smooth transform is for.
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
// One pixel short of the pixmap so the square's right and bottom edges land
// inside it rather than on its border.
paintItem(painter, QRectF(0, 0, sizePx - 1, sizePx - 1), itemId);
}
}
else
{
const QByteArray& svg = getSvg(itemId);
if (!svg.isEmpty())
{
QSvgRenderer renderer(svg);
pixmap = QPixmap(sizePx, sizePx);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
renderer.render(&painter);
}
}
return m_pixmapCache.emplace(key, std::move(pixmap)).first->second;
}
void ItemIconCache::clearPixmapCache()
{
m_pixmapCache.clear();
}

View File

@@ -8,38 +8,78 @@
#include <QPixmap>
#include <QString>
// Rasterizes and caches per-item icon SVGs (REQ-UI-ITEM-ICON). Item icons are
// self-contained, full-color SVGs loaded from a directory, one file per item type
// named after the item's id (e.g. "iron_ore.svg"). Shared by the recipe-selection
// dialog (REQ-UI-RECIPE-ICON) and the game world's belt/port item rendering so the
// rasterization is not duplicated.
class QPainter;
class QRectF;
struct VisualsConfig;
// Rasterizes and caches per-item icon SVGs, and composes them onto the item's colored
// square (REQ-UI-ITEM-ICON). Item icons are self-contained, full-color SVGs loaded from
// a directory, one file per item type named after the item's id (e.g. "iron_ore.svg").
//
// A missing icon file is not an error: hasIcon() returns false for it and the caller
// falls back (a colored square in the world, a name caption in the dialog).
// The square is the item's `fill` and `outline` from visuals.toml with the icon inset
// within it, and it backs the icon both in the game world and wherever the UI displays
// an item as an item: the selection panel's item chips (REQ-UI-SINGLE-SELECTION,
// REQ-UI-HQ-PANEL), and every recipe drawn as a line -- the recipe summary, the
// selection dialog's option buttons, the item production tooltip
// (REQ-UI-RECIPE-SUMMARY, REQ-UI-SELECT-OPTIONS, REQ-UI-ITEM-TOOLTIP). Defined here
// once rather than per widget, in
// two forms: paintItem() for the world's fractional geometry, getSquarePixmap() for
// widgets that want a ready-made pixmap.
//
// The bare icon of getPixmap() has one remaining use: the inline building_block icon
// that stands in for the word "Blocks" beside a number (REQ-UI-BLOCKS-ICON), which is a
// decoration on a line of text rather than an item display and takes no square.
//
// A missing icon file is not an error: hasIcon() returns false for it and the item shows
// its colored square alone.
class ItemIconCache
{
public:
// iconDir is the directory holding the "<item_id>.svg" icon files
// (typically "<configDir>/../icons/items").
explicit ItemIconCache(const QString& iconDir);
// iconDir is the directory holding the "<item_id>.svg" icon files (typically
// "<configDir>/../icons/items"). visuals supplies the per-item square colors and
// must outlive the cache; its contents may be replaced on a restart (REQ-CFG-RELOAD),
// which is what clearPixmapCache() is for.
ItemIconCache(const QString& iconDir, const VisualsConfig* visuals);
// True if an icon SVG file exists for the given item id. Loads the file's bytes
// on first query and remembers the result (including absence) so repeated calls
// are cheap.
bool hasIcon(const std::string& itemId);
// Returns the item's icon rasterized to a transparent sizePx*sizePx pixmap,
// cached per (item id, size) so it is rendered once and reused across frames and
// only re-rasterized when the target size changes (REQ-UI-ITEM-ICON). Returns a
// null pixmap if the item has no icon file (callers should gate on hasIcon()).
// Paints the item's colored square into rect and its icon inset within it
// (REQ-UI-ITEM-ICON). Takes the rect as a QRectF so the world can keep painting at
// sub-pixel geometry. An item with no visuals entry gets no square, one with no icon
// file no icon; with neither, this paints nothing.
void paintItem(QPainter& painter, const QRectF& rect, const std::string& itemId);
// The same composition rasterized to a sizePx*sizePx pixmap for widget use, cached
// per (item id, size) so it is rendered once and reused. Returns a null pixmap only
// when the item has neither a visuals entry nor an icon file, which is the one case
// in which a caller has nothing to show and falls back to text.
QPixmap getSquarePixmap(const std::string& itemId, int sizePx);
// Returns the item's icon alone, without its square, rasterized to a transparent
// sizePx*sizePx pixmap and cached per (item id, size) so it is rendered once and
// reused across frames (REQ-UI-ITEM-ICON). Returns a null pixmap if the item has no
// icon file (callers should gate on hasIcon()).
QPixmap getPixmap(const std::string& itemId, int sizePx);
// Drops every rasterized pixmap. Called when the visuals are reloaded on a restart
// (REQ-CFG-RELOAD), because the composed squares carry the colors they were painted
// with; they are re-rasterized on next use.
void clearPixmapCache();
private:
// Returns the raw SVG bytes for an item id, loading and caching them on first
// access. An absent file caches an empty QByteArray so it is not retried.
const QByteArray& getSvg(const std::string& itemId);
// Shared rasterize-and-cache step. cacheKey distinguishes the bare and squared
// variants of one item within the single pixmap cache.
QPixmap getPixmap(const std::string& cacheKey, const std::string& itemId,
int sizePx, bool withSquare);
QString m_iconDir;
const VisualsConfig* m_visuals; // Not owned; lives in MainWindow.
std::map<std::string, QByteArray> m_svgById;
std::map<std::pair<std::string, int>, QPixmap> m_pixmapCache;
};

60
src/ui/ItemProducers.cpp Normal file
View File

@@ -0,0 +1,60 @@
#include "ItemProducers.h"
#include "GameConfig.h"
#include "RecipesConfig.h"
#include "Simulation.h"
namespace
{
bool producesItem(const RecipeDef& recipe, const std::string& itemId)
{
for (const RecipeOutput& output : recipe.outputs)
{
if (output.item == itemId)
{
return true;
}
}
return false;
}
bool isAvailable(const RecipeDef& recipe, const Simulation& sim)
{
if (recipe.building == BuildingType::Miner
|| recipe.building == BuildingType::Assembler)
{
return sim.isRecipeUnlocked(recipe.id);
}
return sim.isBuildingUnlocked(recipe.building);
}
} // namespace
ItemProduction findItemProduction(const std::string& itemId, const Simulation& sim,
const GameConfig& config)
{
ItemProduction result;
bool anyProducer = false;
for (const RecipeDef& recipe : config.recipes.recipes)
{
if (!producesItem(recipe, itemId)) { continue; }
anyProducer = true;
if (isAvailable(recipe, sim))
{
result.recipes.push_back(&recipe);
}
}
if (!result.recipes.empty())
{
result.origin = ItemOrigin::Produced;
}
else
{
result.origin = anyProducer ? ItemOrigin::Undiscovered : ItemOrigin::Salvaged;
}
return result;
}

35
src/ui/ItemProducers.h Normal file
View File

@@ -0,0 +1,35 @@
#pragma once
#include <string>
#include <vector>
struct GameConfig;
struct RecipeDef;
class Simulation;
// Where an item comes from, as far as the player has discovered (REQ-UI-ITEM-TOOLTIP).
enum class ItemOrigin
{
Produced, // at least one recipe the player can run makes it
Undiscovered, // recipes make it, but none of them is available yet
Salvaged, // no recipe makes it at all -- scrap, which comes from debris
};
struct ItemProduction
{
ItemOrigin origin = ItemOrigin::Salvaged;
// The available producers, in config order. Empty unless origin is Produced.
std::vector<const RecipeDef*> recipes;
};
// Every way the player can currently produce the given item, for the tooltip that
// explains an item chip (REQ-UI-ITEM-TOOLTIP).
//
// What counts as available differs by building type, because only Miner and Assembler
// recipes are individually unlocked (REQ-LOCK-UI-RECIPE): those are filtered by the
// unlock state, while a Smelter's or Reprocessing Plant's implicit recipes
// (REQ-BLD-SMELTER, REQ-BLD-REPROCESSING) are filtered by whether their building is
// unlocked yet (REQ-LOCK-BUILDING) -- there is no sense in naming a path through a
// plant the player cannot place.
ItemProduction findItemProduction(const std::string& itemId, const Simulation& sim,
const GameConfig& config);

View File

@@ -7,6 +7,7 @@
#include <QApplication>
#include <QCloseEvent>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QInputDialog>
@@ -55,7 +56,7 @@ MainWindow::MainWindow(Simulation* sim, const std::string& configDir,
// REQ-UI-BUILD-ICON).
const QString configDirPath = QString::fromStdString(m_configDir);
m_itemIcons = std::make_unique<ItemIconCache>(
QDir::cleanPath(configDirPath + "/../icons/items"));
QDir::cleanPath(configDirPath + "/../icons/items"), &m_visuals);
m_buildingIcons = std::make_unique<BuildingIconCache>(
QDir::cleanPath(configDirPath + "/../icons/buildings"));
@@ -223,7 +224,8 @@ void MainWindow::handleEvent(std::shared_ptr<const SchematicChoicesAvailableEven
ModalPauseScope pause(*m_gameWorldView);
ModalDimScope dim(*m_dimOverlay);
SchematicChoiceDialog dialog(event->choices, m_sim->getConfig().recipes, this);
SchematicChoiceDialog dialog(event->choices, m_sim->getConfig().recipes,
m_itemIcons.get(), m_buildingIcons.get(), this);
dialog.exec();
std::shared_ptr<ApplySchematicChoiceCommand> command =
@@ -283,6 +285,9 @@ std::optional<GameConfig> MainWindow::reloadConfig()
VisualsConfig newVisuals = VisualsLoader::load(m_configDir + "/visuals.toml");
m_visuals = std::move(newVisuals);
m_dimOverlay->setDimColor(m_visuals.overlays.modalDim);
// The composed item squares carry the colors they were painted with, so they
// are dropped for the new ones to take effect (REQ-UI-ITEM-ICON).
m_itemIcons->clearPixmapCache();
return newConfig;
}
catch (const std::exception& e)
@@ -313,7 +318,10 @@ void MainWindow::openShipLayoutDialog(BuildingId shipyardId,
m_layoutBlueprints,
std::move(unlockedModuleIds),
m_gameWorldView->isDebugDrawEnabled(),
this);
m_itemIcons.get(), this);
// Opened from the panel's "Configure" button (REQ-MOD-UI-PREVIEW) or straight after
// a schematic change (REQ-MOD-UI-AUTO-DIALOG), so it opens on the panel either way.
placeOnSelectionPanel(dialog);
if (dialog.exec() == QDialog::Accepted && dialog.getResult().has_value())
{
std::shared_ptr<SetShipLayoutCommand> command =
@@ -325,6 +333,45 @@ void MainWindow::openShipLayoutDialog(BuildingId shipyardId,
}
}
void MainWindow::placeOnSelectionPanel(QDialog& dialog) const
{
// The panel is up whenever one of these modals opens -- they are opened from its own
// controls, and it is shown whenever anything is selected (REQ-UI-EMPTY-SELECTION).
// Were it not, there would be no rectangle to center on and Qt's own centering on
// this window stands.
if (!m_selectionPanel->isVisible()) { return; }
// The dialog has never been shown, so it is still at its default size until its
// layout has run; centering it before that would use the wrong extent.
dialog.adjustSize();
const QSize dialogSize = dialog.size();
// The panel's live geometry, so a panel the player has dragged
// (REQ-UI-SELECTION-PANEL-DRAG) carries the modal with it.
const QRect panelRect(m_selectionPanel->mapToGlobal(QPoint(0, 0)),
m_selectionPanel->size());
const QRect windowRect(mapToGlobal(QPoint(0, 0)), size());
QPoint topLeft(panelRect.center().x() - dialogSize.width() / 2,
panelRect.center().y() - dialogSize.height() / 2);
// Pushed back inside the window, never resized to fit (REQ-UI-PANEL-MODAL). The far
// edge is clamped first and the near edge second, which is what aligns a dialog too
// large for the window with the window's top-left corner rather than pushing it off
// the opposite edge.
topLeft.setX(qMax(windowRect.left(),
qMin(topLeft.x(), windowRect.right() - dialogSize.width() + 1)));
topLeft.setY(qMax(windowRect.top(),
qMin(topLeft.y(), windowRect.bottom() - dialogSize.height() + 1)));
// Positions the dialog's frame, whose size is not known until it is first shown, so
// the result sits low by the title bar height against a true center -- measuring it
// would mean showing the dialog at the wrong place first. The move also marks the
// dialog as positioned, which is what stops QDialog from centering it on this window
// when it is shown.
dialog.move(topLeft);
}
void MainWindow::handleEvent(std::shared_ptr<const LayoutDialogRequestedEvent> event)
{
// A construction site has no Building yet; fall back to its site record so
@@ -381,7 +428,9 @@ void MainWindow::handleEvent(std::shared_ptr<const RecipeSelectionRequestedEvent
bool autoOpenLayout = false;
std::string chosenSchematic;
RecipeSelectionDialog dialog(options, title, m_itemIcons.get(), this);
RecipeSelectionDialog dialog(options, title, m_itemIcons.get(),
m_buildingIcons.get(), this);
placeOnSelectionPanel(dialog);
if (dialog.exec() == QDialog::Accepted && dialog.getChosenId().has_value())
{
std::shared_ptr<SetRecipeCommand> command = std::make_shared<SetRecipeCommand>();

View File

@@ -36,6 +36,7 @@ class BlueprintLibrary;
class BuildingIconCache;
class ItemIconCache;
class QCloseEvent;
class QDialog;
class QResizeEvent;
class MainWindow : public QWidget,
@@ -83,6 +84,11 @@ private:
const std::string& schematicId,
const ShipLayoutConfig& currentLayout);
// Centers a modal opened from the selection panel on that panel, kept inside this
// window (REQ-UI-PANEL-MODAL). Called on the constructed dialog before exec(), and
// only for the two modals the panel opens.
void placeOnSelectionPanel(QDialog& dialog) const;
// Runs the blueprint selection dialog and enters placement mode for whatever the
// player picked (REQ-UI-BLUEPRINT-DIALOG). Holds no pause or dim scope of its own:
// both callers already hold theirs, which is what keeps the dim continuous when a

35
src/ui/OptionButton.cpp Normal file
View File

@@ -0,0 +1,35 @@
#include "OptionButton.h"
#include <QLayout>
#include <QStyle>
#include <QStyleOptionButton>
OptionButton::OptionButton(QWidget* parent)
: QPushButton(parent)
{
}
QSize OptionButton::sizeHint() const
{
if (layout() == nullptr)
{
return QPushButton::sizeHint();
}
return sizeForFace(layout()->sizeHint());
}
QSize OptionButton::minimumSizeHint() const
{
if (layout() == nullptr)
{
return QPushButton::minimumSizeHint();
}
return sizeForFace(layout()->minimumSize());
}
QSize OptionButton::sizeForFace(const QSize& faceSize) const
{
QStyleOptionButton option;
initStyleOption(&option);
return style()->sizeFromContents(QStyle::CT_PushButton, &option, faceSize, this);
}

28
src/ui/OptionButton.h Normal file
View File

@@ -0,0 +1,28 @@
#pragma once
#include <QPushButton>
#include <QSize>
// A push button whose face is built of widgets rather than of a caption: an option's
// name over the recipe line stating what it makes (REQ-UI-SELECT-OPTIONS), or a module's
// name over what it costs (REQ-MOD-UI-DIALOG).
//
// It exists only to be measured correctly. QPushButton computes its size hint from its
// text and icon and ignores a layout set on it, so a button carrying a face of widgets
// would be sized as if it were empty and clip everything in it. This asks the layout
// instead, and then lets the style add what the button's own frame needs.
class OptionButton : public QPushButton
{
Q_OBJECT
public:
explicit OptionButton(QWidget* parent = nullptr);
QSize sizeHint() const override;
QSize minimumSizeHint() const override;
private:
// The style's button size for the given face size, or the plain QPushButton hint
// when there is no face to measure.
QSize sizeForFace(const QSize& faceSize) const;
};

196
src/ui/RecipeLineRow.cpp Normal file
View File

@@ -0,0 +1,196 @@
#include "RecipeLineRow.h"
#include <QFont>
#include <QHBoxLayout>
#include <QLabel>
#include <QLayoutItem>
#include <QMargins>
#include <QPixmap>
#include <QVBoxLayout>
#include "BuildingIconCache.h"
#include "ItemIconCache.h"
namespace
{
// Size the items' colored squares and the building's chip are drawn at on a line, in
// device-independent pixels. Larger than the artwork they carry, which the square
// insets (REQ-UI-ITEM-ICON).
const int kIconSizePx = 18;
// Adds a freshly built label to the line and shows it.
//
// The show is what makes it count: a widget created under an already-visible parent
// starts hidden, and a layout treats a hidden item as empty, so an unshown label would
// add nothing to the size hint the surrounding widget measures itself against as soon
// as this returns.
void addAndShow(QHBoxLayout* layout, QLabel* label)
{
layout->addWidget(label);
label->show();
}
// Empties one of the two rows, leaving the row widget and its layout in place.
void clearRow(QHBoxLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0))
{
if (item->widget())
{
item->widget()->deleteLater();
}
delete item;
}
}
} // namespace
RecipeLineRow::RecipeLineRow(ItemIconCache* itemIcons, BuildingIconCache* buildingIcons,
QWidget* parent)
: QWidget(parent)
, m_itemIcons(itemIcons)
, m_buildingIcons(buildingIcons)
{
m_outerLayout = new QVBoxLayout(this);
m_outerLayout->setContentsMargins(0, 0, 0, 0);
m_outerLayout->setSpacing(1);
m_headerRow = new QWidget(this);
m_headerLayout = new QHBoxLayout(m_headerRow);
m_headerLayout->setContentsMargins(0, 0, 0, 0);
m_headerLayout->setSpacing(4);
m_headerRow->hide();
m_outerLayout->addWidget(m_headerRow);
m_amountsRow = new QWidget(this);
m_amountsLayout = new QHBoxLayout(m_amountsRow);
m_amountsLayout->setContentsMargins(0, 0, 0, 0);
m_amountsLayout->setSpacing(4);
m_outerLayout->addWidget(m_amountsRow);
hide();
}
void RecipeLineRow::setCardChrome(bool enabled)
{
// Palette colors like the item chip's chrome (REQ-UI-SELECTION-CARD), not
// visuals.toml, which is for world rendering. The selector names this class alone, so
// nothing inside the card inherits the border.
setAttribute(Qt::WA_StyledBackground, enabled);
setStyleSheet(enabled
? QStringLiteral("RecipeLineRow { border: 1px solid palette(mid); "
"border-radius: 4px; }")
: QString());
m_outerLayout->setContentsMargins(enabled ? QMargins(6, 4, 6, 4)
: QMargins(0, 0, 0, 0));
}
void RecipeLineRow::setLine(const Spec& spec)
{
if (spec.isEmpty())
{
// Forgotten as well as hidden, so re-selecting the same recipe later is seen as
// a change and shows the row again.
m_spec = Spec();
hide();
return;
}
if (spec == m_spec)
{
return;
}
m_spec = spec;
rebuild(spec);
show();
}
void RecipeLineRow::rebuild(const Spec& spec)
{
clearRow(m_headerLayout);
clearRow(m_amountsLayout);
// First line: which building runs the recipe and which recipe it is, where the line
// has to distinguish one producer from another (REQ-UI-ITEM-TOOLTIP). A building with
// no chip file leaves the icon off, as everywhere else (REQ-UI-BUILD-ICON).
if (spec.building.has_value() && m_buildingIcons != nullptr)
{
const QPixmap chip =
m_buildingIcons->getChip(buildingTypeId(*spec.building), kIconSizePx);
if (!chip.isNull())
{
QLabel* chipLabel = new QLabel(m_headerRow);
chipLabel->setPixmap(chip);
addAndShow(m_headerLayout, chipLabel);
}
}
if (!spec.name.isEmpty())
{
QLabel* nameLabel = new QLabel(spec.name, m_headerRow);
QFont nameFont = nameLabel->font();
nameFont.setBold(true);
nameLabel->setFont(nameFont);
addAndShow(m_headerLayout, nameLabel);
}
const bool hasHeader = m_headerLayout->count() > 0;
if (hasHeader)
{
m_headerLayout->addStretch(1);
}
m_headerRow->setVisible(hasHeader);
// Second line: what the cycle costs, makes and takes.
addAmounts(spec.inputs);
if (!spec.inputs.empty() && !spec.outputs.empty())
{
const QChar rightArrow(0x2192); // U+2192 RIGHTWARDS ARROW
addAndShow(m_amountsLayout, new QLabel(QString(rightArrow), m_amountsRow));
}
addAmounts(spec.outputs);
if (spec.durationSeconds.has_value() && *spec.durationSeconds > 0.0)
{
const QChar middleDot(0x00B7); // U+00B7 MIDDLE DOT
const QString time = spec.durationIsAddition
? tr("+%1 s").arg(*spec.durationSeconds, 0, 'f', 1)
: tr("%1 s").arg(*spec.durationSeconds, 0, 'f', 1);
addAndShow(m_amountsLayout, new QLabel(
QStringLiteral("%1 %2").arg(middleDot).arg(time), m_amountsRow));
}
m_amountsLayout->addStretch(1);
}
void RecipeLineRow::addAmounts(const std::vector<Amount>& amounts)
{
for (const Amount& entry : amounts)
{
// Between one item and the next, so a run of icons and numbers reads as a sum
// rather than as a list.
if (&entry != &amounts.front())
{
addAndShow(m_amountsLayout, new QLabel(QStringLiteral("+"), m_amountsRow));
}
// The item's icon on its colored square (REQ-UI-ITEM-ICON). A missing icon file
// is not an error: the square stands alone then, and only an item with no square
// either falls back to its id in text.
const QPixmap icon = (m_itemIcons != nullptr)
? m_itemIcons->getSquarePixmap(entry.itemId, kIconSizePx)
: QPixmap();
if (!icon.isNull())
{
QLabel* iconLabel = new QLabel(m_amountsRow);
iconLabel->setPixmap(icon);
addAndShow(m_amountsLayout, iconLabel);
}
else
{
addAndShow(m_amountsLayout,
new QLabel(QString::fromStdString(entry.itemId), m_amountsRow));
}
addAndShow(m_amountsLayout,
new QLabel(QString::number(entry.amount), m_amountsRow));
}
}

115
src/ui/RecipeLineRow.h Normal file
View File

@@ -0,0 +1,115 @@
#pragma once
#include <optional>
#include <string>
#include <vector>
#include <QString>
#include <QWidget>
#include "BuildingType.h"
class BuildingIconCache;
class ItemIconCache;
class QHBoxLayout;
class QVBoxLayout;
// One recipe drawn: what it consumes, an arrow, what it produces, and how long a cycle
// takes (REQ-UI-RECIPE-SUMMARY), under a header naming the building that runs it and the
// recipe itself where the recipe has to identify itself. Every place the UI states what
// something makes draws this same line, so a recipe reads alike wherever it is shown:
//
// * beneath the selection button, for the recipe a building is running
// (REQ-UI-RECIPE-SUMMARY);
// * on a selection dialog's option buttons, under the option's name
// (REQ-UI-SELECT-OPTIONS);
// * in an item's production tooltip and in the unlock-choice dialog, there led by the
// icon of the building that runs the recipe and its name
// (REQ-UI-ITEM-TOOLTIP, REQ-DEF-SCHEMATIC-DROP);
// * on a module button and in the layout dialog's build cost, where there is a price
// and a time but nothing produced (REQ-MOD-UI-DIALOG, REQ-MOD-UI-STATS-PANEL).
class RecipeLineRow : public QWidget
{
Q_OBJECT
public:
// One item and how many of it the line states.
struct Amount
{
std::string itemId;
int amount = 0;
bool operator==(const Amount& other) const
{
return itemId == other.itemId && amount == other.amount;
}
};
// What the line says. Everything but the inputs is optional, which is what lets the
// one widget serve the summary, the option buttons, the tooltip lines and the cost
// lines.
struct Spec
{
// The chip of the building running the recipe, on the header line, where the
// recipe has to say which building that is -- an item may have several producers
// (REQ-UI-ITEM-TOOLTIP). Unset wherever the surrounding widget already
// establishes the building, and the header line is then left out entirely.
std::optional<BuildingType> building;
// The recipe's name, beside the building chip on the header line. Empty where the
// name is the caption of the widget around this one instead.
QString name;
std::vector<Amount> inputs;
// Empty for a line that produces no item of its own: a ship schematic, or a
// module's price. No arrow is drawn then.
std::vector<Amount> outputs;
std::optional<double> durationSeconds;
// True where the time is added to something else rather than being a cycle of
// its own, and so reads "+3.0 s" (REQ-MOD-UI-DIALOG).
bool durationIsAddition = false;
bool operator==(const Spec& other) const
{
return building == other.building && name == other.name
&& inputs == other.inputs && outputs == other.outputs
&& durationSeconds == other.durationSeconds
&& durationIsAddition == other.durationIsAddition;
}
bool isEmpty() const { return inputs.empty() && outputs.empty(); }
};
// Both caches may be null, which leaves the icons off: an item with no square and
// no icon falls back to its id, and a building with no chip to its name alone.
// Neither is owned.
RecipeLineRow(ItemIconCache* itemIcons, BuildingIconCache* buildingIcons,
QWidget* parent = nullptr);
// Hides the row when the spec has nothing to state, which is how a building with no
// recipe shows no summary at all (REQ-UI-RECIPE-SUMMARY).
void setLine(const Spec& spec);
// Boxes the line in a card of its own, for the two places that stack several of them
// (REQ-UI-ITEM-TOOLTIP, REQ-DEF-SCHEMATIC-DROP): a run of bare lines reads as one
// field of icons and numbers, and the box is what separates one recipe from the next.
// Off by default -- a line drawn inside a button or a panel section is already framed
// by what holds it.
void setCardChrome(bool enabled);
private:
void rebuild(const Spec& spec);
void addAmounts(const std::vector<Amount>& amounts);
ItemIconCache* m_itemIcons;
BuildingIconCache* m_buildingIcons;
QVBoxLayout* m_outerLayout;
// The two lines, each a row widget of its own so a rebuild only has to empty their
// layouts -- no nested layout to take apart. The header is hidden where the spec
// names neither a building nor a recipe.
QWidget* m_headerRow;
QHBoxLayout* m_headerLayout;
QWidget* m_amountsRow;
QHBoxLayout* m_amountsLayout;
// What the row currently shows, so a refresh at tick rate rebuilds it only when the
// recipe actually changed.
Spec m_spec;
};

View File

@@ -2,60 +2,46 @@
#include <cstddef>
#include <QGridLayout>
#include <QIcon>
#include <QPixmap>
#include <QFont>
#include <QFrame>
#include <QLabel>
#include <QPushButton>
#include <QSize>
#include <QStringList>
#include <QScrollArea>
#include <QVBoxLayout>
#include "Building.h"
#include "BuildingType.h"
#include "DisplayName.h"
#include "GameConfig.h"
#include "ItemIconCache.h"
#include "OptionButton.h"
#include "RecipesConfig.h"
#include "RecipeTooltip.h"
#include "ShipsConfig.h"
#include "Simulation.h"
namespace
{
QString itemLine(const std::string& itemId, int amount)
std::vector<RecipeLineRow::Amount> toAmounts(
const std::vector<RecipeIngredient>& ingredients)
{
return QStringLiteral(" ")
+ QString::fromStdString(toDisplayName(itemId))
+ QStringLiteral(" x ") + QString::number(amount);
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(ingredients.size());
for (const RecipeIngredient& ingredient : ingredients)
{
amounts.push_back(RecipeLineRow::Amount{ ingredient.item, ingredient.amount });
}
return amounts;
}
QString shipTooltip(const ShipDef& def)
std::vector<RecipeLineRow::Amount> toAmounts(const std::vector<RecipeOutput>& outputs)
{
const QString name = QString::fromStdString(toDisplayName(def.id));
QStringList lines;
lines << QObject::tr("Ship: %1").arg(name);
if (def.schematic.materials.empty())
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(outputs.size());
for (const RecipeOutput& output : outputs)
{
lines << QObject::tr("Materials: none");
amounts.push_back(RecipeLineRow::Amount{ output.item, output.amount });
}
else
{
lines << QObject::tr("Materials:");
for (const RecipeIngredient& material : def.schematic.materials)
{
lines << itemLine(material.item, material.amount);
}
lines << QObject::tr(" + installed modules");
}
lines << QObject::tr("Completion time: %1 s")
.arg(def.schematic.productionTimeSeconds);
lines << QObject::tr("Produces: 1 %1").arg(name);
return lines.join('\n');
return amounts;
}
} // namespace
@@ -64,16 +50,24 @@ std::vector<RecipeSelectionOption> buildRecipeSelectionOptions(
BuildingType type, Simulation& sim, const GameConfig& config)
{
std::vector<RecipeSelectionOption> options;
options.push_back({std::string(), QObject::tr("(None)"), QString()});
options.push_back({std::string(), QObject::tr("(None)"), RecipeLineRow::Spec()});
if (type == BuildingType::Shipyard)
{
for (const ShipDef& def : config.ships.ships)
{
if (!sim.isSchematicUnlocked(def.id)) { continue; }
// The base materials and base production time, excluding the modules the
// player has not placed yet (REQ-UI-SELECT-OPTIONS). No output item: a ship
// has no icon, so the caption is what the option produces.
RecipeLineRow::Spec line;
line.inputs = toAmounts(def.schematic.materials);
line.durationSeconds = def.schematic.productionTimeSeconds;
options.push_back({def.id,
QString::fromStdString(toDisplayName(def.id)),
shipTooltip(def)});
line});
}
}
else
@@ -87,16 +81,15 @@ std::vector<RecipeSelectionOption> buildRecipeSelectionOptions(
{
continue;
}
// Icon shown on the option button (REQ-UI-RECIPE-ICON): the recipe's
// configured icon item, else its first output item.
const std::string iconItemId = recipe.icon
? *recipe.icon
: (recipe.outputs.empty() ? std::string()
: recipe.outputs.front().item);
RecipeLineRow::Spec line;
line.inputs = toAmounts(recipe.inputs);
line.outputs = toAmounts(recipe.outputs);
line.durationSeconds = recipe.durationSeconds;
options.push_back({recipe.id,
QString::fromStdString(toDisplayName(recipe.id)),
buildRecipeTooltip(recipe),
iconItemId});
line});
}
}
@@ -105,46 +98,77 @@ std::vector<RecipeSelectionOption> buildRecipeSelectionOptions(
namespace
{
// On-screen size of a recipe option button's item icon (REQ-UI-RECIPE-ICON).
const QSize kOptionIconSize(32, 32);
// Height the option list is allowed to take, as the dialog's parent window's height
// less what the window margins and the dialog's own frame need. Fully unlocked, an
// Assembler offers more options than any window can hold, and the modal is never
// resized to fit (REQ-UI-PANEL-MODAL) -- so the list scrolls instead.
const int kListHeightReservePx = 80;
// Fallback cap for a dialog built without a parent window to measure.
const int kFallbackListHeightPx = 600;
}
RecipeSelectionDialog::RecipeSelectionDialog(
const std::vector<RecipeSelectionOption>& options,
const QString& title, ItemIconCache* itemIcons, QWidget* parent)
const QString& title, ItemIconCache* itemIcons, BuildingIconCache* buildingIcons,
QWidget* parent)
: QDialog(parent)
{
setWindowTitle(title);
setModal(true);
QVBoxLayout* mainLayout = new QVBoxLayout(this);
QGridLayout* grid = new QGridLayout();
mainLayout->addLayout(grid);
const int columnCount = 2;
// One vertical column of buttons, each stating what it makes (REQ-UI-SELECT-OPTIONS).
QScrollArea* scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
scrollArea->setMaximumHeight(parent != nullptr
? qMax(kListHeightReservePx, parent->height() - kListHeightReservePx)
: kFallbackListHeightPx);
mainLayout->addWidget(scrollArea);
QWidget* list = new QWidget(scrollArea);
QVBoxLayout* listLayout = new QVBoxLayout(list);
listLayout->setContentsMargins(0, 0, 0, 0);
listLayout->setSpacing(4);
for (int i = 0; i < static_cast<int>(options.size()); ++i)
{
const RecipeSelectionOption& option = options[static_cast<std::size_t>(i)];
QPushButton* button = new QPushButton(this);
// Icon-only when the produced item has an icon (REQ-UI-RECIPE-ICON); otherwise
// fall back to the caption. The name stays reachable via the tooltip.
if (!option.iconItemId.empty() && itemIcons->hasIcon(option.iconItemId))
// An OptionButton so the face of widgets below is what sizes the button
// (REQ-UI-SELECT-OPTIONS).
OptionButton* button = new OptionButton(list);
if (option.line.isEmpty())
{
button->setIcon(QIcon(itemIcons->getPixmap(
option.iconItemId, kOptionIconSize.width())));
button->setIconSize(kOptionIconSize);
// The "(None)" option makes nothing and is a caption alone
// (REQ-UI-SELECT-OPTIONS).
button->setText(option.caption);
}
else
{
button->setText(option.caption);
// The name over the recipe it stands for. Both are transparent to the mouse
// so a click anywhere on the face still reaches the button beneath them.
QVBoxLayout* face = new QVBoxLayout(button);
face->setContentsMargins(8, 6, 8, 6);
face->setSpacing(2);
QLabel* nameLabel = new QLabel(option.caption, button);
QFont nameFont = nameLabel->font();
nameFont.setBold(true);
nameLabel->setFont(nameFont);
nameLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true);
face->addWidget(nameLabel);
RecipeLineRow* line = new RecipeLineRow(itemIcons, buildingIcons, button);
line->setAttribute(Qt::WA_TransparentForMouseEvents, true);
face->addWidget(line);
line->setLine(option.line);
}
if (!option.tooltip.isEmpty())
{
button->setToolTip(option.tooltip);
}
button->setMinimumHeight(40);
grid->addWidget(button, i / columnCount, i % columnCount);
listLayout->addWidget(button);
m_optionIds.push_back(option.id);
const int index = i;
@@ -153,6 +177,9 @@ RecipeSelectionDialog::RecipeSelectionDialog(
onOptionClicked(index);
});
}
listLayout->addStretch(1);
scrollArea->setWidget(list);
}
std::optional<std::string> RecipeSelectionDialog::getChosenId() const

View File

@@ -8,11 +8,13 @@
#include <QString>
#include "BuildingType.h"
#include "RecipeLineRow.h"
struct GameConfig;
class BuildingIconCache;
class ItemIconCache;
class Simulation;
class QPushButton;
class ItemIconCache;
// One selectable entry in the recipe/schematic selection dialog
// (REQ-UI-SELECT-BUTTON). The "(None)" entry uses an empty id.
@@ -20,23 +22,23 @@ struct RecipeSelectionOption
{
std::string id;
QString caption;
QString tooltip;
// Id of the item whose icon is shown on the option button (REQ-UI-RECIPE-ICON);
// empty for the "(None)" option and for Shipyard schematics, which keep their
// caption. When set but no icon file exists, the button falls back to the caption.
std::string iconItemId;
// What the option makes, drawn beneath its caption on the button
// (REQ-UI-SELECT-OPTIONS). Empty for the "(None)" option, which is a caption alone.
// A ship schematic fills the inputs and the time and leaves the outputs empty: a
// ship is not an item and has no icon, so the caption is what it produces.
RecipeLineRow::Spec line;
};
// Builds the lock-aware list of selectable options for a production building
// of the given type, with display captions and info tooltips
// (REQ-UI-SELECT-BUTTON, REQ-UI-SELECT-TOOLTIP). The first entry is always a
// of the given type, with display captions and recipe lines
// (REQ-UI-SELECT-BUTTON, REQ-UI-SELECT-OPTIONS). The first entry is always a
// "(None)" option with an empty id. Shared by the selection dialog and the
// panel selection button so both render identical captions and tooltips, and
// panel selection button so both render identical captions, and
// usable for construction sites which have no Building yet (REQ-BLD-SITE-CONFIG).
std::vector<RecipeSelectionOption> buildRecipeSelectionOptions(
BuildingType type, Simulation& sim, const GameConfig& config);
// Modal dialog showing a grid of option buttons (REQ-UI-SELECT-BUTTON). The
// Modal dialog listing the options in one vertical column (REQ-UI-SELECT-OPTIONS). The
// game is paused by the caller while it is open. Clicking an option selects it
// and closes the dialog; dismissing it (close/Esc) leaves no choice.
class RecipeSelectionDialog : public QDialog
@@ -44,12 +46,10 @@ class RecipeSelectionDialog : public QDialog
Q_OBJECT
public:
// itemIcons is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); used to
// render recipe options icon-only (REQ-UI-RECIPE-ICON). Options whose item has
// no icon file fall back to their caption text. Not owned.
// The icon caches draw each option's recipe line (REQ-UI-ITEM-ICON). Not owned.
RecipeSelectionDialog(const std::vector<RecipeSelectionOption>& options,
const QString& title, ItemIconCache* itemIcons,
QWidget* parent = nullptr);
BuildingIconCache* buildingIcons, QWidget* parent = nullptr);
std::optional<std::string> getChosenId() const;

View File

@@ -1,52 +0,0 @@
#include "RecipeTooltip.h"
#include <QObject>
#include <QStringList>
#include "DisplayName.h"
#include "RecipesConfig.h"
namespace
{
QString itemLine(const std::string& itemId, int amount)
{
return QStringLiteral(" ")
+ QString::fromStdString(toDisplayName(itemId))
+ QStringLiteral(" x ") + QString::number(amount);
}
} // namespace
QString buildRecipeTooltip(const RecipeDef& recipe)
{
QStringList lines;
lines << QObject::tr("Recipe: %1")
.arg(QString::fromStdString(toDisplayName(recipe.id)));
if (recipe.inputs.empty())
{
lines << QObject::tr("Inputs: none");
}
else
{
lines << QObject::tr("Inputs:");
for (const RecipeIngredient& ingredient : recipe.inputs)
{
lines << itemLine(ingredient.item, ingredient.amount);
}
}
lines << QObject::tr("Completion time: %1 s").arg(recipe.durationSeconds);
if (!recipe.outputs.empty())
{
lines << QObject::tr("Produces:");
for (const RecipeOutput& output : recipe.outputs)
{
lines << itemLine(output.item, output.amount);
}
}
return lines.join('\n');
}

View File

@@ -1,11 +0,0 @@
#pragma once
#include <QString>
struct RecipeDef;
// Builds the recipe info tooltip text (REQ-UI-SELECT-TOOLTIP): the recipe name,
// each input item name and quantity, the completion time, and the produced
// output item name and quantity. Shared by the recipe-selection dialog and the
// schematic choice dialog's "Unlocks recipes:" list so both render identically.
QString buildRecipeTooltip(const RecipeDef& recipe);

View File

@@ -6,12 +6,35 @@
#include <QVBoxLayout>
#include "DisplayName.h"
#include "RecipeTooltip.h"
#include "RecipeLineRow.h"
#include "RecipesConfig.h"
namespace
{
std::vector<RecipeLineRow::Amount> toAmounts(
const std::vector<RecipeIngredient>& ingredients)
{
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(ingredients.size());
for (const RecipeIngredient& ingredient : ingredients)
{
amounts.push_back(RecipeLineRow::Amount{ ingredient.item, ingredient.amount });
}
return amounts;
}
std::vector<RecipeLineRow::Amount> toAmounts(const std::vector<RecipeOutput>& outputs)
{
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(outputs.size());
for (const RecipeOutput& output : outputs)
{
amounts.push_back(RecipeLineRow::Amount{ output.item, output.amount });
}
return amounts;
}
QString grantKindLabel(SchematicType type)
{
switch (type)
@@ -28,7 +51,8 @@ QString grantKindLabel(SchematicType type)
SchematicChoiceDialog::SchematicChoiceDialog(
const std::vector<SchematicChoiceOption>& options,
const RecipesConfig& recipes,
const RecipesConfig& recipes, ItemIconCache* itemIcons,
BuildingIconCache* buildingIcons,
QWidget* parent)
: QDialog(parent)
, m_chosenIndex(0)
@@ -56,7 +80,12 @@ SchematicChoiceDialog::SchematicChoiceDialog(
QWidget* card = new QWidget(this);
QVBoxLayout* cardLayout = new QVBoxLayout(card);
card->setStyleSheet("QWidget { border: 1px solid gray; padding: 8px; }");
// Scoped to the card by object name. An unscoped "QWidget" selector cascades to
// every descendant, which boxed each label and each icon of the recipe lines
// inside it as well.
card->setObjectName(QStringLiteral("schematicChoiceCard"));
card->setStyleSheet(QStringLiteral(
"QWidget#schematicChoiceCard { border: 1px solid gray; padding: 8px; }"));
QLabel* nameLabel = new QLabel(QString::fromStdString(option.displayName), card);
QFont nameFont = nameLabel->font();
@@ -108,14 +137,24 @@ SchematicChoiceDialog::SchematicChoiceDialog(
{
for (const std::string& recipeId : option.newlyUnlockedRecipeIds)
{
QLabel* recipeLabel = new QLabel(
QString::fromStdString(toDisplayName(recipeId)), card);
recipeLabel->setAlignment(Qt::AlignCenter);
if (const RecipeDef* def = recipes.findRecipeDef(recipeId))
{
recipeLabel->setToolTip(buildRecipeTooltip(*def));
}
cardLayout->addWidget(recipeLabel);
const RecipeDef* def = recipes.findRecipeDef(recipeId);
if (def == nullptr) { continue; }
// The recipe drawn as it is everywhere else, led by the building
// that runs it and its name, so the line says everything there is
// to say about it and carries no tooltip (REQ-DEF-SCHEMATIC-DROP).
RecipeLineRow::Spec spec;
spec.building = def->building;
spec.name = QString::fromStdString(toDisplayName(def->id));
spec.inputs = toAmounts(def->inputs);
spec.outputs = toAmounts(def->outputs);
spec.durationSeconds = def->durationSeconds;
RecipeLineRow* line =
new RecipeLineRow(itemIcons, buildingIcons, card);
line->setCardChrome(true);
cardLayout->addWidget(line);
line->setLine(spec);
}
}
}

View File

@@ -7,14 +7,19 @@
#include "SchematicChoiceOption.h"
struct RecipesConfig;
class BuildingIconCache;
class ItemIconCache;
class SchematicChoiceDialog : public QDialog
{
Q_OBJECT
public:
// The icon caches draw the recipe lines of the "Unlocks recipes" list
// (REQ-DEF-SCHEMATIC-DROP, REQ-UI-ITEM-ICON, REQ-UI-BUILD-ICON). Not owned.
SchematicChoiceDialog(const std::vector<SchematicChoiceOption>& options,
const RecipesConfig& recipes,
const RecipesConfig& recipes, ItemIconCache* itemIcons,
BuildingIconCache* buildingIcons,
QWidget* parent = nullptr);
int getChosenIndex() const;

View File

@@ -5,11 +5,16 @@
#include <functional>
#include "DisplayName.h"
#include "OptionButton.h"
#include "ProductionRules.h"
#include "RecipeLineRow.h"
#include "SectionBox.h"
#include <QGridLayout>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
@@ -22,6 +27,18 @@
namespace
{
std::vector<RecipeLineRow::Amount> toAmounts(
const std::vector<RecipeIngredient>& ingredients)
{
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(ingredients.size());
for (const RecipeIngredient& ingredient : ingredients)
{
amounts.push_back(RecipeLineRow::Amount{ ingredient.item, ingredient.amount });
}
return amounts;
}
const int kCellSize = 32;
// Empty ship tiles pulse between this grey and white at 1 Hz while a module is
@@ -401,9 +418,11 @@ ShipLayoutDialog::ShipLayoutDialog(const GameConfig* config,
std::vector<ShipLayoutBlueprint>& allBlueprints,
std::set<std::string> unlockedModuleIds,
bool debugDraw,
ItemIconCache* itemIcons,
QWidget* parent)
: QDialog(parent)
, m_config(config)
, m_itemIcons(itemIcons)
, m_shipId(shipId)
, m_unlockedModuleIds(std::move(unlockedModuleIds))
, m_rows(0)
@@ -463,10 +482,22 @@ ShipLayoutDialog::ShipLayoutDialog(const GameConfig* config,
// Middle: three-column area (stats | module buttons | blueprints).
QHBoxLayout* columnsLayout = new QHBoxLayout();
// Left column: ship stats panel.
// Left column: ship stats panel, and beneath it what the layout being configured
// would cost to build (REQ-MOD-UI-DIALOG). The cost sits outside the stats panel
// because that widget is shared with the live ship card and the balancing tool,
// neither of which costs anything -- and the balancing tool is deliberately built
// without the item icons this line draws with.
QVBoxLayout* leftLayout = new QVBoxLayout();
m_statsPanel = new ShipStatsPanel(config, this);
m_statsPanel->setDebugDrawEnabled(m_debugDraw);
columnsLayout->addWidget(m_statsPanel);
leftLayout->addWidget(m_statsPanel);
m_buildCostSection = new SectionBox(tr("Build cost"), this);
m_buildCostLine = new RecipeLineRow(m_itemIcons, nullptr, m_buildCostSection);
m_buildCostSection->getContentLayout()->addWidget(m_buildCostLine);
leftLayout->addWidget(m_buildCostSection);
leftLayout->addStretch(1);
columnsLayout->addLayout(leftLayout);
// Center column: module selection buttons.
QVBoxLayout* centerLayout = new QVBoxLayout();
@@ -487,11 +518,34 @@ ShipLayoutDialog::ShipLayoutDialog(const GameConfig* config,
m_moduleButtons.push_back(nullptr);
continue;
}
const QString label = QString::fromStdString(toDisplayName(def.id))
+ "\n" + QString::fromStdString(def.glyph);
QPushButton* btn = new QPushButton(label, this);
// The module's name over what it costs -- its materials and the production time
// it adds (REQ-MOD-UI-DIALOG). The glyph is how a module is identified on the
// layout grid, not here. Both children are transparent to the mouse so a click
// anywhere on the face still reaches the button.
OptionButton* btn = new OptionButton(this);
btn->setCheckable(true);
btn->setFixedHeight(48);
QVBoxLayout* face = new QVBoxLayout(btn);
face->setContentsMargins(8, 4, 8, 4);
face->setSpacing(1);
QLabel* nameLabel =
new QLabel(QString::fromStdString(toDisplayName(def.id)), btn);
nameLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true);
face->addWidget(nameLabel);
RecipeLineRow::Spec cost;
cost.inputs = toAmounts(def.materials);
cost.durationSeconds = def.productionTimeSeconds;
cost.durationIsAddition = true;
RecipeLineRow* costLine = new RecipeLineRow(m_itemIcons, nullptr, btn);
costLine->setAttribute(Qt::WA_TransparentForMouseEvents, true);
face->addWidget(costLine);
costLine->setLine(cost);
// The config tooltip stays: it says what the module does, which the cost line
// does not (REQ-MOD-UI-MODULE-TOOLTIP).
if (def.tooltip)
{
btn->setToolTip(QString::fromStdString(*def.tooltip));
@@ -731,6 +785,29 @@ void ShipLayoutDialog::updateGridWidget()
void ShipLayoutDialog::updateStats()
{
m_statsPanel->refresh(m_shipId, m_placedModules);
// What the layout as it currently stands would cost to build, so the price follows
// every placement and removal (REQ-MOD-UI-DIALOG). The sums come from the
// simulation's own rules rather than being added up a second time here
// (REQ-MOD-MATERIALS, REQ-MOD-PRODUCTION-TIME).
ShipLayoutConfig layout;
layout.placedModules = m_placedModules;
const std::map<std::string, int> materials =
computeShipyardRequiredMaterials(*m_config, m_shipId, layout);
RecipeLineRow::Spec cost;
cost.inputs.reserve(materials.size());
for (const std::pair<const std::string, int>& entry : materials)
{
cost.inputs.push_back(RecipeLineRow::Amount{ entry.first, entry.second });
}
cost.durationSeconds =
computeShipyardProductionTimeSeconds(*m_config, m_shipId, layout);
m_buildCostLine->setLine(cost);
// A schematic costing no materials at all has no line to draw, and the section then
// stays out of the way.
m_buildCostSection->setVisible(!cost.inputs.empty());
}
bool ShipLayoutDialog::canPlaceModule(const ModuleDef& def, QPoint position,

View File

@@ -14,7 +14,10 @@
#include "ShipLayout.h"
#include "ShipLayoutBlueprint.h"
class ItemIconCache;
class QPushButton;
class RecipeLineRow;
class SectionBox;
class ShipStatsPanel;
class ShipLayoutDialog : public QDialog
@@ -22,12 +25,15 @@ class ShipLayoutDialog : public QDialog
Q_OBJECT
public:
// itemIcons draws what each module costs and what the layout costs in total
// (REQ-MOD-UI-DIALOG, REQ-MOD-UI-STATS-PANEL). Not owned.
ShipLayoutDialog(const GameConfig* config,
const std::string& shipId,
const ShipLayoutConfig& currentLayout,
std::vector<ShipLayoutBlueprint>& allBlueprints,
std::set<std::string> unlockedModuleIds,
bool debugDraw,
ItemIconCache* itemIcons,
QWidget* parent = nullptr);
std::optional<ShipLayoutConfig> getResult() const;
@@ -60,6 +66,7 @@ private:
void loadLayoutBlueprint(const std::vector<PlacedModule>& modules);
const GameConfig* m_config;
ItemIconCache* m_itemIcons;
std::string m_shipId;
std::set<std::string> m_unlockedModuleIds;
std::vector<std::string> m_shipLayout;
@@ -81,6 +88,8 @@ private:
QPushButton* m_removeButton;
QWidget* m_gridWidget;
ShipStatsPanel* m_statsPanel;
SectionBox* m_buildCostSection;
RecipeLineRow* m_buildCostLine;
bool m_debugDraw;
std::optional<ShipLayoutConfig> m_result;

View File

@@ -541,37 +541,14 @@ void WorldRenderer::drawPortItems(QPainter& painter, const WorldCoordinates& coo
void WorldRenderer::drawWorldItem(QPainter& painter, const std::string& itemId,
QPointF center, float halfPx)
{
if (!m_itemIcons) { return; }
// The colored square carrying the item's icon (REQ-GW-TILE-SIZE, REQ-UI-ITEM-ICON).
// The composition lives in the icon cache, which draws it the same way here and in
// the UI's item displays, so an item reads the same on a belt as in a panel.
const QRectF itemRect(center.x() - halfPx, center.y() - halfPx,
halfPx * 2, halfPx * 2);
// The colored square from visuals.toml (REQ-GW-TILE-SIZE) backs every item, icon or
// not: it is what gives the item contrast against the tile beneath it, and its dark
// outline is what separates neighbouring items where they overlap on a belt.
const std::map<std::string, ItemVisuals>::const_iterator it =
m_visuals.items.find(itemId);
if (it != m_visuals.items.end())
{
painter.fillRect(itemRect, it->second.fill);
painter.setPen(QPen(it->second.outline, 1));
painter.setBrush(Qt::NoBrush);
painter.drawRect(itemRect);
}
if (!m_itemIcons || !m_itemIcons->hasIcon(itemId)) { return; }
// The icon goes on top, inset so a frame of the square's color stays visible all
// around it (REQ-UI-ITEM-ICON). The inset is needed because each icon's viewBox is
// cropped tight to its artwork: drawn at the full rect, a solid icon would cover the
// square entirely. It is rasterized once at the inset pixel size and cached, so this
// is a plain pixmap blit per frame.
constexpr double kIconInsetFraction = 0.15;
const double inset = kIconInsetFraction * static_cast<double>(halfPx * 2.0f);
const QRectF iconRect = itemRect.adjusted(inset, inset, -inset, -inset);
int sizePx = qRound(iconRect.width());
if (sizePx < 1) { sizePx = 1; }
painter.drawPixmap(iconRect, m_itemIcons->getPixmap(itemId, sizePx),
QRectF(0, 0, sizePx, sizePx));
m_itemIcons->paintItem(painter, itemRect, itemId);
}
void WorldRenderer::drawBeltItems(QPainter& painter, const WorldCoordinates& coordinates,

View File

@@ -10,7 +10,7 @@
#include "DisplayName.h"
#include "FactoryQueries.h"
#include "ProductionSection.h"
#include "RecipeSummaryRow.h"
#include "RecipeLineRow.h"
#include "SectionBox.h"
#include "SelectionNames.h"
#include "Simulation.h"
@@ -18,13 +18,13 @@
namespace
{
std::vector<RecipeSummaryRow::Amount> toAmounts(const std::map<std::string, int>& map)
std::vector<RecipeLineRow::Amount> toAmounts(const std::map<std::string, int>& map)
{
std::vector<RecipeSummaryRow::Amount> amounts;
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(map.size());
for (const std::pair<const std::string, int>& entry : map)
{
amounts.push_back(RecipeSummaryRow::Amount{ entry.first, entry.second });
amounts.push_back(RecipeLineRow::Amount{ entry.first, entry.second });
}
return amounts;
}
@@ -66,17 +66,17 @@ BufferedBuildingContent::BufferedBuildingContent(const SelectionContext& context
{
// The summary is configuration -- what the building will do -- so it sits with the
// selection control and is shown for a construction site too (REQ-UI-RECIPE-SUMMARY).
m_recipeSummary = new RecipeSummaryRow(context.itemIcons, this);
m_recipeSummary = new RecipeLineRow(context.itemIcons, context.buildingIcons, this);
getConfigurationLayout()->addWidget(m_recipeSummary);
m_inputSection = new SectionBox(tr("Input buffers"), this);
m_inputChips = new ItemChipRow(context.itemIcons, m_inputSection);
m_inputChips = new ItemChipRow(context, m_inputSection);
m_inputSection->getContentLayout()->addWidget(m_inputChips);
m_production = new ProductionSection(this);
m_outputSection = new SectionBox(tr("Output buffer"), this);
m_outputChips = new ItemChipRow(context.itemIcons, m_outputSection);
m_outputChips = new ItemChipRow(context, m_outputSection);
m_outputSection->getContentLayout()->addWidget(m_outputChips);
// In the direction the materials flow: what goes in, what is being made of it, what
@@ -98,10 +98,14 @@ void BufferedBuildingContent::refreshConfiguration()
setBuildingIdentity(target.type, getBuildingTypeName(target.type));
// The card already names the building in its header, so the summary states the cycle
// alone -- no building chip, no recipe name (REQ-UI-RECIPE-SUMMARY).
const CycleInfo cycle = getCycleInfo(target);
m_recipeSummary->setSummary(toAmounts(cycle.perCycleInputs),
toAmounts(cycle.perCycleOutputs),
cycle.durationSeconds);
RecipeLineRow::Spec summary;
summary.inputs = toAmounts(cycle.perCycleInputs);
summary.outputs = toAmounts(cycle.perCycleOutputs);
summary.durationSeconds = cycle.durationSeconds;
m_recipeSummary->setLine(summary);
refreshControls(target);
}

View File

@@ -11,7 +11,7 @@
struct Building;
struct BuildingTarget;
class ProductionSection;
class RecipeSummaryRow;
class RecipeLineRow;
class SectionBox;
// Shared body of the four cards that show one building with buffers -- the Miner and
@@ -74,7 +74,7 @@ private:
BuildingId m_id;
RecipeSummaryRow* m_recipeSummary;
RecipeLineRow* m_recipeSummary;
// Input buffers, production progress, output buffer -- in that order, so the card
// reads the way the materials flow (REQ-UI-SINGLE-SELECTION).

View File

@@ -14,7 +14,7 @@ SET(HDRS
${CMAKE_CURRENT_SOURCE_DIR}/EmptyNote.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemChip.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemChipRow.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSummaryRow.h
${CMAKE_CURRENT_SOURCE_DIR}/ItemTooltip.h
${CMAKE_CURRENT_SOURCE_DIR}/ProductionSection.h
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionControl.h
${CMAKE_CURRENT_SOURCE_DIR}/ClearBeltControl.h
@@ -49,7 +49,7 @@ SET(SRCS
${CMAKE_CURRENT_SOURCE_DIR}/EmptyNote.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemChip.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemChipRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSummaryRow.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ItemTooltip.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ProductionSection.cpp
${CMAKE_CURRENT_SOURCE_DIR}/RecipeSelectionControl.cpp
${CMAKE_CURRENT_SOURCE_DIR}/ClearBeltControl.cpp

View File

@@ -23,7 +23,7 @@ HqContent::HqContent(const SelectionContext& context, const SelectionRequest& re
m_hpBar = new BarRow(tr("HP"), this);
m_stockSection = new SectionBox(tr("Building blocks"), this);
m_stockChips = new ItemChipRow(context.itemIcons, m_stockSection);
m_stockChips = new ItemChipRow(context, m_stockSection);
m_stockSection->getContentLayout()->addWidget(m_stockChips);
// HP first, as on every card that has it (REQ-UI-SELECTION-CARD, REQ-UI-HQ-PANEL).

View File

@@ -1,11 +1,15 @@
#include "ItemChip.h"
#include <QCursor>
#include <QFont>
#include <QHBoxLayout>
#include <QLabel>
#include <QPalette>
#include <QTimer>
#include <QVBoxLayout>
#include "ItemTooltip.h"
namespace
{
@@ -13,11 +17,18 @@ namespace
const int kCountSizeRisePt = 2;
const int kSubLineSizeDropPt = 1;
// How long the cursor rests on a chip before its tooltip appears, in milliseconds.
// Matches the feel of an ordinary tooltip, which this one replaces (REQ-UI-ITEM-TOOLTIP).
const int kHoverDelayMs = 500;
} // namespace
ItemChip::ItemChip(const QPixmap& icon, QWidget* parent)
ItemChip::ItemChip(const SelectionContext& context, const std::string& itemId,
const QPixmap& icon, QWidget* parent)
: QWidget(parent)
, m_context(context)
, m_itemId(itemId)
{
// Its own boxed chrome, drawn with palette colors like the rest of the panel's
// furniture rather than from visuals.toml, which is for world rendering.
@@ -58,6 +69,11 @@ ItemChip::ItemChip(const QPixmap& icon, QWidget* parent)
layout->addWidget(m_iconLabel);
layout->addWidget(text);
m_hoverTimer = new QTimer(this);
m_hoverTimer->setSingleShot(true);
m_hoverTimer->setInterval(kHoverDelayMs);
connect(m_hoverTimer, &QTimer::timeout, this, &ItemChip::showTooltip);
}
void ItemChip::setCount(const QString& count)
@@ -70,3 +86,28 @@ void ItemChip::setSubLine(const QString& subLine)
m_subLineLabel->setText(subLine);
m_subLineLabel->setVisible(!subLine.isEmpty());
}
void ItemChip::enterEvent(QEvent* event)
{
m_hoverTimer->start();
QWidget::enterEvent(event);
}
void ItemChip::leaveEvent(QEvent* event)
{
m_hoverTimer->stop();
if (m_tooltip != nullptr)
{
m_tooltip->hide();
}
QWidget::leaveEvent(event);
}
void ItemChip::showTooltip()
{
if (m_tooltip == nullptr)
{
m_tooltip = new ItemTooltip(m_context, m_itemId, this);
}
m_tooltip->showAt(QCursor::pos());
}

View File

@@ -1,28 +1,51 @@
#pragma once
#include <string>
#include <QPixmap>
#include <QString>
#include <QWidget>
#include "SelectionContext.h"
class ItemTooltip;
class QEvent;
class QLabel;
class QTimer;
// One buffered item: its icon, its count in a larger type, and a sub-line beneath the
// count (REQ-UI-SINGLE-SELECTION). Boxed so a row of them reads as separate quantities
// rather than as a run of text.
//
// Hovering it explains where its item comes from (REQ-UI-ITEM-TOOLTIP).
class ItemChip : public QWidget
{
Q_OBJECT
public:
// An empty icon leaves the icon off and the chip laid out around the text alone.
ItemChip(const QPixmap& icon, QWidget* parent = nullptr);
ItemChip(const SelectionContext& context, const std::string& itemId,
const QPixmap& icon, QWidget* parent = nullptr);
void setCount(const QString& count);
// Left empty for an item with nothing to say beneath its count.
void setSubLine(const QString& subLine);
protected:
void enterEvent(QEvent* event) override;
void leaveEvent(QEvent* event) override;
private:
QLabel* m_iconLabel;
QLabel* m_countLabel;
QLabel* m_subLineLabel;
void showTooltip();
SelectionContext m_context;
std::string m_itemId;
QLabel* m_iconLabel;
QLabel* m_countLabel;
QLabel* m_subLineLabel;
// Held back so a cursor crossing the chip on its way elsewhere does not flash the
// tooltip, the way an ordinary tooltip is.
QTimer* m_hoverTimer;
// Built on the first hover, because most chips are never hovered at all.
ItemTooltip* m_tooltip = nullptr;
};

View File

@@ -8,8 +8,9 @@
namespace
{
// Size the item icon is drawn at inside a chip, in device-independent pixels.
const int kChipIconSizePx = 18;
// Size the item's colored square is drawn at inside a chip, in device-independent
// pixels. Larger than the artwork it carries, which the square insets (REQ-UI-ITEM-ICON).
const int kChipIconSizePx = 22;
// Chips per row. Two fit the panel's capped width side by side; a third would force the
// counts to shrink.
@@ -18,9 +19,9 @@ const int kChipsPerRow = 2;
} // namespace
ItemChipRow::ItemChipRow(ItemIconCache* itemIcons, QWidget* parent)
ItemChipRow::ItemChipRow(const SelectionContext& context, QWidget* parent)
: QWidget(parent)
, m_itemIcons(itemIcons)
, m_context(context)
{
m_layout = new QGridLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
@@ -64,13 +65,13 @@ void ItemChipRow::rebuildChips(const std::vector<Entry>& entries)
for (std::size_t index = 0; index < entries.size(); ++index)
{
const std::string& itemId = entries[index].itemId;
// A missing icon file is not an error (REQ-UI-ITEM-ICON): the chip is then laid
// out around its count alone.
const QPixmap icon = m_itemIcons->hasIcon(itemId)
? m_itemIcons->getPixmap(itemId, kChipIconSizePx)
: QPixmap();
// The item's icon on its colored square (REQ-UI-ITEM-ICON). A missing icon file
// is not an error: the chip then carries the square alone, and only an item with
// no square either leaves the chip laid out around its count alone.
const QPixmap icon =
m_context.itemIcons->getSquarePixmap(itemId, kChipIconSizePx);
ItemChip* chip = new ItemChip(icon, this);
ItemChip* chip = new ItemChip(m_context, itemId, icon, this);
m_layout->addWidget(chip, static_cast<int>(index) / kChipsPerRow,
static_cast<int>(index) % kChipsPerRow);
// Shown right away, because the panel measures itself as soon as this returns. A

View File

@@ -6,8 +6,9 @@
#include <QString>
#include <QWidget>
#include "SelectionContext.h"
class ItemChip;
class ItemIconCache;
class QGridLayout;
// The buffered items of one building, each as a chip carrying the item's icon, its
@@ -28,16 +29,18 @@ public:
QString subLine;
};
// itemIcons is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); an item with
// no icon file simply shows no icon, which is not an error. Not owned.
explicit ItemChipRow(ItemIconCache* itemIcons, QWidget* parent = nullptr);
// The context supplies the icon cache each chip draws its item with
// (REQ-UI-ITEM-ICON) -- an item with no icon file simply shows no icon, which is not
// an error -- and what a chip's tooltip reads to explain its item
// (REQ-UI-ITEM-TOOLTIP).
explicit ItemChipRow(const SelectionContext& context, QWidget* parent = nullptr);
void setEntries(const std::vector<Entry>& entries);
private:
void rebuildChips(const std::vector<Entry>& entries);
ItemIconCache* m_itemIcons;
SelectionContext m_context;
QGridLayout* m_layout;
std::vector<std::string> m_itemIds; // what the chips currently stand for
std::vector<ItemChip*> m_chips;

View File

@@ -0,0 +1,166 @@
#include "ItemTooltip.h"
#include <QFont>
#include <QGuiApplication>
#include <QLabel>
#include <QLayoutItem>
#include <QPalette>
#include <QRect>
#include <QScreen>
#include <QVBoxLayout>
#include "DisplayName.h"
#include "GameConfig.h"
#include "ItemProducers.h"
#include "RecipeLineRow.h"
#include "RecipesConfig.h"
#include "Simulation.h"
namespace
{
// Gap between the cursor and the tooltip's corner, in device-independent pixels. Wide
// enough that the cursor never covers the heading.
const int kCursorOffsetPx = 16;
std::vector<RecipeLineRow::Amount> toAmounts(
const std::vector<RecipeIngredient>& ingredients)
{
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(ingredients.size());
for (const RecipeIngredient& ingredient : ingredients)
{
amounts.push_back(RecipeLineRow::Amount{ ingredient.item, ingredient.amount });
}
return amounts;
}
std::vector<RecipeLineRow::Amount> toAmounts(const std::vector<RecipeOutput>& outputs)
{
std::vector<RecipeLineRow::Amount> amounts;
amounts.reserve(outputs.size());
for (const RecipeOutput& output : outputs)
{
amounts.push_back(RecipeLineRow::Amount{ output.item, output.amount });
}
return amounts;
}
// The screen the cursor is on, falling back to the primary screen when the position is
// on none of them (a cursor between two screens of different heights).
QRect availableScreenRect(const QPoint& globalPos)
{
const QScreen* screen = QGuiApplication::screenAt(globalPos);
if (screen == nullptr)
{
screen = QGuiApplication::primaryScreen();
}
return (screen != nullptr) ? screen->availableGeometry() : QRect();
}
} // namespace
ItemTooltip::ItemTooltip(const SelectionContext& context, const std::string& itemId,
QWidget* parent)
: QFrame(parent, Qt::ToolTip)
, m_context(context)
, m_itemId(itemId)
{
// The palette's tooltip colors behind a themed border, so it reads as a tooltip
// rather than as a stray window.
setFrameShape(QFrame::StyledPanel);
setAutoFillBackground(true);
QPalette tooltipPalette = palette();
tooltipPalette.setColor(QPalette::Window,
tooltipPalette.color(QPalette::ToolTipBase));
tooltipPalette.setColor(QPalette::WindowText,
tooltipPalette.color(QPalette::ToolTipText));
setPalette(tooltipPalette);
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(6, 4, 6, 4);
m_layout->setSpacing(2);
}
void ItemTooltip::showAt(const QPoint& globalPos)
{
rebuild();
adjustSize();
// Kept on the screen the cursor is on: a tooltip for a chip near the right or
// bottom edge would otherwise be cut off.
const QRect screen = availableScreenRect(globalPos);
QPoint topLeft(globalPos.x() + kCursorOffsetPx, globalPos.y() + kCursorOffsetPx);
if (screen.isValid())
{
topLeft.setX(qMax(screen.left(),
qMin(topLeft.x(), screen.right() - width() + 1)));
topLeft.setY(qMax(screen.top(),
qMin(topLeft.y(), screen.bottom() - height() + 1)));
}
move(topLeft);
show();
}
void ItemTooltip::rebuild()
{
while (QLayoutItem* item = m_layout->takeAt(0))
{
if (item->widget())
{
item->widget()->deleteLater();
}
delete item;
}
// The heading names the item. For an input chip this is the only place it is named
// at all, since such a chip carries a count and no name (REQ-UI-SINGLE-SELECTION).
QLabel* heading =
new QLabel(QString::fromStdString(toDisplayName(m_itemId)), this);
QFont headingFont = heading->font();
headingFont.setBold(true);
heading->setFont(headingFont);
m_layout->addWidget(heading);
heading->show();
const ItemProduction production =
findItemProduction(m_itemId, *m_context.sim, *m_context.config);
// Scrap is salvaged from debris rather than crafted (REQ-RES-DEBRIS-DROP), so it
// says where it comes from in place of the caption and lists nothing.
QLabel* caption = new QLabel(production.origin == ItemOrigin::Salvaged
? tr("Salvaged from debris")
: tr("Produced by"), this);
m_layout->addWidget(caption);
caption->show();
if (production.origin == ItemOrigin::Undiscovered)
{
// Made somehow, but by nothing the player has unlocked -- named without being
// shown a path they cannot take yet (REQ-UI-ITEM-TOOLTIP).
QLabel* undiscovered = new QLabel(tr("Undiscovered"), this);
m_layout->addWidget(undiscovered);
undiscovered->show();
return;
}
for (const RecipeDef* recipe : production.recipes)
{
RecipeLineRow::Spec spec;
spec.building = recipe->building;
spec.name = QString::fromStdString(toDisplayName(recipe->id));
spec.inputs = toAmounts(recipe->inputs);
spec.outputs = toAmounts(recipe->outputs);
spec.durationSeconds = recipe->durationSeconds;
// Boxed, because an item with several producers stacks several of these and a run
// of bare lines reads as one field of icons (REQ-UI-ITEM-TOOLTIP).
RecipeLineRow* line =
new RecipeLineRow(m_context.itemIcons, m_context.buildingIcons, this);
line->setCardChrome(true);
m_layout->addWidget(line);
line->setLine(spec);
}
}

View File

@@ -0,0 +1,36 @@
#pragma once
#include <string>
#include <QFrame>
#include "SelectionContext.h"
class QVBoxLayout;
// The tooltip an item chip shows on hover: the item's name, and every way the player
// can currently produce it, each drawn as a recipe line (REQ-UI-ITEM-TOOLTIP).
//
// A window of its own rather than a Qt tooltip, because Qt's are text and this one is
// drawn -- item squares, building chips and all. It is a Qt::ToolTip window, so it
// floats above everything and takes no input.
class ItemTooltip : public QFrame
{
Q_OBJECT
public:
ItemTooltip(const SelectionContext& context, const std::string& itemId,
QWidget* parent = nullptr);
// Rebuilds the content and shows the tooltip near the given screen position, kept
// inside the screen. Rebuilt on every show because what produces an item changes as
// the player unlocks recipes (REQ-LOCK-UI-RECIPE).
void showAt(const QPoint& globalPos);
private:
void rebuild();
SelectionContext m_context;
std::string m_itemId;
QVBoxLayout* m_layout;
};

View File

@@ -45,13 +45,14 @@ void RecipeSelectionControl::setRecipeId(const std::string& recipeId)
if (option.id == recipeId && !option.id.empty())
{
m_button->setText(option.caption);
m_button->setToolTip(option.tooltip);
return;
}
}
// No tooltip of its own: what the building has selected is drawn beneath the button
// as the recipe summary, and where its items come from is reachable by hovering the
// card's item chips (REQ-UI-SELECT-BUTTON, REQ-UI-ITEM-TOOLTIP).
m_button->setText(m_type == BuildingType::Shipyard
? tr("Select schematic")
: tr("Select recipe"));
m_button->setToolTip(QString());
}

View File

@@ -1,120 +0,0 @@
#include "RecipeSummaryRow.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QLayoutItem>
#include <QPixmap>
#include "ItemIconCache.h"
namespace
{
// Size the item icons are drawn at on the summary line, in device-independent pixels.
const int kSummaryIconSizePx = 14;
// Adds a freshly built label to the summary and shows it.
//
// The show is what makes it count: a widget created under an already-visible parent
// starts hidden, and a layout treats a hidden item as empty, so an unshown label would
// add nothing to the size hint the panel measures itself against as soon as this
// returns.
void addAndShow(QHBoxLayout* layout, QLabel* label)
{
layout->addWidget(label);
label->show();
}
} // namespace
RecipeSummaryRow::RecipeSummaryRow(ItemIconCache* itemIcons, QWidget* parent)
: QWidget(parent)
, m_itemIcons(itemIcons)
{
m_layout = new QHBoxLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
m_layout->setSpacing(4);
hide();
}
void RecipeSummaryRow::setSummary(const std::vector<Amount>& inputs,
const std::vector<Amount>& outputs,
double durationSeconds)
{
if (outputs.empty() && inputs.empty())
{
// Forgotten as well as hidden, so re-selecting the same recipe later is seen as
// a change and shows the row again.
m_inputs.clear();
m_outputs.clear();
m_durationSeconds = -1.0;
hide();
return;
}
if (inputs == m_inputs && outputs == m_outputs
&& durationSeconds == m_durationSeconds)
{
return;
}
m_inputs = inputs;
m_outputs = outputs;
m_durationSeconds = durationSeconds;
rebuild(inputs, outputs, durationSeconds);
show();
}
void RecipeSummaryRow::rebuild(const std::vector<Amount>& inputs,
const std::vector<Amount>& outputs,
double durationSeconds)
{
while (QLayoutItem* item = m_layout->takeAt(0))
{
if (item->widget())
{
item->widget()->deleteLater();
}
delete item;
}
addAmounts(inputs);
if (!inputs.empty())
{
const QChar rightArrow(0x2192); // U+2192 RIGHTWARDS ARROW
addAndShow(m_layout, new QLabel(QString(rightArrow), this));
}
addAmounts(outputs);
if (durationSeconds > 0.0)
{
const QChar middleDot(0x00B7); // U+00B7 MIDDLE DOT
addAndShow(m_layout, new QLabel(
QStringLiteral("%1 %2").arg(middleDot).arg(
tr("%1 s").arg(durationSeconds, 0, 'f', 1)), this));
}
m_layout->addStretch(1);
}
void RecipeSummaryRow::addAmounts(const std::vector<Amount>& amounts)
{
for (const Amount& entry : amounts)
{
// A missing icon file is not an error (REQ-UI-ITEM-ICON): the item's id then
// stands in for its icon.
if (m_itemIcons->hasIcon(entry.itemId))
{
QLabel* iconLabel = new QLabel(this);
iconLabel->setPixmap(
m_itemIcons->getPixmap(entry.itemId, kSummaryIconSizePx));
addAndShow(m_layout, iconLabel);
}
else
{
addAndShow(m_layout,
new QLabel(QString::fromStdString(entry.itemId), this));
}
addAndShow(m_layout, new QLabel(QString::number(entry.amount), this));
}
}

View File

@@ -1,52 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <QWidget>
class ItemIconCache;
class QHBoxLayout;
// What one production cycle does, on a line: each input item with its per-cycle amount,
// an arrow, each output with its amount, and the cycle time
// (REQ-UI-RECIPE-SUMMARY). It restates the selected recipe without the player having to
// open the selection dialog, and it is the panel's only display of the cycle time.
class RecipeSummaryRow : public QWidget
{
Q_OBJECT
public:
struct Amount
{
std::string itemId;
int amount = 0;
bool operator==(const Amount& other) const
{
return itemId == other.itemId && amount == other.amount;
}
};
// itemIcons is the window-wide per-item icon cache (REQ-UI-ITEM-ICON); an item with
// no icon file falls back to its id. Not owned.
explicit RecipeSummaryRow(ItemIconCache* itemIcons, QWidget* parent = nullptr);
// Hides the row when there is nothing selected to produce, which is how a building
// with no recipe shows no summary at all.
void setSummary(const std::vector<Amount>& inputs,
const std::vector<Amount>& outputs, double durationSeconds);
private:
void rebuild(const std::vector<Amount>& inputs, const std::vector<Amount>& outputs,
double durationSeconds);
void addAmounts(const std::vector<Amount>& amounts);
ItemIconCache* m_itemIcons;
QHBoxLayout* m_layout;
// What the row currently shows, so a refresh at tick rate rebuilds it only when the
// recipe actually changed.
std::vector<Amount> m_inputs;
std::vector<Amount> m_outputs;
double m_durationSeconds = -1.0;
};

View File

@@ -83,20 +83,11 @@ BufferedBuildingContent::CycleInfo ShipyardContent::getCycleInfo(
*getContext().config, target.recipeId, target.shipLayout);
// A shipyard's output is the ship itself, which never lands in an item buffer -- so
// the summary shows one ship rather than an item id.
info.durationSeconds = shipDef->schematic.productionTimeSeconds;
if (target.shipLayout.has_value())
{
for (const PlacedModule& placed : target.shipLayout->placedModules)
{
const ModuleDef* moduleDef =
getContext().config->modules.findModuleDef(placed.moduleId);
if (moduleDef)
{
info.durationSeconds += moduleDef->productionTimeSeconds;
}
}
}
// the summary shows no output item at all. The time is the schematic's plus its
// modules', from the same place the layout dialog's build cost reads it
// (REQ-MOD-PRODUCTION-TIME).
info.durationSeconds = computeShipyardProductionTimeSeconds(
*getContext().config, target.recipeId, target.shipLayout);
info.runsProduction = true;
return info;
}