Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions doppio/crates/engine/examples/render_scene.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
//! Builds a tiny scene through the C ABI and renders it to a PNG, with no editor and no window.
//!
//! ```text
//! cmake --build build --target caffeine-capi -j
//! cd doppio && cargo run -p doppio-engine --example render_scene -- /tmp/scene.png
//! ```
//!
//! `CAFFEINE_CAPI_LIB` points at another `libcaffeine-capi` when it is not in `build/`.
//! See `caffeine-website/content/en/docs/api/headless-engine-api.md`.

use doppio_engine::{Engine, FieldValue};

/// Adds a component by name and sets fields by name: the whole "scene description" language.
struct Scene<'a> {
engine: &'a mut Engine,
}

impl Scene<'_> {
fn component(&mut self, entity: u32, name: &str) -> u32 {
let type_id = self
.engine
.component_types()
.iter()
.find(|t| t.name == name)
.unwrap_or_else(|| panic!("no component named {name}"))
.id;
self.engine.add_component(entity, type_id).expect("add");
type_id
}

fn set(&mut self, entity: u32, type_id: u32, field: &str, value: FieldValue) {
let component = self
.engine
.entity_components(entity)
.iter()
.position(|c| c.type_id == type_id)
.expect("component was added") as u32;
let index = self
.engine
.component_types()
.iter()
.find(|t| t.id == type_id)
.and_then(|t| t.fields.iter().position(|f| f.name == field))
.unwrap_or_else(|| panic!("no field named {field}")) as u32;
self.engine
.set_component_field(entity, component, index, &value)
.expect("set field");
}

/// An entity drawn as a built-in shape (`Cube`, `Sphere`, `Plane`...).
fn shape(&mut self, name: &str, primitive: &str, at: [f32; 3], scale: [f32; 3]) -> u32 {
let entity = self.engine.create_entity(name).expect("entity");
let filter = self.component(entity, "Mesh Filter");
let option = self
.engine
.component_types()
.iter()
.find(|t| t.id == filter)
.and_then(|t| t.fields.iter().find(|f| f.name == "Primitive"))
.and_then(|f| f.options.iter().position(|o| o == primitive))
.unwrap_or_else(|| panic!("no primitive named {primitive}"));
self.set(entity, filter, "Primitive", FieldValue::Enum(option as i32));
self.component(entity, "Mesh Renderer");
self.engine.set_position(entity, at).expect("position");
self.engine.set_scale(entity, scale).expect("scale");
entity
}
}

fn main() {
let out = std::env::args()
.nth(1)
.unwrap_or_else(|| "scene.png".to_owned());
let mut engine =
Engine::load_default().expect("libcaffeine-capi not found (see CAFFEINE_CAPI_LIB)");

// A project folder for the materials (any folder works).
let root = std::env::temp_dir().join("caffeine-render-scene");
std::fs::create_dir_all(&root).expect("folder");
engine
.set_asset_root(&root.to_string_lossy())
.expect("asset root");

let mut scene = Scene {
engine: &mut engine,
};
let ground = scene.shape("Ground", "Plane", [0.0, 0.0, 0.0], [10.0, 1.0, 10.0]);
let cube = scene.shape("Cube", "Cube", [-1.2, 0.5, 0.0], [1.0, 1.0, 1.0]);
let ball = scene.shape("Ball", "Sphere", [1.2, 0.5, 0.0], [1.0, 1.0, 1.0]);

let sun = scene.engine.create_entity("Sun").expect("entity");
let light = scene.component(sun, "Light");
scene.set(sun, light, "Intensity", FieldValue::F32(1.2));
scene.component(sun, "Directional Light");
scene
.engine
.set_rotation(sun, [-40.0, 130.0, 0.0])
.expect("rotation");

// Materials are `.mat` assets: write them, then assign them to entities by path.
for (entity, name, albedo, roughness) in [
(ground, "ground", [0.25, 0.4, 0.2, 1.0], 0.9),
(cube, "red", [0.8, 0.1, 0.1, 1.0], 0.4),
(ball, "steel", [0.7, 0.7, 0.75, 1.0], 0.2),
] {
let mut material = scene.engine.new_material().expect("material");
material.albedo = albedo;
material.roughness = roughness;
let path = root.join(format!("{name}.mat"));
scene
.engine
.save_material(&path.to_string_lossy(), &material)
.expect("save");
scene
.engine
.apply_material(entity, &path.to_string_lossy())
.expect("apply");
}

// The camera orbits a focus point: yaw/pitch in radians, distance in metres.
engine
.set_camera(doppio_engine::Camera {
yaw: 0.6,
pitch: 0.35,
distance: 6.0,
focus: [0.0, 0.5, 0.0],
})
.expect("camera");

// The editor grid is on by default; a clean picture turns it off.
let mut settings = engine.viewport_settings().expect("settings");
settings.show_grid = false;
engine.set_viewport_settings(settings).expect("settings");

let (width, height) = (960, 540);
let pixels = engine.render(width, height).expect("render");
image::save_buffer(&out, &pixels, width, height, image::ColorType::Rgba8).expect("png");
println!("wrote {out} ({width}x{height})");
}
4 changes: 4 additions & 0 deletions doppio/crates/ui/src/uikit/components/node_canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub enum PortKind {
Look,
/// Terrain Generator: a field (a grid of 0-1 values: a height map or a mask).
Height,
/// Nature Generator: a material (library, card, colour or your own asset).
Material,
}

