feat: render programmable 3d scenes cameras and picking

This commit is contained in:
2026-11-10 23:19:26 +08:00
parent 040b779f5f
commit ad2c01bc29
33 changed files with 2463 additions and 42 deletions
+7
View File
@@ -31,6 +31,10 @@ impl Color {
#[derive(Clone, Debug)]
pub enum DrawCommand {
Scene3D {
rect: Rect,
view: std::sync::Arc<crate::scene3d::View>,
},
Clear(Color),
PushClip(Rect),
PopClip,
@@ -63,6 +67,7 @@ impl DrawCommand {
pub fn translated(mut self, delta: Point) -> Self {
match &mut self {
Self::WrappedText { rect, .. }
| Self::Scene3D { rect, .. }
| Self::PushClip(rect)
| Self::FillRoundedRect { rect, .. }
| Self::StrokeRoundedRect { rect, .. } => {
@@ -93,6 +98,7 @@ impl DisplayList {
Some(rect)
}
DrawCommand::PushClip(rect) => Some(rect),
DrawCommand::Scene3D { rect, .. } => Some(rect),
DrawCommand::FillRoundedRect { rect, radius, .. } => {
*radius *= scale;
Some(rect)
@@ -131,6 +137,7 @@ impl DisplayList {
for command in &mut self.commands {
match command {
DrawCommand::WrappedText { rect, .. }
| DrawCommand::Scene3D { rect, .. }
| DrawCommand::PushClip(rect)
| DrawCommand::FillRoundedRect { rect, .. }
| DrawCommand::StrokeRoundedRect { rect, .. } => {
+15 -1
View File
@@ -432,7 +432,9 @@ fn shape(node: &UiNode, children: Vec<Size>, constraints: [f32; 4]) -> Result<Sh
size.height + padding.vertical(),
)
}
UiKind::CanvasViewport { width, height, .. } => Shape::Rect(*width, *height),
UiKind::CanvasViewport { width, height, .. } | UiKind::Viewport3D { width, height, .. } => {
Shape::Rect(*width, *height)
}
UiKind::Canvas { positions, .. } | UiKind::Scene2D { positions, .. } => {
let mut size = Size::default();
for (position, child) in positions.iter().zip(children) {
@@ -490,6 +492,13 @@ pub fn paint_native(node: &UiNode, x: f32, y: f32, size: Size) -> Option<RenderC
let size_for_text = size;
let inset = insets(node);
match &node.kind {
UiKind::Viewport3D { view, .. } => Some(RenderCommand::Scene3D {
x: x + inset.left,
y: y + inset.top,
width: (size.width - inset.horizontal()).max(0.),
height: (size.height - inset.vertical()).max(0.),
view: view.clone(),
}),
UiKind::Text { value, size, color } => Some(RenderCommand::Text {
x: x + inset.left,
y: y + inset.top,
@@ -1009,6 +1018,11 @@ impl LayoutRuntime {
coordinate(y + size.height)?;
mounts.push(MountGeometry {
canvas_viewport: matches!(item.node.kind, UiKind::CanvasViewport { .. }),
scene3d_viewport: matches!(item.node.kind, UiKind::Viewport3D { .. }),
camera_controls: matches!(
item.node.kind,
UiKind::CanvasViewport { .. } | UiKind::Viewport3D { controls: true, .. }
),
viewport_clip: None,
view: None,
id: item.id,
+1
View File
@@ -6,6 +6,7 @@ pub(crate) mod layout;
pub(crate) mod native_visual;
pub(crate) mod page;
pub(crate) mod scene;
pub(crate) mod scene3d;
pub(crate) mod scroll;
pub(crate) mod software_renderer;
pub(crate) mod source_hit;
+17
View File
@@ -275,6 +275,23 @@ impl NativeCallable for Method {
let mut commands = Vec::new();
for command in layout::paint_commands(&node, x, y, Size { width, height }) {
let fields = match command {
RenderCommand::Scene3D {
x,
y,
width,
height,
view,
} => {
let snapshot = cx.allocate(crate::scene3d::PaintView(view))?;
vec![
("kind", Value::Text("scene3d".into())),
("x", value(x)),
("y", value(y)),
("width", value(width)),
("height", value(height)),
("scene", Value::Object(snapshot)),
]
}
RenderCommand::Text {
x,
y,
+456
View File
@@ -0,0 +1,456 @@
//! Software 3D surfaces share the application's existing CPU compositor. Mesh
//! visibility and picking use the same camera and transformed world triangles.
pub mod math;
use math::{Camera, Matrix, Projection, Vec3};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
pub const MAX_TRIANGLES: usize = 65_536;
pub const MAX_VERTICES: usize = 32_768;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Geometry {
pub vertices: Vec<Vec3>,
pub triangles: Vec<[u32; 3]>,
}
impl Geometry {
pub fn valid(&self) -> bool {
self.vertices.len() <= MAX_VERTICES
&& self.triangles.len() <= MAX_TRIANGLES
&& self.vertices.iter().all(|point| point.valid())
&& self
.triangles
.iter()
.flatten()
.all(|&index| (index as usize) < self.vertices.len())
}
pub fn cuboid(width: f32, height: f32, depth: f32) -> Self {
let (x, y, z) = (width / 2., height / 2., depth / 2.);
Self {
vertices: vec![
Vec3::new(-x, -y, -z),
Vec3::new(x, -y, -z),
Vec3::new(x, y, -z),
Vec3::new(-x, y, -z),
Vec3::new(-x, -y, z),
Vec3::new(x, -y, z),
Vec3::new(x, y, z),
Vec3::new(-x, y, z),
],
triangles: vec![
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mesh {
pub identity: String,
pub geometry: Arc<Geometry>,
pub world: Matrix,
pub color: [f32; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Light {
pub direction: Vec3,
pub color: [f32; 3],
pub intensity: f32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Scene {
pub meshes: Vec<Mesh>,
pub lights: Vec<Light>,
pub ambient: f32,
pub background: [f32; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct View {
pub scene: Arc<Scene>,
pub camera: Camera,
}
#[derive(Debug)]
pub struct PaintView(pub Arc<View>);
impl endor_core::ObjectPayload for PaintView {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn kind_name(&self) -> &'static str {
"immutable-3d-paint"
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Hit {
pub identity: String,
pub point: Vec3,
pub normal: Vec3,
pub distance: f32,
pub triangle: usize,
pub barycentric: [f32; 3],
}
impl View {
pub fn valid(&self) -> bool {
let color_valid = |color: [f32; 3]| {
color
.iter()
.all(|value| value.is_finite() && (0.0..=1.0).contains(value))
};
self.camera.valid()
&& self.scene.ambient.is_finite()
&& (0.0..=1.0).contains(&self.scene.ambient)
&& color_valid(self.scene.background)
&& self.scene.meshes.len() <= 4096
&& self.scene.lights.len() <= 32
&& self.scene.meshes.iter().all(|mesh| {
mesh.geometry.valid()
&& mesh.world.0.iter().all(|v| v.is_finite())
&& color_valid(mesh.color)
&& mesh
.geometry
.vertices
.iter()
.all(|point| mesh.world.point(*point).valid())
})
&& self.scene.lights.iter().all(|light| {
color_valid(light.color)
&& light.direction.valid()
&& (light.direction.length() - 1.).abs() < 0.0001
&& light.intensity.is_finite()
&& (0.0..=32.0).contains(&light.intensity)
})
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.vertices.len())
.sum::<usize>()
<= 262_144
&& self
.scene
.meshes
.iter()
.map(|mesh| mesh.geometry.triangles.len())
.sum::<usize>()
<= MAX_TRIANGLES
}
pub fn pick(&self, u: f32, v: f32, aspect: f32) -> Option<Hit> {
if !self.camera.valid()
|| !(0.0..=1.0).contains(&u)
|| !(0.0..=1.0).contains(&v)
|| !aspect.is_finite()
|| aspect <= 0.
{
return None;
}
let ray = self.camera.ray(u, v, aspect)?;
let basis = self.camera.basis()?;
let mut hit: Option<Hit> = None;
for mesh in &self.scene.meshes {
for (triangle, indices) in mesh.geometry.triangles.iter().enumerate() {
let [a, b, c] =
indices.map(|i| mesh.world.point(mesh.geometry.vertices[i as usize]));
let Some((distance, barycentric)) = ray.triangle(a, b, c) else {
continue;
};
let point = ray.origin + ray.direction * distance;
let depth = self.camera.view(basis, point).z;
if depth < self.camera.near
|| depth > self.camera.far
|| hit.as_ref().is_some_and(|hit| hit.distance <= distance)
{
continue;
}
let Some(normal) = (b - a).cross(c - a).normalized() else {
continue;
};
hit = Some(Hit {
identity: mesh.identity.clone(),
point,
normal,
distance,
triangle,
barycentric,
});
}
}
hit
}
}
fn channel(value: f32) -> u32 {
(value.clamp(0., 1.) * 255.).round() as u32
}
pub fn rgb(color: [f32; 3]) -> u32 {
channel(color[0]) << 16 | channel(color[1]) << 8 | channel(color[2])
}
struct CachedSurface {
view: Arc<View>,
width: u32,
height: u32,
pixels: Arc<[u32]>,
}
#[derive(Default)]
struct SurfaceCache {
entries: std::collections::VecDeque<CachedSurface>,
pixels: usize,
}
pub fn surface(view: &Arc<View>, width: u32, height: u32) -> Result<Arc<[u32]>, &'static str> {
static CACHE: std::sync::OnceLock<std::sync::Mutex<SurfaceCache>> = std::sync::OnceLock::new();
let cache = CACHE.get_or_init(Default::default);
{
let cache = cache.lock().map_err(|_| "3D surface cache poisoned")?;
if let Some(entry) = cache.entries.iter().find(|entry| {
Arc::ptr_eq(&entry.view, view) && entry.width == width && entry.height == height
}) {
return Ok(entry.pixels.clone());
}
}
// Do not hold a cache lock across rendering: world UI can contain another
// 3D viewport and recurse through the compositor.
let pixels: Arc<[u32]> = render(view, width, height)?.into();
let mut cache = cache.lock().map_err(|_| "3D surface cache poisoned")?;
while cache.entries.len() >= 8 || cache.pixels + pixels.len() > 8_388_608 {
let Some(entry) = cache.entries.pop_front() else {
break;
};
cache.pixels -= entry.pixels.len();
}
cache.pixels += pixels.len();
cache.entries.push_back(CachedSurface {
view: view.clone(),
width,
height,
pixels: pixels.clone(),
});
Ok(pixels)
}
/// Homogeneous frustum planes expressed in view space. Clipping before division
/// handles triangles crossing the near plane without huge screen coordinates.
fn clip(mut polygon: Vec<Vec3>, camera: Camera, aspect: f32) -> Vec<Vec3> {
let (x, y, slope) = match camera.projection {
Projection::Perspective { fov } => {
let y = (fov.to_radians() / 2.).tan();
(y * aspect, y, 1.)
}
Projection::Orthographic { height } => (height * aspect / 2., height / 2., 0.),
};
let planes = [
[0., 0., 1., -camera.near],
[0., 0., -1., camera.far],
[1., 0., x * slope, x * (1. - slope)],
[-1., 0., x * slope, x * (1. - slope)],
[0., 1., y * slope, y * (1. - slope)],
[0., -1., y * slope, y * (1. - slope)],
];
for [a, b, c, d] in planes {
if polygon.is_empty() {
break;
}
let distance = |p: Vec3| a * p.x + b * p.y + c * p.z + d;
let mut output = Vec::new();
let mut previous = *polygon.last().unwrap();
let mut before = distance(previous);
for current in polygon {
let after = distance(current);
if (before >= 0.) != (after >= 0.) {
output.push(previous + (current - previous) * (before / (before - after)));
}
if after >= 0. {
output.push(current);
}
previous = current;
before = after;
}
polygon = output;
}
polygon
}
pub fn render(view: &View, width: u32, height: u32) -> Result<Vec<u32>, &'static str> {
let area = width as usize * height as usize;
// Offscreen targets have a hard per-surface resource bound.
if area > 4_194_304 || width == 0 || height == 0 || !view.valid() {
return Err("invalid 3D surface or resource budget exceeded");
}
let mut pixels = vec![rgb(view.scene.background); area];
let mut depths = vec![f32::INFINITY; area];
let camera = view.camera;
let basis = camera.basis().unwrap();
let aspect = width as f32 / height as f32;
let perspective = matches!(camera.projection, Projection::Perspective { .. });
let project = |point: Vec3| {
let half = match camera.projection {
Projection::Perspective { fov } => point.z * (fov.to_radians() / 2.).tan(),
Projection::Orthographic { height } => height / 2.,
};
Vec3::new(
(point.x / (half * aspect) + 1.) * width as f32 / 2.,
(1. - point.y / half) * height as f32 / 2.,
point.z,
)
};
let mut work = 0usize;
for mesh in &view.scene.meshes {
for indices in &mesh.geometry.triangles {
let [a, b, c] = indices.map(|i| mesh.world.point(mesh.geometry.vertices[i as usize]));
let Some(normal) = (b - a).cross(c - a).normalized() else {
continue;
};
let mut light = [view.scene.ambient; 3];
for source in &view.scene.lights {
let intensity = normal.dot(source.direction * -1.).max(0.) * source.intensity;
for (channel, color) in light.iter_mut().zip(source.color) {
*channel += intensity * color;
}
}
let color = rgb(std::array::from_fn(|i| mesh.color[i] * light[i]));
let polygon = clip(
vec![
camera.view(basis, a),
camera.view(basis, b),
camera.view(basis, c),
],
camera,
aspect,
);
if polygon.len() < 3 {
continue;
}
for index in 1..polygon.len() - 1 {
let [a, b, c] = [polygon[0], polygon[index], polygon[index + 1]].map(project);
let min_x = a.x.min(b.x).min(c.x).floor().max(0.) as u32;
let max_x = a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32;
let min_y = a.y.min(b.y).min(c.y).floor().max(0.) as u32;
let max_y = a.y.max(b.y).max(c.y).ceil().min(height as f32) as u32;
work += max_x.saturating_sub(min_x) as usize * max_y.saturating_sub(min_y) as usize;
if work > 32_000_000 {
return Err("3D raster work budget exceeded");
}
let edge = |a: Vec3, b: Vec3, x: f32, y: f32| {
(x - a.x) * (b.y - a.y) - (y - a.y) * (b.x - a.x)
};
let area = edge(a, b, c.x, c.y);
if area.abs() < 1e-6 {
continue;
}
for y in min_y..max_y {
for x in min_x..max_x {
let px = x as f32 + 0.5;
let py = y as f32 + 0.5;
let weights = [
edge(b, c, px, py) / area,
edge(c, a, px, py) / area,
edge(a, b, px, py) / area,
];
if weights.iter().any(|weight| *weight < -1e-5) {
continue;
}
let depth = if perspective {
1. / (weights[0] / a.z + weights[1] / b.z + weights[2] / c.z)
} else {
weights[0] * a.z + weights[1] * b.z + weights[2] * c.z
};
let index = y as usize * width as usize + x as usize;
if depth < depths[index] {
depths[index] = depth;
pixels[index] = color;
}
}
}
}
}
}
Ok(pixels)
}
#[cfg(test)]
mod tests {
use super::*;
fn view(geometry: Geometry) -> View {
View {
camera: Camera::default(),
scene: Arc::new(Scene {
meshes: vec![Mesh {
identity: "mesh".into(),
geometry: Arc::new(geometry),
world: Matrix::default(),
color: [1., 0., 0.],
}],
lights: vec![],
ambient: 1.,
background: [1., 1., 1.],
}),
}
}
#[test]
fn triangles_crossing_near_plane_are_clipped_and_pick_uses_the_same_range() {
let mut view = view(Geometry {
vertices: vec![
Vec3::new(-1., -1., 0.5),
Vec3::new(1., -1., 2.),
Vec3::new(0., 1., 2.),
],
triangles: vec![[0, 1, 2]],
});
view.camera.position = Vec3::default();
view.camera.target = Vec3::new(0., 0., 1.);
view.camera.near = 1.;
view.camera.far = 10.;
view.camera.projection = Projection::Perspective { fov: 90. };
let pixels = render(&view, 64, 64).unwrap();
assert!(pixels.contains(&0xFF0000));
let hit = view.pick(0.5, 0.5, 1.).unwrap();
assert!(hit.point.z >= view.camera.near && hit.point.z <= view.camera.far);
view.camera.far = 1.1;
assert!(view.pick(0.5, 0.5, 1.).is_none());
}
#[test]
fn group_transform_order_and_orthographic_rays_are_consistent() {
let local = Matrix::trs(
Vec3::new(1., 0., 0.),
Vec3::new(0., 90., 0.),
Vec3::new(1., 1., 1.),
);
let parent = Matrix::trs(
Vec3::new(10., 0., 0.),
Vec3::default(),
Vec3::new(1., 1., 1.),
);
let transformed = parent.compose(local).point(Vec3::new(0., 0., 1.));
assert!((transformed.x - 12.).abs() < 1e-5 && transformed.z.abs() < 1e-5);
let camera = Camera {
projection: Projection::Orthographic { height: 4. },
..Camera::default()
};
let left = camera.ray(0.25, 0.5, 1.).unwrap();
let right = camera.ray(0.75, 0.5, 1.).unwrap();
assert_eq!(left.direction, right.direction);
assert_eq!(right.origin.x - left.origin.x, 2.);
}
#[test]
fn surface_cache_reuses_immutable_frames_and_rejects_invalid_resources() {
let view = Arc::new(view(Geometry::cuboid(1., 1., 1.)));
let first = surface(&view, 64, 64).unwrap();
let second = surface(&view, 64, 64).unwrap();
assert!(Arc::ptr_eq(&first, &second));
assert!(render(&view, 4000, 4000).is_err());
let mut invalid = (*view).clone();
invalid.camera.target = invalid.camera.position;
assert!(!invalid.valid());
assert!(render(&invalid, 64, 64).is_err());
}
}
+222
View File
@@ -0,0 +1,222 @@
use serde::{Deserialize, Serialize};
use std::ops::{Add, Mul, Sub};
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Vec3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
impl Vec3 {
pub const fn new(x: f32, y: f32, z: f32) -> Self {
Self { x, y, z }
}
pub fn dot(self, b: Self) -> f32 {
self.x * b.x + self.y * b.y + self.z * b.z
}
pub fn cross(self, b: Self) -> Self {
Self::new(
self.y * b.z - self.z * b.y,
self.z * b.x - self.x * b.z,
self.x * b.y - self.y * b.x,
)
}
pub fn length(self) -> f32 {
self.dot(self).sqrt()
}
pub fn normalized(self) -> Option<Self> {
let length = self.length();
(length.is_finite() && length > 1e-6).then(|| self * (1.0 / length))
}
pub fn valid(self) -> bool {
[self.x, self.y, self.z]
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
}
}
impl Add for Vec3 {
type Output = Self;
fn add(self, b: Self) -> Self {
Self::new(self.x + b.x, self.y + b.y, self.z + b.z)
}
}
impl Sub for Vec3 {
type Output = Self;
fn sub(self, b: Self) -> Self {
Self::new(self.x - b.x, self.y - b.y, self.z - b.z)
}
}
impl Mul<f32> for Vec3 {
type Output = Self;
fn mul(self, b: f32) -> Self {
Self::new(self.x * b, self.y * b, self.z * b)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Matrix(pub [f32; 16]);
impl Default for Matrix {
fn default() -> Self {
Self([
1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
])
}
}
impl Matrix {
pub fn compose(self, local: Self) -> Self {
let mut out = [0.; 16];
for row in 0..4 {
for col in 0..4 {
out[row * 4 + col] = (0..4)
.map(|k| self.0[row * 4 + k] * local.0[k * 4 + col])
.sum();
}
}
Self(out)
}
pub fn point(self, p: Vec3) -> Vec3 {
Vec3::new(
self.0[0] * p.x + self.0[1] * p.y + self.0[2] * p.z + self.0[3],
self.0[4] * p.x + self.0[5] * p.y + self.0[6] * p.z + self.0[7],
self.0[8] * p.x + self.0[9] * p.y + self.0[10] * p.z + self.0[11],
)
}
pub fn trs(position: Vec3, rotation: Vec3, scale: Vec3) -> Self {
let (sx, cx) = rotation.x.to_radians().sin_cos();
let (sy, cy) = rotation.y.to_radians().sin_cos();
let (sz, cz) = rotation.z.to_radians().sin_cos();
// Local X, then Y, then Z rotation; scale first, translation last.
Self([
cz * cy * scale.x,
(cz * sy * sx - sz * cx) * scale.y,
(cz * sy * cx + sz * sx) * scale.z,
position.x,
sz * cy * scale.x,
(sz * sy * sx + cz * cx) * scale.y,
(sz * sy * cx - cz * sx) * scale.z,
position.y,
-sy * scale.x,
cy * sx * scale.y,
cy * cx * scale.z,
position.z,
0.,
0.,
0.,
1.,
])
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Projection {
Perspective { fov: f32 },
Orthographic { height: f32 },
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Camera {
pub position: Vec3,
pub target: Vec3,
pub up: Vec3,
pub near: f32,
pub far: f32,
pub projection: Projection,
}
impl Default for Camera {
fn default() -> Self {
Self {
position: Vec3::new(0., 0., 5.),
target: Vec3::default(),
up: Vec3::new(0., 1., 0.),
near: 0.1,
far: 1000.,
projection: Projection::Perspective { fov: 50. },
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Basis {
pub right: Vec3,
pub up: Vec3,
pub forward: Vec3,
}
impl Camera {
pub fn basis(self) -> Option<Basis> {
let forward = (self.target - self.position).normalized()?;
let right = forward.cross(self.up).normalized()?;
let up = right.cross(forward).normalized()?;
Some(Basis { right, up, forward })
}
pub fn valid(self) -> bool {
self.position.valid()
&& self.target.valid()
&& self.up.valid()
&& self.basis().is_some()
&& self.near.is_finite()
&& self.far.is_finite()
&& self.near > 0.
&& self.far > self.near
&& self.far <= 1_000_000.
&& match self.projection {
Projection::Perspective { fov } => fov.is_finite() && (1.0..=175.0).contains(&fov),
Projection::Orthographic { height } => {
height.is_finite() && height > 0. && height <= 1_000_000.
}
}
}
pub fn view(self, basis: Basis, p: Vec3) -> Vec3 {
let p = p - self.position;
Vec3::new(p.dot(basis.right), p.dot(basis.up), p.dot(basis.forward))
}
pub fn ray(self, u: f32, v: f32, aspect: f32) -> Option<Ray> {
let basis = self.basis()?;
let (x, y) = (u * 2. - 1., 1. - v * 2.);
match self.projection {
Projection::Perspective { fov } => {
let half = (fov.to_radians() / 2.).tan();
Some(Ray {
origin: self.position,
direction: (basis.forward
+ basis.right * (x * half * aspect)
+ basis.up * (y * half))
.normalized()?,
})
}
Projection::Orthographic { height } => Some(Ray {
origin: self.position
+ basis.right * (x * height * aspect / 2.)
+ basis.up * (y * height / 2.),
direction: basis.forward,
}),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Ray {
pub origin: Vec3,
pub direction: Vec3,
}
impl Ray {
pub fn triangle(self, a: Vec3, b: Vec3, c: Vec3) -> Option<(f32, [f32; 3])> {
let ab = b - a;
let ac = c - a;
let p = self.direction.cross(ac);
let determinant = ab.dot(p);
if determinant.abs() < 1e-7 {
return None;
}
let inverse = 1.0 / determinant;
let t = self.origin - a;
let u = t.dot(p) * inverse;
if !(0.0..=1.0).contains(&u) {
return None;
}
let q = t.cross(ab);
let v = self.direction.dot(q) * inverse;
if v < 0. || u + v > 1. {
return None;
}
let distance = ac.dot(q) * inverse;
(distance >= 0.).then_some((distance, [1. - u - v, u, v]))
}
}
+44 -5
View File
@@ -7,7 +7,12 @@ use crate::{
pub struct SoftwareRenderer;
impl SoftwareRenderer {
pub fn render(list: &DisplayList, target: &mut [u32], width: u32, height: u32) {
pub fn render(
list: &DisplayList,
target: &mut [u32],
width: u32,
height: u32,
) -> Result<(), &'static str> {
let mut canvas = Canvas {
pixels: target,
width,
@@ -18,6 +23,39 @@ impl SoftwareRenderer {
for command in list.commands() {
match command {
DrawCommand::Scene3D { rect, view } => {
let left = rect.x.max(canvas.clip.x).max(0.).floor() as u32;
let top = rect.y.max(canvas.clip.y).max(0.).floor() as u32;
let right = (rect.x + rect.width)
.min(canvas.clip.x + canvas.clip.width)
.min(width as f32)
.ceil()
.max(0.) as u32;
let bottom = (rect.y + rect.height)
.min(canvas.clip.y + canvas.clip.height)
.min(height as f32)
.ceil()
.max(0.) as u32;
if left >= right || top >= bottom || rect.width <= 0. || rect.height <= 0. {
continue;
}
let lod = (2048. / rect.width.max(rect.height)).min(1.);
let w = (rect.width * lod).ceil().max(1.) as u32;
let h = (rect.height * lod).ceil().max(1.) as u32;
let surface = crate::scene3d::surface(view, w, h)?;
for y in top..bottom {
for x in left..right {
let u = (((x as f32 + 0.5 - rect.x) / rect.width) * w as f32)
.clamp(0., (w - 1) as f32)
as u32;
let v = (((y as f32 + 0.5 - rect.y) / rect.height) * h as f32)
.clamp(0., (h - 1) as f32)
as u32;
canvas.pixels[y as usize * width as usize + x as usize] =
surface[v as usize * w as usize + u as usize];
}
}
}
DrawCommand::PushClip(rect) => {
clips.push(canvas.clip);
let x = canvas.clip.x.max(rect.x);
@@ -66,6 +104,7 @@ impl SoftwareRenderer {
} => canvas.draw_text(*origin, value, *style, *color),
}
}
Ok(())
}
}
@@ -245,7 +284,7 @@ mod tests {
color: Color::rgb(0, 0, 255),
});
let mut pixels = vec![0; 80 * 60];
SoftwareRenderer::render(&list, &mut pixels, 80, 60);
SoftwareRenderer::render(&list, &mut pixels, 80, 60).unwrap();
let mut second_line = false;
for y in 0..60 {
for x in 0..80 {
@@ -270,7 +309,7 @@ mod tests {
color: Color::rgb(255, 0, 0),
});
let mut pixels = vec![0; 16];
SoftwareRenderer::render(&list, &mut pixels, 4, 4);
SoftwareRenderer::render(&list, &mut pixels, 4, 4).unwrap();
assert_eq!(pixels[5], 0x00ff0000);
assert_eq!(pixels[0], 0);
}
@@ -286,7 +325,7 @@ mod tests {
color: Color::rgba(255, 255, 255, 128),
});
let mut pixels = vec![0; 256 * 48];
SoftwareRenderer::render(&list, &mut pixels, 256, 48);
SoftwareRenderer::render(&list, &mut pixels, 256, 48).unwrap();
assert!(pixels.iter().any(|pixel| *pixel > 0));
assert!(pixels.iter().all(|pixel| (pixel & 255) <= 128));
assert!(pixels.iter().any(|pixel| (1..128).contains(&(pixel & 255))));
@@ -299,7 +338,7 @@ mod tests {
color: Color::rgba(255, 255, 255, 0),
});
let mut pixels = vec![0; 256 * 48];
SoftwareRenderer::render(&invisible, &mut pixels, 256, 48);
SoftwareRenderer::render(&invisible, &mut pixels, 256, 48).unwrap();
assert!(pixels.iter().all(|pixel| *pixel == 0));
}
}
+18 -1
View File
@@ -68,9 +68,26 @@ fn decode(
}
let x = number(store, command, "x")?;
let y = number(store, command, "y")?;
let color = text(store, command, "color")?;
let kind = text(store, command, "kind")?;
let color = if kind == "scene3d" {
String::new()
} else {
text(store, command, "color")?
};
let result = match kind.as_str() {
"scene3d" => {
let snapshot = object(store.get_attr(command, "scene")?)?;
RenderCommand::Scene3D {
x,
y,
width: number(store, command, "width")?,
height: number(store, command, "height")?,
view: store
.payload::<crate::scene3d::PaintView>(snapshot, "immutable 3D paint snapshot")?
.0
.clone(),
}
}
"roundedRect" | "strokeRoundedRect" => {
let width = number(store, command, "width")?;
let height = number(store, command, "height")?;
+8 -1
View File
@@ -232,6 +232,13 @@ pub fn project(
(mount.width - inset.horizontal()).max(0.0),
(mount.height - inset.vertical()).max(0.0),
))
} else if matches!(node.kind, UiKind::Viewport3D { .. }) {
Some(Rect::new(
mount.x + inset.left,
mount.y + inset.top,
(mount.width - inset.horizontal()).max(0.),
(mount.height - inset.vertical()).max(0.),
))
} else if node.clip_children {
let border = node.border;
Some(Rect::new(
@@ -249,7 +256,7 @@ pub fn project(
let rect = view.rect(rect);
let rect = [rect.x, rect.y, rect.width, rect.height];
child_clip = Some(clip.map_or(rect, |clip| intersect(clip, rect)));
if mount.canvas_viewport {
if mount.canvas_viewport || mount.scene3d_viewport {
mount.viewport_clip = child_clip;
}
}