use sgl_3d::glam::camera;
use sgl_3d::{
AlphaMode, AutoExposure, Camera, CompensationCurve, Decal, DirectionalLight, DirectionalShadow,
Fog, FogVolume, FrameInput, HemisphereLight, InstanceState, Light, LightShape, Mobility,
Renderer, Scene,
asset::{Asset, CompressedImage, CpuMesh, Image, Material, Vertex},
environment::{EnvironmentMap, PmremAtlas},
glam::{Mat4, Quat, Vec3},
settings::{MotionBlur, RenderPreset, Settings},
};
use std::{error::Error, path::PathBuf};
struct Options {
output: PathBuf,
frames: u32,
light: f32,
emission: f32,
anisotropy: f32,
alpha: bool,
decals: bool,
motion_blur: bool,
fog: bool,
}
impl Options {
fn parse() -> Result<Self, Box<dyn Error>> {
let mut options = Self {
output: "target/sgl-3d-offscreen.png".into(),
frames: 8,
light: 3.,
emission: 2.,
anisotropy: 0.,
alpha: false,
decals: false,
motion_blur: false,
fog: false,
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--frames" => {
options.frames = args.next().ok_or("--frames requires a count")?.parse()?
}
"--light" => {
options.light = args
.next()
.ok_or("--light requires an intensity")?
.parse()?
}
"--anisotropy" => {
options.anisotropy = args
.next()
.ok_or("--anisotropy requires strength 0..1")?
.parse()?;
}
"--emission" => {
options.emission = args
.next()
.ok_or("--emission requires an intensity")?
.parse()?
}
"--alpha" => options.alpha = true,
"--decals" => options.decals = true,
"--motion-blur" => options.motion_blur = true,
"--fog" => options.fog = true,
"--help" | "-h" => {
println!(
"offscreen [output.png] [--frames N] [--light F] [--emission F] [--anisotropy F] [--alpha] [--decals] [--motion-blur] [--fog]"
);
std::process::exit(0);
}
flag if flag.starts_with('-') => {
return Err(format!("unknown option {flag}").into());
}
_ => options.output = arg.into(),
}
}
if options.frames == 0 {
return Err("--frames must be at least one".into());
}
if !(0.0..=1.0).contains(&options.anisotropy) {
return Err("anisotropy strength must be finite in 0..1".into());
}
if !options.light.is_finite()
|| options.light < 0.
|| !options.emission.is_finite()
|| options.emission < 0.
{
return Err("light and emission intensities must be finite and nonnegative".into());
}
Ok(options)
}
}
fn material(base: [f32; 4], emissive: [f32; 3], metallic: f32, roughness: f32) -> Material {
Material {
name: "procedural surface".into(),
base,
emissive,
metallic,
roughness,
coat_roughness: 0.3,
..Default::default() }
}
fn cuboid(center: Vec3, size: Vec3, material: usize) -> CpuMesh {
let half = size * 0.5;
let mut mesh = CpuMesh {
vertices: Vec::new(),
indices: Vec::new(),
material,
deformation: Default::default(),
};
for (normal, u, v) in [
(Vec3::X, -Vec3::Z, Vec3::Y),
(-Vec3::X, Vec3::Z, Vec3::Y),
(Vec3::Y, Vec3::X, -Vec3::Z),
(-Vec3::Y, Vec3::X, Vec3::Z),
(Vec3::Z, Vec3::X, Vec3::Y),
(-Vec3::Z, -Vec3::X, Vec3::Y),
] {
let start = mesh.vertices.len() as u32;
for [s, t] in [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]] {
mesh.vertices.push(Vertex {
tangent: [u.x, u.y, u.z, 1.],
lightmap_bounds: [0., 0., 1., 1.],
lightmap_uv: [0.; 2],
position: (center + (normal + u * s + v * t) * half).to_array(),
normal: normal.to_array(),
uv: [(s + 1.) * 0.5, (t + 1.) * 0.5],
color: [1.; 4],
});
}
mesh.indices.extend([0, 1, 2, 0, 2, 3].map(|i| start + i));
}
mesh
}
fn panel(center: Vec3, u: Vec3, v: Vec3, material: usize) -> CpuMesh {
let normal = u.cross(v).normalize();
CpuMesh {
vertices: [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]
.map(|[s, t]| Vertex {
tangent: [u.x, u.y, u.z, 1.],
lightmap_bounds: [0., 0., 1., 1.],
lightmap_uv: [0.; 2],
position: (center + u * s + v * t).to_array(),
normal: normal.to_array(),
uv: [(s + 1.) * 0.5, (1. - t) * 0.5],
color: [1.; 4],
})
.to_vec(),
indices: vec![0, 1, 2, 0, 2, 3],
material,
deformation: Default::default(),
}
}
fn alpha_content() -> Result<Asset, Box<dyn Error>> {
let grate = CompressedImage::from_ktx2(include_bytes!("grate.ktx2"))?;
let mut bars = material([0.6, 0.6, 0.62, 1.], [0.; 3], 0.8, 0.35);
bars.base_texture = Some(0);
bars.double_sided = true;
bars.alpha = AlphaMode::Mask { cutoff: 0.5 };
let glass = |base: [f32; 4]| Material {
double_sided: true,
alpha: AlphaMode::Blend {
receives_screen_space_reflections: false,
},
..material(base, [0.; 3], 0., 0.05)
};
Ok(Asset {
meshes: vec![
panel(Vec3::new(1.4, 2.4, 1.2), Vec3::X * 1.2, Vec3::Z * 1.2, 0),
panel(Vec3::new(-1.2, 1., 1.9), Vec3::X * 0.7, Vec3::Y * 0.9, 1),
panel(Vec3::new(-0.7, 0.8, 2.6), Vec3::X * 0.7, Vec3::Y * 0.7, 2),
],
materials: vec![
bars,
glass([0.2, 0.5, 1., 0.35]),
glass([1., 0.55, 0.15, 0.45]),
],
images: vec![Image::Compressed(grate)],
rig: Default::default(),
})
}
fn add_decals(
device: &wgpu::Device,
queue: &wgpu::Queue,
scene: &mut Scene,
) -> Result<(), Box<dyn Error>> {
let stripes = image::RgbaImage::from_fn(128, 32, |x, y| {
let paint = if (x + y) / 16 % 2 == 0 {
[230, 170, 20]
} else {
[20, 20, 22]
};
let edge = y.min(31 - y).min(4) * 255 / 4;
image::Rgba([paint[0], paint[1], paint[2], edge as u8])
});
let base_color = scene.add_decal_image(Image::Rgba8(stripes))?;
let matte = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 230, 0, 255]));
let metallic_roughness = scene.add_decal_image(Image::Rgba8(matte))?;
let stripe = |position: Vec3, turn: f32| Decal {
position,
rotation: Quat::from_rotation_y(turn),
size: Vec3::new(2.4, 0.3, 0.6),
metallic_roughness: Some(metallic_roughness),
normal_fade: 0.5,
..Decal::new(base_color) };
scene.add_decal(device, queue, stripe(Vec3::new(0.6, -0.05, 2.), 0.))?;
scene.add_decal(device, queue, stripe(Vec3::new(2.4, -0.05, 0.6), 1.2))?;
Ok(())
}
fn neutral_environment() -> EnvironmentMap {
EnvironmentMap {
panorama: image::RgbaImage::from_pixel(4, 2, image::Rgba([50, 50, 50, 255])),
filtered: PmremAtlas {
width: 336,
height: 64,
rgba16: [0x2800u16, 0x2800, 0x2800, 0x3c00]
.into_iter()
.flat_map(u16::to_le_bytes)
.cycle()
.take(336 * 64 * 8)
.collect(),
},
}
}
fn read_pixels(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
) -> Result<Vec<u8>, Box<dyn Error>> {
let stride = (texture.width() * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
* wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("offscreen image readback"),
size: u64::from(stride) * u64::from(texture.height()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(stride),
rows_per_image: Some(texture.height()),
},
},
texture.size(),
);
queue.submit([encoder.finish()]);
let (send, receive) = std::sync::mpsc::channel();
buffer
.slice(..)
.map_async(wgpu::MapMode::Read, move |result| {
let _ = send.send(result);
});
device.poll(wgpu::PollType::wait_indefinitely())?;
receive.recv()??;
let mapped = buffer.slice(..).get_mapped_range().unwrap();
Ok(mapped
.chunks_exact(stride as usize)
.flat_map(|row| row[..texture.width() as usize * 4].iter().copied())
.collect())
}
async fn run(options: Options) -> Result<(), Box<dyn Error>> {
let adapter = wgpu::Instance::default()
.request_adapter(&Default::default())
.await?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
required_features: (adapter.features()
& (wgpu::Features::SHADER_F16 | wgpu::Features::TEXTURE_COMPRESSION_BC))
| sgl_3d::graphics_device::features(&adapter),
required_limits: sgl_3d::graphics_device::limits(&adapter),
..Default::default()
})
.await?;
println!(
"GPU: {} ({:?})",
adapter.get_info().name,
adapter.get_info().backend
);
let world = Asset {
meshes: vec![
cuboid(Vec3::new(0., -0.25, 0.), Vec3::new(10., 0.4, 8.), 0),
cuboid(Vec3::new(-2.4, 1.1, 0.), Vec3::new(0.18, 2.2, 0.18), 1),
],
materials: vec![
material([0.12, 0.16, 0.2, 1.], [0.; 3], 0.1, 0.4),
material(
[0.02, 0.03, 0.04, 1.],
[0.1, 0.55, 1.].map(|x| x * options.emission),
0.,
0.5,
),
],
images: Vec::new(),
rig: Default::default(),
};
let mut cube = Asset {
meshes: vec![cuboid(Vec3::ZERO, Vec3::splat(1.6), 0)],
materials: vec![material([0.7, 0.18, 0.05, 1.], [0.; 3], 0.25, 0.27)],
images: Vec::new(),
rig: Default::default(),
};
cube.materials[0].anisotropy_strength = options.anisotropy;
cube.materials[0].anisotropy_rotation = std::f32::consts::FRAC_PI_4;
let size = [320, 240];
let mut scene = Scene::new(&device, &queue);
let world = scene.add_asset(&device, &queue, world)?.model;
scene.add_instance(&device, &queue, InstanceState::new(world), Mobility::Static)?;
let cube = scene.add_asset(&device, &queue, cube)?.model;
let mut moving = InstanceState::new(cube);
let instance = scene.add_instance(&device, &queue, moving, Mobility::Moving)?;
if options.alpha {
let alpha = scene.add_asset(&device, &queue, alpha_content()?)?.model;
scene.add_instance(&device, &queue, InstanceState::new(alpha), Mobility::Static)?;
}
if options.fog {
scene.update_fog_volumes(
&device,
&queue,
&[FogVolume {
center: Vec3::new(0., 1.5, 0.),
size: Vec3::new(6., 3., 6.),
density: 0.15,
albedo: [0.9, 0.95, 1.],
edge_fade: 0.5,
..Default::default()
}],
)?;
}
if options.decals {
add_decals(&device, &queue, &mut scene)?;
}
let environment = scene.add_environment(&device, &queue, &neutral_environment())?;
scene.add_light(
&device,
&queue,
Light {
position: Vec3::new(-2.1, 1.6, 0.3),
shape: LightShape::Point {
radius: LightShape::DEFAULT_RADIUS,
},
color: [0.1, 0.55, 1.],
intensity: 2. * options.emission,
range: 8.,
baked: false,
specular: 1.,
casts_shadow: true,
..Default::default()
},
)?;
scene.add_light(
&device,
&queue,
Light {
position: Vec3::new(1.8, 3.5, 1.5),
shape: LightShape::Spot {
direction: Vec3::NEG_Y,
inner_angle: 0.35,
outer_angle: 0.6,
radius: LightShape::DEFAULT_RADIUS,
},
color: [1., 0.8, 0.6],
intensity: 40.,
range: 6.,
baked: false,
specular: 1.,
casts_shadow: true,
..Default::default()
},
)?;
scene.add_light(
&device,
&queue,
Light {
position: Vec3::new(0., 2.2, -2.),
shape: LightShape::Rect {
direction: Vec3::new(0., -0.6, 1.),
width_axis: Vec3::X,
width: 2.4,
height: 0.3,
},
color: [0.7, 0.9, 1.],
intensity: 12.,
range: 7.,
baked: false,
specular: 1.,
casts_shadow: false,
..Default::default()
},
)?;
let output = device.create_texture(&wgpu::TextureDescriptor {
label: Some("offscreen output"),
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let output_view = output.create_view(&Default::default());
let settings = Settings {
preset: RenderPreset::Low,
atmosphere: options.fog,
motion_blur: if options.motion_blur {
MotionBlur::Full
} else {
MotionBlur::Off
},
..Settings::default()
};
let mut renderer = Renderer::new(&device, &queue, output.format(), size, 1., &settings)?;
let eye = Vec3::new(6., 4., 7.);
let view = camera::rh::view::look_at_mat4(eye, Vec3::new(0., 0.7, 0.), Vec3::Y);
let projection = sgl_3d::perspective(50f32.to_radians(), size[0] as f32 / size[1] as f32, 0.1);
let mut frame = FrameInput::new(Camera {
view,
projection,
eye,
});
frame.environment = Some(environment);
frame.directional_lights[0] = Some(DirectionalLight {
direction: Vec3::new(0.4, -1., -0.5),
color: [1., 0.85, 0.7],
illuminance: options.light,
shadow: Some(DirectionalShadow {
distance: 20.,
cascades: 2,
}),
..Default::default()
});
frame.atmosphere = true;
frame.fog = Fog {
density: 0.04,
anisotropy: 0.5,
height: 2.,
height_falloff: 0.5,
length: 40.,
..Fog::default()
};
frame.hemisphere_light = HemisphereLight {
sky_color: [0.2, 0.3, 0.5],
ground_color: [0.05, 0.03, 0.02],
intensity: 0.2,
};
frame.exposure.automatic = Some(AutoExposure {
compensation: CompensationCurve::new(&[[0., -2.5]])?,
correction_min: -2.,
correction_max: 2.,
..Default::default()
});
let mut first = Vec::new();
for frame_index in 0..options.frames {
let phase = frame_index as f32 / options.frames.max(2) as f32;
moving.pose = Mat4::from_translation(Vec3::new(-0.5 + phase, 0.85, 0.))
* Mat4::from_rotation_y(phase);
scene.set_instance(&queue, instance, moving)?;
frame.elapsed_seconds = frame_index as f64 / 60.;
frame.camera_cut = frame_index == 0;
renderer.resize(&device, size, 1., &settings);
let mut encoder = device.create_command_encoder(&Default::default());
renderer.render(
&device,
&queue,
&mut encoder,
&mut scene,
&frame,
&settings,
&output_view,
None,
);
queue.submit([encoder.finish()]);
renderer.finish_frame(&mut scene);
if frame_index == 0 {
first = read_pixels(&device, &queue, &output)?;
}
}
let pixels = read_pixels(&device, &queue, &output)?;
let changed = pixels
.chunks_exact(4)
.zip(first.chunks_exact(4))
.filter(|(last, first)| last[..3] != first[..3])
.count();
let mean = pixels
.chunks_exact(4)
.map(|p| 0.2126 * f64::from(p[0]) + 0.7152 * f64::from(p[1]) + 0.0722 * f64::from(p[2]))
.sum::<f64>()
/ f64::from(size[0] * size[1]);
if let Some(parent) = options
.output
.parent()
.filter(|p| !p.as_os_str().is_empty())
{
std::fs::create_dir_all(parent)?;
}
image::save_buffer(
&options.output,
&pixels,
size[0],
size[1],
image::ColorType::Rgba8,
)?;
println!(
"Rendered {} frames, {}x{}, light={}, emission={}; mean encoded luma={mean:.3}/255, first/final changed pixels={changed}; {}",
options.frames,
size[0],
size[1],
options.light,
options.emission,
options.output.display()
);
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
pollster::block_on(run(Options::parse()?))
}