impl PortKind {
Expand All @@ -46,6 +48,7 @@ impl PortKind {
PortKind::Waves => theme::ICON_CYAN,
PortKind::Look => theme::WARNING,
PortKind::Height => theme::ICON_ORANGE,
PortKind::Material => theme::ICON_PINK,
}
}

Expand All @@ -60,6 +63,7 @@ impl PortKind {
PortKind::Waves => "waves",
PortKind::Look => "look",
PortKind::Height => "field",
PortKind::Material => "material",
}
}

Expand Down
25 changes: 25 additions & 0 deletions doppio/crates/ui/src/uikit/nature/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub enum Kind {
Mesh,
Skeleton,
Points,
/// A material (library preset, card, solid colour or one of your own assets).
Material,
}

impl Kind {
Expand All @@ -36,6 +38,7 @@ impl Kind {
Kind::Mesh => "mesh",
Kind::Skeleton => "skeleton",
Kind::Points => "points",
Kind::Material => "material",
}
}
}
Expand Down Expand Up @@ -70,6 +73,7 @@ pub enum Value {
Mesh(Part),
Skeleton(super::tree::Skeleton),
Points(Vec<PointInst>),
Material(MaterialSpec),
}

/// What an op sees: its parameters, its inputs and the quality level.
Expand Down Expand Up @@ -104,6 +108,12 @@ impl<'a> Args<'a> {
_ => None,
}
}
pub fn material(&self, i: usize) -> Option<&'a MaterialSpec> {
match self.inputs.get(i).copied().flatten() {
Some(Value::Material(m)) => Some(m),
_ => None,
}
}
pub fn points(&self, i: usize) -> Option<&'a Vec<PointInst>> {
match self.inputs.get(i).copied().flatten() {
Some(Value::Points(p)) => Some(p),
Expand Down Expand Up @@ -364,6 +374,21 @@ impl NatureGraph {
if part.is_empty() {
continue;
}
// Nothing is chosen inside a Part: the material has to arrive on its port (a generated
// surface counts, it brings its own).
if self.node(link.from).is_some_and(|n| n.op == "part") && part.surface.is_none() {
let wired = self
.links
.iter()
.find(|l| l.to == link.from && l.input == 1)
.and_then(|l| memo.get(&l.from).and_then(|v| v.get(l.output)));
if !matches!(wired, Some(Value::Material(_))) {
return Err(format!(
"The {} part has no material: wire a material node (Materials category) into its Material port",
part.name
));
}
}
match model
.parts
.iter_mut()
Expand Down
6 changes: 3 additions & 3 deletions doppio/crates/ui/src/uikit/nature/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ pub enum MaterialSpec {
/// A plain colour and roughness (stylised models, flower centres).
Solid { rgb: [f32; 3], roughness: f32 },
/// One of **your own** materials: an asset path to an existing `.mat` (used as it is).
Project(String),
Project(String, (u32, u32)),
/// One of your own images with transparency (a PNG leaf, petal, grass blade...): turned into a
/// cut-out card material.
ProjectTexture(String),
ProjectTexture(String, (u32, u32)),
}

impl MaterialSpec {
Expand All @@ -66,7 +66,7 @@ impl MaterialSpec {
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect(),
MaterialSpec::Project(path) | MaterialSpec::ProjectTexture(path) => {
MaterialSpec::Project(path, _) | MaterialSpec::ProjectTexture(path, _) => {
let stem = std::path::Path::new(path)
.file_stem()
.and_then(|s| s.to_str())
Expand Down
52 changes: 42 additions & 10 deletions doppio/crates/ui/src/uikit/nature/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,48 @@ fn chain(g: &mut NatureGraph, ids: &[NodeId]) {
}
}

fn part(g: &mut NatureGraph, col: f32, row: f32, name: &str, material: &str) -> NodeId {
/// Adds the node that gives a material from a table label (a library preset, a card texture or a solid
/// colour) and returns it. Presets use this so every part has an explicit material node.
fn material_node(g: &mut NatureGraph, label: &str, col: f32, row: f32) -> NodeId {
if let Some(i) = ops::LIBRARY_LABELS.iter().position(|l| *l == label) {
return g.add_with("mat_library", at(col, row), &[("preset", i as f32)]);
}
if let Some(i) = ops::CARD_LABELS.iter().position(|l| *l == label) {
return g.add_with("mat_cards", at(col, row), &[("card", i as f32)]);
}
let rgb = ops::solid_rgb(label);
g.add_with(
"part",
"mat_solid",
at(col, row),
&[
("name", ops::part_name_index(name)),
("material", ops::material_index(material)),
],
&[("r", rgb[0]), ("g", rgb[1]), ("b", rgb[2])],
)
}

/// A part with its own material node wired in.
fn part(g: &mut NatureGraph, col: f32, row: f32, name: &str, material: &str) -> NodeId {
let p = g.add_with(
"part",
at(col, row),
&[("name", ops::part_name_index(name))],
);
let m = material_node(g, material, col, row - 0.75);
assert!(g.connect(m, 0, p, 1), "material cannot feed the part");
p
}

/// Feeds the texture wired into a part to the Leaves node too, so it knows the atlas layout.
fn share_texture(g: &mut NatureGraph, leaves: NodeId, leaf_part: NodeId) {
let Some(link) = g
.links
.iter()
.find(|l| l.to == leaf_part && l.input == 1)
.copied()
else {
return;
};
assert!(g.connect(link.from, 0, leaves, 1));
}

fn finish(g: &mut NatureGraph, col: f32, parts: &[NodeId]) {
let out = g.add("output", at(col, 1.0));
for (i, p) in parts.iter().enumerate() {
Expand Down Expand Up @@ -429,12 +460,13 @@ fn tree(
at(1.0, 2.0),
&[
("density", leaf_density),
("size", leaf_size),
// Given in metres by the recipes; the node takes a share of the tree's height.
("size", leaf_size / height * 100.0),
("seed", seed),
("shapes", if foliage.contains("Mix") { 1.0 } else { 0.0 }),
],
);
let leaf_part = part(&mut g, 2.0, 2.0, "leaves", foliage);
share_texture(&mut g, leaves, leaf_part);
chain(&mut g, &[grow, leaves, leaf_part]);
parts.push(leaf_part);
}
Expand Down Expand Up @@ -462,12 +494,12 @@ fn ancient_oak() -> NatureGraph {
at(2.0, 2.0),
&[
("density", 14.0),
("size", 0.75),
("size", 0.75 / 7.5 * 100.0),
("seed", 12.0),
("shapes", 1.0),
],
);
let leaf_part = part(&mut g, 3.0, 2.0, "leaves", "Leaves · Broadleaf Mix (atlas)");
share_texture(&mut g, leaves, leaf_part);
assert!(g.connect(grow, 0, leaves, 0));
assert!(g.connect(leaves, 0, leaf_part, 0));
// Moss on the trunk and the roots (only the up-facing, lower parts get it).
Expand Down
Loading
Loading