Integrate reviewed UI transplant with main's refactor

Preserve the existing 123-improving-ui history and resolve the merge to the tested main-based transplant from 5c69e51. Retain main's graph, explorer, library, embedded editors and fixes alongside the selected panel and dialog improvements.

The resulting tree exactly matches the validated transplant. Superseded UI code and unresolved import, plugin and renderer changes are excluded from the final tree.
This commit is contained in:
chasse20 committed 2026-11-07 09:04:45 -05:00
commit 7d4e2b5bb1
155 files changed
+2235 -21496

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+57 -7
View File
@@ -1,3 +1,56 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# AGENTS.md: guide for AI agents and contributors
MaterialCraft is an open-source, native **node-based procedural material designer**: a clean-room
@@ -13,10 +66,7 @@ TextureCraft) in user-facing text: UI, window titles, About, installers, release
Machine names stay lowercase: crates (`materialcraft-*`), binaries, file names, ids
(`ai.storyteller.materialcraft`). The project format is SBS (`.sbs`). Legacy package compatibility is not required.
Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next
to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its
standards, and contribute reusable learnings back there. Shared code goes only in craft-libs
(`standards/shared-libraries.md`); otherwise copy, don't depend. TextureCraft is the sibling this
Shared code goes only in craft-libs; otherwise copy, don't depend. TextureCraft is the sibling this
repository's infrastructure (xtask, automation, packaging, docking, theme) was copied from.
The goal is full parity with the professional node-based material workflow (the same panels,
@@ -106,7 +156,7 @@ implementation, in code, docs and commits.
People trust MaterialCraft with hours of work. A malformed package, a hostile command or MCP
parameter, an odd keystroke or a full disk must produce an error the user or agent can act on,
never a panic. The shared standard is `../craftrules/standards/never-crash.md`.
never a panic.
- Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or
`unimplemented!`. Every production crate root carries
@@ -183,6 +233,6 @@ after every arc of work that builds and passes.
- `ROADMAP.md`: milestones, parity estimate and remaining effort.
- `docs/target-app-parity.md` and `docs/gaps.md`: the assessment and the work list.
- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing.
- `plan/` (local, gitignored): execution plan and notes.
- `docs/releasing.md`: release builds and signing.
- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent.
- `log/` (local, gitignored): the dev log.
+1 -5
View File
@@ -1,5 +1 @@
# MaterialCraft: instructions for Claude
Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository
(workspace map, golden rules including the asset and attribution rules, the definition of done).
Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps.
@AGENTS.md
Generated
-1
View File
@@ -2485,7 +2485,6 @@ dependencies = [
"log",
"materialcraft-engine",
"materialcraft-render",
"rayon",
"rfd",
"serde",
"serde_json",
-94
View File
@@ -1,94 +0,0 @@
# UI parity drop (re-based on main after the primitive rewrite)
What changed, per area of the reference screenshots. Everything is wired to the engine; no empty settings.
## Re-port onto main (2026-11-06)
- Built on `origin/main` (1a468e7, PR #125). Everything from the 123-improving-ui drop was re-applied in the new
layout: one type per file, new engine commands in their own module (`engine/src/resource_cmds.rs`, registered by
one line in `commands.rs`), 3D view settings in `engine/src/view3d_settings.rs`, the 3D view split into
`ui-egui/src/view3d/{actions,menus,overlays,settings,side_strip}.rs`, the explorer actions in `explorer/{actions,package_menu}.rs`,
the new-graph dialog in `new_graph_dialog.rs`, graph toolbar tools in `graph/toolbar_tools.rs`, auto conversion in `graph/auto_convert.rs`.
- Upstream features kept as they are: the material-preview assignment (View in 3D view, graph drop onto the 3D view,
`view.3d.outputs`, `view.3d.clear`), the Material assignment list now lives at the bottom of the 3D view's Materials menu;
the function and FX-Map pattern editors; `snapToGrid` from `prefs.snap_to_grid`.
- `.mcraft` is gone upstream, so everything here is SBS only: linked bitmaps are written as `<filepath>` without `binembedded`,
plugins load `.sbs` packages, the Plugin Manager installs `.sbs` files.
- Library: the reference's generator/filter groups are no longer Rust nodes ("SBS library nodes belong in SBS graphs"), so
the library shows the 26 atomic nodes, graph items, the 85 function ops (added through the function editor), the package's
graphs by kind, and the graphs of loaded plugin packages filed under each graph's `attributes.category` (else "PBR materials ▸ Plugins").
The remaining reference groups stay listed, greyed, with a 0 count.
## Menu pass (2026-11-06, late)
- Library: the "SDF functions" group is now "MCF functions"; empty reference groups explain on hover that library
packages (Tools ▸ Plugin Manager) fill them.
- Help menu points at getartcraft.com: Documentation/website → the MaterialCraft app page, Tutorials → /tutorials,
What's new → /news, System requirements → /faq, Support and feedback → /support, Discord; release notes and bug
reports stay on GitHub. Home and About carry the same links.
- Home screen: Samples shows the starter templates and the graphs of loaded library packages (click imports the graph).
- Graph toolbar quick-insert row now has every atomic node (added SVG, Text, Gradient Dynamic, Motion Blur,
Value Processor, Input Color, Input Value).
## Fixes (2026-11-07)
- Height in the 3D view: the "Material outputs" template now derives its Normal output from the Height (a
`normal` node between them) like the old base material did, so a height wired in shows as relief and shading
right away; with the normal map switched off (Material page ▸ Use maps) the relief shades from its own geometry.
- 3D view ▸ Display ▸ Preview size is a submenu (a combo box inside a menu closed the menu before it applied).
- Navigation pins can be dragged (snap to grid applies), and right-click gives Rename (in place), Go to pin and
Delete; new engine command `graph.pin.edit {id, name?, at?}` in `engine/src/pin_commands.rs`.
- Function graph library: operations grouped by category (collapsible, with an icon and a count), each with a
text badge saying what it is ("F2", "+", "≥", "sin", "if", "(F1)", "$F1"…), its inputs, and a tooltip
describing it; the search also matches the badge. Function node cards show the same badge in their body.
## Menus (File / Edit / Tools / Windows / Help)
- File: New ▸ Graph / Empty package, Open, Recent, Save, Save as, Save a copy as, Export with dependencies, Import bitmap, Link bitmap, Export outputs, Export material, Send to TextureCraft, Close, Quit.
- Tools: Switch engine (F9: CPU thread count, rayon pool), Cancel rendering, Suspend engine, Clear cache, Reload resources, Plugin Manager.
- Windows: panels, Main toolbar toggle, Dependency Manager, maximize/unmaximize (Shift+Space), reset layout.
- Help: docs, tutorials, release notes, requirements, automation, feedback, bug report, export log, about. No vendor names, no Partners.
- Status bar: "MC Engine: CPU (n threads)".
## Explorer
- Package context menu: New ▸, Import ▸ (Bitmap, Graph from a package), Link ▸ Bitmap, Reload, Save/Save as/Save a copy as, Export with dependencies, Send to ▸ TextureCraft, Copy/Paste (graphs), Close package, Compute Outputs, Show in Explorer, Dependency Manager.
- Graph context menu: Open (Return), Copy, Paste, Remove (Del), Rename (F2, in place), View Outputs In 3D View, Compute Outputs, Export outputs.
- Resources: Relink, Add a Bitmap node, Remove. Linked bitmaps show a link icon.
- Default graph name is Material_Graph.
- Not done: "Open dependencies" (we have no package-to-package links to open).
## Library
- Tree: All nodes, Favorites (persisted, right-click a tile), Graph items (Comment, Frame, Pin + inputs/outputs/dot), Atomic nodes, FxMap nodes, Function nodes ▸ (groups), Texture generators ▸, Filters ▸, Material filters ▸ (ours + planned empty groups greyed with 0), Mesh-based generators, Spline & Path tools, SDF functions (planned, greyed), Functions (function graphs of the package), PBR materials ▸ This package / Plugins, Values ▸ Constant.
- Collapsible groups with counts, search, icon/list view, tile size slider.
- Function nodes drop into the open function editor; plugin graphs are copied into the package on drop (file.importGraph).
## New graph dialog
- Category dropdown, group headings, ⓘ template info, width/height with a link toggle, "Create graph in".
## Graph toolbar
- Row 1: frame all, 1:1, screenshot (PNG), graph info popup, find node, thumbnails, cook times, straight/curved wires, grid, snap, compute, clean up; right: Stack checkbox + align buttons, Parent size with link and reset.
- Row 2: atomic quick-insert, comment, dot, frame, pin.
## 3D view
- Menus: Scene (11 scenes incl. Plane hi-res, Cloth, Rounded cylinder, Sphere 2 tiles; Display UVs in 2D View; Load/Save state file; Save as default; Reset), Materials ▸ Default (Edit properties, 9 shaders, reset common/material, create graph), Lights, Camera (Frame F, viewpoints, Save Render Alt+S, Copy Render, Reset Position R), Environment, Display (wireframe, axis, backface culling, bounding box, grid, light gizmos, resolution/stats/FPS overlays), Renderer (Edit settings).
- "Edit properties" pages in the Properties panel: Camera (focal length, projection, background type/colour, render resolution, clip planes), Lights (ambient + 2 point lights with colour strips), Environment (enabled, exposure, rotation dial/turns/degrees, environment preview), Renderer (resolution, scale, samples, AO rays), Material (OpenPBR sections: UVs, Base, Specular, Transmission, Subsurface, Coat, Fuzz, Emission, Thin-film, Geometry, Height; each with the "use map" checkbox, sRGB/Float/HSV colour strips).
- Left tool strip: frame, property pages, display toggles.
- Renderer: point lights with shadows, ambient, env on/off, 9 shading models, common values, wireframe, backface culling, clip planes, background colour/environment, FOV/ortho, tessellation factor.
- Engine: `view.3d` takes nested objects (camera/lights/renderer/display/material), `view.3d.reset {what}`, `view.3d.state`, `view.3d.loadState`.
## Preferences (Edit ▸ Preferences)
- Tabs General / Projects / Graph / 3D View / Bakers / Library / Shortcuts with OK / Cancel / Apply.
- General: recent count, history size (session.settings), language (English for now), appearance, invert zoom, save/export path mode + fixed folder, temp (backup) folder, image cache budget, cook threads, auto backup interval + versions (rotating files), cooking size limit (caps previews and exports).
- Projects: plugins folder, backups folder, default 3D state (save/clear), default lighting state, library view, preview size, 3D pan limit/speed.
- Graph: Tab menu, drag-create, 3D on open, thumbnails, 2D on open, auto display new node, auto colour/grayscale conversion node, grid/snap/wires/timings.
- 3D View: environment hidden by default, viewport scaling, sample count.
- Bakers: baking threads. Library: rebuild thumbnails, clear cache. Shortcuts: node creation shortcuts (click a field, press keys).
- Skipped on purpose: UDIM, .sbsar publishing.
## Plugin Manager (Tools ▸ Plugin Manager)
- Filter, Plugins/Loaded table, Browse (opens the plugins folder), Install (copies .sbs files in), Refresh.
- A plugin = a package file or a folder with package files + optional plugin.json {name, version, author, description} in Documents/MaterialCraft/plugins. Loaded plugins' graphs show in the library under PBR materials ▸ Plugins.
## Engine commands added
file.linkBitmap, file.reloadResources, file.deleteResource, file.importGraph, file.packageGraphs, file.saveCopy, file.exportWithDependencies, graph.add, session.settings, view.3d.reset {what}, view.3d.state, view.3d.loadState; `view.3d` nested objects. Resources can be linked (SBS keeps relative links).
## Checks run here
cargo fmt --all, cargo check --workspace --all-targets, cargo clippy --workspace --all-targets -- -D warnings, cargo xtask layers,
cargo test --workspace --release --no-fail-fast. `cargo xtask wasm` could not run in this container (the wasm target cannot be
downloaded here); please run it on your side.
-545
View File
@@ -1,545 +0,0 @@
//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel
//! method (see [`crate::rpc`]), answered in process (headless) or by the running app (bridge).
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{CallToolResult, ContentBlock as Content};
use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
use crate::headless::batch_reply;
use crate::security::MAX_BATCH_STEPS;
use crate::workspace::authorize_command;
use crate::{AutomationError, BridgeClient, Headless, bad};
/// Where tools run.
pub enum Backend {
/// An in-process session.
Headless(Arc<Mutex<Headless>>),
/// The running desktop app, over its control channel.
Bridge(Arc<BridgeClient>),
}
#[derive(Clone)]
pub struct MaterialcraftMcp {
backend: Arc<Backend>,
tool_router: ToolRouter<Self>,
}
// ---------------------------------------------------------------------------------------------
// Parameters (serialized back to JSON as the control method's params)
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct FilterParams {
/// Only entries whose id or label contains this text (case-insensitive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct LibraryParams {
/// Only nodes whose id or label contains this text.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
/// Only nodes in this library category, e.g. "Noises", "Patterns", "Filters/Blurs".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct RunParams {
/// Command id from `command_list`, e.g. `graph.node.add`, `graph.connect`, `edit.undo`.
pub id: String,
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BatchParams {
/// Commands run in order; the batch stops at the first error and reports its index.
pub steps: Vec<RunParams>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct NewGraphParams {
/// Template id: empty, pbr (default: six material outputs), bricks, stone_tiles, wood, metal_plates, rusty_metal, lava, marble, wicker, fabric, ground.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub template: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Graph size in pixels, a power of two from 16 to 8192 (default 1024).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct NodeAddParams {
/// Node definition id from `library_list`, e.g. `perlin_noise`, `blend`, `levels`, `normal`, `output`.
pub def: String,
/// Graph position `[x, y]` (default: right of `connectFrom`, else the origin).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<[f32; 2]>,
/// Parameter values by id (see `library_list`): numbers, `[x, y]`, `"#rrggbb"`, enum indices.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
/// Wire `{node, port?}`'s output into the new node's first input.
#[serde(default, rename = "connectFrom", skip_serializing_if = "Option::is_none")]
pub connect_from: Option<Value>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ConnectParams {
/// Source node id.
pub from: u64,
/// Source output port id (default: its first output).
#[serde(default, rename = "fromPort", skip_serializing_if = "Option::is_none")]
pub from_port: Option<String>,
/// Target node id.
pub to: u64,
/// Target input port id (default: its first input).
#[serde(default, rename = "toPort", skip_serializing_if = "Option::is_none")]
pub to_port: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ParamSetParams {
/// Node id.
pub id: u64,
/// Parameter id (see `library_list`).
pub param: String,
/// The value: a number, `[x, y]`, `"#rrggbb"`, an enum index, a curve `[[x, y], …]` or a gradient `[[pos, color], …]`.
pub value: Value,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct PathParams {
/// Forward-slash path relative to the workspace root.
pub path: String,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Forward-slash path relative to the write root (`.sbs` is appended unless it ends in `.sbs`
/// or `.mcraft`). Omit to save to the package's own file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BitmapParams {
/// Image file relative to the read root (png, jpg, tga, tif, bmp, webp, exr, hdr).
pub path: String,
/// Resource name (default: the file name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ExportParams {
/// Output folder relative to the write root (created if missing; `.` = the root).
pub dir: String,
/// png (default), jpg, tga, tif, bmp, webp, exr, hdr.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// File name pattern with $(graph), $(identifier) and $(usage) (default `$(graph)_$(identifier)`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pattern: Option<String>,
/// 8, 16 or 32 bits (default: the graph's output format).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
/// Pixels of the larger side, rounded down to a power of two, 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MaterialExportParams {
/// Forward-slash path relative to the write root (`.mcmat` is appended if missing). The
/// parent folder must exist.
pub path: String,
/// Graph index (default: the open graph).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graph: Option<u32>,
/// Square size in pixels, rounded to a power of two from 16 to 8192 (default: the graph's size).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
/// Exposed input values to cook with and embed, by input id (see `session_inspect`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub values: Option<Value>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default: the material on the 3D view's scene) or `2d` (a node's output).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
/// Pixels, 16..2048.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
/// Camera yaw/pitch in degrees for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yaw: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pitch: Option<f32>,
/// 3D scene: rounded_cube, cube, sphere, cylinder, plane, torus, material_ball.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scene: Option<String>,
/// 2D: the node to show (default: the 2D view's node, else the first output).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node: Option<u64>,
/// 2D: the output port index.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<u32>,
/// Cook at the full graph size instead of the preview size.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub full: Option<bool>,
/// 3D: UV repeats of the material on the scene for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tiling: Option<f32>,
/// 3D beauty render: a finer displaced mesh, ambient occlusion and a shadowed key light (slower).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hq: Option<bool>,
/// With `hq`: displacement depth in scene radii (default: the view's height depth).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub displacement: Option<f32>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ScreenshotParams {
/// `3d` (default) or `2d`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MenuParams {
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `ui.newGraph`, `ui.view.library`.
pub id: String,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct InputParams {
/// Input events in window points, applied in order on the next frames. Each is one of:
/// {"type":"move","pos":[x,y]}, {"type":"down"|"up","pos":[x,y],"button":"left"|"right"|"middle"},
/// {"type":"click"|"doubleClick","pos":[x,y],"button"?}, {"type":"drag","from":[x,y],"to":[x,y],"button"?,"steps"?},
/// {"type":"scroll","pos":[x,y],"delta":[dx,dy]}, {"type":"key","key":"A"|"Enter"|"Space"|…,"modifiers"?:["ctrl","shift","alt"]},
/// {"type":"text","text":"…"}.
pub events: Vec<Value>,
}
// ---------------------------------------------------------------------------------------------
// Results
fn ok_json(v: &Value) -> CallToolResult {
match json_text(v) {
Ok(text) => CallToolResult::success(vec![Content::text(text)]),
Err(e) => fail(e),
}
}
fn fail(e: impl std::fmt::Display) -> CallToolResult {
CallToolResult::error(vec![Content::text(e.to_string())])
}
fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpError> {
Ok(match r {
Ok(v) => ok_json(&v),
Err(e) => fail(e),
})
}
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content.
fn image_result(r: Result<Value, AutomationError>, note: &str, refit: bool) -> Result<CallToolResult, McpError> {
let png = r.and_then(|v| {
let b64 = v.get("png").and_then(Value::as_str).ok_or_else(|| AutomationError::Other("the reply has no PNG".into()))?;
if !refit {
check_png(b64.len() / 4 * 3)?;
return Ok(b64.to_string());
}
let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| AutomationError::Other(format!("bad PNG data: {e}")))?;
Ok(base64::engine::general_purpose::STANDARD.encode(fit_png(bytes, MAX_PNG_SIDE)?))
});
Ok(match png {
Ok(b64) => CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note.to_string())]),
Err(e) => fail(e),
})
}
fn params<T: Serialize>(p: &T) -> Value {
serde_json::to_value(p).unwrap_or(Value::Null)
}
impl MaterialcraftMcp {
pub fn headless(h: Headless) -> Self {
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
}
pub fn bridge(client: BridgeClient) -> Self {
Self::with_backend(Backend::Bridge(Arc::new(client)))
}
pub fn with_backend(backend: Backend) -> Self {
MaterialcraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
}
/// Serve MCP on stdin/stdout until the client disconnects.
pub async fn serve_stdio(self) -> Result<(), AutomationError> {
let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP start: {e}")))?;
running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
Ok(())
}
fn is_bridge(&self) -> bool {
matches!(*self.backend, Backend::Bridge(_))
}
/// One control-channel method on the backend.
async fn call(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
match &*self.backend {
Backend::Headless(h) => {
let (h, m) = (h.clone(), method.to_string());
// Edits run on snapshots (`Session::edit`), so a panicking command leaves the
// session consistent: keep serving after a poisoned lock.
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
.await
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
}
Backend::Bridge(b) => match method {
"command.run" => {
let id = p.get("id").and_then(Value::as_str).unwrap_or_default();
authorize_command(id, p.get("params").unwrap_or(&Value::Null))?;
b.call(method, p).await
}
"package.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
"package.save" | "package.open" | "bitmap.import" | "outputs.export" | "material.export" | "command.batch" | "render" => {
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
}
_ => b.call(method, p).await,
},
}
}
async fn run(&self, id: &str, p: Value) -> Result<Value, AutomationError> {
self.call("command.run", json!({"id": id, "params": p})).await
}
async fn bridge_only(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
if self.is_bridge() {
self.call(method, p).await
} else {
Err(bad(format!(
"`{method}` needs the running app: start `materialcraft --control <port>` and run `materialcraft-cli mcp --bridge <port>` (headless renders: view_render)"
)))
}
}
}
// ---------------------------------------------------------------------------------------------
// Tools
#[tool_router]
impl MaterialcraftMcp {
#[tool(description = "The whole session as JSON: package, graphs, the open graph's nodes (definition, parameters, base \
parameters, ports, cook errors, timings, mean values), connections, frames, comments, pins, exposed inputs, views and history.")]
async fn session_inspect(&self) -> Result<CallToolResult, McpError> {
to_result(self.call("session.inspect", json!({})).await)
}
#[tool(description = "List engine commands: id, label, menu path, shortcut, params doc and whether it can run now.")]
async fn command_list(&self, Parameters(p): Parameters<FilterParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("command.list", params(&p)).await)
}
#[tool(description = "Run an engine command by id with JSON params (see command_list). Runs with defaults, never opens a \
dialog. Commands given host paths are disabled: use package_open, package_save, bitmap_import and outputs_export.")]
async fn command_run(&self, Parameters(p): Parameters<RunParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("command.run", params(&p)).await)
}
#[tool(description = "Run several commands in order: steps [{id, params}]. Stops at the first error. Returns {completed, \
results, failed: {index, id, error} | null}; a failed batch is a tool error.")]
async fn command_batch(&self, Parameters(p): Parameters<BatchParams>) -> Result<CallToolResult, McpError> {
if p.steps.len() > MAX_BATCH_STEPS {
return Ok(fail(format!("at most {MAX_BATCH_STEPS} steps per batch")));
}
let reply = if self.is_bridge() {
let mut results = Vec::new();
let mut failed = None;
for (i, s) in p.steps.iter().enumerate() {
match self.call("command.run", params(s)).await {
Ok(v) => results.push(v),
Err(e) => {
failed = Some((i, s.id.as_str(), e.to_string()));
break;
}
}
}
batch_reply(results, failed)
} else {
match self.call("command.batch", params(&p)).await {
Ok(v) => v,
Err(e) => return Ok(fail(e)),
}
};
Ok(if reply["failed"].is_null() { ok_json(&reply) } else { fail(json_text(&reply).unwrap_or_else(|e| e.to_string())) })
}
#[tool(description = "The node library: every node's id, label, category, input and output ports and parameters (id, \
default, range, enum options). Filter by text or category.")]
async fn library_list(&self, Parameters(p): Parameters<LibraryParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("library.list", params(&p)).await)
}
#[tool(description = "Add a new graph to the package from a template and open it. Returns {graph, name}.")]
async fn graph_new(&self, Parameters(p): Parameters<NewGraphParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("file.new", params(&p)).await)
}
#[tool(description = "Add a node to the open graph (optionally wired from another node's output). Returns {id}.")]
async fn node_add(&self, Parameters(p): Parameters<NodeAddParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("graph.node.add", params(&p)).await)
}
#[tool(description = "Wire an output port of one node into an input port of another (replacing what fed that input).")]
async fn node_connect(&self, Parameters(p): Parameters<ConnectParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("graph.connect", params(&p)).await)
}
#[tool(description = "Set one parameter of a node.")]
async fn node_param(&self, Parameters(p): Parameters<ParamSetParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("graph.node.param", params(&p)).await)
}
#[tool(
description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists what an SBS file holds that MaterialCraft can't read yet (missing nodes are kept as placeholders)."
)]
async fn package_open(&self, Parameters(p): Parameters<PathParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.open", params(&p)).await)
}
#[tool(
description = "Save the package (path relative to the write root; omit to save to its own file). Saves SBS (.sbs, the main format) unless the path ends in .mcraft."
)]
async fn package_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("package.save", params(&p)).await)
}
#[tool(description = "Embed an image (path relative to the read root) as a bitmap resource. Returns its name, for a \
`bitmap` node's `resource` parameter.")]
async fn bitmap_import(&self, Parameters(p): Parameters<BitmapParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("bitmap.import", params(&p)).await)
}
#[tool(description = "Cook a graph at full size and write every output (base color, normal, roughness, …) into a folder \
relative to the write root. Returns the written files.")]
async fn outputs_export(&self, Parameters(p): Parameters<ExportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("outputs.export", params(&p)).await)
}
#[tool(description = "Cook a graph at full size and write it as a portable .mcmat material (cooked maps, exposed inputs, \
source package) to a path relative to the write root, for TextureCraft. Optional graph, size and exposed input values. \
Returns {path, bytes}.")]
async fn material_export(&self, Parameters(p): Parameters<MaterialExportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("material.export", params(&p)).await)
}
#[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \
2048 px a side. In bridge mode use view_screenshot.")]
async fn view_render(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
let note = format!("render {}", params(&p));
image_result(self.call("render", params(&p)).await, &note, false)
}
#[tool(description = "Bridge mode: PNG of the live app's 3D or 2D view.")]
async fn view_screenshot(&self, Parameters(p): Parameters<ScreenshotParams>) -> Result<CallToolResult, McpError> {
image_result(self.bridge_only("view.screenshot", params(&p)).await, "screenshot of an app view", true)
}
#[tool(description = "Bridge mode: PNG of the whole app window (downscaled to 2048 px a side at most).")]
async fn ui_screenshot(&self) -> Result<CallToolResult, McpError> {
image_result(self.bridge_only("ui.screenshot", json!({})).await, "screenshot of the app window", true)
}
#[tool(description = "Bridge mode: the app's UI state (panels, windows, graph view camera, node rectangles on screen, toasts).")]
async fn ui_inspect(&self) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.inspect", json!({})).await)
}
#[tool(description = "Bridge mode: activate a menu item by id like a click (may open a window). ui.menu.list lists ids.")]
async fn ui_menu_invoke(&self, Parameters(p): Parameters<MenuParams>) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.menu.invoke", params(&p)).await)
}
#[tool(description = "Bridge mode: synthesize mouse, keyboard and text input in the app window (clicks, drags between \
node ports, scrolling, shortcuts, typing). Positions are window points (see ui_inspect for node rectangles).")]
async fn ui_input(&self, Parameters(p): Parameters<InputParams>) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.input", params(&p)).await)
}
}
#[tool_handler(
router = self.tool_router,
name = "materialcraft",
instructions = "MaterialCraft procedural material designer. A package holds graphs of nodes; each graph's output nodes \
(usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \
(templates: pbr, bricks, wood, …) or package_open, browse nodes with library_list, build with node_add / node_connect \
/ node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \
view_render (3d, or 2d for one node), then package_save, outputs_export or material_export (.mcmat for TextureCraft). Undo: command_run edit.undo."
)]
impl ServerHandler for MaterialcraftMcp {}
#[cfg(test)]
mod tests {
use super::*;
use crate::headless::Filesystem;
#[tokio::test(flavor = "multi_thread")]
async fn a_panic_does_not_wedge_the_session() {
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
let Backend::Headless(h) = &*mcp.backend else { panic!("headless") };
let h2 = h.clone();
let _ = tokio::task::spawn_blocking(move || {
let _g = h2.lock().unwrap();
panic!("boom")
})
.await;
assert!(mcp.call("session.inspect", json!({})).await.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn material_export_tool_writes_through_the_workspace_only() {
let base = std::env::temp_dir().join(format!("mc-mcp-{}-material", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let args = || Parameters(MaterialExportParams { path: "m".into(), graph: None, size: Some(16), values: None });
let denied = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Denied));
assert_eq!(denied.material_export(args()).await.unwrap().is_error, Some(true));
let ws = crate::AuthorizedWorkspace::new(None, Some(&base)).unwrap();
let mcp = MaterialcraftMcp::headless(Headless::new(materialcraft_engine::sample_session(), Filesystem::Workspace(ws)));
assert_eq!(mcp.material_export(args()).await.unwrap().is_error, Some(false));
assert!(base.join("m.mcmat").is_file());
let escape = Parameters(MaterialExportParams { path: "../m.mcmat".into(), graph: None, size: Some(16), values: None });
assert_eq!(mcp.material_export(escape).await.unwrap().is_error, Some(true));
assert!(!base.parent().unwrap().join("m.mcmat").exists());
}
#[test]
fn oversized_replies_become_errors() {
let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
assert_eq!(r.is_error, Some(true));
}
}
-67
View File
@@ -1,67 +0,0 @@
//! Function graphs: small typed expression graphs evaluated per pixel (pixel processor), once
//! per cook (value processor) or to compute a parameter dynamically. The data lives here; the
//! evaluator is `materialcraft_nodes::function`.
use serde::{Deserialize, Serialize};
use crate::Value;
/// A node in a function graph.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FnNode {
pub id: u32,
/// Operation id, e.g. `const_float`, `add`, `sample_gray`, `get_float2` (see the evaluator's
/// catalog for the full list).
pub op: String,
/// Upstream node per input slot, in the op's slot order.
#[serde(default)]
pub inputs: Vec<Option<u32>>,
/// The constant (`const_*`), the variable name (`get_*`) or the input index (`sample_*`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
#[serde(default)]
pub pos: [f32; 2],
}
/// A function graph: nodes plus the id of the node whose value is the result.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FnGraph {
pub nodes: Vec<FnNode>,
#[serde(default)]
pub output: Option<u32>,
}
impl FnGraph {
pub fn node(&self, id: u32) -> Option<&FnNode> {
self.nodes.iter().find(|n| n.id == id)
}
fn next_id(&self) -> u32 {
self.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1)
}
/// Append a node and return its id.
pub fn add(&mut self, op: &str, inputs: &[u32], value: Option<Value>) -> u32 {
let id = self.next_id();
let x = self.nodes.len() as f32 * 140.0;
self.nodes.push(FnNode { id, op: op.into(), inputs: inputs.iter().map(|i| Some(*i)).collect(), value, pos: [x, 0.0] });
id
}
/// A graph returning one constant.
pub fn constant(v: Value) -> FnGraph {
let op = match &v {
Value::Float(_) => "const_float",
Value::Float2(_) => "const_float2",
Value::Float3(_) => "const_float3",
Value::Float4(_) | Value::Color(_) => "const_float4",
Value::Int(_) | Value::Enum(_) => "const_int",
Value::Bool(_) => "const_bool",
_ => "const_float",
};
let mut g = FnGraph::default();
let id = g.add(op, &[], Some(v));
g.output = Some(id);
g
}
}
-191
View File
@@ -1,191 +0,0 @@
//! Portable materials (`.mcmat`): a cooked material other apps (TextureCraft) apply without a
//! graph engine, plus the package it came from so an app that can run `materialcraft-cli`
//! re-cooks it with other parameter values, sizes and mesh maps.
//!
//! A zip: `material.json` ([`Manifest`]), `maps/<usage>.png` (8-bit sRGB for color usages,
//! 16-bit linear otherwise; normals in the OpenGL convention) and `source.mcraft`.
use std::collections::BTreeMap;
use std::io::{Cursor, Read, Write};
use materialcraft_core::{ExposedParam, Value};
use serde::{Deserialize, Serialize};
use crate::{FormatError, MAX_JSON, MAX_RESOURCE, Result};
/// The portable material extension.
pub const MATERIAL_EXT: &str = "mcmat";
/// `format` of every manifest.
pub const FORMAT: &str = "craft-material";
/// Newest manifest version this build reads and writes.
pub const VERSION: u32 = 1;
const MANIFEST: &str = "material.json";
const SOURCE: &str = "source.mcraft";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
pub format: String,
pub version: u32,
pub name: String,
/// The graph of the source package the maps were cooked from.
pub graph: String,
/// Size of the maps in pixels.
pub size: [u32; 2],
pub maps: Vec<MapEntry>,
/// Parameters other apps may change (scalar, vector, color, toggle and option inputs).
pub parameters: Vec<Parameter>,
/// Image inputs of the graph, fed from mesh maps by identifier.
pub inputs: Vec<ImageInput>,
#[serde(default)]
pub presets: Vec<PresetEntry>,
pub source: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MapEntry {
/// Usage id: `baseColor`, `normal`, `roughness`, `metallic`, `height`, `ambientOcclusion`,
/// `emissive`, `opacity`, `specular`.
pub usage: String,
pub file: String,
/// `srgb` or `linear`.
pub color_space: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Parameter {
#[serde(flatten)]
pub param: ExposedParam,
/// The value the maps were cooked with.
pub value: Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageInput {
pub identifier: String,
/// `gray` or `color`.
pub kind: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PresetEntry {
pub name: String,
pub values: BTreeMap<String, Value>,
}
/// Whether maps of `usage` hold colors (stored sRGB-encoded) rather than data (linear).
pub fn srgb_usage(usage: &str) -> bool {
matches!(usage, "baseColor" | "emissive" | "specular")
}
/// Whether other apps can set a value of this type from the manifest.
pub fn portable(v: &Value) -> bool {
matches!(
v,
Value::Float(_)
| Value::Float2(_)
| Value::Float3(_)
| Value::Float4(_)
| Value::Int(_)
| Value::Int2(_)
| Value::Bool(_)
| Value::Color(_)
| Value::Enum(_)
)
}
/// Write a portable material: `manifest` (its `source` is set here), the encoded maps named by
/// `manifest.maps[].file`, and the source package bytes.
pub fn write_material(manifest: &Manifest, maps: &[(String, Vec<u8>)], source: &[u8]) -> Result<Vec<u8>> {
let io = |e: zip::result::ZipError| FormatError::Io(e.to_string());
let manifest = Manifest { source: SOURCE.into(), ..manifest.clone() };
let json = serde_json::to_vec_pretty(&manifest).map_err(|e| FormatError::Io(e.to_string()))?;
let mut buf = Cursor::new(Vec::new());
{
let mut z = zip::ZipWriter::new(&mut buf);
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
// Maps and the package are already compressed.
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
z.start_file(MANIFEST, deflate).map_err(io)?;
z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?;
for (file, bytes) in maps {
z.start_file(file.as_str(), stored).map_err(io)?;
z.write_all(bytes).map_err(|e| FormatError::Io(e.to_string()))?;
}
z.start_file(SOURCE, stored).map_err(io)?;
z.write_all(source).map_err(|e| FormatError::Io(e.to_string()))?;
z.finish().map_err(io)?;
}
Ok(buf.into_inner())
}
/// Read a portable material's manifest and source package bytes.
pub fn read_material(bytes: &[u8]) -> Result<(Manifest, Vec<u8>)> {
let bad = |m: String| FormatError::BadPackage(format!("portable material: {m}"));
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| bad(e.to_string()))?;
let mut read = |name: &str, cap: u64| -> Result<Vec<u8>> {
let mut data = Vec::new();
z.by_name(name).map_err(|_| bad(format!("{name} is missing")))?.take(cap).read_to_end(&mut data).map_err(|e| FormatError::Io(e.to_string()))?;
Ok(data)
};
let manifest: Manifest = serde_json::from_slice(&read(MANIFEST, MAX_JSON)?).map_err(|e| bad(e.to_string()))?;
if manifest.format != FORMAT || manifest.version > VERSION {
return Err(bad(format!("unsupported {} version {}", manifest.format, manifest.version)));
}
let source = read(&manifest.source, MAX_RESOURCE)?;
Ok((manifest, source))
}
/// Whether `bytes` look like a portable material (a zip with `material.json`).
pub fn is_material(bytes: &[u8]) -> bool {
zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(MANIFEST).is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
fn manifest() -> Manifest {
let param = ExposedParam {
id: "rough".into(),
label: "Roughness".into(),
group: String::new(),
default: Value::Float(0.5),
min: 0.0,
max: 1.0,
options: Vec::new(),
};
Manifest {
format: FORMAT.into(),
version: VERSION,
name: "Bricks".into(),
graph: "Bricks".into(),
size: [64, 64],
maps: vec![MapEntry { usage: "baseColor".into(), file: "maps/baseColor.png".into(), color_space: "srgb".into() }],
parameters: vec![Parameter { param, value: Value::Float(0.25) }],
inputs: vec![ImageInput { identifier: "curvature".into(), kind: "gray".into() }],
presets: Vec::new(),
source: String::new(),
}
}
#[test]
fn round_trips_and_rejects_newer_versions() {
let m = manifest();
let bytes = write_material(&m, &[("maps/baseColor.png".into(), vec![1, 2, 3])], b"pkg").unwrap();
assert!(is_material(&bytes));
let (back, source) = read_material(&bytes).unwrap();
assert_eq!(back, Manifest { source: SOURCE.into(), ..m.clone() }, "the writer names the source entry");
assert_eq!(source, b"pkg");
// Parameters are flat objects with the value in the API's typed form.
let json = serde_json::to_value(&m).unwrap();
assert_eq!(json["parameters"][0]["id"], "rough");
assert_eq!(json["parameters"][0]["value"], serde_json::json!({"t": "float", "v": 0.25}));
let newer = Manifest { version: VERSION + 1, ..m };
assert!(read_material(&write_material(&newer, &[], b"").unwrap()).is_err());
assert!(!is_material(b"not a zip"));
assert!(read_material(b"garbage").is_err());
}
}
File diff suppressed because it is too large. Load diff
-99
View File
@@ -1,99 +0,0 @@
//! Clean-room import of a bounded subset of numeric SBS parameter expressions.
//! Unsupported operations retain the reader's warning-and-default behavior.
use materialcraft_core::{
Value,
function::{FnGraph, FnNode},
};
use std::collections::{BTreeMap, HashMap};
use super::{XmlNode, child_element, child_value, children_named, sbs_constant, sbs_constant_element, to_natural_value};
pub(super) const MAX_NODES: usize = 4096;
fn float_dims(value: &Value) -> Option<usize> {
match value {
Value::Float(_) => Some(1),
Value::Float2(_) => Some(2),
Value::Float3(_) => Some(3),
Value::Float4(_) => Some(4),
_ => None,
}
}
pub(super) fn read(dynamic: XmlNode, variables: &BTreeMap<String, Value>, target: &Value) -> Result<FnGraph, String> {
let expected = float_dims(target).ok_or("only float parameter expressions are supported")?;
let elements: Vec<_> = child_element(dynamic, "paramNodes").into_iter().flat_map(|p| children_named(p, "paramNode")).take(MAX_NODES + 1).collect();
if elements.is_empty() || elements.len() > MAX_NODES {
return Err(format!("expected 1..{MAX_NODES} function nodes"));
}
let mut ids = HashMap::new();
for (index, node) in elements.iter().enumerate() {
let uid = child_value(*node, "uid").filter(|s| !s.is_empty()).ok_or("function node has no uid")?;
if ids.insert(uid, index as u32 + 1).is_some() {
return Err(format!("duplicate function uid `{uid}`"));
}
}
let output = child_value(dynamic, "rootnode").and_then(|uid| ids.get(uid)).copied().ok_or("function rootnode is missing or unknown")?;
let mut graph = FnGraph { nodes: Vec::with_capacity(elements.len()), output: Some(output) };
for (index, node) in elements.iter().enumerate() {
if child_value(*node, "disabled").is_some_and(|v| v != "0") {
return Err("disabled function nodes are not supported".into());
}
let name = child_value(*node, "function").ok_or("function node has no operation")?;
if child_value(*node, "type").is_some_and(|t| !matches!(t, "256" | "512" | "1024" | "2048")) {
return Err(format!("`{name}` has an unsupported result type"));
}
let (op, ports): (&str, &[&str]) = match name {
"const_float1" => ("const_float", &[]),
"const_float2" | "const_float3" | "const_float4" => (name, &[]),
"get_float1" | "get_float2" | "get_float3" | "get_float4" => ("get_var", &[]),
"add" | "sub" | "mul" | "div" => (name, &["a", "b"]),
"neg" | "abs" | "floor" | "ceil" | "cos" | "sin" | "sqrt" | "log" | "exp" => (name, &["a"]),
_ => return Err(format!("unsupported function operation `{name}`")),
};
let value = if ports.is_empty() {
let data = child_element(*node, "funcDatas")
.into_iter()
.flat_map(|p| children_named(p, "funcData"))
.find(|p| child_value(*p, "name") == Some(name))
.ok_or_else(|| format!("`{name}` has no function data"))?;
let value = data
.children()
.filter(|n| n.is_element())
.find_map(|n| sbs_constant_element(n).or_else(|| sbs_constant(n)))
.ok_or_else(|| format!("`{name}` has no constant value"))?;
let value = to_natural_value(&value);
let dims = name.chars().last().and_then(|c| c.to_digit(10)).unwrap_or(0) as usize;
if op == "get_var" {
let Value::Text(variable) = &value else { return Err(format!("`{name}` needs a variable name")) };
if variables.get(variable).and_then(float_dims) != Some(dims) {
return Err(format!("`{name}` references an unknown or differently typed input `{variable}`"));
}
} else if float_dims(&value) != Some(dims) {
return Err(format!("`{name}` has the wrong constant type"));
}
Some(value)
} else {
None
};
let mut inputs = vec![None; ports.len()];
for connection in child_element(*node, "connections").into_iter().flat_map(|p| children_named(p, "connection")) {
let port = child_value(connection, "identifier").unwrap_or("");
let slot = ports.iter().position(|p| *p == port).and_then(|i| inputs.get_mut(i)).ok_or_else(|| format!("`{name}` has no input `{port}`"))?;
if slot.is_some() {
return Err(format!("duplicate function input `{port}`"));
}
*slot = Some(child_value(connection, "connRef").and_then(|uid| ids.get(uid)).copied().ok_or("function connection references an unknown node")?);
}
if inputs.iter().any(Option::is_none) {
return Err(format!("`{name}` has an unconnected input"));
}
graph.nodes.push(FnNode { id: index as u32 + 1, op: op.into(), inputs, value, pos: [index as f32 * 140.0, 0.0] });
}
let program = materialcraft_nodes::function::compile(&graph, variables, 0)?;
if program.dims() != expected {
return Err("function result type does not match the parameter".into());
}
Ok(graph)
}
-92
View File
@@ -1,92 +0,0 @@
//! Original synthetic XML fixtures exercise structural SBS import without a native payload.
use materialcraft_core::Value;
use materialcraft_formats::sbs::{SbsRead, read_sbs, write_sbs};
use std::collections::BTreeMap;
fn node(uid: &str, op: &str, value: &str, connections: &str) -> String {
let data = if value.is_empty() { String::new() } else { format!("<funcDatas><funcData><name v=\"{op}\"/>{value}</funcData></funcDatas>") };
format!("<paramNode><uid v=\"{uid}\"/><function v=\"{op}\"/>{data}<connections>{connections}</connections></paramNode>")
}
fn wire(port: &str, uid: &str) -> String {
format!("<connection><identifier v=\"{port}\"/><connRef v=\"{uid}\"/></connection>")
}
fn xml(nodes: &str, root: &str, filter: &str, parameter: &str) -> String {
format!(
r#"<package><content><graph><identifier v="Math"/><paraminputs><paraminput><identifier v="amount"/><uid v="90"/><type v="256"/><defaultValue><constantValueFloat1 v="0.75"/></defaultValue></paraminput></paraminputs><compNodes><compNode><uid v="10"/><compImplementation><compFilter><filter v="{filter}"/><parameters><parameter><name v="{parameter}"/><paramValue><dynamicValue><rootnode v="{root}"/><paramNodes>{nodes}</paramNodes></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode></compNodes></graph></content></package>"#
)
}
fn read(text: &str) -> SbsRead {
let report = read_sbs(text.as_bytes(), "math.sbs", &|_| None).unwrap();
assert!(!report.exact);
report
}
fn expression() -> String {
// XML order and connection order deliberately differ from dependency/operand order.
[
node("99999999999", "sub", "", &(wire("b", "2") + &wire("a", "1"))),
node("2", "const_float1", r#"<constantValue><constantValueFloat1 v="0.25"/></constantValue>"#, ""),
node("1", "get_float1", r#"<constantValueString v="amount"/>"#, ""),
]
.concat()
}
#[test]
fn imports_arithmetic_and_keeps_exposed_inputs_live() {
let report = read(&xml(&expression(), "99999999999", "blur", "intensity"));
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
let f = &report.pkg.graphs[0].nodes[0].functions["intensity"];
assert_eq!(f.nodes.len(), 3);
let mut vars = BTreeMap::new();
for (input, expected) in [(0.75, 0.5), (0.5, 0.25)] {
vars.insert("amount".into(), Value::Float(input));
let program = materialcraft_nodes::function::compile(f, &vars, 0).unwrap();
assert_eq!(program.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new()), [expected; 4]);
}
let saved = write_sbs(&report.pkg).unwrap();
assert_eq!(read_sbs(&saved, "saved.sbs", &|_| None).unwrap().pkg, report.pkg);
}
#[test]
fn imports_vector_constants_and_unary_operations() {
let nodes = node("1", "const_float2", r#"<constValue><constantValueFloat2 v="-0.25 0.75"/></constValue>"#, "") + &node("2", "abs", "", &wire("a", "1"));
let report = read(&xml(&nodes, "2", "transformation", "offset"));
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
let p = materialcraft_nodes::function::compile(&report.pkg.graphs[0].nodes[0].functions["offset"], &BTreeMap::new(), 0).unwrap();
assert_eq!(p.dims(), 2);
assert_eq!(&p.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new())[..2], &[0.25, 0.75]);
}
#[test]
fn invalid_or_unsupported_expressions_warn_and_keep_defaults() {
let valid = xml(&expression(), "99999999999", "blur", "intensity");
for (case, text) in [
valid.replace("rootnode v=\"99999999999\"", "rootnode v=\"missing\""),
valid.replace("function v=\"sub\"", "function v=\"while\""),
valid.replace("connRef v=\"2\"", "connRef v=\"missing\""),
valid.replace("connRef v=\"2\"", "connRef v=\"99999999999\""),
valid.replace("identifier v=\"b\"", "identifier v=\"a\""),
valid.replace("identifier v=\"b\"", "identifier v=\"unknown\""),
valid.replace("uid v=\"2\"", "uid v=\"1\""),
valid.replace("constantValueString v=\"amount\"", "constantValueString v=\"unknown\""),
valid.replace("get_float1", "get_float2"),
valid.replace("function v=\"sub\"", "function v=\"sub\"/><disabled v=\"1\""),
valid.replace("function v=\"sub\"", "function v=\"sub\"/><type v=\"16\""),
valid.replace(&wire("b", "2"), ""),
xml(&node("1", "const_float2", r#"<constantValueFloat2 v="1 2"/>"#, ""), "1", "blur", "intensity"),
]
.into_iter()
.enumerate()
{
let report = read(&text);
assert!(report.pkg.graphs[0].nodes[0].functions.is_empty(), "case {case}: unsupported expression was imported");
assert!(report.warnings.iter().any(|w| w.contains("imported its default")), "{:?}", report.warnings);
}
}
#[test]
fn oversized_functions_are_rejected_and_simple_bindings_still_work() {
let constant = node("1", "const_float1", r#"<constantValueFloat1 v="1"/>"#, "");
let report = read(&xml(&constant.repeat(4097), "1", "blur", "intensity"));
assert!(report.pkg.graphs[0].nodes[0].functions.is_empty());
assert!(report.warnings.iter().any(|w| w.contains("4096")));
let getter = node("1", "get_float1", r#"<constantValueString v="amount"/>"#, "");
let report = read(&xml(&getter, "1", "blur", "intensity"));
assert_eq!(report.pkg.graphs[0].nodes[0].bindings["intensity"], "amount");
assert!(report.warnings.is_empty());
}
@@ -1,154 +0,0 @@
//! The reported library-node aliases must preserve imported settings and connections.
use materialcraft_core::{Graph, Package, Value};
use materialcraft_formats::sbs::{read_sbs, write_sbs};
fn plain_xml(bytes: &[u8]) -> String {
let text = String::from_utf8(bytes.to_vec()).unwrap();
// Exercise XML import rather than the writer's embedded exact native-package copy.
format!("{}</package>", text.split("<!--").next().unwrap())
}
const DEFS: [&str; 4] = ["histogram_scan", "auto_levels", "flood_fill", "height_blend"];
fn fixture(def: &str) -> String {
let mut pkg = Package::new("Import check");
let mut graph = Graph::new("G");
let source = graph.add_node("uniform", [0.0, 0.0]);
let second = (def == "height_blend").then(|| graph.add_node("uniform", [0.0, 150.0]));
let filter = graph.add_node(def, [150.0, 0.0]);
graph.connect(source, "output", filter, if def == "height_blend" { "top" } else { "input" }).unwrap();
if let Some(second) = second {
graph.connect(second, "output", filter, "bottom").unwrap();
}
if def == "histogram_scan" {
let n = graph.node_mut(filter).unwrap();
n.params.insert("position".into(), Value::Float(0.25));
n.params.insert("contrast".into(), Value::Float(0.75));
}
pkg.graphs.push(graph);
plain_xml(&write_sbs(&pkg).unwrap())
}
fn aliased_fixture(def: &str) -> String {
let xml = fixture(def);
match def {
"histogram_scan" => xml
.replace("<name v=\"position\"/>", "<name v=\"Position\"/>")
.replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>")
.replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>"),
"auto_levels" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>"),
"flood_fill" => xml.replace("<identifier v=\"input\"/>", "<identifier v=\"mask\"/>"),
"height_blend" => {
xml.replace("<identifier v=\"top\"/>", "<identifier v=\"height_top\"/>").replace("<identifier v=\"bottom\"/>", "<identifier v=\"height_bottom\"/>")
}
_ => panic!("unknown fixture node {def}"),
}
}
fn assert_wires(pkg: &Package, def: &str) {
let g = &pkg.graphs[0];
let sources: Vec<_> = g.nodes.iter().filter(|n| n.def == "uniform").collect();
let filter = g.nodes.iter().find(|n| n.def == def).unwrap();
let ports: &[&str] = if def == "height_blend" { &["top", "bottom"] } else { &["input"] };
assert_eq!(sources.len(), ports.len());
assert_eq!(g.connections.len(), ports.len());
for (source, port) in sources.iter().zip(ports) {
let wire = g.input_of(filter.id, port).unwrap();
assert_eq!((wire.from, wire.from_port.as_str(), wire.to, wire.to_port.as_str()), (source.id, "output", filter.id, *port));
}
}
fn assert_scan_values(pkg: &Package) {
let n = pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap();
assert_eq!(n.params.get("position"), Some(&Value::Float(0.25)));
assert_eq!(n.params.get("contrast"), Some(&Value::Float(0.75)));
assert!(!n.params.contains_key("Position") && !n.params.contains_key("Contrast"));
}
#[test]
fn canonical_names_keep_parameters_and_wires() {
for def in DEFS {
let read = read_sbs(fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(!read.exact);
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, def);
if def == "histogram_scan" {
assert_scan_values(&read.pkg);
}
}
}
#[test]
fn histogram_scan_keeps_reported_parameter_spellings() {
let xml = fixture("histogram_scan").replace("<name v=\"position\"/>", "<name v=\"Position\"/>").replace("<name v=\"contrast\"/>", "<name v=\"Contrast\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_scan_values(&read.pkg);
}
#[test]
fn histogram_scan_keeps_reported_input_connection() {
let xml = fixture("histogram_scan").replace("<identifier v=\"input\"/>", "<identifier v=\"Input_1\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "histogram_scan");
}
#[test]
fn auto_levels_keeps_reported_input_connection() {
let xml = fixture("auto_levels").replace("<identifier v=\"input\"/>", "<identifier v=\"Input\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "auto_levels");
}
#[test]
fn flood_fill_keeps_reported_mask_connection() {
let read = read_sbs(aliased_fixture("flood_fill").as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "flood_fill");
}
#[test]
fn height_blend_keeps_reported_connections_without_swapping_sources() {
let read = read_sbs(aliased_fixture("height_blend").as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_wires(&read.pkg, "height_blend");
}
#[test]
fn aliased_imports_survive_a_structural_save_and_reload() {
for def in DEFS {
let read = read_sbs(aliased_fixture(def).as_bytes(), "check.sbs", &|_| None).unwrap();
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
let xml = plain_xml(&write_sbs(&read.pkg).unwrap());
let back = read_sbs(xml.as_bytes(), "saved.sbs", &|_| None).unwrap();
assert!(!back.exact);
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
assert_wires(&back.pkg, def);
if def == "histogram_scan" {
assert_scan_values(&back.pkg);
}
}
}
#[test]
fn unknown_parameters_still_warn() {
let xml = fixture("histogram_scan").replace("<name v=\"contrast\"/>", "<name v=\"UnexpectedContrast\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert_eq!(read.warnings.len(), 1);
assert!(read.warnings[0].contains("UnexpectedContrast"));
let n = read.pkg.graphs[0].nodes.iter().find(|n| n.def == "histogram_scan").unwrap();
assert_eq!(n.params.get("position"), Some(&Value::Float(0.25)));
assert!(!n.params.contains_key("contrast") && !n.params.contains_key("UnexpectedContrast"));
}
#[test]
fn unknown_inputs_still_warn_and_drop_the_wire() {
for def in DEFS {
let original = if def == "height_blend" { "top" } else { "input" };
let xml = fixture(def).replace(&format!("<identifier v=\"{original}\"/>"), "<identifier v=\"UnexpectedInput\"/>");
let read = read_sbs(xml.as_bytes(), "check.sbs", &|_| None).unwrap();
assert_eq!(read.warnings.len(), 1);
assert!(read.warnings[0].contains("UnexpectedInput"));
let g = &read.pkg.graphs[0];
if def == "height_blend" {
assert_eq!(g.connections.len(), 1);
assert_eq!(g.connections[0].to_port, "bottom");
assert_eq!(g.connections[0].from, g.nodes[1].id);
assert_eq!(g.nodes.len(), 3);
} else {
assert!(g.connections.is_empty());
assert_eq!(g.nodes.len(), 2);
}
}
}
-549
View File
@@ -1,549 +0,0 @@
//! The atomic nodes: the built-in operations every graph is made of (blend, blur, levels,
//! curve, HSL, warp, transform, normal, distance, …) plus the graph's own input, output and
//! dot nodes.
use materialcraft_core::Gradient;
use materialcraft_image::{Image, Kind, luminance};
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::ops::{self, BLEND_MODES};
pub const ATOMIC: &str = "Atomic nodes";
pub const GRAPH_ITEMS: &str = "Graph items";
/// Output usages (the material channel an output feeds).
pub const USAGES: &[&str] = &["Base color", "Normal", "Roughness", "Metallic", "Height", "Ambient occlusion", "Emissive", "Opacity", "Specular", "Any"];
/// Machine ids of [`USAGES`], used in exports and inspect output.
pub const USAGE_IDS: &[&str] = &["baseColor", "normal", "roughness", "metallic", "height", "ambientOcclusion", "emissive", "opacity", "specular", "any"];
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("bitmap", "Bitmap", ATOMIC)
.desc("A bitmap resource of the package, resampled to the node size.")
.atomic()
.generator()
.resource("resource", "Bitmap resource")
.choice("colour_space", "Color space", &["sRGB", "Linear (data)"], 0)
.color_out()
.cook(bitmap),
node("blend", "Blend", ATOMIC)
.desc("Blends a foreground over a background with a blending mode, weighted by opacity and an optional mask.")
.atomic()
.any_in("foreground", "Foreground")
.any_in("background", "Background")
.gray_in("mask", "Opacity")
.float("opacity", "Opacity", 1.0, 0.0, 1.0)
.choice("mode", "Blending mode", BLEND_MODES, 0)
.choice("alpha", "Alpha blending", &["Use source alpha", "Ignore alpha"], 0)
.cook(blend),
node("blur", "Blur", ATOMIC).desc("Gaussian blur.").atomic().any_in("input", "Input").float("intensity", "Intensity", 2.0, 0.0, 32.0).cook(blur),
node("channels_shuffle", "Channels Shuffle", ATOMIC)
.desc("Builds a color image from any channels of two inputs.")
.atomic()
.any_in("input1", "Input 1")
.any_in("input2", "Input 2")
.choice("red", "Red", CHANNEL_SOURCES, 0)
.choice("green", "Green", CHANNEL_SOURCES, 1)
.choice("blue", "Blue", CHANNEL_SOURCES, 2)
.choice("alpha", "Alpha", CHANNEL_SOURCES, 3)
.color_out()
.cook(channels_shuffle),
node("curve", "Curve", ATOMIC).desc("Remaps values through a tone curve.").atomic().any_in("input", "Input").curve("curve", "Curve").cook(curve),
node("directional_blur", "Directional Blur", ATOMIC)
.desc("Blurs along one direction.")
.atomic()
.any_in("input", "Input")
.float("intensity", "Intensity", 10.0, 0.0, 64.0)
.angle("angle", "Angle", 0.0)
.cook(directional_blur),
node("directional_warp", "Directional Warp", ATOMIC)
.desc("Offsets the input along a direction, by an intensity map.")
.atomic()
.any_in("input", "Input")
.gray_in("intensity_input", "Intensity input")
.float("intensity", "Intensity", 10.0, 0.0, 64.0)
.angle("angle", "Warp angle", 0.0)
.cook(directional_warp),
node("distance", "Distance", ATOMIC)
.desc("Grows white areas of a mask into a distance gradient; with a source, spreads its colors outward.")
.atomic()
.gray_in("mask", "Mask")
.any_in("source", "Source")
.float("distance", "Maximum distance", 10.0, 0.0, 256.0)
.boolean("combine", "Combine distance with source", false)
.cook(distance),
node("emboss", "Emboss", ATOMIC)
.desc("Lights the input with the relief of a height map.")
.atomic()
.any_in("input", "Input")
.gray_in("height", "Height")
.float("intensity", "Intensity", 5.0, 0.0, 32.0)
.angle("light_angle", "Light angle", 0.375)
.color("highlight", "Highlight color", [1.0, 1.0, 1.0, 1.0])
.color("shadow", "Shadow color", [0.0, 0.0, 0.0, 1.0])
.cook(emboss),
node("gradient_dynamic", "Gradient (Dynamic)", ATOMIC)
.desc("Maps a grayscale input through the colors of a row of a gradient image.")
.atomic()
.gray_in("input", "Input")
.color_in("gradient", "Gradient")
.float("position", "Position", 0.5, 0.0, 1.0)
.choice("orientation", "Orientation", &["Horizontal", "Vertical"], 0)
.color_out()
.cook(gradient_dynamic),
node("gradient_map", "Gradient Map", ATOMIC)
.desc("Maps grayscale values to colors along a gradient.")
.atomic()
.gray_in("input", "Input")
.gradient("gradient", "Gradient", Gradient::default())
.choice("mode", "Color mode", &["Color", "Grayscale"], 0)
.cook(gradient_map),
node("grayscale_conversion", "Grayscale Conversion", ATOMIC)
.desc("Weighted sum of the RGBA channels.")
.atomic()
.color_in("input", "Input")
.float("red", "Red weight", 0.333, 0.0, 1.0)
.float("green", "Green weight", 0.333, 0.0, 1.0)
.float("blue", "Blue weight", 0.333, 0.0, 1.0)
.float("alpha", "Alpha weight", 0.0, 0.0, 1.0)
.boolean("flatten_alpha", "Flatten alpha", false)
.gray_out()
.cook(grayscale_conversion),
node("hsl", "HSL", ATOMIC)
.desc("Hue, saturation and lightness adjustments (0.5 = unchanged).")
.atomic()
.color_in("input", "Input")
.float("hue", "Hue", 0.5, 0.0, 1.0)
.float("saturation", "Saturation", 0.5, 0.0, 1.0)
.float("lightness", "Lightness", 0.5, 0.0, 1.0)
.color_out()
.cook(hsl),
node("levels", "Levels", ATOMIC)
.desc("Remaps the input range, midtones and output range.")
.atomic()
.any_in("input", "Input")
.float("in_low", "Level in low", 0.0, 0.0, 1.0)
.float("in_mid", "Level in mid", 0.5, 0.0, 1.0)
.float("in_high", "Level in high", 1.0, 0.0, 1.0)
.float("out_low", "Level out low", 0.0, 0.0, 1.0)
.float("out_high", "Level out high", 1.0, 0.0, 1.0)
.cook(levels),
node("normal", "Normal", ATOMIC)
.desc("Converts a height map to a tangent-space normal map.")
.atomic()
.gray_in("input", "Input")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.choice("format", "Normal format", &["OpenGL", "DirectX"], 0)
.boolean("height_alpha", "Height in alpha", false)
.color_out()
.cook(normal),
node("pixel_processor", "Pixel Processor", ATOMIC)
.desc("Computes every pixel with a function graph ($pos, $size; sample the inputs).")
.atomic()
.any_in("input0", "Input 0")
.any_in("input1", "Input 1")
.any_in("input2", "Input 2")
.any_in("input3", "Input 3")
.function("function", "Per pixel function", crate::function::default_pixel_function())
.choice("output", "Output", &["Color", "Grayscale"], 0)
.cook(crate::function::pixel_processor),
node("value_processor", "Value Processor", ATOMIC)
.desc("Computes one value with a function graph and outputs it as a uniform image.")
.atomic()
.any_in("input0", "Input 0")
.function("function", "Function", materialcraft_core::function::FnGraph::constant(materialcraft_core::Value::Float(0.5)))
.cook(crate::function::value_processor),
node("sharpen", "Sharpen", ATOMIC)
.desc("Unsharp mask.")
.atomic()
.any_in("input", "Input")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.cook(sharpen),
node("transformation", "Transformation 2D", ATOMIC)
.desc("Offsets, scales and rotates the input.")
.atomic()
.any_in("input", "Input")
.float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0)
.float2("scale", "Scale", [1.0, 1.0], 0.01, 10.0)
.angle("rotation", "Rotation", 0.0)
.choice("filtering", "Filtering", &["Bilinear", "Nearest"], 0)
.color("matte", "Matte color", [0.0, 0.0, 0.0, 0.0])
.cook(transformation),
node("uniform", "Uniform Color", ATOMIC)
.desc("A single color or gray value.")
.atomic()
.generator()
.color("color", "Color", [0.5, 0.5, 0.5, 1.0])
.choice("mode", "Output", &["Color", "Grayscale"], 0)
.cook(uniform),
node("warp", "Warp", ATOMIC)
.desc("Distorts the input along the slopes of a gradient map.")
.atomic()
.any_in("input", "Input")
.gray_in("gradient", "Gradient")
.float("intensity", "Intensity", 1.0, 0.0, 32.0)
.cook(warp),
node("input_color", "Input Color", GRAPH_ITEMS)
.desc("A color image input of the graph.")
.atomic()
.generator()
.text("identifier", "Identifier", "input")
.color("default", "Default color", [0.5, 0.5, 0.5, 1.0])
.color_out()
.cook(input_color_default),
node("input_grayscale", "Input Grayscale", GRAPH_ITEMS)
.desc("A grayscale image input of the graph.")
.atomic()
.generator()
.text("identifier", "Identifier", "input")
.color("default", "Default value", [0.5, 0.5, 0.5, 1.0])
.gray_out()
.cook(input_gray_default),
node("output", "Output", GRAPH_ITEMS)
.desc("An output of the graph: a material channel (usage) or any image.")
.atomic()
.any_in("input", "Input")
.text("identifier", "Identifier", "output")
.choice("usage", "Usage", USAGES, 0)
.cook(passthrough),
node("dot", "Dot", GRAPH_ITEMS).desc("A reroute point for wires.").atomic().any_in("input", "Input").cook(passthrough),
node("graph_instance", "Graph Instance", GRAPH_ITEMS)
.desc("Another graph of the package, used as a node.")
.atomic()
.text("graph", "Graph", "")
.cook(crate::catalog::no_cook),
]
}
const CHANNEL_SOURCES: &[&str] =
&["Input 1 red", "Input 1 green", "Input 1 blue", "Input 1 alpha", "Input 2 red", "Input 2 green", "Input 2 blue", "Input 2 alpha", "Black", "White"];
fn bitmap(ctx: &Ctx) -> CookResult {
let name = ctx.text("resource");
// "Linear (data)" keeps the file's values as stored (normal maps, masks); sRGB decodes color.
let key = materialcraft_image::resource_key(name, ctx.i("colour_space") == 1);
match (ctx.resource)(&key) {
Some(img) => Ok(vec![img.resize(ctx.w, ctx.h, ctx.tile)]),
None if name.is_empty() => Ok(vec![ctx.gen_color(|u, v| {
let c = if ((u * 8.0) as i32 + (v * 8.0) as i32) % 2 == 0 { 0.8 } else { 0.2 };
[c, c, c, 1.0]
})]),
None => Err(format!("no bitmap resource `{name}`")),
}
}
fn blend(ctx: &Ctx) -> CookResult {
let (fg, bg) = (ctx.sized(0), ctx.sized(1));
let kind = if [&fg, &bg].iter().any(|i| i.as_ref().is_some_and(|i| !i.is_gray())) { Kind::Color } else { Kind::Gray };
let fg = fg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 0.0]));
let bg = bg.unwrap_or_else(|| Image::filled(ctx.w, ctx.h, kind, [0.0, 0.0, 0.0, 1.0]));
let mask = ctx.sized(2).map(|m| m.to_gray());
let (mode, op) = (ctx.i("mode"), ctx.f("opacity"));
let use_alpha = ctx.i("alpha") == 0 && !fg.is_gray();
Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| {
let (x, y) = (x as i64, y as i64);
let m = mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false));
ops::blend_px(mode, bg.get(x, y, false), fg.get(x, y, false), op * m, use_alpha, true)
})])
}
fn blur(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let sigma = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0 * 0.5;
Ok(vec![ops::gaussian(&img, sigma, ctx.tile)])
}
fn channels_shuffle(ctx: &Ctx) -> CookResult {
let a = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
let b = ctx.any_or(1, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
let src = [ctx.i("red"), ctx.i("green"), ctx.i("blue"), ctx.i("alpha")];
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let (pa, pb) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
src.map(|s| match s {
0..=3 => pa[s as usize],
4..=7 => pb[(s - 4) as usize],
9 => 1.0,
_ => 0.0,
})
})])
}
fn curve(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let c = ctx.curve("curve");
// A 1024-entry table: the curve is smooth, so linear lookups are exact enough.
let lut: Vec<f32> = (0..=1024).map(|i| c.eval(i as f32 / 1024.0)).collect();
let f = |v: f32| {
let t = v.clamp(0.0, 1.0) * 1024.0;
let i = t as usize;
let a = lut.get(i).copied().unwrap_or(0.0);
let b = lut.get(i + 1).copied().unwrap_or(a);
a + (b - a) * (t - i as f32)
};
Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])])
}
fn dir_vec(turns: f32) -> (f32, f32) {
let a = turns * std::f32::consts::TAU;
(a.cos(), -a.sin())
}
fn directional_blur(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let len = ctx.f("intensity").max(0.0) * ctx.w as f32 / 256.0;
if len < 0.5 {
return Ok(vec![img]);
}
let (dx, dy) = dir_vec(ctx.f("angle"));
let n = (len.ceil() as i32).clamp(1, 512);
let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let mut acc = [0.0; 4];
for i in -n..=n {
let t = i as f32 / n as f32 * len * 0.5;
let p = img.sample(u + dx * t * iw, v + dy * t * ih, ctx.tile);
for k in 0..4 {
acc[k] += p[k];
}
}
acc.map(|a| a / (2 * n + 1) as f32)
})])
}
fn directional_warp(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let map = ctx.gray_or(1, 0.0);
let (dx, dy) = dir_vec(ctx.f("angle"));
let k = ctx.f("intensity") / 256.0;
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let m = map.sample_gray(u, v, ctx.tile) * k;
img.sample(u + dx * m, v + dy * m, ctx.tile)
})])
}
fn distance(ctx: &Ctx) -> CookResult {
let mask = ctx.gray_or(0, 0.0);
let maxd = (ctx.f("distance").max(0.0) * ctx.w as f32 / 256.0).max(1e-3);
let data = mask.data.clone();
let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5;
let Some(src) = ctx.sized(1) else {
let d2 = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile);
return Ok(vec![ops::gray_from(ctx.w, ctx.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]);
};
// Propagate the exact nearest mask pixel. Gradient walks can stall at stationary points or
// stop before reaching the mask, leaving background-colored gaps inside the distance range.
let (d2, sites) = ops::distance_sq_with_sites(ctx.w, ctx.h, inside, ctx.tile);
let combine = ctx.b("combine");
Ok(vec![Image::generate(ctx.w, ctx.h, src.kind, |x, y| {
let i = y as usize * ctx.w as usize + x as usize;
let site = sites.get(i).copied().unwrap_or(usize::MAX);
let mut c = if site == usize::MAX {
[0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]
} else {
src.get((site % ctx.w as usize) as i64, (site / ctx.w as usize) as i64, false)
};
let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
if d > maxd {
c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }];
} else if combine {
let f = (1.0 - d / maxd).clamp(0.0, 1.0);
c = [c[0] * f, c[1] * f, c[2] * f, c[3]];
}
c
})])
}
fn emboss(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]);
let hmap = ctx.gray_or(1, 0.0);
let (lx, ly) = dir_vec(ctx.f("light_angle"));
let k = ctx.f("intensity") * ctx.w as f32 / 64.0;
let (hi, sh) = (ctx.v4("highlight"), ctx.v4("shadow"));
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let (gx, gy) = ops::slope(&hmap, x as i64, y as i64, ctx.tile);
let l = (-(gx * lx + gy * ly) * k).clamp(-1.0, 1.0);
let p = img.get(x as i64, y as i64, false);
let tint = if l >= 0.0 { hi } else { sh };
let t = l.abs();
[p[0] + (tint[0] - p[0]) * t, p[1] + (tint[1] - p[1]) * t, p[2] + (tint[2] - p[2]) * t, p[3]]
})])
}
fn gradient_dynamic(ctx: &Ctx) -> CookResult {
let input = ctx.gray_or(0, 0.0);
let grad = ctx.input(1).map(|g| g.to_color()).unwrap_or_else(|| Image::generate_uv(256, 1, Kind::Color, |u, _| [u, u, u, 1.0]));
let pos = ctx.f("position");
let vertical = ctx.i("orientation") == 1;
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let t = input.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0);
if vertical { grad.sample(pos, t, false) } else { grad.sample(t, pos, false) }
})])
}
fn gradient_map(ctx: &Ctx) -> CookResult {
let input = ctx.gray_or(0, 0.0);
let g = ctx.gradient("gradient");
let lut: Vec<[f32; 4]> = (0..=512).map(|i| g.eval(i as f32 / 512.0)).collect();
let gray = ctx.i("mode") == 1;
let look = |v: f32| lut.get((v.clamp(0.0, 1.0) * 512.0).round() as usize).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]);
Ok(vec![if gray { input.map(Kind::Gray, |p| [luminance(look(p[0])), 0.0, 0.0, 0.0]) } else { input.map(Kind::Color, |p| look(p[0])) }])
}
fn grayscale_conversion(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
let w = [ctx.f("red"), ctx.f("green"), ctx.f("blue"), ctx.f("alpha")];
let flatten = ctx.b("flatten_alpha");
Ok(vec![img.map(Kind::Gray, |p| {
let mut v = p[0] * w[0] + p[1] * w[1] + p[2] * w[2] + p[3] * w[3];
if flatten {
v *= p[3];
}
[v, 0.0, 0.0, 0.0]
})])
}
fn hsl(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
let (dh, sat, lig) = (ctx.f("hue") - 0.5, ctx.f("saturation"), ctx.f("lightness"));
Ok(vec![img.map(Kind::Color, |p| {
let [h, s, l] = ops::rgb_to_hsl(p);
let s = if sat <= 0.5 { s * sat * 2.0 } else { s + (1.0 - s) * (sat - 0.5) * 2.0 };
let l = if lig <= 0.5 { l * lig * 2.0 } else { l + (1.0 - l) * (lig - 0.5) * 2.0 };
let c = ops::hsl_to_rgb(h + dh, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0));
[c[0], c[1], c[2], p[3]]
})])
}
/// The Levels mapping for one value.
pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 {
let span = in_high - in_low;
let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) };
// NaN (from an input or a hostile parameter) would otherwise spread through the graph.
let t = if t.is_finite() { t } else { 0.0 };
let mid = in_mid.clamp(0.001, 0.999);
let g = 0.5f32.ln() / mid.ln();
out_low + t.powf(g) * (out_high - out_low)
}
fn levels(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let p = [ctx.f("in_low"), ctx.f("in_mid"), ctx.f("in_high"), ctx.f("out_low"), ctx.f("out_high")];
let f = |v: f32| levels_fn(v, p[0], p[1], p[2], p[3], p[4]);
Ok(vec![img.map(img.kind, |c| [f(c[0]), f(c[1]), f(c[2]), c[3]])])
}
/// Tangent-space normal from a height map; `k` scales the slopes.
pub fn height_to_normal(h: &Image, k: f32, directx: bool, tile: bool, alpha_height: bool) -> Image {
Image::generate(h.w, h.h, Kind::Color, |x, y| {
let (dx, dy) = ops::slope(h, x as i64, y as i64, tile);
let (nx, ny, nz) = (-dx * k, dy * k, 1.0);
let l = (nx * nx + ny * ny + nz * nz).sqrt();
let ny = if directx { -ny } else { ny };
let a = if alpha_height { h.get_gray(x as i64, y as i64, tile) } else { 1.0 };
[nx / l * 0.5 + 0.5, ny / l * 0.5 + 0.5, nz / l * 0.5 + 0.5, a]
})
}
fn normal(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
let k = ctx.f("intensity") * ctx.w as f32 / 32.0;
Ok(vec![height_to_normal(&h, k, ctx.i("format") == 1, ctx.tile, ctx.b("height_alpha"))])
}
fn sharpen(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let soft = ops::gaussian(&img, 1.0, ctx.tile);
let k = ctx.f("intensity");
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let (a, b) = (img.get(x as i64, y as i64, false), soft.get(x as i64, y as i64, false));
[a[0] + (a[0] - b[0]) * k, a[1] + (a[1] - b[1]) * k, a[2] + (a[2] - b[2]) * k, a[3]]
})])
}
/// Sample `img` through the inverse of offset → rotate → scale about the center.
pub fn transform_sample(img: &Image, u: f32, v: f32, offset: [f32; 2], scale: [f32; 2], rot_turns: f32, nearest: bool, tile: bool) -> Option<[f32; 4]> {
let (s, c) = (rot_turns * std::f32::consts::TAU).sin_cos();
let (x, y) = (u - 0.5 - offset[0], v - 0.5 - offset[1]);
let (x, y) = (x * c - y * s, x * s + y * c);
let (sx, sy) = (if scale[0].abs() < 1e-4 { 1e-4 } else { scale[0] }, if scale[1].abs() < 1e-4 { 1e-4 } else { scale[1] });
let (su, sv) = (x / sx + 0.5, y / sy + 0.5);
if !tile && (!(0.0..1.0).contains(&su) || !(0.0..1.0).contains(&sv)) {
return None;
}
Some(if nearest { img.sample_nearest(su, sv, tile) } else { img.sample(su, sv, tile) })
}
fn transformation(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let (off, sc, rot) = (ctx.v2("offset"), ctx.v2("scale"), ctx.f("rotation"));
let nearest = ctx.i("filtering") == 1;
let matte = ctx.v4("matte");
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, off, sc, rot, nearest, ctx.tile).unwrap_or(matte))])
}
fn uniform(ctx: &Ctx) -> CookResult {
let c = ctx.v4("color");
Ok(vec![if ctx.i("mode") == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [luminance(c); 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, c) }])
}
fn warp(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let grad = ctx.gray_or(1, 0.0);
let k = ctx.f("intensity");
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (x, y) = ((u * ctx.w as f32) as i64, (v * ctx.h as f32) as i64);
let (dx, dy) = ops::slope(&grad, x, y, ctx.tile);
img.sample(u + dx * k, v + dy * k, ctx.tile)
})])
}
fn input_color_default(ctx: &Ctx) -> CookResult {
Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, ctx.v4("default"))])
}
fn input_gray_default(ctx: &Ctx) -> CookResult {
Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Gray, [ctx.v4("default")[0]; 4])])
}
pub(crate) fn passthrough(ctx: &Ctx) -> CookResult {
Ok(vec![ctx.sized(0).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))])
}
/// The kind an output port produces given the node's inputs.
pub fn output_kind(def: &NodeDef, port: usize, inputs: &[Option<Image>]) -> Kind {
match def.outputs.get(port).map(|p| p.kind) {
Some(PortKind::Gray) => Kind::Gray,
Some(PortKind::Color) => Kind::Color,
_ => inputs.iter().flatten().next().map_or(Kind::Gray, |i| i.kind),
}
}
#[cfg(test)]
mod levels_tests {
use super::levels_fn;
#[test]
fn levels_remaps_the_input_range_midtones_and_output_range() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-5;
// Identity by default.
for v in [0.0, 0.25, 0.5, 1.0] {
assert!(close(levels_fn(v, 0.0, 0.5, 1.0, 0.0, 1.0), v));
}
// The input range stretches and clips.
assert!(close(levels_fn(0.4, 0.2, 0.5, 0.6, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.1, 0.2, 0.5, 0.6, 0.0, 1.0), 0.0));
assert!(close(levels_fn(0.9, 0.2, 0.5, 0.6, 0.0, 1.0), 1.0));
// Mid is relative to the input range: the value there becomes 0.5.
assert!(close(levels_fn(0.25, 0.0, 0.25, 1.0, 0.0, 1.0), 0.5));
assert!(close(levels_fn(0.3, 0.2, 0.25, 0.6, 0.0, 1.0), 0.5));
// The output range, inverted when low > high.
assert!(close(levels_fn(0.5, 0.0, 0.5, 1.0, 0.2, 0.6), 0.4));
assert!(close(levels_fn(0.0, 0.0, 0.5, 1.0, 1.0, 0.0), 1.0));
// A collapsed input range is a threshold; NaN never escapes.
assert_eq!(levels_fn(0.49, 0.5, 0.5, 0.5, 0.0, 1.0), 0.0);
assert_eq!(levels_fn(0.5, 0.5, 0.5, 0.5, 0.0, 1.0), 1.0);
assert!(levels_fn(f32::NAN, 0.0, 0.5, 1.0, 0.0, 1.0).is_finite());
assert!(levels_fn(0.5, f32::NAN, 0.5, f32::NAN, 0.0, 1.0).is_finite());
}
}
-60
View File
@@ -1,60 +0,0 @@
//! Parameter resolution tests.
use std::collections::BTreeMap;
use materialcraft_core::Value;
use crate::{catalog, clamp_params, find, resolve_params};
fn over(k: &str, v: Value) -> BTreeMap<String, Value> {
BTreeMap::from([(k.to_string(), v)])
}
#[test]
fn resolve_params_clamps_to_hard_limits() {
let def = find("splatter").unwrap();
let p = resolve_params(def, &over("size", Value::Float(1e30)));
assert_eq!(p["size"], Value::Float(17.0));
let p = resolve_params(def, &over("size", Value::Float(-1e30)));
assert_eq!(p["size"], Value::Float(-16.0));
let p = resolve_params(def, &over("count", Value::Int(i32::MAX)));
assert_eq!(p["count"], Value::Int(33984));
let p = resolve_params(def, &over("size", Value::Float(f32::NAN)));
assert_eq!(p["size"], def.param("size").unwrap().default);
let shape = find("shape").unwrap();
let p = resolve_params(shape, &over("size_xy", Value::Float2([1e9, -1e9])));
assert_eq!(p["size_xy"], Value::Float2([34.0, -32.0]));
}
#[test]
fn clamp_params_covers_values_set_after_resolution() {
let def = find("splatter").unwrap();
let mut p = resolve_params(def, &BTreeMap::new());
p.insert("size".into(), Value::Float(1e9));
clamp_params(def, &mut p);
assert_eq!(p["size"], Value::Float(17.0));
}
#[test]
fn defaults_lie_inside_their_hard_limits() {
for def in catalog() {
let p = resolve_params(def, &BTreeMap::new());
for d in &def.params {
assert_eq!(p[d.id], d.default, "{}.{} default is outside its range", def.id, d.id);
}
}
}
#[test]
fn manual_values_beyond_slider_and_multiple_angle_turns_survive() {
let def = find("splatter").unwrap();
assert_eq!(resolve_params(def, &over("size", Value::Float(1.25)))["size"], Value::Float(1.25));
for def in catalog() {
for p in &def.params {
if p.angle && matches!(p.default, Value::Float(_)) {
let v = p.max + (p.max - p.min);
assert_eq!(resolve_params(def, &over(p.id, Value::Float(v)))[p.id], Value::Float(v));
}
}
}
}
-950
View File
@@ -1,950 +0,0 @@
//! Filters: adjustments, blending, blurs, channels, effects, normal map tools, tiling and
//! transforms.
use std::f32::consts::TAU;
use materialcraft_image::{Image, Kind, luminance};
use crate::atomic::{height_to_normal, levels_fn, transform_sample};
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::ops;
#[cfg(test)]
#[path = "filters.test.rs"]
mod tests;
const ADJ: &str = "Filters/Adjustments";
const BLENDING: &str = "Filters/Blending";
const BLURS: &str = "Filters/Blurs";
const CHANNELS: &str = "Filters/Channels";
const EFFECTS: &str = "Filters/Effects";
const NORMAL: &str = "Filters/Normal map";
const TILING: &str = "Filters/Tiling";
const TRANSFORMS: &str = "Filters/Transforms";
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
// ---- Adjustments
node("auto_levels", "Auto Levels", ADJ).desc("Stretches the input to the full 0..1 range.").any_in("input", "Input").cook(auto_levels),
node("clamp", "Clamp", ADJ)
.desc("Clamps values between a minimum and a maximum.")
.any_in("input", "Input")
.float("min", "Min", 0.0, 0.0, 1.0)
.float("max", "Max", 1.0, 0.0, 1.0)
.cook(clamp),
node("color_to_mask", "Color to Mask", ADJ)
.desc("White where the input is close to a key color.")
.color_in("input", "Input")
.color("color", "Key color", [1.0, 0.0, 0.0, 1.0])
.float("range", "Range", 0.2, 0.0, 1.0)
.float("softness", "Softness", 0.1, 0.0, 1.0)
.gray_out()
.cook(color_to_mask),
node("contrast_luminosity", "Contrast/Luminosity", ADJ)
.desc("Contrast and brightness (0 = unchanged).")
.any_in("input", "Input")
.float("contrast", "Contrast", 0.0, -1.0, 1.0)
.float("luminosity", "Luminosity", 0.0, -1.0, 1.0)
.cook(contrast_luminosity),
node("exposure", "Exposure", ADJ).desc("Exposure in stops.").any_in("input", "Input").float("stops", "Exposure (EV)", 0.0, -10.0, 10.0).cook(exposure),
node("gamma", "Gamma", ADJ).desc("Raises values to a power.").any_in("input", "Input").float("gamma", "Gamma", 1.0, 0.01, 10.0).cook(gamma),
node("histogram_range", "Histogram Range", ADJ)
.desc("Compresses values into a range around a position.")
.gray_in("input", "Input")
.float("range", "Range", 0.5, 0.0, 1.0)
.float("position", "Position", 0.5, 0.0, 1.0)
.gray_out()
.cook(histogram_range),
node("histogram_scan", "Histogram Scan", ADJ)
.desc("Thresholds the input at a position with adjustable contrast.")
.gray_in("input", "Input")
.float("position", "Position", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.boolean("invert", "Invert position", false)
.gray_out()
.cook(histogram_scan),
node("histogram_shift", "Histogram Shift", ADJ)
.desc("Shifts values with wrap-around.")
.gray_in("input", "Input")
.float("position", "Position", 0.5, 0.0, 1.0)
.gray_out()
.cook(histogram_shift),
node("invert", "Invert", ADJ).desc("1 minus the input (alpha kept).").any_in("input", "Input").boolean("alpha", "Invert alpha", false).cook(invert),
node("posterize", "Posterize", ADJ)
.desc("Quantizes values to a number of steps.")
.any_in("input", "Input")
.int("steps", "Steps", 4, 2, 256)
.cook(posterize),
node("replace_color", "Replace Color", ADJ)
.desc("Shifts colors near a source color towards a target color.")
.color_in("input", "Input")
.color("source", "Source color", [1.0, 0.0, 0.0, 1.0])
.color("target", "Target color", [0.0, 0.0, 1.0, 1.0])
.float("range", "Range", 0.3, 0.0, 1.0)
.color_out()
.cook(replace_color),
node("threshold", "Threshold", ADJ)
.desc("White above the threshold, black below.")
.gray_in("input", "Input")
.float("threshold", "Threshold", 0.5, 0.0, 1.0)
.gray_out()
.cook(threshold),
node("colorize", "Colorize", ADJ)
.desc("Tints a grayscale image between two colors.")
.gray_in("input", "Input")
.color("dark", "Dark color", [0.05, 0.03, 0.02, 1.0])
.color("light", "Light color", [0.9, 0.75, 0.5, 1.0])
.color_out()
.cook(colorize),
node("channel_mixer", "Channel Mixer", ADJ)
.desc("Each output channel as a weighted sum of the input channels.")
.color_in("input", "Input")
.float2("red_rg", "Red from R, G", [1.0, 0.0], -2.0, 2.0)
.float("red_b", "Red from B", 0.0, -2.0, 2.0)
.float2("green_rg", "Green from R, G", [0.0, 1.0], -2.0, 2.0)
.float("green_b", "Green from B", 0.0, -2.0, 2.0)
.float2("blue_rg", "Blue from R, G", [0.0, 0.0], -2.0, 2.0)
.float("blue_b", "Blue from B", 1.0, -2.0, 2.0)
.color_out()
.cook(channel_mixer),
// ---- Blending
node("height_blend", "Height Blend", BLENDING)
.desc("Blends two height maps by which is higher, with a soft contrast; also outputs the mask.")
.gray_in("top", "Height top")
.gray_in("bottom", "Height bottom")
.gray_in("mask", "Mask")
.float("offset", "Height offset", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.9, 0.0, 1.0)
.output("height", "Height", PortKind::Gray)
.output("blend_mask", "Blend mask", PortKind::Gray)
.cook(height_blend),
node("alpha_merge", "Alpha Merge", BLENDING)
.desc("Puts a grayscale image in a color image's alpha.")
.color_in("input", "Color")
.gray_in("alpha", "Alpha")
.color_out()
.cook(alpha_merge),
node("rgba_merge", "RGBA Merge", CHANNELS)
.desc("Builds a color image from four grayscale channels.")
.gray_in("r", "R")
.gray_in("g", "G")
.gray_in("b", "B")
.gray_in("a", "A")
.color_out()
.cook(rgba_merge),
node("rgba_split", "RGBA Split", CHANNELS)
.desc("Splits a color image into four grayscale channels.")
.color_in("input", "RGBA")
.output("r", "R", PortKind::Gray)
.output("g", "G", PortKind::Gray)
.output("b", "B", PortKind::Gray)
.output("a", "A", PortKind::Gray)
.cook(rgba_split),
node("switch", "Switch", BLENDING)
.desc("Outputs input A or input B.")
.any_in("a", "Input A")
.any_in("b", "Input B")
.boolean("use_b", "Use input B", false)
.cook(switch),
// ---- Blurs
node("anisotropic_blur", "Anisotropic Blur", BLURS)
.desc("A Gaussian blur stronger along one direction.")
.any_in("input", "Input")
.float("intensity", "Intensity", 4.0, 0.0, 32.0)
.float("anisotropy", "Anisotropy", 0.5, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.cook(anisotropic_blur),
node("non_uniform_blur", "Non Uniform Blur", BLURS)
.desc("Blurs more where the blur map is white.")
.any_in("input", "Input")
.gray_in("blur_map", "Blur map")
.float("intensity", "Intensity", 4.0, 0.0, 32.0)
.cook(non_uniform_blur),
node("radial_blur", "Radial Blur", BLURS)
.desc("Zoom blur from a center.")
.any_in("input", "Input")
.float("intensity", "Intensity", 0.2, 0.0, 1.0)
.float2("center", "Center", [0.5, 0.5], 0.0, 1.0)
.cook(radial_blur),
node("slope_blur", "Slope Blur", BLURS)
.desc("Smears the input along the slopes of a map, like flowing material.")
.any_in("input", "Input")
.gray_in("slope", "Slope")
.float("intensity", "Intensity", 8.0, -64.0, 64.0)
.int("samples", "Samples", 8, 1, 32)
.choice("mode", "Mode", &["Blur", "Min", "Max"], 0)
.cook(slope_blur),
// ---- Effects
node("ambient_occlusion", "Ambient Occlusion", EFFECTS)
.desc("Darkens creases of a height map.")
.gray_in("height", "Height")
.float("spread", "Spreading", 0.15, 0.0, 1.0)
.float("intensity", "Height depth", 0.5, 0.0, 1.0)
.gray_out()
.cook(ambient_occlusion),
node("bevel", "Bevel", EFFECTS)
.desc("Rounds the edges of a mask into a height ramp.")
.gray_in("input", "Mask")
.float("distance", "Distance", 0.05, -1.0, 1.0)
.float("smoothing", "Smoothing", 0.0, 0.0, 1.0)
.gray_out()
.cook(bevel),
node("curvature", "Curvature", EFFECTS)
.desc("Convexity (white) and concavity (black) of a normal map.")
.color_in("normal", "Normal")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.gray_out()
.cook(curvature),
node("dilation", "Dilation", EFFECTS)
.desc("Grows bright areas (maximum filter).")
.any_in("input", "Input")
.int("radius", "Radius", 2, 0, 64)
.cook(dilation),
node("erosion", "Erosion", EFFECTS)
.desc("Shrinks bright areas (minimum filter).")
.any_in("input", "Input")
.int("radius", "Radius", 2, 0, 64)
.cook(erosion),
node("edge_detect", "Edge Detect", EFFECTS)
.desc("White along the edges of a mask.")
.gray_in("input", "Input")
.float("width", "Edge width", 2.0, 0.0, 32.0)
.float("roundness", "Edge roundness", 0.5, 0.0, 1.0)
.gray_out()
.cook(edge_detect),
node("glow", "Glow", EFFECTS)
.desc("A soft glow around bright areas.")
.any_in("input", "Input")
.float("threshold", "Threshold", 0.5, 0.0, 1.0)
.float("size", "Size", 8.0, 0.0, 64.0)
.float("amount", "Amount", 0.5, 0.0, 2.0)
.cook(glow),
node("highpass", "Highpass", EFFECTS)
.desc("Keeps the fine detail, centered on gray.")
.any_in("input", "Input")
.float("radius", "Radius", 6.0, 0.0, 64.0)
.cook(highpass),
node("mosaic", "Mosaic", EFFECTS).desc("Pixelates into blocks.").any_in("input", "Input").int("cells", "Cells", 16, 1, 512).cook(mosaic),
node("swirl", "Swirl", EFFECTS)
.desc("Twists the image around its center.")
.any_in("input", "Input")
.float("amount", "Amount", 0.5, -4.0, 4.0)
.float("radius", "Radius", 0.5, 0.0, 1.0)
.cook(swirl),
node("vignette", "Vignette", EFFECTS)
.desc("Darkens towards the borders.")
.any_in("input", "Input")
.float("amount", "Amount", 0.5, 0.0, 1.0)
.float("softness", "Softness", 0.5, 0.0, 1.0)
.cook(vignette),
node("quantize", "Quantize Grayscale", EFFECTS)
.desc("Snaps gray values to steps with soft transitions.")
.gray_in("input", "Input")
.int("steps", "Steps", 4, 2, 64)
.float("smoothness", "Smoothness", 0.1, 0.0, 1.0)
.gray_out()
.cook(quantize),
// ---- Normal map
node("height_to_normal", "Height to Normal", NORMAL)
.desc("Same as Normal: a normal map from a height map.")
.gray_in("input", "Height")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.choice("format", "Normal format", &["OpenGL", "DirectX"], 0)
.color_out()
.cook(height_normal),
node("normal_blend", "Normal Blend", NORMAL)
.desc("Combines two normal maps (reoriented normal mapping).")
.color_in("base", "Normal base")
.color_in("detail", "Normal detail")
.gray_in("mask", "Mask")
.float("opacity", "Opacity", 1.0, 0.0, 1.0)
.color_out()
.cook(normal_blend),
node("normal_invert", "Normal Invert", NORMAL)
.desc("Flips the green (and optionally red) channel: OpenGL / DirectX.")
.color_in("input", "Normal")
.boolean("red", "Invert red", false)
.boolean("green", "Invert green", true)
.color_out()
.cook(normal_invert),
node("normal_normalize", "Normal Normalize", NORMAL)
.desc("Rescales normals to unit length.")
.color_in("input", "Normal")
.color_out()
.cook(normal_normalize),
node("normal_intensity", "Normal Intensity", NORMAL)
.desc("Strengthens or flattens a normal map.")
.color_in("input", "Normal")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.color_out()
.cook(normal_intensity),
node("normal_to_height", "Normal to Height", NORMAL)
.desc("Reconstructs a height map from a normal map.")
.color_in("input", "Normal")
.float("intensity", "Height scale", 1.0, 0.0, 10.0)
.gray_out()
.cook(normal_to_height),
// ---- Tiling
node("make_it_tile", "Make It Tile", TILING)
.desc("Cross-fades the borders so a photo tiles.")
.any_in("input", "Input")
.float("blend", "Blend width", 0.25, 0.0, 0.5)
.cook(make_it_tile),
node("safe_transform", "Safe Transform", TILING)
.desc("Tiling-safe transform: whole-number tiling, offsets and 90° rotations.")
.any_in("input", "Input")
.int("tile", "Tile", 1, 1, 64)
.float2("offset", "Offset", [0.0, 0.0], -1.0, 1.0)
.choice("rotation", "Rotation", &["0°", "90°", "180°", "270°"], 0)
.boolean("flip", "Flip", false)
.cook(safe_transform),
// ---- Transforms
node("mirror", "Mirror", TRANSFORMS)
.desc("Mirrors one half of the image onto the other.")
.any_in("input", "Input")
.choice("axis", "Mirror type", &["Horizontal", "Vertical", "Corner"], 0)
.boolean("flip", "Flip side", false)
.cook(mirror),
node("kaleidoscope", "Kaleidoscope", TRANSFORMS)
.desc("Repeats a wedge of the image around the center.")
.any_in("input", "Input")
.int("segments", "Segments", 6, 2, 64)
.angle("angle", "Angle", 0.0)
.cook(kaleidoscope),
node("cartesian_to_polar", "Cartesian to Polar", TRANSFORMS)
.desc("Wraps the image around the center.")
.any_in("input", "Input")
.cook(cartesian_to_polar),
node("polar_to_cartesian", "Polar to Cartesian", TRANSFORMS)
.desc("Unwraps a circular image into bands.")
.any_in("input", "Input")
.cook(polar_to_cartesian),
node("skew", "Skew", TRANSFORMS)
.desc("Shears the image.")
.any_in("input", "Input")
.float("amount", "Amount", 0.25, -2.0, 2.0)
.boolean("vertical", "Vertical", false)
.cook(skew),
]
}
fn src(ctx: &Ctx) -> Image {
ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0])
}
fn per_value(ctx: &Ctx, f: impl Fn(f32) -> f32 + Sync) -> CookResult {
let img = src(ctx);
Ok(vec![img.map(img.kind, |p| [f(p[0]), f(p[1]), f(p[2]), p[3]])])
}
fn auto_levels(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (lo, hi) = img.range();
let span = (hi - lo).max(1e-6);
per_value(ctx, |v| (v - lo) / span)
}
fn clamp(ctx: &Ctx) -> CookResult {
let (a, b) = (ctx.f("min"), ctx.f("max"));
per_value(ctx, |v| v.max(a).min(b.max(a)))
}
fn color_to_mask(ctx: &Ctx) -> CookResult {
let img = src(ctx).to_color();
let (k, r, s) = (ctx.v4("color"), ctx.f("range"), ctx.f("softness").max(1e-4));
Ok(vec![img.map(Kind::Gray, |p| {
let d = ((p[0] - k[0]).powi(2) + (p[1] - k[1]).powi(2) + (p[2] - k[2]).powi(2)).sqrt();
[(1.0 - (d - r) / s).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
})])
}
fn contrast_luminosity(ctx: &Ctx) -> CookResult {
let (c, l) = (ctx.f("contrast"), ctx.f("luminosity"));
let k = if c >= 0.0 { 1.0 / (1.0 - c * 0.99) } else { 1.0 + c };
per_value(ctx, |v| ((v - 0.5) * k + 0.5 + l).clamp(0.0, 1.0))
}
fn exposure(ctx: &Ctx) -> CookResult {
// Past +-64 stops the result is all black/white anyway; this keeps 2^stops finite.
let k = 2f32.powf(ctx.f("stops").clamp(-64.0, 64.0));
per_value(ctx, |v| v * k)
}
fn gamma(ctx: &Ctx) -> CookResult {
let g = ctx.f("gamma").max(0.01);
per_value(ctx, |v| v.max(0.0).powf(1.0 / g))
}
fn histogram_range(ctx: &Ctx) -> CookResult {
let (r, p) = (ctx.f("range"), ctx.f("position"));
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |c| [(p + (c[0] - 0.5) * r).clamp(0.0, 1.0), 0.0, 0.0, 0.0])])
}
/// The Histogram Scan mapping.
pub fn histogram_scan_fn(v: f32, position: f32, contrast: f32) -> f32 {
let width = (1.0 - contrast).max(0.001);
let lo = position * (1.0 + width) - width;
levels_fn(v, lo, 0.5, lo + width, 0.0, 1.0)
}
fn histogram_scan(ctx: &Ctx) -> CookResult {
let p = if ctx.b("invert") { 1.0 - ctx.f("position") } else { ctx.f("position") };
let c = ctx.f("contrast");
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |v| [histogram_scan_fn(v[0], 1.0 - p, c), 0.0, 0.0, 0.0])])
}
fn histogram_shift(ctx: &Ctx) -> CookResult {
let p = ctx.f("position");
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |v| [(v[0] + p).rem_euclid(1.0), 0.0, 0.0, 0.0])])
}
fn invert(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let a = ctx.b("alpha");
Ok(vec![img.map(img.kind, |p| [1.0 - p[0], 1.0 - p[1], 1.0 - p[2], if a { 1.0 - p[3] } else { p[3] }])])
}
fn posterize(ctx: &Ctx) -> CookResult {
let n = (ctx.i("steps").max(2) - 1) as f32;
per_value(ctx, |v| (v * n).round() / n)
}
fn replace_color(ctx: &Ctx) -> CookResult {
let img = src(ctx).to_color();
let (s, t, r) = (ctx.v4("source"), ctx.v4("target"), ctx.f("range").max(1e-4));
Ok(vec![img.map(Kind::Color, |p| {
let d = ((p[0] - s[0]).powi(2) + (p[1] - s[1]).powi(2) + (p[2] - s[2]).powi(2)).sqrt();
let w = (1.0 - d / r).clamp(0.0, 1.0);
[p[0] + (t[0] - s[0]) * w, p[1] + (t[1] - s[1]) * w, p[2] + (t[2] - s[2]) * w, p[3]]
})])
}
fn threshold(ctx: &Ctx) -> CookResult {
let t = ctx.f("threshold");
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |v| [if v[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])])
}
fn colorize(ctx: &Ctx) -> CookResult {
let (a, b) = (ctx.v4("dark"), ctx.v4("light"));
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Color, |v| {
let t = v[0];
[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, 1.0]
})])
}
fn channel_mixer(ctx: &Ctx) -> CookResult {
let img = src(ctx).to_color();
let (r, g, b) = (ctx.v2("red_rg"), ctx.v2("green_rg"), ctx.v2("blue_rg"));
let (rb, gb, bb) = (ctx.f("red_b"), ctx.f("green_b"), ctx.f("blue_b"));
Ok(vec![
img.map(Kind::Color, |p| [r[0] * p[0] + r[1] * p[1] + rb * p[2], g[0] * p[0] + g[1] * p[1] + gb * p[2], b[0] * p[0] + b[1] * p[1] + bb * p[2], p[3]]),
])
}
fn height_blend(ctx: &Ctx) -> CookResult {
let (top, bot) = (ctx.gray_or(0, 0.0), ctx.gray_or(1, 0.0));
let mask = ctx.sized(2).map(|m| m.to_gray());
let (off, c) = (ctx.f("offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999));
let soft = (1.0 - c) * 0.5 + 1e-4;
let n = (ctx.w * ctx.h) as usize;
let mut h = vec![0.0; n];
let mut m = vec![0.0; n];
for i in 0..n {
let (t, b) = (top.data[i] + off, bot.data[i]);
let mut k = ((t - b) / soft * 0.5 + 0.5).clamp(0.0, 1.0);
if let Some(mm) = &mask {
k *= mm.data[i];
}
h[i] = b + (t - b) * k;
m[i] = k;
}
Ok(vec![ops::gray_from(ctx.w, ctx.h, h), ops::gray_from(ctx.w, ctx.h, m)])
}
fn alpha_merge(ctx: &Ctx) -> CookResult {
let c = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
let a = ctx.gray_or(1, 1.0);
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let p = c.get(x as i64, y as i64, false);
[p[0], p[1], p[2], a.get_gray(x as i64, y as i64, false)]
})])
}
fn rgba_merge(ctx: &Ctx) -> CookResult {
let ch: Vec<Image> = (0..4).map(|i| ctx.gray_or(i, if i == 3 { 1.0 } else { 0.0 })).collect();
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let i = (y * ctx.w + x) as usize;
[ch[0].data[i], ch[1].data[i], ch[2].data[i], ch[3].data[i]]
})])
}
fn rgba_split(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
Ok((0..4).map(|k| img.map(Kind::Gray, |p| [p[k], 0.0, 0.0, 0.0])).collect())
}
fn switch(ctx: &Ctx) -> CookResult {
let i = usize::from(ctx.b("use_b"));
Ok(vec![ctx.sized(i).unwrap_or_else(|| Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]))])
}
fn anisotropic_blur(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let s = ctx.f("intensity") * ctx.w as f32 / 512.0;
let an = ctx.f("anisotropy");
let a = ctx.f("angle") * TAU;
// Blur in a rotated frame: rotate, blur x/y separately, rotate back.
let (sx, sy) = (s, s * (1.0 - an));
if a.abs() < 1e-4 {
return Ok(vec![blur_xy(&img, sx, sy, ctx.tile)]);
}
let rotated =
Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&img, u, v, [0.0, 0.0], [1.0, 1.0], a / TAU, false, true).unwrap_or([0.0; 4]));
let b = blur_xy(&rotated, sx, sy, true);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| transform_sample(&b, u, v, [0.0, 0.0], [1.0, 1.0], -a / TAU, false, true).unwrap_or([0.0; 4]))])
}
fn blur_xy(img: &Image, sx: f32, sy: f32, tile: bool) -> Image {
if !sx.is_finite() || !sy.is_finite() {
return img.clone();
}
// Separable: a horizontal-only Gaussian is a 2D one on an image stretched vertically, so
// blur fully with the smaller sigma and add the extra along x.
let cap = img.w.max(img.h) as f32;
let (sx, sy) = (sx.min(cap), sy.min(cap));
let base = ops::gaussian(img, sy, tile);
let extra = (sx * sx - sy * sy).max(0.0).sqrt();
if extra < 0.1 {
return base;
}
// Independent Gaussians compose in quadrature, so one horizontal Gaussian of sigma `extra`
// finishes the job (box passes: O(1) per pixel, sigma clamped to the image size).
ops::gaussian_h(&base, extra, tile)
}
fn non_uniform_blur(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let map = ctx.gray_or(1, 1.0);
let s = ctx.f("intensity") * ctx.w as f32 / 512.0;
// Four blur levels, blended by the map.
let levels: Vec<Image> = (0..4).map(|i| ops::gaussian(&img, s * i as f32 / 3.0, ctx.tile)).collect();
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let t = map.get_gray(x as i64, y as i64, false).clamp(0.0, 1.0) * 3.0;
let i = (t.floor() as usize).min(2);
let f = t - i as f32;
let (a, b) = (levels[i].get(x as i64, y as i64, false), levels[i + 1].get(x as i64, y as i64, false));
[a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f, a[3] + (b[3] - a[3]) * f]
})])
}
fn radial_blur(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (k, c) = (ctx.f("intensity"), ctx.v2("center"));
let n = 24;
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let mut acc = [0.0; 4];
for i in 0..n {
let t = 1.0 - k * i as f32 / n as f32;
let p = img.sample(c[0] + (u - c[0]) * t, c[1] + (v - c[1]) * t, ctx.tile);
for j in 0..4 {
acc[j] += p[j] / n as f32;
}
}
acc
})])
}
fn slope_blur(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let slope = ops::gaussian(&ctx.gray_or(1, 0.5), 1.0, ctx.tile);
let k = ctx.f("intensity") / 256.0;
let n = ctx.i("samples").clamp(1, 64);
let mode = ctx.i("mode");
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (mut pu, mut pv) = (u, v);
let mut acc = img.sample(u, v, ctx.tile);
let mut cnt = 1.0;
for _ in 0..n {
let (x, y) = ((pu * ctx.w as f32) as i64, (pv * ctx.h as f32) as i64);
let (dx, dy) = ops::slope(&slope, x, y, ctx.tile);
let l = (dx * dx + dy * dy).sqrt().max(1e-6);
pu -= dx / l * k / n as f32 * 4.0;
pv -= dy / l * k / n as f32 * 4.0;
let p = img.sample(pu, pv, ctx.tile);
for j in 0..4 {
acc[j] = match mode {
1 => acc[j].min(p[j]),
2 => acc[j].max(p[j]),
_ => acc[j] + p[j],
};
}
cnt += 1.0;
}
if mode == 0 { acc.map(|a| a / cnt) } else { acc }
})])
}
fn ambient_occlusion(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
let spread = ctx.f("spread").max(0.001) * ctx.w as f32 * 0.25;
let depth = ctx.f("intensity");
let wide = ops::gaussian(&h, spread, ctx.tile);
let mid = ops::gaussian(&h, spread * 0.35, ctx.tile);
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| {
let i = (y * ctx.w + x) as usize;
let occ = ((wide.data[i] - h.data[i]).max(0.0) * 0.6 + (mid.data[i] - h.data[i]).max(0.0) * 0.4) * depth * 6.0;
[(1.0 - occ).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
})])
}
fn bevel(ctx: &Ctx) -> CookResult {
let m = ctx.gray_or(0, 0.0);
let d = ctx.f("distance");
let dist_px = (d.abs() * ctx.w as f32).max(1e-3);
let data = m.data.clone();
let outside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile);
let inside = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile);
let v: Vec<f32> = (0..outside.len())
.map(|i| {
if d >= 0.0 {
// Inner bevel: ramp up from the edge inward.
if data[i] > 0.5 { (inside[i].sqrt() / dist_px).min(1.0) } else { 0.0 }
} else if data[i] > 0.5 {
1.0
} else {
(1.0 - outside[i].sqrt() / dist_px).max(0.0)
}
})
.collect();
let img = ops::gray_from(ctx.w, ctx.h, v);
let s = ctx.f("smoothing") * ctx.w as f32 / 128.0;
Ok(vec![ops::gaussian(&img.map(Kind::Gray, |p| [(p[0] * std::f32::consts::FRAC_PI_2).sin(), 0.0, 0.0, 0.0]), s, ctx.tile)])
}
fn curvature(ctx: &Ctx) -> CookResult {
let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color();
let k = ctx.f("intensity") * 2.0;
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| {
let (x, y) = (x as i64, y as i64);
let dx = n.get(x + 1, y, ctx.tile)[0] - n.get(x - 1, y, ctx.tile)[0];
let dy = n.get(x, y + 1, ctx.tile)[1] - n.get(x, y - 1, ctx.tile)[1];
[(0.5 + (dx - dy) * k).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
})])
}
fn morph(ctx: &Ctx, max: bool) -> CookResult {
let img = src(ctx);
let r = ctx.i("radius").clamp(0, 64) as i64;
if r == 0 {
return Ok(vec![img]);
}
// Separable square window: rows then columns.
let pass = |src: &Image, horizontal: bool| {
Image::generate(src.w, src.h, src.kind, |x, y| {
let mut acc = src.get(x as i64, y as i64, ctx.tile);
for o in -r..=r {
let p = if horizontal { src.get(x as i64 + o, y as i64, ctx.tile) } else { src.get(x as i64, y as i64 + o, ctx.tile) };
for k in 0..4 {
acc[k] = if max { acc[k].max(p[k]) } else { acc[k].min(p[k]) };
}
}
acc
})
};
Ok(vec![pass(&pass(&img, true), false)])
}
fn dilation(ctx: &Ctx) -> CookResult {
morph(ctx, true)
}
fn erosion(ctx: &Ctx) -> CookResult {
morph(ctx, false)
}
fn edge_detect(ctx: &Ctx) -> CookResult {
let m = ctx.gray_or(0, 0.0);
let w = (ctx.f("width") * ctx.w as f32 / 256.0).max(0.5);
let data = m.data.clone();
let a = ops::distance_sq(ctx.w, ctx.h, |i| data[i] > 0.5, ctx.tile);
let b = ops::distance_sq(ctx.w, ctx.h, |i| data[i] <= 0.5, ctx.tile);
let round = ctx.f("roundness");
let v: Vec<f32> = a
.iter()
.zip(&b)
.map(|(a, b)| {
let d = a.sqrt().max(b.sqrt());
let t = (1.0 - d / w).max(0.0);
// A non-positive exponent on t = 0 gives inf; in range (round <= 1) it is >= 0.2.
t.powf((1.0 - round * 0.8).max(0.01))
})
.collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
}
fn glow(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (t, amt) = (ctx.f("threshold"), ctx.f("amount"));
let bright = img.map(img.kind, |p| {
let l = luminance(p);
let k = if l > t { 1.0 } else { 0.0 };
[p[0] * k, p[1] * k, p[2] * k, p[3]]
});
let b = ops::gaussian(&bright, ctx.f("size") * ctx.w as f32 / 256.0, ctx.tile);
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let (p, g) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
[p[0] + g[0] * amt, p[1] + g[1] * amt, p[2] + g[2] * amt, p[3]]
})])
}
fn highpass(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let b = ops::gaussian(&img, ctx.f("radius") * ctx.w as f32 / 256.0, ctx.tile);
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let (p, q) = (img.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
[p[0] - q[0] + 0.5, p[1] - q[1] + 0.5, p[2] - q[2] + 0.5, p[3]]
})])
}
fn mosaic(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let n = ctx.i("cells").max(1) as f32;
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| img.sample(((u * n).floor() + 0.5) / n, ((v * n).floor() + 0.5) / n, ctx.tile))])
}
fn swirl(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (amt, rad) = (ctx.f("amount") * TAU, ctx.f("radius").max(1e-3));
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (x, y) = (u - 0.5, v - 0.5);
let r = (x * x + y * y).sqrt();
let t = (1.0 - r / rad).max(0.0);
let a = amt * t * t;
let (s, c) = a.sin_cos();
img.sample(x * c - y * s + 0.5, x * s + y * c + 0.5, ctx.tile)
})])
}
fn vignette(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (amt, soft) = (ctx.f("amount"), ctx.f("softness").max(0.01));
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let p = img.sample_nearest(u, v, false);
let r = ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() * std::f32::consts::SQRT_2;
let k = 1.0 - amt * ((r - (1.0 - soft)) / soft).clamp(0.0, 1.0);
[p[0] * k, p[1] * k, p[2] * k, p[3]]
})])
}
fn quantize(ctx: &Ctx) -> CookResult {
let n = (ctx.i("steps").max(2) - 1) as f32;
let s = ctx.f("smoothness").clamp(0.0, 1.0) * 0.5;
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |p| {
let x = p[0] * n;
let f = x.fract();
let t = if s > 0.0 { ((f - 0.5 + s) / (2.0 * s)).clamp(0.0, 1.0) } else { (f >= 0.5) as i32 as f32 };
[(x.floor() + t * t * (3.0 - 2.0 * t)) / n, 0.0, 0.0, 0.0]
})])
}
fn height_normal(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
Ok(vec![height_to_normal(&h, ctx.f("intensity") * ctx.w as f32 / 32.0, ctx.i("format") == 1, ctx.tile, false)])
}
fn unpack(p: [f32; 4]) -> [f32; 3] {
[p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0]
}
fn pack(n: [f32; 3], a: f32) -> [f32; 4] {
let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6);
[n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a]
}
fn flat_normal(ctx: &Ctx, i: usize) -> Image {
ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color()
}
fn normal_blend(ctx: &Ctx) -> CookResult {
let (base, det) = (flat_normal(ctx, 0), flat_normal(ctx, 1));
let mask = ctx.sized(2).map(|m| m.to_gray());
let op = ctx.f("opacity");
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let (x, y) = (x as i64, y as i64);
let k = op * mask.as_ref().map_or(1.0, |m| m.get_gray(x, y, false));
let b = unpack(base.get(x, y, false));
let mut d = unpack(det.get(x, y, false));
d = [d[0] * k, d[1] * k, 1.0 + (d[2] - 1.0) * k];
// Reoriented normal mapping (Barré-Brisebois & Hill).
let t = [b[0], b[1], b[2] + 1.0];
let u = [-d[0], -d[1], d[2]];
// A base normal pointing straight away (z = -1) has no reorientation; keep it.
if t[2].abs() < 1e-4 {
return pack(b, 1.0);
}
let dot = t[0] * u[0] + t[1] * u[1] + t[2] * u[2];
let r = [t[0] * dot / t[2] - u[0], t[1] * dot / t[2] - u[1], t[2] * dot / t[2] - u[2]];
pack(r, 1.0)
})])
}
fn normal_invert(ctx: &Ctx) -> CookResult {
let n = flat_normal(ctx, 0);
let (r, g) = (ctx.b("red"), ctx.b("green"));
Ok(vec![n.map(Kind::Color, |p| [if r { 1.0 - p[0] } else { p[0] }, if g { 1.0 - p[1] } else { p[1] }, p[2], p[3]])])
}
fn normal_normalize(ctx: &Ctx) -> CookResult {
let n = flat_normal(ctx, 0);
Ok(vec![n.map(Kind::Color, |p| pack(unpack(p), p[3]))])
}
fn normal_intensity(ctx: &Ctx) -> CookResult {
let n = flat_normal(ctx, 0);
let k = ctx.f("intensity");
Ok(vec![n.map(Kind::Color, |p| {
let v = unpack(p);
pack([v[0] * k, v[1] * k, v[2].max(1e-3)], p[3])
})])
}
fn normal_to_height(ctx: &Ctx) -> CookResult {
// Integrate the slopes at several scales (a multigrid-style Poisson solve: coarse levels set
// the broad shape, finer ones the detail).
let n = flat_normal(ctx, 0);
let (w, h) = (ctx.w, ctx.h);
let gx = n.map(Kind::Gray, |p| {
let v = unpack(p);
[-v[0] / v[2].max(0.1), 0.0, 0.0, 0.0]
});
let gy = n.map(Kind::Gray, |p| {
let v = unpack(p);
[v[1] / v[2].max(0.1), 0.0, 0.0, 0.0]
});
let mut height = Image::filled(8.min(w), 8.min(h), Kind::Gray, [0.0; 4]);
let mut size = 8u32;
loop {
let (sw, sh) = (size.min(w), size.min(h));
let (gxs, gys) = (gx.resize(sw, sh, true), gy.resize(sw, sh, true));
let scale = w as f32 / sw as f32;
let mut cur = height.resize(sw, sh, true);
for _ in 0..40 {
let prev = cur.clone();
cur = Image::generate(sw, sh, Kind::Gray, |x, y| {
let (x, y) = (x as i64, y as i64);
let nb = prev.get(x - 1, y, true)[0] + prev.get(x + 1, y, true)[0] + prev.get(x, y - 1, true)[0] + prev.get(x, y + 1, true)[0];
// Divergence of the slope field in pixels of this level: the slopes are per
// full-size pixel and one pixel here spans `scale` of them, so multiply.
let div = (gxs.get(x + 1, y, true)[0] - gxs.get(x - 1, y, true)[0] + gys.get(x, y + 1, true)[0] - gys.get(x, y - 1, true)[0]) * 0.5 * scale;
[(nb - div) * 0.25, 0.0, 0.0, 0.0]
});
}
height = cur;
if sw >= w && sh >= h {
break;
}
size *= 2;
}
let (lo, hi) = height.range();
let k = ctx.f("intensity");
let span = (hi - lo).max(1e-6);
Ok(vec![height.map(Kind::Gray, |p| [(((p[0] - lo) / span - 0.5) * k + 0.5).clamp(0.0, 1.0), 0.0, 0.0, 0.0])])
}
fn make_it_tile(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let b = ctx.f("blend").clamp(0.01, 0.5);
// Blend the image with a half-offset copy near the borders.
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let p = img.sample(u, v, true);
let q = img.sample(u + 0.5, v + 0.5, true);
let edge = (u.min(1.0 - u)).min(v.min(1.0 - v));
let t = (edge / b).clamp(0.0, 1.0);
let t = t * t * (3.0 - 2.0 * t);
[q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t, q[3] + (p[3] - q[3]) * t]
})])
}
fn safe_transform(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let n = ctx.i("tile").max(1) as f32;
let off = ctx.v2("offset");
let (rot, flip) = (ctx.i("rotation"), ctx.b("flip"));
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (mut x, mut y) = ((u * n - off[0]).rem_euclid(1.0), (v * n - off[1]).rem_euclid(1.0));
for _ in 0..rot.rem_euclid(4) {
(x, y) = (y, 1.0 - x);
}
if flip {
x = 1.0 - x;
}
img.sample(x, y, true)
})])
}
fn mirror(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (axis, flip) = (ctx.i("axis"), ctx.b("flip"));
let m = |t: f32| {
if flip {
if t < 0.5 { 1.0 - t } else { t }
} else if t > 0.5 {
1.0 - t
} else {
t
}
};
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| match axis {
1 => img.sample(u, m(v), ctx.tile),
2 => img.sample(m(u), m(v), ctx.tile),
_ => img.sample(m(u), v, ctx.tile),
})])
}
fn kaleidoscope(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let seg = TAU / ctx.i("segments").clamp(2, 64) as f32;
let a0 = ctx.f("angle") * TAU;
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (x, y) = (u - 0.5, v - 0.5);
let r = (x * x + y * y).sqrt();
let mut a = (y.atan2(x) - a0).rem_euclid(seg);
if a > seg * 0.5 {
a = seg - a;
}
let a = a + a0;
img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile)
})])
}
fn cartesian_to_polar(ctx: &Ctx) -> CookResult {
let img = src(ctx);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (x, y) = (u - 0.5, v - 0.5);
let r = (x * x + y * y).sqrt() * 2.0;
let a = (y.atan2(x) / TAU).rem_euclid(1.0);
img.sample(a, r, true)
})])
}
fn polar_to_cartesian(ctx: &Ctx) -> CookResult {
let img = src(ctx);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (a, r) = (u * TAU, v * 0.5);
img.sample(0.5 + r * a.cos(), 0.5 + r * a.sin(), ctx.tile)
})])
}
fn skew(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (k, vert) = (ctx.f("amount"), ctx.b("vertical"));
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
if vert { img.sample(u, v + (u - 0.5) * k, ctx.tile) } else { img.sample(u + (v - 0.5) * k, v, ctx.tile) }
})])
}
-103
View File
@@ -1,103 +0,0 @@
#[cfg(test)]
mod normal_blend_tests {
use std::collections::BTreeMap;
use materialcraft_image::{Image, Kind};
use crate::catalog::Ctx;
use crate::catalog::{find, resolve_params};
/// A base normal pointing straight away from the viewer (blue = 0) used to divide by zero.
#[test]
fn normal_blend_with_a_black_base_stays_finite() {
let def = find("normal_blend").expect("normal_blend exists");
let params = resolve_params(def, &BTreeMap::new());
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let black = Image::filled(8, 8, Kind::Color, [0.0, 0.0, 0.0, 1.0]);
let bump = Image::filled(8, 8, Kind::Color, [0.7, 0.4, 0.6, 1.0]);
let inputs = vec![Some(black), Some(bump), None];
let ctx = Ctx { w: 8, h: 8, seed: 1, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
let out = (def.cook)(&ctx).expect("cooks");
assert!(out[0].data.iter().all(|v| v.is_finite()), "NaN or Inf in the blended normal");
}
}
// Tests for the blur helpers.
use materialcraft_image::{Image, Kind};
use super::blur_xy;
fn noise(n: u32) -> Image {
Image::generate(n, n, Kind::Gray, |x, y| [((x * 7 + y * 13) % 17) as f32 / 16.0, 0.0, 0.0, 1.0])
}
#[test]
fn blur_xy_huge_sigma_is_bounded_and_finite() {
let t = std::time::Instant::now();
let out = blur_xy(&noise(64), 1e14, 1.0, true);
assert!(out.data.iter().all(|v| v.is_finite()));
assert!(t.elapsed().as_secs() < 20, "took {:?}", t.elapsed());
}
#[test]
fn blur_xy_horizontal_blur_is_stronger_than_vertical() {
// Vertical stripes survive a vertical-only blur but are smoothed by a horizontal one.
let img = Image::generate(64, 64, Kind::Gray, |x, _| [(x % 2) as f32, 0.0, 0.0, 1.0]);
let out = blur_xy(&img, 6.0, 0.0, true);
let range = out.data.chunks(1).map(|v| v[0]).fold((f32::MAX, f32::MIN), |a, v| (a.0.min(v), a.1.max(v)));
assert!(range.1 - range.0 < 0.1, "stripes should be blurred away: {range:?}");
let mean: f32 = out.data.iter().sum::<f32>() / out.data.len() as f32;
assert!((mean - 0.5).abs() < 0.02);
}
mod height_roundtrip {
//! Round-trip test for Height to Normal -> Normal to Height on a smooth analytic bump.
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::{Image, Kind};
use crate::{Ctx, find, resolve_params};
fn run(id: &str, input: &Image, size: u32, over: &[(&str, Value)]) -> Image {
let def = find(id).unwrap();
let over: BTreeMap<String, Value> = over.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
let params = resolve_params(def, &over);
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let inputs = [Some(input.clone())];
let ctx = Ctx { w: size, h: size, seed: 1, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
(def.cook)(&ctx).unwrap().remove(0)
}
fn pearson(a: &Image, b: &Image) -> f32 {
let n = (a.w * a.h) as usize;
let (ma, mb) = (a.data.iter().take(n).sum::<f32>() / n as f32, b.data.iter().take(n).sum::<f32>() / n as f32);
let (mut sab, mut saa, mut sbb) = (0.0f32, 0.0f32, 0.0f32);
for i in 0..n {
let (da, db) = (a.data[i] - ma, b.data[i] - mb);
sab += da * db;
saa += da * da;
sbb += db * db;
}
sab / (saa * sbb).sqrt().max(1e-9)
}
#[test]
fn normal_to_height_recovers_the_broad_shape_of_a_bump() {
for size in [256u32, 1024] {
// A wide wrap-around Gaussian bump: nearly all of its energy is at coarse scales.
let bump = Image::generate_uv(size, size, Kind::Gray, |u, v| {
let (dx, dy) = (u - 0.5, v - 0.5);
[(-(dx * dx + dy * dy) / (2.0 * 0.12 * 0.12)).exp(), 0.0, 0.0, 0.0]
});
let normal = run("height_to_normal", &bump, size, &[("intensity", Value::Float(2.0))]);
let back = run("normal_to_height", &normal, size, &[]);
let c = pearson(&bump, &back);
assert!(c > 0.99, "size {size}: correlation {c}");
}
}
}
-244
View File
@@ -1,244 +0,0 @@
//! More filters: random per-tile transforms, horizon-based ambient occlusion, a 5×5 Sobel normal
//! map, value band selection, palette quantization and block-averaged pixelation.
use std::f32::consts::TAU;
use materialcraft_image::{Image, Kind, luminance};
use rayon::prelude::*;
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::filters_more::pack;
use crate::noise::rand2;
use crate::noises_more::smoothstep;
const ADJ: &str = "Filters/Adjustments";
const EFFECTS: &str = "Filters/Effects";
const NORMAL: &str = "Filters/Normal map";
const TILING: &str = "Filters/Tiling";
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("tile_random", "Tile Random", TILING)
.desc("Cuts the image into a grid and shows a randomly offset, flipped and rotated window of the input in each tile (breaks up repetition).")
.any_in("input", "Input")
.int("x_amount", "X amount", 4, 1, 256)
.int("y_amount", "Y amount", 4, 1, 256)
.float("offset_random", "Offset random", 1.0, 0.0, 1.0)
.boolean("rotate", "Random 90° rotation", true)
.boolean("flip", "Random flip", true)
.float("luminance_random", "Luminance random", 0.0, 0.0, 1.0)
.cook(tile_random),
node("ambient_occlusion_fast", "Ambient Occlusion (Fast)", EFFECTS)
.desc("Horizon-based ambient occlusion of a height map: how much of the sky each pixel sees within the radius.")
.gray_in("height", "Height")
.float("radius", "Radius", 12.0, 1.0, 128.0)
.float("height_depth", "Height depth", 0.3, 0.0, 1.0)
.float("intensity", "Intensity", 1.0, 0.0, 2.0)
.gray_out()
.cook(ambient_occlusion_fast),
node("normal_from_height_hq", "Normal from Height HQ", NORMAL)
.desc("A smooth normal map from a height map with 5×5 Sobel slopes.")
.gray_in("input", "Height")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.choice("format", "Normal format", &["OpenGL", "DirectX"], 0)
.color_out()
.cook(normal_from_height_hq),
node("histogram_select", "Histogram Select", ADJ)
.desc("White where values lie in a band around the position, fading out with the contrast.")
.gray_in("input", "Input")
.float("position", "Position", 0.5, 0.0, 1.0)
.float("range", "Range", 0.25, 0.0, 1.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
.cook(histogram_select),
node("quantize_color", "Quantize Color", ADJ)
.desc("Reduces the image to a palette of its most representative colors (k-means), with optional ordered dithering.")
.color_in("input", "Input")
.int("colors", "Colors", 8, 2, 64)
.float("dither", "Dither", 0.0, 0.0, 1.0)
.color_out()
.cook(quantize_color),
node("pixelate_color", "Pixelate Color", EFFECTS)
.desc("Averages the image over blocks (separate X and Y counts).")
.any_in("input", "Input")
.int("x_cells", "X cells", 32, 1, 1024)
.int("y_cells", "Y cells", 32, 1, 1024)
.cook(pixelate_color),
]
}
fn tile_random(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Gray, [0.0; 4]);
let (nx, ny) = (ctx.i("x_amount").clamp(1, 256) as f32, ctx.i("y_amount").clamp(1, 256) as f32);
let (off, rot, flip, lr, s) = (ctx.f("offset_random"), ctx.b("rotate"), ctx.b("flip"), ctx.f("luminance_random"), ctx.seed);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, img.kind, |u, v| {
let (cx, cy) = ((u * nx).floor(), (v * ny).floor());
let (ci, cj) = ((cx as i32).rem_euclid(nx as i32), (cy as i32).rem_euclid(ny as i32));
let r = |k: u32| rand2(ci, cj, s ^ k.wrapping_mul(0x2545_f491));
// Offset from the tile center in uv, flipped and turned by quarter turns.
let (mut a, mut b) = ((u * nx - cx - 0.5) / nx, (v * ny - cy - 0.5) / ny);
if flip && r(1) < 0.5 {
a = -a;
}
if rot {
for _ in 0..(r(2) * 4.0) as i32 {
(a, b) = (-b, a);
}
}
let su = (cx + 0.5) / nx + a + (r(3) - 0.5) * off;
let sv = (cy + 0.5) / ny + b + (r(4) - 0.5) * off;
let p = img.sample(su, sv, true);
let k = 1.0 - lr * r(5);
[p[0] * k, p[1] * k, p[2] * k, p[3]]
})])
}
fn ambient_occlusion_fast(ctx: &Ctx) -> CookResult {
const DIRS: usize = 8;
const STEPS: usize = 6;
let h = ctx.gray_or(0, 0.0);
let scale = ctx.w as f32 / 256.0;
let rad = (ctx.f("radius") * scale).clamp(1.0, 1024.0);
let hs = ctx.f("height_depth") * 64.0 * scale;
let k = ctx.f("intensity");
// Integer offsets along each direction, denser near the pixel, and their true distances.
let taps: Vec<(i64, i64, f32)> = (0..DIRS)
.flat_map(|d| {
let (sn, cs) = ((d as f32 + 0.5) / DIRS as f32 * TAU).sin_cos();
(1..=STEPS).map(move |s| {
let dist = rad * (s as f32 / STEPS as f32).powf(1.5);
let (ox, oy) = ((cs * dist).round(), (sn * dist).round());
(ox as i64, oy as i64, (ox * ox + oy * oy).sqrt().max(1.0))
})
})
.collect();
let tile = ctx.tile;
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| {
let (x, y) = (x as i64, y as i64);
let h0 = h.get_gray(x, y, tile);
let occ: f32 = taps
.chunks(STEPS)
.map(|dir| {
// Tangent of the highest horizon in this direction, as the sine of its angle.
let m = dir.iter().fold(0.0f32, |m, &(ox, oy, d)| m.max((h.get_gray(x + ox, y + oy, tile) - h0) * hs / d));
m / (1.0 + m * m).sqrt()
})
.sum();
[(1.0 - k * occ / DIRS as f32).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
})])
}
fn normal_from_height_hq(ctx: &Ctx) -> CookResult {
const SMOOTH: [f32; 5] = [1.0, 4.0, 6.0, 4.0, 1.0];
const DERIV: [f32; 5] = [-1.0, -2.0, 0.0, 2.0, 1.0];
let h = ctx.gray_or(0, 0.0);
// The kernels sum to 128 × the slope of a linear ramp.
let k = ctx.f("intensity") * ctx.w as f32 / 32.0 / 128.0;
let dx_fmt = ctx.i("format") == 1;
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let (mut gx, mut gy) = (0.0, 0.0);
for j in 0..5 {
for i in 0..5 {
let v = h.get_gray(x as i64 + i as i64 - 2, y as i64 + j as i64 - 2, ctx.tile);
gx += SMOOTH[j] * DERIV[i] * v;
gy += DERIV[j] * SMOOTH[i] * v;
}
}
let ny = gy * k;
pack([-gx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0)
})])
}
fn histogram_select(ctx: &Ctx) -> CookResult {
let (pos, half) = (ctx.f("position"), ctx.f("range") * 0.5);
let soft = (1.0 - ctx.f("contrast").clamp(0.0, 1.0)) * 0.25 + 1e-3;
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |p| [1.0 - smoothstep(half, half + soft, (p[0] - pos).abs()), 0.0, 0.0, 0.0])])
}
/// Index of the color in `pal` nearest to `c`.
fn nearest(pal: &[[f32; 3]], c: [f32; 3]) -> usize {
let d = |p: &[f32; 3]| (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2);
pal.iter().enumerate().min_by(|a, b| d(a.1).total_cmp(&d(b.1))).map_or(0, |(i, _)| i)
}
fn quantize_color(ctx: &Ctx) -> CookResult {
const BAYER: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0];
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
let k = ctx.i("colors").clamp(2, 64) as usize;
let rgb = |p: &[f32]| [p[0], p[1], p[2]];
// Lloyd's k-means on up to ~4096 samples, seeded at luminance quantiles.
let step = (img.data.len() / 4 / 4096).max(1);
let mut samples: Vec<[f32; 3]> = img.data.chunks_exact(4).step_by(step).map(rgb).collect();
samples.sort_by(|a, b| luminance([a[0], a[1], a[2], 1.0]).total_cmp(&luminance([b[0], b[1], b[2], 1.0])));
let mut pal: Vec<[f32; 3]> = (0..k).filter_map(|j| samples.get(((j as f32 + 0.5) / k as f32 * samples.len() as f32) as usize).copied()).collect();
for _ in 0..8 {
let mut acc = vec![[0.0f32; 4]; pal.len()];
for s in &samples {
if let Some(a) = acc.get_mut(nearest(&pal, *s)) {
*a = [a[0] + s[0], a[1] + s[1], a[2] + s[2], a[3] + 1.0];
}
}
for (p, a) in pal.iter_mut().zip(&acc) {
if a[3] > 0.0 {
*p = [a[0] / a[3], a[1] / a[3], a[2] / a[3]];
}
}
}
let spread = ctx.f("dither") / (k as f32).cbrt();
Ok(vec![Image::generate(img.w, img.h, Kind::Color, |x, y| {
let p = img.get(x as i64, y as i64, false);
let d = ((BAYER[(y as usize % 4) * 4 + x as usize % 4] + 0.5) / 16.0 - 0.5) * spread;
let c = pal.get(nearest(&pal, [p[0] + d, p[1] + d, p[2] + d])).copied().unwrap_or([p[0], p[1], p[2]]);
[c[0], c[1], c[2], p[3]]
})])
}
fn pixelate_color(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]);
let (w, h) = (img.w as usize, img.h as usize);
let (nx, ny) = (ctx.i("x_cells").clamp(1, 1024) as usize, ctx.i("y_cells").clamp(1, 1024) as usize);
// Block `b` of `n` over `len` pixels covers `b·len/n .. (b+1)·len/n` (at least one pixel).
let range = |n: usize, len: usize, b: usize| (b * len / n, ((b + 1) * len / n).max(b * len / n + 1).min(len));
let block = |n: usize, len: usize, p: usize| (((p + 1) * n).saturating_sub(1) / len).min(n - 1);
let means: Vec<[f32; 4]> = (0..nx * ny)
.into_par_iter()
.map(|bi| {
let ((x0, x1), (y0, y1)) = (range(nx, w, bi % nx), range(ny, h, bi / nx));
let mut s = [0.0f32; 4];
for y in y0..y1 {
for x in x0..x1 {
let p = img.get(x as i64, y as i64, false);
s = std::array::from_fn(|c| s[c] + p[c]);
}
}
let n = ((x1 - x0) * (y1 - y0)).max(1) as f32;
s.map(|v| v / n)
})
.collect();
Ok(vec![Image::generate(img.w, img.h, img.kind, |x, y| {
means.get(block(ny, h, y as usize) * nx + block(nx, w, x as usize)).copied().unwrap_or([0.0, 0.0, 0.0, 1.0])
})])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nearest_and_block_math() {
assert_eq!(nearest(&[[0.0; 3], [1.0; 3]], [0.7; 3]), 1);
// Pixelate: a 2-cell split of a black/white image averages each half exactly.
let img = Image::gray(8, 2, |x, _| if x < 4 { 0.0 } else { 1.0 });
let def = crate::catalog::find("pixelate_color").unwrap();
let mut p = crate::catalog::resolve_params(def, &Default::default());
p.insert("x_cells".into(), materialcraft_core::Value::Int(2));
p.insert("y_cells".into(), materialcraft_core::Value::Int(1));
let no_res = |_: &str| None;
let vars = Default::default();
let inputs = [Some(img)];
let ctx = Ctx { w: 8, h: 2, seed: 0, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars };
let out = &pixelate_color(&ctx).unwrap()[0];
assert_eq!((out.get(3, 1, false)[0], out.get(4, 0, false)[0]), (0.0, 1.0));
}
}
-490
View File
@@ -1,490 +0,0 @@
//! More filters: tone remaps and per-channel adjustments, two-input math, median and unsharp
//! mask, Sobel edges, glows and shadows from masks, curvature from height, and normal map tools.
use std::f32::consts::TAU;
use materialcraft_image::{Image, Kind};
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::flood_fill::region_rand;
use crate::noise::fbm;
use crate::noises_more::smoothstep;
use crate::ops;
const ADJ: &str = "Filters/Adjustments";
const BLENDING: &str = "Filters/Blending";
const BLURS: &str = "Filters/Blurs";
const EFFECTS: &str = "Filters/Effects";
const NORMAL: &str = "Filters/Normal map";
/// A tangent-space normal from a normal map pixel (0..1 → -1..1).
#[inline]
pub(crate) fn unpack(p: [f32; 4]) -> [f32; 3] {
[p[0] * 2.0 - 1.0, p[1] * 2.0 - 1.0, p[2] * 2.0 - 1.0]
}
/// A normalized normal back to a normal map pixel.
#[inline]
pub(crate) fn pack(n: [f32; 3], a: f32) -> [f32; 4] {
let l = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6);
[n[0] / l * 0.5 + 0.5, n[1] / l * 0.5 + 0.5, n[2] / l * 0.5 + 0.5, a]
}
/// The pixel offset of `dist` (pixels at 256) along `angle` (turns, y down).
fn offset(ctx: &Ctx, angle: f32, dist: f32) -> (i64, i64) {
let (s, c) = (angle * TAU).sin_cos();
let d = dist * ctx.w as f32 / 256.0;
((c * d).round() as i64, (-s * d).round() as i64)
}
fn px(ctx: &Ctx, v: f32) -> f32 {
v * ctx.w as f32 / 256.0
}
pub(crate) fn defs() -> Vec<NodeDef> {
let two = |id, label, desc| node(id, label, BLENDING).desc(desc).any_in("input_a", "A").any_in("input_b", "B");
let mask_in = |id, label, cat| node(id, label, cat).gray_in("input", "Mask");
vec![
// ---- Adjustments
node("remap", "Remap", ADJ)
.desc("Maps the input range linearly onto the output range.")
.any_in("input", "Input")
.float("in_min", "Input min", 0.0, 0.0, 1.0)
.float("in_max", "Input max", 1.0, 0.0, 1.0)
.float("out_min", "Output min", 0.0, 0.0, 1.0)
.float("out_max", "Output max", 1.0, 0.0, 1.0)
.boolean("clamp", "Clamp", true)
.cook(remap),
node("smoothstep", "Smoothstep", ADJ)
.desc("A smooth S-shaped step from the low edge (black) to the high edge (white).")
.any_in("input", "Input")
.float("low", "Low edge", 0.25, 0.0, 1.0)
.float("high", "High edge", 0.75, 0.0, 1.0)
.cook(smoothstep_node),
node("s_curve", "S-Curve Contrast", ADJ)
.desc("Raises contrast around a pivot with a smooth S curve (keeps black and white).")
.any_in("input", "Input")
.float("amount", "Amount", 0.5, 0.0, 1.0)
.float("pivot", "Pivot", 0.5, 0.01, 0.99)
.cook(s_curve),
node("channel_levels", "Channel Levels", ADJ)
.desc("Levels with a separate input range per channel.")
.any_in("input", "Input")
.color("low", "Input low", [0.0, 0.0, 0.0, 0.0])
.color("high", "Input high", [1.0, 1.0, 1.0, 1.0])
.float("gamma", "Gamma", 1.0, 0.1, 4.0)
.cook(channel_levels),
node("auto_levels_channels", "Auto Levels per Channel", ADJ)
.desc("Stretches each color channel separately to the full 0..1 range.")
.any_in("input", "Input")
.cook(auto_levels_channels),
node("invert_channels", "Invert Channels", ADJ)
.desc("Inverts the chosen channels.")
.any_in("input", "Input")
.boolean("red", "Red", true)
.boolean("green", "Green", true)
.boolean("blue", "Blue", true)
.boolean("alpha", "Alpha", false)
.cook(invert_channels),
node("clamp_channels", "Clamp Channels", ADJ)
.desc("Clamps each channel between its own minimum and maximum.")
.any_in("input", "Input")
.color("min", "Min", [0.0, 0.0, 0.0, 0.0])
.color("max", "Max", [1.0, 1.0, 1.0, 1.0])
.cook(clamp_channels),
node("color_variation", "Color Variation", ADJ)
.desc("Random hue, saturation and value shifts: per region when a flood fill index map is connected, else from soft noise.")
.color_in("input", "Input")
.color_in("index", "Index map (optional)")
.float("hue", "Hue random", 0.03, 0.0, 0.5)
.float("saturation", "Saturation random", 0.15, 0.0, 1.0)
.float("value", "Value random", 0.2, 0.0, 1.0)
.float("scale", "Noise scale", 4.0, 1.0, 64.0)
.color_out()
.cook(color_variation),
// ---- Blending
node("lerp", "Lerp", BLENDING)
.desc("Linear interpolation from A to B by a mask (or a constant position without one).")
.any_in("input_a", "A")
.any_in("input_b", "B")
.gray_in("mask", "Mask")
.float("position", "Position (no mask)", 0.5, 0.0, 1.0)
.cook(lerp),
two("minimum", "Minimum", "The darker of A and B, per channel.").cook(minimum),
two("maximum", "Maximum", "The brighter of A and B, per channel.").cook(maximum),
two("multiply", "Multiply", "A times B.").cook(multiply),
two("difference", "Difference", "The absolute difference of A and B.").cook(difference),
two("add", "Add", "A plus B.").boolean("clamp", "Clamp", true).cook(add),
two("subtract", "Subtract", "A minus B.").boolean("clamp", "Clamp", true).cook(subtract),
// ---- Blurs
node("median", "Median", BLURS)
.desc("Median of each neighbourhood: removes specks while keeping edges.")
.any_in("input", "Input")
.choice("size", "Size", &["3 × 3", "5 × 5"], 0)
.cook(median),
node("unsharp_mask", "Unsharp Mask", BLURS)
.desc("Sharpens by adding back the difference from a blurred copy.")
.any_in("input", "Input")
.float("radius", "Radius", 2.0, 0.0, 32.0)
.float("amount", "Amount", 1.0, 0.0, 5.0)
.float("threshold", "Threshold", 0.0, 0.0, 1.0)
.cook(unsharp_mask),
// ---- Effects
node("sobel", "Sobel Edges", EFFECTS)
.desc("Edge strength from the Sobel operator.")
.gray_in("input", "Input")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.gray_out()
.cook(sobel),
mask_in("outer_glow", "Outer Glow", EFFECTS)
.desc("A glow fading outward from a mask (by exact distance).")
.float("size", "Size", 16.0, 0.0, 256.0)
.float("intensity", "Intensity", 1.0, 0.0, 1.0)
.float("falloff", "Falloff", 2.0, 0.25, 8.0)
.gray_out()
.cook(outer_glow),
mask_in("inner_shadow", "Inner Shadow", EFFECTS)
.desc("Darkens the inside of a mask along the edges facing the light.")
.angle("angle", "Light angle", -0.125)
.float("distance", "Distance", 6.0, 0.0, 64.0)
.float("size", "Size", 8.0, 0.0, 128.0)
.float("opacity", "Opacity", 0.75, 0.0, 1.0)
.gray_out()
.cook(inner_shadow),
mask_in("drop_shadow", "Drop Shadow", EFFECTS)
.desc("An offset, blurred shadow under a mask.")
.angle("angle", "Angle", -0.125)
.float("distance", "Distance", 8.0, 0.0, 128.0)
.float("size", "Blur", 4.0, 0.0, 64.0)
.float("opacity", "Opacity", 0.75, 0.0, 1.0)
.output("output", "Output", PortKind::Gray)
.output("shadow", "Shadow", PortKind::Gray)
.cook(drop_shadow),
node("height_curvature", "Curvature from Height", EFFECTS)
.desc("Convex areas above 0.5, concave below, from a height map.")
.gray_in("input", "Height")
.float("radius", "Radius", 2.0, 0.25, 32.0)
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.gray_out()
.cook(height_curvature),
mask_in("outline", "Outline", EFFECTS)
.desc("A line of constant width around the edges of a mask.")
.float("width", "Width", 4.0, 0.0, 64.0)
.choice("position", "Position", &["Outside", "Center", "Inside"], 1)
.gray_out()
.cook(outline),
// ---- Normal map
node("normal_combine", "Normal Combine", NORMAL)
.desc("Combines a detail normal map over a base one (whiteout blending).")
.color_in("base", "Base normal")
.color_in("detail", "Detail normal")
.float("intensity", "Detail intensity", 1.0, 0.0, 4.0)
.color_out()
.cook(normal_combine),
node("normal_rotate", "Normal Rotate", NORMAL)
.desc("Rotates the directions of a normal map (for rotated textures).")
.color_in("input", "Normal")
.angle("angle", "Angle", 0.0)
.color_out()
.cook(normal_rotate),
node("normal_sobel", "Normal Sobel", NORMAL)
.desc("A normal map from a height map with Sobel slopes (smoother than plain differences).")
.gray_in("input", "Height")
.float("intensity", "Intensity", 1.0, 0.0, 10.0)
.choice("format", "Format", &["OpenGL", "DirectX"], 0)
.color_out()
.cook(normal_sobel),
]
}
fn src(ctx: &Ctx) -> Image {
ctx.any_or(0, Kind::Gray, [0.0, 0.0, 0.0, 1.0])
}
/// Map R, G and B (gray: the value) with `f(value, channel)`; alpha kept.
fn per_channel(ctx: &Ctx, f: impl Fn(f32, usize) -> f32 + Sync) -> CookResult {
let img = src(ctx);
Ok(vec![img.map(img.kind, |p| [f(p[0], 0), f(p[1], 1), f(p[2], 2), p[3]])])
}
fn remap(ctx: &Ctx) -> CookResult {
let (a, b, c, d, cl) = (ctx.f("in_min"), ctx.f("in_max"), ctx.f("out_min"), ctx.f("out_max"), ctx.b("clamp"));
let span = if (b - a).abs() < 1e-6 { 1e-6 } else { b - a };
per_channel(ctx, |v, _| {
let t = (v - a) / span;
c + (d - c) * if cl { t.clamp(0.0, 1.0) } else { t }
})
}
fn smoothstep_node(ctx: &Ctx) -> CookResult {
let (lo, hi) = (ctx.f("low"), ctx.f("high"));
per_channel(ctx, |v, _| smoothstep(lo, hi.max(lo + 1e-4), v))
}
fn s_curve(ctx: &Ctx) -> CookResult {
// A negative k on a zero base gives inf; clamp it (k = 0 gives the finite 1).
let (k, p) = ((1.0 + ctx.f("amount") * 4.0).max(0.0), ctx.f("pivot").clamp(0.01, 0.99));
per_channel(ctx, |v, _| {
let v = v.clamp(0.0, 1.0);
if v < p { p * (v / p).powf(k) } else { 1.0 - (1.0 - p) * ((1.0 - v) / (1.0 - p)).powf(k) }
})
}
fn channel_levels(ctx: &Ctx) -> CookResult {
let (lo, hi, g) = (ctx.v4("low"), ctx.v4("high"), 1.0 / ctx.f("gamma").max(0.01));
per_channel(ctx, |v, c| {
let span = (hi[c] - lo[c]).abs().max(1e-6).copysign(hi[c] - lo[c]);
((v - lo[c]) / span).clamp(0.0, 1.0).powf(g)
})
}
fn auto_levels_channels(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let c = img.channels();
let mut lo = [f32::INFINITY; 3];
let mut hi = [f32::NEG_INFINITY; 3];
for p in img.data.chunks(c) {
for k in 0..c.min(3) {
lo[k] = lo[k].min(p[k]);
hi[k] = hi[k].max(p[k]);
}
}
per_channel(ctx, |v, k| {
let k = if c == 1 { 0 } else { k };
let span = hi[k] - lo[k];
if span.is_finite() && span > 1e-6 { (v - lo[k]) / span } else { v }
})
}
fn invert_channels(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let flags = [ctx.b("red"), ctx.b("green"), ctx.b("blue"), ctx.b("alpha")];
Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| if flags[k] { 1.0 - p[k] } else { p[k] }))])
}
fn clamp_channels(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let (lo, hi) = (ctx.v4("min"), ctx.v4("max"));
Ok(vec![img.map(img.kind, |p| std::array::from_fn(|k| p[k].max(lo[k]).min(hi[k].max(lo[k]))))])
}
fn color_variation(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
let index = ctx.input(1);
let (hr, sr, vr, sc, s, tile) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value"), ctx.f("scale").max(1.0).round(), ctx.seed, ctx.tile);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| {
let p = img.sample_nearest(u, v, false);
// Three random shifts in -1..1: per flood fill region, or from noise.
let r: [f32; 3] = match index.map(|i| i.sample_nearest(u, v, tile)) {
Some(q) if q[3] > 0.5 => std::array::from_fn(|k| region_rand(q[2], 10 + k as u32, s) * 2.0 - 1.0),
Some(_) => [0.0; 3],
None => std::array::from_fn(|k| (fbm(u, v, sc, 3, 0.5, s.wrapping_add(k as u32 * 101)) - 0.5) * 4.0),
};
let hsl = ops::rgb_to_hsl(p);
let c = ops::hsl_to_rgb(hsl[0] + hr * r[0], (hsl[1] * (1.0 + sr * r[1])).clamp(0.0, 1.0), (hsl[2] * (1.0 + vr * r[2])).max(0.0));
[c[0], c[1], c[2], p[3]]
})])
}
fn lerp(ctx: &Ctx) -> CookResult {
let kind = ctx.main_kind(Kind::Gray);
let (a, b) = (ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind), ctx.any_or(1, kind, [1.0; 4]).to_kind(kind));
let m = ctx.gray_or(2, ctx.f("position"));
Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| {
let (x, y) = (x as i64, y as i64);
let (p, q, t) = (a.get(x, y, false), b.get(x, y, false), m.get_gray(x, y, false));
std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t)
})])
}
/// Per-channel `f(a, b)` of two inputs (in the kind of the first connected one); B defaults to
/// `b_default`; alpha from A.
fn binary(ctx: &Ctx, b_default: f32, f: impl Fn(f32, f32) -> f32 + Sync) -> CookResult {
let kind = ctx.main_kind(Kind::Gray);
let a = ctx.any_or(0, kind, [0.0, 0.0, 0.0, 1.0]).to_kind(kind);
let b = ctx.any_or(1, kind, [b_default, b_default, b_default, 1.0]).to_kind(kind);
Ok(vec![Image::generate(ctx.w, ctx.h, kind, |x, y| {
let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
[f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]]
})])
}
fn minimum(ctx: &Ctx) -> CookResult {
binary(ctx, 1.0, f32::min)
}
fn maximum(ctx: &Ctx) -> CookResult {
binary(ctx, 0.0, f32::max)
}
fn multiply(ctx: &Ctx) -> CookResult {
binary(ctx, 1.0, |a, b| a * b)
}
fn difference(ctx: &Ctx) -> CookResult {
binary(ctx, 0.0, |a, b| (a - b).abs())
}
fn add(ctx: &Ctx) -> CookResult {
let cl = ctx.b("clamp");
binary(ctx, 0.0, |a, b| if cl { (a + b).clamp(0.0, 1.0) } else { a + b })
}
fn subtract(ctx: &Ctx) -> CookResult {
let cl = ctx.b("clamp");
binary(ctx, 0.0, |a, b| if cl { (a - b).clamp(0.0, 1.0) } else { a - b })
}
fn median(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let r: i64 = if ctx.i("size") == 1 { 2 } else { 1 };
let c = img.channels();
let tile = ctx.tile;
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let mut buf = [[0.0f32; 25]; 4];
let mut n = 0;
for dy in -r..=r {
for dx in -r..=r {
let p = img.get(x as i64 + dx, y as i64 + dy, tile);
for (k, b) in buf.iter_mut().enumerate() {
b[n] = p[k];
}
n += 1;
}
}
let mut out = [0.0; 4];
for (k, b) in buf.iter_mut().enumerate().take(c) {
let s = &mut b[..n];
let (_, m, _) = s.select_nth_unstable_by(n / 2, f32::total_cmp);
out[k] = *m;
}
out
})])
}
fn unsharp_mask(ctx: &Ctx) -> CookResult {
let img = src(ctx);
let blurred = ops::gaussian(&img, px(ctx, ctx.f("radius")), ctx.tile);
let (amt, th) = (ctx.f("amount"), ctx.f("threshold"));
Ok(vec![Image::generate(ctx.w, ctx.h, img.kind, |x, y| {
let (p, q) = (img.get(x as i64, y as i64, false), blurred.get(x as i64, y as i64, false));
let f = |a: f32, b: f32| if (a - b).abs() > th { a + (a - b) * amt } else { a };
[f(p[0], q[0]), f(p[1], q[1]), f(p[2], q[2]), p[3]]
})])
}
/// Sobel slopes (dx, dy) of a gray image, in value units per pixel.
fn sobel_slope(img: &Image, x: i64, y: i64, tile: bool) -> (f32, f32) {
let g = |dx: i64, dy: i64| img.get_gray(x + dx, y + dy, tile);
let gx = g(1, -1) + 2.0 * g(1, 0) + g(1, 1) - g(-1, -1) - 2.0 * g(-1, 0) - g(-1, 1);
let gy = g(-1, 1) + 2.0 * g(0, 1) + g(1, 1) - g(-1, -1) - 2.0 * g(0, -1) - g(1, -1);
(gx / 8.0, gy / 8.0)
}
fn sobel(ctx: &Ctx) -> CookResult {
let img = ctx.gray_or(0, 0.0);
let k = ctx.f("intensity") * 2.0;
Ok(vec![Image::gray(ctx.w, ctx.h, |x, y| {
let (dx, dy) = sobel_slope(&img, x as i64, y as i64, ctx.tile);
((dx * dx + dy * dy).sqrt() * k).min(1.0)
})])
}
/// The mask input (inside where above 0.5).
fn mask(ctx: &Ctx) -> Image {
ctx.gray_or(0, 0.0)
}
fn outer_glow(ctx: &Ctx) -> CookResult {
let m = mask(ctx);
let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.data.get(i).is_some_and(|v| *v > 0.5), ctx.tile);
let (size, amt, fall) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("intensity"), ctx.f("falloff").max(0.01));
let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv.max((1.0 - d.sqrt() / size).max(0.0).powf(fall) * amt)).collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
}
fn inner_shadow(ctx: &Ctx) -> CookResult {
let m = mask(ctx);
let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance"));
let (w, tile) = (ctx.w as usize, ctx.tile);
// Distance to the nearest pixel outside the mask shifted toward the shadow.
let d2 = ops::distance_sq(ctx.w, ctx.h, |i| m.get_gray((i % w) as i64 - ox, (i / w) as i64 - oy, tile) <= 0.5, tile);
let (size, op) = (px(ctx, ctx.f("size")).max(1e-3), ctx.f("opacity"));
let v = d2.iter().zip(m.data.iter()).map(|(d, mv)| mv * (1.0 - op * (1.0 - d.sqrt() / size).clamp(0.0, 1.0))).collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
}
fn drop_shadow(ctx: &Ctx) -> CookResult {
let m = mask(ctx);
let (ox, oy) = offset(ctx, ctx.f("angle"), ctx.f("distance"));
let shifted = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64 - ox, y as i64 - oy, ctx.tile));
let op = ctx.f("opacity");
let shadow = ops::gaussian(&shifted, px(ctx, ctx.f("size")), ctx.tile).map(Kind::Gray, |p| [p[0] * op, 0.0, 0.0, 0.0]);
let out = Image::gray(ctx.w, ctx.h, |x, y| m.get_gray(x as i64, y as i64, false).max(shadow.get_gray(x as i64, y as i64, false)));
Ok(vec![out, shadow])
}
fn height_curvature(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
let r = px(ctx, ctx.f("radius"));
// Difference of Gaussians: a band-limited Laplacian that ignores pixel noise.
let (fine, wide) = (ops::gaussian(&h, r * 0.5, ctx.tile), ops::gaussian(&h, r * 2.0, ctx.tile));
let k = ctx.f("intensity") * 8.0;
let v = fine.data.iter().zip(wide.data.iter()).map(|(a, b)| (0.5 + (a - b) * k).clamp(0.0, 1.0)).collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
}
fn outline(ctx: &Ctx) -> CookResult {
let m = mask(ctx);
let inside = |i: usize| m.data.get(i).is_some_and(|v| *v > 0.5);
let to_in = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile);
let to_out = ops::distance_sq(ctx.w, ctx.h, |i| !inside(i), ctx.tile);
let w = px(ctx, ctx.f("width"));
let (lo, hi) = match ctx.i("position") {
0 => (0.0, w),
2 => (-w, 0.0),
_ => (-w * 0.5, w * 0.5),
};
// Signed distance to the edge (positive outside), half a pixel off each side of it.
let v = (0..to_in.len())
.map(|i| {
let sd = if inside(i) { 0.5 - to_out[i].sqrt() } else { to_in[i].sqrt() - 0.5 };
(sd - lo + 0.5).clamp(0.0, 1.0) * (hi - sd + 0.5).clamp(0.0, 1.0)
})
.collect();
Ok(vec![ops::gray_from(ctx.w, ctx.h, v)])
}
fn flat(ctx: &Ctx, i: usize) -> Image {
ctx.any_or(i, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color()
}
fn normal_combine(ctx: &Ctx) -> CookResult {
let (base, det) = (flat(ctx, 0), flat(ctx, 1));
let k = ctx.f("intensity");
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let (b, d) = (unpack(base.get(x as i64, y as i64, false)), unpack(det.get(x as i64, y as i64, false)));
// Whiteout blending: add the slopes, multiply the heights.
pack([b[0] + d[0] * k, b[1] + d[1] * k, b[2] * (1.0 + (d[2] - 1.0) * k.min(1.0)).max(1e-3)], 1.0)
})])
}
fn normal_rotate(ctx: &Ctx) -> CookResult {
let n = flat(ctx, 0);
let (s, c) = (ctx.f("angle") * TAU).sin_cos();
Ok(vec![n.map(Kind::Color, |p| {
let v = unpack(p);
pack([v[0] * c - v[1] * s, v[0] * s + v[1] * c, v[2]], p[3])
})])
}
fn normal_sobel(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
let k = ctx.f("intensity") * ctx.w as f32 / 32.0;
let dx_fmt = ctx.i("format") == 1;
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let (dx, dy) = sobel_slope(&h, x as i64, y as i64, ctx.tile);
let ny = dy * k;
pack([-dx * k, if dx_fmt { -ny } else { ny }, 1.0], 1.0)
})])
}
-306
View File
@@ -1,306 +0,0 @@
//! Filters › Flood fill: labels the connected white regions of a tile mask and turns each region
//! into per-region data (random values, colors, gradients, sizes, positions).
//!
//! The index map that [`flood_fill`] writes holds, per region pixel: R, G = the region's
//! bounding-box center (UV), B = a random id, A = 1. Gaps are all zero. Downstream nodes re-label
//! the index map (pixels of one region share the same RGB), so they recover the exact bounding
//! box, and a pixel's place inside it, at any size. Labeling wraps across the image edges when
//! the graph tiles, so a tile crossing an edge is one region.
use std::f32::consts::TAU;
use materialcraft_image::{Image, Kind};
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::noise::{hash3, rand1};
const FLOOD: &str = "Filters/Flood fill";
const NONE: u32 = u32::MAX;
/// Connected regions of an image.
pub struct Regions {
/// Region index per pixel (`u32::MAX` = background).
pub label: Vec<u32>,
/// Unwrapped pixel coordinates (a region crossing an edge continues past it).
pub pos: Vec<[i32; 2]>,
/// Per region: min x, min y, max x, max y (unwrapped, inclusive).
pub bbox: Vec<[i32; 4]>,
}
/// Label the 4-connected regions of pixels where `inside` holds and neighbours are `same`.
pub fn label(w: u32, h: u32, tile: bool, inside: impl Fn(usize) -> bool, same: impl Fn(usize, usize) -> bool) -> Regions {
let (wi, hi) = (w as i32, h as i32);
let n = w as usize * h as usize;
let mut label = vec![NONE; n];
let mut pos = vec![[0i32; 2]; n];
let mut bbox = Vec::new();
let mut queue: Vec<usize> = Vec::new();
for start in 0..n {
if label[start] != NONE || !inside(start) {
continue;
}
let id = bbox.len() as u32;
let s = [(start % w as usize) as i32, (start / w as usize) as i32];
label[start] = id;
pos[start] = s;
let mut b = [s[0], s[1], s[0], s[1]];
queue.clear();
queue.push(start);
let mut head = 0;
while let Some(&i) = queue.get(head) {
head += 1;
let p = pos[i];
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
let q = [p[0] + dx, p[1] + dy];
let (x, y) = if tile {
(q[0].rem_euclid(wi), q[1].rem_euclid(hi))
} else if (0..wi).contains(&q[0]) && (0..hi).contains(&q[1]) {
(q[0], q[1])
} else {
continue;
};
let j = (y * wi + x) as usize;
if label[j] != NONE || !inside(j) || !same(i, j) {
continue;
}
label[j] = id;
pos[j] = q;
b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])];
queue.push(j);
}
}
bbox.push(b);
}
Regions { label, pos, bbox }
}
/// What a downstream node knows about the region under a pixel.
pub struct RegionPx {
/// The region's random id (0..1).
pub id: f32,
/// Bounding-box center (UV, wrapped into 0..1).
pub center: [f32; 2],
/// Bounding-box size (UV).
pub size: [f32; 2],
/// The pixel's place inside the bounding box (0..1).
pub local: [f32; 2],
}
/// Bounding-box center and size (UV) of a region.
fn bbox_uv(b: [i32; 4], w: u32, h: u32) -> ([f32; 2], [f32; 2]) {
let (wf, hf) = (w as f32, h as f32);
let (ex, ey) = ((b[2] - b[0] + 1) as f32, (b[3] - b[1] + 1) as f32);
let center = [((b[0] + b[2] + 1) as f32 * 0.5 / wf).rem_euclid(1.0), ((b[1] + b[3] + 1) as f32 * 0.5 / hf).rem_euclid(1.0)];
(center, [(ex / wf).min(1.0), (ey / hf).min(1.0)])
}
/// A uniform random value per region (and per `k`), from the region's id and the node's seed.
pub fn region_rand(id: f32, k: u32, seed: u32) -> f32 {
rand1(id.to_bits() ^ k.wrapping_mul(0x9e37_79b9), seed)
}
/// The index map input at the output size (nearest sampling keeps region values exact).
fn index_input(ctx: &Ctx, i: usize) -> Image {
match ctx.input(i) {
Some(img) => Image::generate_uv(ctx.w, ctx.h, Kind::Color, |u, v| img.sample_nearest(u, v, false)),
None => Image::filled(ctx.w, ctx.h, Kind::Color, [0.0; 4]),
}
}
/// Run `f` for every region pixel of index map input `i`; background pixels get `bg`.
pub fn per_region(ctx: &Ctx, i: usize, kind: Kind, bg: [f32; 4], f: impl Fn(&RegionPx, f32, f32) -> [f32; 4] + Sync) -> Image {
let idx = index_input(ctx, i).to_color();
let d = idx.data.as_slice();
let px = |i: usize| d.get(i * 4..i * 4 + 4).unwrap_or(&[0.0; 4]);
let regions = label(ctx.w, ctx.h, ctx.tile, |i| px(i)[3] > 0.5, |a, b| px(a)[..3] == px(b)[..3]);
let (w, h) = (ctx.w, ctx.h);
Image::generate(w, h, kind, |x, y| {
let i = (y * w + x) as usize;
let Some(b) = regions.label.get(i).and_then(|l| regions.bbox.get(*l as usize)) else {
return bg;
};
let (center, size) = bbox_uv(*b, w, h);
let p = regions.pos[i];
let local = [(p[0] - b[0]) as f32 + 0.5, (p[1] - b[1]) as f32 + 0.5];
let local = [local[0] / (b[2] - b[0] + 1) as f32, local[1] / (b[3] - b[1] + 1) as f32];
let r = RegionPx { id: px(i)[2], center, size, local };
f(&r, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32)
})
}
pub(crate) fn defs() -> Vec<NodeDef> {
let index_in = |id, label| node(id, label, FLOOD).color_in("input", "Index map");
vec![
node("flood_fill", "Flood Fill", FLOOD)
.desc("Finds every connected white region of a tile mask (regions crossing the edges are one) and writes an index map: R, G = region center, B = random id, A = 1.")
.gray_in("input", "Mask")
.float("threshold", "Threshold", 0.5, 0.0, 1.0)
.output("output", "Index map", PortKind::Color)
.cook(flood_fill),
index_in("flood_fill_to_random_grayscale", "Flood Fill to Random Grayscale")
.desc("A random gray per region.")
.float("min", "Min", 0.0, 0.0, 1.0)
.float("max", "Max", 1.0, 0.0, 1.0)
.gray_out()
.cook(to_random_gray),
index_in("flood_fill_to_random_color", "Flood Fill to Random Color")
.desc("A random color per region.")
.float("saturation", "Saturation", 0.7, 0.0, 1.0)
.float("lightness", "Lightness", 0.5, 0.0, 1.0)
.float("lightness_random", "Lightness random", 0.3, 0.0, 1.0)
.color_out()
.cook(to_random_color),
index_in("flood_fill_to_gradient", "Flood Fill to Gradient")
.desc("A linear gradient across each region's bounding box.")
.angle("angle", "Angle", 0.0)
.float("angle_random", "Angle random", 0.0, 0.0, 1.0)
.float("slope_random", "Slope random", 0.0, 0.0, 1.0)
.gray_out()
.cook(to_gradient),
index_in("flood_fill_to_bbox_size", "Flood Fill to BBox Size")
.desc("Each region's bounding-box size.")
.choice("mode", "Size", &["Width", "Height", "Max", "Min", "Area"], 2)
.gray_out()
.cook(to_bbox_size),
index_in("flood_fill_to_position", "Flood Fill to Position")
.desc("Each region's center position (R = X, G = Y).")
.color_out()
.cook(to_position),
index_in("flood_fill_to_grayscale", "Flood Fill to Grayscale")
.desc("Each region takes the value of the input at its center.")
.gray_in("source", "Source")
.gray_out()
.cook(to_grayscale),
index_in("flood_fill_to_color", "Flood Fill to Color")
.desc("Each region takes the color of the input at its center.")
.color_in("source", "Source")
.color_out()
.cook(to_color),
]
}
fn flood_fill(ctx: &Ctx) -> CookResult {
let t = ctx.f("threshold");
let m = ctx.gray_or(0, 0.0);
let d = m.data.as_slice();
let regions = label(ctx.w, ctx.h, ctx.tile, |i| d.get(i).is_some_and(|v| *v > t), |_, _| true);
let (w, h, s) = (ctx.w, ctx.h, ctx.seed);
let info: Vec<[f32; 4]> = regions
.bbox
.iter()
.map(|b| {
let (c, size) = bbox_uv(*b, w, h);
// Stable per region: from its center and size, not its scan order.
let k = hash3((c[0] * 65536.0) as i32, (c[1] * 65536.0) as i32, s ^ (((size[0] * 4096.0) as u32) << 12) ^ ((size[1] * 4096.0) as u32));
[c[0], c[1], ((k >> 8) as f32 / (1u32 << 24) as f32).max(1e-4), 1.0]
})
.collect();
Ok(vec![Image::generate(w, h, Kind::Color, |x, y| {
regions.label.get((y * w + x) as usize).and_then(|l| info.get(*l as usize)).copied().unwrap_or([0.0; 4])
})])
}
fn to_random_gray(ctx: &Ctx) -> CookResult {
let (lo, hi, s) = (ctx.f("min"), ctx.f("max"), ctx.seed);
Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| [lo + (hi - lo) * region_rand(r.id, 0, s), 0.0, 0.0, 0.0])])
}
fn to_random_color(ctx: &Ctx) -> CookResult {
let (sat, l, lr, s) = (ctx.f("saturation"), ctx.f("lightness"), ctx.f("lightness_random"), ctx.seed);
Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| {
let light = (l + (region_rand(r.id, 2, s) - 0.5) * lr).clamp(0.0, 1.0);
let c = crate::ops::hsl_to_rgb(region_rand(r.id, 1, s), sat, light);
[c[0], c[1], c[2], 1.0]
})])
}
fn to_gradient(ctx: &Ctx) -> CookResult {
let (a, ar, sr, s) = (ctx.f("angle"), ctx.f("angle_random"), ctx.f("slope_random"), ctx.seed);
Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| {
let (sn, cs) = ((a + (region_rand(r.id, 3, s) - 0.5) * ar) * TAU).sin_cos();
// Projection onto the direction, normalized so the gradient spans 0..1 over the box.
let (x, y) = (r.local[0] - 0.5, r.local[1] - 0.5);
let t = 0.5 + (x * cs + y * sn) / (cs.abs() + sn.abs()).max(1e-6);
let slope = 1.0 - sr * region_rand(r.id, 4, s);
[(t * slope).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
})])
}
fn to_bbox_size(ctx: &Ctx) -> CookResult {
let mode = ctx.i("mode");
Ok(vec![per_region(ctx, 0, Kind::Gray, [0.0; 4], |r, _, _| {
let [w, h] = r.size;
let v = match mode {
0 => w,
1 => h,
3 => w.min(h),
4 => w * h,
_ => w.max(h),
};
[v, 0.0, 0.0, 0.0]
})])
}
fn to_position(ctx: &Ctx) -> CookResult {
Ok(vec![per_region(ctx, 0, Kind::Color, [0.0, 0.0, 0.0, 1.0], |r, _, _| [r.center[0], r.center[1], 0.0, 1.0])])
}
fn sample_at_center(ctx: &Ctx, kind: Kind) -> Image {
let src = ctx.input(1).map(|i| i.to_kind(kind));
let tile = ctx.tile;
per_region(ctx, 0, kind, [0.0, 0.0, 0.0, 1.0], |r, _, _| src.as_ref().map_or([1.0; 4], |img| img.sample(r.center[0], r.center[1], tile)))
}
fn to_grayscale(ctx: &Ctx) -> CookResult {
Ok(vec![sample_at_center(ctx, Kind::Gray)])
}
fn to_color(ctx: &Ctx) -> CookResult {
Ok(vec![sample_at_center(ctx, Kind::Color)])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::{find, resolve_params};
fn cook(id: &str, inputs: &[Option<Image>], w: u32) -> Vec<Image> {
let def = find(id).unwrap();
let params = resolve_params(def, &BTreeMap::new());
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w, h: w, seed: 3, tile: true, inputs, params: &params, resource: &no_res, vars: &vars };
(def.cook)(&ctx).unwrap()
}
#[test]
fn separate_squares_differ_and_edge_square_wraps() {
// Square A at 2..6, square B at 10..14, square C straddling the right edge (x 14..16 and 0..1)
// in rows 10..13.
let mask = Image::gray(16, 16, |x, y| {
let a = (2..6).contains(&x) && (2..6).contains(&y);
let b = (9..13).contains(&x) && (2..6).contains(&y);
let c = !(1..14).contains(&x) && (10..13).contains(&y);
(a || b || c) as i32 as f32
});
let idx = &cook("flood_fill", &[Some(mask)], 16)[0];
let (a, b) = (idx.get(3, 3, false), idx.get(10, 3, false));
assert_eq!(a[3], 1.0);
assert_ne!(a[2], b[2], "separate squares get different ids");
assert_eq!(idx.get(0, 0, false), [0.0; 4], "gaps stay empty");
let (l, r) = (idx.get(0, 11, false), idx.get(15, 11, false));
assert_eq!(l, r, "a square across the edge is one region");
// Pixels 14, 15 and 0 (wrapped to 16): the box middle is 15.5 px.
assert!((l[0] - 15.5 / 16.0).abs() < 1e-5, "{l:?}");
let gray = &cook("flood_fill_to_random_grayscale", &[Some(idx.clone())], 16)[0];
assert_eq!(gray.get(0, 11, false), gray.get(15, 11, false));
assert_ne!(gray.get(3, 3, false), gray.get(10, 3, false));
let size = &cook("flood_fill_to_bbox_size", &[Some(idx.clone())], 16)[0];
assert!((size.get(15, 11, false)[0] - 3.0 / 16.0).abs() < 1e-5);
let grad = &cook("flood_fill_to_gradient", &[Some(idx.clone())], 16)[0];
assert!(grad.get(2, 3, false)[0] < grad.get(5, 3, false)[0]);
assert!(grad.get(14, 11, false)[0] < grad.get(0, 11, false)[0], "the gradient continues across the edge");
}
}
-482
View File
@@ -1,482 +0,0 @@
//! Function graph evaluation: a [`FnGraph`] is compiled once into a flat instruction list
//! (dependency order from the output node), then run per pixel with a small register file. All
//! values are 4-wide; scalars are broadcast to every lane, so component-wise ops need no type
//! checks. The pixel processor samples its inputs at any position; the value processor runs once.
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_core::function::FnGraph;
use materialcraft_image::{Image, Kind};
use crate::catalog::{CookResult, Ctx};
use crate::noise;
/// Function node operations: (id, label, input count, library category).
pub const FN_OPS: &[(&str, &str, usize, &str)] = &[
("const_float", "Float", 0, "Constant"),
("const_float2", "Float2", 0, "Constant"),
("const_float3", "Float3", 0, "Constant"),
("const_float4", "Float4", 0, "Constant"),
("const_int", "Integer", 0, "Constant"),
("const_bool", "Boolean", 0, "Constant"),
("get_pos", "$pos", 0, "Variables"),
("get_size", "$size", 0, "Variables"),
("get_var", "Get variable", 0, "Variables"),
("sample_gray", "Sample Gray", 1, "Samplers"),
("sample_color", "Sample Color", 1, "Samplers"),
("vec2", "Vector Float2", 2, "Vector"),
("vec3", "Vector Float3", 3, "Vector"),
("vec4", "Vector Float4", 4, "Vector"),
("swizzle", "Swizzle", 1, "Vector"),
("to_int", "To Integer", 1, "Cast"),
("to_float", "To Float", 1, "Cast"),
("add", "Add", 2, "Operator"),
("sub", "Subtraction", 2, "Operator"),
("mul", "Multiplication", 2, "Operator"),
("div", "Division", 2, "Operator"),
("mod", "Modulo", 2, "Operator"),
("neg", "Negation", 1, "Operator"),
("dot", "Dot Product", 2, "Operator"),
("and", "And", 2, "Logical"),
("or", "Or", 2, "Logical"),
("not", "Not", 1, "Logical"),
("gt", "Greater", 2, "Comparison"),
("ge", "Greater or equal", 2, "Comparison"),
("lt", "Lower", 2, "Comparison"),
("le", "Lower or equal", 2, "Comparison"),
("eq", "Equal", 2, "Comparison"),
("ne", "Not equal", 2, "Comparison"),
("abs", "Absolute", 1, "Function"),
("floor", "Floor", 1, "Function"),
("ceil", "Ceil", 1, "Function"),
("frac", "Fractional part", 1, "Function"),
("sqrt", "Square root", 1, "Function"),
("exp", "Exponential", 1, "Function"),
("log", "Logarithm", 1, "Function"),
("log2", "Logarithm base 2", 1, "Function"),
("pow2", "2^x", 1, "Function"),
("sin", "Sine", 1, "Function"),
("cos", "Cosine", 1, "Function"),
("tan", "Tangent", 1, "Function"),
("atan2", "Arc tangent 2", 2, "Function"),
("cartesian", "Cartesian", 2, "Function"),
("pow", "Power", 2, "Function"),
("min", "Minimum", 2, "Function"),
("max", "Maximum", 2, "Function"),
("clamp", "Clamp", 3, "Function"),
("lerp", "Linear interpolation", 3, "Function"),
("length", "Length", 1, "Function"),
("normalize", "Normalize", 1, "Function"),
("rand", "Random", 1, "Function"),
("noise", "Perlin noise", 1, "Function"),
("if_else", "If...Else", 3, "Control"),
];
#[derive(Clone, Debug)]
enum Op {
Const([f32; 4]),
Pos,
Size,
Sample { input: usize, gray: bool },
Unary(fn(f32) -> f32),
Binary(fn(f32, f32) -> f32),
Ternary(fn(f32, f32, f32) -> f32),
Dot,
Length,
Normalize,
Vec(usize),
Swizzle([usize; 4]),
Rand,
Noise,
IfElse,
Cartesian,
}
#[derive(Clone, Debug)]
struct Instr {
op: Op,
args: Vec<usize>,
/// Lanes that carry meaning (1 = scalar).
dims: usize,
}
/// A compiled function graph.
#[derive(Clone, Debug)]
pub struct Program {
code: Vec<Instr>,
seed: u32,
}
fn b(v: bool) -> f32 {
if v { 1.0 } else { 0.0 }
}
/// Return zero for nonfinite arithmetic results.
fn finite_or_zero(v: f32) -> f32 {
if v.is_finite() { v } else { 0.0 }
}
fn dims_of(v: &Value) -> usize {
match v {
Value::Float2(_) | Value::Int2(_) => 2,
Value::Float3(_) => 3,
Value::Float4(_) | Value::Color(_) => 4,
_ => 1,
}
}
fn broadcast(v: &Value) -> [f32; 4] {
match dims_of(v) {
1 => [v.as_f32().unwrap_or(0.0); 4],
_ => v.as_vec4().unwrap_or([0.0; 4]),
}
}
/// Compile `g` for evaluation. `vars` resolves `get_var` names (exposed graph inputs).
pub fn compile(g: &FnGraph, vars: &BTreeMap<String, Value>, seed: u32) -> Result<Program, String> {
let out = g.output.ok_or("the function has no output node")?;
let mut code: Vec<Instr> = Vec::new();
let mut reg: BTreeMap<u32, usize> = BTreeMap::new();
// Iterative post-order from the output; a node seen twice on the current path is a cycle.
let mut stack: Vec<(u32, bool)> = vec![(out, false)];
let mut on_path = std::collections::BTreeSet::new();
while let Some((id, done)) = stack.pop() {
if reg.contains_key(&id) {
continue;
}
let n = g.node(id).ok_or_else(|| format!("missing function node {id}"))?;
if !done {
if !on_path.insert(id) {
return Err("the function graph has a cycle".into());
}
stack.push((id, true));
for i in n.inputs.iter().flatten() {
if !reg.contains_key(i) {
stack.push((*i, false));
}
}
continue;
}
on_path.remove(&id);
if code.len() > 4096 {
return Err("the function graph is too large".into());
}
let args: Vec<usize> = n.inputs.iter().map(|i| i.and_then(|i| reg.get(&i).copied())).map(|r| r.unwrap_or(usize::MAX)).collect();
let arity = FN_OPS.iter().find(|o| o.0 == n.op).map(|o| o.2).ok_or_else(|| format!("unknown function op `{}`", n.op))?;
if args.len() < arity || args.iter().take(arity).any(|a| *a == usize::MAX) {
return Err(format!("`{}` needs {arity} connected input(s)", n.op));
}
let dim = |k: usize| args.get(k).and_then(|r| code.get(*r)).map_or(1, |i: &Instr| i.dims);
let maxd = (0..arity).map(dim).max().unwrap_or(1);
let (op, dims) = match n.op.as_str() {
o if o.starts_with("const_") => {
let v = n.value.clone().unwrap_or(Value::Float(0.0));
(Op::Const(broadcast(&v)), dims_of(&v))
}
"get_pos" => (Op::Pos, 2),
"get_size" => (Op::Size, 2),
"get_var" => {
let name = match &n.value {
Some(Value::Text(s)) => s.as_str(),
_ => "",
};
let v = vars.get(name).cloned().unwrap_or(Value::Float(0.0));
(Op::Const(broadcast(&v)), dims_of(&v))
}
"sample_gray" | "sample_color" => {
let input = n.value.as_ref().and_then(Value::as_i32).unwrap_or(0).clamp(0, 3) as usize;
let gray = n.op == "sample_gray";
(Op::Sample { input, gray }, if gray { 1 } else { 4 })
}
"vec2" => (Op::Vec(2), 2),
"vec3" => (Op::Vec(3), 3),
"vec4" => (Op::Vec(4), 4),
"swizzle" => {
let s = match &n.value {
Some(Value::Text(s)) => s.clone(),
_ => "x".into(),
};
let mut idx = [0usize; 4];
let mut len = 0;
for (k, ch) in s.chars().take(4).enumerate() {
idx[k] = match ch {
'y' | 'g' => 1,
'z' | 'b' => 2,
'w' | 'a' => 3,
_ => 0,
};
len = k + 1;
}
if len == 1 {
idx = [idx[0]; 4];
}
(Op::Swizzle(idx), len.max(1))
}
"to_int" | "floor" => (Op::Unary(f32::floor), maxd),
"to_float" => (Op::Unary(|a| a), maxd),
"add" => (Op::Binary(|a, b| a + b), maxd),
"sub" => (Op::Binary(|a, b| a - b), maxd),
"mul" => (Op::Binary(|a, b| a * b), maxd),
"div" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a / b }), maxd),
"mod" => (Op::Binary(|a, b| if b == 0.0 { 0.0 } else { a.rem_euclid(b) }), maxd),
"neg" => (Op::Unary(|a| -a), maxd),
"dot" => (Op::Dot, 1),
"and" => (Op::Binary(|a, x| b(a != 0.0 && x != 0.0)), maxd),
"or" => (Op::Binary(|a, x| b(a != 0.0 || x != 0.0)), maxd),
"not" => (Op::Unary(|a| b(a == 0.0)), maxd),
"gt" => (Op::Binary(|a, x| b(a > x)), maxd),
"ge" => (Op::Binary(|a, x| b(a >= x)), maxd),
"lt" => (Op::Binary(|a, x| b(a < x)), maxd),
"le" => (Op::Binary(|a, x| b(a <= x)), maxd),
"eq" => (Op::Binary(|a, x| b(a == x)), maxd),
"ne" => (Op::Binary(|a, x| b(a != x)), maxd),
"abs" => (Op::Unary(f32::abs), maxd),
"ceil" => (Op::Unary(f32::ceil), maxd),
"frac" => (Op::Unary(|a| a - a.floor()), maxd),
"sqrt" => (Op::Unary(|a| a.max(0.0).sqrt()), maxd),
"exp" => (Op::Unary(f32::exp), maxd),
"log" => (Op::Unary(|a| if a > 0.0 { a.ln() } else { 0.0 }), maxd),
"log2" => (Op::Unary(|a| if a > 0.0 { finite_or_zero(a.log2()) } else { 0.0 }), maxd),
"pow2" => (Op::Unary(|a| finite_or_zero(a.exp2())), maxd),
"sin" => (Op::Unary(f32::sin), maxd),
"cos" => (Op::Unary(f32::cos), maxd),
"tan" => (Op::Unary(f32::tan), maxd),
"atan2" => (Op::Binary(f32::atan2), maxd),
"cartesian" => (Op::Cartesian, 2),
"pow" => (Op::Binary(|a, x| if a < 0.0 && x.fract() != 0.0 { 0.0 } else { a.powf(x) }), maxd),
"min" => (Op::Binary(f32::min), maxd),
"max" => (Op::Binary(f32::max), maxd),
"clamp" => (Op::Ternary(|a, lo, hi| a.max(lo).min(hi.max(lo))), maxd),
"lerp" => (Op::Ternary(|a, x, t| a + (x - a) * t), maxd.max(dim(0)).max(dim(1))),
"length" => (Op::Length, 1),
"normalize" => (Op::Normalize, dim(0)),
"rand" => (Op::Rand, dim(0)),
"noise" => (Op::Noise, 1),
"if_else" => (Op::IfElse, dim(1).max(dim(2))),
other => return Err(format!("unknown function op `{other}`")),
};
reg.insert(id, code.len());
code.push(Instr { op, args: args.into_iter().take(arity).collect(), dims });
}
Ok(Program { code, seed })
}
impl Program {
/// Lanes of the result.
pub fn dims(&self) -> usize {
self.code.last().map_or(1, |i| i.dims)
}
/// Run at normalized position `pos` of an image of `size`, sampling `inputs`.
pub fn eval(&self, pos: [f32; 2], size: [f32; 2], inputs: &[Option<Image>], tile: bool, regs: &mut Vec<[f32; 4]>) -> [f32; 4] {
regs.clear();
for ins in &self.code {
let a = |k: usize| ins.args.get(k).and_then(|r| regs.get(*r)).copied().unwrap_or([0.0; 4]);
let v = match &ins.op {
Op::Const(c) => *c,
Op::Pos => [pos[0], pos[1], 0.0, 0.0],
Op::Size => [size[0], size[1], 0.0, 0.0],
Op::Sample { input, gray } => {
let p = a(0);
match inputs.get(*input).and_then(Option::as_ref) {
Some(img) if *gray => [img.sample_gray(p[0], p[1], tile); 4],
Some(img) => img.sample(p[0], p[1], tile),
None => [0.0, 0.0, 0.0, 1.0],
}
}
Op::Unary(f) => a(0).map(f),
Op::Binary(f) => {
let (x, y) = (a(0), a(1));
[f(x[0], y[0]), f(x[1], y[1]), f(x[2], y[2]), f(x[3], y[3])]
}
Op::Ternary(f) => {
let (x, y, z) = (a(0), a(1), a(2));
[f(x[0], y[0], z[0]), f(x[1], y[1], z[1]), f(x[2], y[2], z[2]), f(x[3], y[3], z[3])]
}
Op::Dot => {
let (x, y) = (a(0), a(1));
let n = ins.args.iter().filter_map(|r| self.code.get(*r)).map(|i| i.dims).max().unwrap_or(1);
[(0..n).map(|k| x[k] * y[k]).sum(); 4]
}
Op::Length => {
let x = a(0);
let n = ins.args.first().and_then(|r| self.code.get(*r)).map_or(1, |i| i.dims);
[(0..n).map(|k| x[k] * x[k]).sum::<f32>().sqrt(); 4]
}
Op::Normalize => {
let x = a(0);
let l = (0..ins.dims).map(|k| x[k] * x[k]).sum::<f32>().sqrt();
if l > 0.0 { x.map(|c| c / l) } else { x }
}
Op::Vec(n) => {
let mut o = [0.0; 4];
for k in 0..*n {
o[k] = a(k)[0];
}
o
}
Op::Swizzle(idx) => {
let x = a(0);
idx.map(|i| x[i])
}
Op::Rand => a(0).map(|c| noise::rand1(c.to_bits(), self.seed)),
Op::Noise => {
let p = a(0);
[noise::perlin(p[0], p[1], 0, self.seed) * 0.5 + 0.5; 4]
}
Op::Cartesian => {
// Inputs are radius and angle (radians); the result is a Float2.
let (radius, angle) = (a(0)[0], a(1)[0]);
if radius.is_finite() && angle.is_finite() {
let (sin, cos) = angle.sin_cos();
[finite_or_zero(radius * cos), finite_or_zero(radius * sin), 0.0, 0.0]
} else {
[0.0; 4]
}
}
Op::IfElse => {
if a(0)[0] != 0.0 {
a(1)
} else {
a(2)
}
}
};
regs.push(v);
}
regs.last().copied().unwrap_or([0.0; 4])
}
}
/// The default pixel processor function: the first input, unchanged.
pub fn default_pixel_function() -> FnGraph {
let mut g = FnGraph::default();
let pos = g.add("get_pos", &[], None);
let s = g.add("sample_color", &[pos], Some(Value::Int(0)));
g.output = Some(s);
g
}
pub(crate) fn pixel_processor(ctx: &Ctx) -> CookResult {
let f = ctx.function("function").ok_or("no function")?;
let prog = compile(f, ctx.vars, ctx.seed)?;
let gray = ctx.i("output") == 1;
let dims = prog.dims();
let size = [ctx.w as f32, ctx.h as f32];
let kind = if gray { Kind::Gray } else { Kind::Color };
Ok(vec![Image::generate_uv(ctx.w, ctx.h, kind, |u, v| {
// shortcut: one register file per pixel; a thread-local would save the allocation.
let mut regs = Vec::with_capacity(prog.code.len());
let r = prog.eval([u, v], size, ctx.inputs, ctx.tile, &mut regs);
match (gray, dims) {
(true, _) => [r[0], 0.0, 0.0, 0.0],
(false, 1) => [r[0], r[0], r[0], 1.0],
(false, 2) => [r[0], r[1], 0.0, 1.0],
(false, 3) => [r[0], r[1], r[2], 1.0],
_ => r,
}
})])
}
pub(crate) fn value_processor(ctx: &Ctx) -> CookResult {
let f = ctx.function("function").ok_or("no function")?;
let prog = compile(f, ctx.vars, ctx.seed)?;
let r = prog.eval([0.5, 0.5], [ctx.w as f32, ctx.h as f32], ctx.inputs, ctx.tile, &mut Vec::new());
Ok(vec![if prog.dims() == 1 { Image::filled(ctx.w, ctx.h, Kind::Gray, [r[0]; 4]) } else { Image::filled(ctx.w, ctx.h, Kind::Color, r) }])
}
#[cfg(test)]
mod tests {
use super::*;
fn evaluate_math(op: &str, values: &[Value]) -> (usize, [f32; 4]) {
let mut g = FnGraph::default();
let inputs: Vec<_> = values
.iter()
.map(|value| {
let op = match value {
Value::Float2(_) => "const_float2",
Value::Float3(_) => "const_float3",
Value::Float4(_) => "const_float4",
_ => "const_float",
};
g.add(op, &[], Some(value.clone()))
})
.collect();
g.output = Some(g.add(op, &inputs, None));
let p = compile(&g, &BTreeMap::new(), 0).unwrap();
(p.dims(), p.eval([0.0; 2], [1.0; 2], &[], true, &mut Vec::new()))
}
#[test]
fn base_two_functions_preserve_lanes_and_scalar_broadcast() {
let (dims, result) = evaluate_math("pow2", &[Value::Float4([-2.0, 0.0, 1.0, 3.0])]);
assert_eq!((dims, result), (4, [0.25, 1.0, 2.0, 8.0]));
let (dims, result) = evaluate_math("log2", &[Value::Float4([0.25, 1.0, 2.0, 8.0])]);
assert_eq!((dims, result), (4, [-2.0, 0.0, 1.0, 3.0]));
assert_eq!(evaluate_math("pow2", &[Value::Float(3.0)]), (1, [8.0; 4]));
assert_eq!(evaluate_math("log2", &[Value::Float(8.0)]), (1, [3.0; 4]));
for op in ["pow2", "log2"] {
assert_eq!(evaluate_math(op, &[Value::Float2([1.0, 2.0])]).0, 2);
assert_eq!(evaluate_math(op, &[Value::Float3([1.0, 2.0, 3.0])]).0, 3);
}
}
#[test]
fn cartesian_uses_radius_then_angle_in_radians() {
for (radius, angle, expected) in [
(2.0, 0.0, [2.0, 0.0]),
(2.0, std::f32::consts::FRAC_PI_2, [0.0, 2.0]),
(2.0, -std::f32::consts::FRAC_PI_2, [0.0, -2.0]),
(2.0, std::f32::consts::PI, [-2.0, 0.0]),
(0.0, 1.0, [0.0, 0.0]),
] {
let (dims, result) = evaluate_math("cartesian", &[Value::Float(radius), Value::Float(angle)]);
assert_eq!(dims, 2);
assert!((result[0] - expected[0]).abs() < 1e-6);
assert!((result[1] - expected[1]).abs() < 1e-6);
assert_eq!(&result[2..], &[0.0, 0.0]);
}
}
#[test]
fn new_math_functions_handle_invalid_domains_and_missing_inputs() {
assert_eq!(evaluate_math("log2", &[Value::Float4([0.0, -1.0, f32::NAN, f32::INFINITY])]).1, [0.0; 4]);
assert_eq!(evaluate_math("pow2", &[Value::Float4([128.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY])]).1, [0.0; 4]);
for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert_eq!(evaluate_math("cartesian", &[Value::Float(invalid), Value::Float(0.0)]).1, [0.0; 4]);
assert_eq!(evaluate_math("cartesian", &[Value::Float(1.0), Value::Float(invalid)]).1, [0.0; 4]);
}
for op in ["pow2", "log2", "cartesian"] {
let mut g = FnGraph::default();
g.output = Some(g.add(op, &[], None));
assert!(compile(&g, &BTreeMap::new(), 0).is_err());
}
}
#[test]
fn compiles_and_runs_arithmetic() {
let mut g = FnGraph::default();
let pos = g.add("get_pos", &[], None);
let x = g.add("swizzle", &[pos], Some(Value::Text("x".into())));
let two = g.add("const_float", &[], Some(Value::Float(2.0)));
let m = g.add("mul", &[x, two], None);
g.output = Some(m);
let p = compile(&g, &BTreeMap::new(), 0).unwrap();
assert_eq!(p.dims(), 1);
let r = p.eval([0.25, 0.5], [8.0, 8.0], &[], true, &mut Vec::new());
assert_eq!(r[0], 0.5);
}
#[test]
fn rejects_bad_graphs() {
let mut g = FnGraph::default();
let a = g.add("add", &[], None);
g.output = Some(a);
assert!(compile(&g, &BTreeMap::new(), 0).is_err());
g.nodes[0].inputs = vec![Some(a), Some(a)];
assert!(compile(&g, &BTreeMap::new(), 0).is_err());
assert!(compile(&FnGraph::default(), &BTreeMap::new(), 0).is_err());
}
}
-282
View File
@@ -1,282 +0,0 @@
//! Atomic › FX-Map: a pattern instancer (regular grid, random scatter or random quadtree
//! subdivision), plus the shared splatting engine of the scatter nodes. Instances wrap across the
//! edges, so the output tiles.
use std::f32::consts::{SQRT_2, TAU};
use materialcraft_image::{Image, Kind};
use crate::atomic::ATOMIC;
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::noise::{hash, rand1};
use crate::patterns::{PATTERNS, SHAPES, shape};
/// One placed pattern: center (uv), half extents (uv), rotation (turns), luminance and the index
/// of the pattern it shows.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Inst {
pub c: [f32; 2],
pub r: [f32; 2],
pub rot: f32,
pub lum: f32,
pub pat: usize,
}
pub(crate) const BLENDS: &[&str] = &["Max", "Add", "Alpha over"];
/// Renders `items` over black. Item `i` covers the rotated box ±`r` around its center, where
/// `pat(i, x, y)` is its pattern (0..1) at local coordinates -1..1. Items are binned on a grid about
/// their size so a pixel only tests its neighbours; later items draw on top (Alpha over).
pub(crate) fn splat(ctx: &Ctx, items: &[Inst], blend: i32, pat: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image {
let valid = |it: &Inst| it.r[0] > 1e-6 && it.r[1] > 1e-6 && it.c.iter().chain(&it.r).all(|v| v.is_finite());
let n = items.iter().filter(|it| valid(it)).count().max(1);
let mean_r = items.iter().filter(|it| valid(it)).map(|it| it.r[0].max(it.r[1])).sum::<f32>() / n as f32;
let g = ((0.5 / mean_r.max(1e-4)) as usize).clamp(1, 256);
let gf = g as f32;
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g];
for (i, it) in items.iter().enumerate().filter(|(_, it)| valid(it)) {
let br = it.r[0].max(it.r[1]) * SQRT_2;
// At most one full turn of bins per axis, so no item lands twice in a bin.
let span = |c: f32| {
let a = ((c - br) * gf).floor() as i64;
(a, (((c + br) * gf).floor() as i64).min(a + g as i64 - 1))
};
let ((x0, x1), (y0, y1)) = (span(it.c[0]), span(it.c[1]));
for gy in y0..=y1 {
for gx in x0..=x1 {
if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) {
b.push(i as u32);
}
}
}
}
let rots: Vec<(f32, f32)> = items.iter().map(|it| (-it.rot * TAU).sin_cos()).collect();
let tile = ctx.tile;
Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| {
let mut acc = 0.0f32;
let bin = bins.get(((v * gf) as usize).min(g - 1) * g + ((u * gf) as usize).min(g - 1));
for &i in bin.into_iter().flatten() {
let (Some(it), Some(&(s, c))) = (items.get(i as usize), rots.get(i as usize)) else { continue };
let (mut dx, mut dy) = (u - it.c[0], v - it.c[1]);
if tile {
dx -= dx.round();
dy -= dy.round();
}
let (x, y) = ((dx * c - dy * s) / it.r[0], (dx * s + dy * c) / it.r[1]);
if x.abs() > 1.0 || y.abs() > 1.0 {
continue;
}
let p = pat(i as usize, x, y);
if p <= 0.0 {
continue;
}
acc = match blend {
1 => acc + p * it.lum,
2 => acc + (it.lum - acc) * p.min(1.0),
_ => acc.max(p * it.lum),
};
}
[acc, 0.0, 0.0, 0.0]
})
}
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("fx_map", "FX-Map", ATOMIC)
.desc(
"Instances up to three patterns on a grid, at random positions or in a random quadtree, with per-instance scale, rotation, \
position and luminance jitter. Scale 1 fills an instance's cell. Unconnected: soft discs. Tiles.",
)
.atomic()
.generator()
.gray_in("pattern0", "Pattern 0")
.gray_in("pattern1", "Pattern 1")
.gray_in("pattern2", "Pattern 2")
.choice("mode", "Mode", &["Grid", "Random", "Quadtree"], 2)
.int("count", "Count (random)", 64, 1, 20000)
.int("x_amount", "X amount", 4, 1, 256)
.int("y_amount", "Y amount", 4, 1, 256)
.int("subdivisions", "Subdivisions (quadtree)", 3, 0, 8)
.float("split_chance", "Subdivide chance", 0.5, 0.0, 1.0)
.float("scale", "Scale", 0.9, 0.0, 2.0)
.float("scale_random", "Scale random", 0.2, 0.0, 1.0)
.angle("rotation", "Rotation", 0.0)
.float("rotation_random", "Rotation random", 0.0, 0.0, 1.0)
.float("position_random", "Position random", 0.0, 0.0, 1.0)
.float("luminance", "Luminance", 1.0, 0.0, 1.0)
.float("luminance_random", "Luminance random", 0.4, 0.0, 1.0)
.float("pattern_random", "Pattern random", 1.0, 0.0, 1.0)
.choice("blending", "Blending", BLENDS, 0)
.int("seed_offset", "Seed offset", 0, 0, 10000)
.gray_out()
.cook(fx_map),
node("shape_splatter", "Shape Splatter", PATTERNS)
.desc("Scatters the pattern input (or a shape) with random scale, rotation and luminance; the mask input sets where instances land.")
.generator()
.gray_in("pattern", "Pattern")
.gray_in("mask", "Mask")
.choice("shape", "Shape (no input)", SHAPES, 3)
.int("count", "Count", 300, 1, 20000)
.float("size", "Size", 0.05, 0.0, 1.0)
.float("size_random", "Size random", 0.5, 0.0, 1.0)
.float("rotation_random", "Rotation random", 1.0, 0.0, 1.0)
.float("luminance_random", "Luminance random", 0.4, 0.0, 1.0)
.choice("blending", "Blending", BLENDS, 0)
.gray_out()
.cook(shape_splatter),
]
}
/// A connected pattern at local `(x, y)` (-1..1), or a soft disc when there is none.
pub(crate) fn sample_pattern(pats: &[Image], k: usize, x: f32, y: f32) -> f32 {
match pats.get(k) {
Some(img) => img.sample_gray((x + 1.0) * 0.5, (y + 1.0) * 0.5, false),
None => shape(3, x, y),
}
}
/// Cells of a random quadtree over an `nx × ny` root grid: (center, size, key). A cell splits
/// with probability `chance` until `depth`.
fn quadtree(nx: i32, ny: i32, depth: i32, chance: f32, seed: u32) -> Vec<([f32; 2], [f32; 2], u32)> {
const MAX_CELLS: usize = 1 << 18;
let mut out = Vec::new();
let mut stack: Vec<([f32; 2], [f32; 2], i32, u32)> = Vec::new();
for j in (0..ny).rev() {
for i in (0..nx).rev() {
let size = [1.0 / nx as f32, 1.0 / ny as f32];
stack.push(([i as f32 * size[0], j as f32 * size[1]], size, 0, hash((j * nx + i) as u32 ^ 0x5157_0000)));
}
}
while let Some((p, s, lvl, key)) = stack.pop() {
if lvl < depth && rand1(key, seed ^ 0x51ed) < chance && out.len() + stack.len() + 4 <= MAX_CELLS {
let h = [s[0] * 0.5, s[1] * 0.5];
for q in (0..4u32).rev() {
let o = [p[0] + (q & 1) as f32 * h[0], p[1] + (q >> 1) as f32 * h[1]];
stack.push((o, h, lvl + 1, hash(key.wrapping_mul(4).wrapping_add(q + 1))));
}
} else {
out.push(([p[0] + s[0] * 0.5, p[1] + s[1] * 0.5], s, key));
}
}
out
}
/// The instances an FX-Map places (separate from rendering, so it can be tested).
pub(crate) fn fx_instances(ctx: &Ctx, n_patterns: usize) -> Vec<Inst> {
let seed = ctx.seed.wrapping_add(ctx.i("seed_offset") as u32);
let (nx, ny) = (ctx.i("x_amount").clamp(1, 256), ctx.i("y_amount").clamp(1, 256));
let cells: Vec<([f32; 2], [f32; 2], u32)> = match ctx.i("mode") {
0 => (0..ny)
.flat_map(|j| {
(0..nx).map(move |i| ([(i as f32 + 0.5) / nx as f32, (j as f32 + 0.5) / ny as f32], [1.0 / nx as f32, 1.0 / ny as f32], (j * nx + i) as u32))
})
.collect(),
1 => {
let count = ctx.i("count").clamp(1, 20000) as u32;
let side = 1.0 / (count as f32).sqrt();
(0..count).map(|i| ([rand1(i * 2, seed ^ 0xa11), rand1(i * 2 + 1, seed ^ 0xa11)], [side, side], i)).collect()
}
_ => quadtree(nx, ny, ctx.i("subdivisions").clamp(0, 8), ctx.f("split_chance"), seed),
};
let (sc, sr, rot, rr, pr) = (ctx.f("scale"), ctx.f("scale_random"), ctx.f("rotation"), ctx.f("rotation_random"), ctx.f("position_random"));
let (lum, lr, patr) = (ctx.f("luminance"), ctx.f("luminance_random"), ctx.f("pattern_random"));
let n = n_patterns.max(1);
cells
.into_iter()
.map(|(c, size, key)| {
let r = |k: u32| rand1(key.wrapping_mul(8).wrapping_add(k), seed);
let s = sc * (1.0 - sr * r(2));
Inst {
c: [c[0] + (r(0) - 0.5) * pr * size[0], c[1] + (r(1) - 0.5) * pr * size[1]],
r: [size[0] * 0.5 * s, size[1] * 0.5 * s],
rot: rot + (r(3) - 0.5) * rr,
lum: lum * (1.0 - lr * r(4)),
pat: if r(5) < patr { ((r(6) * n as f32) as usize).min(n - 1) } else { 0 },
}
})
.collect()
}
fn fx_map(ctx: &Ctx) -> CookResult {
let pats: Vec<Image> = (0..3).filter_map(|i| ctx.input(i).map(Image::to_gray)).collect();
let items = fx_instances(ctx, pats.len());
Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| sample_pattern(&pats, items.get(i).map_or(0, |it| it.pat), x, y))])
}
fn shape_splatter(ctx: &Ctx) -> CookResult {
let pats: Vec<Image> = ctx.input(0).map(Image::to_gray).into_iter().collect();
let mask = ctx.input(1);
let (k, s) = (ctx.i("shape"), ctx.seed);
let (size, sr, rr, lr) = (ctx.f("size"), ctx.f("size_random"), ctx.f("rotation_random"), ctx.f("luminance_random"));
let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 20000) as u32)
.filter_map(|i| {
let r = |k: u32| rand1(i * 8 + k, s);
let c = [r(0), r(1)];
// Instances land where the mask is bright: kept with probability = mask value.
if mask.is_some_and(|m| r(2) >= m.sample_gray(c[0], c[1], ctx.tile)) {
return None;
}
let rad = size * (1.0 - sr * r(3));
Some(Inst { c, r: [rad, rad], rot: (r(4) - 0.5) * rr, lum: 1.0 - lr * r(5), pat: 0 })
})
.collect();
Ok(vec![splat(ctx, &items, ctx.i("blending"), |_, x, y| if pats.is_empty() { shape(k, x, y) } else { sample_pattern(&pats, 0, x, y) })])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use materialcraft_core::Value;
use super::*;
use crate::catalog::{find, resolve_params};
fn with(params: &[(&str, Value)], f: impl FnOnce(&Ctx)) {
let def = find("fx_map").unwrap();
let mut p = resolve_params(def, &BTreeMap::new());
for (k, v) in params {
p.insert(k.to_string(), v.clone());
}
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let inputs = [None, None, None];
f(&Ctx { w: 64, h: 64, seed: 3, tile: true, inputs: &inputs, params: &p, resource: &no_res, vars: &vars });
}
#[test]
fn fx_map_instance_counts() {
with(&[("mode", Value::Enum(0)), ("x_amount", Value::Int(5)), ("y_amount", Value::Int(3))], |c| assert_eq!(fx_instances(c, 1).len(), 15));
with(&[("mode", Value::Enum(1)), ("count", Value::Int(77))], |c| assert_eq!(fx_instances(c, 1).len(), 77));
let quad = |chance: f32, depth: i32| {
let mut n = 0;
with(
&[
("mode", Value::Enum(2)),
("x_amount", Value::Int(2)),
("y_amount", Value::Int(1)),
("subdivisions", Value::Int(depth)),
("split_chance", Value::Float(chance)),
],
|c| n = fx_instances(c, 1).len(),
);
n
};
assert_eq!(quad(0.0, 3), 2);
assert_eq!(quad(1.0, 3), 2 * 64);
let some = quad(0.5, 4);
assert!(some > 2 && some < 2 * 256, "{some}");
}
#[test]
fn fx_map_is_deterministic_per_seed() {
let cook = |off: i32| {
let mut img = None;
with(&[("seed_offset", Value::Int(off))], |c| img = Some(fx_map(c).unwrap().remove(0)));
img.unwrap()
};
assert_eq!(cook(0), cook(0));
assert_ne!(cook(0), cook(1));
assert!(cook(0).mean()[0] > 0.05);
}
}
-419
View File
@@ -1,419 +0,0 @@
//! Texture generators › Noises. All tile seamlessly: lattice scales are whole numbers of cells.
use materialcraft_image::{Image, Kind};
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::noise::{self, cellular, fbm, perlin, rand2, ridged, value, value_xy};
use crate::ops;
pub const NOISES: &str = "Texture generators/Noises";
fn scale(ctx: &Ctx) -> f32 {
ctx.f("scale").max(1.0).round()
}
pub(crate) fn defs() -> Vec<NodeDef> {
let n = |id, label| node(id, label, NOISES).generator();
vec![
n("anisotropic_noise", "Anisotropic Noise")
.desc("Streaks of value noise stretched along one axis.")
.float("scale", "X amount", 4.0, 1.0, 64.0)
.float("scale_y", "Y amount", 64.0, 1.0, 512.0)
.float("smoothness", "Smoothness", 0.5, 0.0, 1.0)
.float("interpolation", "Interpolation", 1.0, 0.0, 1.0)
.gray_out()
.cook(anisotropic),
n("bnw_spots_1", "BnW Spots 1")
.desc("Contrasted black and white spots.")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(bnw1),
n("bnw_spots_2", "BnW Spots 2")
.desc("Rounder black and white spots.")
.float("scale", "Scale", 6.0, 1.0, 64.0)
.float("roughness", "Roughness", 0.3, 0.0, 1.0)
.gray_out()
.cook(bnw2),
n("bnw_spots_3", "BnW Spots 3")
.desc("Fine black and white speckles.")
.float("scale", "Scale", 16.0, 1.0, 64.0)
.float("roughness", "Roughness", 0.6, 0.0, 1.0)
.gray_out()
.cook(bnw3),
n("cells_1", "Cells 1")
.desc("Distance to the nearest cell point (soft bumps).")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(cells1),
n("cells_2", "Cells 2")
.desc("Cell borders (second minus first distance).")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(cells2),
n("cells_3", "Cells 3")
.desc("Flat cells, each a random gray.")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(cells3),
n("cells_4", "Cells 4")
.desc("Chebyshev cells: square bumps.")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(cells4),
n("clouds_1", "Clouds 1")
.desc("Soft fractal clouds.")
.float("scale", "Scale", 4.0, 1.0, 32.0)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(clouds1),
n("clouds_2", "Clouds 2")
.desc("Warped, wispy clouds.")
.float("scale", "Scale", 3.0, 1.0, 32.0)
.float("roughness", "Roughness", 0.55, 0.0, 1.0)
.gray_out()
.cook(clouds2),
n("clouds_3", "Clouds 3")
.desc("Detailed, contrasted clouds.")
.float("scale", "Scale", 6.0, 1.0, 32.0)
.float("roughness", "Roughness", 0.6, 0.0, 1.0)
.gray_out()
.cook(clouds3),
n("creased", "Creased")
.desc("Ridged fractal noise: folds and creases.")
.float("scale", "Scale", 3.0, 1.0, 32.0)
.float("roughness", "Roughness", 0.55, 0.0, 1.0)
.float("warp", "Warp intensity", 0.3, 0.0, 1.0)
.gray_out()
.cook(creased),
n("crystal_1", "Crystal 1").desc("Faceted crystal plates.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal1),
n("crystal_2", "Crystal 2").desc("Sharp crystal shards.").float("scale", "Scale", 6.0, 1.0, 64.0).gray_out().cook(crystal2),
n("dirt", "Dirt").desc("Clumps of dirt.").float("scale", "Scale", 6.0, 1.0, 64.0).float("density", "Density", 0.5, 0.0, 1.0).gray_out().cook(dirt),
n("dust", "Dust").desc("Sparse specks of dust.").float("density", "Density", 0.02, 0.0, 0.2).float("size", "Size", 1.0, 0.0, 8.0).gray_out().cook(dust),
n("fractal_sum_base", "Fractal Sum Base")
.desc("Sum of Perlin noise octaves.")
.float("scale", "Min level", 2.0, 1.0, 64.0)
.int("octaves", "Octaves", 8, 1, 12)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(fractal_sum),
n("fur", "Fur")
.desc("Short directional fibers.")
.float("scale", "Density", 1.0, 0.1, 4.0)
.angle("angle", "Direction", 0.25)
.float("length", "Length", 8.0, 0.0, 64.0)
.gray_out()
.cook(fur),
n("gaussian_noise", "Gaussian Noise")
.desc("Smoothly interpolated value noise.")
.float("scale", "Scale", 16.0, 1.0, 256.0)
.gray_out()
.cook(gaussian_noise),
n("grunge_map_1", "Grunge Map 1")
.desc("Stains and blotches.")
.float("scale", "Scale", 3.0, 1.0, 32.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
.cook(grunge1),
n("grunge_map_2", "Grunge Map 2")
.desc("Speckled grime.")
.float("scale", "Scale", 5.0, 1.0, 32.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
.cook(grunge2),
n("grunge_map_3", "Grunge Map 3")
.desc("Streaky leaks.")
.float("scale", "Scale", 4.0, 1.0, 32.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
.cook(grunge3),
n("liquid", "Liquid")
.desc("Domain-warped flowing noise.")
.float("scale", "Scale", 3.0, 1.0, 32.0)
.float("warp", "Warp", 0.6, 0.0, 2.0)
.gray_out()
.cook(liquid),
n("moisture_noise", "Moisture Noise")
.desc("Damp patches with soft edges.")
.float("scale", "Scale", 4.0, 1.0, 32.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
.cook(moisture),
n("perlin_noise", "Perlin Noise")
.desc("Single-octave gradient noise.")
.float("scale", "Scale", 8.0, 1.0, 256.0)
.float("disorder", "Disorder", 0.0, 0.0, 1.0)
.gray_out()
.cook(perlin_noise),
n("plasma", "Plasma").desc("Interfering sine waves through noise.").float("scale", "Scale", 4.0, 1.0, 32.0).gray_out().cook(plasma),
n("turbulence", "Turbulence")
.desc("Billowing absolute-value fractal noise.")
.float("scale", "Scale", 4.0, 1.0, 32.0)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(turbulence),
n("voronoi", "Voronoi")
.desc("Cellular noise with a choice of distance and output.")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.choice("metric", "Distance", &["Euclidean", "Manhattan", "Chebyshev"], 0)
.choice("style", "Output", &["F1", "F2", "F2 - F1", "Cell id"], 2)
.gray_out()
.cook(voronoi),
n("white_noise", "White Noise").desc("Independent random value per pixel.").choice("mode", "Output", &["Grayscale", "Color"], 0).cook(white_noise),
]
}
fn anisotropic(ctx: &Ctx) -> CookResult {
let (sx, sy) = (scale(ctx), ctx.f("scale_y").max(1.0).round());
let smooth = ctx.f("smoothness");
let s = ctx.seed;
let base = ctx.gen_gray(|u, v| {
let a = value_xy(u * sx, v * sy, sx as i32, sy as i32, s);
let b = value_xy(u * sx * 2.0, v * sy, (sx * 2.0) as i32, sy as i32, s ^ 77) * 0.5;
(a * 0.75 + b * 0.25 * (1.0 - smooth) + 0.125 * smooth).clamp(0.0, 1.0)
});
Ok(vec![if smooth > 0.0 { ops::gaussian(&base, smooth * 2.0, ctx.tile) } else { base }])
}
fn contrast(v: f32, c: f32) -> f32 {
((v - 0.5) * (1.0 + c * 8.0) + 0.5).clamp(0.0, 1.0)
}
fn bnw1(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 6, 0.3 + r * 0.4, s), 0.6))])
}
fn bnw2(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 3, 0.3 + r * 0.4, s), 1.2))])
}
fn bnw3(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 7, 0.4 + r * 0.4, s), 0.9))])
}
fn cell_cook(ctx: &Ctx, metric: u32, f: impl Fn(noise::Cell) -> f32 + Sync) -> CookResult {
let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| f(cellular(u * sc, v * sc, sc as i32, dis, metric, s)).clamp(0.0, 1.0))])
}
fn cells1(ctx: &Ctx) -> CookResult {
cell_cook(ctx, 0, |c| 1.0 - c.f1 * 1.2)
}
fn cells2(ctx: &Ctx) -> CookResult {
cell_cook(ctx, 0, |c| ((c.f2 - c.f1) * 2.5).min(1.0))
}
fn cells3(ctx: &Ctx) -> CookResult {
cell_cook(ctx, 0, |c| c.id)
}
fn cells4(ctx: &Ctx) -> CookResult {
cell_cook(ctx, 2, |c| 1.0 - c.f1 * 1.6)
}
fn crystal1(ctx: &Ctx) -> CookResult {
let (sc, s) = (scale(ctx), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let c = cellular(u * sc, v * sc, sc as i32, 1.0, 0, s);
(c.id * 0.6 + (c.f2 - c.f1).min(0.4) + 0.1).clamp(0.0, 1.0)
})])
}
fn crystal2(ctx: &Ctx) -> CookResult {
let (sc, s) = (scale(ctx), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let c = cellular(u * sc, v * sc, sc as i32, 1.0, 1, s);
(c.id * 0.7 + (1.0 - c.f1).max(0.0) * 0.3).clamp(0.0, 1.0)
})])
}
fn dirt(ctx: &Ctx) -> CookResult {
let (sc, d, s) = (scale(ctx), ctx.f("density"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let base = fbm(u, v, sc, 6, 0.55, s);
let spots = 1.0 - cellular(u * sc * 4.0, v * sc * 4.0, (sc * 4.0) as i32, 1.0, 0, s ^ 9).f1;
let t = 1.0 - d;
(((base * 0.7 + spots * 0.3) - t * 0.6) * 3.0).clamp(0.0, 1.0)
})])
}
fn dust(ctx: &Ctx) -> CookResult {
let (d, s) = (ctx.f("density"), ctx.seed);
let img = Image::gray(ctx.w, ctx.h, |x, y| if noise::rand2(x as i32, y as i32, s) < d { 0.5 + 0.5 * noise::rand2(y as i32, x as i32, s ^ 3) } else { 0.0 });
let sigma = ctx.f("size") * ctx.w as f32 / 1024.0;
let b = ops::gaussian(&img, sigma, ctx.tile);
let gain = 1.0 + sigma * sigma * 4.0;
Ok(vec![b.map(Kind::Gray, |p| [(p[0] * gain).min(1.0), 0.0, 0.0, 0.0])])
}
fn fractal_sum(ctx: &Ctx) -> CookResult {
let (sc, o, r, s) = (scale(ctx), ctx.i("octaves").clamp(1, 12) as u32, ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, o, r, s))])
}
fn fur(ctx: &Ctx) -> CookResult {
let s = ctx.seed;
let density = ctx.f("scale").clamp(0.1, 4.0);
let img = Image::gray(ctx.w, ctx.h, |x, y| {
let r = rand2(x as i32, y as i32, s);
if r < 0.15 * density { rand2(y as i32, x as i32, s ^ 5) } else { 0.0 }
});
let len = ctx.f("length") * ctx.w as f32 / 256.0;
let (dx, dy) = ((ctx.f("angle") * std::f32::consts::TAU).cos(), -(ctx.f("angle") * std::f32::consts::TAU).sin());
let n = (len.ceil() as i32).clamp(1, 256);
let (iw, ih) = (1.0 / ctx.w as f32, 1.0 / ctx.h as f32);
Ok(vec![Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| {
let mut acc = 0.0;
for i in 0..=n {
let t = i as f32 / n as f32 * len;
acc += img.sample_nearest(u - dx * t * iw, v - dy * t * ih, ctx.tile)[0] * (1.0 - i as f32 / (n + 1) as f32);
}
[(acc * 2.5 / (n as f32).sqrt()).min(1.0), 0.0, 0.0, 0.0]
})])
}
fn gaussian_noise(ctx: &Ctx) -> CookResult {
let (sc, s) = (scale(ctx), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let a = value(u * sc, v * sc, sc as i32, s);
let b = value(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 1);
(a * 0.7 + b * 0.3).clamp(0.0, 1.0)
})])
}
fn grunge(ctx: &Ctx, f: impl Fn(f32, f32, f32, u32) -> f32 + Sync) -> CookResult {
let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| contrast(f(u, v, sc, s), c))])
}
fn grunge1(ctx: &Ctx) -> CookResult {
grunge(ctx, |u, v, sc, s| {
let a = fbm(u, v, sc, 7, 0.6, s);
let b = 1.0 - cellular(u * sc * 3.0, v * sc * 3.0, (sc * 3.0) as i32, 1.0, 0, s ^ 4).f1;
a * 0.75 + b * 0.25
})
}
fn grunge2(ctx: &Ctx) -> CookResult {
grunge(ctx, |u, v, sc, s| {
let a = fbm(u, v, sc, 8, 0.65, s);
let speck = if rand2((u * 512.0) as i32, (v * 512.0) as i32, s ^ 8) > 0.9 { 0.25 } else { 0.0 };
(a - speck).clamp(0.0, 1.0)
})
}
fn grunge3(ctx: &Ctx) -> CookResult {
grunge(ctx, |u, v, sc, s| {
// Whole cell counts per axis (and the matching periods) so both edges tile.
let cy = (sc * 0.5).round().max(1.0);
let streak = value_xy(u * sc * 8.0, v * cy, (sc * 8.0) as i32, cy as i32, s);
let a = fbm(u, v, sc, 6, 0.55, s ^ 2);
streak * 0.5 + a * 0.5
})
}
fn liquid(ctx: &Ctx) -> CookResult {
let (sc, w, s) = (scale(ctx), ctx.f("warp"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let qx = fbm(u, v, sc, 4, 0.5, s) - 0.5;
let qy = fbm(u + 0.37, v + 0.71, sc, 4, 0.5, s ^ 3) - 0.5;
fbm(u + qx * w, v + qy * w, sc, 5, 0.5, s ^ 7)
})])
}
fn moisture(ctx: &Ctx) -> CookResult {
let (sc, c, s) = (scale(ctx), ctx.f("contrast"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let a = fbm(u, v, sc, 6, 0.5, s);
let b = (perlin(u * sc * 2.0, v * sc * 2.0, (sc * 2.0) as i32, s ^ 6)).abs();
contrast(a * 0.8 + (1.0 - b) * 0.2, c)
})])
}
fn perlin_noise(ctx: &Ctx) -> CookResult {
let (sc, d, s) = (scale(ctx), ctx.f("disorder"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let (wu, wv) = if d > 0.0 { ((perlin(u * 3.0, v * 3.0, 3, s ^ 1)) * d * 0.1, (perlin(u * 3.0, v * 3.0, 3, s ^ 2)) * d * 0.1) } else { (0.0, 0.0) };
(perlin((u + wu) * sc, (v + wv) * sc, sc as i32, s) * 0.5 + 0.5).clamp(0.0, 1.0)
})])
}
fn plasma(ctx: &Ctx) -> CookResult {
let (sc, s) = (scale(ctx), ctx.seed);
let tau = std::f32::consts::TAU;
Ok(vec![ctx.gen_gray(|u, v| {
let n = fbm(u, v, sc, 3, 0.5, s) * 2.0;
let a = (u * tau * sc + n * 3.0).sin() + (v * tau * sc + n * 2.0).sin() + ((u + v) * tau * sc.round() + n).sin();
(a / 6.0 + 0.5).clamp(0.0, 1.0)
})])
}
fn turbulence(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
// A negative roughness makes `ridged` negative; clamp so the sqrt can't be NaN.
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ridged(u, v, sc, 6, r, s).max(0.0).sqrt())])
}
fn creased(ctx: &Ctx) -> CookResult {
let (sc, r, w, s) = (scale(ctx), ctx.f("roughness"), ctx.f("warp"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let q = fbm(u, v, sc, 3, 0.5, s ^ 11) - 0.5;
ridged(u + q * w * 0.3, v - q * w * 0.3, sc, 6, r, s)
})])
}
fn clouds1(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| fbm(u, v, sc, 8, r, s))])
}
fn clouds2(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let q = fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5;
fbm(u + q * 0.35, v + q * 0.35, sc, 8, r, s)
})])
}
fn clouds3(ctx: &Ctx) -> CookResult {
let (sc, r, s) = (scale(ctx), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| contrast(fbm(u, v, sc, 9, r, s), 0.35))])
}
fn voronoi(ctx: &Ctx) -> CookResult {
let (sc, dis, s) = (scale(ctx), ctx.f("disorder"), ctx.seed);
let (metric, style) = (ctx.i("metric").clamp(0, 2) as u32, ctx.i("style"));
Ok(vec![ctx.gen_gray(|u, v| {
let c = cellular(u * sc, v * sc, sc as i32, dis, metric, s);
match style {
0 => c.f1.min(1.0),
1 => (c.f2 * 0.8).min(1.0),
3 => c.id,
_ => ((c.f2 - c.f1) * 2.0).min(1.0),
}
})])
}
fn white_noise(ctx: &Ctx) -> CookResult {
let s = ctx.seed;
Ok(vec![if ctx.i("mode") == 1 {
Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
[rand2(x as i32, y as i32, s), rand2(x as i32, y as i32, s ^ 1), rand2(x as i32, y as i32, s ^ 2), 1.0]
})
} else {
Image::gray(ctx.w, ctx.h, |x, y| rand2(x as i32, y as i32, s))
}])
}
#[cfg(test)]
#[path = "generators.test.rs"]
mod tests;
-48
View File
@@ -1,48 +0,0 @@
//! Tiling tests for generators whose cell counts differ per axis.
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::Image;
use crate::{Ctx, find, resolve_params};
fn cook(id: &str, scale: f32, extra: &[(&str, Value)]) -> Image {
let def = find(id).unwrap();
let mut over: BTreeMap<String, Value> = extra.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
over.insert("scale".into(), Value::Float(scale));
let params = resolve_params(def, &over);
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let inputs = vec![None; def.inputs.len()];
let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
(def.cook)(&ctx).unwrap().remove(0)
}
/// Wrap jump along both axes versus the typical neighbour difference.
fn seams(img: &Image) -> (f32, f32, f32, f32) {
let (mut hs, mut hi, mut vs, mut vi) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
for k in 0..64 {
hs += (img.get(63, k, false)[0] - img.get(0, k, false)[0]).abs();
hi += (img.get(31, k, false)[0] - img.get(32, k, false)[0]).abs();
vs += (img.get(k, 63, false)[0] - img.get(k, 0, false)[0]).abs();
vi += (img.get(k, 31, false)[0] - img.get(k, 32, false)[0]).abs();
}
(hs, hi, vs, vi)
}
#[test]
fn grunge_map_3_tiles_at_odd_scales() {
for scale in [3.0, 5.0, 7.0] {
let (hs, hi, vs, vi) = seams(&cook("grunge_map_3", scale, &[]));
assert!(hs <= hi * 3.0 + 0.5, "scale {scale}: horizontal seam {hs} vs {hi}");
assert!(vs <= vi * 3.0 + 0.5, "scale {scale}: vertical seam {vs} vs {vi}");
}
}
#[test]
fn anisotropic_noise_tiles_with_different_axis_scales() {
let (hs, hi, vs, vi) = seams(&cook("anisotropic_noise", 8.0, &[("scale_y", Value::Float(3.0))]));
assert!(hs <= hi * 3.0 + 0.5, "horizontal seam {hs} vs {hi}");
assert!(vs <= vi * 3.0 + 0.5, "vertical seam {vs} vs {vi}");
}
-90
View File
@@ -1,90 +0,0 @@
//! Material filters: nodes that make or process whole PBR materials (several outputs).
use materialcraft_image::{Image, Kind, linear_to_srgb, srgb_to_linear};
use crate::atomic::height_to_normal;
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::ops;
const PBR: &str = "Material filters/PBR utilities";
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("pbr_base_material", "PBR Base Material", PBR)
.desc("A uniform PBR material: base color, normal, roughness, metallic, height and ambient occlusion.")
.generator()
.color("base_color", "Base color", [0.5, 0.5, 0.5, 1.0])
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("metallic", "Metallic", 0.0, 0.0, 1.0)
.float("height", "Height", 0.5, 0.0, 1.0)
.float("ao", "Ambient occlusion", 1.0, 0.0, 1.0)
.output("base_color", "Base color", PortKind::Color)
.output("normal", "Normal", PortKind::Color)
.output("roughness", "Roughness", PortKind::Gray)
.output("metallic", "Metallic", PortKind::Gray)
.output("height", "Height", PortKind::Gray)
.output("ambient_occlusion", "Ambient occlusion", PortKind::Gray)
.cook(pbr_base),
node("height_normal_ao", "Height to Normal and AO", PBR)
.desc("A normal map and an ambient occlusion map from one height map.")
.gray_in("height", "Height")
.float("normal_intensity", "Normal intensity", 1.0, 0.0, 10.0)
.float("ao_spread", "AO spreading", 0.15, 0.0, 1.0)
.float("ao_depth", "AO depth", 0.5, 0.0, 1.0)
.output("normal", "Normal", PortKind::Color)
.output("ambient_occlusion", "Ambient occlusion", PortKind::Gray)
.cook(height_normal_ao),
node("albedo_safe", "Albedo Safe Color", PBR)
.desc("Keeps base colors inside the physically plausible range (sRGB 30-240).")
.color_in("input", "Base color")
.color_out()
.cook(albedo_safe),
node("metallic_mask", "Metallic From Mask", PBR)
.desc("Turns a mask into a clean metallic map (fully metallic or not).")
.gray_in("input", "Mask")
.float("threshold", "Threshold", 0.5, 0.0, 1.0)
.gray_out()
.cook(metallic_mask),
]
}
fn pbr_base(ctx: &Ctx) -> CookResult {
let (w, h) = (ctx.w, ctx.h);
let g = |v: f32| Image::filled(w, h, Kind::Gray, [v; 4]);
Ok(vec![
Image::filled(w, h, Kind::Color, ctx.v4("base_color")),
Image::filled(w, h, Kind::Color, [0.5, 0.5, 1.0, 1.0]),
g(ctx.f("roughness")),
g(ctx.f("metallic")),
g(ctx.f("height")),
g(ctx.f("ao")),
])
}
fn height_normal_ao(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.5);
let n = height_to_normal(&h, ctx.f("normal_intensity") * ctx.w as f32 / 32.0, false, ctx.tile, false);
let spread = ctx.f("ao_spread").max(0.001) * ctx.w as f32 * 0.25;
let wide = ops::gaussian(&h, spread, ctx.tile);
let depth = ctx.f("ao_depth");
let ao = Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| {
let i = (y * ctx.w + x) as usize;
[(1.0 - (wide.data[i] - h.data[i]).max(0.0) * depth * 6.0).clamp(0.0, 1.0), 0.0, 0.0, 0.0]
});
Ok(vec![n, ao])
}
fn albedo_safe(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
let (lo, hi) = (30.0 / 255.0, 240.0 / 255.0);
Ok(vec![img.map(Kind::Color, |p| {
let f = |v: f32| srgb_to_linear(linear_to_srgb(v).clamp(lo, hi));
[f(p[0]), f(p[1]), f(p[2]), p[3]]
})])
}
fn metallic_mask(ctx: &Ctx) -> CookResult {
let t = ctx.f("threshold");
let img = ctx.gray_or(0, 0.0);
Ok(vec![img.map(Kind::Gray, |p| [if p[0] >= t { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0])])
}
-274
View File
@@ -1,274 +0,0 @@
//! More material filters: blending whole PBR materials (by mask or by height), weathering masks
//! (edge wear, dirt, dust) and base color utilities.
use materialcraft_image::{Image, Kind};
use crate::catalog::{B, CookResult, Ctx, NodeDef, PortKind, node};
use crate::filters_more::{pack, unpack};
use crate::noise::fbm;
use crate::noises_more::smoothstep;
use crate::ops;
const MAT_BLEND: &str = "Material filters/Blending";
const WEATHER: &str = "Material filters/Weathering";
const PBR: &str = "Material filters/PBR utilities";
/// The channels of a blended material: kind and default (unconnected) value.
const KINDS: [(PortKind, [f32; 4]); 5] = [
(PortKind::Color, [0.5, 0.5, 0.5, 1.0]),
(PortKind::Color, [0.5, 0.5, 1.0, 1.0]),
(PortKind::Gray, [0.5; 4]),
(PortKind::Gray, [0.0; 4]),
(PortKind::Gray, [0.5; 4]),
];
const IN_1: [(&str, &str); 5] =
[("base_color_1", "Base color 1"), ("normal_1", "Normal 1"), ("roughness_1", "Roughness 1"), ("metallic_1", "Metallic 1"), ("height_1", "Height 1")];
const IN_2: [(&str, &str); 5] =
[("base_color_2", "Base color 2"), ("normal_2", "Normal 2"), ("roughness_2", "Roughness 2"), ("metallic_2", "Metallic 2"), ("height_2", "Height 2")];
const OUT: [(&str, &str); 5] = [("base_color", "Base color"), ("normal", "Normal"), ("roughness", "Roughness"), ("metallic", "Metallic"), ("height", "Height")];
/// Inputs for two materials, then the blended material's outputs.
fn material_ports(mut b: B) -> B {
for set in [IN_1, IN_2] {
for ((id, label), (kind, _)) in set.into_iter().zip(KINDS) {
b = b.input(id, label, kind);
}
}
for ((id, label), (kind, _)) in OUT.into_iter().zip(KINDS) {
b = b.output(id, label, kind);
}
b
}
fn kind_of(k: PortKind) -> Kind {
if k == PortKind::Color { Kind::Color } else { Kind::Gray }
}
/// Material `slot` (0 or 1), channel `c`, at the output size.
fn channel(ctx: &Ctx, slot: usize, c: usize) -> Image {
let (pk, def) = KINDS[c];
let kind = kind_of(pk);
ctx.any_or(slot * 5 + c, kind, def).to_kind(kind)
}
/// Blend the two input materials by `t` per pixel (0 = material 1); normals are renormalized.
fn mix_materials(ctx: &Ctx, t: &[f32]) -> Vec<Image> {
(0..5)
.map(|c| {
let (a, b) = (channel(ctx, 0, c), channel(ctx, 1, c));
Image::generate(ctx.w, ctx.h, a.kind, |x, y| {
let t = t.get((y * ctx.w + x) as usize).copied().unwrap_or(0.0);
let (p, q) = (a.get(x as i64, y as i64, false), b.get(x as i64, y as i64, false));
let mut o: [f32; 4] = std::array::from_fn(|k| p[k] + (q[k] - p[k]) * t);
if c == 1 {
let (n1, n2) = (unpack(p), unpack(q));
o = pack(std::array::from_fn(|k| n1[k] + (n2[k] - n1[k]) * t), o[3]);
}
o
})
})
.collect()
}
/// Weathering parameters shared by the mask nodes.
fn weather_params(b: B) -> B {
b.float("amount", "Amount", 0.5, 0.0, 1.0)
.float("noise_scale", "Noise scale", 8.0, 1.0, 64.0)
.float("noise_amount", "Noise amount", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.6, 0.0, 1.0)
}
/// A weathering mask: `base(i)` (0..1, where the effect belongs) broken up by fractal noise and
/// thresholded by the amount.
fn weather(ctx: &Ctx, base: impl Fn(usize) -> f32 + Sync) -> Image {
let (amt, ns, na, s) = (ctx.f("amount"), ctx.f("noise_scale").max(1.0).round(), ctx.f("noise_amount"), ctx.seed);
let soft = (1.0 - ctx.f("contrast")) * 0.5 + 0.01;
Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| {
let i = ((v * ctx.h as f32) as usize).min((ctx.h as usize).saturating_sub(1)) * ctx.w as usize
+ ((u * ctx.w as f32) as usize).min((ctx.w as usize).saturating_sub(1));
let val = base(i) - 2.0 * na * (1.0 - fbm(u, v, ns, 6, 0.6, s));
[smoothstep(1.0 - amt - soft, 1.0 - amt + soft, val), 0.0, 0.0, 0.0]
})
}
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
material_ports(node("material_blend", "Material Blend", MAT_BLEND))
.desc("Blends two whole PBR materials by a mask (white = material 2).")
.gray_in("mask", "Mask")
.float("opacity", "Opacity", 1.0, 0.0, 1.0)
.cook(material_blend),
material_ports(node("material_height_blend", "Material Height Blend", MAT_BLEND))
.desc("Blends two whole PBR materials by their heights: the higher one shows, with a soft transition.")
.float("height_offset", "Height offset", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.9, 0.0, 1.0)
.output("mask", "Mask", PortKind::Gray)
.cook(material_height_blend),
weather_params(
node("edge_wear", "Edge Wear", WEATHER)
.desc("A mask of worn, exposed edges from the convex areas of a height map (or a curvature map), broken up by noise.")
.gray_in("height", "Height")
.gray_in("curvature", "Curvature (optional)")
.float("width", "Edge width", 4.0, 0.25, 64.0),
)
.gray_out()
.cook(edge_wear),
weather_params(
node("dirt_mask", "Dirt Mask", WEATHER)
.desc("A mask of dirt gathering in cavities of a height map (and dark ambient occlusion), broken up by noise.")
.gray_in("height", "Height")
.gray_in("ao", "Ambient occlusion (optional)")
.float("spread", "Spread", 16.0, 0.5, 128.0),
)
.gray_out()
.cook(dirt_mask),
weather_params(
node("dust_mask", "Dust Mask", WEATHER)
.desc("A mask of dust settling on surfaces facing a direction (from a normal map) and on flat areas.")
.color_in("normal", "Normal")
.angle("direction", "Up direction", 0.25)
.float("flat", "On flat areas", 0.3, 0.0, 1.0),
)
.gray_out()
.cook(dust_mask),
node("material_color_adjust", "Material Color Adjust", PBR)
.desc("Hue, saturation and value of a base color, optionally through a mask.")
.color_in("input", "Base color")
.gray_in("mask", "Mask")
.float("hue", "Hue", 0.0, -0.5, 0.5)
.float("saturation", "Saturation", 0.0, -1.0, 1.0)
.float("value", "Value", 0.0, -1.0, 1.0)
.color_out()
.cook(material_color_adjust),
node("metal_base_color", "Metal Base Color", PBR)
.desc("The measured base color (linear reflectance) of a common metal, with metallic = 1.")
.generator()
.choice("metal", "Metal", &["Iron", "Silver", "Aluminum", "Gold", "Copper", "Chromium", "Nickel", "Titanium", "Cobalt", "Platinum"], 0)
.output("base_color", "Base color", PortKind::Color)
.output("metallic", "Metallic", PortKind::Gray)
.cook(metal_base_color),
]
}
fn material_blend(ctx: &Ctx) -> CookResult {
let op = ctx.f("opacity");
let m = ctx.gray_or(10, 1.0);
let t: Vec<f32> = m.data.iter().map(|v| (v * op).clamp(0.0, 1.0)).collect();
Ok(mix_materials(ctx, &t))
}
fn material_height_blend(ctx: &Ctx) -> CookResult {
let (h1, h2) = (channel(ctx, 0, 4), channel(ctx, 1, 4));
let (off, c) = (ctx.f("height_offset") - 0.5, ctx.f("contrast").clamp(0.0, 0.999));
let soft = (1.0 - c) * 0.5 + 1e-4;
let t: Vec<f32> = h1.data.iter().zip(h2.data.iter()).map(|(a, b)| ((b + off - a) / soft * 0.5 + 0.5).clamp(0.0, 1.0)).collect();
let mut out = mix_materials(ctx, &t);
out.push(ops::gray_from(ctx.w, ctx.h, t));
Ok(out)
}
fn edge_wear(ctx: &Ctx) -> CookResult {
let edge: Vec<f32> = match ctx.sized(1) {
Some(c) => c.to_gray().data.iter().map(|v| ((v - 0.5) * 2.0).clamp(0.0, 1.0)).collect(),
None => {
let h = ctx.gray_or(0, 0.0);
let wide = ops::gaussian(&h, ctx.f("width") * ctx.w as f32 / 256.0, ctx.tile);
h.data.iter().zip(wide.data.iter()).map(|(a, b)| ((a - b) * 4.0).clamp(0.0, 1.0)).collect()
}
};
Ok(vec![weather(ctx, |i| edge.get(i).copied().unwrap_or(0.0))])
}
fn dirt_mask(ctx: &Ctx) -> CookResult {
let h = ctx.gray_or(0, 0.0);
let wide = ops::gaussian(&h, ctx.f("spread") * ctx.w as f32 / 256.0, ctx.tile);
let ao = ctx.sized(1).map(|a| a.to_gray());
let cav: Vec<f32> = (0..h.data.len())
.map(|i| {
let c = ((wide.data[i] - h.data[i]) * 4.0).clamp(0.0, 1.0);
ao.as_ref().and_then(|a| a.data.get(i)).map_or(c, |a| c.max(1.0 - a))
})
.collect();
Ok(vec![weather(ctx, |i| cav.get(i).copied().unwrap_or(0.0))])
}
fn dust_mask(ctx: &Ctx) -> CookResult {
let n = ctx.any_or(0, Kind::Color, [0.5, 0.5, 1.0, 1.0]).to_color();
let (s, c) = (ctx.f("direction") * std::f32::consts::TAU).sin_cos();
let flat = ctx.f("flat");
let base: Vec<f32> = n
.data
.chunks(4)
.map(|p| {
let v = unpack([p[0], p[1], p[2], 1.0]);
((v[0] * c + v[1] * s) * 3.0 + flat * ((v[2] - 0.8) * 5.0).max(0.0)).clamp(0.0, 1.0)
})
.collect();
Ok(vec![weather(ctx, |i| base.get(i).copied().unwrap_or(0.0))])
}
fn material_color_adjust(ctx: &Ctx) -> CookResult {
let img = ctx.any_or(0, Kind::Color, [0.5, 0.5, 0.5, 1.0]).to_color();
let m = ctx.gray_or(1, 1.0);
let (dh, ds, dv) = (ctx.f("hue"), ctx.f("saturation"), ctx.f("value"));
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Color, |x, y| {
let p = img.get(x as i64, y as i64, false);
let t = m.get_gray(x as i64, y as i64, false);
let hsl = ops::rgb_to_hsl(p);
let q = ops::hsl_to_rgb(hsl[0] + dh, (hsl[1] * (1.0 + ds)).clamp(0.0, 1.0), (hsl[2] * (1.0 + dv)).max(0.0));
[p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t, p[3]]
})])
}
/// Linear base colors (normal-incidence reflectance) of metals, from published measurements.
const METALS: [[f32; 3]; 10] = [
[0.560, 0.570, 0.580],
[0.972, 0.960, 0.915],
[0.913, 0.922, 0.924],
[1.000, 0.766, 0.336],
[0.955, 0.638, 0.538],
[0.550, 0.556, 0.554],
[0.660, 0.609, 0.526],
[0.542, 0.497, 0.449],
[0.662, 0.655, 0.634],
[0.672, 0.637, 0.585],
];
fn metal_base_color(ctx: &Ctx) -> CookResult {
let c = METALS.get(ctx.i("metal").max(0) as usize).copied().unwrap_or(METALS[0]);
Ok(vec![Image::filled(ctx.w, ctx.h, Kind::Color, [c[0], c[1], c[2], 1.0]), Image::filled(ctx.w, ctx.h, Kind::Gray, [1.0; 4])])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use materialcraft_image::{Image, Kind};
use crate::{Ctx, find, resolve_params};
#[test]
fn material_blend_picks_material_2_under_white_mask() {
let def = find("material_blend").unwrap();
let params = resolve_params(def, &BTreeMap::new());
let red = Image::filled(8, 8, Kind::Color, [1.0, 0.0, 0.0, 1.0]);
let tilted = Image::filled(8, 8, Kind::Color, [0.8, 0.5, 0.9, 1.0]);
let mut inputs = vec![None; def.inputs.len()];
inputs[5] = Some(red);
inputs[6] = Some(tilted);
inputs[7] = Some(Image::filled(8, 8, Kind::Gray, [0.1; 4]));
inputs[10] = Some(Image::gray(8, 8, |x, _| if x < 4 { 0.0 } else { 1.0 }));
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w: 8, h: 8, seed: 0, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
let out = (def.cook)(&ctx).unwrap();
assert_eq!(out.len(), 5);
assert_eq!(out[0].get(6, 2, false), [1.0, 0.0, 0.0, 1.0], "white mask: material 2's base color");
assert_eq!(out[0].get(1, 2, false), [0.5, 0.5, 0.5, 1.0], "black mask: material 1 (default gray)");
assert!((out[2].get(6, 2, false)[0] - 0.1).abs() < 1e-6);
let n = out[1].get(6, 2, false);
let len = ((n[0] * 2.0 - 1.0).powi(2) + (n[1] * 2.0 - 1.0).powi(2) + (n[2] * 2.0 - 1.0).powi(2)).sqrt();
assert!((len - 1.0).abs() < 1e-4, "blended normals are unit length");
assert!(n[0] > 0.7, "material 2's normal: {n:?}");
}
}
-190
View File
@@ -1,190 +0,0 @@
//! Tileable noise primitives: integer hashing, value and gradient (Perlin) noise on a periodic
//! lattice, fractal sums and cellular (Worley) noise. Every function takes normalized coordinates
//! (0..1 across the image) and a period in cells, so whole-number scales tile seamlessly.
/// A 32-bit integer hash (lowbias32 by Chris Wellons, public domain).
#[inline]
pub fn hash(mut x: u32) -> u32 {
x ^= x >> 16;
x = x.wrapping_mul(0x7feb_352d);
x ^= x >> 15;
x = x.wrapping_mul(0x846c_a68b);
x ^= x >> 16;
x
}
#[inline]
pub fn hash3(x: i32, y: i32, seed: u32) -> u32 {
hash((x as u32).wrapping_mul(0x8da6_b343) ^ hash((y as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f)))
}
/// Uniform 0..1 from a lattice point.
#[inline]
pub fn rand2(x: i32, y: i32, seed: u32) -> f32 {
(hash3(x, y, seed) >> 8) as f32 / (1u32 << 24) as f32
}
/// Uniform 0..1 from an index.
#[inline]
pub fn rand1(i: u32, seed: u32) -> f32 {
(hash(i ^ hash(seed.wrapping_add(0x9e37_79b9))) >> 8) as f32 / (1u32 << 24) as f32
}
#[inline]
fn fade(t: f32) -> f32 {
t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
}
#[inline]
fn wrapi(i: i32, p: i32) -> i32 {
if p <= 0 { i } else { i.rem_euclid(p) }
}
/// Value noise in 0..1, lattice period `p` cells (coordinates already scaled to cells).
pub fn value(x: f32, y: f32, p: i32, seed: u32) -> f32 {
value_xy(x, y, p, p, seed)
}
/// Value noise in 0..1 with a separate lattice period per axis (`px`, `py` cells), so a noise
/// stretched differently along x and y still tiles.
pub fn value_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 {
let (x0, y0) = (x.floor(), y.floor());
let (tx, ty) = (fade(x - x0), fade(y - y0));
let (ix, iy) = (x0 as i32, y0 as i32);
let r = |i: i32, j: i32| rand2(wrapi(i, px), wrapi(j, py), seed);
let a = r(ix, iy) + (r(ix + 1, iy) - r(ix, iy)) * tx;
let b = r(ix, iy + 1) + (r(ix + 1, iy + 1) - r(ix, iy + 1)) * tx;
a + (b - a) * ty
}
/// Gradient (Perlin) noise in about -1..1, lattice period `p` cells.
pub fn perlin(x: f32, y: f32, p: i32, seed: u32) -> f32 {
let (x0, y0) = (x.floor(), y.floor());
let (fx, fy) = (x - x0, y - y0);
let (ix, iy) = (x0 as i32, y0 as i32);
let g = |i: i32, j: i32, dx: f32, dy: f32| {
let h = hash3(wrapi(i, p), wrapi(j, p), seed);
let a = (h >> 8) as f32 * (std::f32::consts::TAU / (1u32 << 24) as f32);
a.cos() * dx + a.sin() * dy
};
let (u, v) = (fade(fx), fade(fy));
let n00 = g(ix, iy, fx, fy);
let n10 = g(ix + 1, iy, fx - 1.0, fy);
let n01 = g(ix, iy + 1, fx, fy - 1.0);
let n11 = g(ix + 1, iy + 1, fx - 1.0, fy - 1.0);
let a = n00 + (n10 - n00) * u;
let b = n01 + (n11 - n01) * u;
(a + (b - a) * v) * std::f32::consts::SQRT_2
}
/// Fractal sum of Perlin noise in 0..1: `octaves` layers from `scale` cells, each `lacunarity`
/// (2) times finer and `gain` times weaker. Tileable when `scale` is whole.
pub fn fbm(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 {
let mut sum = 0.0;
let mut amp = 1.0;
let mut norm = 0.0;
let mut s = scale.max(1.0).round();
for o in 0..octaves.clamp(1, 12) {
sum += perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 1013)) * amp;
norm += amp;
amp *= gain;
s *= 2.0;
}
(sum / norm.max(1e-6)) * 0.5 + 0.5
}
/// Ridged (creased) fractal: `1 - |perlin|` layers, 0..1.
pub fn ridged(u: f32, v: f32, scale: f32, octaves: u32, gain: f32, seed: u32) -> f32 {
let mut sum = 0.0;
let mut amp = 1.0;
let mut norm = 0.0;
let mut s = scale.max(1.0).round();
for o in 0..octaves.clamp(1, 12) {
let n = 1.0 - perlin(u * s, v * s, s as i32, seed.wrapping_add(o * 7919)).abs();
sum += n * n * amp;
norm += amp;
amp *= gain;
s *= 2.0;
}
sum / norm.max(1e-6)
}
/// Result of a cellular lookup: the nearest and second-nearest feature distances (in cells),
/// the nearest feature's random id (0..1) and its position (cells).
#[derive(Clone, Copy, Debug)]
pub struct Cell {
pub f1: f32,
pub f2: f32,
pub id: f32,
pub center: [f32; 2],
}
/// Worley noise with one jittered feature point per cell (`jitter` 0..1), period `p` cells.
/// `metric`: 0 Euclidean, 1 Manhattan, 2 Chebyshev.
pub fn cellular(x: f32, y: f32, p: i32, jitter: f32, metric: u32, seed: u32) -> Cell {
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
let mut f1 = f32::MAX;
let mut f2 = f32::MAX;
let mut id = 0.0;
let mut center = [0.0, 0.0];
for j in -2..=2 {
for i in -2..=2 {
let (cx, cy) = (ix + i, iy + j);
let (wx, wy) = (wrapi(cx, p), wrapi(cy, p));
let px = cx as f32 + 0.5 + (rand2(wx, wy, seed) - 0.5) * jitter;
let py = cy as f32 + 0.5 + (rand2(wx, wy, seed ^ 0x5bd1_e995) - 0.5) * jitter;
let (dx, dy) = (px - x, py - y);
let d = match metric {
1 => dx.abs() + dy.abs(),
2 => dx.abs().max(dy.abs()),
_ => (dx * dx + dy * dy).sqrt(),
};
if d < f1 {
f2 = f1;
f1 = d;
id = rand2(wx, wy, seed ^ 0x2545_f491);
center = [px, py];
} else if d < f2 {
f2 = d;
}
}
}
Cell { f1, f2, id, center }
}
/// Gaussian-distributed sample (Box–Muller) from two uniforms.
pub fn gauss(u1: f32, u2: f32) -> f32 {
(-2.0 * u1.max(1e-7).ln()).sqrt() * (std::f32::consts::TAU * u2).cos()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn perlin_tiles_at_its_period() {
for k in 0..20 {
let y = k as f32 * 0.37;
let a = perlin(0.0, y, 4, 7);
let b = perlin(4.0, y, 4, 7);
assert!((a - b).abs() < 1e-5, "{a} {b}");
}
let a = fbm(0.0, 0.3, 4.0, 5, 0.5, 1);
let b = fbm(1.0, 0.3, 4.0, 5, 0.5, 1);
assert!((a - b).abs() < 1e-4);
}
#[test]
fn cellular_tiles_and_ranges() {
let a = cellular(0.1, 0.2, 5, 1.0, 0, 3).f1;
let b = cellular(5.1, 0.2, 5, 1.0, 0, 3).f1;
assert!((a - b).abs() < 1e-4);
assert!((0.0..1.5).contains(&a));
}
#[test]
fn rand_is_uniformish() {
let m: f32 = (0..10000).map(|i| rand1(i, 9)).sum::<f32>() / 10000.0;
assert!((m - 0.5).abs() < 0.02);
}
}
-281
View File
@@ -1,281 +0,0 @@
//! Texture generators › Noises: 3D noises that still tile. Perlin and Worley use a 3D lattice that
//! is periodic in x and y (whole-number scales) and free in z, so scrubbing `z` animates the
//! pattern. The simplex variant samples 4D simplex noise on a flat torus (u and v each mapped to a
//! circle), which tiles at any scale; `z` slides the torus through the 4D field.
use std::f32::consts::TAU;
use crate::catalog::{B, CookResult, Ctx, NodeDef, node};
use crate::generators::NOISES;
use crate::noise::{hash, hash3};
use crate::noises_more::fractal;
#[inline]
fn wrap(i: i32, p: i32) -> i32 {
if p <= 0 { i } else { i.rem_euclid(p) }
}
/// A hash of a 3D lattice point, periodic in x and y.
#[inline]
fn hash_xyz(i: i32, j: i32, k: i32, px: i32, py: i32, seed: u32) -> u32 {
hash(hash3(wrap(i, px), wrap(j, py), seed) ^ (k as u32).wrapping_mul(0x9e37_79b1))
}
#[inline]
fn fade(t: f32) -> f32 {
t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
}
/// 3D gradient (Perlin) noise in about -1..1, periods `px`, `py` cells in x and y.
pub fn perlin3(x: f32, y: f32, z: f32, px: i32, py: i32, seed: u32) -> f32 {
const G: [[f32; 3]; 12] = [
[1.0, 1.0, 0.0],
[-1.0, 1.0, 0.0],
[1.0, -1.0, 0.0],
[-1.0, -1.0, 0.0],
[1.0, 0.0, 1.0],
[-1.0, 0.0, 1.0],
[1.0, 0.0, -1.0],
[-1.0, 0.0, -1.0],
[0.0, 1.0, 1.0],
[0.0, -1.0, 1.0],
[0.0, 1.0, -1.0],
[0.0, -1.0, -1.0],
];
let (x0, y0, z0) = (x.floor(), y.floor(), z.floor());
let (fx, fy, fz) = (x - x0, y - y0, z - z0);
let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32);
let g = |a: i32, b: i32, c: i32| {
let gr = G[(hash_xyz(ix + a, iy + b, iz + c, px, py, seed) % 12) as usize];
gr[0] * (fx - a as f32) + gr[1] * (fy - b as f32) + gr[2] * (fz - c as f32)
};
let (u, v, w) = (fade(fx), fade(fy), fade(fz));
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
let x00 = lerp(g(0, 0, 0), g(1, 0, 0), u);
let x10 = lerp(g(0, 1, 0), g(1, 1, 0), u);
let x01 = lerp(g(0, 0, 1), g(1, 0, 1), u);
let x11 = lerp(g(0, 1, 1), g(1, 1, 1), u);
lerp(lerp(x00, x10, v), lerp(x01, x11, v), w)
}
/// Uniform 0..1 from a hash.
#[inline]
fn unit(h: u32) -> f32 {
(h >> 8) as f32 / (1u32 << 24) as f32
}
/// 3D Worley noise: nearest and second-nearest feature distances (cells), periodic in x and y.
pub fn worley3(x: f32, y: f32, z: f32, px: i32, py: i32, jitter: f32, seed: u32) -> (f32, f32) {
let (ix, iy, iz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32);
let (mut f1, mut f2) = (f32::MAX, f32::MAX);
for k in -1..=1 {
for j in -1..=1 {
for i in -1..=1 {
let (cx, cy, cz) = (ix + i, iy + j, iz + k);
let h = hash_xyz(cx, cy, cz, px, py, seed);
let o = |s: u32| 0.5 + (unit(hash(h ^ s)) - 0.5) * jitter;
let (dx, dy, dz) = (cx as f32 + o(1) - x, cy as f32 + o(2) - y, cz as f32 + o(3) - z);
let d = (dx * dx + dy * dy + dz * dz).sqrt();
if d < f1 {
f2 = f1;
f1 = d;
} else if d < f2 {
f2 = d;
}
}
}
}
(f1, f2)
}
/// 4D simplex noise in about -1..1 (after Gustavson's public description of the algorithm).
pub fn simplex4(p: [f32; 4], seed: u32) -> f32 {
const F4: f32 = 0.309_017; // (√5 − 1) / 4
const G4: f32 = 0.138_196_6; // (5 − √5) / 20
let s = (p[0] + p[1] + p[2] + p[3]) * F4;
let i: [f32; 4] = std::array::from_fn(|k| (p[k] + s).floor());
let t = (i[0] + i[1] + i[2] + i[3]) * G4;
let x0: [f32; 4] = std::array::from_fn(|k| p[k] - (i[k] - t));
// Rank the coordinates to find the simplex the point is in.
let mut rank = [0i32; 4];
for a in 0..4 {
for b in a + 1..4 {
if x0[a] > x0[b] {
rank[a] += 1;
} else {
rank[b] += 1;
}
}
}
let ii: [i32; 4] = std::array::from_fn(|k| i[k] as i32);
let mut n = 0.0;
for c in 0..5 {
let off: [i32; 4] = std::array::from_fn(|k| (rank[k] >= 4 - c) as i32);
let x: [f32; 4] = std::array::from_fn(|k| x0[k] - off[k] as f32 + c as f32 * G4);
let t = 0.6 - x.iter().map(|v| v * v).sum::<f32>();
if t <= 0.0 {
continue;
}
let h = hash(hash3(ii[0] + off[0], ii[1] + off[1], seed) ^ hash3(ii[2] + off[2], ii[3] + off[3], seed ^ 0x68e3_1da4));
// 32 gradients: one coordinate zero, the other three ±1.
let zero = (h >> 3) as usize & 3;
let mut dot = 0.0;
let mut bit = 0;
for k in 0..4 {
if k != zero {
dot += if h >> bit & 1 == 0 { x[k] } else { -x[k] };
bit += 1;
}
}
n += t * t * t * t * dot;
}
27.0 * n
}
/// Fractal 4D simplex on a torus at `(u, v)`: tiles in u and v for any scale.
fn simplex_torus(u: f32, v: f32, z: f32, scale: f32, octaves: i32, gain: f32, seed: u32) -> f32 {
let (su, cu) = (u * TAU).sin_cos();
let (sv, cv) = (v * TAU).sin_cos();
// Circumference `scale` cells per axis.
let r = scale / TAU;
fractal(octaves, gain, |m, o| {
let (r, z) = (r * m, z * m);
let p = [r * cu + z * 0.7, r * su + z * 0.3, r * cv - z * 0.5, r * sv + z * 0.4];
(simplex4(p, seed.wrapping_add(o * 977)) * 0.5 + 0.5).clamp(0.0, 1.0)
})
}
/// Shared noise parameters.
fn noise_params(b: B, scale: f32, octaves: i32) -> B {
b.generator()
.float("scale", "Scale", scale, 1.0, 64.0)
.int("octaves", "Octaves", octaves, 1, 10)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("z", "Z (slice)", 0.0, 0.0, 16.0)
.float("contrast", "Contrast", 0.5, 0.0, 1.0)
.gray_out()
}
pub(crate) fn defs() -> Vec<NodeDef> {
let n = |id, label| node(id, label, NOISES);
vec![
noise_params(n("perlin_noise_3d", "Perlin Noise 3D").desc("Fractal 3D gradient noise; Z scrubs through the volume. Tiles."), 4.0, 5)
.cook(perlin_noise_3d),
noise_params(
n("simplex_noise_3d", "Simplex Noise 3D").desc("Fractal simplex noise sampled on a 4D torus; Z moves through it. Tiles at any scale."),
4.0,
5,
)
.cook(simplex_noise_3d),
noise_params(
n("worley_noise_3d", "Worley Noise 3D")
.desc("Cellular noise from 3D feature points; Z scrubs through the cells. Tiles.")
.choice("distance", "Distance", &["F1", "F2", "F2 - F1"], 0)
.float("jitter", "Jitter", 1.0, 0.0, 1.0),
6.0,
1,
)
.cook(worley_noise_3d),
]
}
/// Common noise settings: whole-number scale, octaves, gain, z, contrast gain, seed.
fn settings(ctx: &Ctx) -> (f32, i32, f32, f32, f32, u32) {
(ctx.f("scale").max(1.0).round(), ctx.i("octaves"), ctx.f("roughness"), ctx.f("z"), 1.0 + ctx.f("contrast") * 3.0, ctx.seed)
}
/// Expand around mid gray by `k`.
#[inline]
fn spread(v: f32, k: f32) -> f32 {
((v - 0.5) * k + 0.5).clamp(0.0, 1.0)
}
fn perlin_noise_3d(ctx: &Ctx) -> CookResult {
let (s, oct, gain, z, k, seed) = settings(ctx);
Ok(vec![ctx.gen_gray(|u, v| {
let n = fractal(oct, gain, |m, o| {
let p = s * m;
perlin3(u * p, v * p, z * m + o as f32 * 17.31, p as i32, p as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5
});
spread(n, k)
})])
}
fn simplex_noise_3d(ctx: &Ctx) -> CookResult {
let (_, oct, gain, z, k, seed) = settings(ctx);
let s = ctx.f("scale").max(0.1);
Ok(vec![ctx.gen_gray(|u, v| spread(simplex_torus(u, v, z, s, oct, gain, seed), k))])
}
fn worley_noise_3d(ctx: &Ctx) -> CookResult {
let (s, oct, gain, z, k, seed) = settings(ctx);
let (mode, jit) = (ctx.i("distance"), ctx.f("jitter").clamp(0.0, 1.0));
Ok(vec![ctx.gen_gray(|u, v| {
let n = fractal(oct, gain, |m, o| {
let p = s * m;
let (f1, f2) = worley3(u * p, v * p, z * m, p as i32, p as i32, jit, seed.wrapping_add(o * 977));
match mode {
1 => f2 * 0.75,
2 => (f2 - f1) * 1.5,
_ => f1,
}
.clamp(0.0, 1.0)
});
// Cell distances already span 0..1: contrast 0.5 leaves them as they are.
spread(n, k * 0.4)
})])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::catalog::{find, resolve_params};
#[test]
fn primitives_tile_and_stay_in_range() {
for k in 0..20 {
let (y, z) = (k as f32 * 0.37, k as f32 * 0.11);
assert!((perlin3(0.0, y, z, 4, 4, 7) - perlin3(4.0, y, z, 4, 4, 7)).abs() < 1e-5);
assert!((perlin3(y, 0.0, z, 4, 4, 7) - perlin3(y, 4.0, z, 4, 4, 7)).abs() < 1e-5);
assert!((worley3(0.0, y, z, 5, 5, 1.0, 3).0 - worley3(5.0, y, z, 5, 5, 1.0, 3).0).abs() < 1e-4);
}
let mut lo = f32::MAX;
let mut hi = f32::MIN;
for k in 0..20000 {
let p = [k as f32 * 0.131, k as f32 * 0.071 + 0.3, (k as f32 * 0.017).sin() * 9.0, k as f32 * 0.029];
let v = simplex4(p, 1);
lo = lo.min(v);
hi = hi.max(v);
}
assert!(lo > -1.2 && hi < 1.2 && hi - lo > 1.0, "{lo} {hi}");
}
/// Each 3D noise matches across u = 0/1 and v = 0/1, and z changes it.
#[test]
fn noises_3d_tile_both_ways() {
let no_res = |_: &str| None;
let vars = BTreeMap::new();
for id in ["perlin_noise_3d", "simplex_noise_3d", "worley_noise_3d"] {
let def = find(id).unwrap();
let cook = |z: f32| {
let mut p = resolve_params(def, &BTreeMap::new());
p.insert("z".into(), materialcraft_core::Value::Float(z));
let ctx = Ctx { w: 64, h: 64, seed: 5, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
(def.cook)(&ctx).unwrap().remove(0)
};
let img = cook(0.5);
let (mut seam_x, mut seam_y, mut inner) = (0.0f32, 0.0f32, 0.0f32);
for i in 0..64 {
seam_x += (img.get(63, i, false)[0] - img.get(0, i, false)[0]).abs();
seam_y += (img.get(i, 63, false)[0] - img.get(i, 0, false)[0]).abs();
inner += (img.get(31, i, false)[0] - img.get(32, i, false)[0]).abs() + (img.get(i, 31, false)[0] - img.get(i, 32, false)[0]).abs();
}
assert!(seam_x <= inner * 1.5 + 0.2 && seam_y <= inner * 1.5 + 0.2, "{id}: seams {seam_x} {seam_y} vs inner {inner}");
assert_ne!(img, cook(1.7), "{id}: z changes the slice");
let (lo, hi) = img.range();
assert!(hi - lo > 0.3, "{id}: contrast {lo}..{hi}");
}
}
}
-440
View File
@@ -1,440 +0,0 @@
//! More Texture generators › Noises: fractal variants, fibers, organic cells and natural
//! materials (sand, wood, marble, stone, bark, concrete). All tile: every lattice uses whole-number
//! periods per axis.
use std::f32::consts::{PI, TAU};
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::generators::NOISES;
use crate::noise::{cellular, fbm, hash3, rand1, rand2, value};
#[inline]
pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
let t = ((x - e0) / (e1 - e0).max(1e-6)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
#[inline]
fn wrap(i: i32, p: i32) -> i32 {
if p <= 0 { i } else { i.rem_euclid(p) }
}
/// Gradient (Perlin) noise in about -1..1 with separate lattice periods per axis, so stretched
/// noise still tiles.
pub(crate) fn perlin_xy(x: f32, y: f32, px: i32, py: i32, seed: u32) -> f32 {
let (x0, y0) = (x.floor(), y.floor());
let (fx, fy) = (x - x0, y - y0);
let (ix, iy) = (x0 as i32, y0 as i32);
let g = |i: i32, j: i32, dx: f32, dy: f32| {
let a = (hash3(wrap(i, px), wrap(j, py), seed) >> 8) as f32 * (TAU / (1u32 << 24) as f32);
a.cos() * dx + a.sin() * dy
};
let fade = |t: f32| t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
let (u, v) = (fade(fx), fade(fy));
let a = g(ix, iy, fx, fy) + (g(ix + 1, iy, fx - 1.0, fy) - g(ix, iy, fx, fy)) * u;
let b = g(ix, iy + 1, fx, fy - 1.0) + (g(ix + 1, iy + 1, fx - 1.0, fy - 1.0) - g(ix, iy + 1, fx, fy - 1.0)) * u;
(a + (b - a) * v) * std::f32::consts::SQRT_2
}
/// Fractal sum of `f(level multiplier, octave)` (each 0..1): `octaves` layers, each twice as fine
/// and `gain` times weaker. Normalized to 0..1.
pub(crate) fn fractal(octaves: i32, gain: f32, f: impl Fn(f32, u32) -> f32) -> f32 {
let (mut sum, mut amp, mut norm, mut m) = (0.0, 1.0, 0.0, 1.0);
for o in 0..octaves.clamp(1, 10) as u32 {
sum += f(m, o) * amp;
norm += amp;
amp *= gain;
m *= 2.0;
}
sum / f32::max(norm, 1e-6)
}
/// Stretched fractal Perlin noise in 0..1 with `sx` × `sy` base cells.
fn fbm_xy(u: f32, v: f32, sx: f32, sy: f32, octaves: i32, gain: f32, seed: u32) -> f32 {
fractal(octaves, gain, |m, o| {
let (px, py) = (sx * m, sy * m);
perlin_xy(u * px, v * py, px as i32, py as i32, seed.wrapping_add(o * 977)) * 0.5 + 0.5
})
}
/// A thin bright line per stretched noise zero crossing (fibers, grain).
fn fiber(u: f32, v: f32, along: f32, across: f32, sharp: f32, seed: u32) -> f32 {
(1.0 - perlin_xy(u * along, v * across, along as i32, across as i32, seed).abs()).powf(sharp)
}
fn whole(ctx: &Ctx, id: &str) -> f32 {
ctx.f(id).max(1.0).round()
}
pub(crate) fn defs() -> Vec<NodeDef> {
let n = |id, label| node(id, label, NOISES).generator();
vec![
n("value_noise", "Value Noise")
.desc("Fractal value noise: smooth blocks of random values.")
.float("scale", "Scale", 8.0, 1.0, 256.0)
.int("octaves", "Octaves", 1, 1, 10)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(value_noise),
n("ridged_fractal", "Ridged Fractal")
.desc("Ridged multi-octave noise: sharp crests like mountain ridges.")
.float("scale", "Scale", 4.0, 1.0, 64.0)
.int("octaves", "Octaves", 6, 1, 10)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("sharpness", "Sharpness", 2.0, 0.5, 8.0)
.gray_out()
.cook(ridged_fractal),
n("voronoi_fractal", "Voronoi Fractal")
.desc("Several octaves of cell bumps.")
.float("scale", "Scale", 4.0, 1.0, 64.0)
.int("octaves", "Octaves", 4, 1, 8)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(voronoi_fractal),
n("cells_fractal", "Cells Fractal")
.desc("Several octaves of cell borders: cracked, crystalline networks.")
.float("scale", "Scale", 4.0, 1.0, 64.0)
.int("octaves", "Octaves", 3, 1, 8)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(cells_fractal),
n("directional_noise", "Directional Noise")
.desc("Fractal noise stretched along one axis: streaks and brushed patterns.")
.float("scale", "Scale along", 2.0, 1.0, 64.0)
.float("scale_across", "Scale across", 24.0, 1.0, 256.0)
.int("octaves", "Octaves", 5, 1, 10)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.boolean("vertical", "Vertical", false)
.gray_out()
.cook(directional_noise),
n("fibers", "Fibers")
.desc("Thin, nearly parallel fibers.")
.float("density", "Density", 96.0, 4.0, 512.0)
.float("length", "Length", 2.0, 1.0, 32.0)
.float("sharpness", "Sharpness", 12.0, 1.0, 64.0)
.boolean("vertical", "Vertical", false)
.gray_out()
.cook(fibers),
n("messy_fibers", "Messy Fibers")
.desc("Tangled fibers in both directions, warped by clouds.")
.float("density", "Density", 64.0, 4.0, 512.0)
.float("warp", "Warp", 0.5, 0.0, 2.0)
.float("sharpness", "Sharpness", 10.0, 1.0, 64.0)
.gray_out()
.cook(messy_fibers),
n("leather", "Leather")
.desc("Leather grain: small bumpy cells split by creases, over soft clouds.")
.float("scale", "Scale", 24.0, 2.0, 128.0)
.float("crease", "Crease width", 0.25, 0.0, 1.0)
.float("warp", "Warp", 0.4, 0.0, 1.0)
.float("clouds", "Clouds", 0.3, 0.0, 1.0)
.gray_out()
.cook(leather),
n("microscope", "Microscope View")
.desc("Strongly warped cell walls, like tissue under a microscope.")
.float("scale", "Scale", 6.0, 1.0, 64.0)
.float("warp", "Warp", 0.6, 0.0, 2.0)
.float("width", "Wall width", 0.15, 0.01, 1.0)
.gray_out()
.cook(microscope),
n("gaussian_spots", "Gaussian Spots")
.desc("Scattered soft round spots of random size and intensity.")
.float("scale", "Scale", 8.0, 1.0, 64.0)
.float("size", "Size", 0.3, 0.01, 1.0)
.float("size_random", "Size random", 0.5, 0.0, 1.0)
.float("density", "Density", 0.8, 0.0, 1.0)
.gray_out()
.cook(gaussian_spots),
n("crackle", "Crackle")
.desc("Wiggly cracks along cell borders, with finer secondary cracks.")
.float("scale", "Scale", 5.0, 1.0, 64.0)
.float("width", "Width", 0.08, 0.005, 0.5)
.float("disorder", "Disorder", 0.5, 0.0, 2.0)
.float("amount", "Amount", 1.0, 0.0, 1.0)
.gray_out()
.cook(crackle),
n("sand_dunes", "Sand Dunes")
.desc("Wind-shaped dunes: gentle windward slopes, steep lee sides and fine ripples.")
.int("count", "Dunes", 6, 1, 64)
.float("warp", "Warp", 0.6, 0.0, 2.0)
.float("steepness", "Lee side", 0.3, 0.05, 0.95)
.float("ripples", "Ripples", 0.15, 0.0, 1.0)
.gray_out()
.cook(sand_dunes),
n("wood_grain", "Wood Grain")
.desc("Distorted growth rings and fibers of sawn wood (grain along X).")
.float("rings", "Rings", 16.0, 1.0, 128.0)
.float("stretch", "Stretch", 6.0, 1.0, 32.0)
.float("sharpness", "Ring sharpness", 3.0, 0.5, 16.0)
.float("fibers", "Fibers", 0.3, 0.0, 1.0)
.gray_out()
.cook(wood_grain),
n("marble", "Marble")
.desc("Thin veins from sine bands warped by fractal noise.")
.float("scale", "Bands", 2.0, 1.0, 32.0)
.float("turbulence", "Turbulence", 3.0, 0.0, 10.0)
.float("sharpness", "Vein sharpness", 4.0, 1.0, 64.0)
.choice("direction", "Direction", &["Horizontal", "Vertical", "Diagonal"], 2)
.gray_out()
.cook(marble),
n("stones", "Stones")
.desc("Packed rounded stones with gaps (height).")
.float("scale", "Scale", 6.0, 1.0, 64.0)
.float("gap", "Gap", 0.06, 0.0, 0.5)
.float("bevel", "Bevel", 0.25, 0.01, 1.0)
.float("height_random", "Height random", 0.4, 0.0, 1.0)
.float("detail", "Detail", 0.2, 0.0, 1.0)
.float("disorder", "Disorder", 1.0, 0.0, 1.0)
.gray_out()
.cook(stones),
n("ripples", "Ripples")
.desc("Interfering waves, like a water surface.")
.float("scale", "Scale", 8.0, 1.0, 32.0)
.int("waves", "Waves", 10, 1, 32)
.float("warp", "Warp", 0.3, 0.0, 2.0)
.gray_out()
.cook(ripples),
n("concrete", "Concrete")
.desc("Cement clouds with small air pits and fine grain.")
.float("scale", "Scale", 4.0, 1.0, 32.0)
.float("pits", "Pit density", 0.3, 0.0, 1.0)
.float("pit_size", "Pit size", 0.5, 0.0, 1.0)
.float("roughness", "Roughness", 0.6, 0.0, 1.0)
.gray_out()
.cook(concrete),
n("bark", "Bark")
.desc("Deep vertical bark furrows.")
.float("scale", "Furrows", 8.0, 1.0, 64.0)
.float("stretch", "Length", 1.0, 1.0, 16.0)
.float("warp", "Warp", 0.4, 0.0, 2.0)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.gray_out()
.cook(bark),
]
}
fn value_noise(ctx: &Ctx) -> CookResult {
let (sc, o, r, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| value(u * sc * m, v * sc * m, (sc * m) as i32, s.wrapping_add(k * 131))))])
}
fn ridged_fractal(ctx: &Ctx) -> CookResult {
let (sc, o, r, sh, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("sharpness").max(0.1), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
fractal(o, r, |m, k| (1.0 - perlin_xy(u * sc * m, v * sc * m, (sc * m) as i32, (sc * m) as i32, s.wrapping_add(k * 7919)).abs()).powf(sh))
})])
}
fn cell_fractal(ctx: &Ctx, f: impl Fn(crate::noise::Cell) -> f32 + Sync) -> CookResult {
let (sc, o, r, d, s) = (whole(ctx, "scale"), ctx.i("octaves"), ctx.f("roughness"), ctx.f("disorder"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| fractal(o, r, |m, k| f(cellular(u * sc * m, v * sc * m, (sc * m) as i32, d, 0, s.wrapping_add(k * 311)))))])
}
fn voronoi_fractal(ctx: &Ctx) -> CookResult {
cell_fractal(ctx, |c| (1.0 - c.f1).clamp(0.0, 1.0))
}
fn cells_fractal(ctx: &Ctx) -> CookResult {
cell_fractal(ctx, |c| ((c.f2 - c.f1) * 2.0).min(1.0))
}
fn directional_noise(ctx: &Ctx) -> CookResult {
let (along, across, o, r, s) = (whole(ctx, "scale"), whole(ctx, "scale_across"), ctx.i("octaves"), ctx.f("roughness"), ctx.seed);
let vert = ctx.b("vertical");
Ok(vec![ctx.gen_gray(|u, v| if vert { fbm_xy(u, v, across, along, o, r, s) } else { fbm_xy(u, v, along, across, o, r, s) })])
}
fn fibers(ctx: &Ctx) -> CookResult {
let (d, l, sh, s) = (whole(ctx, "density"), whole(ctx, "length"), ctx.f("sharpness").max(1.0), ctx.seed);
let vert = ctx.b("vertical");
Ok(vec![ctx.gen_gray(|u, v| {
let (u, v) = if vert { (v, u) } else { (u, v) };
let a = fiber(u, v, l, d, sh, s);
let b = fiber(u, v, l * 2.0, d * 2.0, sh, s ^ 0x51);
(a + b * 0.6).min(1.0)
})])
}
fn messy_fibers(ctx: &Ctx) -> CookResult {
let (d, w, sh, s) = (whole(ctx, "density"), ctx.f("warp") * 0.15, ctx.f("sharpness").max(1.0), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let wu = u + (fbm(u, v, 3.0, 4, 0.5, s ^ 1) - 0.5) * w;
let wv = v + (fbm(u, v, 3.0, 4, 0.5, s ^ 2) - 0.5) * w;
let h = fiber(wu, wv, 3.0, d, sh, s);
let vt = fiber(wv, wu, 3.0, d, sh, s ^ 0x77);
let fine = fiber(wv, wu, 6.0, d * 2.0, sh, s ^ 0x99);
(h + vt * 0.8 + fine * 0.4).min(1.0)
})])
}
fn leather(ctx: &Ctx) -> CookResult {
let (sc, cw, w, cl, s) = (whole(ctx, "scale"), ctx.f("crease").max(1e-3), ctx.f("warp"), ctx.f("clouds"), ctx.seed);
let lo = (sc / 6.0).round().max(1.0);
Ok(vec![ctx.gen_gray(|u, v| {
let qx = (fbm(u, v, lo, 4, 0.5, s ^ 3) - 0.5) * w / sc * 2.0;
let qy = (fbm(u, v, lo, 4, 0.5, s ^ 4) - 0.5) * w / sc * 2.0;
let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s);
let crease = smoothstep(0.0, cw, c.f2 - c.f1);
let bump = (1.0 - c.f1 * 0.9).clamp(0.0, 1.0);
let clouds = fbm(u, v, lo, 5, 0.5, s ^ 7);
(crease * (0.55 + 0.45 * bump) * (1.0 - cl + cl * clouds)).clamp(0.0, 1.0)
})])
}
fn microscope(ctx: &Ctx) -> CookResult {
let (sc, w, wd, s) = (whole(ctx, "scale"), ctx.f("warp"), ctx.f("width").max(1e-3), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let qx = (fbm(u, v, sc, 4, 0.5, s ^ 5) - 0.5) * w / sc * 3.0;
let qy = (fbm(u, v, sc, 4, 0.5, s ^ 6) - 0.5) * w / sc * 3.0;
let c = cellular((u + qx) * sc, (v + qy) * sc, sc as i32, 1.0, 0, s);
let wall = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1);
let inner = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 8) * 0.35 * (1.0 - c.f1).max(0.0);
(wall + inner).clamp(0.0, 1.0)
})])
}
fn gaussian_spots(ctx: &Ctx) -> CookResult {
let (sc, size, sr, dens, s) = (whole(ctx, "scale"), ctx.f("size").max(0.01), ctx.f("size_random"), ctx.f("density"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let mut sum = 0.0;
for layer in 0..2u32 {
let n = sc * (layer + 1) as f32;
let (x, y) = (u * n, v * n);
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
let ls = s.wrapping_add(layer * 0x3c6e);
for j in -1..=1 {
for i in -1..=1 {
let (cx, cy) = (wrap(ix + i, n as i32), wrap(iy + j, n as i32));
if rand2(cx, cy, ls ^ 9) > dens {
continue;
}
let px = (ix + i) as f32 + rand2(cx, cy, ls);
let py = (iy + j) as f32 + rand2(cx, cy, ls ^ 1);
let r = size * (1.0 - sr * rand2(cx, cy, ls ^ 2)) * 0.5;
let d2 = (px - x).powi(2) + (py - y).powi(2);
sum += (-d2 / (2.0 * r * r)).exp() * (0.4 + 0.6 * rand2(cx, cy, ls ^ 3)) / (layer + 1) as f32;
}
}
}
sum.min(1.0)
})])
}
fn crackle(ctx: &Ctx) -> CookResult {
let (sc, wd, dis, amt, s) = (whole(ctx, "scale"), ctx.f("width").max(1e-3), ctx.f("disorder"), ctx.f("amount"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let qx = (fbm(u, v, sc, 4, 0.5, s ^ 1) - 0.5) * dis / sc;
let qy = (fbm(u, v, sc, 4, 0.5, s ^ 2) - 0.5) * dis / sc;
let (wu, wv) = (u + qx, v + qy);
let c = cellular(wu * sc, wv * sc, sc as i32, 1.0, 0, s);
let main = 1.0 - smoothstep(0.0, wd, c.f2 - c.f1);
let n2 = sc * 3.0;
let c2 = cellular(wu * n2, wv * n2, n2 as i32, 1.0, 0, s ^ 5);
// Finer cracks only in some areas, so they break off instead of closing into cells.
let fine = (1.0 - smoothstep(0.0, wd * 1.5, c2.f2 - c2.f1)) * smoothstep(0.55, 0.65, fbm(u, v, sc * 2.0, 3, 0.5, s ^ 11)) * 0.6;
let vis = smoothstep(0.9 - amt, 1.1 - amt, fbm(u, v, 2.0, 3, 0.5, s ^ 3) * 0.999);
(main.max(fine) * if amt >= 1.0 { 1.0 } else { vis }).clamp(0.0, 1.0)
})])
}
fn sand_dunes(ctx: &Ctx) -> CookResult {
let (n, w, k, rp, s) = (ctx.i("count").max(1) as f32, ctx.f("warp"), ctx.f("steepness").clamp(0.05, 0.95), ctx.f("ripples"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let q = fbm(u, v, 3.0, 5, 0.5, s) - 0.5;
let t = (v * n + q * w * 2.0).rem_euclid(1.0);
let p = if t < 1.0 - k { t / (1.0 - k) } else { (1.0 - t) / k };
let p = p * p * (3.0 - 2.0 * p);
let rip = (TAU * (v * n * 8.0 + q * 6.0 + u * 2.0)).sin() * 0.5 + 0.5;
p * (1.0 - rp) + rip * rp * (0.5 + 0.5 * p)
})])
}
fn wood_grain(ctx: &Ctx) -> CookResult {
let (rings, st, sh, fb, s) = (ctx.f("rings").max(1.0), whole(ctx, "stretch"), ctx.f("sharpness").max(0.1), ctx.f("fibers"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let n = fbm_xy(u, v, 1.0, st, 4, 0.45, s);
let t = (n * rings).rem_euclid(1.0);
let ring = t.powf(sh);
let f = fiber(u, v, 2.0, 160.0, 8.0, s ^ 0x3b);
((1.0 - ring * 0.65) * (1.0 - f * fb * 0.35)).clamp(0.0, 1.0)
})])
}
fn marble(ctx: &Ctx) -> CookResult {
let (n, turb, sh, dir, s) = (whole(ctx, "scale"), ctx.f("turbulence"), ctx.f("sharpness").max(1.0), ctx.i("direction"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let base = match dir {
0 => v,
1 => u,
_ => u + v,
};
let f = fbm(u, v, 3.0, 6, 0.55, s);
let vein = |k: f32, f: f32| (1.0 - (PI * (base * n * k + turb * f)).sin().abs()).powf(sh * k);
// Main veins plus a finer, fainter network.
let v2 = vein(2.0, fbm(u, v, 4.0, 6, 0.55, s ^ 9));
(0.25 + 0.2 * fbm(u, v, 6.0, 5, 0.5, s ^ 4) + 0.6 * vein(1.0, f).max(v2 * 0.45)).clamp(0.0, 1.0)
})])
}
fn stones(ctx: &Ctx) -> CookResult {
let (sc, gap, bev, hr, det, dis, s) =
(whole(ctx, "scale"), ctx.f("gap"), ctx.f("bevel").max(1e-3), ctx.f("height_random"), ctx.f("detail"), ctx.f("disorder"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let c = cellular(u * sc, v * sc, sc as i32, dis, 0, s);
let e = (c.f2 - c.f1) * 0.5 - gap * 0.5;
if e <= 0.0 {
return 0.0;
}
let dome = smoothstep(0.0, bev, e).sqrt();
let d = fbm(u, v, sc * 2.0, 4, 0.5, s ^ 3);
(dome * (1.0 - hr * c.id) * (1.0 - det + det * d)).clamp(0.0, 1.0)
})])
}
fn ripples(ctx: &Ctx) -> CookResult {
let (sc, n, w, s) = (whole(ctx, "scale"), ctx.i("waves").clamp(1, 32) as u32, ctx.f("warp"), ctx.seed);
// Whole-number wave vectors keep every wave periodic over the image.
let waves: Vec<(f32, f32, f32, f32)> = (0..n)
.map(|k| {
let (dy, dx) = (rand1(k * 4, s) * TAU).sin_cos();
let mag = sc * (0.5 + 0.5 * rand1(k * 4 + 1, s));
let (mut kx, ky) = ((dx * mag).round(), (dy * mag).round());
if kx == 0.0 && ky == 0.0 {
kx = 1.0;
}
(kx, ky, rand1(k * 4 + 2, s), 1.0 / (1.0 + k as f32 * 0.3))
})
.collect();
let norm: f32 = waves.iter().map(|w| w.3).sum();
Ok(vec![ctx.gen_gray(|u, v| {
let q = (fbm(u, v, 2.0, 3, 0.5, s ^ 7) - 0.5) * w;
let sum: f32 = waves.iter().map(|(kx, ky, ph, a)| (TAU * (kx * u + ky * v + ph + q)).sin() * a).sum();
(sum / norm.max(1e-6) * 0.5 + 0.5).clamp(0.0, 1.0)
})])
}
fn concrete(ctx: &Ctx) -> CookResult {
let (sc, pits, ps, r, s) = (whole(ctx, "scale"), ctx.f("pits"), ctx.f("pit_size"), ctx.f("roughness"), ctx.seed);
let pn = (sc * 12.0).round();
Ok(vec![ctx.gen_gray(|u, v| {
let base = fbm(u, v, sc, 8, r, s);
let c = cellular(u * pn, v * pn, pn as i32, 1.0, 0, s ^ 5);
let rad = 0.08 + ps * 0.3;
let pit = if c.id < pits { 1.0 - smoothstep(rad * 0.6, rad, c.f1) } else { 0.0 };
let grain = value(u * 192.0, v * 192.0, 192, s ^ 9);
(base * 0.75 + grain * 0.25 - pit * 0.45).clamp(0.0, 1.0)
})])
}
fn bark(ctx: &Ctx) -> CookResult {
let (sx, sy, w, r, s) = (whole(ctx, "scale"), whole(ctx, "stretch"), ctx.f("warp"), ctx.f("roughness"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let q = (fbm(u, v, 4.0, 4, 0.5, s ^ 3) - 0.5) * w / sx;
fractal(5, r, |m, k| {
let (px, py) = (sx * m, sy * m);
(1.0 - perlin_xy((u + q) * px, v * py, px as i32, py as i32, s.wrapping_add(k * 613)).abs()).powi(2)
})
})])
}
-558
View File
@@ -1,558 +0,0 @@
//! Texture generators › Patterns: shapes, tilings, gradients and scattered elements.
use std::f32::consts::{PI, TAU};
use materialcraft_image::{Image, Kind};
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::noise::{rand1, rand2};
pub const PATTERNS: &str = "Texture generators/Patterns";
pub const SHAPES: &[&str] = &[
"Square",
"Disc",
"Paraboloid",
"Bell",
"Gaussian",
"Thorn",
"Pyramid",
"Brick",
"Gradation",
"Waves",
"Half bell",
"Ridged bell",
"Crescent",
"Capsule",
"Cone",
"Hexagon",
];
/// A shape's value at local coordinates `(x, y)` in -1..1 (1 at the center, 0 outside).
pub fn shape(kind: i32, x: f32, y: f32) -> f32 {
let r = (x * x + y * y).sqrt();
let m = x.abs().max(y.abs());
let v = match kind {
0 => (m <= 1.0) as i32 as f32,
1 => (r <= 1.0) as i32 as f32,
2 => 1.0 - r * r,
3 => {
let t = (1.0 - r).max(0.0);
t * t * (3.0 - 2.0 * t)
}
4 => (-r * r * 4.0).exp() * (r <= 1.0) as i32 as f32,
5 => (1.0 - r).max(0.0).powi(3),
6 => 1.0 - m,
7 => {
let bx = (1.0 - x.abs()) * 6.0;
let by = (1.0 - y.abs()) * 3.0;
bx.min(by).clamp(0.0, 1.0)
}
8 => (x * 0.5 + 0.5) * (m <= 1.0) as i32 as f32,
9 => (x * PI * 2.0).cos() * 0.5 + 0.5,
10 => {
let t = (1.0 - r).max(0.0);
if y < 0.0 { 0.0 } else { t * t * (3.0 - 2.0 * t) }
}
11 => {
let t = (1.0 - r).max(0.0);
(t * t * (3.0 - 2.0 * t)) * (1.0 - ((r * PI * 3.0).sin()).abs() * 0.4)
}
12 => {
let r2 = ((x - 0.35) * (x - 0.35) + y * y).sqrt();
((r <= 1.0) && (r2 > 0.75)) as i32 as f32
}
13 => {
let dx = (x.abs() - 0.5).max(0.0);
let d = (dx * dx + y * y * 4.0).sqrt();
(d <= 0.5) as i32 as f32
}
14 => (1.0 - r).max(0.0),
15 => {
let (ax, ay) = (x.abs(), y.abs());
((ax * 0.866 + ay * 0.5).max(ay) <= 0.95) as i32 as f32
}
_ => 0.0,
};
v.clamp(0.0, 1.0)
}
pub(crate) fn defs() -> Vec<NodeDef> {
let p = |id, label| node(id, label, PATTERNS).generator();
vec![
p("brick_generator", "Brick Generator")
.desc("Rows of bricks with mortar gaps, bevels and random heights.")
.int("bricks_x", "Bricks X", 4, 1, 64)
.int("bricks_y", "Bricks Y", 8, 1, 64)
.float("offset", "Row offset", 0.5, 0.0, 1.0)
.float("gap", "Gap", 0.04, 0.0, 0.5)
.float("bevel", "Bevel", 0.12, 0.0, 1.0)
.float("height_random", "Height random", 0.3, 0.0, 1.0)
.float("lum_random", "Luminance random", 0.0, 0.0, 1.0)
.gray_out()
.cook(bricks),
p("checker", "Checker").desc("A checkerboard.").int("tiling", "Tiling", 4, 1, 64).gray_out().cook(checker),
p("gradient_linear_1", "Gradient Linear 1")
.desc("A ramp from black to white.")
.int("tiling", "Tiling", 1, 1, 16)
.boolean("vertical", "Vertical", false)
.gray_out()
.cook(gradient_linear_1),
p("gradient_linear_2", "Gradient Linear 2")
.desc("A mirrored ramp (white in the middle).")
.int("tiling", "Tiling", 1, 1, 16)
.boolean("vertical", "Vertical", false)
.gray_out()
.cook(gradient_linear_2),
p("gradient_radial", "Gradient Radial")
.desc("White at the center fading outward.")
.float("radius", "Radius", 0.5, 0.0, 1.0)
.gray_out()
.cook(gradient_radial),
p("hexagons", "Hexagons")
.desc("A honeycomb of beveled hexagons.")
.int("tiling", "Tiling", 4, 1, 64)
.float("size", "Size", 0.9, 0.0, 1.0)
.float("bevel", "Bevel", 0.3, 0.0, 1.0)
.gray_out()
.cook(hexagons),
p("polygon", "Polygon")
.desc("A regular polygon.")
.int("sides", "Sides", 6, 3, 32)
.float("scale", "Scale", 0.8, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.float("gradient", "Gradient", 0.0, 0.0, 1.0)
.int("tiling", "Tiling", 1, 1, 16)
.gray_out()
.cook(polygon),
p("scratches", "Scratches")
.desc("Random thin scratches.")
.int("count", "Count", 60, 0, 1000)
.float("length", "Length", 0.25, 0.0, 1.0)
.float("width", "Width", 1.0, 0.1, 8.0)
.angle("angle", "Angle", 0.1)
.float("angle_random", "Angle random", 0.2, 0.0, 1.0)
.gray_out()
.cook(scratches),
p("shape", "Shape")
.desc("A single shape, optionally tiled.")
.choice("pattern", "Pattern", SHAPES, 1)
.int("tiling", "Tiling", 1, 1, 64)
.float("size", "Size", 0.8, 0.0, 2.0)
.float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0)
.angle("angle", "Angle", 0.0)
.gray_out()
.cook(shape_node),
p("splatter", "Splatter")
.desc("Scattered shapes of random size and gray.")
.choice("pattern", "Pattern", SHAPES, 4)
.int("count", "Count", 64, 1, 2000)
.float("size", "Size", 0.08, 0.0, 1.0)
.float("size_random", "Size random", 0.6, 0.0, 1.0)
.float("lum_random", "Luminance random", 0.5, 0.0, 1.0)
.gray_out()
.cook(splatter),
p("star", "Star")
.desc("A star shape.")
.int("points", "Points", 5, 2, 32)
.float("inner", "Inner radius", 0.45, 0.0, 1.0)
.float("scale", "Scale", 0.8, 0.0, 1.0)
.int("tiling", "Tiling", 1, 1, 16)
.gray_out()
.cook(star),
p("stripes", "Stripes")
.desc("Parallel bands with soft edges.")
.int("count", "Count", 8, 1, 128)
.float("width", "Width", 0.5, 0.0, 1.0)
.float("softness", "Softness", 0.0, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.gray_out()
.cook(stripes),
p("tile_generator", "Tile Generator")
.desc("Places a shape on a grid with per-tile random size, position, rotation and luminance.")
.choice("pattern", "Pattern", SHAPES, 0)
.int("x_amount", "X amount", 8, 1, 128)
.int("y_amount", "Y amount", 8, 1, 128)
.float("scale", "Scale", 0.9, 0.0, 2.0)
.float2("size_xy", "Size XY", [1.0, 1.0], 0.0, 2.0)
.float("scale_random", "Scale random", 0.0, 0.0, 1.0)
.float("offset", "Row offset", 0.0, 0.0, 1.0)
.float("position_random", "Position random", 0.0, 0.0, 1.0)
.float("rotation_random", "Rotation random", 0.0, 0.0, 1.0)
.float("lum_random", "Luminance random", 0.0, 0.0, 1.0)
.float("mask_random", "Mask random", 0.0, 0.0, 1.0)
.gray_out()
.cook(tile_generator),
p("tile_sampler", "Tile Sampler")
.desc("Like Tile Generator, but each tile shows the pattern input.")
.gray_in("pattern", "Pattern input")
.gray_in("scale_map", "Scale map")
.int("x_amount", "X amount", 8, 1, 128)
.int("y_amount", "Y amount", 8, 1, 128)
.float("scale", "Scale", 1.0, 0.0, 2.0)
.float("scale_random", "Scale random", 0.0, 0.0, 1.0)
.float("offset", "Row offset", 0.0, 0.0, 1.0)
.float("position_random", "Position random", 0.0, 0.0, 1.0)
.float("rotation_random", "Rotation random", 0.0, 0.0, 1.0)
.float("lum_random", "Luminance random", 0.0, 0.0, 1.0)
.choice("blend", "Blending", &["Max", "Add"], 0)
.gray_out()
.cook(tile_sampler),
p("weave", "Weave")
.desc("Interlaced threads (height).")
.int("tiling", "Tiling", 6, 1, 64)
.float("width", "Thread width", 0.8, 0.0, 1.0)
.gray_out()
.cook(weave),
p("waveform", "Waveform")
.desc("Sine bands.")
.int("count", "Count", 8, 1, 128)
.float("amplitude", "Amplitude", 0.0, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.gray_out()
.cook(waveform),
]
}
/// Rotate `(x, y)` by `turns`.
#[inline]
fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) {
let (s, c) = (turns * TAU).sin_cos();
(x * c - y * s, x * s + y * c)
}
fn bricks(ctx: &Ctx) -> CookResult {
let (bx, by) = (ctx.i("bricks_x").max(1) as f32, ctx.i("bricks_y").max(1) as f32);
let (off, gap, bevel, hr, lr, s) = (ctx.f("offset"), ctx.f("gap"), ctx.f("bevel").max(1e-4), ctx.f("height_random"), ctx.f("lum_random"), ctx.seed);
Ok(vec![ctx.gen_gray(|u, v| {
let row = (v * by).floor();
let x = u * bx + off * row;
let col = x.floor();
let (fx, fy) = (x - col, v * by - row);
let colw = (col as i32).rem_euclid(bx as i32);
// Distance to the brick's edge, in brick-height units.
let ex = fx.min(1.0 - fx) * by / bx;
let ey = fy.min(1.0 - fy);
let e = ex.min(ey) - gap * 0.5;
if e <= 0.0 {
return 0.0;
}
let t = (e / (bevel * 0.5)).min(1.0);
let rnd = rand2(colw, row as i32, s);
let base = 1.0 - hr * rnd;
let lum = 1.0 - lr * rand2(colw, row as i32, s ^ 99);
(t * base * lum).clamp(0.0, 1.0)
})])
}
fn checker(ctx: &Ctx) -> CookResult {
let n = ctx.i("tiling").max(1) as f32;
Ok(vec![ctx.gen_gray(|u, v| (((u * n).floor() + (v * n).floor()) as i32 & 1) as f32)])
}
fn gradient_linear_1(ctx: &Ctx) -> CookResult {
let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical"));
Ok(vec![ctx.gen_gray(|u, v| ((if vert { v } else { u }) * n).fract())])
}
fn gradient_linear_2(ctx: &Ctx) -> CookResult {
let (n, vert) = (ctx.i("tiling").max(1) as f32, ctx.b("vertical"));
Ok(vec![ctx.gen_gray(|u, v| 1.0 - ((((if vert { v } else { u }) * n).fract()) * 2.0 - 1.0).abs())])
}
fn gradient_radial(ctx: &Ctx) -> CookResult {
let r = ctx.f("radius").max(1e-3);
Ok(vec![ctx.gen_gray(|u, v| (1.0 - ((u - 0.5).powi(2) + (v - 0.5).powi(2)).sqrt() / r).clamp(0.0, 1.0))])
}
fn hexagons(ctx: &Ctx) -> CookResult {
let n = ctx.i("tiling").max(1) as f32;
let (size, bevel) = (ctx.f("size"), ctx.f("bevel").max(1e-3));
let sq3 = 3f32.sqrt();
// Flat-top hexes of circumradius 1: two lattices, (3i, √3j) and (3i + 1.5, √3j + √3/2). The
// image holds n lattice periods across and the nearest whole number down, so it tiles.
let m = (n * 3.0 / sq3).round().max(1.0);
Ok(vec![ctx.gen_gray(|u, v| {
let (px, py) = (u * n * 3.0, v * m * sq3);
let a = ((px / 3.0).round() * 3.0, (py / sq3).round() * sq3);
let b = (((px - 1.5) / 3.0).round() * 3.0 + 1.5, ((py - sq3 * 0.5) / sq3).round() * sq3 + sq3 * 0.5);
let da = (px - a.0).powi(2) + (py - a.1).powi(2);
let db = (px - b.0).powi(2) + (py - b.1).powi(2);
let (cx, cy) = if da < db { a } else { b };
let (dx, dy) = ((px - cx).abs(), (py - cy).abs());
let inr = sq3 * 0.5;
let d = (dy / inr).max((dx * inr + dy * 0.5) / inr);
((size - d) / bevel).clamp(0.0, 1.0)
})])
}
fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) {
(((u * n).fract() - 0.5) * 2.0, ((v * n).fract() - 0.5) * 2.0)
}
fn polygon(ctx: &Ctx) -> CookResult {
let sides = ctx.i("sides").clamp(3, 64) as f32;
let (sc, ang, grad, n) = (ctx.f("scale").max(1e-3), ctx.f("angle"), ctx.f("gradient"), ctx.i("tiling").max(1) as f32);
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, n);
let (x, y) = rot(x, y, ang);
let a = y.atan2(x);
let seg = TAU / sides;
let d = (x * x + y * y).sqrt() * ((a.rem_euclid(seg) - seg * 0.5).cos()) / (seg * 0.5).cos();
let e = 1.0 - d / sc;
if grad <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / grad).clamp(0.0, 1.0) }
})])
}
fn scratches(ctx: &Ctx) -> CookResult {
let count = ctx.i("count").clamp(0, 5000) as u32;
let (len, width, ang, ar, s) = (ctx.f("length"), ctx.f("width") / ctx.w as f32, ctx.f("angle"), ctx.f("angle_random"), ctx.seed);
let segs: Vec<([f32; 2], [f32; 2], f32)> = (0..count)
.map(|i| {
let p = [rand1(i * 4, s), rand1(i * 4 + 1, s)];
let a = (ang + (rand1(i * 4 + 2, s) - 0.5) * ar) * TAU;
let l = len * (0.5 + 0.5 * rand1(i * 4 + 3, s));
([p[0], p[1]], [a.cos() * l, -a.sin() * l], 0.4 + 0.6 * rand1(i * 7 + 5, s))
})
.collect();
// Bin segments by their bounding boxes on a coarse grid so each pixel tests only nearby ones.
const G: usize = 16;
let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G];
for (k, (p, d, _)) in segs.iter().enumerate() {
let (x0, x1) = (p[0].min(p[0] + d[0]) - width, p[0].max(p[0] + d[0]) + width);
let (y0, y1) = (p[1].min(p[1] + d[1]) - width, p[1].max(p[1] + d[1]) + width);
// At most one full turn of bins per axis, so no segment lands twice in a bin.
let (gy0, gx0) = ((y0 * G as f32).floor() as i64, (x0 * G as f32).floor() as i64);
let gy1 = ((y1 * G as f32).floor() as i64).min(gy0.saturating_add(G as i64 - 1));
let gx1 = ((x1 * G as f32).floor() as i64).min(gx0.saturating_add(G as i64 - 1));
for gy in gy0..=gy1 {
for gx in gx0..=gx1 {
if let Some(b) = bins.get_mut(gy.rem_euclid(G as i64) as usize * G + gx.rem_euclid(G as i64) as usize) {
b.push(k);
}
}
}
}
Ok(vec![ctx.gen_gray(|u, v| {
let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)];
let mut best: f32 = 0.0;
for k in bin {
let (p, d, lum) = segs[*k];
for (ox, oy) in [(0.0, 0.0), (1.0, 0.0), (-1.0, 0.0), (0.0, 1.0), (0.0, -1.0)] {
let (qx, qy) = (u - p[0] + ox, v - p[1] + oy);
let t = ((qx * d[0] + qy * d[1]) / (d[0] * d[0] + d[1] * d[1]).max(1e-9)).clamp(0.0, 1.0);
let (ex, ey) = (qx - d[0] * t, qy - d[1] * t);
let dist = (ex * ex + ey * ey).sqrt();
if dist < width {
best = best.max((1.0 - dist / width) * lum * (1.0 - (t * 2.0 - 1.0).abs().powi(4)));
}
}
}
best
})])
}
fn shape_node(ctx: &Ctx) -> CookResult {
let (k, n, size, sxy, ang) = (ctx.i("pattern"), ctx.i("tiling").max(1) as f32, ctx.f("size").max(1e-3), ctx.v2("size_xy"), ctx.f("angle"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, n);
let (x, y) = rot(x, y, ang);
shape(k, x / (size * sxy[0].max(1e-3)), y / (size * sxy[1].max(1e-3)))
})])
}
fn splatter(ctx: &Ctx) -> CookResult {
let count = ctx.i("count").clamp(1, 2000) as u32;
let (k, size, sr, lr, s) = (ctx.i("pattern"), ctx.f("size"), ctx.f("size_random"), ctx.f("lum_random"), ctx.seed);
let items: Vec<([f32; 2], f32, f32, f32)> = (0..count)
.map(|i| ([rand1(i * 5, s), rand1(i * 5 + 1, s)], size * (1.0 - sr * rand1(i * 5 + 2, s)), 1.0 - lr * rand1(i * 5 + 3, s), rand1(i * 5 + 4, s)))
.collect();
let base = Image::filled(ctx.w, ctx.h, Kind::Gray, [0.0; 4]);
Ok(vec![stamp(ctx, base, &items, |x, y, _| shape(k, x, y), |a, b| a.max(b))])
}
/// Splat `items` (center, radius, luminance, rotation turns) onto `base` with `f` combining.
fn stamp(
ctx: &Ctx,
base: Image,
items: &[([f32; 2], f32, f32, f32)],
sh: impl Fn(f32, f32, usize) -> f32 + Sync,
combine: impl Fn(f32, f32) -> f32 + Sync,
) -> Image {
const G: usize = 32;
let mut bins: Vec<Vec<usize>> = vec![Vec::new(); G * G];
for (i, (c, r, _, _)) in items.iter().enumerate() {
let r = r * 1.42;
// At most one full turn of bins per axis, so no item lands twice in a bin.
let (gy0, gx0) = (((c[1] - r) * G as f32).floor() as i64, ((c[0] - r) * G as f32).floor() as i64);
let gy1 = (((c[1] + r) * G as f32).floor() as i64).min(gy0.saturating_add(G as i64 - 1));
let gx1 = (((c[0] + r) * G as f32).floor() as i64).min(gx0.saturating_add(G as i64 - 1));
for gy in gy0..=gy1 {
for gx in gx0..=gx1 {
if let Some(b) = bins.get_mut(gy.rem_euclid(G as i64) as usize * G + gx.rem_euclid(G as i64) as usize) {
b.push(i);
}
}
}
}
let tile = ctx.tile;
Image::generate_uv(ctx.w, ctx.h, Kind::Gray, |u, v| {
let mut acc = base.sample_nearest(u, v, false)[0];
let bin = &bins[((v * G as f32) as usize).min(G - 1) * G + ((u * G as f32) as usize).min(G - 1)];
for i in bin {
let (c, r, lum, rt) = items[*i];
if r <= 0.0 {
continue;
}
let mut dx = u - c[0];
let mut dy = v - c[1];
if tile {
dx -= dx.round();
dy -= dy.round();
}
let (x, y) = rot(dx / r, dy / r, rt);
if x.abs() <= 1.0 && y.abs() <= 1.0 {
acc = combine(acc, sh(x, y, *i) * lum);
}
}
[acc, 0.0, 0.0, 0.0]
})
}
fn star(ctx: &Ctx) -> CookResult {
let pts = ctx.i("points").clamp(2, 64) as f32;
let (inner, sc, n) = (ctx.f("inner"), ctx.f("scale").max(1e-3), ctx.i("tiling").max(1) as f32);
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, n);
let a = y.atan2(x) + PI / 2.0;
let seg = TAU / pts;
let t = ((a.rem_euclid(seg) / seg) * 2.0 - 1.0).abs();
let rad = sc * (inner + (1.0 - inner) * t);
((x * x + y * y).sqrt() <= rad) as i32 as f32
})])
}
fn stripes(ctx: &Ctx) -> CookResult {
let n = ctx.i("count").max(1) as f32;
let (w, soft, ang) = (ctx.f("width"), ctx.f("softness").max(1e-3), ctx.f("angle"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, _) = rot(u - 0.5, v - 0.5, ang);
let f = (x * n).rem_euclid(1.0);
let d = (f - 0.5).abs() * 2.0;
((w - d) / soft + 0.5).clamp(0.0, 1.0)
})])
}
fn tile_params(ctx: &Ctx) -> (f32, f32, f32, f32, f32, f32, f32, f32, u32) {
(
ctx.i("x_amount").max(1) as f32,
ctx.i("y_amount").max(1) as f32,
ctx.f("scale"),
ctx.f("scale_random"),
ctx.f("offset"),
ctx.f("position_random"),
ctx.f("rotation_random"),
ctx.f("lum_random"),
ctx.seed,
)
}
fn tile_generator(ctx: &Ctx) -> CookResult {
let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx);
let (k, sxy, mr) = (ctx.i("pattern"), ctx.v2("size_xy"), ctx.f("mask_random"));
Ok(vec![ctx.gen_gray(|u, v| {
let row = (v * ny).floor();
let mut best: f32 = 0.0;
// Shapes may reach into neighbouring cells (scale > 1, position jitter): check 3×3.
for dj in -1..=1 {
for di in -1..=1 {
let r = row + dj as f32;
let x = u * nx + off * r;
let col = x.floor() + di as f32;
let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32));
if mr > 0.0 && rand2(ci, ri, s ^ 0x55) < mr {
continue;
}
let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr;
let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr;
let size = sc * (1.0 - sr * rand2(ci, ri, s ^ 3));
if size <= 0.0 {
continue;
}
let (lx, ly) = ((x - col - 0.5 - jx) * 2.0, (v * ny - r - 0.5 - jy) * 2.0);
let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr);
let val = shape(k, lx / (size * sxy[0].max(1e-3)), ly / (size * sxy[1].max(1e-3)));
best = best.max(val * (1.0 - lr * rand2(ci, ri, s ^ 5)));
}
}
best
})])
}
fn tile_sampler(ctx: &Ctx) -> CookResult {
let (nx, ny, sc, sr, off, pr, rr, lr, s) = tile_params(ctx);
let pattern =
ctx.input(0).map(|p| p.to_gray()).unwrap_or_else(|| Image::generate_uv(64, 64, Kind::Gray, |u, v| [shape(3, u * 2.0 - 1.0, v * 2.0 - 1.0); 4]));
let smap = ctx.input(1).map(|p| p.to_gray());
let add = ctx.i("blend") == 1;
Ok(vec![ctx.gen_gray(|u, v| {
let row = (v * ny).floor();
let mut acc: f32 = 0.0;
for dj in -1..=1 {
for di in -1..=1 {
let r = row + dj as f32;
let x = u * nx + off * r;
let col = x.floor() + di as f32;
let (ci, ri) = ((col as i32).rem_euclid(nx as i32), (r as i32).rem_euclid(ny as i32));
let jx = (rand2(ci, ri, s ^ 1) - 0.5) * pr;
let jy = (rand2(ci, ri, s ^ 2) - 0.5) * pr;
let mapk = smap.as_ref().map_or(1.0, |m| m.sample_gray((col + 0.5) / nx, (r + 0.5) / ny, true));
let size = sc * mapk * (1.0 - sr * rand2(ci, ri, s ^ 3));
if size <= 0.0 {
continue;
}
let (lx, ly) = ((x - col - 0.5 - jx) / size, (v * ny - r - 0.5 - jy) / size);
let (lx, ly) = rot(lx, ly, (rand2(ci, ri, s ^ 4) - 0.5) * rr);
if lx.abs() > 0.5 || ly.abs() > 0.5 {
continue;
}
let val = pattern.sample_gray(lx + 0.5, ly + 0.5, false) * (1.0 - lr * rand2(ci, ri, s ^ 5));
acc = if add { acc + val } else { acc.max(val) };
}
}
acc.min(1.0)
})])
}
fn weave(ctx: &Ctx) -> CookResult {
let n = ctx.i("tiling").max(1) as f32;
let w = ctx.f("width").clamp(0.01, 1.0);
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = (u * n, v * n);
let (cx, cy) = (x.floor() as i32, y.floor() as i32);
let (fx, fy) = (x.fract(), y.fract());
// Horizontal thread across the cell row, vertical thread down the column; which is on
// top alternates in a checker.
let hthread = ((fy - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fy - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt();
let vthread = ((fx - 0.5).abs() * 2.0 <= w) as i32 as f32 * (1.0 - ((fx - 0.5) * 2.0 / w).powi(2)).max(0.0).sqrt();
let h_top = (cx + cy) & 1 == 0;
// The thread on top bulges along its length.
let hb = hthread * (0.6 + 0.4 * (fx * PI).sin());
let vb = vthread * (0.6 + 0.4 * (fy * PI).sin());
if h_top { hb.max(vb * 0.6) } else { vb.max(hb * 0.6) }
})])
}
fn waveform(ctx: &Ctx) -> CookResult {
let n = ctx.i("count").max(1) as f32;
let (amp, ang) = (ctx.f("amplitude"), ctx.f("angle"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = rot(u - 0.5, v - 0.5, ang);
let w = (y * TAU * 2.0).sin() * amp * 0.1;
((x + w) * TAU * n).sin() * 0.5 + 0.5
})])
}
#[cfg(test)]
#[path = "patterns.test.rs"]
mod tests;
-36
View File
@@ -1,36 +0,0 @@
//! Hostile-parameter tests for the binned pattern generators in `patterns.rs`.
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::Image;
use crate::{Ctx, find, resolve_params};
fn cook(id: &str, over: &[(&str, Value)]) -> Image {
let def = find(id).unwrap();
let over: BTreeMap<String, Value> = over.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
let params = resolve_params(def, &over);
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let inputs = vec![None; def.inputs.len()];
let ctx = Ctx { w: 32, h: 32, seed: 3, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
(def.cook)(&ctx).unwrap().remove(0)
}
fn assert_quick(id: &str, over: &[(&str, Value)]) {
let t = std::time::Instant::now();
let img = cook(id, over);
assert!(img.data.iter().all(|v| v.is_finite()), "{id} produced non-finite values");
assert!(t.elapsed().as_secs() < 20, "{id} took {:?}", t.elapsed());
}
#[test]
fn splatter_huge_size_is_bounded() {
assert_quick("splatter", &[("size", Value::Float(1e6)), ("count", Value::Int(2000))]);
}
#[test]
fn scratches_huge_length_is_bounded() {
assert_quick("scratches", &[("length", Value::Float(1e6)), ("width", Value::Float(1e6)), ("count", Value::Int(5000))]);
}
-532
View File
@@ -1,532 +0,0 @@
//! More Texture generators › Patterns: tilings (herringbone, basketweave, planks, scales,
//! triangles, octagons, tread plate), grids, shapes and gradients. Tile patterns share gap, bevel
//! and luminance-random parameters; every tiling repeats a whole number of times per image.
use std::f32::consts::{SQRT_2, TAU};
use crate::catalog::{B, CookResult, Ctx, NodeDef, node};
use crate::noise::rand2;
use crate::patterns::PATTERNS;
/// Rotate `(x, y)` by `turns`.
#[inline]
fn rot(x: f32, y: f32, turns: f32) -> (f32, f32) {
let (s, c) = (turns * TAU).sin_cos();
(x * c - y * s, x * s + y * c)
}
/// Coverage from a signed inside distance `e`: hard when `soft` is 0, else a ramp of width `soft`.
#[inline]
fn fill(e: f32, soft: f32) -> f32 {
if soft <= 0.0 { (e >= 0.0) as i32 as f32 } else { (e / soft).clamp(0.0, 1.0) }
}
/// A beveled tile from the distance `e` to its edge: `gap` eats the edge, `bevel` ramps up.
#[inline]
fn tile_height(e: f32, t: &TileLook, rnd: f32) -> f32 {
let e = e - t.gap * 0.5;
if e <= 0.0 { 0.0 } else { (e / t.bevel).min(1.0) * (1.0 - t.lum_random * rnd) }
}
/// Soft bands around integer + 0.5 of `t`: `width` 0..1 of each period, `soft` edge.
#[inline]
fn band(t: f32, width: f32, soft: f32) -> f32 {
let d = (t.rem_euclid(1.0) - 0.5).abs() * 2.0;
((width - d) / soft.max(1e-3) + 0.5).clamp(0.0, 1.0)
}
/// Local coordinates -1..1 in an `n`×`n` repetition.
#[inline]
fn tiled(u: f32, v: f32, n: f32) -> (f32, f32) {
((u * n).rem_euclid(1.0) * 2.0 - 1.0, (v * n).rem_euclid(1.0) * 2.0 - 1.0)
}
struct TileLook {
gap: f32,
bevel: f32,
lum_random: f32,
seed: u32,
}
fn look(ctx: &Ctx) -> TileLook {
TileLook { gap: ctx.f("gap"), bevel: ctx.f("bevel").max(1e-4), lum_random: ctx.f("lum_random"), seed: ctx.seed }
}
/// The gap, bevel and luminance-random parameters of tile patterns.
fn with_look(b: B, gap: f32, bevel: f32) -> B {
b.float("gap", "Gap", gap, 0.0, 0.5).float("bevel", "Bevel", bevel, 0.0, 1.0).float("lum_random", "Luminance random", 0.3, 0.0, 1.0)
}
fn n(ctx: &Ctx, id: &str) -> f32 {
ctx.i(id).max(1) as f32
}
pub(crate) fn defs() -> Vec<NodeDef> {
let p = |id, label| node(id, label, PATTERNS).generator();
vec![
p("grid_lines", "Grid Lines")
.desc("A grid of lines.")
.int("tiling", "Tiling", 8, 1, 128)
.float("width", "Line width", 0.06, 0.0, 1.0)
.float("softness", "Softness", 0.0, 0.0, 0.5)
.gray_out()
.cook(grid_lines),
p("dots_grid", "Dots Grid")
.desc("Round dots on a grid (perforated metal, polka dots).")
.int("tiling", "Tiling", 8, 1, 128)
.float("radius", "Diameter", 0.6, 0.0, 1.0)
.float("softness", "Softness", 0.0, 0.0, 0.5)
.boolean("staggered", "Staggered rows", true)
.gray_out()
.cook(dots_grid),
with_look(p("diamond_grid", "Diamond Grid").desc("Beveled diamond (45°) tiles.").int("tiling", "Tiling", 4, 1, 64), 0.05, 0.15)
.gray_out()
.cook(diamond_grid),
with_look(
p("herringbone", "Herringbone").desc("Planks laid in a herringbone pattern.").int("tiling", "Tiling", 2, 1, 32).int(
"length",
"Plank length",
3,
2,
8,
),
0.08,
0.2,
)
.gray_out()
.cook(herringbone),
with_look(
p("basketweave", "Basketweave").desc("Squares of parallel planks alternating direction.").int("tiling", "Tiling", 4, 1, 64).int(
"strips",
"Planks per square",
3,
1,
16,
),
0.08,
0.2,
)
.gray_out()
.cook(basketweave),
p("chevron", "Chevron")
.desc("Zigzag bands.")
.int("count", "Bands", 8, 1, 128)
.int("zigs", "Zigzags", 4, 1, 64)
.float("height", "Zig height", 1.0, 0.0, 8.0)
.float("width", "Width", 0.5, 0.0, 1.0)
.float("softness", "Softness", 0.1, 0.0, 1.0)
.gray_out()
.cook(chevron),
p("fish_scales", "Fish Scales")
.desc("Overlapping rows of round scales (height).")
.int("tiling", "Tiling", 6, 1, 64)
.float("radius", "Radius", 0.65, 0.5, 1.0)
.float("lum_random", "Luminance random", 0.2, 0.0, 1.0)
.gray_out()
.cook(fish_scales),
with_look(p("triangle_grid", "Triangle Grid").desc("Beveled triangle tiles.").int("tiling", "Tiling", 6, 1, 64), 0.04, 0.12)
.gray_out()
.cook(triangle_grid),
p("spiral", "Spiral")
.desc("An Archimedean spiral.")
.float("turns", "Turns", 6.0, 0.0, 64.0)
.float("width", "Width", 0.5, 0.0, 1.0)
.float("softness", "Softness", 0.3, 0.0, 1.0)
.int("tiling", "Tiling", 1, 1, 16)
.gray_out()
.cook(spiral),
p("concentric_rings", "Concentric Rings")
.desc("Rings around the center.")
.float("count", "Rings", 8.0, 0.0, 64.0)
.float("width", "Width", 0.5, 0.0, 1.0)
.float("softness", "Softness", 0.3, 0.0, 1.0)
.int("tiling", "Tiling", 1, 1, 16)
.gray_out()
.cook(concentric_rings),
p("gradient_axial", "Gradient Axial")
.desc("A ramp from point 1 (black) to point 2 (white).")
.float2("point_1", "Point 1", [0.2, 0.5], 0.0, 1.0)
.float2("point_2", "Point 2", [0.8, 0.5], 0.0, 1.0)
.gray_out()
.cook(gradient_axial),
p("gradient_circular", "Gradient Circular")
.desc("A ramp around the center (by angle).")
.angle("angle", "Start angle", 0.0)
.int("tiling", "Tiling", 1, 1, 16)
.gray_out()
.cook(gradient_circular),
p("cross", "Cross")
.desc("A plus-shaped cross.")
.float("length", "Arm length", 0.8, 0.0, 1.0)
.float("thickness", "Thickness", 0.25, 0.0, 1.0)
.float("softness", "Softness", 0.0, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.int("tiling", "Tiling", 1, 1, 32)
.gray_out()
.cook(cross),
p("rounded_rectangle", "Rounded Rectangle")
.desc("A rectangle with rounded corners.")
.float2("size", "Size", [0.8, 0.6], 0.0, 1.0)
.float("radius", "Corner radius", 0.2, 0.0, 1.0)
.float("softness", "Softness", 0.0, 0.0, 1.0)
.angle("angle", "Angle", 0.0)
.int("tiling", "Tiling", 1, 1, 32)
.gray_out()
.cook(rounded_rectangle),
p("ring", "Ring")
.desc("A circular ring.")
.float("radius", "Radius", 0.6, 0.0, 1.0)
.float("width", "Width", 0.15, 0.0, 1.0)
.float("softness", "Softness", 0.05, 0.0, 1.0)
.int("tiling", "Tiling", 1, 1, 32)
.gray_out()
.cook(ring),
with_look(
p("arc_pavement", "Arc Pavement")
.desc("Cobblestones laid in overlapping fan-shaped arcs.")
.int("tiling", "Tiling", 3, 1, 32)
.int("bands", "Rows per arc", 4, 1, 16)
.int("stones", "Stones in outer row", 7, 1, 32),
0.08,
0.25,
)
.gray_out()
.cook(arc_pavement),
with_look(p("octagon_tiles", "Octagon Tiles").desc("Octagons with small square tiles between them.").int("tiling", "Tiling", 4, 1, 64), 0.03, 0.08)
.gray_out()
.cook(octagon_tiles),
with_look(
p("planks", "Planks")
.desc("Rows of floor boards of random length, staggered.")
.int("rows", "Rows", 8, 1, 64)
.float("length", "Plank length", 0.33, 0.02, 1.0)
.float("length_random", "Length random", 0.5, 0.0, 1.0),
0.06,
0.15,
)
.gray_out()
.cook(planks),
p("tread_plate", "Tread Plate")
.desc("Raised diagonal bars alternating direction, like metal floor plates (height).")
.int("tiling", "Tiling", 6, 1, 64)
.float("length", "Bar length", 1.0, 0.0, 1.4)
.float("width", "Bar width", 0.3, 0.01, 1.0)
.gray_out()
.cook(tread_plate),
]
}
fn grid_lines(ctx: &Ctx) -> CookResult {
let (t, w, soft) = (n(ctx, "tiling"), ctx.f("width"), ctx.f("softness"));
Ok(vec![ctx.gen_gray(|u, v| {
let d = |a: f32| {
let f = (a * t).rem_euclid(1.0);
f.min(1.0 - f)
};
fill(w * 0.5 - d(u).min(d(v)), soft)
})])
}
fn dots_grid(ctx: &Ctx) -> CookResult {
let (t, r, soft, stag) = (n(ctx, "tiling"), ctx.f("radius"), ctx.f("softness"), ctx.b("staggered"));
Ok(vec![ctx.gen_gray(|u, v| {
let row = (v * t).floor();
// A parity shift (not row × offset) keeps the pattern seamless for any row count.
let shift = if stag && (row as i32) & 1 == 1 { 0.5 } else { 0.0 };
let (x, y) = ((u * t + shift).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5);
fill(r * 0.5 - (x * x + y * y).sqrt(), soft * 0.5)
})])
}
fn diamond_grid(ctx: &Ctx) -> CookResult {
let (t, l) = (n(ctx, "tiling"), look(ctx));
let ti = t as i32;
Ok(vec![ctx.gen_gray(|u, v| {
let (a, b) = ((u + v) * t, (u - v) * t);
let (fa, fb) = (a.rem_euclid(1.0), b.rem_euclid(1.0));
let e = fa.min(1.0 - fa).min(fb).min(1.0 - fb);
// Canonical diamond index: (A, B) ~ (A + t, B ± t).
let (ia, ib) = (a.floor() as i32, b.floor() as i32);
let k = ib.div_euclid(ti);
tile_height(e, &l, rand2((ia - k * ti).rem_euclid(2 * ti), ib - k * ti, l.seed))
})])
}
fn herringbone(ctx: &Ctx) -> CookResult {
let (t, len, lk) = (n(ctx, "tiling") as i32, ctx.i("length").clamp(2, 8), look(ctx));
let lf = len as f32;
let span = (t * 2 * len) as f32;
// 1 × L planks: a horizontal plank [0, L)×[0, 1) and a vertical one [L, L+1)×[1-L, 1) repeat
// on the lattice m·(1, 1) + n·(L, -L), which has period 2L on both axes.
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = (u * span, v * span);
let (m0, n0) = (((x + y) * 0.5).floor() as i32, ((x - y) / (2.0 * lf)).floor() as i32);
for dm in -(len / 2 + 2)..=1 {
for dn in -2..=1 {
let (m, nn) = (m0 + dm, n0 + dn);
let (qx, qy) = (x - (m + nn * len) as f32, y - (m - nn * len) as f32);
let hit = if (0.0..lf).contains(&qx) && (0.0..1.0).contains(&qy) {
Some((qx.min(lf - qx).min(qy).min(1.0 - qy), 0))
} else if (lf..lf + 1.0).contains(&qx) && (1.0 - lf..1.0).contains(&qy) {
Some(((qx - lf).min(lf + 1.0 - qx).min(qy - 1.0 + lf).min(1.0 - qy), 1))
} else {
None
};
if let Some((e, kind)) = hit {
let k = nn.div_euclid(t);
let (cm, cn) = ((m - k * len * t).rem_euclid(2 * len * t), nn - k * t);
return tile_height(e, &lk, rand2(cm * 2 + kind, cn, lk.seed));
}
}
}
0.0
})])
}
fn basketweave(ctx: &Ctx) -> CookResult {
let (t, strips, l) = (n(ctx, "tiling"), n(ctx, "strips"), look(ctx));
Ok(vec![ctx.gen_gray(|u, v| {
let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32);
let (fx, fy) = ((u * t).rem_euclid(1.0), (v * t).rem_euclid(1.0));
let horizontal = (cx + cy) & 1 == 0;
let (across, along) = if horizontal { (fy * strips, fx * strips) } else { (fx * strips, fy * strips) };
let fa = across.rem_euclid(1.0);
let e = fa.min(1.0 - fa).min(along).min(strips - along);
let id = (cy.rem_euclid(t as i32) * t as i32 + cx.rem_euclid(t as i32)) * 16 + across.floor() as i32;
tile_height(e, &l, rand2(id, 0, l.seed))
})])
}
fn chevron(ctx: &Ctx) -> CookResult {
let (c, z, hgt, w, soft) = (n(ctx, "count"), n(ctx, "zigs"), ctx.f("height"), ctx.f("width"), ctx.f("softness"));
Ok(vec![ctx.gen_gray(|u, v| {
let zig = ((u * z).rem_euclid(1.0) - 0.5).abs() * 2.0;
band(v * c + zig * hgt, w, soft)
})])
}
/// The topmost scale over `(x, y)` (in cells) of a staggered scale layout: rows 0.5 apart, odd
/// rows shifted by half a cell, earlier rows on top. Returns (column, row, dx, dy, d / r).
fn scale_hit(x: f32, y: f32, r: f32) -> Option<(i32, i32, f32, f32, f32)> {
let j0 = ((y - r) * 2.0).floor() as i32;
let j1 = ((y + r) * 2.0).ceil() as i32;
for j in j0..=j1 {
let shift = if j & 1 == 1 { 0.5 } else { 0.0 };
let i = (x - shift).round() as i32;
let (dx, dy) = (x - (i as f32 + shift), y - j as f32 * 0.5);
let d = (dx * dx + dy * dy).sqrt();
if d < r {
return Some((i, j, dx, dy, d / r));
}
}
None
}
fn fish_scales(ctx: &Ctx) -> CookResult {
let (t, r, lr, s) = (n(ctx, "tiling"), ctx.f("radius").clamp(0.5, 1.0), ctx.f("lum_random"), ctx.seed);
let ti = t as i32;
Ok(vec![ctx.gen_gray(|u, v| {
let Some((i, j, _, _, d)) = scale_hit(u * t, v * t, r) else {
return 0.0;
};
(1.0 - d * d).sqrt() * (1.0 - lr * rand2(i.rem_euclid(ti), j.rem_euclid(2 * ti), s))
})])
}
fn triangle_grid(ctx: &Ctx) -> CookResult {
let (t, l) = (n(ctx, "tiling"), look(ctx));
// Rows of near-equilateral triangles; an even row count keeps the half-cell row shift seamless.
let rows = (2.0 * (t * 0.577).round()).max(2.0);
let (ti, ri) = (t as i32, rows as i32);
let k = 2.0 / 5f32.sqrt();
Ok(vec![ctx.gen_gray(|u, v| {
let row = (v * rows).floor() as i32;
let fy = (v * rows).rem_euclid(1.0);
let x = u * t + if row & 1 == 1 { 0.5 } else { 0.0 };
let col = x.floor() as i32;
let dx = x.rem_euclid(1.0) - 0.5;
let (e, id) = if dx.abs() <= fy * 0.5 {
((1.0 - fy).min((fy * 0.5 - dx.abs()) * k), col * 2)
} else {
// A down-pointing triangle centered on the nearer whole column.
let (c, ddx) = if dx < 0.0 { (col, dx + 0.5) } else { (col + 1, dx - 0.5) };
(fy.min(((1.0 - fy) * 0.5 - ddx.abs()) * k), c * 2 + 1)
};
tile_height(e, &l, rand2(id.rem_euclid(2 * ti), row.rem_euclid(ri), l.seed))
})])
}
fn spiral(ctx: &Ctx) -> CookResult {
let (turns, w, soft, t) = (ctx.f("turns"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
let r = (x * x + y * y).sqrt();
if r > 1.0 {
return 0.0;
}
band(r * turns - y.atan2(x) / TAU, w, soft)
})])
}
fn concentric_rings(ctx: &Ctx) -> CookResult {
let (c, w, soft, t) = (ctx.f("count"), ctx.f("width"), ctx.f("softness"), n(ctx, "tiling"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
band((x * x + y * y).sqrt() * c, w, soft)
})])
}
fn gradient_axial(ctx: &Ctx) -> CookResult {
let (a, b) = (ctx.v2("point_1"), ctx.v2("point_2"));
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let len2 = (dx * dx + dy * dy).max(1e-8);
Ok(vec![ctx.gen_gray(|u, v| (((u - a[0]) * dx + (v - a[1]) * dy) / len2).clamp(0.0, 1.0))])
}
fn gradient_circular(ctx: &Ctx) -> CookResult {
let (a, t) = (ctx.f("angle"), n(ctx, "tiling"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
((-y).atan2(x) / TAU - a).rem_euclid(1.0)
})])
}
fn cross(ctx: &Ctx) -> CookResult {
let (len, th, soft, a, t) = (ctx.f("length"), ctx.f("thickness") * 0.5, ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
let (x, y) = rot(x, y, a);
let arm = |p: f32, q: f32| (len - p.abs()).min(th - q.abs());
fill(arm(x, y).max(arm(y, x)), soft)
})])
}
fn rounded_rectangle(ctx: &Ctx) -> CookResult {
let (sz, rad, soft, a, t) = (ctx.v2("size"), ctx.f("radius"), ctx.f("softness"), ctx.f("angle"), n(ctx, "tiling"));
let r = rad.min(sz[0]).min(sz[1]).max(0.0);
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
let (x, y) = rot(x, y, a);
// Signed distance to a rounded box (negative inside).
let (qx, qy) = (x.abs() - sz[0] + r, y.abs() - sz[1] + r);
let d = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r;
fill(-d, soft)
})])
}
fn ring(ctx: &Ctx) -> CookResult {
let (rad, w, soft, t) = (ctx.f("radius"), ctx.f("width") * 0.5, ctx.f("softness"), n(ctx, "tiling"));
Ok(vec![ctx.gen_gray(|u, v| {
let (x, y) = tiled(u, v, t);
fill(w - ((x * x + y * y).sqrt() - rad).abs(), soft)
})])
}
fn arc_pavement(ctx: &Ctx) -> CookResult {
let (t, bands, stones, l) = (n(ctx, "tiling"), n(ctx, "bands"), n(ctx, "stones"), look(ctx));
let ti = t as i32;
let r = 0.75;
Ok(vec![ctx.gen_gray(|u, v| {
let Some((i, j, dx, dy, rr)) = scale_hit(u * t, v * t, r) else {
return 0.0;
};
let band_f = rr * bands;
let k = band_f.floor();
let count = (stones * (k + 0.5) / bands).round().max(1.0);
let a = (dy.atan2(dx) / TAU + 0.5) * count;
let fr = band_f.rem_euclid(1.0);
let fa = a.rem_euclid(1.0);
// Distances in band-width units: radial, and along the arc at this radius.
let e = fr.min(1.0 - fr).min(fa.min(1.0 - fa) * TAU * band_f.max(0.5) / count);
let id = ((j.rem_euclid(2 * ti) * ti + i.rem_euclid(ti)) * 32 + k as i32) * 64 + a.floor() as i32;
tile_height(e, &l, rand2(id, 7, l.seed))
})])
}
fn octagon_tiles(ctx: &Ctx) -> CookResult {
let (t, l) = (n(ctx, "tiling"), look(ctx));
let ti = t as i32;
// A regular octagon in a unit cell: its corner cuts lie on |x| + |y| = 0.5 + side / 2.
let cut = 0.5 + 0.5 / (1.0 + SQRT_2);
Ok(vec![ctx.gen_gray(|u, v| {
let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32);
let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5);
let (ax, ay) = (x.abs(), y.abs());
if ax + ay <= cut {
let e = (0.5 - ax.max(ay)).min((cut - ax - ay) / SQRT_2);
tile_height(e, &l, rand2(cx.rem_euclid(ti), cy.rem_euclid(ti), l.seed))
} else {
// The small square around the nearest cell corner.
let e = (ax + ay - cut) / SQRT_2;
let (kx, ky) = (cx + (x > 0.0) as i32, cy + (y > 0.0) as i32);
tile_height(e, &l, rand2(kx.rem_euclid(ti), ky.rem_euclid(ti), l.seed ^ 0x6d))
}
})])
}
fn planks(ctx: &Ctx) -> CookResult {
let (rows, l) = (n(ctx, "rows"), look(ctx));
let count = (1.0 / ctx.f("length").max(0.02)).round().clamp(1.0, 64.0);
let (ci, ri) = (count as i32, rows as i32);
let jit = ctx.f("length_random").clamp(0.0, 1.0) * 0.4;
let s = ctx.seed;
Ok(vec![ctx.gen_gray(|u, v| {
let row = ((v * rows).floor() as i32).rem_euclid(ri);
let fy = (v * rows).rem_euclid(1.0);
let t = u * count + rand2(row, 0, s ^ 0x11) * count;
// Plank ends: one per whole step of `t`, jittered; indices wrap so each row tiles.
let cut = |j: i32| j as f32 + (rand2(j.rem_euclid(ci), row, s) - 0.5) * 2.0 * jit;
let j = t.floor() as i32;
let j = if t < cut(j) {
j - 1
} else if t >= cut(j + 1) {
j + 1
} else {
j
};
let along = (t - cut(j)).min(cut(j + 1) - t) / count * rows;
let e = along.min(fy).min(1.0 - fy);
tile_height(e, &l, rand2(j.rem_euclid(ci), row, s ^ 0x22))
})])
}
fn tread_plate(ctx: &Ctx) -> CookResult {
let (t, len, w) = (n(ctx, "tiling"), ctx.f("length") * 0.5, ctx.f("width").max(0.01) * 0.5);
Ok(vec![ctx.gen_gray(|u, v| {
let (cx, cy) = ((u * t).floor() as i32, (v * t).floor() as i32);
let (x, y) = ((u * t).rem_euclid(1.0) - 0.5, (v * t).rem_euclid(1.0) - 0.5);
let turn = if (cx + cy) & 1 == 0 { 0.125 } else { -0.125 };
let (x, y) = rot(x, y, turn);
// An elongated lens with a flat top and rounded flanks.
let d = ((x / len.max(1e-3)).powi(2) + (y / w).powi(2)).sqrt();
(1.0 - d.powi(4)).max(0.0).sqrt()
})])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::{Ctx, find, resolve_params};
#[test]
fn tilings_wrap_seamlessly() {
for id in ["herringbone", "planks", "triangle_grid", "fish_scales", "arc_pavement", "diamond_grid", "octagon_tiles"] {
let def = find(id).unwrap();
let params = resolve_params(def, &BTreeMap::new());
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w: 128, h: 128, seed: 5, tile: true, inputs: &[], params: &params, resource: &no_res, vars: &vars };
let img = &(def.cook)(&ctx).unwrap()[0];
// Sampling the pattern one period further along either axis gives the same image: the
// last column/row continues into the first like any interior neighbour.
let (mut seam, mut inner) = (0.0f32, 0.0f32);
for k in 0..128 {
seam += (img.get(127, k, false)[0] - img.get(0, k, false)[0]).abs() + (img.get(k, 127, false)[0] - img.get(k, 0, false)[0]).abs();
inner += (img.get(63, k, false)[0] - img.get(64, k, false)[0]).abs() + (img.get(k, 63, false)[0] - img.get(k, 64, false)[0]).abs();
}
assert!(seam <= inner * 3.0 + 1.0, "{id}: seam {seam} vs inner {inner}");
assert!(img.mean()[0] > 0.05, "{id} is empty");
}
}
}
-487
View File
@@ -1,487 +0,0 @@
//! Atomic › SVG: rasterizes SVG path data (the `d` attribute: M L H V C S Q T Z, absolute and
//! relative) with an even-odd or non-zero fill and an optional stroke. Fill coverage is exact
//! horizontally over four sub-scanlines per pixel. Also the shared capsule (thick line)
//! rasterizer used by the stroke, the Text node and the scratches.
use materialcraft_image::{Image, Kind};
use rayon::prelude::*;
use crate::atomic::ATOMIC;
use crate::catalog::{CookResult, Ctx, NodeDef, node};
/// A leaf with a midrib slit, in 0..100 units.
const DEFAULT_PATH: &str = "M50 4 C80 20 94 55 52 96 L50 90 L48 96 C6 55 20 20 50 4 Z M49 22 Q46 55 50 84 Q54 55 51 22 Z";
/// Most points a path may flatten to (an allocation cap for hostile input).
const MAX_POINTS: usize = 400_000;
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("svg", "SVG", ATOMIC)
.desc("Draws SVG path data (M L H V C S Q T Z, absolute and relative; y points down) filled and optionally stroked, anti-aliased.")
.atomic()
.generator()
.text("path", "Path data", DEFAULT_PATH)
.choice("units", "Units", &["0..1", "0..100"], 1)
.color("fill", "Fill color", [1.0, 1.0, 1.0, 1.0])
.choice("fill_rule", "Fill rule", &["Even-odd", "Non-zero"], 1)
.float("stroke_width", "Stroke width", 0.0, 0.0, 64.0)
.color("stroke", "Stroke color", [0.5, 0.5, 0.5, 1.0])
.color_out()
.cook(svg),
]
}
/// A flattened subpath in path units; `closed` after Z.
#[derive(Clone, Debug, PartialEq)]
pub struct Poly {
pub pts: Vec<[f32; 2]>,
pub closed: bool,
}
struct Lexer<'a> {
s: &'a [u8],
i: usize,
}
impl Lexer<'_> {
fn skip(&mut self) {
while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') {
self.i += 1;
}
}
fn peek(&mut self) -> Option<u8> {
self.skip();
self.s.get(self.i).copied()
}
fn at_number(&mut self) -> bool {
self.peek().is_some_and(|c| c.is_ascii_digit() || matches!(c, b'-' | b'+' | b'.'))
}
fn number(&mut self) -> Result<f32, String> {
self.skip();
let (start, s) = (self.i, self.s);
let digit = |j: usize| s.get(j).is_some_and(u8::is_ascii_digit);
let mut j = start + matches!(s.get(start), Some(b'+' | b'-')) as usize;
let mut digits = 0;
while digit(j) {
j += 1;
digits += 1;
}
if s.get(j) == Some(&b'.') {
j += 1;
while digit(j) {
j += 1;
digits += 1;
}
}
if digits == 0 {
return Err(format!("expected a number at byte {start}"));
}
if matches!(s.get(j), Some(b'e' | b'E')) {
let mut k = j + 1 + matches!(s.get(j + 1), Some(b'+' | b'-')) as usize;
let k0 = k;
while digit(k) {
k += 1;
}
if k > k0 {
j = k;
}
}
let txt = s.get(start..j).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or("");
let v: f32 = txt.parse().map_err(|_| format!("bad number '{txt}' at byte {start}"))?;
if !v.is_finite() {
return Err(format!("number out of range at byte {start}"));
}
self.i = j;
Ok(v)
}
fn pair(&mut self) -> Result<[f32; 2], String> {
Ok([self.number()?, self.number()?])
}
}
/// Builds flattened subpaths while parsing.
struct Pen {
polys: Vec<Poly>,
cur: [f32; 2],
start: [f32; 2],
/// The previous segment's last control point and whether it was cubic (for S and T).
ctrl: Option<([f32; 2], bool)>,
steps_per_unit: f32,
points: usize,
}
impl Pen {
fn push(&mut self, p: [f32; 2]) -> Result<(), String> {
self.points += 1;
if self.points > MAX_POINTS {
return Err(format!("path too complex (over {MAX_POINTS} points)"));
}
match self.polys.last_mut() {
Some(poly) if !poly.closed => poly.pts.push(p),
// Drawing after Z starts a new subpath at the closed one's start.
_ => self.polys.push(Poly { pts: vec![self.start, p], closed: false }),
}
self.cur = p;
Ok(())
}
fn move_to(&mut self, p: [f32; 2]) {
self.polys.push(Poly { pts: vec![p], closed: false });
(self.cur, self.start) = (p, p);
}
/// A Bézier through `ctrl` (2 or 3 points after the current one), flattened in steps of
/// about 1 / `steps_per_unit` along its control polygon.
fn curve(&mut self, ctrl: &[[f32; 2]]) -> Result<(), String> {
let mut pts = vec![self.cur];
pts.extend_from_slice(ctrl);
let len: f32 = pts.windows(2).map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()).sum();
let n = (len * self.steps_per_unit).ceil().clamp(2.0, 256.0) as usize;
for k in 1..=n {
let t = k as f32 / n as f32;
// De Casteljau.
let mut q = pts.clone();
while q.len() > 1 {
q = q.windows(2).map(|w| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t]).collect();
}
self.push(q.first().copied().unwrap_or(self.cur))?;
}
Ok(())
}
fn reflect(&self, cubic: bool) -> [f32; 2] {
match self.ctrl {
Some((c, was_cubic)) if was_cubic == cubic => [2.0 * self.cur[0] - c[0], 2.0 * self.cur[1] - c[1]],
_ => self.cur,
}
}
}
/// Parses SVG path data into flattened subpaths. Curves get about `steps_per_unit` segments per
/// unit of control-polygon length (2..256 per curve). Bad input is an error, never a panic.
pub fn parse_path(d: &str, steps_per_unit: f32) -> Result<Vec<Poly>, String> {
let mut lx = Lexer { s: d.as_bytes(), i: 0 };
let steps_per_unit = if steps_per_unit.is_finite() { steps_per_unit.max(0.0) } else { 0.0 };
let mut pen = Pen { polys: Vec::new(), cur: [0.0; 2], start: [0.0; 2], ctrl: None, steps_per_unit, points: 0 };
let mut prev: Option<u8> = None;
while let Some(c) = lx.peek() {
let op = if c.is_ascii_alphabetic() {
lx.i += 1;
c
} else if lx.at_number() {
// Repeated arguments repeat the command; extra pairs after a move are lines.
match prev {
Some(b'M') => b'L',
Some(b'm') => b'l',
Some(p) if !matches!(p, b'Z' | b'z') => p,
_ => return Err(format!("number without a command at byte {}", lx.i)),
}
} else {
return Err(format!("unexpected '{}' at byte {}", c as char, lx.i));
};
if prev.is_none() && !matches!(op, b'M' | b'm') {
return Err("path data must start with a move (M)".into());
}
let rel = op.is_ascii_lowercase();
let o = if rel { pen.cur } else { [0.0; 2] };
let at = |p: [f32; 2]| [p[0] + o[0], p[1] + o[1]];
let mut ctrl = None;
match op.to_ascii_uppercase() {
b'M' => pen.move_to(at(lx.pair()?)),
b'L' => pen.push(at(lx.pair()?))?,
b'H' => pen.push([lx.number()? + o[0], pen.cur[1]])?,
b'V' => pen.push([pen.cur[0], lx.number()? + o[1]])?,
b'C' => {
let (c1, c2, p) = (at(lx.pair()?), at(lx.pair()?), at(lx.pair()?));
pen.curve(&[c1, c2, p])?;
ctrl = Some((c2, true));
}
b'S' => {
let c1 = pen.reflect(true);
let (c2, p) = (at(lx.pair()?), at(lx.pair()?));
pen.curve(&[c1, c2, p])?;
ctrl = Some((c2, true));
}
b'Q' => {
let (c1, p) = (at(lx.pair()?), at(lx.pair()?));
pen.curve(&[c1, p])?;
ctrl = Some((c1, false));
}
b'T' => {
let c1 = pen.reflect(false);
pen.curve(&[c1, at(lx.pair()?)])?;
ctrl = Some((c1, false));
}
b'Z' => {
if let Some(p) = pen.polys.last_mut() {
p.closed = true;
}
pen.cur = pen.start;
}
b'A' => return Err("arc commands (A) are not supported; use curves".into()),
_ => return Err(format!("unknown command '{}'", op as char)),
}
pen.ctrl = ctrl;
prev = Some(op);
}
Ok(pen.polys)
}
/// Fill coverage (0..1 per pixel, row-major) of polygons in pixel coordinates (each implicitly
/// closed): exact horizontal span coverage on four sub-scanlines per pixel row.
pub(crate) fn fill(w: u32, h: u32, polys: &[Vec<[f32; 2]>], even_odd: bool) -> Vec<f32> {
// Edges as (x0, y0, x1, y1, winding) with y0 < y1.
let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new();
for p in polys {
for (k, a) in p.iter().enumerate() {
let b = p.get(k + 1).or(p.first()).copied().unwrap_or(*a);
if a[1] < b[1] {
edges.push((a[0], a[1], b[0], b[1], 1));
} else if b[1] < a[1] {
edges.push((b[0], b[1], a[0], a[1], -1));
}
}
}
let wu = w as usize;
let rows: Vec<Vec<f32>> = (0..h)
.into_par_iter()
.map(|y| {
let mut row = vec![0.0f32; wu];
let mut xs: Vec<(f32, i32)> = Vec::new();
for s in 0..4 {
let sy = y as f32 + (s as f32 + 0.5) * 0.25;
xs.clear();
xs.extend(edges.iter().filter(|e| e.1 <= sy && sy < e.3).map(|e| (e.0 + (sy - e.1) * (e.2 - e.0) / (e.3 - e.1), e.4)));
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut wind = 0;
for k in 0..xs.len() {
wind += xs[k].1;
let inside = if even_odd { wind & 1 != 0 } else { wind != 0 };
if let (true, Some(next)) = (inside, xs.get(k + 1)) {
add_span(&mut row, xs[k].0, next.0, 0.25);
}
}
}
row
})
.collect();
rows.concat()
}
/// Adds `wt` × the overlap of `[a, b)` with each pixel of `row`.
fn add_span(row: &mut [f32], a: f32, b: f32, wt: f32) {
let n = row.len() as f32;
let (a, b) = (a.clamp(0.0, n), b.clamp(0.0, n));
if b <= a {
return;
}
for px in a.floor() as usize..(b.ceil() as usize).min(row.len()) {
let ov = b.min(px as f32 + 1.0) - a.max(px as f32);
if let Some(v) = row.get_mut(px) {
*v += ov.max(0.0) * wt;
}
}
}
/// A line segment with a weight (its peak coverage).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Seg {
pub a: [f32; 2],
pub b: [f32; 2],
pub wt: f32,
}
/// Thick line segments ("capsules") of radius `r` in pixel space, binned on a grid for fast
/// lookups. Coverage ramps over one pixel at the border (anti-aliased); with `tile` it wraps.
pub(crate) struct Capsules {
segs: Vec<Seg>,
r: f32,
g: usize,
cell: [f32; 2],
bins: Vec<Vec<u32>>,
size: [f32; 2],
tile: bool,
}
impl Capsules {
pub fn new(segs: Vec<Seg>, r: f32, w: u32, h: u32, tile: bool) -> Capsules {
let r = if r.is_finite() { r.max(0.0) } else { 0.0 };
let reach = r + 1.0;
let g = ((w.max(h) as f32 / (reach * 4.0).max(8.0)) as usize).clamp(1, 128);
let cell = [w as f32 / g as f32, h as f32 / g as f32];
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); g * g];
for (i, s) in segs.iter().enumerate() {
if !s.a.iter().chain(&s.b).all(|v| v.is_finite()) {
continue;
}
let span = |a: f32, b: f32, c: f32| {
let lo = ((a.min(b) - reach) / c).floor() as i64;
(lo, (((a.max(b) + reach) / c).floor() as i64).min(lo + g as i64 - 1))
};
let ((x0, x1), (y0, y1)) = (span(s.a[0], s.b[0], cell[0]), span(s.a[1], s.b[1], cell[1]));
for gy in y0..=y1 {
for gx in x0..=x1 {
if !tile && (gx < 0 || gy < 0 || gx >= g as i64 || gy >= g as i64) {
continue;
}
if let Some(b) = bins.get_mut(gy.rem_euclid(g as i64) as usize * g + gx.rem_euclid(g as i64) as usize) {
b.push(i as u32);
}
}
}
}
Capsules { segs, r, g, cell, bins, size: [w as f32, h as f32], tile }
}
/// Coverage (0..1, the strongest segment's weight) at pixel coordinates `(x, y)`.
pub fn coverage(&self, x: f32, y: f32) -> f32 {
let (gx, gy) = (((x / self.cell[0]) as usize).min(self.g - 1), ((y / self.cell[1]) as usize).min(self.g - 1));
let mut best = 0.0f32;
for &i in self.bins.get(gy * self.g + gx).into_iter().flatten() {
let Some(s) = self.segs.get(i as usize) else { continue };
let (mut px, mut py) = (x - s.a[0], y - s.a[1]);
if self.tile {
px -= (px / self.size[0]).round() * self.size[0];
py -= (py / self.size[1]).round() * self.size[1];
}
let (dx, dy) = (s.b[0] - s.a[0], s.b[1] - s.a[1]);
let t = ((px * dx + py * dy) / (dx * dx + dy * dy).max(1e-12)).clamp(0.0, 1.0);
let d = ((px - dx * t).powi(2) + (py - dy * t).powi(2)).sqrt();
best = best.max((self.r - d + 0.5).clamp(0.0, 1.0) * s.wt);
}
best
}
}
/// A color image from fill and stroke coverage over transparent black (premultiplied).
pub(crate) fn composite(
w: u32,
h: u32,
fill: [f32; 4],
cover: impl Fn(u32, u32) -> f32 + Sync,
stroke: [f32; 4],
stroke_cover: impl Fn(u32, u32) -> f32 + Sync,
) -> Image {
Image::generate(w, h, Kind::Color, |x, y| {
let f = cover(x, y).clamp(0.0, 1.0) * fill[3];
let s = stroke_cover(x, y).clamp(0.0, 1.0) * stroke[3];
let k = f * (1.0 - s);
[fill[0] * k + stroke[0] * s, fill[1] * k + stroke[1] * s, fill[2] * k + stroke[2] * s, k + s]
})
}
fn svg(ctx: &Ctx) -> CookResult {
let unit = if ctx.i("units") == 1 { 100.0 } else { 1.0 };
let (sx, sy) = (ctx.w as f32 / unit, ctx.h as f32 / unit);
// About one curve segment per 3 pixels.
let polys = parse_path(ctx.text("path"), sx.max(sy) / 3.0)?;
let rings: Vec<Vec<[f32; 2]>> = polys.iter().map(|p| p.pts.iter().map(|q| [q[0] * sx, q[1] * sy]).collect()).collect();
let cov = fill(ctx.w, ctx.h, &rings, ctx.i("fill_rule") == 0);
let sw = ctx.f("stroke_width").max(0.0) * ctx.w as f32 / 256.0;
let caps = (sw > 0.0).then(|| {
let mut segs = Vec::new();
for (p, ring) in polys.iter().zip(&rings) {
segs.extend(ring.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 }));
if let (true, Some(a), Some(b)) = (p.closed, ring.last(), ring.first()) {
segs.push(Seg { a: *a, b: *b, wt: 1.0 });
}
if ring.len() == 1 {
segs.extend(ring.first().map(|a| Seg { a: *a, b: *a, wt: 1.0 }));
}
}
Capsules::new(segs, sw * 0.5, ctx.w, ctx.h, false)
});
let w = ctx.w as usize;
Ok(vec![composite(
ctx.w,
ctx.h,
ctx.v4("fill"),
|x, y| cov.get(y as usize * w + x as usize).copied().unwrap_or(0.0),
ctx.v4("stroke"),
|x, y| caps.as_ref().map_or(0.0, |c| c.coverage(x as f32 + 0.5, y as f32 + 0.5)),
)])
}
#[cfg(test)]
mod tests {
use super::*;
fn pts(d: &str) -> Vec<Vec<[f32; 2]>> {
parse_path(d, 1.0).unwrap().into_iter().map(|p| p.pts).collect()
}
#[test]
fn parses_lines_absolute_and_relative() {
assert_eq!(pts("M0 0 L10 0 L10 10 Z"), vec![vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]]);
assert_eq!(pts("m1,1 l2,0 0,2 h-2 v-1"), vec![vec![[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0], [1.0, 2.0]]]);
// Extra pairs after M are lines; compact number syntax.
assert_eq!(pts("M0 0 1 1 2-2"), vec![vec![[0.0, 0.0], [1.0, 1.0], [2.0, -2.0]]]);
assert_eq!(pts("M.5.5L1e1-1E0"), vec![vec![[0.5, 0.5], [10.0, -1.0]]]);
assert_eq!(pts("M0 0H5V5H0z M8 8 L9 9").len(), 2);
}
#[test]
fn parses_curves_to_their_endpoints() {
for d in
["M0 0 C0 10 10 10 10 0", "M0 0 c0 10 10 10 10 0", "M0 0 Q5 10 10 0", "M0 0 q5 10 10 0", "M0 0 Q5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 S10 -5 10 0"]
{
let p = pts(d);
let last = *p[0].last().unwrap();
assert!((last[0] - 10.0).abs() < 1e-4 && last[1].abs() < 1e-4, "{d}: {last:?}");
assert!(p[0].len() > 3, "{d} is flattened");
}
// The cubic's midpoint bulges to 7.5.
let p = parse_path("M0 0 C0 10 10 10 10 0", 0.0).unwrap();
assert_eq!(p[0].pts.len(), 3);
assert!((p[0].pts[1][1] - 7.5).abs() < 1e-4);
}
#[test]
fn bad_paths_are_errors() {
for d in ["L0 0", "M0", "M0 0 L1", "M0 0 X1 1", "M0 0 L1 1e99", "M0 0 A1 1 0 0 1 2 2", "5 5", "M0 0 Z 3 4", "M 0 0 L - 1"] {
assert!(parse_path(d, 1.0).is_err(), "{d}");
}
assert!(parse_path("", 1.0).unwrap().is_empty());
assert!(parse_path("M0 0 C1 1 2 2 3 3", f32::NAN).is_ok());
}
#[test]
fn fill_rules_and_coverage() {
let sq = |a: f32, b: f32, ccw: bool| {
let mut v = vec![[a, a], [b, a], [b, b], [a, b]];
if ccw {
v.reverse();
}
v
};
// Square of 4..12 on a 16×16 grid: area 64; a half-pixel edge gives half coverage.
let c = fill(16, 16, &[sq(4.0, 12.0, false)], false);
assert!((c.iter().sum::<f32>() - 64.0).abs() < 1e-3);
let c = fill(16, 16, &[sq(4.5, 12.0, false)], false);
assert!((c[8 * 16 + 4] - 0.5).abs() < 1e-4);
// A hole: even-odd always; non-zero only with opposite winding.
let eo = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], true);
let nz_same = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, false)], false);
let nz_opp = fill(16, 16, &[sq(2.0, 14.0, false), sq(6.0, 10.0, true)], false);
let center = 8 * 16 + 8;
assert_eq!((eo[center], nz_same[center], nz_opp[center]), (0.0, 1.0, 0.0));
}
#[test]
fn default_svg_draws_the_leaf() {
let def = crate::catalog::find("svg").unwrap();
let p = crate::catalog::resolve_params(def, &Default::default());
let no_res = |_: &str| None;
let vars = Default::default();
let ctx = Ctx { w: 64, h: 64, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
let img = &svg(&ctx).unwrap()[0];
let a = img.mean()[3];
assert!(a > 0.2 && a < 0.7, "{a}");
assert!(img.get(20, 32, false)[3] > 0.9 && img.get(2, 2, false)[3] == 0.0);
}
}
-219
View File
@@ -1,219 +0,0 @@
//! Atomic › Text: renders a string with MaterialCraft's own single-stroke vector font, drawn as
//! anti-aliased capsules. The font is original data defined below.
use std::f32::consts::TAU;
use crate::atomic::ATOMIC;
use crate::catalog::{CookResult, Ctx, NodeDef, node};
use crate::svg::{Capsules, Seg, composite};
/// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit
/// pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8
/// the descender. A single pair is a dot. Original design for MaterialCraft.
const GLYPHS: &[(char, &str)] = &[
('A', "062046 1333"),
('B', "06003041423303 3344453606"),
('C', "4130100105163645"),
('D', "06003041453606"),
('E', "40000646 0333"),
('F', "400006 0333"),
('G', "41301001051636454323"),
('H', "0006 4046 0343"),
('I', "1030 2026 1636"),
('J', "4045361605"),
('K', "0006 4004 1346"),
('L', "000646"),
('M', "0600234046"),
('N', "06004640"),
('O', "103041453616050110"),
('P', "06003041423303"),
('Q', "103041453616050110 2446"),
('R', "06003041423303 2346"),
('S', "413010010213334445361605"),
('T', "0040 2026"),
('U', "000516364540"),
('V', "002640"),
('W', "0016233640"),
('X', "0046 4006"),
('Y', "002340 2326"),
('Z', "00400646"),
('a', "4246 4332120305163645"),
('b', "0006 0312324345361605"),
('c', "4332120305163645"),
('d', "4046 4332120305163645"),
('e', "04444332120305163645"),
('f', "4130201116 0232"),
('g', "4247381807 4332120305163645"),
('h', "0006 0312324346"),
('i', "2226 20"),
('j', "3237281807 30"),
('k', "0006 3205 1436"),
('l', "10202536"),
('m', "0206 03122326 23324346"),
('n', "0206 0312324346"),
('o', "123243453616050312"),
('p', "0208 0312324345361605"),
('q', "4248 4332120305163645"),
('r', "0206 04223243"),
('s', "43321203143445361605"),
('t', "10152636 0232"),
('u', "0205163645 4246"),
('v', "022642"),
('w', "0216243642"),
('x', "0246 4206"),
('y', "0226 4218"),
('z', "02420646"),
('0', "103041453616050110 3115"),
('1', "112026 1636"),
('2', "01103041420646"),
('3', "01103041423313 334445361605"),
('4', "36300444"),
('5', "400003334445361605"),
('6', "30100105163645443303"),
('7', "004016"),
('8', "13020110304142331304051636454433"),
('9', "43130201103041453616"),
('.', "26"),
(',', "2617"),
('!', "2024 26"),
('?', "0110304142332324 26"),
(':', "22 26"),
(';', "22 2617"),
('-', "1333"),
('+', "1333 2224"),
('=', "1232 1434"),
('*', "1135 3115 0333"),
('/', "4006"),
('\\', "0046"),
('(', "30212536"),
(')', "10212516"),
('[', "30202636"),
(']', "10202616"),
('<', "410345"),
('>', "014305"),
('\'', "2021"),
('"', "1011 3031"),
('_', "0747"),
('#', "1115 3135 0242 0444"),
('%', "4006 01 45"),
(' ', ""),
];
/// A character's strokes; unknown characters show as `?`.
fn glyph(c: char) -> &'static str {
let find = |c: char| GLYPHS.iter().find(|(g, _)| *g == c).map(|(_, s)| *s);
find(c).or_else(|| find('?')).unwrap_or("")
}
/// The strokes of `s` as polylines in grid units.
fn strokes(s: &str) -> impl Iterator<Item = Vec<[f32; 2]>> + '_ {
s.split(' ')
.filter(|t| !t.is_empty())
.map(|t| t.as_bytes().chunks_exact(2).map(|p| [p[0].saturating_sub(b'0') as f32, p[1].saturating_sub(b'0') as f32]).collect())
}
/// Longest text drawn (an allocation cap).
const MAX_CHARS: usize = 10_000;
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("text", "Text", ATOMIC)
.desc("Draws text with a built-in single-stroke font (A–Z, a–z, 0–9, punctuation). \\n starts a new line.")
.atomic()
.generator()
.text("text", "Text", "MaterialCraft")
.float("size", "Size", 0.09, 0.0, 1.0)
.float2("position", "Position", [0.5, 0.5], 0.0, 1.0)
.choice("alignment", "Alignment", &["Left", "Center", "Right"], 1)
.color("color", "Color", [1.0, 1.0, 1.0, 1.0])
.float("weight", "Stroke weight", 0.7, 0.05, 3.0)
.float("letter_spacing", "Letter spacing", 1.0, 0.0, 5.0)
.float("line_spacing", "Line spacing", 1.0, 0.0, 5.0)
.angle("rotation", "Rotation", 0.0)
.boolean("tiling", "Tiling (wrap at edges)", true)
.color_out()
.cook(text),
]
}
/// The capsule segments of `txt` in pixel space.
fn layout(ctx: &Ctx, txt: &str) -> Vec<Seg> {
let unit = ctx.f("size").max(0.0) * ctx.h as f32 / 8.0;
let (adv, line_h) = (4.0 + 2.0 * ctx.f("letter_spacing"), 10.0 * ctx.f("line_spacing"));
let (align, pos) = (ctx.i("alignment"), ctx.v2("position"));
let (s, c) = (ctx.f("rotation") * TAU).sin_cos();
let anchor = [pos[0] * ctx.w as f32, pos[1] * ctx.h as f32];
let lines: Vec<&str> = txt.split('\n').collect();
// The block is centered vertically on the anchor (cap height of the first line to baseline of the last).
let top = -((lines.len().max(1) - 1) as f32 * line_h + 6.0) * 0.5;
let mut segs = Vec::new();
for (li, line) in lines.iter().enumerate() {
let n = line.chars().count() as f32;
let width = if n > 0.0 { (n - 1.0) * adv + 4.0 } else { 0.0 };
let x0 = match align {
0 => 0.0,
1 => -width * 0.5,
_ => -width,
};
let y0 = top + li as f32 * line_h;
for (ci, ch) in line.chars().enumerate() {
let gx = x0 + ci as f32 * adv;
for stroke in strokes(glyph(ch)) {
let px: Vec<[f32; 2]> = stroke
.iter()
.map(|p| {
let (x, y) = ((gx + p[0]) * unit, (y0 + p[1]) * unit);
[anchor[0] + x * c + y * s, anchor[1] - x * s + y * c]
})
.collect();
match px.as_slice() {
[a] => segs.push(Seg { a: *a, b: *a, wt: 1.0 }),
_ => segs.extend(px.windows(2).map(|w| Seg { a: w[0], b: w[1], wt: 1.0 })),
}
}
}
}
segs
}
fn text(ctx: &Ctx) -> CookResult {
let txt: String = ctx.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect();
let r = ctx.f("weight").max(0.0) * ctx.f("size").max(0.0) * ctx.h as f32 / 16.0;
let caps = Capsules::new(layout(ctx, &txt), r, ctx.w, ctx.h, ctx.b("tiling"));
Ok(vec![composite(ctx.w, ctx.h, ctx.v4("color"), |x, y| caps.coverage(x as f32 + 0.5, y as f32 + 0.5), [0.0; 4], |_, _| 0.0)])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::catalog::{find, resolve_params};
#[test]
fn font_data_is_well_formed() {
for (c, s) in GLYPHS {
for t in s.split(' ').filter(|t| !t.is_empty()) {
assert!(t.len() % 2 == 0 && t.bytes().all(|b| b.is_ascii_digit()), "{c:?}: {t}");
assert!(t.as_bytes().chunks(2).all(|p| p[0] <= b'4' && p[1] <= b'8'), "{c:?}: {t} leaves the grid");
}
}
for c in ('A'..='Z').chain('a'..='z').chain('0'..='9') {
assert!(GLYPHS.iter().any(|(g, _)| *g == c), "{c} missing");
}
}
#[test]
fn renders_material_craft() {
let def = find("text").unwrap();
let p = resolve_params(def, &BTreeMap::new());
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let ctx = Ctx { w: 256, h: 256, seed: 0, tile: true, inputs: &[], params: &p, resource: &no_res, vars: &vars };
let img = &text(&ctx).unwrap()[0];
let lit = img.data.chunks(4).filter(|p| p[3] > 0.5).count();
assert!(lit > 300, "{lit} pixels");
// Centered: nothing in the top and bottom quarters.
assert!((0..256).all(|x| img.get(x, 20, false)[3] == 0.0 && img.get(x, 236, false)[3] == 0.0));
}
}
-300
View File
@@ -1,300 +0,0 @@
//! Wear and weathering: cracks, paint strokes, scratches along a direction field, rust, moss and
//! lichen, leaks (drips running down from a mask) and chipped edges. The generators tile.
use std::f32::consts::{PI, TAU};
use materialcraft_image::{Image, Kind};
use rayon::prelude::*;
use crate::catalog::{CookResult, Ctx, NodeDef, PortKind, node};
use crate::fx_map::{BLENDS, Inst, splat};
use crate::generators::NOISES;
use crate::noise::{cellular, fbm, rand1, value, value_xy};
use crate::noises_more::smoothstep;
use crate::ops;
use crate::patterns::PATTERNS;
use crate::svg::{Capsules, Seg};
const WEATHER: &str = "Material filters/Weathering";
pub(crate) fn defs() -> Vec<NodeDef> {
vec![
node("cracks", "Cracks", NOISES)
.desc("A connected network of thin cracks along warped cell borders, with finer branching cracks. White = crack.")
.generator()
.float("scale", "Scale", 5.0, 1.0, 32.0)
.float("width", "Width", 1.5, 0.0, 16.0)
.float("warp", "Warp", 0.5, 0.0, 1.0)
.float("branches", "Branches", 0.5, 0.0, 1.0)
.gray_out()
.cook(cracks),
node("paint_strokes", "Paint Strokes", PATTERNS)
.desc("Overlapping brush strokes with bristle streaks and ragged ends.")
.generator()
.int("count", "Count", 150, 1, 5000)
.float("length", "Length", 0.35, 0.0, 1.0)
.float("width", "Width", 0.07, 0.0, 0.5)
.angle("angle", "Angle", 0.0)
.float("angle_random", "Angle random", 0.08, 0.0, 1.0)
.int("bristles", "Bristles", 20, 1, 256)
.float("luminance_random", "Luminance random", 0.5, 0.0, 1.0)
.choice("blending", "Blending", BLENDS, 2)
.gray_out()
.cook(paint_strokes),
node("scratches_generator", "Scratches Generator", PATTERNS)
.desc("Thin tapered scratches that bend along a direction field (gray = angle in turns) and land where the mask is bright.")
.generator()
.gray_in("direction", "Direction field")
.gray_in("mask", "Mask")
.int("count", "Count", 200, 0, 5000)
.float("length", "Length", 0.25, 0.0, 1.0)
.float("width", "Width", 1.0, 0.1, 16.0)
.angle("angle", "Angle", 0.0)
.float("angle_random", "Angle random", 0.15, 0.0, 1.0)
.float("curvature", "Curvature", 0.1, 0.0, 1.0)
.float("field_intensity", "Field intensity", 0.25, 0.0, 1.0)
.float("luminance_random", "Luminance random", 0.6, 0.0, 1.0)
.gray_out()
.cook(scratches_generator),
node("rust", "Rust", WEATHER)
.desc("A mask of rust blotches and pitting; with a mask input it grows out from the mask (edges, cavities).")
.generator()
.gray_in("mask", "Mask (optional)")
.float("amount", "Amount", 0.45, 0.0, 1.0)
.float("scale", "Scale", 6.0, 1.0, 64.0)
.float("spread", "Spread", 12.0, 0.0, 128.0)
.float("pitting", "Pitting", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.7, 0.0, 1.0)
.gray_out()
.cook(rust),
node("moss", "Moss / Lichen", WEATHER)
.desc("Fuzzy moss clumps (gathering in low areas) or round lichen rosettes (on high areas) of an optional height map.")
.generator()
.gray_in("height", "Height (optional)")
.choice("style", "Style", &["Moss", "Lichen"], 0)
.float("amount", "Amount", 0.5, 0.0, 1.0)
.float("scale", "Scale", 6.0, 1.0, 64.0)
.float("height_bias", "Height bias", 0.5, 0.0, 1.0)
.float("contrast", "Contrast", 0.6, 0.0, 1.0)
.gray_out()
.cook(moss),
node("leaks", "Leaks", WEATHER)
.desc("Streaky drips running down from a mask (unconnected: random stains), fading with length and meandering.")
.gray_in("mask", "Mask")
.float("length", "Length", 0.35, 0.0, 1.0)
.float("length_random", "Length random", 0.7, 0.0, 1.0)
.float("streaks", "Streaks", 32.0, 1.0, 256.0)
.float("wobble", "Wobble", 0.3, 0.0, 1.0)
.gray_out()
.cook(leaks),
node("edge_damage", "Edge Damage", WEATHER)
.desc("Chips the edges of a height mask (white = material) in chunky, ragged bites; also outputs the damage mask.")
.gray_in("height", "Height")
.float("width", "Width", 8.0, 0.0, 64.0)
.float("amount", "Amount", 0.5, 0.0, 1.0)
.float("scale", "Chip scale", 12.0, 1.0, 64.0)
.float("roughness", "Roughness", 0.5, 0.0, 1.0)
.float("depth", "Depth", 1.0, 0.0, 1.0)
.gray_out()
.output("mask", "Damage mask", PortKind::Gray)
.cook(edge_damage),
]
}
/// `v` pixels at 256 px, at the output size.
fn px(ctx: &Ctx, v: f32) -> f32 {
v * ctx.w as f32 / 256.0
}
fn whole(ctx: &Ctx, id: &str) -> f32 {
ctx.f(id).max(1.0).round()
}
/// A soft threshold: 1 where `v` is above `1 - amount`; `contrast` 1 is hard, 0 soft.
fn thresh(v: f32, amount: f32, contrast: f32) -> f32 {
let soft = (1.0 - contrast.clamp(0.0, 1.0)) * 0.25 + 0.005;
smoothstep(1.0 - amount - soft, 1.0 - amount + soft, v)
}
/// A gray image from `f(pixel index, u, v)`.
fn gen_px(ctx: &Ctx, f: impl Fn(usize, f32, f32) -> f32 + Sync) -> Image {
let (w, h) = (ctx.w.max(1), ctx.h.max(1));
Image::generate(w, h, Kind::Gray, |x, y| [f(y as usize * w as usize + x as usize, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32), 0.0, 0.0, 0.0])
}
fn cracks(ctx: &Ctx) -> CookResult {
let (s, wpx, warp, br, seed) = (whole(ctx, "scale"), px(ctx, ctx.f("width")), ctx.f("warp"), ctx.f("branches"), ctx.seed);
let cell_px = ctx.w as f32 / s;
Ok(vec![ctx.gen_gray(|u, v| {
// Broad bends plus fine jaggedness, both in cell units.
let k = warp / s;
let wu = u + (fbm(u, v, 4.0, 4, 0.5, seed ^ 11) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 14) - 0.5) * 0.3 * k;
let wv = v + (fbm(u, v, 4.0, 4, 0.5, seed ^ 12) - 0.5) * 2.0 * k + (fbm(u, v, s * 4.0, 3, 0.5, seed ^ 15) - 0.5) * 0.3 * k;
let line = |m: f32, sd: u32, half: f32| {
let c = cellular(wu * s * m, wv * s * m, (s * m) as i32, 1.0, 0, sd);
1.0 - smoothstep(half, half + 1.0, (c.f2 - c.f1) * 0.5 * cell_px / m)
};
let main = line(1.0, seed, wpx * 0.5);
if br <= 0.0 {
return main;
}
let keep = smoothstep(1.0 - br, 1.0 - br + 0.2, fbm(u, v, s, 3, 0.5, seed ^ 13));
main.max(line(3.0, seed ^ 7, wpx * 0.3) * keep * 0.8)
})])
}
fn paint_strokes(ctx: &Ctx) -> CookResult {
let (len, wid, ang, ar, lr, s) = (ctx.f("length"), ctx.f("width"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("luminance_random"), ctx.seed);
let bristles = ctx.i("bristles").clamp(1, 256) as f32;
let items: Vec<Inst> = (0..ctx.i("count").clamp(1, 5000) as u32)
.map(|i| {
let r = |k: u32| rand1(i * 8 + k, s);
Inst {
c: [r(0), r(1)],
r: [len * 0.5 * (0.7 + 0.3 * r(2)), wid * 0.5 * (0.8 + 0.4 * r(3))],
rot: ang + (r(4) - 0.5) * ar,
lum: 1.0 - lr * r(5),
pat: 0,
}
})
.collect();
Ok(vec![splat(ctx, &items, ctx.i("blending"), |i, x, y| {
let sd = s ^ (i as u32).wrapping_mul(0x9e37_79b9);
// Bristle density across the stroke; the ends are ragged per bristle.
let b = value(y * bristles + 0.5, 0.5, 0, sd);
let ragged = value(y * bristles * 0.5 + 3.1, x * 2.0, 0, sd ^ 1);
let end = 1.0 - smoothstep(0.55 + 0.4 * ragged, 1.0, x.abs());
let edge = 1.0 - smoothstep(0.7, 1.0, y.abs());
end * edge * (0.45 + 0.55 * b)
})])
}
fn scratches_generator(ctx: &Ctx) -> CookResult {
const STEPS: u32 = 12;
let (len, ang, ar, curv, fi, lr, s) =
(ctx.f("length"), ctx.f("angle"), ctx.f("angle_random"), ctx.f("curvature"), ctx.f("field_intensity"), ctx.f("luminance_random"), ctx.seed);
let (field, mask) = (ctx.input(0), ctx.input(1));
let (w, h) = (ctx.w as f32, ctx.h as f32);
let mut segs = Vec::new();
for i in 0..ctx.i("count").clamp(0, 5000) as u32 {
let r = |k: u32| rand1(i * 8 + k, s);
let mut p = [r(0), r(1)];
if mask.is_some_and(|m| r(2) >= m.sample_gray(p[0], p[1], ctx.tile)) {
continue;
}
let (base, bend, lum) = (ang + (r(3) - 0.5) * ar, (r(4) - 0.5) * curv, 1.0 - lr * r(6));
let step = len * (0.4 + 0.6 * r(5)) / STEPS as f32;
for k in 0..STEPS {
let t = k as f32 / STEPS as f32;
let a = (base + bend * t + field.map_or(0.0, |f| f.sample_gray(p[0], p[1], ctx.tile) * fi)) * TAU;
let q = [p[0] + a.cos() * step, p[1] - a.sin() * step];
let taper = ((t + 0.5 / STEPS as f32) * PI).sin().sqrt();
segs.push(Seg { a: [p[0] * w, p[1] * h], b: [q[0] * w, q[1] * h], wt: lum * taper });
p = q;
}
}
let caps = Capsules::new(segs, px(ctx, ctx.f("width")) * 0.5, ctx.w, ctx.h, ctx.tile);
Ok(vec![Image::generate(ctx.w, ctx.h, Kind::Gray, |x, y| [caps.coverage(x as f32 + 0.5, y as f32 + 0.5), 0.0, 0.0, 0.0])])
}
fn rust(ctx: &Ctx) -> CookResult {
let (amt, s, pit, con, seed) = (ctx.f("amount"), whole(ctx, "scale"), ctx.f("pitting"), ctx.f("contrast"), ctx.seed);
let grow = ctx.sized(0).map(|m| ops::gaussian(&m.to_gray(), px(ctx, ctx.f("spread")), ctx.tile));
Ok(vec![gen_px(ctx, |i, u, v| {
let blotch = fbm(u, v, s, 6, 0.55, seed);
let base = match &grow {
Some(g) => 0.5 * blotch + 0.6 * g.data.get(i).copied().unwrap_or(0.0),
None => blotch,
};
let c = cellular(u * s * 8.0, v * s * 8.0, (s * 8.0) as i32, 1.0, 0, seed ^ 3);
let pits = (1.0 - smoothstep(0.05, 0.4, c.f1)) * (c.id < pit) as i32 as f32;
// Pits speckle the surroundings of the blotches only.
thresh(base + pits * 0.2 * smoothstep(0.3, 0.5, base), amt, con) * (0.7 + 0.3 * fbm(u, v, s * 16.0, 3, 0.6, seed ^ 5))
})])
}
fn moss(ctx: &Ctx) -> CookResult {
let (lichen, amt, s, bias, con, seed) = (ctx.i("style") == 1, ctx.f("amount"), whole(ctx, "scale"), ctx.f("height_bias"), ctx.f("contrast"), ctx.seed);
let hgt = ctx.sized(0).map(|h| h.to_gray());
Ok(vec![gen_px(ctx, |i, u, v| {
let hb = hgt.as_ref().map_or(0.0, |h| (h.data.get(i).copied().unwrap_or(0.5) - 0.5) * bias);
let fine = |m: f32, sd: u32| value(u * s * m, v * s * m, (s * m) as i32, seed ^ sd);
if !lichen {
// Fuzzy clumps, thicker in low areas.
let clump = fbm(u, v, s, 5, 0.6, seed) - hb + (fine(24.0, 9) - 0.5) * 0.25;
return thresh(clump, amt, con) * (0.55 + 0.45 * fine(48.0, 10));
}
// Round rosettes with brighter rims, on high areas.
let c = cellular(u * s, v * s, s as i32, 0.9, 0, seed);
if c.id >= amt * 1.4 + hb {
return 0.0;
}
let rad = (0.25 + 0.35 * (c.id * 7.31).fract()) * (0.8 + 0.4 * fbm(u, v, s * 8.0, 3, 0.5, seed ^ 4));
let soft = 0.01 + (1.0 - con) * 0.06;
(1.0 - smoothstep(rad - soft, rad, c.f1)) * (0.55 + 0.45 * smoothstep(rad * 0.4, rad, c.f1)) * (0.8 + 0.2 * fine(32.0, 6))
})])
}
fn leaks(ctx: &Ctx) -> CookResult {
let (w, h, seed) = (ctx.w as usize, ctx.h as usize, ctx.seed);
let src = match ctx.sized(0) {
Some(m) => m.to_gray(),
None => ctx.gen_gray(|u, v| smoothstep(0.62, 0.7, fbm(u, v, 4.0, 4, 0.5, seed ^ 21))),
};
let (len, lr, streaks, wob) = (ctx.f("length").max(0.0) * h as f32, ctx.f("length_random"), whole(ctx, "streaks"), ctx.f("wobble"));
// Each column carries its value down, fading over a length that varies across columns.
let cols: Vec<Vec<f32>> = (0..w)
.into_par_iter()
.map(|x| {
let u = (x as f32 + 0.5) / w as f32;
let r = 0.6 * value(u * streaks, 0.5, streaks as i32, seed ^ 23) + 0.4 * value(u * streaks * 4.0, 0.5, (streaks * 4.0) as i32, seed ^ 24);
let decay = (-3.0 / (len * (1.0 - lr * r)).max(1.0)).exp();
let mut col = vec![0.0f32; h];
let mut acc = 0.0f32;
// Tiling: a second pass carries drips over the bottom edge to the top.
let passes = if ctx.tile { 2 } else { 1 };
for pass in 0..passes {
for (y, out) in col.iter_mut().enumerate() {
acc = src.data.get(y * w + x).copied().unwrap_or(0.0).max(acc * decay);
if pass + 1 == passes {
*out = acc;
}
}
}
col
})
.collect();
let run = Image::gray(ctx.w, ctx.h, |x, y| cols.get(x as usize).and_then(|c| c.get(y as usize)).copied().unwrap_or(0.0));
Ok(vec![ctx.gen_gray(|u, v| {
let dx = (fbm(u, v, 8.0, 3, 0.5, seed ^ 22) - 0.5) * wob * 0.04;
run.sample_gray(u + dx, v, ctx.tile) * (0.75 + 0.25 * value_xy(u * streaks * 2.0, v * 3.0, (streaks * 2.0) as i32, 3, seed ^ 25))
})])
}
fn edge_damage(ctx: &Ctx) -> CookResult {
let hgt = ctx.gray_or(0, 0.0);
let data = hgt.data.clone();
let solid = |i: usize| data.get(i).is_some_and(|v| *v > 0.5);
let dist = ops::distance_sq(ctx.w, ctx.h, |i| !solid(i), ctx.tile);
let (wpx, amt, s, rough, depth, seed) = (px(ctx, ctx.f("width")), ctx.f("amount"), whole(ctx, "scale"), ctx.f("roughness"), ctx.f("depth"), ctx.seed);
let mask = gen_px(ctx, |i, u, v| {
if !solid(i) {
return 0.0;
}
let d = dist.get(i).map_or(0.0, |d| d.sqrt());
// Chunky bites per cell, made ragged by noise.
let c = cellular(u * s, v * s, s as i32, 1.0, 0, seed);
let r = c.id * (1.0 - rough * 0.5) + (fbm(u, v, s * 2.0, 4, 0.5, seed ^ 3) - 0.5) * rough * 1.5;
let reach = wpx * 2.0 * amt * r.max(0.0);
1.0 - smoothstep(reach - 0.75, reach + 0.75, d)
});
let out = Image::gray(ctx.w, ctx.h, |x, y| {
let i = (y * ctx.w + x) as usize;
data.get(i).copied().unwrap_or(0.0) * (1.0 - depth * mask.data.get(i).copied().unwrap_or(0.0))
});
Ok(vec![out, mask])
}
#[cfg(test)]
#[path = "weathering.test.rs"]
mod tests;
-34
View File
@@ -1,34 +0,0 @@
//! Tiling tests for the weathering nodes.
use std::collections::BTreeMap;
use crate::{Ctx, find, resolve_params};
/// Mean absolute difference across the wrap versus across every interior neighbour pair, per axis.
fn wrap_vs_interior(id: &str) -> [(f32, f32); 2] {
let def = find(id).unwrap();
let params = resolve_params(def, &BTreeMap::new());
let no_res = |_: &str| None;
let vars = BTreeMap::new();
let inputs = vec![Some(materialcraft_image::Image::filled(64, 64, materialcraft_image::Kind::Gray, [1.0; 4])); def.inputs.len()];
let ctx = Ctx { w: 64, h: 64, seed: 9, tile: true, inputs: &inputs, params: &params, resource: &no_res, vars: &vars };
let img = (def.cook)(&ctx).unwrap().remove(0);
let g = |x: i64, y: i64| img.get(x, y, false)[0];
let (mut hw, mut hi, mut vw, mut vi) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
for k in 0..64 {
hw += (g(63, k) - g(0, k)).abs();
vw += (g(k, 63) - g(k, 0)).abs();
for j in 0..63 {
hi += (g(j, k) - g(j + 1, k)).abs() / 63.0;
vi += (g(k, j) - g(k, j + 1)).abs() / 63.0;
}
}
[(hw, hi), (vw, vi)]
}
#[test]
fn leaks_tile_in_both_directions() {
for (axis, (wrap, interior)) in wrap_vs_interior("leaks").into_iter().enumerate() {
assert!(wrap <= interior * 3.0 + 0.5, "axis {axis}: wrap {wrap} vs interior {interior}");
}
}
Binary file not shown.
-459
View File
@@ -1,459 +0,0 @@
//! The function graph editor: a window with a small node canvas for a pixel or value
//! processor's function. Right-click (or Space) adds operations by category, dragging from an
//! output to an input wires them, the starred node is the result. Each change commits the whole
//! function through `graph.node.param`.
use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::NodeId;
use materialcraft_engine::core::Value;
use materialcraft_engine::core::function::{FnGraph, FnNode};
use materialcraft_engine::nodes::function::FN_OPS;
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
const W: f32 = 130.0;
const HEADER: f32 = 18.0;
const ROW: f32 = 18.0;
/// The open editor: which node's parameter, and the canvas camera.
pub struct FnEditor {
pub node: NodeId,
pub param: String,
pan: Vec2,
zoom: f32,
drag: Option<FnDrag>,
menu_at: Pos2,
/// The camera has been fitted to the nodes.
framed: bool,
}
enum FnDrag {
Node(u32, Vec2),
Wire(u32),
Pan,
}
impl FnEditor {
pub fn new(node: NodeId, param: &str) -> FnEditor {
FnEditor { node, param: param.into(), pan: vec2(-40.0, -40.0), zoom: 1.0, drag: None, menu_at: Pos2::ZERO, framed: false }
}
}
fn arity(op: &str) -> usize {
FN_OPS.iter().find(|o| o.0 == op).map_or(0, |o| o.2)
}
fn label(op: &str) -> &'static str {
FN_OPS.iter().find(|o| o.0 == op).map_or("?", |o| o.1)
}
fn category_color(op: &str) -> Color32 {
match FN_OPS.iter().find(|o| o.0 == op).map_or("", |o| o.3) {
"Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e),
"Variables" => Color32::from_rgb(0x6d, 0x52, 0xb5),
"Samplers" => Color32::from_rgb(0xa8, 0x3c, 0x34),
"Vector" | "Cast" => Color32::from_rgb(0x3a, 0x66, 0xb0),
"Operator" => Color32::from_rgb(0x3b, 0x7f, 0x4c),
"Logical" | "Comparison" | "Control" => Color32::from_rgb(0xb3, 0x5a, 0x2c),
_ => Color32::from_rgb(0x1e, 0x8a, 0xa0),
}
}
/// The value a new node of `op` starts with.
fn default_value(op: &str) -> Option<Value> {
Some(match op {
"const_float" => Value::Float(0.5),
"const_float2" => Value::Float2([0.5, 0.5]),
"const_float3" => Value::Float3([0.5, 0.5, 0.5]),
"const_float4" => Value::Float4([0.5, 0.5, 0.5, 1.0]),
"const_int" => Value::Int(1),
"const_bool" => Value::Bool(true),
"get_var" => Value::Text(String::new()),
"sample_gray" | "sample_color" => Value::Int(0),
"swizzle" => Value::Text("x".into()),
_ => return None,
})
}
fn node_rect(n: &FnNode) -> Rect {
let rows = arity(&n.op).max(1) as f32 + if n.value.is_some() { 1.0 } else { 0.0 };
Rect::from_min_size(pos2(n.pos[0], n.pos[1]), vec2(W, HEADER + rows * ROW + 6.0))
}
fn in_port(r: Rect, i: usize) -> Pos2 {
pos2(r.left(), r.top() + HEADER + ROW * (i as f32 + 0.5))
}
fn out_port(r: Rect) -> Pos2 {
pos2(r.right(), r.top() + HEADER + ROW * 0.5)
}
/// The function currently stored on the node: a function parameter, or (`fn:<param>`) the
/// function driving a dynamic parameter.
fn current(app: &MaterialCraftApp, e: &FnEditor) -> Option<FnGraph> {
let n = app.session.graph().ok()?.node(e.node).ok()?;
if let Some(p) = e.param.strip_prefix("fn:") {
return n.functions.get(p).cloned();
}
match n.params.get(&e.param) {
Some(Value::Function(f)) => Some((**f).clone()),
_ => materialcraft_engine::nodes::find(&n.def)?.param(&e.param).and_then(|p| match &p.default {
Value::Function(f) => Some((**f).clone()),
_ => None,
}),
}
}
fn commit(app: &mut MaterialCraftApp, node: NodeId, param: &str, g: &FnGraph) {
if let Some(p) = param.strip_prefix("fn:") {
app.run("graph.node.function", json!({"id": node.0, "param": p, "function": g}));
return;
}
let v = serde_json::to_value(Value::Function(Box::new(g.clone()))).unwrap_or(serde_json::Value::Null);
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": v}));
}
/// Add a function node of `op` to the open function editor (the library's Function nodes).
/// Returns false when no function graph is open.
pub fn add_op(app: &mut MaterialCraftApp, op: &str) -> bool {
let Some(e) = app.fn_editor.as_ref() else { return false };
let (node, param) = (e.node, e.param.clone());
let Some(mut g) = current(app, e) else { return false };
if !FN_OPS.iter().any(|o| o.0 == op) || g.nodes.len() >= 10_000 {
return false;
}
let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1);
// Below the lowest node, so new nodes never stack on one another.
let bottom = g.nodes.iter().map(|n| n.pos[1]).fold(-ROW * 4.0, f32::max) + ROW * 4.0;
let left = g.nodes.iter().map(|n| n.pos[0]).fold(0.0, f32::min);
g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [left, bottom] });
if g.output.is_none() {
g.output = Some(id);
}
commit(app, node, &param, &g);
true
}
/// Draw the editor window when one is open.
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
let Some(mut e) = app.fn_editor.take() else { return };
let Some(mut g) = current(app, &e) else { return };
let title = app.session.graph().ok().and_then(|gr| gr.node(e.node).ok()).map(crate::graph_view::node_label).unwrap_or_default();
let mut open = true;
let mut changed = false;
let what = e.param.strip_prefix("fn:").map_or_else(|| tr("Function graph").to_string(), |p| format!("{} {p}", tr("Function of")));
egui::Window::new(format!("{title} - {what}"))
.id(egui::Id::unique(("fn-editor", e.node.0, e.param.as_str())))
.open(&mut open)
.default_size(vec2(760.0, 460.0))
.resizable(true)
.show(ctx, |ui| {
let tk = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(tr("Right-click or Space to add operations; drag from an output dot to an input; the starred node is the result."))
.size(11.0)
.color(tk.text_dim),
);
});
changed = canvas(&mut e, &mut g, ui);
});
if changed {
commit(app, e.node, &e.param, &g);
}
if open {
app.fn_editor = Some(e);
}
}
fn canvas(e: &mut FnEditor, g: &mut FnGraph, ui: &mut Ui) -> bool {
let tk = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Function graph");
let p = ui.painter_at(rect);
p.rect_filled(rect, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c));
if !e.framed {
e.framed = true;
let b = g.nodes.iter().map(node_rect).fold(Rect::NOTHING, |a, r| a.union(r));
if b.is_finite() && b.width() > 0.0 {
let b = b.expand(30.0);
e.zoom = (rect.width() / b.width()).min(rect.height() / b.height()).clamp(0.3, 1.2);
e.pan = b.center().to_vec2() - rect.size() * 0.5 / e.zoom;
}
}
let to_s = |q: Pos2, e: &FnEditor| rect.min + (q.to_vec2() - e.pan) * e.zoom;
let to_g = |s: Pos2, e: &FnEditor| ((s - rect.min) / e.zoom + e.pan).to_pos2();
let mut changed = false;
let pointer = ui.input(|i| i.pointer.hover_pos());
// Zoom and pan.
if resp.hovered() {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
if scroll.abs() > 0.0
&& let Some(ptr) = pointer
{
let before = to_g(ptr, e);
e.zoom = (e.zoom * (scroll * 0.0025).exp()).clamp(0.3, 2.5);
e.pan = before.to_vec2() - (ptr - rect.min) / e.zoom;
}
}
// Wires.
for n in &g.nodes {
let r = node_rect(n);
for (i, src) in n.inputs.iter().enumerate() {
if let Some(s) = src.and_then(|s| g.node(s)) {
let a = to_s(out_port(node_rect(s)), e);
let b = to_s(in_port(r, i), e);
let dx = ((b.x - a.x).abs() * 0.5).max(24.0);
p.add(egui::epaint::CubicBezierShape::from_points_stroke(
[a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b],
false,
Color32::TRANSPARENT,
Stroke::new(2.0, Color32::from_gray(0xb4)),
));
}
}
}
// Nodes.
let font = FontId::proportional((11.0 * e.zoom).clamp(7.0, 16.0));
let mut remove: Option<u32> = None;
let mut set_output: Option<u32> = None;
let mut ports: Vec<(u32, Option<usize>, Pos2)> = Vec::new();
let ids: Vec<u32> = g.nodes.iter().map(|n| n.id).collect();
for id in ids {
let Some(idx) = g.nodes.iter().position(|n| n.id == id) else { continue };
let mut r = node_rect(&g.nodes[idx]);
if let Some(FnDrag::Node(d, delta)) = &e.drag
&& *d == id
{
r = r.translate(*delta);
}
let sr = Rect::from_min_max(to_s(r.min, e), to_s(r.max, e));
let n = &g.nodes[idx];
let is_out = g.output == Some(id);
p.rect_filled(sr, 5.0, Color32::from_rgb(0x1e, 0x20, 0x24));
let header = Rect::from_min_size(sr.min, vec2(sr.width(), HEADER * e.zoom));
p.rect_filled(header, egui::CornerRadius { nw: 5, ne: 5, sw: 0, se: 0 }, category_color(&n.op));
let star = if is_out { format!("{} ", icon::STAR) } else { String::new() };
p.text(header.left_center() + vec2(5.0, 0.0), Align2::LEFT_CENTER, format!("{star}{}", label(&n.op)), font.clone(), Color32::WHITE);
p.rect_stroke(sr, 5.0, Stroke::new(if is_out { 2.0 } else { 1.0 }, if is_out { tk.accent } else { Color32::from_gray(0x10) }), StrokeKind::Outside);
for i in 0..arity(&n.op) {
let pos = to_s(in_port(r, i), e);
p.circle(pos, 4.5, Color32::from_gray(0xc8), Stroke::new(1.0, Color32::from_gray(0x18)));
ports.push((id, Some(i), pos));
}
let op = to_s(out_port(r), e);
p.circle(op, 4.5, Color32::from_rgb(0xe8, 0xa9, 0x3c), Stroke::new(1.0, Color32::from_gray(0x18)));
ports.push((id, None, op));
// Inline value editor.
if n.value.is_some() {
let row = Rect::from_min_size(
to_s(pos2(r.left() + 6.0, r.top() + HEADER + arity(&n.op).max(1) as f32 * ROW + 2.0), e),
vec2((W - 12.0) * e.zoom, (ROW - 2.0) * e.zoom),
);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(row));
if let Some(v) = g.nodes[idx].value.as_mut() {
changed |= value_editor(&mut child, v);
}
}
let body = ui.interact(sr, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag());
crate::widgets::name(&body, egui::Role::Button, label(&g.nodes[idx].op));
if body.drag_started() && e.drag.is_none() {
e.drag = Some(FnDrag::Node(id, Vec2::ZERO));
}
body.context_menu(|ui| {
if ui.button(format!("{} {}", icon::STAR, tr("Use as result"))).clicked() {
set_output = Some(id);
ui.close();
}
if ui.button(format!("{} {}", icon::X, tr("Delete"))).clicked() {
remove = Some(id);
ui.close();
}
});
}
if let Some(id) = set_output {
g.output = Some(id);
changed = true;
}
if let Some(id) = remove {
g.nodes.retain(|n| n.id != id);
for n in &mut g.nodes {
for i in &mut n.inputs {
if *i == Some(id) {
*i = None;
}
}
}
if g.output == Some(id) {
g.output = None;
}
changed = true;
}
// Gestures: wires from output dots, panning.
let near = |ptr: Pos2| ports.iter().filter(|(_, _, q)| q.distance(ptr) < 9.0).min_by(|a, b| a.2.distance(ptr).total_cmp(&b.2.distance(ptr))).cloned();
if resp.drag_started_by(egui::PointerButton::Middle) || (resp.drag_started() && ui.input(|i| i.modifiers.alt)) {
e.drag = Some(FnDrag::Pan);
} else if ui.input(|i| i.pointer.primary_pressed())
&& e.drag.is_none()
&& let Some(ptr) = pointer
&& rect.contains(ptr)
&& let Some((id, None, _)) = near(ptr)
{
e.drag = Some(FnDrag::Wire(id));
}
let delta = ui.input(|i| i.pointer.delta());
match &mut e.drag {
Some(FnDrag::Node(_, d)) => *d += delta / e.zoom,
Some(FnDrag::Pan) => e.pan -= delta / e.zoom,
Some(FnDrag::Wire(id)) => {
if let (Some(ptr), Some(src)) = (pointer, ports.iter().find(|(n, s, _)| n == id && s.is_none())) {
p.line_segment([src.2, ptr], Stroke::new(2.0, tk.accent));
}
}
None => {}
}
if ui.input(|i| i.pointer.any_released()) {
match e.drag.take() {
Some(FnDrag::Node(id, d)) => {
if let Some(n) = g.nodes.iter_mut().find(|n| n.id == id)
&& d.length() > 0.5
{
n.pos = [n.pos[0] + d.x, n.pos[1] + d.y];
changed = true;
}
}
Some(FnDrag::Wire(src)) => {
if let Some(ptr) = pointer
&& let Some((dst, Some(slot), _)) = near(ptr)
&& dst != src
&& !reaches(g, dst, src)
&& let Some(n) = g.nodes.iter_mut().find(|n| n.id == dst)
{
if n.inputs.len() <= slot {
n.inputs.resize(slot + 1, None);
}
n.inputs[slot] = Some(src);
changed = true;
}
}
_ => {}
}
}
// Adding operations.
if resp.secondary_clicked()
&& let Some(ptr) = pointer
{
e.menu_at = to_g(ptr, e);
}
if resp.hovered()
&& ui.input(|i| i.key_pressed(egui::Key::Space))
&& let Some(ptr) = pointer
{
e.menu_at = to_g(ptr, e);
egui::Popup::open_id(ui.ctx(), resp.id.with("menu"));
}
let at = e.menu_at;
let mut add: Option<&'static str> = None;
resp.context_menu(|ui| {
let mut cats: Vec<&str> = FN_OPS.iter().map(|o| o.3).collect();
cats.dedup();
for c in cats {
ui.menu_button(tr(c), |ui| {
for o in FN_OPS.iter().filter(|o| o.3 == c) {
if ui.button(tr(o.1)).clicked() {
add = Some(o.0);
ui.close();
}
}
});
}
});
if let Some(op) = add {
let id = g.nodes.iter().map(|n| n.id + 1).max().unwrap_or(1);
g.nodes.push(FnNode { id, op: op.into(), inputs: vec![None; arity(op)], value: default_value(op), pos: [at.x, at.y] });
if g.output.is_none() {
g.output = Some(id);
}
changed = true;
}
changed
}
/// Whether `a` feeds `b` (directly or through other nodes, or is `b`): then `b` may not feed `a`.
fn reaches(g: &FnGraph, a: u32, b: u32) -> bool {
let mut stack = vec![b];
let mut seen = std::collections::BTreeSet::new();
while let Some(n) = stack.pop() {
if n == a {
return true;
}
if !seen.insert(n) {
continue;
}
if let Some(node) = g.node(n) {
stack.extend(node.inputs.iter().flatten());
}
}
false
}
/// A compact editor for a function node's value. Returns true when it changed.
fn value_editor(ui: &mut Ui, v: &mut Value) -> bool {
let drag = |ui: &mut Ui, f: &mut f32| ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(3)).changed();
ui.horizontal(|ui| match v {
Value::Float(f) => drag(ui, f),
Value::Float2(a) => {
let x = drag(ui, &mut a[0]);
drag(ui, &mut a[1]) || x
}
Value::Float3(a) => {
let mut c = false;
for f in a.iter_mut() {
c |= drag(ui, f);
}
c
}
Value::Float4(a) | Value::Color(a) => {
let mut c = false;
for f in a.iter_mut() {
c |= ui.add(egui::DragValue::new(f).speed(0.01).max_decimals(2)).changed();
}
c
}
Value::Int(i) => ui.add(egui::DragValue::new(i).speed(0.1)).changed(),
Value::Bool(b) => ui.checkbox(b, "").changed(),
Value::Text(t) => {
let r = ui.add(egui::TextEdit::singleline(t).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, "Value");
r.changed()
}
_ => false,
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cycles_are_detected() {
let mut g = FnGraph::default();
let a = g.add("get_pos", &[], None);
let b = g.add("swizzle", &[a], Some(Value::Text("x".into())));
// a feeds b: wiring b into a would loop.
assert!(reaches(&g, a, b));
assert!(!reaches(&g, b, a));
assert_eq!(arity("add"), 2);
assert!(default_value("const_float").is_some());
}
}
File diff suppressed because it is too large. Load diff
-95
View File
@@ -1,95 +0,0 @@
#[cfg(test)]
mod lib_tests {
use crate::MaterialCraftApp;
use crate::cook::execute_guarded;
use crate::state::UiState;
use materialcraft_engine::sample_session;
use serde_json::json;
#[test]
fn run_reports_errors_as_toasts_and_keeps_the_session() {
let mut app = MaterialCraftApp::headless(sample_session(), UiState::default());
assert!(app.run("no.such.command", json!({})).is_none());
assert!(app.toasts.iter().any(|t| t.error));
assert!(app.run("graph.node.add", json!({"def": "levels"})).is_some());
}
#[test]
fn guarded_execute_returns_command_errors_as_strings() {
let mut s = sample_session();
let e = execute_guarded(&mut s, "no.such.command", &json!({})).unwrap_err();
assert!(!e.is_empty());
assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok());
}
}
#[cfg(test)]
mod unsaved_state_tests {
use crate::unsaved::{Choice, Guarded, guard};
use crate::{MaterialCraftApp, state::UiState};
fn app(modified: bool) -> MaterialCraftApp {
let mut s = materialcraft_engine::sample_session();
s.modified = modified;
MaterialCraftApp::headless(s, UiState::default())
}
#[test]
fn closing_all_over_unsaved_work_waits_for_an_answer() {
let mut a = app(true);
let before = a.session.pkg.name.clone();
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
assert!(a.ui.windows.unsaved.is_some());
assert_eq!(a.session.pkg.name, before, "nothing was replaced yet");
// The held action is visible as serde state (control channel `ui.inspect`).
let v = serde_json::to_value(&a.ui).unwrap();
assert_eq!(v["windows"]["unsaved"]["kind"], "menu");
}
#[test]
fn closing_all_over_a_clean_package_just_happens() {
let mut a = app(false);
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
assert!(a.ui.windows.unsaved.is_none());
assert_eq!(a.session.pkg.graphs.first().map(|g| g.name.as_str()), Some("Material_Graph"), "the empty package replaced it");
}
#[test]
fn discard_runs_the_held_action_and_cancel_keeps_the_work() {
let mut a = app(true);
guard(&mut a, Guarded::Menu { id: "ui.closeAll".into() });
let step = crate::unsaved::answer(&mut a.ui.windows.unsaved, Choice::Cancel);
assert_eq!(step, crate::unsaved::Step::Stop);
assert!(a.session.modified);
}
#[test]
fn a_pending_dialog_is_not_restored_from_saved_state() {
let mut a = app(true);
guard(&mut a, Guarded::Quit);
let saved = serde_json::to_string(&a.ui).unwrap();
let back: UiState = serde_json::from_str(&saved).unwrap();
assert!(back.windows.unsaved.is_none());
}
}
#[cfg(test)]
mod gesture_tests {
use crate::end_gesture_if_released;
#[test]
fn pointer_release_ends_the_merge_run() {
let mut s = materialcraft_engine::sample_session();
let base = s.history().len();
let set = |s: &mut materialcraft_engine::Session| {
s.edit_merged("k", "Set parameter", |_| Ok(())).unwrap();
};
set(&mut s);
end_gesture_if_released(&mut s, false);
set(&mut s);
assert_eq!(s.history().len(), base + 1, "still dragging: merged");
end_gesture_if_released(&mut s, true);
set(&mut s);
assert_eq!(s.history().len(), base + 2, "released: a new step");
}
}
-776
View File
@@ -1,776 +0,0 @@
//! Properties: the selected node's base and specific parameters, or the graph's own settings,
//! inputs and outputs when no node is selected. Every change is an engine command (slider drags
//! merge into one undo step).
use egui::{Color32, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::{Curve, Gradient, NodeId, OutputFormat, SizeMode, Value};
use materialcraft_engine::nodes::ParamDef;
use serde_json::{Value as J, json};
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
/// The panel title: "<node> - Properties" or "<graph> - Properties".
pub fn title(app: &MaterialCraftApp) -> String {
if let Some((page, _)) = &app.props3d {
return crate::view3d_props::title(*page);
}
let sel = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().map(crate::graph_view::node_label));
let name = sel.or_else(|| app.session.graph().ok().map(|g| g.name.clone())).unwrap_or_default();
format!("{name} - {}", tr("Properties"))
}
fn section(ui: &mut Ui, id: &str, title: &str, body: impl FnOnce(&mut Ui)) {
let tk = Tokens::get(ui.ctx());
let id = ui.make_persistent_id(id);
let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true);
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
crate::widgets::name(&resp, egui::Role::Button, title);
ui.painter().rect_filled(r, 3.0, tk.row);
let chev = if state.is_open() { icon::CARET_DOWN } else { icon::CARET_RIGHT };
ui.painter().text(r.left_center() + vec2(6.0, 0.0), egui::Align2::LEFT_CENTER, chev, egui::FontId::proportional(10.0), tk.text_dim);
ui.painter().text(r.left_center() + vec2(20.0, 0.0), egui::Align2::LEFT_CENTER, title.to_uppercase(), egui::FontId::proportional(10.5), tk.text_strong);
if resp.clicked() {
state.toggle(ui);
}
state.show_body_unindented(ui, |ui| {
ui.add_space(3.0);
body(ui);
ui.add_space(6.0);
});
}
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
// A 3D view page stays until the user selects something else in the graph.
if let Some((page, sel)) = app.props3d.clone() {
if sel != app.session.selection {
app.props3d = None;
} else {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.push_id(("props3d", page.title()), |ui| crate::view3d_props::show(app, ui, page));
});
return;
}
}
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.set_width(ui.available_width());
let node = app.session.selection.last().and_then(|id| app.session.graph().ok()?.node(*id).ok().cloned());
ui.push_id((app.session.graph, node.as_ref().map(|n| n.id)), |ui| match node {
Some(n) => node_props(app, ui, &n),
None => graph_props(app, ui),
});
});
}
fn node_props(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) {
let tk = Tokens::get(ui.ctx());
let def = materialcraft_engine::nodes::find(&n.def);
// Header: label (renamable) and description.
ui.horizontal(|ui| {
ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph_view::header_color(&n.def));
ui.add_space(8.0);
let mut label = if n.label.is_empty() { crate::graph_view::node_label(n) } else { n.label.clone() };
let r = ui.add(egui::TextEdit::singleline(&mut label).desired_width(ui.available_width() - 4.0).font(egui::TextStyle::Heading));
crate::widgets::name(&r, egui::Role::TextInput, "Node label");
if r.changed() {
app.run("graph.node.rename", json!({"id": n.id.0, "label": label}));
}
});
if let Some(d) = def
&& !d.description.is_empty()
{
ui.label(RichText::new(d.description).size(11.0).color(tk.text_dim));
}
if let Some(r) = app.session.cooked.nodes.get(&n.id)
&& let Some(e) = &r.error
{
ui.label(RichText::new(format!("{} {e}", icon::WARNING)).color(tk.danger));
}
ui.add_space(4.0);
section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, n));
if n.def == "graph_instance" {
section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, n));
return;
}
let Some(def) = def else { return };
if def.params.is_empty() {
return;
}
section(ui, "specific", tr("Specific parameters"), |ui| {
if n.def == "levels" {
crate::levels_editor::show(app, ui, n);
ui.add_space(6.0);
}
let exposed: Vec<(String, String)> =
app.session.graph().map(|g| g.exposed.iter().map(|e| (e.id.clone(), e.label.clone())).collect()).unwrap_or_default();
for p in &def.params {
let cur = n.params.get(p.id).cloned().unwrap_or_else(|| p.default.clone());
if n.functions.contains_key(p.id) {
function_row(app, ui, n.id, p.id, p.label);
continue;
}
let bound = n.bindings.get(p.id).cloned();
param_row(app, ui, n.id, p, cur, bound, &exposed);
}
});
}
fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) {
let b = &n.base;
let id = n.id.0;
let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")];
let cur = modes.iter().find(|m| m.0 == b.size_mode).map_or("", |m| m.1);
crate::widgets::combo(ui, tr("Output size"), tr(cur), |ui| {
for (m, label) in modes {
if ui.selectable_label(b.size_mode == m, tr(label)).clicked() {
let key = match m {
SizeMode::RelativeToInput => "relativeToInput",
SizeMode::RelativeToParent => "relativeToParent",
SizeMode::Absolute => "absolute",
};
let size = if m == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) };
app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size}));
}
}
});
let (lo, hi) = if b.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) };
for (axis, label) in [(0usize, "Width"), (1, "Height")] {
let mut v = b.size[axis] as f32;
let caption = if b.size_mode == SizeMode::Absolute {
format!("{label} {} px", 1u32 << b.size[axis].clamp(4, 13))
} else {
format!("{label} x {}", 2f32.powi(b.size[axis]))
};
if crate::widgets::slider(ui, &caption, &mut v, lo..=hi, 0).changed() {
let mut size = b.size;
size[axis] = v.round() as i32;
app.run("graph.node.base", json!({"id": id, "size": size}));
}
}
crate::widgets::combo(ui, tr("Output format"), tr(b.format.label()), |ui| {
for f in OutputFormat::ALL {
if ui.selectable_label(b.format == f, tr(f.label())).clicked() {
let key = match f {
OutputFormat::Inherit => "inherit",
OutputFormat::U8 => "u8",
OutputFormat::U16 => "u16",
OutputFormat::F16 => "f16",
OutputFormat::F32 => "f32",
};
app.run("graph.node.base", json!({"id": id, "format": key}));
}
}
});
let mut seed = b.seed as f32;
if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() {
app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64}));
}
if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() {
let s = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000;
app.run("graph.node.base", json!({"id": id, "seed": s}));
}
let mut tiling = b.tiling[0] && b.tiling[1];
if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() {
app.run("graph.node.base", json!({"id": id, "tiling": tiling}));
}
}
fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: J) {
app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value}));
}
fn typed(v: &Value) -> J {
serde_json::to_value(v).unwrap_or(J::Null)
}
/// One parameter: its editor, plus the expose/bind menu.
fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, p: &ParamDef, cur: Value, bound: Option<String>, exposed: &[(String, String)]) {
let tk = Tokens::get(ui.ctx());
if let Some(input) = &bound {
ui.horizontal(|ui| {
ui.label(RichText::new(tr(p.label)).color(tk.text));
ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tk.accent));
if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() {
app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": J::Null}));
}
});
return;
}
let resp_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| {
resp.context_menu(|ui| {
if ui.button(tr("Reset to default")).clicked() {
app.run("graph.node.reset", json!({"id": node.0, "param": p.id}));
ui.close();
}
let dynamic = !matches!(p.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_));
if dynamic && ui.button(tr("Set function...")).clicked() {
if app.run("graph.node.function", json!({"id": node.0, "param": p.id})).is_some() {
app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{}", p.id)));
}
ui.close();
}
if ui.button(tr("Expose as graph input")).clicked() {
app.run("graph.exposed.add", json!({"id": p.id, "label": p.label, "bind": {"node": node.0, "param": p.id}}));
ui.close();
}
if !exposed.is_empty() {
ui.menu_button(tr("Bind to input"), |ui| {
for (id, label) in exposed {
if ui.button(label).clicked() {
app.run("graph.node.bind", json!({"id": node.0, "param": p.id, "input": id}));
ui.close();
}
}
});
}
});
};
match cur {
Value::Float(mut v) => {
if p.angle {
let mut deg = v * 360.0;
let r = crate::widgets::slider(ui, tr(p.label), &mut deg, -360.0..=360.0, 1);
if r.changed() {
v = deg / 360.0;
set(app, node, p.id, json!(v));
}
resp_menu(app, &r);
} else {
let (lo, hi) = (p.min.min(v), p.max.max(v));
let r = crate::widgets::slider(ui, tr(p.label), &mut v, lo..=hi, if hi - lo > 20.0 { 1 } else { 3 });
if r.changed() {
set(app, node, p.id, json!(v));
}
resp_menu(app, &r);
}
}
Value::Int(i) => {
let mut v = i as f32;
let range = p.min.min(v)..=p.max.max(v);
let r = crate::widgets::slider(ui, tr(p.label), &mut v, range, 0);
if r.changed() && v.round() as i32 != i {
set(app, node, p.id, json!(v.round() as i32));
}
resp_menu(app, &r);
}
Value::Float2(v) => {
ui.label(RichText::new(tr(p.label)).color(tk.text));
let mut nv = v;
for (k, axis) in ["X", "Y"].iter().enumerate() {
let range = p.min.min(nv[k])..=p.max.max(nv[k]);
let r = crate::widgets::slider(ui, axis, &mut nv[k], range, 3);
if r.changed() {
set(app, node, p.id, json!(nv));
}
resp_menu(app, &r);
}
}
Value::Int2(v) => {
ui.label(RichText::new(tr(p.label)).color(tk.text));
for k in 0..2 {
let mut f = v[k] as f32;
if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, p.min..=p.max, 0).changed() {
let mut nv = v;
nv[k] = f.round() as i32;
set(app, node, p.id, json!(nv));
}
}
}
Value::Bool(b) => {
let mut v = b;
let r = ui.checkbox(&mut v, tr(p.label));
if r.changed() {
set(app, node, p.id, json!(v));
}
resp_menu(app, &r);
}
Value::Color(c) | Value::Float4(c) => {
ui.horizontal(|ui| {
ui.label(RichText::new(tr(p.label)).color(tk.text));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut rgb = [c[0], c[1], c[2]];
if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, p.id), &mut rgb, 90.0) {
set(app, node, p.id, json!([rgb[0], rgb[1], rgb[2], c[3]]));
}
});
});
}
Value::Enum(i) => {
let cur = p.options.get(i as usize).copied().unwrap_or("?");
crate::widgets::combo(ui, tr(p.label), tr(cur), |ui| {
for (k, o) in p.options.iter().enumerate() {
if ui.selectable_label(k as u32 == i, tr(o)).clicked() {
set(app, node, p.id, json!(k));
}
}
});
}
Value::Text(t) if p.resource => {
let names: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect();
crate::widgets::combo(ui, tr(p.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| {
for n in &names {
if ui.selectable_label(*n == t, n).clicked() {
set(app, node, p.id, json!(n));
}
}
});
if ui.button(format!("{} {}", icon::IMAGE, tr("Import bitmap..."))).clicked() {
crate::menus::invoke(app, ui.ctx(), "file.importBitmap");
}
}
Value::Text(t) => {
ui.horizontal(|ui| {
ui.label(RichText::new(tr(p.label)).color(tk.text));
let mut s = t.clone();
let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, p.label);
if r.changed() {
set(app, node, p.id, json!(s));
}
});
}
Value::Curve(c) => {
ui.label(RichText::new(tr(p.label)).color(tk.text));
if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, p.id), &c) {
set(app, node, p.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>()));
}
}
Value::Gradient(g) => {
ui.label(RichText::new(tr(p.label)).color(tk.text));
if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, p.id), &g) {
set(app, node, p.id, typed(&Value::Gradient(ng)));
}
}
Value::Function(f) => {
ui.label(RichText::new(tr(p.label)).color(tk.text));
crate::windows::function_summary(app, ui, node, p.id, &f);
}
other => {
ui.label(format!("{}: {}", p.label, other.type_name()));
}
}
}
/// A parameter driven by a function: its label, Edit and Remove.
fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) {
let tk = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(tr(label)).color(tk.text));
ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tk.accent));
if ui.small_button(tr("Edit")).clicked() {
app.fn_editor = Some(crate::function_editor::FnEditor::new(node, &format!("fn:{param}")));
}
if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() {
app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true}));
}
});
}
fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, n: &materialcraft_engine::core::Node) {
let tk = Tokens::get(ui.ctx());
let Some((gi, sub)) = materialcraft_engine::eval::instance_graph(&app.session.pkg, n) else {
ui.label(RichText::new(tr("The instanced graph is missing")).color(tk.danger));
return;
};
let exposed = sub.exposed.clone();
if ui.button(format!("{} {}", icon::ARROW_SQUARE_OUT, tr("Open graph"))).clicked() {
app.run("graph.open", json!({"graph": gi}));
return;
}
if exposed.is_empty() {
ui.label(RichText::new(tr("This graph exposes no inputs")).color(tk.text_dim));
}
for e in exposed {
let cur = n.params.get(&e.id).cloned().unwrap_or_else(|| e.default.clone());
if let Some(v) = input_editor(ui, &e, &cur) {
app.run("graph.node.param", json!({"id": n.id.0, "param": e.id, "value": v}));
}
}
}
/// The editor for one exposed input's value; returns the new value as JSON when it changed.
fn input_editor(ui: &mut Ui, e: &materialcraft_engine::core::ExposedParam, cur: &Value) -> Option<J> {
match *cur {
Value::Float(mut f) => {
let v0 = f;
crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 3).changed().then(|| json!(f))
}
Value::Int(i) => {
let mut f = i as f32;
let v0 = f;
crate::widgets::slider(ui, &e.label, &mut f, e.min.min(v0)..=e.max.max(v0), 0).changed().then(|| json!(f.round()))
}
Value::Bool(mut b) => ui.checkbox(&mut b, &e.label).changed().then(|| json!(b)),
Value::Enum(i) => {
let mut out = None;
crate::widgets::combo(ui, &e.label, e.options.get(i as usize).cloned().unwrap_or_default(), |ui| {
for (k, o) in e.options.iter().enumerate() {
if ui.selectable_label(k as u32 == i, o).clicked() {
out = Some(json!(k));
}
}
});
out
}
Value::Color(c) => {
let mut rgb = [c[0], c[1], c[2]];
let mut out = None;
ui.horizontal(|ui| {
ui.label(&e.label);
if crate::widgets::color_swatch(ui, &format!("exp-{}", e.id), &mut rgb, 80.0) {
out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]]));
}
});
out
}
ref other => {
ui.label(format!("{}: {}", e.label, other.type_name()));
None
}
}
}
fn graph_props(app: &mut MaterialCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
let Ok(g) = app.session.graph() else {
ui.label(tr("No graph is open"));
return;
};
let g = g.clone();
section(ui, "graph-base", tr("Base parameters"), |ui| {
ui.horizontal(|ui| {
ui.label(tr("Name"));
let mut name = g.name.clone();
let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, "Graph name");
if r.lost_focus() && name != g.name {
app.run("graph.rename", json!({"name": name}));
}
});
for (axis, label) in [(0usize, "Width"), (1, "Height")] {
let mut v = g.size[axis] as f32;
if crate::widgets::slider(ui, &format!("{} {} px", tr(label), 1u32 << g.size[axis]), &mut v, 4.0..=13.0, 0).changed() {
let mut s = g.size;
s[axis] = v.round() as u32;
app.run("graph.size", json!({"log2": s}));
}
}
crate::widgets::combo(ui, tr("Output format"), tr(g.format.label()), |ui| {
for (f, key) in [(OutputFormat::U8, "u8"), (OutputFormat::U16, "u16"), (OutputFormat::F16, "f16"), (OutputFormat::F32, "f32")] {
if ui.selectable_label(g.format == f, tr(f.label())).clicked() {
app.run("graph.format", json!({"format": key}));
}
}
});
let mut seed = g.seed as f32;
if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() {
app.run("graph.seed", json!({"seed": seed.round() as i64}));
}
});
section(ui, "graph-attr", tr("Attributes"), |ui| {
for (key, label, cur) in [
("category", "Category", &g.attributes.category),
("description", "Description", &g.attributes.description),
("author", "Author", &g.attributes.author),
("tags", "Tags", &g.attributes.tags),
] {
ui.horizontal(|ui| {
ui.label(tr(label));
let mut s = cur.clone();
let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width()));
crate::widgets::name(&r, egui::Role::TextInput, label);
if r.lost_focus() && s != *cur {
app.run("graph.attributes", json!({key: s}));
}
});
}
});
section(ui, "graph-inputs", tr("Input parameters"), |ui| {
if g.exposed.is_empty() {
ui.label(RichText::new(tr("Right-click a node parameter > Expose as graph input")).size(11.0).color(tk.text_dim));
} else {
presets_bar(app, ui, &g);
}
let mut groups: Vec<&str> = Vec::new();
for e in &g.exposed {
if !groups.contains(&e.group.as_str()) {
groups.push(&e.group);
}
}
let mut last_group: Option<&str> = None;
let mut order: Vec<&materialcraft_engine::core::ExposedParam> = Vec::new();
for grp in &groups {
order.extend(g.exposed.iter().filter(|e| e.group == *grp));
}
for e in order {
if last_group != Some(e.group.as_str()) && !e.group.is_empty() {
ui.label(RichText::new(e.group.to_uppercase()).size(10.5).strong().color(tk.text_dim));
}
last_group = Some(e.group.as_str());
let cur = g.input_value(&e.id).cloned().unwrap_or_else(|| e.default.clone());
ui.horizontal(|ui| {
if crate::widgets::icon_button(ui, icon::X, tr("Delete input"), false, 18.0).clicked() {
app.run("graph.exposed.delete", json!({"id": e.id}));
}
ui.vertical(|ui| {
if let Some(v) = input_editor(ui, e, &cur) {
app.run("graph.exposed.set", json!({"id": e.id, "value": v}));
}
});
});
}
});
input_previews(app, ui, &g);
section(ui, "graph-outputs", tr("Outputs"), |ui| {
for n in g.nodes.iter().filter(|n| n.def == "output") {
let usage = n.params.get("usage").and_then(Value::as_i32).unwrap_or(0) as usize;
let label = format!(
"{} {} | {}",
icon::SIGN_OUT,
materialcraft_engine::nodes::atomic::USAGES.get(usage).copied().unwrap_or("Any"),
materialcraft_engine::eval::identifier(n)
);
if ui.add(egui::Button::selectable(app.session.view2d.node == Some(n.id), label)).clicked() {
app.run("view.2d", json!({"node": n.id.0}));
}
}
});
}
/// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such
/// as a mesh map baked in TextureCraft.
fn input_previews(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) {
let inputs = materialcraft_engine::material_cmds::image_inputs(g);
if inputs.is_empty() {
return;
}
let resources: Vec<String> = app.session.pkg.resources.iter().map(|r| r.name.clone()).collect();
section(ui, "graph-input-images", tr("Input previews"), |ui| {
for i in &inputs {
let id = &i.identifier;
let bound = g.input_images.get(id);
ui.horizontal(|ui| {
ui.label(id);
egui::ComboBox::from_id_salt(("input-preview", id)).width(120.0).selected_text(bound.map_or(tr("None"), String::as_str)).show_ui(ui, |ui| {
if ui.selectable_label(bound.is_none(), tr("None")).clicked() {
app.run("graph.input.unbind", json!({"identifier": id}));
}
for r in &resources {
if ui.selectable_label(bound == Some(r), r).clicked() {
app.run("graph.input.bind", json!({"identifier": id, "resource": r}));
}
}
});
#[cfg(not(target_arch = "wasm32"))]
if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked()
&& let Some(p) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
{
app.run("graph.input.bind", json!({"identifier": id, "path": p.display().to_string()}));
}
});
}
});
}
/// Presets: apply one, save the current inputs under a name, delete one.
fn presets_bar(app: &mut MaterialCraftApp, ui: &mut Ui, g: &materialcraft_engine::core::Graph) {
let name_id = ui.make_persistent_id("preset-name");
let mut name: String = ui.data(|d| d.get_temp(name_id)).unwrap_or_default();
ui.horizontal(|ui| {
let names: Vec<String> = g.presets.iter().map(|p| p.name.clone()).collect();
let r = egui::ComboBox::from_id_salt("presets").width(110.0).selected_text(tr("Presets")).show_ui(ui, |ui| {
for n in &names {
if ui.button(n).clicked() {
app.run("graph.preset.apply", json!({"name": n}));
}
}
if names.is_empty() {
ui.label(tr("No presets yet"));
}
});
crate::widgets::name(&r.response, egui::Role::ComboBox, "Presets");
let t = ui.add(egui::TextEdit::singleline(&mut name).hint_text(tr("Preset name")).desired_width(90.0));
crate::widgets::name(&t, egui::Role::TextInput, "Preset name");
if crate::widgets::icon_button(ui, icon::FLOPPY_DISK, tr("Save preset"), false, 20.0).clicked() && !name.trim().is_empty() {
app.run("graph.preset.save", json!({"name": name}));
}
if crate::widgets::icon_button(ui, icon::X, tr("Delete preset"), false, 20.0).clicked() && !name.trim().is_empty() {
app.run("graph.preset.delete", json!({"name": name}));
}
});
ui.data_mut(|d| d.insert_temp(name_id, name));
}
/// A tone curve editor: drag points, double-click to add one, right-click a point to remove it.
/// Returns the new curve when it changed.
pub fn curve_editor(ui: &mut Ui, id: &str, c: &Curve) -> Option<Curve> {
let tk = Tokens::get(ui.ctx());
let w = ui.available_width().min(240.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, w * 0.75), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Curve editor");
let p = ui.painter_at(rect);
p.rect_filled(rect, 4.0, tk.field);
for i in 1..4 {
let t = i as f32 / 4.0;
p.line_segment([pos2(rect.left() + rect.width() * t, rect.top()), pos2(rect.left() + rect.width() * t, rect.bottom())], Stroke::new(1.0, tk.separator));
p.line_segment([pos2(rect.left(), rect.top() + rect.height() * t), pos2(rect.right(), rect.top() + rect.height() * t)], Stroke::new(1.0, tk.separator));
}
let to_s = |x: f32, y: f32| pos2(rect.left() + x * rect.width(), rect.bottom() - y * rect.height());
let from_s = |s: Pos2| (((s.x - rect.left()) / rect.width()).clamp(0.0, 1.0), ((rect.bottom() - s.y) / rect.height()).clamp(0.0, 1.0));
let pts: Vec<Pos2> = (0..=64).map(|i| i as f32 / 64.0).map(|x| to_s(x, c.eval(x).clamp(0.0, 1.0))).collect();
p.add(egui::Shape::line(pts, Stroke::new(2.0, tk.accent)));
let drag_id = ui.make_persistent_id(id).with("drag");
let mut dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
let pointer = resp.interact_pointer_pos().or(resp.hover_pos());
let nearest = pointer.and_then(|q| {
c.points
.iter()
.enumerate()
.map(|(i, pt)| (i, to_s(pt.x, pt.y).distance(q)))
.filter(|(_, d)| *d < 10.0)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(i, _)| i)
});
for (i, pt) in c.points.iter().enumerate() {
let hot = Some(i) == nearest || Some(i) == dragging;
p.circle(to_s(pt.x, pt.y), if hot { 5.0 } else { 4.0 }, tk.panel, Stroke::new(1.5, if hot { tk.text_strong } else { tk.text }));
}
let mut out: Option<Curve> = None;
if resp.drag_started() {
dragging = nearest;
}
if resp.dragged()
&& let (Some(i), Some(q)) = (dragging, pointer)
{
let (x, y) = from_s(q);
let mut nc = c.clone();
let last = nc.points.len().saturating_sub(1);
if let Some(pt) = nc.points.get_mut(i) {
// End points keep their x.
if i != 0 && i != last {
pt.x = x;
}
pt.y = y;
}
nc.points.sort_by(|a, b| a.x.total_cmp(&b.x));
out = Some(nc);
}
if resp.drag_stopped() {
dragging = None;
}
ui.data_mut(|d| d.insert_temp(drag_id, dragging));
if resp.double_clicked()
&& let Some(q) = pointer
{
let (x, _) = from_s(q);
let mut nc = c.clone();
nc.points.push(materialcraft_engine::core::CurvePoint { x, y: c.eval(x) });
nc.points.sort_by(|a, b| a.x.total_cmp(&b.x));
out = Some(nc);
}
if resp.secondary_clicked()
&& let Some(i) = nearest
&& i != 0
&& i + 1 != c.points.len()
{
let mut nc = c.clone();
nc.points.remove(i);
out = Some(nc);
}
out
}
/// A gradient editor: the ramp with its keys below; drag keys, click the ramp to add one, pick a
/// key's color, right-click a key to remove it.
pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient) -> Option<Gradient> {
let tk = Tokens::get(ui.ctx());
let w = ui.available_width().min(260.0);
let (rect, resp) = ui.allocate_exact_size(vec2(w, 30.0), Sense::click_and_drag());
crate::widgets::name(&resp, egui::Role::Canvas, "Gradient editor");
let p = ui.painter_at(rect.expand(6.0));
let bar = Rect::from_min_size(rect.min, vec2(w, 18.0));
let n = 64;
for i in 0..n {
let t0 = i as f32 / n as f32;
let c = g.eval(t0 + 0.5 / n as f32);
let q = |v: f32| (materialcraft_engine::image::linear_to_srgb(v.clamp(0.0, 1.0)) * 255.0) as u8;
let r = Rect::from_min_max(pos2(bar.left() + bar.width() * t0, bar.top()), pos2(bar.left() + bar.width() * (t0 + 1.0 / n as f32) + 0.5, bar.bottom()));
p.rect_filled(r, 0.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2])));
}
p.rect_stroke(bar, 2.0, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
let sel_id = ui.make_persistent_id(id).with("sel");
let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0);
let key_x = |pos: f32| bar.left() + pos * bar.width();
let pointer = resp.interact_pointer_pos().or(resp.hover_pos());
let nearest = pointer.and_then(|q| {
g.keys.iter().enumerate().map(|(i, k)| (i, (key_x(k.pos) - q.x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i)
});
for (i, k) in g.keys.iter().enumerate() {
let x = key_x(k.pos);
let tri = vec![pos2(x, bar.bottom() + 1.0), pos2(x - 5.0, bar.bottom() + 10.0), pos2(x + 5.0, bar.bottom() + 10.0)];
p.add(egui::Shape::convex_polygon(tri, if i == sel { tk.accent } else { tk.text }, Stroke::NONE));
}
let mut out: Option<Gradient> = None;
if resp.drag_started()
&& let Some(i) = nearest
{
sel = i;
}
if resp.dragged()
&& let Some(q) = pointer
&& nearest.is_some()
{
let mut ng = g.clone();
if let Some(k) = ng.keys.get_mut(sel) {
k.pos = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0);
}
let moved = ng.keys.get(sel).copied();
ng.sort();
if let Some(m) = moved {
sel = ng.keys.iter().position(|k| k.pos == m.pos && k.color == m.color).unwrap_or(sel);
}
out = Some(ng);
}
if resp.clicked()
&& let Some(q) = pointer
{
match nearest {
Some(i) => sel = i,
None => {
let t = ((q.x - bar.left()) / bar.width()).clamp(0.0, 1.0);
let mut ng = g.clone();
ng.keys.push(materialcraft_engine::core::GradientKey { pos: t, color: g.eval(t) });
ng.sort();
sel = ng.keys.iter().position(|k| k.pos == t).unwrap_or(0);
out = Some(ng);
}
}
}
if resp.secondary_clicked()
&& let Some(i) = nearest
&& g.keys.len() > 1
{
let mut ng = g.clone();
ng.keys.remove(i);
sel = 0;
out = Some(ng);
}
ui.data_mut(|d| d.insert_temp(sel_id, sel));
if let Some(k) = g.keys.get(sel) {
ui.horizontal(|ui| {
ui.label(RichText::new(format!("{} {:.2}", tr("Key at"), k.pos)).size(11.0).color(tk.text_dim));
let mut rgb = [k.color[0], k.color[1], k.color[2]];
if crate::widgets::color_swatch(ui, &format!("{id}-key"), &mut rgb, 60.0) {
let mut ng = out.clone().unwrap_or_else(|| g.clone());
if let Some(kk) = ng.keys.get_mut(sel) {
kk.color = [rgb[0], rgb[1], rgb[2], kk.color[3]];
}
out = Some(ng);
}
});
}
out
}
-330
View File
@@ -1,330 +0,0 @@
//! UI state: serde data, so the control channel can read and drive it and eframe persists it.
use serde::{Deserialize, Serialize};
use materialcraft_engine::CameraPrefs;
use crate::docking::Dock;
use crate::theme::{Accent, Brightness};
/// Preferences (Edit ▸ Preferences).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Prefs {
/// UI language code (`i18n::LANGUAGES`).
pub language: String,
pub brightness: Brightness,
pub accent: Accent,
pub ui_scale: f32,
/// Largest node output while editing (0 = full size).
pub preview_size: u32,
/// Minutes between autosaves of a modified package (0 = off).
pub autosave_minutes: u32,
/// Show node thumbnails in the graph.
pub thumbnails: bool,
/// Library tiles: large icons or a list.
pub library_list: bool,
/// Library tile size (icons view), 56..160 px.
pub library_tile: f32,
/// Open the home screen when the app starts.
pub show_home: bool,
/// 3D view camera: pan limit and speed.
pub camera: CameraPrefs,
/// Show the main toolbar under the menu bar (Windows ▸ Main toolbar).
pub show_main_toolbar: bool,
/// Worker threads the cook may use (Tools ▸ Switch engine; 0 = every core).
pub cook_threads: usize,
/// Graph toolbar: show each node's cook time.
pub node_timings: bool,
/// Graph toolbar: straight wires instead of curves.
pub straight_wires: bool,
/// Graph toolbar: dropped nodes land on the grid.
pub snap_grid: bool,
/// Graph toolbar: draw the background grid.
pub show_grid: bool,
/// General: how many recent packages the File menu keeps.
pub recent_count: u32,
/// General: undo steps kept.
pub history_size: u32,
/// General: wheel zooms the other way in every view.
pub invert_zoom: bool,
/// General: where file dialogs open: `last`, `package` or `custom` (`save_path`).
pub save_path_mode: String,
pub save_path: String,
/// General: the auto-backup folder (empty = Documents/MaterialCraft/autosave).
pub temp_dir: String,
/// General: the cooked image cache's size in MB (0 = automatic).
pub cache_mb: u32,
/// General: auto-backup versions kept per package.
pub backup_versions: u32,
/// General: cap on every cook's larger side in px (0 = none).
pub cook_limit: u32,
/// Projects: lights on in a new session when no default 3D state is saved (ambient, point 1, point 2).
pub default_lights: [bool; 3],
/// Graph: Tab opens the node search.
pub tab_key_menu: bool,
/// Graph: dragging a wire into empty space opens the node search.
pub drag_create: bool,
/// Graph: show the 3D view when a graph opens.
pub view_3d_on_open: bool,
/// Graph: show the graph's output in the 2D view when it opens.
pub view_2d_on_open: bool,
/// Graph: show a newly added node in the 2D view.
pub auto_display_new_node: bool,
/// Graph: insert a conversion node when a color wire meets a grayscale input (or the reverse).
pub auto_convert: bool,
/// 3D view: the environment is hidden behind the mesh by default.
pub env_hidden: bool,
/// 3D view: default viewport render scale (0 = auto).
pub viewport_scale: f32,
/// 3D view: default samples per pixel of the resting frame (n × n).
pub sample_count: u32,
/// Bakers: worker threads (0 = every core).
pub bake_threads: u32,
}
impl Default for Prefs {
fn default() -> Self {
Prefs {
language: crate::i18n::os_language().into(),
brightness: Brightness::default(),
accent: Accent::default(),
ui_scale: 1.0,
preview_size: 512,
autosave_minutes: 5,
thumbnails: true,
library_list: false,
library_tile: 78.0,
show_home: true,
camera: CameraPrefs::default(),
show_main_toolbar: true,
cook_threads: 0,
node_timings: false,
straight_wires: false,
snap_grid: false,
show_grid: true,
recent_count: 12,
history_size: 200,
invert_zoom: false,
save_path_mode: "last".into(),
save_path: String::new(),
temp_dir: String::new(),
cache_mb: 0,
backup_versions: 6,
cook_limit: 8192,
default_lights: [true, false, false],
tab_key_menu: true,
drag_create: true,
view_3d_on_open: true,
view_2d_on_open: true,
auto_display_new_node: true,
auto_convert: false,
env_hidden: true,
viewport_scale: 0.0,
sample_count: 2,
bake_threads: 0,
}
}
}
/// Which dialogs are open.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Windows {
pub new_graph: bool,
pub export: bool,
pub about: bool,
pub preferences: bool,
pub shortcuts: bool,
pub home: bool,
pub plugin_manager: bool,
pub switch_engine: bool,
/// The Dependency Manager window (Windows menu).
pub dependencies: bool,
/// The action waiting on the "unsaved changes" dialog (readable over the control channel;
/// never restored from a saved layout).
#[serde(skip_deserializing)]
pub unsaved: Option<crate::unsaved::Guarded>,
}
/// The graph view's camera: the graph point at the view's top-left corner, and the zoom.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphCamera {
pub pan: [f32; 2],
pub zoom: f32,
}
impl GraphCamera {
pub const ZOOM: (f32, f32) = (0.08, 4.0);
/// The camera with a finite pan and a zoom inside [`Self::ZOOM`] (state set from outside can
/// hold a zoom of 0 or NaN, which the view divides by).
pub fn sanitized(self) -> GraphCamera {
let d = GraphCamera::default();
let pan = |v: f32, d: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { d };
let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { d.zoom };
GraphCamera { pan: [pan(self.pan[0], d.pan[0]), pan(self.pan[1], d.pan[1])], zoom }
}
}
impl Default for GraphCamera {
fn default() -> Self {
GraphCamera { pan: [-60.0, -60.0], zoom: 0.8 }
}
}
/// The 2D view's camera: image zoom (1 = one image pixel per point) and center offset.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ImageCamera {
pub zoom: f32,
pub offset: [f32; 2],
/// Fit the image to the view (until the user zooms).
pub fit: bool,
}
impl ImageCamera {
pub const ZOOM: (f32, f32) = (0.02, 64.0);
/// The camera with a finite offset and a zoom inside [`Self::ZOOM`].
pub fn sanitized(self) -> ImageCamera {
let off = |v: f32| if v.is_finite() { v.clamp(-1.0e9, 1.0e9) } else { 0.0 };
let zoom = if self.zoom.is_finite() { self.zoom.clamp(Self::ZOOM.0, Self::ZOOM.1) } else { 1.0 };
ImageCamera { zoom, offset: [off(self.offset[0]), off(self.offset[1])], fit: self.fit }
}
}
impl Default for ImageCamera {
fn default() -> Self {
ImageCamera { zoom: 1.0, offset: [0.0, 0.0], fit: true }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct UiState {
pub dock: Dock,
pub prefs: Prefs,
pub windows: Windows,
pub graph_camera: GraphCamera,
pub image_camera: ImageCamera,
/// Library: the selected category path ("" = all) and the search text.
pub library_category: String,
pub library_search: String,
/// Library entries starred by the user (node ids, `@graph`, `fn:op`).
pub library_favorites: Vec<String>,
/// Library tree groups that are folded shut.
pub library_collapsed: Vec<String>,
/// Recently opened or saved packages, newest first.
pub recent: Vec<String>,
/// Plugins (file or folder paths in the plugins folder) whose graphs the library offers.
pub plugins_loaded: Vec<String>,
/// 3D view ▸ Scene ▸ Save Current State As Default: the state new sessions and Reset Scene use.
pub view3d_default: Option<serde_json::Value>,
/// The folder the last file dialog ended in (Preferences ▸ Save/Export path: Last path).
pub last_dir: String,
/// Preferences ▸ Shortcuts: node creation shortcuts, def id → shortcut ("Ctrl+Shift+B").
pub node_shortcuts: Vec<(String, String)>,
/// New graph dialog fields.
pub new_graph_template: String,
pub new_graph_name: String,
pub new_graph_size: u32,
/// New graph height when the two sizes are unlinked (0 = same as the width).
pub new_graph_height: u32,
/// Keep width and height the same in the new graph dialog.
pub new_graph_link: bool,
/// Template category shown in the new graph dialog (empty = all).
pub new_graph_category: String,
/// Graph toolbar: the parent size's width and height change together.
pub parent_link: bool,
/// Graph toolbar: the align buttons also stack the nodes (no gaps).
pub stack_align: bool,
/// Export dialog fields.
pub export_dir: String,
pub export_format: String,
pub export_depth: u32,
/// Export size in pixels; 0 = the graph's own size.
pub export_size: u32,
pub export_pattern: String,
/// Frame the whole graph on the next frame.
#[serde(skip)]
pub frame_all: bool,
}
impl Default for UiState {
fn default() -> Self {
UiState {
dock: Dock::default(),
prefs: Prefs::default(),
windows: Windows::default(),
graph_camera: GraphCamera::default(),
image_camera: ImageCamera::default(),
library_category: String::new(),
library_search: String::new(),
library_favorites: Vec::new(),
library_collapsed: Vec::new(),
recent: Vec::new(),
plugins_loaded: Vec::new(),
view3d_default: None,
last_dir: String::new(),
node_shortcuts: Vec::new(),
new_graph_template: "pbr".into(),
new_graph_name: "Material_Graph".into(),
new_graph_size: 1024,
new_graph_height: 0,
new_graph_link: true,
new_graph_category: String::new(),
parent_link: true,
stack_align: true,
export_dir: String::new(),
export_format: "png".into(),
export_depth: 0,
export_size: 0,
export_pattern: "$(graph)_$(identifier)".into(),
frame_all: true,
}
}
}
impl UiState {
/// Remember `path` at the top of the recent list.
pub fn add_recent(&mut self, path: &str) {
self.recent.retain(|p| p != path);
self.recent.insert(0, path.to_string());
self.recent.truncate(self.prefs.recent_count.clamp(1, 50) as usize);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cameras_bound_huge_finite_offsets_before_screen_math() {
let g = GraphCamera { pan: [f32::MAX, f32::MIN], zoom: 4.0 }.sanitized();
assert!(g.pan.iter().all(|v| (v * g.zoom).is_finite() && v.abs() <= 1.0e9));
let i = ImageCamera { offset: [f32::MAX, f32::MIN], zoom: 64.0, fit: false }.sanitized();
assert!(i.offset.iter().all(|v| (v * i.zoom).is_finite() && v.abs() <= 1.0e9));
}
#[test]
fn cameras_sanitize_zero_and_non_finite_zoom() {
let g = GraphCamera { pan: [f32::NAN, 5.0], zoom: 0.0 }.sanitized();
assert_eq!(g.zoom, GraphCamera::ZOOM.0);
assert!(g.pan[0].is_finite() && g.pan[1] == 5.0);
assert_eq!(GraphCamera { pan: [0.0; 2], zoom: f32::NAN }.sanitized().zoom, GraphCamera::default().zoom);
assert_eq!(ImageCamera { zoom: -3.0, offset: [f32::INFINITY, 1.0], fit: false }.sanitized().zoom, ImageCamera::ZOOM.0);
assert_eq!(ImageCamera { zoom: 1e9, offset: [0.0; 2], fit: false }.sanitized().zoom, ImageCamera::ZOOM.1);
}
#[test]
fn camera_prefs_persist_and_default_when_missing() {
// Preferences saved before the camera settings existed still load, with the defaults.
let old: Prefs = serde_json::from_value(serde_json::json!({"uiScale": 1.25})).unwrap();
assert_eq!(old.camera, CameraPrefs::default());
assert_eq!(old.ui_scale, 1.25);
let p = Prefs { camera: CameraPrefs { pan_limit: 8.0, pan_speed: 0.5 }, ..Prefs::default() };
let v = serde_json::to_value(&p).unwrap();
assert_eq!(v["camera"], serde_json::json!({"panLimit": 8.0, "panSpeed": 0.5}));
assert_eq!(serde_json::from_value::<Prefs>(v).unwrap(), p);
}
}
-40
View File
@@ -1,40 +0,0 @@
use egui::{Event, Pos2, Rect, epaint::Shape, vec2};
use egui_kittest::Harness;
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
pub fn harness(render: bool) -> Harness<'static, MaterialCraftApp> {
let app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let builder = Harness::builder().with_size(vec2(1600.0, 960.0)).with_step_dt(1.0 / 60.0);
let builder = if render { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
h.run_steps(8);
let pointer = h.state().graph.view.center();
h.event(Event::PointerMoved(pointer));
h.step();
h.key_press(egui::Key::Tab);
h.step();
h.run_steps(3);
assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).is_some());
assert!(label_position(&h, "Bitmap").is_some(), "fresh search must show its first result");
h
}
pub fn label_position(h: &Harness<'static, MaterialCraftApp>, label: &str) -> Option<Pos2> {
let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap();
fn find(shape: &Shape, clip: Rect, popup: Rect, label: &str) -> Option<Pos2> {
match shape {
Shape::Text(t) if clip.contains(t.pos) && popup.contains(t.pos) && t.galley.text().trim() == label => {
Some(t.pos + vec2(0.0, t.galley.size().y * 0.5))
}
Shape::Vec(v) => v.iter().find_map(|s| find(s, clip, popup, label)),
_ => None,
}
}
h.output().shapes.iter().find_map(|s| find(&s.shape, s.clip_rect, popup, label))
}
-71
View File
@@ -1,71 +0,0 @@
//! Resetting the search selection must also reveal it in a previously scrolled list.
#[path = "common/search.rs"]
mod search;
use egui::{Event, Key, Modifiers};
use egui_kittest::{Harness, kittest::Queryable};
use materialcraft_ui_egui::MaterialCraftApp;
fn scroll(h: &mut Harness<'static, MaterialCraftApp>, rows: usize) {
for _ in 0..rows {
h.key_press(Key::ArrowDown);
h.step();
}
h.run_steps(25);
}
fn filter_after_scrolling(h: &mut Harness<'static, MaterialCraftApp>) {
scroll(h, 45);
h.event(Event::Text("noises".into()));
h.step();
h.run_steps(25);
assert!(search::label_position(h, "Anisotropic Noise").is_some(), "selected first filtered result is offscreen");
}
fn assert_inserted(h: &mut Harness<'static, MaterialCraftApp>, def: &str) {
h.key_press(Key::Enter);
h.step();
let g = h.state().session.graph().unwrap();
assert_eq!(g.nodes.len(), 1);
assert_eq!(g.nodes[0].def, def);
}
#[test]
fn filtering_after_scrolling_reveals_and_inserts_first_match() {
let mut h = search::harness(false);
filter_after_scrolling(&mut h);
assert_inserted(&mut h, "anisotropic_noise");
}
#[test]
fn clearing_a_scrolled_query_reveals_and_inserts_first_match() {
let mut h = search::harness(false);
h.event(Event::Text("noises".into()));
h.step();
scroll(&mut h, 15);
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.step();
h.key_press(Key::Backspace);
h.step();
h.run_steps(25);
assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after clearing");
assert_inserted(&mut h, "bitmap");
}
#[test]
fn reopening_a_scrolled_search_reveals_first_match() {
let mut h = search::harness(false);
scroll(&mut h, 45);
h.key_press(Key::Escape);
h.step();
h.run_steps(3);
h.key_press(Key::Tab);
h.step();
h.run_steps(25);
assert!(h.get_by_label("Search nodes").rect().width() > 0.0);
assert!(search::label_position(&h, "Bitmap").is_some(), "selected first result is offscreen after reopening");
assert_inserted(&mut h, "bitmap");
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn filtered_first_result_screenshot() {
let mut h = search::harness(true);
filter_after_scrolling(&mut h);
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
h.render().unwrap().save(dir.join("filtered-first-result.png")).unwrap();
}
-43
View File
@@ -1,43 +0,0 @@
//! Clicking anywhere across a search result's row should insert that result.
#[path = "common/search.rs"]
mod search;
use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
use egui_kittest::Harness;
use materialcraft_ui_egui::MaterialCraftApp;
fn right_side(h: &Harness<'static, MaterialCraftApp>) -> Pos2 {
let y = search::label_position(h, "Bitmap").unwrap().y;
let popup = h.ctx.memory(|m| m.area_rect(egui::Id::unique("node-search"))).unwrap();
pos2(popup.right() - 24.0, y)
}
fn click(h: &mut Harness<'static, MaterialCraftApp>, pos: Pos2) {
h.event(Event::PointerMoved(pos));
h.step();
for pressed in [true, false] {
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.step();
}
h.run_steps(3);
}
#[test]
fn clicking_label_or_right_side_inserts_the_same_result() {
for right in [false, true] {
let mut h = search::harness(false);
let pos = if right { right_side(&h) } else { search::label_position(&h, "Bitmap").unwrap() + vec2(8.0, 0.0) };
click(&mut h, pos);
let graph = h.state().session.graph().unwrap();
assert_eq!(graph.nodes.len(), 1, "row click did not insert a node (right_side={right})");
assert_eq!(graph.nodes[0].def, "bitmap");
}
}
#[test]
#[ignore = "requires an offscreen GPU"]
fn full_width_result_screenshot() {
let mut h = search::harness(true);
let pos = right_side(&h);
h.event(Event::PointerMoved(pos));
h.run_steps(3);
let dir = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR"));
std::fs::create_dir_all(&dir).unwrap();
h.render().unwrap().save(dir.join("full-width-search-result.png")).unwrap();
}
+21 -1
View File
@@ -111,7 +111,15 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, ctx: &egui
reply(&mut out, Value::Null, json!({"ok": false, "error": "request too large"}));
return;
}
Ok(LineRead::Eof) | Err(_) => return,
Ok(LineRead::Eof) => return,
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
let sent = reply(&mut out, Value::Null, json!({"ok": false, "error": "request is not UTF-8"}));
if !sent || deadline.is_some() {
return;
}
continue;
}
Err(_) => return,
}
if line.trim().is_empty() {
continue;
@@ -230,6 +238,18 @@ mod tests {
assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection");
}
#[test]
fn non_utf8_line_before_auth_gets_refusal_reply() {
let addr = server();
let (mut w, mut r) = connect(addr);
w.write_all(b"\xff\n").unwrap();
w.flush().unwrap();
let mut reply = String::new();
let n = r.read_line(&mut reply).unwrap();
assert!(n > 0, "a non-UTF8 first line gets a refusal reply, not a silent close");
assert_eq!(serde_json::from_str::<Value>(&reply).unwrap()["ok"], false);
}
#[test]
fn connections_are_limited_and_idle_ones_time_out() {
let addr = server();
+1 -1
View File
@@ -125,7 +125,7 @@ mod tests {
assert_eq!(s.pkg.name, "Untitled package");
assert_eq!(s.pkg.graphs.len(), 1);
let g = s.graph().unwrap();
assert_eq!(g.name, "Material_Graph");
assert_eq!(g.name, "New_graph");
assert!(g.nodes.is_empty());
assert!(g.connections.is_empty());
assert!(s.path.is_none());
+1 -1
View File
@@ -227,7 +227,7 @@ impl Headless {
self.light = Some(Lighting::new(&v.environment));
}
let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0);
let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale };
let depth = o.displacement.unwrap_or(v.height_scale);
let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level };
let mut settings = Settings {
yaw: o.yaw.unwrap_or(v.yaw),
+21 -5
View File
@@ -158,11 +158,19 @@ fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &st
let mut authed = false;
let mut deadline = Some(AuthDeadline::start(&w, AUTH_TIMEOUT)?);
loop {
match read_bounded_line(&mut r, &mut line)? {
LineRead::Eof => return Ok(()),
LineRead::TooLong => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})),
LineRead::Line if line.trim().is_empty() => continue,
LineRead::Line => {}
match read_bounded_line(&mut r, &mut line) {
Ok(LineRead::Eof) => return Ok(()),
Ok(LineRead::TooLong) => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})),
Ok(LineRead::Line) if line.trim().is_empty() => continue,
Ok(LineRead::Line) => {}
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request is not UTF-8"}))?;
if !authed {
return Ok(());
}
continue;
}
Err(e) => return Err(e),
}
if authed {
write_reply(&mut w, &respond(h, &line))?;
@@ -338,6 +346,14 @@ mod tests {
assert!(e.contains("disabled for automation"), "{e}");
}
#[test]
fn render_displacement_applies_without_hq() {
let h = session();
let flat = call(&h, "render", json!({"width": 32, "height": 32, "displacement": 0.0})).unwrap();
let strong = call(&h, "render", json!({"width": 32, "height": 32, "displacement": 0.5})).unwrap();
assert_ne!(flat["png"], strong["png"], "displacement must change the 3D relief without hq");
}
#[test]
fn tcp_requires_the_token() {
use std::io::{BufRead, BufReader};
+1 -10
View File
@@ -11,20 +11,11 @@ pub struct Resource {
/// The file's bytes (stored in the zip, not in `package.json`)
#[serde(skip)]
pub bytes: ResourceBytes,
/// A linked resource: the file it is read from (relative to the package's folder when it
/// lies inside it), reloaded by "Reload resources". `None` = embedded in the package
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
}
impl Resource {
/// A resource named `name`, stored as `file` in the package
pub fn new(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes) -> Resource {
Resource { name: name.into(), file: file.into(), bytes, link: None }
}
/// A resource that stays on disk at `link` and is read from there
pub fn linked(name: impl Into<String>, file: impl Into<String>, bytes: ResourceBytes, link: impl Into<String>) -> Resource {
Resource { name: name.into(), file: file.into(), bytes, link: Some(link.into()) }
Resource { name: name.into(), file: file.into(), bytes }
}
}
-2
View File
@@ -48,7 +48,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(crate::file_cmds::specs());
v.extend(crate::resource_cmds::specs());
v.extend(crate::atomic_sample_commands::specs());
v.extend(crate::material_cmds::specs());
v.extend(crate::edit_cmds::specs());
@@ -59,7 +58,6 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::frame_commands::specs());
v.extend(crate::function_commands::specs());
v.extend(crate::comment_commands::specs());
v.extend(crate::pin_commands::specs());
v.extend(crate::node_cmds::specs());
v.extend(crate::node_graph_commands::specs());
v.extend(crate::pattern_graph_commands::specs());
+21 -7
View File
@@ -16,7 +16,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Graph...",
["File", "New"],
Some("Ctrl+N"),
"{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
"{name?, kind? (material|function), template? (see graph.templates), size? (default 1024), width?, height?} adds and opens a graph; material dimensions override size per axis, rounded down to powers of two in 16..8192 px",
always,
new_graph
),
@@ -69,7 +69,8 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1)
};
let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
let log2 = 63 - size.leading_zeros();
let width_log2 = graph_dimension(parameters, "width", size)?;
let height_log2 = graph_dimension(parameters, "height", size)?;
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
session.edit("New graph", |session| {
@@ -79,7 +80,9 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
graph.function = Some(materialcraft_core::FunctionGraph::default());
graph
} else {
template(template_id, &name, log2)?
let mut graph = template(template_id, &name, width_log2)?;
graph.size = [width_log2, height_log2];
graph
};
session.pkg.graphs.push(graph);
session.graph = session.pkg.graphs.len() - 1;
@@ -91,9 +94,17 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
})
}
fn graph_dimension(parameters: &J, axis: &str, default_pixels: u64) -> Result<u32> {
let pixels = match parameters.get(axis) {
Some(value) => value.as_u64().ok_or_else(|| bad("file.new", format!("`{axis}` must be a nonnegative integer in pixels")))?,
None => default_pixels,
};
Ok(63 - pixels.clamp(16, 8192).leading_zeros())
}
fn new_package(s: &mut Session, p: &J) -> Result<J> {
let mut pkg = Package::new(strp(p, "name").unwrap_or("Untitled package"));
pkg.graphs.push(template("pbr", "Material_Graph", 10)?);
pkg.graphs.push(template("pbr", "New_graph", 10)?);
replace_package(s, pkg, None);
Ok(json!({"name": s.pkg.name}))
}
@@ -232,9 +243,7 @@ pub fn export_outputs(s: &Session, gi: usize, ext: &str, pattern: &str, depth: O
}
let g = pkg.graph(gi)?;
let dec = s.resource_decoder();
let mut opts = materialcraft_eval::Options::new(&dec);
opts.max_size = s.cook_limit;
let cooked = materialcraft_eval::cook(&pkg, gi, &opts, &s.cache);
let cooked = materialcraft_eval::cook(&pkg, gi, &materialcraft_eval::Options::new(&dec), &s.cache);
let mut out = Vec::new();
let mut names = std::collections::HashSet::new();
for (id, usage, ident, img) in materialcraft_eval::outputs(g, &cooked) {
@@ -284,6 +293,11 @@ fn export(s: &mut Session, p: &J) -> Result<J> {
let (gi, ext, pattern, depth, size) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth, size)?;
std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?;
for f in &files {
if std::path::Path::new(dir).join(&f.file).exists() {
return Err(bad("file.export", format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", f.file)));
}
}
let mut written = Vec::new();
for f in files {
let path = std::path::Path::new(dir).join(&f.file);
+24 -39
View File
@@ -2,7 +2,7 @@
use serde_json::{Value as J, json};
use materialcraft_core::{ExposedParameter, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value};
use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value};
use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p};
use crate::{Result, Session, cmd};
@@ -13,15 +13,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
cmd!("graph.rename", "Rename graph", [], None, "{name, graph?}", has_graph, rename),
cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete),
cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate),
cmd!(
"graph.add",
"Add graph",
[],
None,
"{graph: a graph as JSON (edit.copy of a graph, graph.get)} adds the graph to the package under a unique name and opens it",
always,
add
),
cmd!("graph.size", "Graph size", [], None, "{width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", has_graph, size),
cmd!("graph.seed", "Random seed", [], None, "{seed}", has_graph, |s, p| {
let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32;
@@ -40,7 +31,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"Expose parameter",
[],
None,
"{id, label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}",
"{id (optional with bind: then named after the parameter and kept unique), label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}",
has_graph,
exposed_add
),
@@ -148,30 +139,6 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> {
})
}
/// Paste a whole graph (the explorer's Copy/Paste): its JSON, renamed when the name is taken.
fn add(s: &mut Session, p: &J) -> Result<J> {
const MAX_NODES: usize = 100_000;
let v = p.get("graph").ok_or_else(|| bad("graph.add", "`graph` is required"))?;
let mut g: materialcraft_core::Graph = serde_json::from_value(v.clone()).map_err(|e| bad("graph.add", format!("not a graph: {e}")))?;
if g.nodes.len() > MAX_NODES {
return Err(bad("graph.add", format!("a graph holds at most {MAX_NODES} nodes")));
}
if g.name.trim().is_empty() {
g.name = "Material_Graph".into();
}
s.edit("Add graph", |s| {
g.name = s.pkg.unique_graph_name(&g.name);
let name = g.name.clone();
s.pkg.graphs.push(g);
s.graph = s.pkg.graphs.len() - 1;
s.open_material_preview();
s.selection.clear();
s.annotation_selection = None;
s.view2d.node = None;
Ok(json!({"graph": s.graph, "name": name}))
})
}
fn size(s: &mut Session, p: &J) -> Result<J> {
let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros();
let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) {
@@ -258,12 +225,21 @@ fn pin_delete(s: &mut Session, p: &J) -> Result<J> {
}
fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
let id = strp(p, "id").map(str::trim).filter(|i| !i.is_empty()).ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?.to_string();
if s.graph()?.exposed.iter().any(|e| e.id == id) {
return Err(bad("graph.exposed.add", format!("an input is already called `{id}`")));
}
// From a bound node parameter: its value, range and options become the input's
let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string())));
let id = match strp(p, "id").map(str::trim).filter(|i| !i.is_empty()) {
Some(id) => {
if s.graph()?.exposed.iter().any(|e| e.id == id) {
return Err(bad("graph.exposed.add", format!("an input is already called `{id}`")));
}
id.to_string()
}
// Without an `id`, a bound input is named after its parameter, kept unique across nodes
None => {
let (_, param) = bind.as_ref().ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?;
unique_exposed_id(s.graph()?, param)
}
};
let mut default = Value::Float(0.5);
let (mut min, mut max, mut options) = (0.0f32, 1.0f32, Vec::new());
if let Some((node, param)) = &bind {
@@ -299,6 +275,15 @@ fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
})
}
/// An input id not used in `graph`: `base`, `base_1`, `base_2`…
fn unique_exposed_id(graph: &Graph, base: &str) -> String {
let taken = |id: &str| graph.exposed.iter().any(|e| e.id == id);
if !taken(base) {
return base.to_string();
}
(1..).map(|i| format!("{base}_{i}")).find(|id| !taken(id)).unwrap_or_else(|| base.to_string())
}
fn exposed_set(s: &mut Session, p: &J) -> Result<J> {
let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.set", "`id` is required"))?.to_string();
let v = p.get("value").ok_or_else(|| bad("graph.exposed.set", "`value` is required"))?;
-5
View File
@@ -25,7 +25,6 @@ pub mod graph_grid;
pub mod inspect;
pub mod material_cmds;
pub mod node_cmds;
pub mod resource_cmds;
pub mod samples;
pub mod session;
mod value_input_commands;
@@ -37,13 +36,10 @@ pub use session::{CameraPrefs, Session, View2d, View3d, WARNING_PREFIX};
mod clip;
mod connection_commands;
pub use clip::Clip;
mod view3d_settings;
pub use view3d_settings::{Camera3d, Display3d, Lights3d, Material3d, Renderer3d};
pub use materialcraft_core as core;
pub use materialcraft_eval as eval;
pub use materialcraft_formats as formats;
pub use materialcraft_geom as geom;
pub use materialcraft_image as image;
pub use materialcraft_nodes as nodes;
@@ -76,7 +72,6 @@ mod frame_contents;
mod function_commands;
mod node_graph_commands;
mod pattern_graph_commands;
mod pin_commands;
mod snapshot;
pub use annotation_selection::AnnotationSelection;
pub use frame_contents::FrameContents;
+46 -1
View File
@@ -162,7 +162,7 @@ fn export_material(s: &mut Session, p: &J) -> Result<J> {
for (id, file) in p.get("inputs").and_then(J::as_object).into_iter().flatten() {
let file = file.as_str().ok_or_else(|| bad(CMD, format!("inputs.{id} must be an image path")))?;
let bytes = std::fs::read(file).map_err(|e| bad(CMD, format!("{file}: {e}")))?;
o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, false)?);
o.inputs.insert(id.clone(), materialcraft_formats::decode(&bytes, !srgb_usage(id))?);
}
let bytes = material_bytes(s, gi, &o)?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
@@ -312,4 +312,49 @@ mod tests {
assert!(values_param("t", g, &json!({"values": {"no_such_input": 1}})).is_err());
assert!(values_param("t", g, &json!({})).unwrap().is_empty());
}
#[test]
fn export_material_decodes_data_inputs_as_linear() {
#[cfg(not(target_arch = "wasm32"))]
{
use materialcraft_formats::decode;
let mut s = crate::sample_session();
let input =
crate::execute(&mut s, "graph.node.add", &json!({"def": "input_color", "params": {"identifier": "normal"}})).unwrap()["id"].as_u64().unwrap();
let output =
crate::execute(&mut s, "graph.node.add", &json!({"def": "output", "params": {"usage": ComponentUsage::index("normal")}})).unwrap()["id"]
.as_u64()
.unwrap();
crate::execute(&mut s, "graph.connect", &json!({"from": input, "to": output})).unwrap();
let png = encode(&Image::filled(16, 16, materialcraft_image::Kind::Color, [128.0 / 255.0; 4]), "png", Depth::U16, false).unwrap();
let dir = std::env::temp_dir().join(format!("materialcraft-linear-input-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("normal.png");
std::fs::write(&file, &png).unwrap();
let input_path = file.to_str().unwrap().to_string();
let output_path = dir.join("out.mcmat").to_str().unwrap().to_string();
let result = crate::execute(&mut s, "file.exportMaterial", &json!({"path": output_path, "size": 16, "inputs": {"normal": input_path}}));
assert!(result.is_ok());
let bytes = std::fs::read(&output_path).unwrap();
let _ = std::fs::remove_dir_all(&dir);
// The material archive stores maps uncompressed; pull the normal map
// out of its local file header and decode it as linear data.
let name = b"maps/normal.png";
let pos = bytes.windows(name.len()).position(|w| w == name).unwrap();
let header = pos - 30;
assert_eq!(&bytes[header..header + 4], b"PK\x03\x04");
let name_len = u16::from_le_bytes([bytes[header + 26], bytes[header + 27]]) as usize;
let extra_len = u16::from_le_bytes([bytes[header + 28], bytes[header + 29]]) as usize;
let compressed = u32::from_le_bytes([bytes[header + 18], bytes[header + 19], bytes[header + 20], bytes[header + 21]]) as usize;
let start = header + 30 + name_len + extra_len;
let map = &bytes[start..start + compressed];
let decoded = decode(map, true).unwrap();
assert!((decoded.get(0, 0, false)[0] - 128.0 / 255.0).abs() < 1e-3, "data inputs must be decoded as linear");
}
}
}
-29
View File
@@ -1,29 +0,0 @@
//! Editing a navigation pin after it was added: its name and where it sits
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
use crate::{Result, Session, cmd};
use serde_json::{Value as J, json};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!("graph.pin.edit", "Edit pin", [], None, "{id, name?, at? [x, y]}", has_graph, pin_edit)]
}
fn pin_edit(session: &mut Session, parameters: &J) -> Result<J> {
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.edit", "`id` is required"))?;
let name = strp(parameters, "name").map(str::trim).filter(|name| !name.is_empty()).map(str::to_string);
let at = point(parameters, "at");
if name.is_none() && at.is_none() {
return Err(bad("graph.pin.edit", "`name` or `at` is required"));
}
let label = if at.is_some() { "Move pin" } else { "Rename pin" };
session.edit(label, |session| {
let pin = session.graph_mut()?.pins.iter_mut().find(|pin| pin.id == id).ok_or_else(|| bad("graph.pin.edit", format!("no pin {id}")))?;
if let Some(name) = name {
pin.name = name;
}
if let Some(at) = at {
pin.pos = at;
}
Ok(json!({"id": pin.id, "name": pin.name, "at": pin.pos}))
})
}
-384
View File
@@ -1,384 +0,0 @@
//! Package resources and dependencies: linked bitmaps (read from disk, reloaded on demand),
//! resource removal, graphs imported from other package files, copies of the package with its
//! dependencies, and the session's size settings (history, cache, cooking limit)
use serde_json::{Value as J, json};
use materialcraft_core::{Package, ResourceBytes, Value};
use crate::commands::{CommandSpec, always, bad, strp, u64p};
use crate::{Result, Session, cmd};
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"file.linkBitmap",
"Link bitmap...",
["File"],
None,
"{path, name?} adds an image file as a linked resource (read from disk, reloaded by file.reloadResources; saved as a link when the file lies in the package's folder); returns its name",
always,
link_bitmap
),
cmd!(
"file.reloadResources",
"Reload resources",
["File"],
None,
"{} reads every linked resource from its file again; returns the names reloaded and those whose file is missing",
always,
reload_resources
),
cmd!(
"file.deleteResource",
"Remove resource",
[],
None,
"{name} removes a bitmap resource; the nodes that used it show an error until they get another",
always,
delete_resource
),
cmd!(
"file.importGraph",
"Import graph...",
["File"],
None,
"{path, graph?} copies a graph (default: the first) of another package file into this one, with the graphs it instances and the bitmaps it uses; returns the new graph's name",
always,
import_graph
),
cmd!(
"file.packageGraphs",
"Graphs of a package file",
[],
None,
"{path} lists the graphs of a package file without opening it: [{name, kind, outputs}]",
always,
package_graphs
),
cmd!(
"file.saveCopy",
"Save a copy as...",
["File"],
None,
"{path} writes the package to `path` while the session keeps its own file",
always,
save_copy
),
cmd!(
"file.exportWithDependencies",
"Export with dependencies...",
["File"],
None,
"{dir} writes the package and copies of its linked bitmaps into `dir`, the links made relative; returns the files written",
always,
export_with_dependencies
),
cmd!(
"session.settings",
"Session settings",
[],
None,
"{historySize? (1..10000 undo steps), cacheMb? (16..65536, the cooked image cache), cookLimit? (256..8192 px, or 0 for none: caps every cook, exports included)} sets what is given; returns all three",
always,
session_settings
),
]
}
/// Read package bytes without touching the session: SBS, or a `.mcmat` material's source
pub fn load_bytes(bytes: &[u8], name: &str, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Package> {
if materialcraft_formats::material::is_material(bytes) {
let (_, source) = materialcraft_formats::material::read_material(bytes)?;
return Ok(materialcraft_formats::sbs::read_sbs(&source, "source.sbs", &|_| None)?.pkg);
}
Ok(materialcraft_formats::sbs::read_sbs(bytes, name, linked)?.pkg)
}
/// Copy `graph` of `from` into the session's package: the graph, every graph it instances
/// (recursively) and the bitmap resources its nodes use. Graphs that already exist with the
/// same name are reused when identical, else the copy gets a unique name and the instances
/// that point at it follow. Returns the copied graph's name
pub fn import_graph_from(s: &mut Session, from: &Package, graph: &str) -> Result<String> {
let (_, root) = from.graph_by_name(graph).ok_or_else(|| bad("file.importGraph", format!("`{}` has no graph `{graph}`", from.name)))?;
// Walk the instance tree, deepest dependencies first so renames are known when they are used
let mut order: Vec<String> = Vec::new();
let mut stack = vec![root.name.clone()];
while let Some(name) = stack.pop() {
if order.contains(&name) {
continue;
}
order.push(name.clone());
if let Some((_, g)) = from.graph_by_name(&name) {
for n in g.nodes.iter().filter(|n| n.def == "graph_instance") {
if let Some(Value::Text(t)) = n.params.get("graph")
&& !order.contains(t)
{
stack.push(t.clone());
}
}
}
}
order.reverse();
let from = from.clone();
let root_name = root.name.clone();
s.edit("Import graph", |s| {
let mut renamed: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
for name in &order {
let Some((_, g)) = from.graph_by_name(name) else { continue };
let mut g = g.clone();
for n in g.nodes.iter_mut() {
if n.def == "graph_instance"
&& let Some(Value::Text(t)) = n.params.get("graph").cloned()
&& let Some(new) = renamed.get(&t)
{
n.params.insert("graph".into(), Value::Text(new.clone()));
}
if let Some(Value::Text(r)) = n.params.get("resource").cloned()
&& let Some(res) = from.resource(&r)
&& s.pkg.resource(&r).is_none()
{
s.pkg.resources.push(res.clone());
}
}
if let Some((_, have)) = s.pkg.graph_by_name(name)
&& *have == g
{
renamed.insert(name.clone(), name.clone());
continue;
}
let new = s.pkg.unique_graph_name(name);
g.name = new.clone();
renamed.insert(name.clone(), new);
s.pkg.graphs.push(g);
}
Ok(renamed.get(&root_name).cloned().unwrap_or(root_name))
})
}
#[cfg(not(target_arch = "wasm32"))]
fn load_file(cmd: &str, p: &J) -> Result<(String, Package)> {
let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
Ok((path.to_string(), load_bytes(&bytes, path, &crate::file_cmds::linked_files(path))?))
}
#[cfg(not(target_arch = "wasm32"))]
fn import_graph(s: &mut Session, p: &J) -> Result<J> {
let (_, from) = load_file("file.importGraph", p)?;
let graph = match strp(p, "graph") {
Some(g) => g.to_string(),
None => from.graphs.first().map(|g| g.name.clone()).ok_or_else(|| bad("file.importGraph", "the package has no graphs"))?,
};
let name = import_graph_from(s, &from, &graph)?;
Ok(json!({"name": name}))
}
#[cfg(target_arch = "wasm32")]
fn import_graph(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.importGraph", "the browser has no package files to import from"))
}
#[cfg(not(target_arch = "wasm32"))]
fn package_graphs(_: &mut Session, p: &J) -> Result<J> {
let (_, from) = load_file("file.packageGraphs", p)?;
Ok(json!(
from.graphs
.iter()
.map(|g| json!({"name": g.name, "kind": format!("{:?}", g.kind()), "outputs": g.nodes.iter().filter(|n| n.def == "output").count()}))
.collect::<Vec<_>>()
))
}
#[cfg(target_arch = "wasm32")]
fn package_graphs(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.packageGraphs", "the browser has no package files to read"))
}
/// The path a linked file is stored under: relative to the package's folder when it lies
/// inside it (then the link survives in the saved file), else as given
#[cfg(not(target_arch = "wasm32"))]
fn link_path(s: &Session, path: &str) -> String {
let Some(folder) = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).and_then(|p| std::fs::canonicalize(p).ok()) else {
return path.to_string();
};
match std::fs::canonicalize(path).ok().and_then(|f| f.strip_prefix(&folder).ok().map(|r| r.to_path_buf())) {
Some(rel) => rel.to_string_lossy().replace('\\', "/"),
None => path.to_string(),
}
}
/// Read a linked resource's file: a relative link resolves next to the package
#[cfg(not(target_arch = "wasm32"))]
fn read_link(s: &Session, link: &str) -> std::result::Result<Vec<u8>, String> {
let plain = !link.contains(':') && !link.starts_with('/') && !link.starts_with('\\');
if plain && let Some(path) = &s.path {
return crate::file_cmds::linked_files(path)(link).ok_or_else(|| format!("`{link}` was not found next to the package"));
}
std::fs::read(link).map_err(|e| format!("{link}: {e}"))
}
#[cfg(not(target_arch = "wasm32"))]
fn link_bitmap(s: &mut Session, p: &J) -> Result<J> {
let path = strp(p, "path").ok_or_else(|| bad("file.linkBitmap", "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad("file.linkBitmap", format!("{path}: {e}")))?;
materialcraft_formats::decode(&bytes, false)?;
let file = std::path::Path::new(path).file_name().and_then(|f| f.to_str()).unwrap_or("bitmap.png").to_string();
let link = link_path(s, path);
let wanted = strp(p, "name").map(str::to_string);
let name = s.edit("Link bitmap", |s| {
// Relinking an existing resource keeps its name (the nodes that use it stay valid)
if let Some(r) = wanted.as_deref().and_then(|w| s.pkg.resources.iter_mut().find(|r| r.name == w)) {
r.bytes = ResourceBytes::new(bytes);
r.link = Some(link.clone());
return Ok(r.name.clone());
}
let name = crate::file_cmds::push_resource(&mut s.pkg, &file, bytes, wanted.as_deref());
if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) {
r.link = Some(link.clone());
}
Ok(name)
})?;
s.clear_decoded();
Ok(json!({"name": name, "link": link, "use": {"command": "graph.node.add", "params": {"def": "bitmap", "params": {"resource": name}}}}))
}
#[cfg(target_arch = "wasm32")]
fn link_bitmap(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.linkBitmap", "the browser has no files to link to; import the bitmap instead"))
}
#[cfg(not(target_arch = "wasm32"))]
fn reload_resources(s: &mut Session, _: &J) -> Result<J> {
let links: Vec<(String, String)> = s.pkg.resources.iter().filter_map(|r| r.link.clone().map(|l| (r.name.clone(), l))).collect();
let mut fresh: Vec<(String, Vec<u8>)> = Vec::new();
let mut missing: Vec<String> = Vec::new();
for (name, link) in links {
match read_link(s, &link) {
Ok(bytes) => fresh.push((name, bytes)),
Err(why) => {
s.log(format!("resource `{name}` not reloaded: {why}"));
missing.push(name);
}
}
}
let changed: Vec<String> =
fresh.iter().filter(|(n, b)| s.pkg.resources.iter().any(|r| &r.name == n && r.bytes.as_slice() != b.as_slice())).map(|(n, _)| n.clone()).collect();
if !changed.is_empty() {
s.edit("Reload resources", |s| {
for (name, bytes) in fresh {
if let Some(r) = s.pkg.resources.iter_mut().find(|r| r.name == name) {
r.bytes = ResourceBytes::new(bytes);
}
}
Ok(())
})?;
s.clear_decoded();
}
s.dirty = true;
Ok(json!({"reloaded": changed, "missing": missing}))
}
#[cfg(target_arch = "wasm32")]
fn reload_resources(s: &mut Session, _: &J) -> Result<J> {
s.dirty = true;
Ok(json!({"reloaded": [], "missing": []}))
}
fn delete_resource(s: &mut Session, p: &J) -> Result<J> {
let name = strp(p, "name").ok_or_else(|| bad("file.deleteResource", "`name` is required"))?.to_string();
if s.pkg.resource(&name).is_none() {
return Err(bad("file.deleteResource", format!("no resource `{name}`")));
}
s.edit("Remove resource", |s| {
s.pkg.resources.retain(|r| r.name != name);
Ok(J::Null)
})?;
s.clear_decoded();
Ok(json!({"name": name}))
}
#[cfg(not(target_arch = "wasm32"))]
fn save_copy(s: &mut Session, p: &J) -> Result<J> {
let path = crate::file_cmds::package_path(strp(p, "path").ok_or_else(|| bad("file.saveCopy", "`path` is required"))?);
let bytes = crate::file_cmds::save_bytes(s)?;
materialcraft_formats::write_atomic(std::path::Path::new(&path), &bytes)?;
s.log(format!("Saved a copy to {path}"));
Ok(json!({"path": path, "bytes": bytes.len()}))
}
#[cfg(target_arch = "wasm32")]
fn save_copy(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.saveCopy", "the browser saves with a download"))
}
#[cfg(not(target_arch = "wasm32"))]
fn export_with_dependencies(s: &mut Session, p: &J) -> Result<J> {
let dir = strp(p, "dir").ok_or_else(|| bad("file.exportWithDependencies", "`dir` is required"))?;
let dir = std::path::Path::new(dir);
std::fs::create_dir_all(dir).map_err(|e| bad("file.exportWithDependencies", format!("{}: {e}", dir.display())))?;
let mut written: Vec<String> = Vec::new();
// The copy links every linked bitmap by its file name, next to the package
let mut pkg = s.pkg.clone();
let mut used: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for r in pkg.resources.iter_mut() {
let Some(link) = r.link.clone() else { continue };
let bytes = match read_link(s, &link) {
Ok(b) => b,
Err(why) => {
s.log(format!("`{}` exported embedded: {why}", r.name));
r.link = None;
continue;
}
};
let base = std::path::Path::new(&link).file_name().and_then(|f| f.to_str()).unwrap_or(&r.file).to_string();
let mut file = base.clone();
let mut n = 2;
while !used.insert(file.clone()) {
file = match base.rsplit_once('.') {
Some((stem, ext)) => format!("{stem}_{n}.{ext}"),
None => format!("{base}_{n}"),
};
n += 1;
}
let target = dir.join(&file);
materialcraft_formats::write_atomic(&target, &bytes)?;
written.push(target.display().to_string());
r.link = Some(file);
r.bytes = ResourceBytes::new(bytes);
}
let name = format!("{}.{}", materialcraft_formats::safe_file_name(&pkg.name), materialcraft_formats::sbs::SBS_EXT);
let target = dir.join(&name);
let bytes = materialcraft_formats::sbs::write_sbs(&pkg)?;
materialcraft_formats::write_atomic(&target, &bytes)?;
written.insert(0, target.display().to_string());
s.log(format!("Exported {} with {} dependency file(s) to {}", pkg.name, written.len() - 1, dir.display()));
Ok(json!({"files": written}))
}
#[cfg(target_arch = "wasm32")]
fn export_with_dependencies(_: &mut Session, _: &J) -> Result<J> {
Err(bad("file.exportWithDependencies", "the browser saves with a download"))
}
fn session_settings(s: &mut Session, p: &J) -> Result<J> {
if let Some(n) = u64p(p, "historySize") {
s.max_undo = n.clamp(1, 10_000) as usize;
s.trim_undo();
}
if let Some(mb) = u64p(p, "cacheMb") {
let bytes = (mb.clamp(16, 65_536) as usize) << 20;
if let Ok(mut c) = s.cache.lock() {
c.set_cap(bytes);
}
}
if let Some(px) = u64p(p, "cookLimit") {
let limit = if px == 0 { None } else { Some(px.clamp(256, 8192) as u32) };
if limit != s.cook_limit {
s.cook_limit = limit;
s.dirty = true;
}
}
let cache_mb = s.cache.lock().map(|c| c.cap() >> 20).unwrap_or(0);
Ok(json!({"historySize": s.max_undo, "cacheMb": cache_mb, "cookLimit": s.cook_limit.unwrap_or(0)}))
}
+5 -25
View File
@@ -13,9 +13,6 @@ pub fn template(id: &str, name: &str, size_log2: u32) -> Result<Graph> {
graph.name = name.to_string();
graph.size = [size_log2, size_log2];
if id == "pbr" {
// Uniform colors into every output; the normal is derived from the height, so a height
// wired in shows up in the 3D view right away (as a normal map, and as relief).
let mut height_source = None;
for (index, (identifier, color)) in [
("basecolor", [0.5, 0.5, 0.5, 1.0]),
("normal", [0.5, 0.5, 1.0, 1.0]),
@@ -27,32 +24,15 @@ pub fn template(id: &str, name: &str, size_log2: u32) -> Result<Graph> {
.into_iter()
.enumerate()
{
let y = index as f32 * 180.0;
let output = graph.add_node("output", [440.0, y]);
let source = graph.add_node("uniform", [0.0, index as f32 * 180.0]);
let node = graph.node_mut(source)?;
node.params.insert("color_mode".into(), Value::Bool(index <= 1));
node.params.insert("color".into(), Value::Color(color));
let output = graph.add_node("output", [220.0, index as f32 * 180.0]);
let node = graph.node_mut(output)?;
node.params.insert("identifier".into(), Value::Text(identifier.into()));
node.params.insert("usage".into(), Value::Enum(index as u32));
if identifier == "normal" {
// Filled in below, from the height
continue;
}
let source = graph.add_node("uniform", [0.0, y]);
let node = graph.node_mut(source)?;
node.params.insert("color_mode".into(), Value::Bool(index == 0));
node.params.insert("color".into(), Value::Color(color));
graph.connect(source, "output", output, "input")?;
if identifier == "height" {
height_source = Some(source);
}
}
let normal = graph.add_node("normal", [220.0, 180.0]);
graph.node_mut(normal)?.params.insert("intensity".into(), Value::Float(2.0));
if let Some(height) = height_source {
graph.connect(height, "output", normal, "input")?;
}
let normal_output = graph.nodes.iter().find(|n| n.def == "output" && n.params.get("identifier") == Some(&Value::Text("normal".into()))).map(|n| n.id);
if let Some(output) = normal_output {
graph.connect(normal, "output", output, "input")?;
}
}
Ok(graph)
+9 -60
View File
@@ -10,11 +10,10 @@ use materialcraft_image::Image;
use serde::{Deserialize, Serialize};
use crate::snapshot::Snapshot;
use crate::view3d_settings::{Camera3d, Display3d, Lights3d, Material3d, Renderer3d};
use crate::{AnnotationSelection, Clip, EngineError, Result};
/// Undo keeps this many steps unless the session says otherwise.
pub const MAX_UNDO: usize = 200;
/// Undo keeps this many steps.
const MAX_UNDO: usize = 200;
/// The 3D view's scene and look.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -45,28 +44,6 @@ pub struct View3d {
pub transparency: bool,
/// Show the material's alpha channel on the mesh instead of the lit material.
pub alpha_view: bool,
/// Camera ▸ Edit properties.
pub camera: Camera3d,
/// Lights ▸ Edit properties.
pub lights: Lights3d,
/// Environment ▸ Edit properties: the environment lights the scene.
pub env_enabled: bool,
/// Renderer ▸ Edit settings.
pub renderer: Renderer3d,
/// Display menu toggles.
pub display: Display3d,
/// Materials ▸ Default ▸ Edit properties.
pub material: Material3d,
}
impl View3d {
/// Every nested value brought into its range (after a command merged JSON in).
pub fn sanitize(&mut self) {
self.camera.sanitize();
self.lights.sanitize();
self.renderer.sanitize();
self.material.sanitize();
}
}
impl Default for View3d {
@@ -88,12 +65,6 @@ impl Default for View3d {
show_grid: false,
transparency: true,
alpha_view: false,
camera: Camera3d::default(),
lights: Lights3d::default(),
env_enabled: true,
renderer: Renderer3d::default(),
display: Display3d::default(),
material: Material3d::default(),
}
}
}
@@ -180,10 +151,6 @@ pub struct Session {
pub cache: Arc<Mutex<Cache>>,
/// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry.
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
/// Undo steps kept (Preferences ▸ History stack size).
pub max_undo: usize,
/// Cap on the larger side of every cook, previews and exports alike (Preferences ▸ Cooking size limit).
pub cook_limit: Option<u32>,
undo: Vec<Snapshot>,
redo: Vec<Snapshot>,
/// Edits with the same key coalesce into one undo step (slider drags).
@@ -217,8 +184,6 @@ impl Session {
cook_epoch: 0,
cache: Arc::new(Mutex::new(Cache::default())),
custom_mesh: None,
max_undo: MAX_UNDO,
cook_limit: None,
undo: Vec::new(),
redo: Vec::new(),
merge_key: None,
@@ -346,7 +311,9 @@ impl Session {
fn record_undo(&mut self, snapshot: Snapshot) {
self.undo.push(snapshot);
self.trim_undo();
if self.undo.len() > MAX_UNDO {
self.undo.remove(0);
}
self.redo.clear();
}
@@ -382,23 +349,6 @@ impl Session {
self.undo.iter().map(|s| s.label.clone()).collect()
}
/// Drop the oldest undo steps past `max_undo`.
pub fn trim_undo(&mut self) {
let max = self.max_undo.max(1);
if self.undo.len() > max {
let extra = self.undo.len() - max;
self.undo.drain(..extra);
}
}
/// The preview cap and the cooking size limit, whichever is smaller.
pub fn cook_size(&self, preview: Option<u32>) -> Option<u32> {
match (preview, self.cook_limit) {
(Some(p), Some(l)) => Some(p.min(l)),
(p, l) => p.or(l),
}
}
pub fn undo(&mut self) -> Option<String> {
self.end_group();
let s = self.undo.pop()?;
@@ -407,7 +357,7 @@ impl Session {
self.redo.push(cur);
self.restore(s);
self.merge_key = None;
self.changed();
self.dirty = true;
Some(label)
}
@@ -419,7 +369,7 @@ impl Session {
self.undo.push(cur);
self.restore(s);
self.merge_key = None;
self.changed();
self.dirty = true;
Some(label)
}
@@ -459,7 +409,7 @@ impl Session {
pub fn cook(&mut self) -> &Cooked {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
opts.max_size = self.cook_size(self.preview_size);
opts.max_size = self.preview_size;
let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache);
self.accept_preview(cooked);
self.dirty = false;
@@ -480,8 +430,7 @@ impl Session {
/// Cook graph `gi` at full size, without touching the preview results.
pub fn cook_full(&self, gi: usize) -> Cooked {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
opts.max_size = self.cook_limit;
let opts = Options::new(&dec);
materialcraft_eval::cook(&self.pkg, gi, &opts, &self.cache)
}
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::session::Session;
fn normal_map_session() -> Session {
let mut pkg = Package::new("T");
let png = encode(&Image::filled(4, 4, Kind::Color, [0.5, 0.5, 1.0, 1.0]), "png", Depth::U8, false).unwrap();
pkg.resources.push(Resource::new("n", "n.png", materialcraft_core::ResourceBytes::new(png)));
pkg.resources.push(Resource { name: "n".into(), file: "n.png".into(), bytes: materialcraft_core::ResourceBytes::new(png) });
Session::new(pkg)
}
+1 -1
View File
@@ -3,7 +3,7 @@ use crate::{Session, core};
/// A fresh, unsaved package with one empty graph, used at desktop and browser startup
pub fn new_session() -> Session {
let mut pkg = core::Package::new("Untitled package");
pkg.graphs.push(core::Graph::new("Material_Graph"));
pkg.graphs.push(core::Graph::new("New_graph"));
Session::new(pkg)
}
-171
View File
@@ -1,171 +0,0 @@
//! The 3D view's property pages as session state: camera, lights, renderer, display toggles and
//! the material's common values. Every field is clamped by `sanitize` after a command merges JSON in.
use serde::{Deserialize, Serialize};
pub use materialcraft_geom::preview::{Common, MapUse, PointLight, Shader};
/// The 3D view's camera properties.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Camera3d {
/// Millimetres (a 36 mm frame): 35 mm ≈ 35° vertical field of view on a 3:2 frame.
pub focal_length: f32,
/// `perspective` or `orthographic`.
pub projection: String,
/// `backdrop`, `color` or `environment`.
pub background: String,
/// Linear RGBA.
pub background_color: [f32; 4],
/// Render at a fixed resolution (Save Render) instead of the viewport's.
pub override_resolution: bool,
pub resolution: [u32; 2],
/// Multiplier on the render resolution.
pub resolution_scale: f32,
/// Clip planes from the scene size; else `near`/`far` in mesh radii from the camera.
pub auto_clip: bool,
pub near: f32,
pub far: f32,
}
impl Default for Camera3d {
fn default() -> Self {
Camera3d {
focal_length: 35.0,
projection: "perspective".into(),
background: "backdrop".into(),
background_color: [0.016, 0.016, 0.016, 1.0],
override_resolution: false,
resolution: [1920, 1080],
resolution_scale: 1.0,
auto_clip: true,
near: 0.1,
far: 100.0,
}
}
}
impl Camera3d {
/// Vertical field of view in degrees for the focal length (36 × 24 mm frame).
pub fn fov(&self) -> f32 {
(2.0 * (12.0 / self.focal_length.max(1.0)).atan()).to_degrees().clamp(5.0, 120.0)
}
pub(crate) fn sanitize(&mut self) {
let d = Camera3d::default();
let f = |v: f32, lo: f32, hi: f32, dv: f32| if v.is_finite() { v.clamp(lo, hi) } else { dv };
self.focal_length = f(self.focal_length, 4.0, 1200.0, d.focal_length);
if !["perspective", "orthographic"].contains(&self.projection.as_str()) {
self.projection = d.projection;
}
if !["backdrop", "color", "environment"].contains(&self.background.as_str()) {
self.background = d.background;
}
for (i, v) in self.background_color.iter_mut().enumerate() {
*v = f(*v, 0.0, 1.0, d.background_color[i]);
}
self.resolution = self.resolution.map(|v| v.clamp(16, 8192));
self.resolution_scale = f(self.resolution_scale, 0.1, 4.0, d.resolution_scale);
self.near = f(self.near, 0.001, 1000.0, d.near);
self.far = f(self.far, 0.01, 10_000.0, d.far).max(self.near * 1.01);
}
}
/// The 3D view's lights: an ambient term and two point lights.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Lights3d {
pub ambient_on: bool,
/// Linear RGB.
pub ambient: [f32; 3],
pub point: [PointLight; 2],
}
impl Default for Lights3d {
fn default() -> Self {
Lights3d { ambient_on: true, ambient: [0.0; 3], point: PointLight::DEFAULTS }
}
}
impl Lights3d {
pub(crate) fn sanitize(&mut self) {
for v in self.ambient.iter_mut() {
*v = if v.is_finite() { v.clamp(0.0, 16.0) } else { 0.0 };
}
let d = PointLight::DEFAULTS;
self.point = [self.point[0].sanitized(d[0]), self.point[1].sanitized(d[1])];
}
}
/// Renderer ▸ Edit settings.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Renderer3d {
pub use_viewport_resolution: bool,
pub resolution: [u32; 2],
/// Resolution scale of the viewport render (0.25..2).
pub scale: f32,
/// Supersampling of the resting frame (1..4 per axis).
pub samples: u32,
/// Ray-traced ambient occlusion rays per sample (0 = off).
pub ao_rays: u32,
}
impl Default for Renderer3d {
fn default() -> Self {
Renderer3d { use_viewport_resolution: true, resolution: [1920, 1080], scale: 1.0, samples: 2, ao_rays: 0 }
}
}
impl Renderer3d {
pub(crate) fn sanitize(&mut self) {
self.resolution = self.resolution.map(|v| v.clamp(16, 4096));
self.scale = if self.scale.is_finite() { self.scale.clamp(0.25, 2.0) } else { 1.0 };
self.samples = self.samples.clamp(1, 4);
self.ao_rays = self.ao_rays.min(64);
}
}
/// Display menu toggles.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Display3d {
pub wireframe: bool,
pub backface_culling: bool,
pub bounding_box: bool,
/// Draw the point lights.
pub lights: bool,
/// Overlay the render resolution.
pub resolution: bool,
/// Overlay the scene statistics (triangles, maps).
pub stats: bool,
/// Overlay the frame rate.
pub fps: bool,
}
/// Materials ▸ Default: the shading model and what each channel is without a map.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Material3d {
pub shader: Shader,
pub common: Common,
pub use_map: MapUse,
/// Displacement subdivision budget multiplier (0.1..4).
pub tessellation: f32,
/// Extra UV scale of the material on the mesh.
pub uv_scale: [f32; 2],
}
impl Default for Material3d {
fn default() -> Self {
Material3d { shader: Shader::OpenPbr, common: Common::default(), use_map: MapUse::default(), tessellation: 1.0, uv_scale: [1.0, 1.0] }
}
}
impl Material3d {
pub(crate) fn sanitize(&mut self) {
self.common = self.common.sanitized();
self.tessellation = if self.tessellation.is_finite() { self.tessellation.clamp(0.1, 4.0) } else { 1.0 };
self.uv_scale = self.uv_scale.map(|v| if v.is_finite() { v.clamp(0.01, 64.0) } else { 1.0 });
}
}
+6 -141
View File
@@ -12,19 +12,14 @@ pub const SCENES: &[(&str, &str)] = &[
("cube", "Cube"),
("cylinder", "Cylinder"),
("plane", "Plane"),
("plane_hires", "Plane (hi-res)"),
("sphere", "Sphere"),
("cloth", "Cloth"),
("material_ball", "Mat ball"),
("rounded_cube", "Rounded cube"),
("rounded_cylinder", "Rounded cylinder"),
("sphere_2_tiles", "Sphere 2 tiles"),
("torus", "Torus"),
];
/// Environments: (id, label).
pub const ENVIRONMENTS: &[(&str, &str)] =
&[("studio", "Studio"), ("contrast", "Studio contrast"), ("warehouse", "Warehouse"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")];
pub const ENVIRONMENTS: &[(&str, &str)] = &[("studio", "Studio"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")];
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
@@ -34,24 +29,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"3D view settings",
[],
None,
"{scene? (cube|cylinder|plane|plane_hires|sphere|cloth|material_ball|rounded_cube|rounded_cylinder|sphere_2_tiles|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night|contrast|warehouse), envRotation?, exposure?, envEnabled?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel), camera? ({focalLength, projection, background, backgroundColor, overrideResolution, resolution, resolutionScale, autoClip, near, far}: the keys given change), lights? ({ambientOn, ambient, point: [{on, color, intensity, position}, …]}), renderer? ({useViewportResolution, resolution, scale, samples, aoRays}), display? ({wireframe, backfaceCulling, boundingBox, lights, resolution, stats, fps}), material? ({shader, common: {…}, useMap: {…}, tessellation, uvScale})} returns the whole 3D view state",
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), normalYFlip? (DirectX normal maps; default false/OpenGL), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}",
always,
view3d
),
cmd!("view.3d.loadMesh", "Load mesh...", [], None, "{path} shows an OBJ, glTF or GLB mesh in the 3D view (scene \"custom\")", always, load_mesh),
cmd!("view.3d.reset", "Reset scene", [], None, "{what?: all|scene|camera|lights|environment|material|renderer|display} (default all)", always, reset3d),
cmd!("view.3d.state", "3D view state", [], None, "{} the whole 3D view state as JSON (Scene ▸ Save current state)", always, |s, _| Ok(
serde_json::to_value(&s.view3d).unwrap_or(J::Null)
)),
cmd!(
"view.3d.loadState",
"Load 3D view state",
[],
None,
"{state: JSON from view.3d.state, keepScene?: bool} restores the 3D view",
always,
load_state
),
cmd!("view.3d.reset", "Reset scene", [], None, "{}", always, |s, _| {
s.view3d = crate::View3d::default();
Ok(J::Null)
}),
cmd!("view.previewSize", "Preview size", [], None, "{size: 64..8192, or 0 for full size} caps node outputs while editing", always, preview_size),
cmd!(
"library.list",
@@ -100,102 +86,6 @@ fn view2d(s: &mut Session, p: &J) -> Result<J> {
Ok(serde_json::to_value(&s.view2d).unwrap_or(J::Null))
}
/// Overlay `patch` on `base`: objects merge key by key, arrays element by element (a shorter
/// patch leaves the rest), a `null` leaves the value alone, anything else replaces.
fn merge_json(base: &mut J, patch: &J) {
match (base, patch) {
(_, J::Null) => {}
(J::Object(b), J::Object(p)) => {
for (k, v) in p {
match b.get_mut(k) {
Some(slot) => merge_json(slot, v),
None => {
b.insert(k.clone(), v.clone());
}
}
}
}
(J::Array(b), J::Array(p)) => {
for (i, v) in p.iter().enumerate() {
match b.get_mut(i) {
Some(slot) => merge_json(slot, v),
None => b.push(v.clone()),
}
}
}
(b, p) => *b = p.clone(),
}
}
/// Merge a nested object of the `view.3d` request into one of the view's sub-structs.
fn merge_into<T: serde::Serialize + serde::de::DeserializeOwned>(key: &str, current: &T, patch: &J) -> Result<T> {
if !patch.is_object() {
return Err(bad("view.3d", format!("`{key}` is an object")));
}
let mut v = serde_json::to_value(current).map_err(|e| bad("view.3d", e.to_string()))?;
merge_json(&mut v, patch);
serde_json::from_value(v).map_err(|e| bad("view.3d", format!("`{key}`: {e}")))
}
fn reset3d(s: &mut Session, p: &J) -> Result<J> {
let d = crate::View3d::default();
let v = &mut s.view3d;
match strp(p, "what").unwrap_or("all") {
"all" => *v = d,
"scene" => {
v.scene = d.scene;
v.tiling = d.tiling;
v.height_scale = d.height_scale;
v.height_level = d.height_level;
}
"camera" => {
v.yaw = d.yaw;
v.pitch = d.pitch;
v.distance = d.distance;
v.target = d.target;
v.camera = d.camera;
}
"lights" => v.lights = d.lights,
"environment" => {
v.environment = d.environment;
v.env_rotation = d.env_rotation;
v.exposure = d.exposure;
v.env_enabled = d.env_enabled;
}
"material" => v.material = d.material,
"renderer" => v.renderer = d.renderer,
"display" => v.display = d.display,
other => return Err(bad("view.3d.reset", format!("unknown `what` `{other}`"))),
}
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
fn load_state(s: &mut Session, p: &J) -> Result<J> {
let state = p.get("state").ok_or_else(|| bad("view.3d.loadState", "`state` is required"))?;
let mut v: crate::View3d = merge_into("state", &crate::View3d::default(), state)?;
v.sanitize();
if !SCENES.iter().any(|(id, _)| *id == v.scene) && !(v.scene == "custom" && s.custom_mesh.is_some()) {
v.scene = crate::View3d::default().scene;
}
if !ENVIRONMENTS.iter().any(|(id, _)| *id == v.environment) {
v.environment = crate::View3d::default().environment;
}
if boolp(p, "keepScene").unwrap_or(false) {
v.scene = s.view3d.scene.clone();
}
v.target = s.camera.clamp_target(v.target);
v.yaw = if v.yaw.is_finite() { v.yaw.rem_euclid(360.0) } else { 0.0 };
v.pitch = if v.pitch.is_finite() { v.pitch.clamp(-89.0, 89.0) } else { 0.0 };
v.distance = if v.distance.is_finite() { v.distance.clamp(1.2, 20.0) } else { 3.2 };
v.tiling = if v.tiling.is_finite() { v.tiling.clamp(0.1, 64.0) } else { 1.0 };
v.exposure = if v.exposure.is_finite() { v.exposure.clamp(-10.0, 10.0) } else { 0.0 };
v.env_rotation = if v.env_rotation.is_finite() { v.env_rotation.rem_euclid(360.0) } else { 0.0 };
v.height_scale = if v.height_scale.is_finite() { v.height_scale.clamp(0.0, 0.5) } else { 0.0 };
v.height_level = if v.height_level.is_finite() { v.height_level.clamp(0.0, 1.0) } else { 0.0 };
s.view3d = v;
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
fn view3d(s: &mut Session, p: &J) -> Result<J> {
// Validated up front so a bad target changes nothing.
let target = match p.get("target") {
@@ -209,12 +99,6 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
}
}
};
// Nested objects are parsed first: a bad one changes nothing.
let camera = p.get("camera").map(|c| merge_into("camera", &s.view3d.camera, c)).transpose()?;
let lights = p.get("lights").map(|l| merge_into("lights", &s.view3d.lights, l)).transpose()?;
let renderer = p.get("renderer").map(|r| merge_into("renderer", &s.view3d.renderer, r)).transpose()?;
let display = p.get("display").map(|d| merge_into("display", &s.view3d.display, d)).transpose()?;
let material = p.get("material").map(|m| merge_into("material", &s.view3d.material, m)).transpose()?;
// A rejected environment must not leave a new scene applied.
let environment = strp(p, "environment");
if let Some(e) = environment
@@ -278,25 +162,6 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
if let Some(b) = boolp(p, "alphaView") {
v.alpha_view = b;
}
if let Some(b) = boolp(p, "envEnabled") {
v.env_enabled = b;
}
if let Some(c) = camera {
v.camera = c;
}
if let Some(l) = lights {
v.lights = l;
}
if let Some(r) = renderer {
v.renderer = r;
}
if let Some(d) = display {
v.display = d;
}
if let Some(m) = material {
v.material = m;
}
v.sanitize();
Ok(serde_json::to_value(&s.view3d).unwrap_or(J::Null))
}
+17
View File
@@ -78,6 +78,23 @@ fn colliding_export_preserves_existing_files_and_writes_no_partial_outputs() {
);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn export_rejects_existing_file_in_destination_before_writing() {
let (mut s, _) = session();
let dir = TempDir::new("existing");
let sentinel = b"existing file must survive a rejected export";
std::fs::write(dir.0.join("first.png"), sentinel).unwrap();
let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"}));
let existing = std::fs::read(dir.0.join("first.png")).unwrap();
let files = std::fs::read_dir(&dir.0).unwrap().count();
assert!(
result.is_err() && existing == sentinel && files == 1,
"export overwrote an existing destination file: response={result:?}, files={files}, sentinel preserved={}",
existing == sentinel
);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn unique_export_writes_both_maps_with_their_expected_pixels() {
+28
View File
@@ -0,0 +1,28 @@
use materialcraft_engine::{core::NodeId, execute, new_session};
use serde_json::json;
#[test]
fn exposing_the_same_parameter_on_two_nodes_gives_each_its_own_input() {
let mut s = new_session();
let nodes: Vec<NodeId> = (0..3).map(|_| NodeId(execute(&mut s, "graph.node.add", &json!({"def": "blend"})).unwrap()["id"].as_u64().unwrap())).collect();
// The properties panel's "Expose as graph input" sends no `id`
let ids: Vec<String> = nodes
.iter()
.map(|node| {
let reply = execute(&mut s, "graph.exposed.add", &json!({"label": "Opacity", "bind": {"node": node.0, "param": "opacity"}})).unwrap();
reply["id"].as_str().unwrap().to_string()
})
.collect();
assert_eq!(ids, ["opacity", "opacity_1", "opacity_2"]);
let graph = s.graph().unwrap();
assert_eq!(graph.exposed.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ids);
for (node, id) in nodes.iter().zip(&ids) {
assert_eq!(graph.node(*node).unwrap().bindings.get("opacity"), Some(id));
}
// An explicit id still has to be free, and an unbound input still needs one
assert!(execute(&mut s, "graph.exposed.add", &json!({"id": "opacity_1", "bind": {"node": nodes[0].0, "param": "opacity"}})).is_err());
assert!(execute(&mut s, "graph.exposed.add", &json!({"default": 0.5})).is_err());
}
@@ -0,0 +1,48 @@
use materialcraft_engine::{execute, new_session};
use serde_json::json;
#[test]
fn rectangular_templates_are_created_and_undone_as_one_edit() {
for template in ["empty", "pbr", "atomics"] {
let mut session = new_session();
let original = session.pkg.clone();
let original_graph = session.graph;
execute(&mut session, "file.new", &json!({"template": template, "name": "Wide", "width": 512, "height": 128})).unwrap();
assert_eq!(session.graph().unwrap().size_px(), [512, 128]);
assert_eq!(session.graph().unwrap().name, "Wide");
assert_eq!(session.pkg.graphs.len(), original.graphs.len() + 1);
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(session.pkg, original);
assert_eq!(session.graph, original_graph);
assert!(!session.modified);
execute(&mut session, "edit.redo", &json!({})).unwrap();
assert_eq!(session.graph().unwrap().size_px(), [512, 128]);
}
}
#[test]
fn dimension_overrides_keep_square_defaults_and_bound_each_axis() {
for (parameters, expected) in [
(json!({"size": 256}), [256, 256]),
(json!({"size": 256, "height": 64}), [256, 64]),
(json!({"size": 256, "width": 64}), [64, 256]),
(json!({"width": 1000, "height": 127}), [512, 64]),
(json!({"width": 0, "height": u64::MAX}), [16, 8192]),
] {
let mut session = new_session();
execute(&mut session, "file.new", &parameters).unwrap();
assert_eq!(session.graph().unwrap().size_px(), expected, "{parameters}");
}
}
#[test]
fn invalid_dimensions_do_not_create_a_partial_graph_or_undo_entry() {
for parameters in [json!({"width": -1}), json!({"height": "128"}), json!({"width": 32.5}), json!({"height": null})] {
let mut session = new_session();
let original = session.pkg.clone();
assert!(execute(&mut session, "file.new", &parameters).is_err(), "{parameters}");
assert_eq!(session.pkg, original);
assert!(!session.modified);
assert!(execute(&mut session, "edit.undo", &json!({})).is_err());
}
}
+11 -43
View File
@@ -1,4 +1,4 @@
use materialcraft_engine::{Session, command_specs, execute, new_session, sample_session};
use materialcraft_engine::{Session, command_specs, execute, sample_session};
use serde_json::{Value, json};
fn run(s: &mut Session, id: &str, p: Value) -> Value {
@@ -235,15 +235,7 @@ fn panic_hunt() {
// Skip file writes to the working directory and opening paths
if matches!(
spec.id,
"file.save"
| "file.saveAs"
| "file.saveCopy"
| "file.exportWithDependencies"
| "file.export"
| "file.open"
| "file.importBitmap"
| "file.exportMaterial"
| "file.sendToTextureCraft"
"file.save" | "file.saveAs" | "file.export" | "file.open" | "file.importBitmap" | "file.exportMaterial" | "file.sendToTextureCraft"
) {
continue;
}
@@ -477,37 +469,13 @@ fn selected_wires_swap_their_sources_and_delete_together() {
}
#[test]
fn graphs_import_from_another_package_with_their_dependencies() {
use materialcraft_engine::core::{Package, Resource, ResourceBytes, Value};
let mut from = Package::new("Other");
from.graphs.push(materialcraft_engine::samples::template("empty", "Leaf", 8).unwrap());
from.graphs.push(materialcraft_engine::samples::template("empty", "Root", 8).unwrap());
from.resources.push(Resource::new("tex", "tex.png", ResourceBytes::new(vec![1, 2, 3])));
{
let root = &mut from.graphs[1];
let inst = root.add_node("graph_instance", [0.0, 0.0]);
root.node_mut(inst).unwrap().params.insert("graph".into(), Value::Text("Leaf".into()));
let bm = root.add_node("bitmap", [0.0, 100.0]);
root.node_mut(bm).unwrap().params.insert("resource".into(), Value::Text("tex".into()));
}
let mut s = new_session();
let name = materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Root").unwrap();
assert_eq!(name, "Root");
assert!(s.pkg.graph_by_name("Leaf").is_some(), "the instanced graph comes along");
assert!(s.pkg.resource("tex").is_some(), "the bitmap comes along");
// Importing again reuses identical graphs instead of duplicating them.
let again = materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Root").unwrap();
assert_eq!(again, "Root");
assert_eq!(s.pkg.graphs.iter().filter(|g| g.name.starts_with("Leaf")).count(), 1);
assert!(materialcraft_engine::resource_cmds::import_graph_from(&mut s, &from, "Nope").is_err());
// graph.add pastes a graph as JSON and refuses garbage.
let g = serde_json::to_value(&from.graphs[0]).unwrap();
let r = execute(&mut s, "graph.add", &json!({"graph": g})).unwrap();
assert_eq!(r["name"], "Leaf_1");
assert!(execute(&mut s, "graph.add", &json!({"graph": "nope"})).is_err());
assert!(execute(&mut s, "graph.add", &json!({})).is_err());
// Resources can be removed.
execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).unwrap();
assert!(s.pkg.resource("tex").is_none());
assert!(execute(&mut s, "file.deleteResource", &json!({"name": "tex"})).is_err());
fn undo_to_unmodified_state_clears_modified_flag() {
let mut s = sample_session();
assert!(!s.modified);
run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 0]}));
assert!(s.modified);
run(&mut s, "edit.undo", json!({}));
assert!(!s.modified, "undoing to the unmodified state should clear the modified flag");
run(&mut s, "edit.redo", json!({}));
assert!(s.modified, "redoing to the modified state should set the modified flag");
}
-63
View File
@@ -51,66 +51,3 @@ fn valid_view_updates_still_apply_and_return_the_complete_settings() {
assert_eq!(result["target"], json!([1.0, 2.0, 3.0]));
assert_eq!(result, serde_json::to_value(&s.view3d).unwrap());
}
#[test]
fn nested_3d_settings_merge_sanitize_and_reject_as_a_whole() {
let mut s = new_session();
// Only the keys given change; the rest of the sub-struct stays.
let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 50}, "lights": {"point": [{"on": true, "intensity": 3}]}})).unwrap();
assert_eq!(v["camera"]["focalLength"], 50.0);
assert_eq!(v["camera"]["projection"], "perspective");
assert_eq!(v["lights"]["point"][0]["on"], true);
assert_eq!(v["lights"]["point"][0]["intensity"], 3.0);
assert_eq!(v["lights"]["point"][1]["on"], false);
let before = s.view3d.clone();
// A malformed nested object rejects the whole request, scalars included.
assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "camera": "nope"})).is_err());
assert!(execute(&mut s, "view.3d", &json!({"yaw": 10, "material": {"shader": "unknown"}})).is_err());
assert_eq!(s.view3d, before);
// Hostile values are clamped, not kept.
let v = execute(&mut s, "view.3d", &json!({"camera": {"focalLength": 1e30, "near": -5, "far": 1e-9}, "material": {"common": {"ior": f64::NAN, "baseColor": [99.0, -1.0, 0.5]}, "tessellation": 1e9}})).unwrap();
assert_eq!(v["camera"]["focalLength"], 1200.0);
assert!(v["camera"]["far"].as_f64().unwrap() > v["camera"]["near"].as_f64().unwrap());
assert_eq!(v["material"]["common"]["ior"], 1.5);
assert_eq!(v["material"]["common"]["baseColor"], json!([64.0, 0.0, 0.5]));
assert_eq!(v["material"]["tessellation"], 4.0);
// Reset one part leaves the others.
execute(&mut s, "view.3d", &json!({"scene": "torus"})).unwrap();
execute(&mut s, "view.3d.reset", &json!({"what": "camera"})).unwrap();
assert_eq!(s.view3d.camera, materialcraft_engine::Camera3d::default());
assert_eq!(s.view3d.scene, "torus");
assert!(execute(&mut s, "view.3d.reset", &json!({"what": "nope"})).is_err());
}
#[test]
fn state_round_trips_and_garbage_state_falls_back_to_defaults() {
let mut s = new_session();
execute(&mut s, "view.3d", &json!({"scene": "cloth", "environment": "warehouse", "exposure": 1.5, "lights": {"ambient": [0.2, 0.2, 0.2]}})).unwrap();
let state = execute(&mut s, "view.3d.state", &json!({})).unwrap();
execute(&mut s, "view.3d.reset", &json!({})).unwrap();
assert_eq!(s.view3d.scene, "rounded_cube");
execute(&mut s, "view.3d.loadState", &json!({"state": state, "keepScene": true})).unwrap();
assert_eq!(s.view3d.scene, "rounded_cube", "keepScene leaves the mesh");
assert_eq!(s.view3d.environment, "warehouse");
assert_eq!(s.view3d.exposure, 1.5);
execute(&mut s, "view.3d.loadState", &json!({"state": {"scene": "nope", "environment": "nope", "yaw": f64::INFINITY, "distance": 1e9}})).unwrap();
assert_eq!(s.view3d.scene, "rounded_cube");
assert_eq!(s.view3d.environment, "studio");
assert_eq!(s.view3d.distance, 20.0);
assert!(execute(&mut s, "view.3d.loadState", &json!({"state": 5})).is_err());
assert!(execute(&mut s, "view.3d.loadState", &json!({})).is_err());
}
#[test]
fn session_settings_bound_history_cache_and_cook_size() {
let mut s = new_session();
let v = execute(&mut s, "session.settings", &json!({"historySize": 3, "cacheMb": 1, "cookLimit": 100})).unwrap();
assert_eq!(v["historySize"], 3);
assert_eq!(v["cacheMb"], 16, "the cache keeps at least 16 MB");
assert_eq!(v["cookLimit"], 256);
for _ in 0..6 {
execute(&mut s, "graph.node.add", &json!({"def": "uniform"})).unwrap();
}
assert_eq!(s.history().len(), 3, "only 3 steps are kept");
assert_eq!(execute(&mut s, "session.settings", &json!({"cookLimit": 0})).unwrap()["cookLimit"], 0);
}
+6 -21
View File
@@ -26,26 +26,6 @@ impl Cache {
self.bytes
}
/// The cache's size limit in bytes
pub fn cap(&self) -> usize {
self.cap
}
/// Change the size limit (at least 16 MB), evicting the least recently used entries past it
pub fn set_cap(&mut self, cap_bytes: usize) {
self.cap = cap_bytes.max(16 << 20);
self.evict();
}
fn evict(&mut self) {
while self.bytes > self.cap && self.entries.len() > 1 {
let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break };
if let Some(e) = self.entries.remove(&k) {
self.bytes = self.bytes.saturating_sub(e.1);
}
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
@@ -76,6 +56,11 @@ impl Cache {
self.bytes = self.bytes.saturating_sub(old.1);
}
self.bytes += size;
self.evict();
while self.bytes > self.cap && self.entries.len() > 1 {
let Some((&k, _)) = self.entries.iter().min_by_key(|(_, e)| e.2) else { break };
if let Some(e) = self.entries.remove(&k) {
self.bytes = self.bytes.saturating_sub(e.1);
}
}
}
}
+5
View File
@@ -52,6 +52,11 @@ pub(crate) fn graph_tree_hash(pkg: &Package, gi: usize) -> u64 {
index.hash(&mut h);
serde_json::to_string(graph).unwrap_or_default().hash(&mut h);
for (id, res) in &graph.input_images {
pkg.resource(res).map(|r| r.bytes.content_hash()).hash(&mut h);
id.hash(&mut h);
graph.input_images_linear.contains(id).hash(&mut h);
}
for n in &graph.nodes {
if let Some(Value::Text(name)) = n.params.get("resource") {
pkg.resource(name).map(|r| r.bytes.content_hash()).hash(&mut h);
+2 -2
View File
@@ -12,9 +12,9 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
let mut cooked = Cooked::default();
let Some(graph) = package.graphs.get(graph_index) else { return cooked };
// The top-level graph's input nodes show their preview images; the caller's images win
// Input nodes show their bound preview images; the caller's images win
let bound;
let options = if options.depth == 0 && !graph.input_images.is_empty() {
let options = if !graph.input_images.is_empty() {
let mut inputs: BTreeMap<String, Image> = graph
.input_images
.iter()
+65
View File
@@ -364,3 +364,68 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() {
p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1));
assert_eq!(first(&p), (0.5, 0.5));
}
#[test]
fn bound_input_image_resource_change_recooks_instance() {
use materialcraft_core::{Resource, ResourceBytes};
use std::sync::atomic::AtomicU8;
let mut sub = Graph::new("sub");
sub.size = [4, 4];
let i = sub.add_node("input_grayscale", [0.0, 0.0]);
sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into()));
let o = sub.add_node("output", [100.0, 0.0]);
sub.connect(i, "output", o, "input").unwrap();
sub.input_images.insert("in".into(), "curv".into());
let (top, inst) = instancing("top", "sub");
let mut p = Package::new("p");
p.graphs = vec![top, sub];
p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100])));
// Stands in for decoding: the first byte picks the shade.
let shade = AtomicU8::new(1);
let res = |_: &str| Some(Image::filled(4, 4, Kind::Gray, [f32::from(shade.load(Ordering::Relaxed)) / 10.0; 4]));
let cache = Mutex::new(Cache::default());
let opts = Options::new(&res);
let first = cook(&p, 0, &opts, &cache);
assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error);
assert!(!first.nodes[&inst].cached);
let unchanged = cook(&p, 0, &opts, &cache);
assert!(unchanged.nodes[&inst].cached, "an unchanged instance should be served from the cache");
p.resources[0].bytes = ResourceBytes::new(vec![2; 100]);
shade.store(2, Ordering::Relaxed);
let second = cook(&p, 0, &opts, &cache);
assert!(!second.nodes[&inst].cached, "changing the bound input image resource must recook the instance");
}
#[test]
fn bound_input_image_linear_flag_change_recooks_instance() {
use materialcraft_core::{Resource, ResourceBytes};
let mut sub = Graph::new("sub");
sub.size = [4, 4];
let i = sub.add_node("input_grayscale", [0.0, 0.0]);
sub.node_mut(i).unwrap().params.insert("identifier".into(), Value::Text("in".into()));
let o = sub.add_node("output", [100.0, 0.0]);
sub.connect(i, "output", o, "input").unwrap();
sub.input_images.insert("in".into(), "curv".into());
let (top, inst) = instancing("top", "sub");
let mut p = Package::new("p");
p.graphs = vec![top, sub];
p.resources.push(Resource::new("curv", "curv.bin", ResourceBytes::new(vec![1; 100])));
let res = |k: &str| {
let (name, linear) = materialcraft_image::split_resource_key(k);
(name == "curv").then(|| Image::filled(4, 4, Kind::Gray, [if linear { 0.5 } else { 0.2 }; 4]))
};
let cache = Mutex::new(Cache::default());
let opts = Options::new(&res);
let first = cook(&p, 0, &opts, &cache);
assert!(first.nodes[&inst].error.is_none(), "{:?}", first.nodes[&inst].error);
assert!(!first.nodes[&inst].cached);
let first_value = first.image(inst, 0).unwrap().data[0];
assert!((first_value - 0.2).abs() < 1e-4, "sRGB bound image should reach the instance, got {first_value}");
let second = cook(&p, 0, &opts, &cache);
assert!(second.nodes[&inst].cached, "an unchanged instance should be served from the cache");
p.graphs[1].input_images_linear.insert("in".into());
let third = cook(&p, 0, &opts, &cache);
assert!(!third.nodes[&inst].cached, "toggling input_images_linear must recook the instance");
let third_value = third.image(inst, 0).unwrap().data[0];
assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}");
}
+36 -1
View File
@@ -132,7 +132,15 @@ fn gltf(bytes: &[u8]) -> Result<Mesh> {
let pos: Vec<Vec3> = pos.map(|p| m.transform_point3(Vec3::from(p))).collect();
let n = pos.len();
match reader.read_normals() {
Some(ns) => normals.extend(ns.map(|q| m.transform_vector3(Vec3::from(q)).normalize_or_zero())),
Some(ns) => {
for q in ns {
let v = m.transform_vector3(Vec3::from(q));
if !v.is_finite() {
return Err(bad("the mesh has non-finite (NaN or infinite) normals"));
}
normals.push(v.normalize_or_zero());
}
}
None => all_normals = false,
}
match reader.read_tex_coords(0) {
@@ -241,6 +249,33 @@ mod tests {
assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err());
}
#[test]
fn gltf_non_finite_normals_are_rejected() {
use base64::Engine as _;
let gltf_with_normals = |normals: [[f32; 3]; 4]| {
let idx: [u16; 6] = [0, 1, 2, 0, 2, 3];
let mut buf: Vec<u8> = QUAD.iter().flatten().flat_map(|f| f.to_le_bytes()).collect();
buf.extend(normals.iter().flatten().flat_map(|f| f.to_le_bytes()));
buf.extend(idx.iter().flat_map(|i| i.to_le_bytes()));
let b64 = base64::engine::general_purpose::STANDARD.encode(&buf);
format!(
r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}],
"meshes":[{{"primitives":[{{"attributes":{{"POSITION":0,"NORMAL":1}},"indices":2}}]}}],
"accessors":[{{"bufferView":0,"componentType":5126,"count":4,"type":"VEC3","min":[-1e9,-1e9,-1e9],"max":[1e9,1e9,1e9]}},{{"bufferView":1,"componentType":5126,"count":4,"type":"VEC3"}},{{"bufferView":2,"componentType":5123,"count":6,"type":"SCALAR"}}],
"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":48}},{{"buffer":0,"byteOffset":48,"byteLength":48}},{{"buffer":0,"byteOffset":96,"byteLength":12}}],
"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#,
buf.len()
)
.into_bytes()
};
let mut nan_normals = [[0.0f32, 0.0, 1.0]; 4];
nan_normals[2][0] = f32::NAN;
assert!(load_mesh("x.gltf", &gltf_with_normals(nan_normals)).is_err());
let mut inf_normals = [[0.0f32, 0.0, 1.0]; 4];
inf_normals[1][2] = f32::INFINITY;
assert!(load_mesh("x.gltf", &gltf_with_normals(inf_normals)).is_err());
}
#[test]
fn a_bad_index_drops_its_whole_triangle_and_later_ones_keep_their_vertices() {
// Triangles: (0,1,2), (0,1,9) out of range, (0,2,3).
+1 -7
View File
@@ -67,7 +67,6 @@ impl<'text> SbsReader<'text, '_> {
let format = child_value(item, "format").unwrap_or("png").trim().to_ascii_lowercase();
let source = child_element(item, "source");
let mut bytes: Option<Vec<u8>> = None;
let mut link: Option<String> = None;
let mut why_missing = String::new();
if let Some(embedded) = source.and_then(|s| child_element(s, "binembedded")) {
@@ -87,7 +86,6 @@ impl<'text> SbsReader<'text, '_> {
match linked(file) {
Some(data) => {
bytes = Some(data);
link = Some(file.to_string());
break;
}
None => why_missing = format!("its file `{file}` was not found next to the package"),
@@ -104,11 +102,7 @@ impl<'text> SbsReader<'text, '_> {
self.resource_bytes += data.len();
let ext = if kind == "svg" { "svg".to_string() } else { format };
let file = crate::safe_file_name(&format!("{name}.{ext}"));
pkg.resources.push(match link {
Some(l) => Resource::linked(name.clone(), file, ResourceBytes::new(data), l),
None => Resource::new(name.clone(), file, ResourceBytes::new(data)),
});
pkg.resources.push(Resource::new(name.clone(), crate::safe_file_name(&format!("{name}.{ext}")), ResourceBytes::new(data)));
}
None => {
let why = if why_missing.is_empty() { "it has no data".to_string() } else { why_missing };
+10 -28
View File
@@ -25,34 +25,16 @@ pub fn write_sbs(pkg: &Package) -> Result<Vec<u8>> {
for resource in &pkg.resources {
let svg = resource.file.to_ascii_lowercase().ends_with(".svg");
let ext = resource.file.rsplit_once('.').map_or("png", |(_, e)| e);
// A resource linked to a file next to the package stays a link; one linked from
// elsewhere (or opened without a folder) is embedded, so the file is whole
let relative = resource.link.as_deref().filter(|l| !l.contains(':') && !l.starts_with('/') && !l.starts_with('\\'));
match relative {
Some(path) => {
let _ = write!(
content,
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"{}\"/></resource>",
xml_escape(&resource.name),
writer.next_uid(),
if svg { "svg" } else { "bitmap" },
xml_escape(ext),
xml_escape(path)
);
}
None => {
let _ = write!(
content,
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
xml_escape(&resource.name),
writer.next_uid(),
if svg { "svg" } else { "bitmap" },
xml_escape(ext),
resource.bytes.len(),
encode_embedded(resource.bytes.as_slice())?
);
}
}
let _ = write!(
content,
"<resource><identifier v=\"{}\"/><uid v=\"{}\"/><type v=\"{}\"/><format v=\"{}\"/><filepath v=\"\"/><source><binembedded><datalength v=\"{}\"/><strdata v=\"{}\"/></binembedded></source></resource>",
xml_escape(&resource.name),
writer.next_uid(),
if svg { "svg" } else { "bitmap" },
xml_escape(ext),
resource.bytes.len(),
encode_embedded(resource.bytes.as_slice())?
);
}
content.push_str("</content></group>");
}
-1
View File
@@ -10,7 +10,6 @@ pub mod bvh;
pub mod camera;
pub mod gbuffer;
pub mod mesh;
pub mod preview;
pub mod primitives;
pub mod unwrap;
-233
View File
@@ -1,233 +0,0 @@
//! The 3D preview's plain-data description shared by the engine (where it is session state)
//! and the renderer: what shows behind the mesh, the lights, the shading model and the
//! material's common values.
use serde::{Deserialize, Serialize};
/// What shows where a camera ray misses the mesh.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Background {
/// The studio vignette.
Backdrop,
/// A flat color (linear RGB).
Color([f32; 3]),
/// The (blurred) environment map.
Environment,
}
/// A point light in the scene (position in scene radii from the center).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PointLight {
pub on: bool,
/// Linear RGB.
pub color: [f32; 3],
pub intensity: f32,
pub position: [f32; 3],
}
impl PointLight {
/// The two default lights: key from the upper left, fill from the right and behind.
pub const DEFAULTS: [PointLight; 2] = [
PointLight { on: false, color: [1.0; 3], intensity: 1.0, position: [-2.5, 3.0, 2.5] },
PointLight { on: false, color: [0.2; 3], intensity: 1.0, position: [3.0, 1.0, -2.0] },
];
/// Every value brought into its range; non-finite values become the default.
pub fn sanitized(mut self, default: PointLight) -> PointLight {
for (v, d) in self.color.iter_mut().zip(default.color) {
*v = if v.is_finite() { v.clamp(0.0, 64.0) } else { d };
}
self.intensity = if self.intensity.is_finite() { self.intensity.clamp(0.0, 100.0) } else { default.intensity };
for (v, d) in self.position.iter_mut().zip(default.position) {
*v = if v.is_finite() { v.clamp(-50.0, 50.0) } else { d };
}
self
}
}
impl Default for PointLight {
fn default() -> Self {
PointLight::DEFAULTS[0]
}
}
/// The shading model.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Shader {
/// Metallic/roughness with coat, fuzz, emission, thin film, transmission and subsurface terms.
OpenPbr,
/// Plain metallic/roughness.
MetallicRoughness,
/// Metallic/roughness with the coat layer.
Coated,
/// Metallic/roughness with the subsurface term.
Subsurface,
/// Specular color / glossiness maps instead of metallic / roughness.
SpecularGlossiness,
/// Lambert diffuse plus a Blinn-Phong highlight from the lights.
Blinn,
/// Diffuse only.
Lambert,
/// The base color as is.
Unlit,
/// Normals as colors (surface inspection).
MeshInfo,
}
impl Shader {
pub const ALL: [(Shader, &'static str); 9] = [
(Shader::OpenPbr, "openPbr"),
(Shader::MetallicRoughness, "metallicRoughness"),
(Shader::Coated, "coated"),
(Shader::Subsurface, "subsurface"),
(Shader::SpecularGlossiness, "specularGlossiness"),
(Shader::Blinn, "blinn"),
(Shader::Lambert, "lambert"),
(Shader::Unlit, "unlit"),
(Shader::MeshInfo, "meshInfo"),
];
pub fn id(self) -> &'static str {
Self::ALL.iter().find(|(s, _)| *s == self).map_or("openPbr", |(_, id)| id)
}
pub fn by_id(id: &str) -> Option<Shader> {
Self::ALL.iter().find(|(_, i)| *i == id).map(|(s, _)| *s)
}
}
/// Which maps drive the material (off = the common value is used even when the map exists).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct MapUse {
pub base_color: bool,
pub roughness: bool,
pub metallic: bool,
pub normal: bool,
pub height: bool,
pub ao: bool,
pub emissive: bool,
pub opacity: bool,
pub specular: bool,
}
impl Default for MapUse {
fn default() -> Self {
MapUse { base_color: true, roughness: true, metallic: true, normal: true, height: true, ao: true, emissive: true, opacity: true, specular: true }
}
}
/// The material's common values: what each channel is where no map drives it, and the layer
/// terms that have no map at all. Colors are linear RGB; weights 0..1.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct Common {
pub base_weight: f32,
pub base_color: [f32; 3],
pub metalness: f32,
pub diffuse_roughness: f32,
pub specular_weight: f32,
pub specular_color: [f32; 3],
pub specular_roughness: f32,
pub ior: f32,
pub transmission_weight: f32,
pub transmission_color: [f32; 3],
pub subsurface_weight: f32,
pub subsurface_color: [f32; 3],
pub coat_weight: f32,
pub coat_color: [f32; 3],
pub coat_roughness: f32,
pub coat_ior: f32,
pub coat_darkening: f32,
pub fuzz_weight: f32,
pub fuzz_color: [f32; 3],
pub emission_luminance: f32,
pub emission_color: [f32; 3],
pub thin_film_weight: f32,
/// Nanometres.
pub thin_film_thickness: f32,
pub thin_film_ior: f32,
pub opacity: f32,
pub thin_walled: bool,
pub ambient_occlusion: f32,
pub height: f32,
}
impl Default for Common {
fn default() -> Self {
Common {
base_weight: 1.0,
base_color: [0.5; 3],
metalness: 0.0,
diffuse_roughness: 0.0,
specular_weight: 1.0,
specular_color: [1.0; 3],
specular_roughness: 0.5,
ior: 1.5,
transmission_weight: 0.0,
transmission_color: [1.0; 3],
subsurface_weight: 0.0,
subsurface_color: [0.8; 3],
coat_weight: 0.0,
coat_color: [1.0; 3],
coat_roughness: 0.0,
coat_ior: 1.6,
coat_darkening: 1.0,
fuzz_weight: 0.0,
fuzz_color: [1.0; 3],
emission_luminance: 0.0,
emission_color: [1.0; 3],
thin_film_weight: 0.0,
thin_film_thickness: 500.0,
thin_film_ior: 1.4,
opacity: 1.0,
thin_walled: false,
ambient_occlusion: 1.0,
height: 0.5,
}
}
}
impl Common {
/// Every value brought into its range; non-finite values become the default.
pub fn sanitized(mut self) -> Common {
let d = Common::default();
let unit = |v: &mut f32, dv: f32| *v = if v.is_finite() { v.clamp(0.0, 1.0) } else { dv };
let col = |c: &mut [f32; 3], dc: [f32; 3]| {
for (v, dv) in c.iter_mut().zip(dc) {
*v = if v.is_finite() { v.clamp(0.0, 64.0) } else { dv };
}
};
unit(&mut self.base_weight, d.base_weight);
col(&mut self.base_color, d.base_color);
unit(&mut self.metalness, d.metalness);
unit(&mut self.diffuse_roughness, d.diffuse_roughness);
unit(&mut self.specular_weight, d.specular_weight);
col(&mut self.specular_color, d.specular_color);
unit(&mut self.specular_roughness, d.specular_roughness);
self.ior = if self.ior.is_finite() { self.ior.clamp(1.0, 3.0) } else { d.ior };
unit(&mut self.transmission_weight, d.transmission_weight);
col(&mut self.transmission_color, d.transmission_color);
unit(&mut self.subsurface_weight, d.subsurface_weight);
col(&mut self.subsurface_color, d.subsurface_color);
unit(&mut self.coat_weight, d.coat_weight);
col(&mut self.coat_color, d.coat_color);
unit(&mut self.coat_roughness, d.coat_roughness);
self.coat_ior = if self.coat_ior.is_finite() { self.coat_ior.clamp(1.0, 3.0) } else { d.coat_ior };
unit(&mut self.coat_darkening, d.coat_darkening);
unit(&mut self.fuzz_weight, d.fuzz_weight);
col(&mut self.fuzz_color, d.fuzz_color);
self.emission_luminance = if self.emission_luminance.is_finite() { self.emission_luminance.clamp(0.0, 100.0) } else { d.emission_luminance };
col(&mut self.emission_color, d.emission_color);
unit(&mut self.thin_film_weight, d.thin_film_weight);
self.thin_film_thickness = if self.thin_film_thickness.is_finite() { self.thin_film_thickness.clamp(0.0, 2000.0) } else { d.thin_film_thickness };
self.thin_film_ior = if self.thin_film_ior.is_finite() { self.thin_film_ior.clamp(1.0, 3.0) } else { d.thin_film_ior };
unit(&mut self.opacity, d.opacity);
unit(&mut self.ambient_occlusion, d.ambient_occlusion);
unit(&mut self.height, d.height);
self
}
}
+1 -43
View File
@@ -216,42 +216,6 @@ pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh {
b.finish("Cylinder")
}
/// A cylinder along Y with rounded rims (`bevel` = rim radius).
pub fn rounded_cylinder(radius: f32, height: f32, bevel: f32, segs: usize) -> Mesh {
let mut b = Builder::default();
let h = height * 0.5;
let bev = bevel.clamp(0.0, radius.min(h) * 0.9);
let mut profile = Vec::new();
for k in 0..=6 {
let a = k as f32 / 6.0 * PI * 0.5;
profile.push((radius - bev + bev * a.sin(), h - bev + bev * a.cos()));
}
for k in 0..=6 {
let a = k as f32 / 6.0 * PI * 0.5;
profile.push((radius - bev + bev * a.cos(), -h + bev - bev * a.sin()));
}
lathe_into(&mut b, Vec3::ZERO, &profile, segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01));
disk_into(&mut b, Vec3::Y * h, radius - bev, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
disk_into(&mut b, -Vec3::Y * h, radius - bev, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01));
b.finish("Rounded cylinder")
}
/// A draped square of cloth: a plane with soft folds, facing +Y.
pub fn cloth(size: f32, subdivisions: usize) -> Mesh {
let mut b = Builder::default();
let s = subdivisions.max(8);
let fold = |x: f32, z: f32| 0.07 * (x * 4.2).sin() * (z * 2.6 + 0.5).cos() + 0.035 * (x * 9.0 + z * 7.0).sin() + 0.02 * (z * 12.0).cos();
b.grid(s, s, |i, j| {
let (u, v) = (j as f32 / s as f32, i as f32 / s as f32);
let (x, z) = ((u - 0.5) * size, (v - 0.5) * size);
let y = fold(x, z);
let e = 1e-3;
let (dx, dz) = ((fold(x + e, z) - fold(x - e, z)) / (2.0 * e), (fold(x, z + e) - fold(x, z - e)) / (2.0 * e));
(Vec3::new(x, y, z), Vec3::new(-dx, 1.0, -dz), Vec2::new(u, v))
});
b.finish("Cloth")
}
/// A torus around Y.
pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh {
let mut b = Builder::default();
@@ -366,11 +330,8 @@ pub fn builtin(id: &str) -> Option<Mesh> {
"cube" => cube(2.0),
"rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15),
"cylinder" => cylinder(1.0, 2.0, 96),
"rounded_cylinder" | "roundedcylinder" => rounded_cylinder(1.0, 2.0, 0.12, 96),
"torus" => torus(1.0, 0.35, 128, 48),
"plane" => plane(2.0, 16),
"plane_hires" | "planehires" => plane(2.0, 128),
"cloth" => cloth(2.0, 96),
"crate" => crate_scene(),
"udim_plane" | "udimplane" => udim_plane(),
_ => return None,
@@ -378,17 +339,14 @@ pub fn builtin(id: &str) -> Option<Mesh> {
}
/// Ids accepted by [`builtin`], in menu order.
pub const BUILTINS: [(&str, &str); 12] = [
pub const BUILTINS: [(&str, &str); 9] = [
("material_ball", "Material ball"),
("sphere", "Sphere"),
("cube", "Cube"),
("rounded_cube", "Rounded cube"),
("cylinder", "Cylinder"),
("rounded_cylinder", "Rounded cylinder"),
("torus", "Torus"),
("plane", "Plane"),
("plane_hires", "Plane (hi-res)"),
("cloth", "Cloth"),
("crate", "Crate"),
("udim_plane", "UDIM plane"),
];
+17 -10
View File
@@ -302,18 +302,12 @@ pub fn blend_channel(mode: i32, b: f32, f: f32) -> f32 {
}
12 => (b - f).abs(),
13 => {
if f >= 1.0 {
1.0
} else {
(b / (1.0 - f)).min(1.0)
}
// W3C color dodge: a black background stays black, even under a white foreground
if f >= 1.0 { if b > 0.0 { 1.0 } else { 0.0 } } else { (b / (1.0 - f)).min(1.0) }
}
14 => {
if f <= 0.0 {
0.0
} else {
1.0 - ((1.0 - b) / f).min(1.0)
}
// W3C color burn: a white background stays white, even under a black foreground
if f <= 0.0 { if b < 1.0 { 0.0 } else { 1.0 } } else { 1.0 - ((1.0 - b) / f).min(1.0) }
}
15 => {
if f < 0.5 {
@@ -352,6 +346,19 @@ pub fn gray_from(w: u32, h: u32, v: Vec<f32>) -> Image {
mod tests {
use super::*;
#[test]
fn color_dodge_and_burn_keep_black_and_white_backgrounds() {
const DODGE: i32 = 13;
const BURN: i32 = 14;
// (background, foreground, expected), W3C compositing formulas
for (b, f, expected) in [(0.0, 1.0, 0.0), (0.0, 0.5, 0.0), (0.5, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.75, 1.0)] {
assert_eq!(blend_channel(DODGE, b, f), expected, "dodge b={b} f={f}");
}
for (b, f, expected) in [(1.0, 0.0, 1.0), (1.0, 0.5, 1.0), (0.5, 0.0, 0.0), (0.75, 0.5, 0.5), (0.0, 0.25, 0.0)] {
assert_eq!(blend_channel(BURN, b, f), expected, "burn b={b} f={f}");
}
}
#[test]
fn blur_keeps_mean_and_tiles() {
let img = Image::gray(32, 32, |x, y| if (x / 4 + y / 4) % 2 == 0 { 1.0 } else { 0.0 });
+12 -9
View File
@@ -14,9 +14,12 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>)
for p in &def.params {
let Some(v) = params.get_mut(p.id) else { continue };
if let Value::Enum(i) = v {
if !p.options.is_empty() {
*i = (*i).min(u32::try_from(p.options.len() - 1).unwrap_or(u32::MAX));
}
// (an enum without options has nothing to choose from: its default stands)
*i = match (p.options.len().checked_sub(1), &p.default) {
(Some(last), _) => (*i).min(u32::try_from(last).unwrap_or(u32::MAX)),
(None, Value::Enum(d)) => *d,
(None, _) => 0,
};
continue;
}
if let Value::Color(c) = v {
@@ -25,11 +28,11 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>)
}
continue;
}
if p.min >= p.max {
continue;
}
// No range declared (an Input Value's default takes any number): only a value that isn't
// a number goes
let ranged = p.min < p.max;
let span = p.max - p.min;
let (lo, hi) = (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span);
let (lo, hi) = if ranged { (p.min - HARD_SPAN * span, p.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) };
// The default's component `i`, or 0 when the default is a different variant
let fallback = |i: usize| match &p.default {
Value::Float(d) => [*d].get(i).copied(),
@@ -46,8 +49,8 @@ pub fn clamp_params(def: &NodeDefinition, params: &mut BTreeMap<String, Value>)
Value::Float2(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float3(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Float4(a) => a.iter_mut().enumerate().for_each(|(i, x)| clamp_at(x, i)),
Value::Int(x) => clamp_int(x),
Value::Int2(a) => a.iter_mut().for_each(clamp_int),
Value::Int(x) if ranged => clamp_int(x),
Value::Int2(a) if ranged => a.iter_mut().for_each(clamp_int),
_ => {}
}
}
+26
View File
@@ -33,6 +33,32 @@ fn clamp_params_covers_values_set_after_resolution() {
assert_eq!(p["opacity"], Value::Float(17.0));
}
#[test]
fn clamp_params_bounds_an_enum_without_options() {
let mut def = find("blend").unwrap().clone();
let enums = def.params.iter_mut().find(|p| matches!(p.default, Value::Enum(_))).expect("an enum parameter");
enums.options = &[];
enums.default = Value::Enum(1);
let id = enums.id;
let mut p = BTreeMap::from([(id.to_string(), Value::Enum(999))]);
clamp_params(&def, &mut p);
assert_eq!(p[id], Value::Enum(1));
}
/// A parameter with no declared range keeps any number, and only a value that isn't a number goes.
#[test]
fn clamp_params_keeps_numbers_without_a_declared_range() {
let def = find("input_value").unwrap();
let default = def.params.iter().find(|p| p.id == "default").unwrap();
assert!(default.min >= default.max, "input_value's default declares no range");
let mut p = over("default", Value::Float(3.5));
clamp_params(def, &mut p);
assert_eq!(p["default"], Value::Float(3.5));
let mut p = over("default", Value::Float(f32::NAN));
clamp_params(def, &mut p);
assert_eq!(p["default"], default.default);
}
#[test]
fn defaults_lie_inside_their_hard_limits() {
for def in catalog() {
+1 -3
View File
@@ -14,6 +14,4 @@ mod relief;
pub use displacement::Displacement;
pub use relief::Relief;
pub use preview::{
Background, Common, Lighting, MapUse, Maps, PointLight, Scene, Settings, Shader, VIEW_TRIANGLES, builtin_mesh, camera, pan, render, render_cancellable,
};
pub use preview::{Lighting, Maps, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable};
+49 -372
View File
@@ -13,8 +13,6 @@ use materialcraft_geom::{Bvh, Mesh, OrbitCamera};
use materialcraft_image::{Image, linear_to_srgb};
use rayon::prelude::*;
pub use materialcraft_geom::preview::{Background, Common, MapUse, PointLight, Shader};
use crate::ibl::{self, EnvImage};
/// The material's maps (any may be missing: defaults are mid gray, flat, rough 0.5, dielectric).
@@ -28,10 +26,6 @@ pub struct Maps {
pub ao: Option<Image>,
pub emissive: Option<Image>,
pub opacity: Option<Image>,
/// Specular color (the specular/glossiness workflow and OpenPBR's specular weight).
pub specular: Option<Image>,
/// Glossiness (the specular/glossiness workflow: 1 − roughness).
pub glossiness: Option<Image>,
}
impl Maps {
@@ -40,19 +34,6 @@ impl Maps {
let mut m = Maps::default();
for (usage, img) in items {
use materialcraft_core::MaterialChannel;
// The specular/glossiness workflow's maps are not preview channels of their own
if usage.eq_ignore_ascii_case("specular") {
if m.specular.is_none() {
m.specular = Some(img.clone());
}
continue;
}
if usage.eq_ignore_ascii_case("glossiness") {
if m.glossiness.is_none() {
m.glossiness = Some(img.clone());
}
continue;
}
let Some(channel) = MaterialChannel::from_id(usage) else { continue };
let slot = match channel {
@@ -173,9 +154,8 @@ pub const VIEW_TRIANGLES: usize = 500_000;
/// A built-in mesh by id; unknown ids give the rounded cube.
pub fn builtin_mesh(id: &str) -> Mesh {
let base = if id == "sphere_2_tiles" { "sphere" } else { id };
let mut m = materialcraft_geom::primitives::builtin(base).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15));
if id == "sphere_2_tiles" {
let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15));
if id == "sphere" {
// The texture wraps twice around, so texels are square at the equator.
m.uvs.iter_mut().for_each(|uv| uv.x *= 2.0);
}
@@ -218,7 +198,7 @@ impl Lighting {
}
/// Camera and look.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug)]
pub struct Settings {
/// Degrees.
pub yaw: f32,
@@ -248,27 +228,6 @@ pub struct Settings {
pub transparency: bool,
/// Show the material's alpha channel on the mesh, unlit (white = opaque, black = clear).
pub alpha_view: bool,
/// Vertical field of view, degrees (perspective).
pub fov: f32,
/// Orthographic projection.
pub ortho: bool,
/// What a miss shows (`show_env` = true overrides it with the environment).
pub background: Background,
/// Fixed near and far clip distances in scene radii from the camera (`None` = automatic).
pub clip: Option<[f32; 2]>,
/// Ambient light added to every surface (linear RGB; black = off).
pub ambient: [f32; 3],
/// Point lights.
pub lights: [PointLight; 2],
/// Environment lighting on (off leaves the ambient and point lights).
pub env_light: bool,
pub shader: Shader,
pub common: Common,
pub use_map: MapUse,
/// Draw the triangle edges over the surface.
pub wireframe: bool,
/// Skip faces turned away from the camera.
pub backface_culling: bool,
}
impl Default for Settings {
@@ -288,18 +247,6 @@ impl Default for Settings {
key_light: 0.0,
transparency: true,
alpha_view: false,
fov: 35.0,
ortho: false,
background: Background::Backdrop,
clip: None,
ambient: [0.0; 3],
lights: PointLight::DEFAULTS,
env_light: true,
shader: Shader::OpenPbr,
common: Common::default(),
use_map: MapUse::default(),
wireframe: false,
backface_culling: false,
}
}
}
@@ -312,9 +259,9 @@ pub fn camera(scene: &Scene, s: &Settings) -> OrbitCamera {
yaw: s.yaw.to_radians(),
pitch: s.pitch.clamp(-89.0, 89.0).to_radians(),
distance: s.distance.clamp(1.05, 50.0) * scene.radius,
fov: if s.fov.is_finite() { s.fov.clamp(5.0, 120.0) } else { 35.0 },
fov: 35.0,
scene_radius: scene.radius,
ortho: s.ortho,
ortho: false,
}
}
@@ -327,6 +274,16 @@ pub fn pan(scene: &Scene, s: &Settings, dx: f32, dy: f32) -> [f32; 3] {
t.to_array().map(|v| if v.is_finite() { v } else { 0.0 })
}
#[inline]
fn tex(img: &Option<Image>, uv: Vec2) -> Option<[f32; 4]> {
img.as_ref().map(|i| i.sample(uv.x, uv.y, true))
}
#[inline]
fn tex_gray(img: &Option<Image>, uv: Vec2, default: f32) -> f32 {
img.as_ref().map_or(default, |i| i.sample_gray(uv.x, uv.y, true))
}
/// Narkowicz's fit of the ACES filmic curve.
#[inline]
fn aces(x: f32) -> f32 {
@@ -350,11 +307,11 @@ fn rotate_y(v: Vec3, deg: f32) -> Vec3 {
/// The material's alpha at `uv`: the opacity output, else the base color's alpha channel, else
/// opaque.
fn alpha(maps: &Maps, s: &Settings, uv: Vec2) -> f32 {
fn alpha(maps: &Maps, uv: Vec2) -> f32 {
let a = match (&maps.opacity, &maps.base_color) {
(Some(o), _) if s.use_map.opacity => o.sample_gray(uv.x, uv.y, true),
(_, Some(b)) if s.use_map.base_color && !b.is_gray() => b.sample(uv.x, uv.y, true)[3] * s.common.opacity,
_ => s.common.opacity,
(Some(o), _) => o.sample_gray(uv.x, uv.y, true),
(None, Some(b)) if !b.is_gray() => b.sample(uv.x, uv.y, true)[3],
_ => 1.0,
};
if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }
}
@@ -413,101 +370,9 @@ struct Shaded {
t: f32,
}
/// Schlick Fresnel for a dielectric of `ior` at `cos`.
#[inline]
fn fresnel(ior: f32, cos: f32) -> f32 {
let f0 = ((ior - 1.0) / (ior + 1.0)).powi(2);
f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5)
}
/// Thin-film interference tint: the reflectance of a film `nm` thick with index `ior` for the
/// three wavelengths 650/550/450 nm at `cos` (a cosine-series approximation).
#[inline]
fn thin_film(nm: f32, ior: f32, cos: f32) -> Vec3 {
let sin2 = (1.0 - cos * cos).clamp(0.0, 1.0) / (ior * ior);
let cos_t = (1.0 - sin2).max(0.0).sqrt();
let path = 2.0 * ior * nm * cos_t;
let r = |lambda: f32| 0.5 + 0.5 * (std::f32::consts::TAU * path / lambda).cos();
Vec3::new(r(650.0), r(550.0), r(450.0))
}
/// Blinn-Phong highlight exponent from roughness.
#[inline]
fn blinn_exponent(rough: f32) -> f32 {
2.0 / (rough * rough).max(1e-3) - 2.0
}
/// What the maps (or the common values) say about the surface at `uv`.
struct Surface {
base: Vec3,
rough: f32,
metal: f32,
ao: f32,
/// Dielectric reflectance at normal incidence (the specular workflow's specular color).
spec_f0: Vec3,
}
fn surface(maps: &Maps, s: &Settings, uv: Vec2) -> Surface {
let c = &s.common;
let common_base = Vec3::from(c.base_color) * c.base_weight;
let base = match &maps.base_color {
Some(b) if s.use_map.base_color => {
let v = b.sample(uv.x, uv.y, true);
Vec3::new(v[0], v[1], v[2]) * c.base_weight
}
_ => common_base,
};
let (rough, spec_f0) = if s.shader == Shader::SpecularGlossiness {
let gloss = match &maps.glossiness {
Some(g) => g.sample_gray(uv.x, uv.y, true),
None => 1.0 - c.specular_roughness,
};
let spec = match &maps.specular {
Some(sp) if s.use_map.specular => {
let v = sp.sample(uv.x, uv.y, true);
Vec3::new(v[0], v[1], v[2])
}
_ => Vec3::from(c.specular_color) * 0.04,
};
((1.0 - gloss).clamp(0.02, 1.0), spec)
} else {
let rough = match &maps.roughness {
Some(r) if s.use_map.roughness => r.sample_gray(uv.x, uv.y, true),
_ => c.specular_roughness,
};
let f0 = ((c.ior - 1.0) / (c.ior + 1.0)).powi(2);
let spec_w = match &maps.specular {
Some(sp) if s.use_map.specular && s.shader == Shader::OpenPbr => sp.sample_gray(uv.x, uv.y, true),
_ => 1.0,
};
(rough.clamp(0.02, 1.0), Vec3::from(c.specular_color) * (f0 * c.specular_weight * spec_w))
};
let metal = match &maps.metallic {
Some(m) if s.use_map.metallic && s.shader != Shader::SpecularGlossiness => m.sample_gray(uv.x, uv.y, true),
_ if s.shader == Shader::SpecularGlossiness => 0.0,
_ => c.metalness,
};
let ao = match &maps.ao {
Some(a) if s.use_map.ao => a.sample_gray(uv.x, uv.y, true),
_ => c.ambient_occlusion,
};
Surface { base, rough, metal: metal.clamp(0.0, 1.0), ao: ao.clamp(0.0, 1.0), spec_f0 }
}
/// Shade the first surface along one ray; `None` = missed the mesh.
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, tmax: f32) -> Option<Shaded> {
let hit = if s.backface_culling {
let m = &scene.mesh;
scene.bvh.closest_filtered(origin, dir, tmax, &|t| {
let Some([i0, i1, i2]) = m.tri(t as usize) else { return true };
match (m.positions.get(i0), m.positions.get(i1), m.positions.get(i2)) {
(Some(a), Some(b), Some(c)) => (*b - *a).cross(*c - *a).dot(dir) < 0.0,
_ => true,
}
})?
} else {
scene.bvh.closest(origin, dir, tmax)?
};
fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px) -> Option<Shaded> {
let hit = scene.bvh.closest(origin, dir, f32::MAX)?;
let m = &scene.mesh;
let [i0, i1, i2] = m.tri(hit.tri as usize)?;
let (w1, w2) = (hit.u, hit.v);
@@ -524,17 +389,16 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2;
let uv = uv0 * s.tiling;
let v = -dir;
let t_total = hit.t;
let a = alpha(maps, s, uv);
// Wireframe: the edges of the triangle hit, in the barycentric sense.
let on_edge = s.wireframe && [w0, w1, w2].iter().any(|w| *w < 0.03);
let a = alpha(maps, uv);
if s.alpha_view {
return Some(Shaded { color: if on_edge { Vec3::new(1.0, 0.5, 0.0) } else { Vec3::splat(a) }, alpha: 1.0, t: t_total });
return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t });
}
let sf = surface(maps, s, uv);
let n = match &maps.normal {
Some(nm) if s.use_map.normal => {
let c = nm.sample(uv.x, uv.y, true);
let base = tex(&maps.base_color, uv).map_or(Vec3::splat(0.5), |c| Vec3::new(c[0], c[1], c[2]));
let rough = tex_gray(&maps.roughness, uv, 0.5).clamp(0.02, 1.0);
let metal = tex_gray(&maps.metallic, uv, 0.0).clamp(0.0, 1.0);
let ao = tex_gray(&maps.ao, uv, 1.0).clamp(0.0, 1.0);
let n = match tex(&maps.normal, uv) {
Some(c) => {
let mut t = Vec3::new(c[0] * 2.0 - 1.0, c[1] * 2.0 - 1.0, c[2] * 2.0 - 1.0);
if s.normal_y_flip {
t.y = -t.y;
@@ -543,119 +407,35 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
// with top-left UVs.
(tan * t.x - bit * t.y + nrm * t.z.max(0.05)).normalize_or_zero()
}
_ => nrm,
None => nrm,
};
let n = if n.dot(v) < 0.0 { nrm } else { n };
let ndv = n.dot(v).clamp(1e-4, 1.0);
let c = &s.common;
let wire = |mut color: Vec3| {
if on_edge {
color = Vec3::new(1.0, 0.5, 0.0);
}
color
};
match s.shader {
Shader::Unlit => return Some(Shaded { color: wire(sf.base), alpha: if s.transparency { a } else { 1.0 }, t: t_total }),
Shader::MeshInfo => return Some(Shaded { color: wire(n * 0.5 + Vec3::splat(0.5)), alpha: 1.0, t: t_total }),
_ => {}
}
let (base, rough, metal, ao) = (sf.base, sf.rough, sf.metal, sf.ao);
let f0 = sf.spec_f0.lerp(base, metal);
// Diffuse roughness darkens the grazing diffuse a little (a cheap Oren-Nayar stand-in).
let diffuse_col = base * (1.0 - metal) * (1.0 - 0.5 * c.diffuse_roughness * (1.0 - ndv));
let f0 = Vec3::splat(0.04).lerp(base, metal);
let diffuse_col = base * (1.0 - metal);
let rot = |d: Vec3| rotate_y(d, -s.env_rotation);
let r = (n * (2.0 * n.dot(v)) - v).normalize_or_zero();
let (sa, sb) = env_brdf(rough, ndv);
let env_diff = if s.env_light { light.diffuse(rot(n)) } else { Vec3::ZERO };
let env_spec = if s.env_light { light.specular(rot(r), rough) } else { Vec3::ZERO };
let ambient = Vec3::from(s.ambient);
let subsurface = matches!(s.shader, Shader::OpenPbr | Shader::Subsurface) && c.subsurface_weight > 0.0;
let mut diff = (env_diff + ambient) * diffuse_col;
if subsurface {
// Light that enters and leaves nearby: the surface glows with the subsurface color.
let sss = (env_diff + ambient) * Vec3::from(c.subsurface_color) * (1.0 - metal);
diff = diff.lerp(sss, c.subsurface_weight);
}
let mut color = match s.shader {
Shader::Lambert => diff,
Shader::Blinn => diff + ambient * f0,
_ => {
let mut spec_tint = f0 * sa + Vec3::splat(sb);
if s.shader == Shader::OpenPbr && c.thin_film_weight > 0.0 {
let film = thin_film(c.thin_film_thickness, c.thin_film_ior, ndv);
spec_tint = spec_tint.lerp(spec_tint * film * 2.0, c.thin_film_weight);
}
diff + env_spec * spec_tint
}
};
color *= ao;
// Direct lights (the key light and the point lights cast shadows).
let need_rays = s.ao_rays > 0 || s.key_light > 0.0 || s.lights.iter().any(|l| l.on);
if need_rays {
let spec = light.specular(rot(r), rough) * (f0 * sa + Vec3::splat(sb));
let diff = light.diffuse(rot(n)) * diffuse_col;
let mut c = (diff + spec) * ao;
if s.ao_rays > 0 || s.key_light > 0.0 {
// The true surface (a displaced scene's facets), offset to avoid self-hits.
let (p0, p1, p2) = (*m.positions.get(i0)?, *m.positions.get(i1)?, *m.positions.get(i2)?);
let face = (p1 - p0).cross(p2 - p0).normalize_or_zero();
let face = if face.dot(nrm) < 0.0 { -face } else { face };
let p = origin + dir * hit.t + face * scene.radius * 2e-4;
if s.ao_rays > 0 {
color *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter);
c *= ambient_occlusion(scene, p, face, s.ao_rays, px.jitter);
}
let mut lit = |l: Vec3, radiance: Vec3, reach: f32| {
if face.dot(l) > 0.0 && !scene.bvh.occluded(p, l, reach) {
let term = match s.shader {
Shader::Lambert => diffuse_col * n.dot(l).max(0.0) / std::f32::consts::PI,
Shader::Blinn => {
let h = (v + l).normalize_or_zero();
let spec = n.dot(h).max(0.0).powf(blinn_exponent(rough)) * (blinn_exponent(rough) + 8.0) / (8.0 * std::f32::consts::PI);
(diffuse_col / std::f32::consts::PI + f0 * spec) * n.dot(l).max(0.0)
}
_ => direct(n, v, l, base, f0, metal, rough),
};
color += term * radiance * ao;
}
};
if s.key_light > 0.0 {
lit(px.key, Vec3::splat(s.key_light), f32::MAX);
}
for pl in s.lights.iter().filter(|l| l.on) {
let lp = scene.center + Vec3::from(pl.position) * scene.radius;
let to = lp - p;
let dist = to.length().max(1e-4);
let l = to / dist;
// Inverse square falloff, normalised so a light at one radius has unit power.
let radiance = Vec3::from(pl.color) * pl.intensity * (scene.radius * scene.radius) / (dist * dist) * 4.0;
lit(l, radiance, dist);
if s.key_light > 0.0 && face.dot(px.key) > 0.0 && !scene.bvh.occluded(p, px.key, f32::MAX) {
c += direct(n, v, px.key, base, f0, metal, rough) * s.key_light * ao;
}
}
let coat = matches!(s.shader, Shader::OpenPbr | Shader::Coated) && c.coat_weight > 0.0;
if coat {
// A dielectric layer over everything: its reflection on top, the base dimmed and tinted below.
let cf = fresnel(c.coat_ior, ndv) * c.coat_weight;
let coat_rough = c.coat_roughness.clamp(0.02, 1.0);
let coat_spec = if s.env_light { light.specular(rot(r), coat_rough) } else { Vec3::ZERO } + ambient * 0.04;
let darkening = 1.0 - c.coat_darkening * c.coat_weight * 0.25;
color = color * (1.0 - cf) * Vec3::from(c.coat_color).lerp(Vec3::ONE, 1.0 - c.coat_weight) * darkening + coat_spec * cf;
if let Some(e) = tex(&maps.emissive, uv) {
c += Vec3::new(e[0], e[1], e[2]);
}
if s.shader == Shader::OpenPbr && c.fuzz_weight > 0.0 {
// Sheen: a soft rim of the fuzz color.
let rim = (1.0 - ndv).powi(3);
color += (env_diff + ambient) * Vec3::from(c.fuzz_color) * (c.fuzz_weight * (0.15 + 0.85 * rim));
}
let mut alpha_out = if s.transparency { a } else { 1.0 };
if s.shader == Shader::OpenPbr && c.transmission_weight > 0.0 {
// Transmission: what lies behind shows through, tinted.
color = color.lerp(color * Vec3::from(c.transmission_color), c.transmission_weight);
alpha_out *= 1.0 - c.transmission_weight * (1.0 - metal) * (1.0 - fresnel(c.ior, ndv));
}
if let Some(e) = &maps.emissive
&& s.use_map.emissive
{
let e = e.sample(uv.x, uv.y, true);
color += Vec3::new(e[0], e[1], e[2]) * c.emission_luminance.max(1.0);
} else if c.emission_luminance > 0.0 {
color += Vec3::from(c.emission_color) * c.emission_luminance;
}
Some(Shaded { color: wire(color), alpha: alpha_out, t: t_total })
Some(Shaded { color: c, alpha: if s.transparency { a } else { 1.0 }, t: hit.t })
}
/// Follow one camera ray through up to [`MAX_LAYERS`] transparent surfaces, compositing front to
@@ -664,12 +444,10 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec3, dir: Vec3, px: &Px, k: f32, miss: Vec3) -> Vec3 {
let mut acc = Vec3::ZERO;
let mut through = 1.0;
let (tmin, mut tmax) = clip_range(scene, s);
let mut o = origin + dir * tmin;
let mut o = origin;
let step = scene.radius * 1e-4;
for _ in 0..MAX_LAYERS {
let Some(h) = shade(scene, maps, light, s, o, dir, px, tmax) else { return acc + miss * through };
tmax = (tmax - h.t - step).max(0.0);
let Some(h) = shade(scene, maps, light, s, o, dir, px) else { return acc + miss * through };
acc += h.color * k * h.alpha * through;
through *= 1.0 - h.alpha;
if through < 1e-3 {
@@ -680,14 +458,6 @@ fn trace(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec
acc + miss * through
}
/// The near and far clip distances along a camera ray (scene radii → world units).
fn clip_range(scene: &Scene, s: &Settings) -> (f32, f32) {
match s.clip {
Some([n, f]) if n.is_finite() && f.is_finite() && f > n => (n.max(0.0) * scene.radius, (f - n.max(0.0)) * scene.radius),
_ => (0.0, f32::MAX),
}
}
/// The studio backdrop at screen position `p` (−1..1): a soft vignette (linear).
fn backdrop(p: Vec2) -> Vec3 {
let t = (p.length() * 0.75).clamp(0.0, 1.0);
@@ -735,16 +505,15 @@ pub fn render_cancellable(scene: &Scene, maps: &Maps, light: &Lighting, s: &Sett
let px = (x as f32 + (sx as f32 + 0.5) / ss as f32) / w as f32 * 2.0 - 1.0;
let py = 1.0 - (y as f32 + (sy as f32 + 0.5) / ss as f32) / h as f32 * 2.0;
let ray = cam.ray(Vec2::new(px, py), aspect);
let bg = backdrop(Vec2::new(px, py));
let p = Px { key, jitter: jitter(x as u32 * ss + sx, y as u32 * ss + sy) };
let miss = match (s.show_env || s.background == Background::Environment, bg_env, s.background) {
(true, Some(e), _) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
(_, _, Background::Color(c)) => Vec3::from(c),
_ => backdrop(Vec2::new(px, py)),
let miss = match (s.show_env, bg_env) {
(true, Some(e)) => e.sample(rotate_y(ray.dir, -s.env_rotation)) * k,
_ => bg,
};
acc += if s.alpha_view {
// Display values: the alpha as is, the background tone mapped.
let (tmin, tmax) = clip_range(scene, s);
match shade(scene, maps, light, s, ray.origin + ray.dir * tmin, ray.dir, &p, tmax) {
match shade(scene, maps, light, s, ray.origin, ray.dir, &p) {
Some(h) => h.color,
None => miss.map(|v| linear_to_srgb(aces(v))),
}
@@ -817,98 +586,6 @@ mod tests {
Image::filled(8, 8, Kind::Gray, [value; 4])
}
/// Mean brightness of the center pixel's neighbourhood.
fn center_lum(px: &[u8], w: usize, h: usize) -> f32 {
let (cx, cy) = (w / 2, h / 2);
let mut sum = 0.0;
for y in cy - 2..cy + 2 {
for x in cx - 2..cx + 2 {
let i = (y * w + x) * 4;
sum += (px[i] as f32 + px[i + 1] as f32 + px[i + 2] as f32) / 3.0;
}
}
sum / 16.0
}
#[test]
fn point_lights_ambient_and_the_environment_switch_change_the_brightness() {
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
let maps = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.5, 0.5, 0.5, 1.0])), ..Maps::default() };
let base = Settings::default();
let plain = center_lum(&render(&scene, &maps, &light, &base, 64, 48), 64, 48);
let dark = Settings { env_light: false, ..base };
let no_env = center_lum(&render(&scene, &maps, &light, &dark, 64, 48), 64, 48);
assert!(no_env < plain - 20.0, "no environment light leaves the sphere dark: {no_env} vs {plain}");
let mut lit = dark;
lit.lights[0].on = true;
lit.lights[0].intensity = 4.0;
let with_light = center_lum(&render(&scene, &maps, &light, &lit, 64, 48), 64, 48);
assert!(with_light > no_env + 20.0, "a point light brightens the dark sphere: {with_light} vs {no_env}");
let ambient = Settings { env_light: false, ambient: [0.5; 3], ..base };
let amb = center_lum(&render(&scene, &maps, &light, &ambient, 64, 48), 64, 48);
assert!(amb > no_env + 20.0, "ambient light lifts it again: {amb} vs {no_env}");
}
#[test]
fn every_shader_renders_and_the_common_values_drive_unmapped_channels() {
let (scene, light) = (Scene::builtin("rounded_cube"), Lighting::new("studio"));
let maps = Maps::default();
for (shader, _) in Shader::ALL {
let s = Settings { shader, ..Settings::default() };
let px = render(&scene, &maps, &light, &s, 48, 32);
assert_eq!(px.len(), 48 * 32 * 4, "{shader:?}");
}
let mut red = Settings::default();
red.common.base_color = [0.8, 0.05, 0.05];
let px = render(&scene, &maps, &light, &red, 64, 48);
let c = ((24 * 64 + 32) * 4) as usize;
assert!(px[c] > px[c + 1] + 30, "the common base color shows without a map: {:?}", &px[c..c + 3]);
// A map wins over the common value, unless its use is switched off.
let blue = Maps { base_color: Some(Image::filled(8, 8, Kind::Color, [0.05, 0.05, 0.8, 1.0])), ..Maps::default() };
let px = render(&scene, &blue, &light, &red, 64, 48);
assert!(px[c + 2] > px[c] + 30, "the map wins: {:?}", &px[c..c + 3]);
let mut off = red;
off.use_map.base_color = false;
let px = render(&scene, &blue, &light, &off, 64, 48);
assert!(px[c] > px[c + 2] + 30, "use_map off falls back to the common color: {:?}", &px[c..c + 3]);
// Emission from the common values lights the surface by itself.
let mut glow = Settings { env_light: false, ..Settings::default() };
glow.common.emission_luminance = 2.0;
glow.common.emission_color = [0.0, 1.0, 0.0];
let px = render(&scene, &maps, &light, &glow, 64, 48);
assert!(px[c + 1] > 150 && px[c] < 60, "emission glows green: {:?}", &px[c..c + 3]);
}
#[test]
fn background_clip_planes_wireframe_and_culling_show_in_the_frame() {
let (scene, light) = (Scene::builtin("sphere"), Lighting::new("studio"));
let maps = Maps::default();
let corner = 0usize;
let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), ..Settings::default() };
let px = render(&scene, &maps, &light, &s, 64, 48);
assert!(px[corner + 1] > 200 && px[corner] < 40, "a flat green background: {:?}", &px[corner..corner + 3]);
// Clip planes past the sphere: only the background is left.
let s = Settings { background: Background::Color([0.0, 1.0, 0.0]), clip: Some([10.0, 12.0]), ..Settings::default() };
let px = render(&scene, &maps, &light, &s, 64, 48);
let c = ((24 * 64 + 32) * 4) as usize;
assert!(px[c + 1] > 200 && px[c] < 40, "clipped away: {:?}", &px[c..c + 3]);
// Wireframe paints orange along the edges of a cube's twelve triangles, not everywhere.
let cube = Scene::builtin("cube");
let s = Settings { wireframe: true, ..Settings::default() };
let px = render(&cube, &maps, &light, &s, 96, 72);
let orange = px.chunks_exact(4).filter(|p| p[0] > 200 && p[1] > 120 && p[1] < 235 && p[2] < 60).count();
assert!(orange > 20 && orange < 96 * 72 / 2, "wire edges drawn: {orange}");
// Backface culling on a plane seen from below leaves the background.
let plane = Scene::builtin("plane");
let below =
Settings { pitch: -60.0, background: Background::Color([0.0, 1.0, 0.0]), backface_culling: true, transparency: false, ..Settings::default() };
let px = render(&plane, &maps, &light, &below, 64, 48);
assert!(px[c + 1] > 200 && px[c] < 40, "the plane's back face is culled: {:?}", &px[c..c + 3]);
let shown = Settings { backface_culling: false, ..below };
let px = render(&plane, &maps, &light, &shown, 64, 48);
assert!(!(px[c + 1] > 200 && px[c] < 40), "without culling the back face shows: {:?}", &px[c..c + 3]);
}
fn displacement(depth: f32, level: f32) -> Displacement {
Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false }
}
-1
View File
@@ -25,7 +25,6 @@ zip = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
sys-locale = "0.3"
rfd = { workspace = true }
rayon = { workspace = true }
# Floating panels open as OS windows.
craft-ui = { workspace = true, features = ["native-windows"] }
+61 -5
View File
@@ -226,6 +226,16 @@ fn merge_json(dst: &mut Value, patch: &Value) {
}
pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value {
match crate::cook::guard("control request", || Ok(handle_inner(app, ctx, method, p))) {
Ok(v) => v,
Err(e) => {
app.session.dirty = false;
err(e)
}
}
}
fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value {
match method {
"ping" => ok(json!("pong")),
"ui.resize" => {
@@ -243,22 +253,37 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let params = p.get("params").cloned().unwrap_or(Value::Null);
match crate::cook::guard("command request", || {
materialcraft_engine::commands::execute_request(&mut app.session, id, &params).map_err(|error| error.to_string())
Ok(materialcraft_engine::commands::execute_request(&mut app.session, id, &params).map_err(|error| error.to_string()))
}) {
Ok(v) => {
Ok(Ok(v)) => {
if id == "view.previewSize" {
app.ui.prefs.preview_size = app.session.preview_size.unwrap_or(0);
}
app.close_subgraph_after(id);
ok(v)
}
Err(e) => err(e),
Ok(Err(e)) => err(e),
Err(e) => {
app.session.dirty = false;
err(e)
}
}
}
"command.list" => ok(materialcraft_engine::commands::list(&app.session, p.get("filter").and_then(Value::as_str))),
"session.inspect" => {
app.session.cook_if_dirty();
ok(materialcraft_engine::inspect::session(&app.session, None))
match crate::cook::guard("session.inspect", || {
app.session.cook_if_dirty();
if app.session.graph().is_err() {
return Err(format!("invalid graph {}", app.session.graph));
}
Ok(materialcraft_engine::inspect::session(&app.session, None))
}) {
Ok(v) => ok(v),
Err(e) => {
app.session.dirty = false;
err(e)
}
}
}
"ui.inspect" => {
let rect = |r: egui::Rect| json!([r.min.x, r.min.y, r.width(), r.height()]);
@@ -266,6 +291,7 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports);
ok(json!({
"state": app.ui,
"maximizedPanel": app.ui.dock.maximized(),
"graphView": rect(view),
"selection": app.session.selection,
"inspectedNode": app.graph.inspected_node,
@@ -294,6 +320,19 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
"toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(),
}))
}
"ui.panel.maximize" => {
let Some(panel) = p.get("panel").cloned().and_then(|value| serde_json::from_value::<crate::docking::Panel>(value).ok()) else {
return err("`panel` must name a workspace panel, such as Graph or View2d");
};
match app.ui.dock.maximize(panel) {
Ok(()) => {
ctx.request_repaint();
ok(Value::Null)
}
Err(error) => err(error),
}
}
"ui.menu.list" => ok(crate::menus::list(app)),
"ui.menu.invoke" => {
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
@@ -391,4 +430,21 @@ mod tests {
let c = &app.ui.graph_camera;
assert!((c.pan[0] + 100.0 / c.zoom).is_finite());
}
#[test]
fn session_inspect_panic_returns_error_and_resets_cook_state() {
let mut app = app();
let ctx = egui::Context::default();
app.session.preview_size = Some(64);
app.session.cook();
let valid_graph = app.session.graph;
app.session.graph = app.session.graph.wrapping_add(1_000);
app.session.dirty = true;
let r = handle(&mut app, &ctx, "session.inspect", &json!({}));
assert_eq!(r["ok"], json!(false), "{r}");
assert!(!app.session.dirty, "cook state not reset after panic: dirty={}", app.session.dirty);
app.session.graph = valid_graph;
let r = handle(&mut app, &ctx, "session.inspect", &json!({}));
assert_eq!(r["ok"], json!(true), "{r}");
}
}
+12 -64
View File
@@ -13,7 +13,11 @@ use crate::MaterialCraftApp;
/// the app (and unsaved work) down
pub fn guard<T>(what: &str, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|p| {
let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default();
let msg = p
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| p.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic payload".to_string());
Err(format!("internal error in {what}: {msg}"))
})
}
@@ -45,58 +49,12 @@ pub struct Cooker {
pub started: Option<f64>,
/// `Session::cook_epoch` when the running cook started
epoch: u64,
/// Tools ▸ Suspend engine: no cook starts until resumed
pub suspended: bool,
/// Tools ▸ Cancel rendering: the running cook stops and nothing restarts until the next edit
pub hold: bool,
/// Tools ▸ Switch engine: worker threads for the cook (0 = all the cores)
pub threads: usize,
#[cfg(not(target_arch = "wasm32"))]
pool: Option<(usize, std::sync::Arc<rayon::ThreadPool>)>,
}
/// Stop the running cook (Tools ▸ Cancel rendering). The graph stays as it was until the
/// next edit computes it again
pub fn cancel(app: &mut MaterialCraftApp) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(flag) = &app.cooker.cancel {
flag.store(true, std::sync::atomic::Ordering::Relaxed);
}
app.cooker.hold = true;
app.session.dirty = false;
}
impl Cooker {
pub fn busy(&self) -> bool {
self.rx.is_some()
}
/// The cook's thread pool for the chosen thread count (built once per count); `None` runs
/// on the global pool (all the cores)
#[cfg(not(target_arch = "wasm32"))]
fn pool(&mut self) -> Option<std::sync::Arc<rayon::ThreadPool>> {
let n = self.threads;
if n == 0 {
self.pool = None;
return None;
}
if let Some((have, p)) = &self.pool
&& *have == n
{
return Some(p.clone());
}
match rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("materialcraft-cook-{i}")).build() {
Ok(p) => {
let p = std::sync::Arc::new(p);
self.pool = Some((n, p.clone()));
Some(p)
}
Err(e) => {
log::warn!("could not build a {n}-thread pool ({e}); using every core");
None
}
}
}
}
/// Collect a finished cook and start the next one if the graph changed
@@ -112,9 +70,8 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
}
match result {
// A stopped cook is partial: keep the previous results and cook again
// (unless the user cancelled it: then wait for the next edit)
Ok(c) if c.cancelled() => {
if app.cooker.epoch == app.session.cook_epoch && !app.cooker.hold {
if app.cooker.epoch == app.session.cook_epoch {
app.session.dirty = true;
}
}
@@ -155,8 +112,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
}
}
}
if app.session.dirty && !app.cooker.suspended {
app.cooker.hold = false;
if app.session.dirty {
start(app, ctx.input(|i| i.time));
ctx.request_repaint();
}
@@ -167,7 +123,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
let s = &mut app.session;
s.dirty = false;
let pkg = s.pkg.clone();
let (gi, max) = (s.graph, s.cook_size(s.preview_size));
let (gi, max) = (s.graph, s.preview_size);
let materials = s.material_preview.graphs();
let cache = s.cache.clone();
let epoch = s.cook_epoch;
@@ -175,20 +131,12 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
let (tx, rx) = std::sync::mpsc::channel();
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let thread_flag = flag.clone();
let pool = app.cooker.pool();
use materialcraft_engine::eval::Options;
let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || {
let run = || {
let mut opts = Options::new(&dec);
opts.max_size = max;
opts.cancel = Some(&thread_flag);
guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache)))
};
// A pool of the chosen size keeps the cook's parallel work to that many threads
let cooked = match pool {
Some(p) => p.install(run),
None => run(),
};
let mut opts = Options::new(&dec);
opts.max_size = max;
opts.cancel = Some(&thread_flag);
let cooked = guard("cook", || Ok(PreviewCook::run(&pkg, gi, &materials, &opts, &cache)));
let _ = tx.send(cooked);
});
match spawned {
+8
View File
@@ -61,6 +61,14 @@ mod worker_failure_tests {
assert_eq!(guard("test", || Ok::<_, String>(7)).unwrap(), 7);
}
#[test]
fn guard_reports_unknown_panic_payload_instead_of_empty() {
let r: Result<u32, String> = guard("test", || -> Result<u32, String> { std::panic::panic_any(42) });
let e = r.unwrap_err();
assert!(e.contains("unknown"), "{e}");
assert!(!e.trim_end().ends_with(':'), "{e}");
}
#[test]
fn a_panicked_cook_worker_reports_errors_on_every_node() {
let mut app = app();
+49 -367
View File
@@ -1,336 +1,74 @@
//! The dock host: every panel (explorer, library, graph, 3D view, 2D view, properties, console,
//! history) is a tab that can be docked, tabbed, resized, floated and closed. craft-ui's shared
//! docking (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews
//! and owns the gestures; this module names the panels, builds the default arrangement, applies
//! the dock's changes and hosts the panel bodies.
//!
//! The graph is the central canvas: it stays docked, never takes tabs and is the only panel that
//! cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`; a layout
//! that does not load or validate becomes the default.
//! Panel hosting, workspace validation and transient maximization
use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement};
use craft_ui::layout::{SplitAxis, SplitSize};
use egui::{Id, Margin, RichText, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::Value;
mod dock;
mod maximization;
mod panel;
mod panel_content;
mod workspace;
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
pub use dock::Dock;
pub use panel::{Panel, VIEWS, view_panel};
pub use workspace::{Workspace, default_workspace, permissions, validate};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Panel {
Graph,
Explorer,
Library,
View3d,
View2d,
Properties,
Console,
History,
}
use craft_ui::docking::{DockArea, DockStyle};
use egui::{Id, Ui};
/// Windows menu items and the panels they show or hide.
pub const VIEWS: [(&str, Panel); 7] = [
("ui.view.explorer", Panel::Explorer),
("ui.view.properties", Panel::Properties),
("ui.view.console", Panel::Console),
("ui.view.3d", Panel::View3d),
("ui.view.2d", Panel::View2d),
("ui.view.library", Panel::Library),
("ui.view.history", Panel::History),
];
/// The panel a Windows menu item toggles.
pub fn view_panel(id: &str) -> Option<Panel> {
VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p)
}
impl Panel {
pub const ALL: [Panel; 8] =
[Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History];
pub fn name(self) -> &'static str {
match self {
Panel::Graph => "Graph",
Panel::Explorer => "Explorer",
Panel::Library => "Library",
Panel::View3d => "3D View",
Panel::View2d => "2D View",
Panel::Properties => "Properties",
Panel::Console => "Console",
Panel::History => "History",
}
}
/// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded.
fn float_rect(self) -> Option<[f32; 4]> {
let slot = match self {
Panel::Console => 0.0,
Panel::History => 1.0,
_ => return None,
};
Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0])
}
}
/// The saved panel arrangement: craft-ui's workspace over MaterialCraft's panels.
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// The graph never moves, floats, closes or takes tabs; panels dock beside it.
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
}
fn tabs(panels: &[Panel]) -> Node<Panel> {
Node::Tabs { panels: panels.to_vec(), active: 0 }
}
fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
}
/// The default: explorer over library on the left; the graph over the 3D and 2D views in the
/// middle; properties on the right. Console and history are closed and open floating.
pub fn default_workspace() -> Workspace {
use Panel::*;
let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library]));
let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d]));
let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views);
let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties])));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
let location = Location {
floating: Some(rect),
anchor: None,
placement: Placement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
};
workspace.hidden.push((panel, location));
}
}
workspace
}
/// craft-ui's checks plus the graph's: a saved or hand-edited file cannot hide, float, group
/// or collapse it.
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = &workspace.layout;
if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) {
return Err("The graph cannot float".into());
}
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) {
return Err("The graph cannot be hidden".into());
}
let mut found = false;
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => {
if panels.len() != 1 {
return Err("The graph cannot share a tab group".into());
}
found = true;
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
return Err("The graph cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => {
return Err("The graph cannot be in a dock".into());
}
_ => {}
}
}
if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) }
}
// ---------------------------------------------------------------------------------------------
// The live dock
/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`).
#[derive(Clone, Debug)]
pub struct Dock {
workspace: Workspace,
/// A panel to bring in front of the other floating windows on the next frame.
raise: Option<Panel>,
/// A panel shown alone over the whole dock (Shift+Space on a panel; Windows ▸ Unmaximize
/// window). Not saved with the layout.
pub maximized: Option<Panel>,
/// The panel under the pointer on the last frame (the one Shift+Space maximizes).
pub hovered: Option<Panel>,
}
impl Default for Dock {
fn default() -> Self {
Dock { workspace: default_workspace(), raise: None, maximized: None, hovered: None }
}
}
impl PartialEq for Dock {
fn eq(&self, other: &Self) -> bool {
self.workspace == other.workspace
}
}
impl Serialize for Dock {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.workspace.serialize(s)
}
}
impl<'de> Deserialize<'de> for Dock {
/// Never fails: a layout that cannot be read or fails the graph's rules is the default.
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(Dock::from_value(Value::deserialize(d)?))
}
}
impl Dock {
/// The dock for a saved layout; the default when it is not a valid workspace.
pub fn from_value(value: Value) -> Dock {
let default = default_workspace();
let loaded = serde_json::from_value::<Workspace>(value).ok();
let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() };
workspace.reconcile(|_| true, permissions, &default);
if validate(&workspace).is_err() {
return Dock::default();
}
Dock { workspace, raise: None, maximized: None, hovered: None }
}
pub fn workspace(&self) -> &Workspace {
&self.workspace
}
pub fn is_open(&self, p: Panel) -> bool {
self.workspace.layout.contains(&p)
}
/// Open and the front tab of its group.
pub fn is_visible(&self, p: Panel) -> bool {
self.workspace.layout.panel_state(&p) == PanelState::Front
}
/// Hide a visible panel, otherwise bring it up.
pub fn toggle(&mut self, p: Panel) {
if self.is_visible(p) { self.close(p) } else { self.focus(p) }
}
pub fn close(&mut self, p: Panel) {
if let Err(error) = self.workspace.set_visible(p, false, None, permissions) {
log::warn!("panel {p:?} was not closed: {error}");
}
}
/// Open `p` (where it was when closed, else where it lives by default) and bring it to the
/// front.
pub fn focus(&mut self, p: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(p, true, None, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(p);
}
Ok(()) => log::warn!("panel {p:?} was not opened: it would break the graph's rules"),
Err(error) => log::warn!("panel {p:?} was not opened: {error}"),
}
}
/// One change from the dock area's gestures. A change that is rejected leaves the layout as
/// it was.
fn apply(&mut self, action: Action<Panel>) {
let mut next = self.workspace.clone();
match next.apply(action, permissions) {
Ok(_) if validate(&next).is_ok() => self.workspace = next,
Ok(_) => log::warn!("a panel move would break the graph's rules"),
Err(error) => log::warn!("a panel move was not applied: {error}"),
}
}
}
// ---------------------------------------------------------------------------------------------
// Drawing
use crate::{MaterialCraftApp, theme::Tokens};
use panel_content::PanelContent;
fn area_id() -> Id {
Id::unique("materialcraft-docking")
}
/// The dock look: every panel group is a card on the window's frame colour, its tab strip
/// without hard lines, the shown tab a pill, uppercase captions.
fn style(ui: &Ui, t: &Tokens) -> DockStyle {
let mut s = DockStyle::from_ui(ui);
s.gap = 6.0;
// Smallest panel extent a divider drag leaves.
s.min_pane = 60.0;
s.background = t.panel;
s.tab_background = t.panel;
s.active_background = t.button;
s.text = t.text_strong;
s.inactive_text = t.text_dim;
s.border = egui::Stroke::NONE;
s.accent = t.accent;
s.floating_background = t.panel;
s.floating_stroke = egui::Stroke::new(1.0, t.button_border);
s.font = egui::FontId::proportional(10.5);
s.min_tab_width = 54.0;
s.tab_height = 30.0;
// Panels arrange in a split tree around the graph; floating title bars only move windows.
s.new_dock_zones = false;
s.title_bar_docks = false;
s
/// Shared appearance for docked and floating panels
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
let mut style = DockStyle::from_ui(ui);
style.gap = 6.0;
// Smallest panel extent a divider drag leaves
style.min_pane = 60.0;
style.background = tokens.panel;
style.tab_background = tokens.panel;
style.active_background = tokens.button;
style.text = tokens.text_strong;
style.inactive_text = tokens.text_dim;
style.border = egui::Stroke::NONE;
style.accent = tokens.accent;
style.floating_background = tokens.panel;
style.floating_stroke = egui::Stroke::new(1.0, tokens.button_border);
style.font = egui::FontId::proportional(10.5);
style.min_tab_width = 54.0;
style.tab_height = 30.0;
// Floating title bars move windows without creating new docks
style.new_dock_zones = false;
style.title_bar_docks = false;
style
}
/// Draw the dock (graph and panels) into `ui`.
/// Draw the saved workspace or its maximized panel
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let tk = Tokens::get(&ctx);
// Shift+Space maximizes the panel under the pointer, or brings the layout back.
if !ctx.egui_wants_keyboard_input() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::Space)) {
app.ui.dock.maximized = match app.ui.dock.maximized {
Some(_) => None,
None => app.ui.dock.hovered,
};
let context = ui.ctx().clone();
if app.ui.dock.maximized().is_some() && maximization::consume_shortcut(&context) {
app.ui.dock.restore();
}
if let Some(panel) = app.ui.dock.maximized {
let title = Panels { app: &mut *app }.logical_label(&panel);
egui::Frame::NONE.fill(tk.panel).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(title).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button(tr("Unmaximize (Shift+Space)")).clicked() {
app.ui.dock.maximized = None;
}
});
});
let rect = ui.available_rect_before_wrap();
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
Panels { app }.body(&mut child, &panel);
});
if let Some(panel) = app.ui.dock.maximized() {
maximization::show(app, ui, panel);
return;
}
let style = style(ui, &tk);
let tokens = Tokens::get(&context);
let style = style(ui, &tokens);
let layout = app.ui.dock.workspace.layout.clone();
let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some());
let mut area = DockArea::new(area_id()).input_blocked(context.memory(|m| m.top_modal_layer()).is_some());
if let Some(panel) = app.ui.dock.raise.take() {
area = area.raise_panel(panel);
}
let output = area.show_content(ui, &layout, &style, &mut Panels { app });
let output = area.show_content(ui, &layout, &style, &mut PanelContent { app });
if let Some(error) = &output.error {
log::warn!("docking: {error}");
}
// A body that changed the layout (a panel opened from its own menu) wins over this frame's
// gestures, which were made against the old one.
if app.ui.dock.workspace.layout != layout {
craft_ui::docking::cancel_drag::<Panel>(&ctx, area_id());
// Panel actions take priority over gestures against the previous layout
if app.ui.dock.workspace.layout != layout || app.ui.dock.maximized().is_some() {
craft_ui::docking::cancel_drag::<Panel>(&context, area_id());
return;
}
for action in output.actions {
@@ -338,62 +76,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
}
/// The panels' contents, names and limits for the dock area.
struct Panels<'a> {
app: &'a mut MaterialCraftApp,
}
impl DockContent<Panel> for Panels<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
let app = &mut *self.app;
if ui.rect_contains_pointer(ui.max_rect()) {
app.ui.dock.hovered = Some(*panel);
}
match panel {
Panel::Graph => crate::graph::show(app, ui),
Panel::View3d => crate::view3d::show(app, ui),
Panel::View2d => crate::view2d::show(app, ui),
_ => {
egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel {
Panel::Explorer => crate::explorer::show(app, ui),
Panel::Library => crate::library::show(app, ui),
Panel::Properties => crate::properties::show(app, ui),
Panel::Console => crate::windows::console(app, ui),
Panel::History => crate::windows::history(app, ui),
_ => {}
});
}
}
}
fn logical_label(&self, panel: &Panel) -> String {
match panel {
Panel::Properties => crate::properties::title(self.app),
Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")),
Panel::View2d => crate::view2d::title(self.app),
p => tr(p.name()).to_string(),
}
}
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into()
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) };
PanelLimits { min, ..PanelLimits::default() }
}
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
Some(vec2(420.0, 320.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
+122
View File
@@ -0,0 +1,122 @@
use craft_ui::docking::{Action, PanelState};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{Panel, Workspace, default_workspace, permissions, validate};
/// Saved workspace and transient panel presentation
#[derive(Clone, Debug)]
pub struct Dock {
pub(super) workspace: Workspace,
pub(super) raise: Option<Panel>,
maximized: Option<Panel>,
}
impl Default for Dock {
fn default() -> Self {
Self { workspace: default_workspace(), raise: None, maximized: None }
}
}
impl PartialEq for Dock {
fn eq(&self, other: &Self) -> bool {
self.workspace == other.workspace
}
}
impl Serialize for Dock {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.workspace.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Dock {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::from_value(Value::deserialize(deserializer)?))
}
}
impl Dock {
/// Invalid layouts fall back to the default workspace
pub fn from_value(value: Value) -> Self {
let default = default_workspace();
let loaded = serde_json::from_value::<Workspace>(value).ok();
let Some(mut workspace) = loaded.filter(|workspace| validate(workspace).is_ok()) else {
return Self::default();
};
workspace.reconcile(|_| true, permissions, &default);
if validate(&workspace).is_err() {
return Self::default();
}
Self { workspace, raise: None, maximized: None }
}
pub fn workspace(&self) -> &Workspace {
&self.workspace
}
pub fn maximized(&self) -> Option<Panel> {
self.maximized
}
/// Maximization never alters the saved layout or opens hidden panels
pub fn maximize(&mut self, panel: Panel) -> Result<(), String> {
if self.workspace.layout.panel_state(&panel) != PanelState::Front {
return Err(format!("{} must be an open, active panel before maximizing", panel.name()));
}
self.maximized = Some(panel);
Ok(())
}
pub fn restore(&mut self) {
self.maximized = None;
}
pub fn is_open(&self, panel: Panel) -> bool {
self.workspace.layout.contains(&panel)
}
pub fn is_visible(&self, panel: Panel) -> bool {
self.maximized.map_or_else(|| self.workspace.layout.panel_state(&panel) == PanelState::Front, |maximized| maximized == panel)
}
/// Hide a visible panel or bring it into view
pub fn toggle(&mut self, panel: Panel) {
if self.is_visible(panel) { self.close(panel) } else { self.focus(panel) }
}
pub fn close(&mut self, panel: Panel) {
match self.workspace.set_visible(panel, false, None, permissions) {
Ok(()) if self.maximized == Some(panel) => self.restore(),
Ok(()) => {}
Err(error) => log::warn!("panel {panel:?} was not closed: {error}"),
}
}
/// Reveal the requested panel in its existing location
pub fn focus(&mut self, panel: Panel) {
let mut next = self.workspace.clone();
match next.set_visible(panel, true, None, permissions) {
Ok(()) if validate(&next).is_ok() => {
self.workspace = next;
self.raise = Some(panel);
if self.maximized != Some(panel) {
self.restore();
}
}
Ok(()) => log::warn!("panel {panel:?} was not opened: it would break the graph's rules"),
Err(error) => log::warn!("panel {panel:?} was not opened: {error}"),
}
}
/// Rejected gestures leave the layout intact
pub(super) fn apply(&mut self, action: Action<Panel>) {
let mut next = self.workspace.clone();
match next.apply(action, permissions) {
Ok(_) if validate(&next).is_ok() => self.workspace = next,
Ok(_) => log::warn!("a panel move would break the graph's rules"),
Err(error) => log::warn!("a panel move was not applied: {error}"),
}
}
}
@@ -0,0 +1,39 @@
use craft_ui::docking::DockContent;
use egui::{Context, Key, Modifiers, RichText, Ui};
use super::{Panel, panel_content::PanelContent};
use crate::{MaterialCraftApp, i18n::tr, theme::Tokens};
pub(super) fn consume_shortcut(context: &Context) -> bool {
if context.egui_wants_keyboard_input()
|| egui::Popup::is_any_open(context)
|| context.memory(|memory| memory.top_modal_layer()).is_some()
|| context.input(|input| input.pointer.any_down())
{
return false;
}
context.input_mut(|input| input.consume_key(Modifiers::SHIFT, Key::Space))
}
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, panel: Panel) {
let tokens = Tokens::get(ui.ctx());
let title = PanelContent { app }.logical_label(&panel);
egui::Frame::NONE.fill(tokens.panel).show(ui, |ui| {
ui.set_min_size(ui.available_size());
ui.horizontal(|ui| {
ui.label(RichText::new(title.to_uppercase()).size(10.5).strong().color(tokens.text_strong));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button(tr("Restore panel layout")).on_hover_text("Shift+Space").clicked() {
crate::menus::invoke(app, ui.ctx(), "ui.unmaximize");
}
});
});
let rectangle = ui.available_rect_before_wrap();
// Match the dock host's scope so widget state survives maximizing and restoring
let mut body = ui.new_child(
egui::UiBuilder::new().scope_id(super::area_id().with(("body", &panel))).max_rect(rectangle).layout(egui::Layout::top_down(egui::Align::Min)),
);
body.set_clip_rect(rectangle.intersect(ui.clip_rect()));
PanelContent { app }.body(&mut body, &panel);
});
}
+57
View File
@@ -0,0 +1,57 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Panel {
Graph,
Explorer,
Library,
View3d,
View2d,
Properties,
Console,
History,
}
/// Windows menu items and the panels they show or hide
pub const VIEWS: [(&str, Panel); 7] = [
("ui.view.explorer", Panel::Explorer),
("ui.view.properties", Panel::Properties),
("ui.view.console", Panel::Console),
("ui.view.3d", Panel::View3d),
("ui.view.2d", Panel::View2d),
("ui.view.library", Panel::Library),
("ui.view.history", Panel::History),
];
/// The panel a Windows menu item toggles
pub fn view_panel(id: &str) -> Option<Panel> {
VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p)
}
impl Panel {
pub const ALL: [Panel; 8] =
[Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History];
pub fn name(self) -> &'static str {
match self {
Panel::Graph => "Graph",
Panel::Explorer => "Explorer",
Panel::Library => "Library",
Panel::View3d => "3D View",
Panel::View2d => "2D View",
Panel::Properties => "Properties",
Panel::Console => "Console",
Panel::History => "History",
}
}
/// Initial floating rectangle in points: `[x, y, width, height]`
pub(super) fn float_rect(self) -> Option<[f32; 4]> {
let slot = match self {
Panel::Console => 0.0,
Panel::History => 1.0,
_ => return None,
};
Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0])
}
}
@@ -0,0 +1,65 @@
use craft_ui::docking::{DockContent, PanelLimits, Permissions};
use egui::{Margin, RichText, Ui, vec2};
use super::{Panel, permissions};
use crate::{MaterialCraftApp, i18n::tr};
/// Panel bodies, titles and sizing constraints
pub(super) struct PanelContent<'a> {
pub(super) app: &'a mut MaterialCraftApp,
}
impl DockContent<Panel> for PanelContent<'_> {
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
let app = &mut *self.app;
if app.ui.dock.maximized().is_none() && ui.rect_contains_pointer(ui.max_rect()) && super::maximization::consume_shortcut(ui.ctx()) {
if let Err(error) = app.ui.dock.maximize(*panel) {
log::warn!("panel was not maximized: {error}");
}
ui.ctx().request_repaint();
}
match panel {
Panel::Graph => crate::graph::show(app, ui),
Panel::View3d => crate::view3d::show(app, ui),
Panel::View2d => crate::view2d::show(app, ui),
_ => {
egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel {
Panel::Explorer => crate::explorer::show(app, ui),
Panel::Library => crate::library::show(app, ui),
Panel::Properties => crate::properties::show(app, ui),
Panel::Console => crate::windows::console(app, ui),
Panel::History => crate::windows::history(app, ui),
_ => {}
});
}
}
}
fn logical_label(&self, panel: &Panel) -> String {
match panel {
Panel::Properties => crate::properties::title(self.app),
Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")),
Panel::View2d => crate::view2d::title(self.app),
p => tr(p.name()).to_string(),
}
}
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into()
}
fn permissions(&self, panel: &Panel) -> Permissions {
permissions(panel)
}
fn limits(&self, panel: &Panel) -> PanelLimits {
let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) };
PanelLimits { min, ..PanelLimits::default() }
}
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
Some(vec2(420.0, 320.0))
}
}
+81
View File
@@ -0,0 +1,81 @@
use craft_ui::docking::{Layout, Location, Node, Permissions, Placement};
use craft_ui::layout::{SplitAxis, SplitSize};
use super::Panel;
/// The saved panel arrangement
pub type Workspace = craft_ui::docking::Workspace<Panel>;
/// The graph stays docked and separate from other tabs
pub fn permissions(panel: &Panel) -> Permissions {
if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
}
fn tabs(panels: &[Panel]) -> Node<Panel> {
Node::Tabs { panels: panels.to_vec(), active: 0 }
}
fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
}
/// Default workspace with console and history initially hidden
pub fn default_workspace() -> Workspace {
use Panel::*;
let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library]));
let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d]));
let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views);
let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties])));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
if let Some(rect) = panel.float_rect() {
let location = Location {
floating: Some(rect),
anchor: None,
placement: Placement::Tab { before: None },
size: None,
stack: None,
sibling: Vec::new(),
group: None,
};
workspace.hidden.push((panel, location));
}
}
workspace
}
/// Validate the workspace and protect the central graph panel
pub fn validate(workspace: &Workspace) -> Result<(), String> {
workspace.validate().map_err(|error| error.to_string())?;
let layout = &workspace.layout;
if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) {
return Err("The graph cannot float".into());
}
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) {
return Err("The graph cannot be hidden".into());
}
let mut found = false;
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => {
if panels.len() != 1 {
return Err("The graph cannot share a tab group".into());
}
found = true;
}
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
return Err("The graph cannot be collapsed".into());
}
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => {
return Err("The graph cannot be in a dock".into());
}
_ => {}
}
}
if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) }
}
+7 -121
View File
@@ -1,15 +1,11 @@
//! The package tree, its graphs, inputs, outputs and resources, each with a context menu
//! The package tree, its graphs, inputs, outputs and resources
use egui::{RichText, Sense, Ui};
use egui::{RichText, Ui};
mod actions;
mod package_menu;
mod tree_row;
use egui_phosphor::regular as icon;
use serde_json::json;
pub use actions::{GraphClipboard, Rename};
use crate::MaterialCraftApp;
use crate::i18n::tr;
use crate::theme::Tokens;
@@ -35,59 +31,16 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
});
ui.add_space(2.0);
let mut menu_pick: Option<&'static str> = None;
let mut resource_action: Option<(&str, usize)> = None;
let mut rename_done: Option<(usize, Option<String>)> = None;
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
let name = format!("{}{}", app.session.pkg.name, if app.session.modified { "*" } else { "" });
let package_row = tree_row::show(ui, &name, icon::PACKAGE, false);
if let Some(path) = &app.session.path {
package_row.clone().on_hover_text(path);
}
package_row.context_menu(|ui| {
if let Some(id) = package_menu::show(app, ui) {
menu_pick = Some(id);
}
});
ui.label(RichText::new(format!("{} {name}", icon::PACKAGE)).strong().color(tk.text_strong));
let mut open: Option<usize> = None;
let mut action: Option<(&str, usize)> = None;
let mut selected_node = None;
let mut assignment = None;
let renaming = app.explorer_rename.0.clone();
let can_paste = app.explorer_clipboard.0.is_some();
// Keyboard over the tree: F2 renames the open graph, Delete removes it
if ui.ui_contains_pointer() && renaming.is_none() && !ui.ctx().egui_wants_keyboard_input() {
let gi = app.session.graph;
ui.input(|i| {
if i.key_pressed(egui::Key::F2) {
action = Some(("rename", gi));
} else if i.key_pressed(egui::Key::Delete) {
action = Some(("delete", gi));
}
});
}
for (index, graph) in app.session.pkg.graphs.iter().enumerate() {
let active = index == app.session.graph;
let function = graph.function.is_some();
// Rename in place (F2 / the context menu)
if let Some((ri, mut text)) = renaming.clone()
&& ri == index
{
let resp = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 24.0));
if !resp.has_focus() && !resp.lost_focus() {
resp.request_focus();
}
let enter = ui.input(|inp| inp.key_pressed(egui::Key::Enter));
let escape = ui.input(|inp| inp.key_pressed(egui::Key::Escape));
if escape {
rename_done = Some((index, None));
} else if resp.lost_focus() || enter {
rename_done = Some((index, Some(text.clone())));
} else if resp.changed() {
app.explorer_rename.0 = Some((index, text));
}
continue;
}
let mut header = |ui: &mut Ui| {
let symbol = if function { icon::FUNCTION } else { icon::TREE_STRUCTURE };
let response = tree_row::show(ui, &graph.name, symbol, active);
@@ -105,19 +58,9 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.close();
}
}
ui.separator();
}
for (label, command, key, enabled) in [
("Open", "open", "Return", true),
("Copy", "copy", "", true),
("Paste", "paste", "", can_paste),
("Remove", "delete", "Del", true),
("Rename", "rename", "F2", true),
("Duplicate", "duplicate", "", true),
("Compute Outputs", "compute", "", true),
("Export outputs...", "export", "", true),
] {
if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() {
for (label, command) in [("Open", "open"), ("Export outputs...", "export"), ("Duplicate", "duplicate"), ("Delete", "delete")] {
if ui.button(tr(label)).clicked() {
action = Some((command, index));
ui.close();
}
@@ -198,71 +141,14 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
Some(("delete", i)) => {
app.run("graph.delete", json!({"graph": i}));
}
Some(("copy", i)) => actions::copy_graph(app, ui.ctx(), i),
Some(("paste", _)) => actions::paste_graph(app),
Some(("rename", i)) => {
if let Some(g) = app.session.pkg.graphs.get(i) {
app.explorer_rename.0 = Some((i, g.name.clone()));
}
}
Some(("compute", i)) if app.run("graph.open", json!({"graph": i})).is_some() => actions::compute(app),
_ => {}
}
if !app.session.pkg.resources.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new(tr("Resources")).color(tk.text_dim).size(11.0));
for (i, r) in app.session.pkg.resources.iter().enumerate() {
let linked = r.link.is_some();
let text = format!("{} {} ({} KB)", if linked { icon::LINK } else { icon::IMAGE }, r.name, r.bytes.len() / 1024);
let hover = match &r.link {
Some(l) => format!("{} {l}", tr("Linked:")),
None => tr("Embedded in the package").to_string(),
};
let resp = ui.add(egui::Label::new(text).sense(Sense::click())).on_hover_text(hover);
resp.context_menu(|ui| {
if linked && ui.button(tr("Relink...")).clicked() {
resource_action = Some(("relink", i));
ui.close();
}
if ui.button(tr("Add a Bitmap node")).clicked() {
resource_action = Some(("node", i));
ui.close();
}
if ui.button(tr("Remove")).clicked() {
resource_action = Some(("delete", i));
ui.close();
}
});
for r in &app.session.pkg.resources {
ui.label(format!("{} {} ({} KB)", icon::IMAGE, r.name, r.bytes.len() / 1024));
}
}
});
if let Some((i, text)) = rename_done {
let old = app.session.pkg.graphs.get(i).map(|g| g.name.clone()).unwrap_or_default();
app.explorer_rename.0 = None;
if let Some(new) = text.map(|t| t.trim().to_string()).filter(|t| !t.is_empty() && *t != old) {
app.run("graph.rename", json!({"graph": i, "name": new}));
}
}
match menu_pick {
Some("explorer.copy") => actions::copy_graph(app, ui.ctx(), app.session.graph),
Some("explorer.paste") => actions::paste_graph(app),
Some("explorer.compute") => actions::compute(app),
Some("explorer.reveal") => actions::reveal(app),
Some(id) => crate::menus::invoke(app, ui.ctx(), id),
None => {}
}
match resource_action {
Some(("delete", i)) => {
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) {
app.run("file.deleteResource", json!({"name": name}));
}
}
Some(("node", i)) => {
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone()) {
app.run("graph.node.add", json!({"def": "bitmap", "params": {"resource": name}}));
}
}
Some(("relink", i)) => actions::relink(app, i),
_ => {}
}
}
-80
View File
@@ -1,80 +0,0 @@
//! What the explorer's menus do beyond running a command: copy and paste whole graphs, compute
//! the outputs again, reveal the package file, relink a bitmap
use serde_json::json;
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// A graph on the explorer's clipboard (Copy / Paste a graph)
#[derive(Clone, Debug, Default)]
pub struct GraphClipboard(pub Option<serde_json::Value>);
/// Rename-in-place state: the graph index and the text being edited
#[derive(Clone, Debug, Default)]
pub struct Rename(pub Option<(usize, String)>);
/// Copy a graph as JSON: to the explorer clipboard, and as text to the system clipboard
pub(super) fn copy_graph(app: &mut MaterialCraftApp, ctx: &egui::Context, i: usize) {
let Some(g) = app.session.pkg.graphs.get(i) else { return };
match serde_json::to_value(g) {
Ok(v) => {
if let Ok(text) = serde_json::to_string(&v) {
ctx.copy_text(text);
}
app.explorer_clipboard.0 = Some(v);
app.toast(format!("{} {}", tr("Copied graph"), g.name), false);
}
Err(e) => app.toast(format!("{}: {e}", tr("Could not copy the graph")), true),
}
}
pub(super) fn paste_graph(app: &mut MaterialCraftApp) {
let Some(v) = app.explorer_clipboard.0.clone() else { return };
if let Some(r) = app.run("graph.add", json!({"graph": v})) {
app.toast(format!("{} {}", tr("Pasted graph"), r["name"].as_str().unwrap_or_default()), false);
}
}
/// Compute the open graph's outputs now: the cache is kept, the cook restarts (also lifts a Cancel)
pub(super) fn compute(app: &mut MaterialCraftApp) {
app.cooker.hold = false;
app.session.dirty = true;
}
/// Show the package file in the system's file browser
pub(super) fn reveal(app: &mut MaterialCraftApp) {
#[cfg(not(target_arch = "wasm32"))]
{
let Some(path) = app.session.path.clone() else { return };
let folder = std::path::Path::new(&path).parent().map(|p| p.to_path_buf()).unwrap_or_default();
let result = if cfg!(target_os = "windows") {
std::process::Command::new("explorer").arg(format!("/select,{path}")).spawn()
} else if cfg!(target_os = "macos") {
std::process::Command::new("open").arg("-R").arg(&path).spawn()
} else {
std::process::Command::new("xdg-open").arg(&folder).spawn()
};
if let Err(e) = result {
app.toast(format!("{} {} ({e})", tr("Package folder:"), folder.display()), true);
}
}
#[cfg(target_arch = "wasm32")]
app.toast(tr("The browser keeps no package folder"), true);
}
/// Pick a new file for a linked resource
pub(super) fn relink(app: &mut MaterialCraftApp, i: usize) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(name) = app.session.pkg.resources.get(i).map(|r| r.name.clone())
&& let Some(p) = crate::windows::dialog(app).add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file()
{
crate::windows::remember_dir(app, &p);
app.run("file.linkBitmap", json!({"path": p.display().to_string(), "name": name}));
}
#[cfg(target_arch = "wasm32")]
{
let _ = i;
app.toast(tr("The browser has no files to link to"), true);
}
}
@@ -1,48 +0,0 @@
//! The package row's context menu (New, Import, Link, Save, Export, Send to, Copy/Paste,
//! Close, Compute, Show in Explorer, Dependency Manager)
use egui::Ui;
use crate::MaterialCraftApp;
use crate::i18n::tr;
/// Draw the menu; returns the menu id picked (a `ui.`/`file.` command or an `explorer.` action)
pub(super) fn show(app: &MaterialCraftApp, ui: &mut Ui) -> Option<&'static str> {
let mut picked: Option<&'static str> = None;
let mut pick = |ui: &mut Ui, label: &str, id: &'static str, key: &str, enabled: bool| {
if crate::menus::menu_row(ui, tr(label), key, enabled).clicked() {
picked = Some(id);
ui.close();
}
};
ui.menu_button(tr("New"), |ui| {
pick(ui, "Graph...", "ui.newGraph", "Ctrl+N", true);
pick(ui, "Function Graph...", "ui.newFunctionGraph", "", true);
});
ui.menu_button(tr("Import"), |ui| {
pick(ui, "Bitmap...", "file.importBitmap", "", true);
pick(ui, "Graph from a package...", "file.importGraph", "", true);
});
ui.menu_button(tr("Link"), |ui| {
pick(ui, "Bitmap...", "file.linkBitmap", "", true);
});
pick(ui, "Reload", "ui.reloadResources", "", true);
ui.separator();
pick(ui, "Save", "file.save", "Ctrl+S", true);
pick(ui, "Save as...", "file.saveAs", "Ctrl+Shift+S", true);
pick(ui, "Save a copy as...", "file.saveCopy", "", true);
pick(ui, "Export with dependencies...", "file.exportWithDependencies", "", true);
ui.menu_button(tr("Send to"), |ui| {
pick(ui, "TextureCraft", "file.sendToTextureCraft", "", true);
});
ui.separator();
pick(ui, "Copy", "explorer.copy", "", true);
pick(ui, "Paste", "explorer.paste", "", app.explorer_clipboard.0.is_some());
ui.separator();
pick(ui, "Close package", "ui.closeAll", "", true);
pick(ui, "Compute Outputs", "explorer.compute", "", true);
pick(ui, "Show in Explorer...", "explorer.reveal", "", app.session.path.is_some());
ui.separator();
pick(ui, "Dependency Manager", "ui.view.dependencies", "", true);
picked
}
+12 -131
View File
@@ -1,141 +1,22 @@
//! The library while a function graph is being edited: the operations by category, each with
//! a text icon saying what it is, its inputs, and a tooltip. Double-click adds one.
use egui::{Align2, Color32, FontId, RichText, Ui, vec2};
use materialcraft_engine::FunctionEdit;
use materialcraft_engine::nodes::function::FunctionDefinition;
use super::op_badge;
use crate::theme::Tokens;
use crate::{MaterialCraftApp, i18n::tr};
/// The categories in the order the reference library lists them
const ORDER: [&str; 10] = ["Constant", "Variables", "Vector", "Cast", "Operator", "Logical", "Comparison", "Function", "Control", "Samplers"];
use egui::Ui;
use materialcraft_engine::FunctionEdit;
pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return };
let tk = Tokens::get(ui.ctx());
let operations = target.available_operations(&app.session);
ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions")));
let search = app.ui.library_search.to_ascii_lowercase();
let operations: Vec<&'static FunctionDefinition> = target
.available_operations(&app.session)
.filter(|d| {
search.is_empty()
|| d.label.to_ascii_lowercase().contains(&search)
|| d.id.contains(&search)
|| op_badge::text(d.id).to_ascii_lowercase().contains(&search)
})
.collect();
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions")).desired_width(f32::INFINITY));
crate::widgets::name(&r, egui::Role::TextInput, "Search functions");
ui.label(RichText::new(tr("Double-click an operation to add it to the function")).small().color(tk.text_dim));
ui.add_space(2.0);
let mut add: Option<&'static str> = None;
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
let mut categories: Vec<&str> = ORDER.to_vec();
for d in &operations {
if !categories.contains(&d.category) {
categories.push(d.category);
egui::ScrollArea::vertical().show(ui, |ui| {
for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) {
if ui.selectable_label(false, tr(definition.label)).double_clicked()
&& let Some(mut editor) = app.function_editor.take()
{
let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]);
editor.edit(app, FunctionEdit::Add { operation: definition.id.into(), at, snap: app.ui.prefs.snap_to_grid }, false);
app.function_editor = Some(editor);
}
}
for category in categories {
let rows: Vec<&&FunctionDefinition> = operations.iter().filter(|d| d.category == category).collect();
if rows.is_empty() {
continue;
}
let key = format!("fn:{category}");
let collapsed = app.ui.library_collapsed.contains(&key) && search.is_empty();
let header = ui.horizontal(|ui| {
let color = op_badge::color(category);
ui.label(RichText::new(if collapsed { egui_phosphor::regular::CARET_RIGHT } else { egui_phosphor::regular::CARET_DOWN }).color(tk.text_dim));
ui.label(RichText::new(op_badge::icon(category)).color(color));
ui.label(RichText::new(tr(category)).strong());
ui.label(RichText::new(format!("{}", rows.len())).small().color(tk.text_dim));
});
let header = ui.interact(header.response.rect, ui.scope_id().with(&key), egui::Sense::click());
crate::widgets::name(&header, egui::Role::TreeItem, category);
if header.clicked() {
if collapsed {
app.ui.library_collapsed.retain(|k| k != &key);
} else {
app.ui.library_collapsed.push(key.clone());
}
}
if collapsed {
continue;
}
for d in rows {
if row(ui, d, &tk) {
add = Some(d.id);
}
}
ui.add_space(4.0);
}
});
if let Some(operation) = add
&& let Some(mut editor) = app.function_editor.take()
{
let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]);
editor.edit(app, FunctionEdit::Add { operation: operation.into(), at, snap: app.ui.prefs.snap_to_grid }, false);
app.function_editor = Some(editor);
}
}
/// One operation: the badge, the label, its inputs; true on a double-click
fn row(ui: &mut Ui, d: &FunctionDefinition, tk: &Tokens) -> bool {
let height = 24.0;
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::click());
crate::widgets::name(&resp, egui::Role::ListItem, d.label);
let p = ui.painter();
if resp.hovered() {
p.rect_filled(rect, 4.0, tk.row_hover);
}
let color = op_badge::color(d.category);
let badge = egui::Rect::from_min_size(rect.min + vec2(14.0, 3.0), vec2(46.0, height - 6.0));
p.rect_filled(badge, 4.0, Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), 48));
p.rect_stroke(badge, 4.0, egui::Stroke::new(1.0, Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), 140)), egui::StrokeKind::Inside);
p.text(badge.center(), Align2::CENTER_CENTER, op_badge::text(d.id), FontId::monospace(11.0), color);
p.text(badge.right_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, tr(d.label), FontId::proportional(12.5), tk.text);
if !d.inputs.is_empty() {
p.text(rect.right_center() - vec2(6.0, 0.0), Align2::RIGHT_CENTER, d.inputs.join(", "), FontId::proportional(10.5), tk.text_dim);
}
let added = resp.double_clicked();
resp.on_hover_ui(|ui| {
ui.label(RichText::new(tr(d.label)).strong());
ui.label(tr(op_badge::describe(d.id)));
ui.label(
RichText::new(format!(
"{}: {} {}: {}",
tr("Category"),
tr(d.category),
tr("Inputs"),
if d.inputs.is_empty() { "none".to_string() } else { d.inputs.join(", ") }
))
.small()
.color(tk.text_dim),
);
});
added
}
#[cfg(test)]
mod tests {
use super::op_badge;
/// Every operation has its own badge, and every badge is drawn from glyphs the UI font has
#[test]
fn every_operation_has_a_badge_in_the_font() {
let allowed = "≠≥≤√×÷−·•¬ƒ";
for d in materialcraft_engine::nodes::function::FUNCTIONS.iter() {
let badge = op_badge::text(d.id);
assert_ne!(badge, "ƒ", "{} has no badge", d.id);
for c in badge.chars() {
assert!(c.is_ascii() || allowed.contains(c), "{}: {c:?} is not in the UI font", d.id);
}
assert_ne!(op_badge::describe(d.id), "A function node.", "{} has no description", d.id);
}
}
}
-1
View File
@@ -4,7 +4,6 @@ mod function_drag;
mod function_editor;
mod function_target;
pub(crate) mod library;
pub(crate) mod op_badge;
mod port_label;
pub(crate) mod properties;
-173
View File
@@ -1,173 +0,0 @@
//! A short text icon for each function operation: what the node is at a glance ("F2", "+",
//! "≥", "sin", "if"), with a colour per category
use egui::Color32;
/// The text icon of a function operation (its id), always from the glyphs the UI font has
pub fn text(id: &str) -> &'static str {
match id {
"const_bool" => "B",
"const_float1" => "F1",
"const_float2" => "F2",
"const_float3" => "F3",
"const_float4" => "F4",
"const_int1" => "I1",
"const_int2" => "I2",
"const_int3" => "I3",
"const_int4" => "I4",
"const_string" => "S",
"get_bool" => "$B",
"get_float1" => "$F1",
"get_float2" => "$F2",
"get_float3" => "$F3",
"get_float4" => "$F4",
"get_integer1" => "$I1",
"get_integer2" => "$I2",
"get_integer3" => "$I3",
"get_integer4" => "$I4",
"get_string" => "$S",
"set" => "$=",
"isdefined" => "$?",
"add" => "+",
"sub" => "−",
"mul" => "×",
"div" => "÷",
"mod" => "%",
"neg" => "−x",
"mulscalar" => "×s",
"dot" => "a·b",
"and" => "&&",
"or" => "||",
"not" => "¬",
"eq" => "=",
"noteq" => "≠",
"gt" => ">",
"gteq" => "≥",
"lr" => "<",
"lreq" => "≤",
"abs" => "|x|",
"floor" => "flr",
"ceil" => "ceil",
"sqrt" => "√",
"exp" => "e^x",
"log" => "ln",
"log2" => "log2",
"pow2" => "2^x",
"sin" => "sin",
"cos" => "cos",
"tan" => "tan",
"atan2" => "atan",
"rand" => "rnd",
"min" => "min",
"max" => "max",
"pow" => "x^y",
"lerp" => "lerp",
"cartesian" => "polar",
"vector2" => "F2( )",
"vector3" => "F3( )",
"vector4" => "F4( )",
"swizzle1" => ".x",
"swizzle2" => ".xy",
"swizzle3" => ".xyz",
"swizzle4" => ".xyzw",
"ivector2" => "I2( )",
"ivector3" => "I3( )",
"ivector4" => "I4( )",
"iswizzle1" => "i.x",
"iswizzle2" => "i.xy",
"iswizzle3" => "i.xyz",
"iswizzle4" => "i.xyzw",
"tofloat" => "(F1)",
"toint1" => "(I1)",
"tofloat2" => "(F2)",
"toint2" => "(I2)",
"tofloat3" => "(F3)",
"toint3" => "(I3)",
"tofloat4" => "(F4)",
"toint4" => "(I4)",
"samplecol" => "RGBA",
"samplelum" => "Gray",
"ifelse" => "if",
"sequence" => "seq",
"while" => "loop",
"passthrough" => "•",
_ => "ƒ",
}
}
/// The colour of a category's badges: the node header colour, lightened so text in it reads
/// on both themes
pub fn color(category: &str) -> Color32 {
let base = super::geometry::category_color(category);
let lift = |c: u8| (c as f32 + (255.0 - c as f32) * 0.45) as u8;
Color32::from_rgb(lift(base.r()), lift(base.g()), lift(base.b()))
}
/// The category's icon (phosphor glyph)
pub fn icon(category: &str) -> &'static str {
use egui_phosphor::regular as icon;
match category {
"Constant" => icon::HASH,
"Variables" => icon::BRACKETS_CURLY,
"Vector" => icon::ARROWS_OUT_CARDINAL,
"Cast" => icon::ARROWS_LEFT_RIGHT,
"Operator" => icon::PLUS_MINUS,
"Logical" => icon::CIRCLES_THREE,
"Comparison" => icon::EQUALS,
"Function" => icon::FUNCTION,
"Control" => icon::GIT_FORK,
"Samplers" => icon::EYEDROPPER_SAMPLE,
_ => icon::DOTS_THREE,
}
}
/// One line on what the operation does (the row's tooltip)
pub fn describe(id: &str) -> &'static str {
match id {
"const_bool" | "const_float1" | "const_float2" | "const_float3" | "const_float4" | "const_int1" | "const_int2" | "const_int3" | "const_int4"
| "const_string" => "A constant value of this type, set in the node's properties.",
"get_bool" | "get_float1" | "get_float2" | "get_float3" | "get_float4" | "get_integer1" | "get_integer2" | "get_integer3" | "get_integer4"
| "get_string" => "Reads a variable of this type: a graph input, an exposed parameter, or $pos / $size / $time.",
"set" => "Stores the value in a named variable for later Get nodes in the same function.",
"isdefined" => "True when the named variable has a value.",
"add" => "a + b (same types).",
"sub" => "a − b.",
"mul" => "a × b, component by component.",
"div" => "a ÷ b.",
"mod" => "The remainder of a ÷ b.",
"neg" => "−a.",
"mulscalar" => "Every component of a multiplied by the scalar.",
"dot" => "The dot product of two vectors.",
"and" | "or" | "not" => "Boolean logic.",
"eq" | "noteq" | "gt" | "gteq" | "lr" | "lreq" => "Compares a with b; the result is a boolean.",
"abs" => "|a|.",
"floor" => "Rounds down to a whole number.",
"ceil" => "Rounds up to a whole number.",
"sqrt" => "The square root.",
"exp" => "e to the power a.",
"log" => "The natural logarithm.",
"log2" => "The logarithm base 2.",
"pow2" => "2 to the power a.",
"sin" | "cos" | "tan" => "Trigonometry; the input is in radians.",
"atan2" => "The angle of the vector (y, x), in radians.",
"rand" => "A random number from 0 to a.",
"min" => "The smaller of a and b.",
"max" => "The larger of a and b.",
"pow" => "a to the power b.",
"lerp" => "a blended to b by x (0 = a, 1 = b).",
"cartesian" => "Polar (rho, theta) to cartesian (x, y).",
"vector2" | "vector3" | "vector4" | "ivector2" | "ivector3" | "ivector4" => "Builds a vector from its components (the first ones, then the last).",
"swizzle1" | "swizzle2" | "swizzle3" | "swizzle4" | "iswizzle1" | "iswizzle2" | "iswizzle3" | "iswizzle4" => {
"Picks and reorders components of a vector (the pattern is in the node's properties)."
}
"tofloat" | "tofloat2" | "tofloat3" | "tofloat4" => "Converts the value to floats.",
"toint1" | "toint2" | "toint3" | "toint4" => "Converts the value to integers (truncated).",
"samplecol" => "The colour of an image input at a position (pixel processors).",
"samplelum" => "The grayscale value of an image input at a position (pixel processors).",
"ifelse" => "The if path when the condition is true, else the else path.",
"sequence" => "Evaluates the first input (for its side effects), returns the last.",
"while" => "Runs the loop input while the condition holds, after init.",
"passthrough" => "A dot: passes its input through, to tidy wires.",
_ => "A function node.",
}
}
+2 -5
View File
@@ -50,7 +50,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
}
let mut camera = crate::graph::GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
camera.zoom_from_input(ui, canvas_bounds, app.ui.prefs.invert_zoom);
camera.zoom_from_input(ui, canvas_bounds);
editor.pan = camera.pan;
editor.zoom = camera.zoom;
let document = standalone.then(|| app.session.graph().ok()).flatten();
@@ -109,10 +109,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline));
let body = node_card::body(screen_rect, editor.zoom);
if node.value.is_none() {
// The operation's text icon ("+", "≥", "sin", "F2( )"): what the node is at a glance
let badge = super::op_badge::text(&node.op);
let size = if badge.chars().count() > 3 { 16.0 } else { 24.0 } * editor.zoom;
painter.text(body.center(), Align2::CENTER_CENTER, badge, FontId::monospace(size.min(30.0)), tokens.text_strong);
painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim);
}
if is_output {
let header = node_card::header(screen_rect, editor.zoom);
+4 -17
View File
@@ -87,29 +87,16 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], ca
hits
}
/// Paint the navigation pins; returns each pin's screen rect (icon and name) for hit testing
pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) -> Vec<(u64, Rect)> {
pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) {
let painter = ui.painter_at(app.graph.view);
let theme = Tokens::get(ui.ctx());
let mut hits = Vec::with_capacity(pins.len());
for pin in pins {
let mut position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id));
if let Some(GraphDrag::Pin { id, delta }) = &app.graph.drag
&& *id == pin.id
{
position += materialcraft_engine::graph_grid::snap_position([delta.x, delta.y], app.ui.prefs.snap_to_grid).into();
}
let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id));
let position = camera.to_screen(position);
let dragging = matches!(&app.graph.drag, Some(GraphDrag::Pin { id, .. }) if *id == pin.id);
let color = if dragging { theme.text_strong } else { theme.accent };
painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), color);
let name = painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text);
let icon_rect = Rect::from_min_max(position + vec2(-9.0, -20.0), position + vec2(9.0, 2.0));
hits.push((pin.id, icon_rect.union(name)));
painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent);
painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text);
}
hits
}
pub(crate) fn offset(app: &MaterialCraftApp, contains: impl FnOnce(&materialcraft_engine::FrameContents) -> bool) -> Vec2 {
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more