use std::{
error::Error,
fmt,
mem::size_of,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
use crate::{
Color, Interpolate, LogicalPixels, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2,
WorldLength,
};
pub(crate) const CIRCLE_SEGMENTS: usize = 64;
pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
pub(crate) const CORNER_SEGMENTS: usize = 12;
pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
const MAX_DASH_ELEMENTS: usize = 8;
const MAX_MITER_LIMIT: f32 = 1_000.0;
const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScenePrimitive {
Circle,
Rect,
Line,
Polyline,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SceneBudgetResource {
Commands,
Points,
TessellatedVertices,
RetainedBytes,
AllocationBytes,
UploadBytes,
DrawBatches,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SceneBudget {
max_commands: usize,
max_points: usize,
max_tessellated_vertices: usize,
max_retained_bytes: usize,
max_allocation_bytes: usize,
max_upload_bytes: usize,
max_draw_batches: usize,
}
impl SceneBudget {
pub const fn new(
max_commands: usize,
max_points: usize,
max_tessellated_vertices: usize,
max_retained_bytes: usize,
max_allocation_bytes: usize,
max_upload_bytes: usize,
max_draw_batches: usize,
) -> Self {
Self {
max_commands,
max_points,
max_tessellated_vertices,
max_retained_bytes,
max_allocation_bytes,
max_upload_bytes,
max_draw_batches,
}
}
pub const fn max_commands(self) -> usize {
self.max_commands
}
pub const fn max_points(self) -> usize {
self.max_points
}
pub const fn max_tessellated_vertices(self) -> usize {
self.max_tessellated_vertices
}
pub const fn max_retained_bytes(self) -> usize {
self.max_retained_bytes
}
pub const fn max_allocation_bytes(self) -> usize {
self.max_allocation_bytes
}
pub const fn max_upload_bytes(self) -> usize {
self.max_upload_bytes
}
pub const fn max_draw_batches(self) -> usize {
self.max_draw_batches
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SceneStatistics {
requested_commands: usize,
accepted_commands: usize,
rejected_commands: usize,
requested_by_primitive: PrimitiveCommandCounts,
accepted_by_primitive: PrimitiveCommandCounts,
rejected_by_primitive: PrimitiveCommandCounts,
retained_points: usize,
estimated_tessellated_vertices: usize,
retained_bytes: usize,
estimated_upload_bytes: usize,
estimated_draw_batches: usize,
}
impl SceneStatistics {
pub const fn requested_commands(self) -> usize {
self.requested_commands
}
pub const fn accepted_commands(self) -> usize {
self.accepted_commands
}
pub const fn rejected_commands(self) -> usize {
self.rejected_commands
}
pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
self.requested_by_primitive
}
pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
self.accepted_by_primitive
}
pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
self.rejected_by_primitive
}
pub const fn retained_points(self) -> usize {
self.retained_points
}
pub const fn estimated_tessellated_vertices(self) -> usize {
self.estimated_tessellated_vertices
}
pub const fn retained_bytes(self) -> usize {
self.retained_bytes
}
pub const fn estimated_upload_bytes(self) -> usize {
self.estimated_upload_bytes
}
pub const fn estimated_draw_batches(self) -> usize {
self.estimated_draw_batches
}
fn with_command(mut self, command: &DrawCommand) -> Self {
let vertices = command.estimated_tessellated_vertices();
self.accepted_commands = self.accepted_commands.saturating_add(1);
self.accepted_by_primitive.increment(command.primitive());
self.retained_points = self
.retained_points
.saturating_add(command.retained_point_count());
self.estimated_tessellated_vertices =
self.estimated_tessellated_vertices.saturating_add(vertices);
self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
self.estimated_upload_bytes = self
.estimated_upload_bytes
.saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PrimitiveCommandCounts {
circles: usize,
rectangles: usize,
lines: usize,
polylines: usize,
}
impl PrimitiveCommandCounts {
pub const fn circles(self) -> usize {
self.circles
}
pub const fn rectangles(self) -> usize {
self.rectangles
}
pub const fn lines(self) -> usize {
self.lines
}
pub const fn polylines(self) -> usize {
self.polylines
}
pub const fn total(self) -> usize {
self.circles
.saturating_add(self.rectangles)
.saturating_add(self.lines)
.saturating_add(self.polylines)
}
pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
match primitive {
ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
}
}
pub(crate) fn adding(mut self, other: Self) -> Self {
self.circles = self.circles.saturating_add(other.circles);
self.rectangles = self.rectangles.saturating_add(other.rectangles);
self.lines = self.lines.saturating_add(other.lines);
self.polylines = self.polylines.saturating_add(other.polylines);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SceneError {
InvalidBackground,
NonFiniteGeometry(ScenePrimitive),
InvalidDimension(ScenePrimitive),
DegenerateGeometry(ScenePrimitive),
DegenerateStrokeTurn {
primitive: ScenePrimitive,
vertex_index: usize,
},
MissingStyle(ScenePrimitive),
InvalidFill(ScenePrimitive),
InvalidStroke(ScenePrimitive),
StrokeExpansionLimitExceeded {
primitive: ScenePrimitive,
limit: usize,
required: usize,
},
UnrepresentableStrokePattern(ScenePrimitive),
InvalidShadow(ScenePrimitive),
InvalidScreenClip,
NonFiniteDepth,
BudgetExceeded {
resource: SceneBudgetResource,
limit: usize,
requested: usize,
},
AllocationFailed {
requested_bytes: usize,
},
}
impl fmt::Display for SceneError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "scene command rejected: {self:?}")
}
}
impl Error for SceneError {}
#[derive(Debug)]
pub struct Scene {
background: Color,
commands: Vec<SceneCommand>,
owned_payload_bytes: usize,
next_order: u64,
current_screen_clip: Option<ScreenClipRect>,
current_depth: f32,
budget: Option<SceneBudget>,
statistics: SceneStatistics,
}
impl Clone for Scene {
fn clone(&self) -> Self {
let commands = self.commands.clone();
let owned_payload_bytes = commands
.iter()
.map(|command| command.command.owned_allocation_bytes())
.fold(0usize, usize::saturating_add);
let mut statistics = self.statistics;
statistics.retained_bytes = commands
.len()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(owned_payload_bytes);
Self {
background: self.background,
commands,
owned_payload_bytes,
next_order: self.next_order,
current_screen_clip: self.current_screen_clip,
current_depth: self.current_depth,
budget: self.budget,
statistics,
}
}
}
impl Scene {
pub fn new(background: Color) -> Result<Self, SceneError> {
Self::create(background, None)
}
pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
Self::create(background, Some(budget))
}
fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
if !background.is_normalized() {
return Err(SceneError::InvalidBackground);
}
Ok(Self {
background,
commands: Vec::new(),
owned_payload_bytes: 0,
next_order: 0,
current_screen_clip: None,
current_depth: 0.0,
budget,
statistics: SceneStatistics::default(),
})
}
pub fn background(&self) -> Color {
self.background
}
pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
if !background.is_normalized() {
return Err(SceneError::InvalidBackground);
}
self.background = background;
Ok(())
}
pub fn clear(&mut self) {
self.commands.clear();
self.owned_payload_bytes = 0;
self.next_order = 0;
self.current_screen_clip = None;
self.current_depth = 0.0;
self.statistics = SceneStatistics::default();
}
pub fn commands(&self) -> &[SceneCommand] {
&self.commands
}
pub fn command_count(&self) -> usize {
self.commands.len()
}
pub fn allocation_bytes(&self) -> usize {
self.commands
.capacity()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(self.owned_payload_bytes)
}
pub(crate) fn preflight_command_storage(
&self,
additional_commands: usize,
additional_owned_bytes: usize,
) -> Result<(), SceneError> {
let Some(budget) = self.budget else {
return Ok(());
};
let retained_bytes = self
.statistics
.retained_bytes
.saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
.saturating_add(additional_owned_bytes);
if retained_bytes > budget.max_retained_bytes {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::RetainedBytes,
limit: budget.max_retained_bytes,
requested: retained_bytes,
});
}
let required_len = self.commands.len().saturating_add(additional_commands);
let owned_payload_bytes = self
.owned_payload_bytes
.saturating_add(additional_owned_bytes);
let capacity = if required_len <= self.commands.capacity() {
self.commands.capacity()
} else {
budgeted_command_capacity(
budget,
self.commands.capacity(),
required_len,
owned_payload_bytes,
)?
};
validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
}
pub const fn budget(&self) -> Option<SceneBudget> {
self.budget
}
pub const fn statistics(&self) -> SceneStatistics {
self.statistics
}
pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
self.current_screen_clip
}
pub fn set_screen_clip(
&mut self,
screen_clip: Option<ScreenClipRect>,
) -> Result<Option<ScreenClipRect>, SceneError> {
if screen_clip.is_some_and(|clip| !clip.is_valid()) {
return Err(SceneError::InvalidScreenClip);
}
Ok(std::mem::replace(
&mut self.current_screen_clip,
screen_clip,
))
}
pub fn with_screen_clip<R>(
&mut self,
screen_clip: ScreenClipRect,
draw: impl FnOnce(&mut Self) -> R,
) -> Result<R, SceneError> {
if !screen_clip.is_valid() {
return Err(SceneError::InvalidScreenClip);
}
let previous = self.current_screen_clip;
let combined = match previous {
Some(outer) => outer.intersection(screen_clip)?,
None => screen_clip,
};
if !combined.is_valid() {
return Err(SceneError::InvalidScreenClip);
}
self.current_screen_clip = Some(combined);
let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
self.current_screen_clip = previous;
match result {
Ok(result) => Ok(result),
Err(payload) => resume_unwind(payload),
}
}
pub fn set_depth(&mut self, depth: f32) -> bool {
self.try_set_depth(depth).is_ok()
}
pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
if !depth.is_finite() {
return Err(SceneError::NonFiniteDepth);
}
self.current_depth = depth;
Ok(())
}
pub fn with_depth<R>(
&mut self,
depth: f32,
draw: impl FnOnce(&mut Self) -> R,
) -> Result<R, SceneError> {
if !depth.is_finite() {
return Err(SceneError::NonFiniteDepth);
}
let previous = self.current_depth;
self.current_depth = depth;
let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
self.current_depth = previous;
match result {
Ok(result) => Ok(result),
Err(payload) => resume_unwind(payload),
}
}
pub fn push(&mut self, command: DrawCommand) -> bool {
self.try_push(command).is_ok()
}
pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
self.try_push_to_layer(Layer::DEFAULT, command)
}
pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
self.try_push_to_layer(layer, command).is_ok()
}
pub fn try_push_to_layer(
&mut self,
layer: Layer,
command: DrawCommand,
) -> Result<(), SceneError> {
let primitive = command.primitive();
self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
self.statistics.requested_by_primitive.increment(primitive);
let result = self.try_push_to_layer_inner(layer, command);
if result.is_err() {
self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
self.statistics.rejected_by_primitive.increment(primitive);
}
result
}
pub fn try_extend_to_layers(
&mut self,
commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
) -> Result<(), SceneError> {
let mut staged = Vec::new();
let mut requested = self.statistics;
let mut attempted = 0usize;
let mut attempted_by_primitive = PrimitiveCommandCounts::default();
let mut next_order = self.next_order;
let existing_owned_payload_bytes = self.owned_payload_bytes;
let mut staged_owned_payload_bytes = 0usize;
for (layer, command) in commands {
let primitive = command.primitive();
attempted = attempted.saturating_add(1);
attempted_by_primitive.increment(primitive);
requested.requested_commands = requested.requested_commands.saturating_add(1);
requested.requested_by_primitive.increment(primitive);
if let Err(error) = command.validate() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
if self
.current_screen_clip
.is_some_and(|screen_clip| !screen_clip.is_valid())
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::InvalidScreenClip);
}
requested = requested.with_command(&command);
if let Some(budget) = self.budget
&& let Err(error) = validate_scene_budget(budget, requested)
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
let command_owned_payload_bytes = command.owned_allocation_bytes();
let prospective_owned_payload_bytes = existing_owned_payload_bytes
.saturating_add(staged_owned_payload_bytes)
.saturating_add(command_owned_payload_bytes);
if let Some(budget) = self.budget {
let required_total = self
.commands
.len()
.saturating_add(staged.len())
.saturating_add(1);
let final_capacity = if required_total <= self.commands.capacity() {
self.commands.capacity()
} else {
match budgeted_command_capacity(
budget,
self.commands.capacity(),
required_total,
prospective_owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
}
};
if let Err(error) = validate_scene_allocation_budget(
budget,
final_capacity,
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
if staged.len() == staged.capacity() {
let staging_capacity = match budgeted_command_capacity(
budget,
staged.capacity(),
staged.len().saturating_add(1),
prospective_owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
};
let mut replacement = Vec::new();
if replacement.try_reserve_exact(staging_capacity).is_err() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(
staging_capacity,
prospective_owned_payload_bytes,
),
});
}
if let Err(error) = validate_scene_allocation_budget(
budget,
replacement.capacity(),
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
replacement.append(&mut staged);
staged = replacement;
} else if let Err(error) = validate_scene_allocation_budget(
budget,
staged.capacity(),
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
} else if staged.try_reserve(1).is_err() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: command.retained_bytes(),
});
}
staged.push(SceneCommand {
layer,
order: next_order,
depth: self.current_depth,
screen_clip: self.current_screen_clip,
command,
});
staged_owned_payload_bytes =
staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
next_order = next_order.saturating_add(1);
}
if staged.is_empty() {
return Ok(());
}
let total = self.commands.len().saturating_add(staged.len());
let owned_payload_bytes =
existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
let requested_capacity = if let Some(budget) = self.budget {
if total <= self.commands.capacity() {
self.commands.capacity()
} else {
match budgeted_command_capacity(
budget,
self.commands.capacity(),
total,
owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
}
}
} else {
total
};
if staged.capacity() < requested_capacity
&& staged
.try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
.is_err()
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
});
}
if let Some(budget) = self.budget
&& let Err(error) =
validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
staged.append(&mut self.commands);
staged.sort_unstable_by_key(|command| (command.layer, command.order));
self.commands = staged;
self.owned_payload_bytes = owned_payload_bytes;
self.next_order = next_order;
self.statistics = requested;
Ok(())
}
fn record_batch_rejection(
&mut self,
command_count: usize,
by_primitive: PrimitiveCommandCounts,
) {
self.statistics.requested_commands = self
.statistics
.requested_commands
.saturating_add(command_count);
self.statistics.rejected_commands = self
.statistics
.rejected_commands
.saturating_add(command_count);
self.statistics.requested_by_primitive =
self.statistics.requested_by_primitive.adding(by_primitive);
self.statistics.rejected_by_primitive =
self.statistics.rejected_by_primitive.adding(by_primitive);
}
pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
let mut counts = PrimitiveCommandCounts::default();
counts.increment(primitive);
self.record_batch_rejection(1, counts);
}
fn try_push_to_layer_inner(
&mut self,
layer: Layer,
command: DrawCommand,
) -> Result<(), SceneError> {
command.validate()?;
if self
.current_screen_clip
.is_some_and(|screen_clip| !screen_clip.is_valid())
{
return Err(SceneError::InvalidScreenClip);
}
let command_retained_bytes = command.retained_bytes();
let owned_payload_bytes = self
.owned_payload_bytes
.saturating_add(command.owned_allocation_bytes());
let requested = self.statistics.with_command(&command);
if let Some(budget) = self.budget {
validate_scene_budget(budget, requested)?;
}
let replacement = if self.commands.len() == self.commands.capacity() {
if let Some(budget) = self.budget {
let required_len = self.commands.len().saturating_add(1);
let capacity = budgeted_command_capacity(
budget,
self.commands.capacity(),
required_len,
owned_payload_bytes,
)?;
let mut replacement = Vec::new();
replacement.try_reserve_exact(capacity).map_err(|_| {
SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
}
})?;
validate_scene_allocation_budget(
budget,
replacement.capacity(),
owned_payload_bytes,
)?;
Some(replacement)
} else {
self.commands
.try_reserve(1)
.map_err(|_| SceneError::AllocationFailed {
requested_bytes: command_retained_bytes,
})?;
None
}
} else {
if let Some(budget) = self.budget {
validate_scene_allocation_budget(
budget,
self.commands.capacity(),
owned_payload_bytes,
)?;
}
None
};
if let Some(mut replacement) = replacement {
replacement.append(&mut self.commands);
self.commands = replacement;
}
let order = self.next_order;
let scene_command = SceneCommand {
layer,
order,
depth: self.current_depth,
screen_clip: self.current_screen_clip,
command,
};
let position = self.commands.partition_point(|existing| {
existing.layer < scene_command.layer
|| (existing.layer == scene_command.layer && existing.order <= scene_command.order)
});
self.commands.insert(position, scene_command);
self.owned_payload_bytes = owned_payload_bytes;
self.next_order = self.next_order.saturating_add(1);
self.statistics = requested;
Ok(())
}
pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
self.try_circle(center, radius, style).is_ok()
}
pub fn try_circle(
&mut self,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
}
pub fn circle_on_layer(
&mut self,
layer: Layer,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> bool {
self.try_circle_on_layer(layer, center, radius, style)
.is_ok()
}
pub fn try_circle_on_layer(
&mut self,
layer: Layer,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_push_to_layer(
layer,
DrawCommand::Circle(Circle {
center,
radius,
style,
}),
)
}
pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
self.try_rect(rect, corner_radius, style).is_ok()
}
pub fn try_rect(
&mut self,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
}
pub fn rect_on_layer(
&mut self,
layer: Layer,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> bool {
self.try_rect_on_layer(layer, rect, corner_radius, style)
.is_ok()
}
pub fn try_rect_on_layer(
&mut self,
layer: Layer,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_push_to_layer(
layer,
DrawCommand::Rect(RectShape {
rect,
corner_radius,
style,
}),
)
}
pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
self.try_line(from, to, width, color).is_ok()
}
pub fn try_line(
&mut self,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
}
pub fn line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> bool {
self.try_line_on_layer(layer, from, to, width, color)
.is_ok()
}
pub fn try_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
}
pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
self.try_styled_line(from, to, style).is_ok()
}
pub fn try_styled_line(
&mut self,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
}
pub fn styled_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> bool {
self.try_styled_line_on_layer(layer, from, to, style)
.is_ok()
}
pub fn try_styled_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
}
pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
self.try_polyline(points, width, color).is_ok()
}
pub fn try_polyline(
&mut self,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
}
pub fn polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> bool {
self.try_polyline_on_layer(layer, points, width, color)
.is_ok()
}
pub fn try_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
}
pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
self.try_styled_polyline(points, style).is_ok()
}
pub fn try_styled_polyline(
&mut self,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
}
pub fn styled_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> bool {
self.try_styled_polyline_on_layer(layer, points, style)
.is_ok()
}
pub fn try_styled_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Layer {
order: i32,
}
impl Layer {
pub const DEFAULT: Self = Self::new(0);
pub const BACKGROUND: Self = Self::new(-100);
pub const FOREGROUND: Self = Self::new(100);
pub const fn new(order: i32) -> Self {
Self { order }
}
pub const fn order(self) -> i32 {
self.order
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenClipRect {
rect: Rect,
}
impl ScreenClipRect {
pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
}
pub fn from_min_size(
min: LogicalScreenPosition,
size: LogicalScreenVector,
) -> Result<Self, SceneError> {
Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
}
fn from_rect(rect: Rect) -> Result<Self, SceneError> {
let clip = Self { rect };
clip.is_valid()
.then_some(clip)
.ok_or(SceneError::InvalidScreenClip)
}
#[cfg(feature = "wgpu")]
pub(crate) fn rect(self) -> Rect {
self.rect
}
pub fn min(self) -> LogicalScreenPosition {
LogicalScreenPosition::from_vec2(self.rect.normalized().min)
}
pub fn max(self) -> LogicalScreenPosition {
LogicalScreenPosition::from_vec2(self.rect.normalized().max)
}
pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
let first = self.rect.normalized();
let second = other.rect.normalized();
let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));
Self::new(
LogicalScreenPosition::from_vec2(min),
LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
)
}
fn is_valid(self) -> bool {
if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
return false;
}
let rect = self.rect.normalized();
rect.width() > 0.0 && rect.height() > 0.0
}
}
#[derive(Debug, Clone)]
pub struct SceneCommand {
layer: Layer,
order: u64,
depth: f32,
screen_clip: Option<ScreenClipRect>,
command: DrawCommand,
}
impl SceneCommand {
pub fn layer(&self) -> Layer {
self.layer
}
pub fn order(&self) -> u64 {
self.order
}
pub fn depth(&self) -> f32 {
self.depth
}
pub fn screen_clip(&self) -> Option<ScreenClipRect> {
self.screen_clip
}
pub fn command(&self) -> &DrawCommand {
&self.command
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DrawCommand {
Circle(Circle),
Rect(RectShape),
Line(Line),
Polyline(Polyline),
}
impl DrawCommand {
pub const fn primitive(&self) -> ScenePrimitive {
match self {
Self::Circle(_) => ScenePrimitive::Circle,
Self::Rect(_) => ScenePrimitive::Rect,
Self::Line(_) => ScenePrimitive::Line,
Self::Polyline(_) => ScenePrimitive::Polyline,
}
}
pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
let command = Self::Circle(Circle {
center,
radius,
style,
});
command.validate()?;
Ok(command)
}
pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
let command = Self::Rect(RectShape {
rect,
corner_radius,
style,
});
command.validate()?;
Ok(command)
}
pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
Self::styled_line(from, to, StrokeStyle2d::new(width, color))
}
pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
let command = Self::Line(Line { from, to, style });
command.validate()?;
Ok(command)
}
pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
Self::styled_polyline(points, StrokeStyle2d::new(width, color))
}
pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
let command = Self::Polyline(Polyline { points, style });
command.validate()?;
Ok(command)
}
fn validate(&self) -> Result<(), SceneError> {
match self {
Self::Circle(circle) => {
if !circle.center.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
}
if !circle.radius.is_finite() || circle.radius <= 0.0 {
return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
}
if !(circle.center + Vec2::splat(circle.radius)).is_finite()
|| !(circle.center - Vec2::splat(circle.radius)).is_finite()
{
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
}
circle.style.validate(ScenePrimitive::Circle)
}
Self::Rect(rectangle) => {
let rect = rectangle.rect.normalized();
if !rect.min.is_finite() || !rect.max.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
}
let width = rect.width();
let height = rect.height();
if !width.is_finite() || !height.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
}
if width <= 0.0
|| height <= 0.0
|| !rectangle.corner_radius.is_finite()
|| rectangle.corner_radius < 0.0
{
return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
}
rectangle.style.validate(ScenePrimitive::Rect)
}
Self::Line(line) => {
if !line.from.is_finite() || !line.to.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
}
if !(line.to - line.from).is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
}
if !drawable_segment(line.from, line.to) {
return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
}
if !line.style.is_valid() {
return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
}
validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
Ok(())
}
Self::Polyline(polyline) => {
validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
Ok(())
}
}
}
fn retained_point_count(&self) -> usize {
match self {
Self::Polyline(polyline) => polyline.points.len(),
Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
}
}
fn retained_bytes(&self) -> usize {
size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
}
fn owned_allocation_bytes(&self) -> usize {
match self {
Self::Polyline(polyline) => {
polyline.points.capacity().saturating_mul(size_of::<Vec2>())
}
Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
}
}
fn estimated_tessellated_vertices(&self) -> usize {
match self {
Self::Circle(circle) => {
let fill_vertices = CIRCLE_SEGMENTS * 3;
let stroke_vertices = CIRCLE_SEGMENTS * 6;
let style = circle.style;
usize::from(style.fill.is_some()) * fill_vertices
+ usize::from(style.stroke.is_some()) * stroke_vertices
+ style.shadow.map_or(0, |shadow| {
fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
})
}
Self::Rect(rectangle) => {
let rect = rectangle.rect.normalized();
let radius = rectangle
.corner_radius
.max(0.0)
.min(rect.width().abs() * 0.5)
.min(rect.height().abs() * 0.5);
let boundary_segments = if radius <= 0.0 {
4
} else {
4 * (CORNER_SEGMENTS + 1)
};
let fill_vertices = boundary_segments * 3;
let stroke_vertices = boundary_segments * 6;
let style = rectangle.style;
usize::from(style.fill.is_some()) * fill_vertices
+ usize::from(style.stroke.is_some()) * stroke_vertices
+ style.shadow.map_or(0, |shadow| {
fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
})
}
Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
}
}
}
fn validate_stroke_path(
points: &[Vec2],
style: StrokeStyle2d,
primitive: ScenePrimitive,
) -> Result<(), SceneError> {
validate_stroke_path_iter(points.iter().copied(), style, primitive)
}
fn validate_stroke_path_iter<I>(
points: I,
style: StrokeStyle2d,
primitive: ScenePrimitive,
) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
return Err(SceneError::InvalidStroke(primitive));
}
if style.width_mode == StrokeWidthMode2d::WorldUnits {
let extent = Vec2::splat(maximum_offset as f32);
if points
.clone()
.any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
{
return Err(SceneError::NonFiniteGeometry(primitive));
}
}
if let Some(dash) = style.dash {
let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
.ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
if required > dash.max_subsegments {
return Err(SceneError::StrokeExpansionLimitExceeded {
primitive,
limit: dash.max_subsegments,
required,
});
}
}
Ok(())
}
pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
let primitive = ScenePrimitive::Polyline;
if !points.clone().all(|point| point.is_finite()) {
return Err(SceneError::NonFiniteGeometry(primitive));
}
let mut deltas = points.clone();
let Some(mut previous) = deltas.next() else {
return Err(SceneError::DegenerateGeometry(primitive));
};
let mut segment_count = 0usize;
for point in deltas {
let delta = point - previous;
if !delta.is_finite() {
return Err(SceneError::NonFiniteGeometry(primitive));
}
previous = point;
segment_count = segment_count.saturating_add(1);
}
if segment_count == 0 {
return Err(SceneError::DegenerateGeometry(primitive));
}
let mut segments = points.clone();
let mut previous = segments
.next()
.expect("a non-empty path was established above");
for point in segments {
if !drawable_segment(previous, point) {
return Err(SceneError::DegenerateGeometry(primitive));
}
previous = point;
}
let mut turns = points;
let mut first = turns
.next()
.expect("a drawable segment was established above");
let mut second = turns
.next()
.expect("a drawable segment was established above");
for (index, third) in turns.enumerate() {
let incoming = second - first;
let outgoing = third - second;
let cross = f64::from(incoming.x) * f64::from(outgoing.y)
- f64::from(incoming.y) * f64::from(outgoing.x);
let dot = f64::from(incoming.x) * f64::from(outgoing.x)
+ f64::from(incoming.y) * f64::from(outgoing.y);
let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
* f64::from(outgoing.x).hypot(f64::from(outgoing.y));
let normalized_cross = cross / direction_product;
if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
{
return Err(SceneError::DegenerateStrokeTurn {
primitive,
vertex_index: index + 1,
});
}
first = second;
second = third;
}
Ok(())
}
pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
validate_polyline_geometry(points.clone())?;
if !style.is_valid() {
return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
}
validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
}
fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
let segment_count = points
.windows(2)
.filter(|pair| drawable_segment(pair[0], pair[1]))
.count();
if segment_count == 0 {
return 0;
}
let body_count = style.dash.map_or(segment_count, |dash| {
dash_subsegment_count(points, dash, None)
.expect("accepted dash paths have representable subsegments")
});
let join_count = segment_count.saturating_sub(1);
let cap_count = if style.dash.is_some() {
body_count.saturating_mul(2)
} else {
2
};
let cap_vertices = match style.cap {
StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
StrokeCap2d::Butt | StrokeCap2d::Square => 0,
};
let join_vertices = match style.join {
StrokeJoin2d::Bevel => join_count.saturating_mul(6),
StrokeJoin2d::Miter => join_count.saturating_mul(12),
StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
}
StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
};
let marker_vertices = (usize::from(style.start_marker.is_some())
+ usize::from(style.end_marker.is_some()))
.saturating_mul(3);
body_count
.saturating_mul(6)
.saturating_add(cap_vertices)
.saturating_add(join_vertices)
.saturating_add(marker_vertices)
}
fn dash_subsegment_count(
points: &[Vec2],
dash: StrokeDashPattern2d,
stop_after: Option<usize>,
) -> Option<usize> {
dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
}
fn dash_subsegment_count_iter<I>(
points: I,
dash: StrokeDashPattern2d,
stop_after: Option<usize>,
) -> Option<usize>
where
I: Iterator<Item = Vec2>,
{
let lengths = dash.lengths();
let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
let mut phase = f64::from(dash.phase).rem_euclid(total);
let mut pattern_index = 0usize;
while phase >= f64::from(lengths[pattern_index]) {
phase -= f64::from(lengths[pattern_index]);
pattern_index = (pattern_index + 1) % lengths.len();
}
let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
let mut count = 0usize;
let mut points = points;
let mut previous = points.next()?;
for point in points {
let delta = point - previous;
let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
let mut segment_remaining = segment_length;
while segment_remaining > 0.0 {
let consumed = segment_remaining.min(pattern_remaining);
if pattern_index.is_multiple_of(2) && consumed > 0.0 {
count = count.saturating_add(1);
if stop_after.is_some_and(|limit| count > limit) {
return Some(count);
}
}
let next_remaining = segment_remaining - consumed;
if next_remaining >= segment_remaining {
return None;
}
let amount_start = 1.0 - segment_remaining / segment_length;
let amount_end = 1.0 - next_remaining / segment_length;
if dash_segment_point(previous, point, amount_start)
== dash_segment_point(previous, point, amount_end)
{
return None;
}
segment_remaining = next_remaining;
pattern_remaining -= consumed;
if pattern_remaining <= 0.0 {
pattern_index = (pattern_index + 1) % lengths.len();
pattern_remaining = f64::from(lengths[pattern_index]);
}
}
previous = point;
}
Some(count)
}
fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
Vec2::new(
(f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
(f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
)
}
fn validate_scene_budget(
budget: SceneBudget,
requested: SceneStatistics,
) -> Result<(), SceneError> {
let limits = [
(
SceneBudgetResource::Commands,
budget.max_commands,
requested.accepted_commands,
),
(
SceneBudgetResource::Points,
budget.max_points,
requested.retained_points,
),
(
SceneBudgetResource::TessellatedVertices,
budget.max_tessellated_vertices,
requested.estimated_tessellated_vertices,
),
(
SceneBudgetResource::RetainedBytes,
budget.max_retained_bytes,
requested.retained_bytes,
),
(
SceneBudgetResource::UploadBytes,
budget.max_upload_bytes,
requested.estimated_upload_bytes,
),
(
SceneBudgetResource::DrawBatches,
budget.max_draw_batches,
requested.estimated_draw_batches,
),
];
for (resource, limit, requested) in limits {
if requested > limit {
return Err(SceneError::BudgetExceeded {
resource,
limit,
requested,
});
}
}
Ok(())
}
fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
command_capacity
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(owned_payload_bytes)
}
fn validate_scene_allocation_budget(
budget: SceneBudget,
command_capacity: usize,
owned_payload_bytes: usize,
) -> Result<(), SceneError> {
let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
if requested > budget.max_allocation_bytes {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit: budget.max_allocation_bytes,
requested,
});
}
Ok(())
}
fn budgeted_command_capacity(
budget: SceneBudget,
current_capacity: usize,
required_len: usize,
owned_payload_bytes: usize,
) -> Result<usize, SceneError> {
let available = budget
.max_allocation_bytes
.saturating_sub(owned_payload_bytes);
let maximum_capacity = available / size_of::<SceneCommand>();
if required_len > maximum_capacity {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit: budget.max_allocation_bytes,
requested: scene_allocation_bytes(required_len, owned_payload_bytes),
});
}
Ok(current_capacity
.max(1)
.saturating_mul(2)
.max(required_len)
.min(maximum_capacity))
}
fn drawable_segment(from: Vec2, to: Vec2) -> bool {
let delta = to - from;
delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
}
#[derive(Debug, Clone)]
pub struct Circle {
center: Vec2,
radius: f32,
style: ShapeStyle,
}
impl Circle {
pub const fn center(&self) -> Vec2 {
self.center
}
pub const fn radius(&self) -> f32 {
self.radius
}
pub const fn style(&self) -> ShapeStyle {
self.style
}
}
#[derive(Debug, Clone)]
pub struct RectShape {
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
}
impl RectShape {
pub const fn rect(&self) -> Rect {
self.rect
}
pub const fn corner_radius(&self) -> f32 {
self.corner_radius
}
pub const fn style(&self) -> ShapeStyle {
self.style
}
}
#[derive(Debug, Clone)]
pub struct Line {
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
}
impl Line {
pub const fn from(&self) -> Vec2 {
self.from
}
pub const fn to(&self) -> Vec2 {
self.to
}
pub const fn stroke(&self) -> Stroke {
self.style.stroke
}
pub const fn stroke_style(&self) -> StrokeStyle2d {
self.style
}
}
#[derive(Debug, Clone)]
pub struct Polyline {
points: Vec<Vec2>,
style: StrokeStyle2d,
}
impl Polyline {
pub fn points(&self) -> &[Vec2] {
&self.points
}
pub const fn stroke(&self) -> Stroke {
self.style.stroke
}
pub const fn stroke_style(&self) -> StrokeStyle2d {
self.style
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeWidthMode2d {
LogicalPixels,
WorldUnits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeCap2d {
Butt,
Square,
Round,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeJoin2d {
Bevel,
Round,
Miter,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeDashPattern2d {
lengths: [f32; MAX_DASH_ELEMENTS],
length_count: u8,
phase: f32,
max_subsegments: usize,
}
impl StrokeDashPattern2d {
pub fn new(
lengths: &[f32],
phase: f32,
max_subsegments: usize,
) -> Result<Self, StrokeStyleError> {
if lengths.len() < 2
|| lengths.len() > MAX_DASH_ELEMENTS
|| !lengths.len().is_multiple_of(2)
{
return Err(StrokeStyleError::InvalidDashElementCount);
}
if lengths
.iter()
.any(|length| !length.is_finite() || *length <= 0.0)
{
return Err(StrokeStyleError::InvalidDashLength);
}
if !phase.is_finite() {
return Err(StrokeStyleError::InvalidDashPhase);
}
if max_subsegments == 0 || max_subsegments > MAX_STROKE_DASH_SUBSEGMENTS {
return Err(StrokeStyleError::InvalidDashExpansionLimit);
}
let mut stored = [0.0; MAX_DASH_ELEMENTS];
stored[..lengths.len()].copy_from_slice(lengths);
Ok(Self {
lengths: stored,
length_count: lengths.len() as u8,
phase,
max_subsegments,
})
}
pub fn lengths(&self) -> &[f32] {
&self.lengths[..usize::from(self.length_count)]
}
pub const fn phase(self) -> f32 {
self.phase
}
pub const fn max_subsegments(self) -> usize {
self.max_subsegments
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeMarker2d {
length: LogicalPixels,
width: LogicalPixels,
}
impl StrokeMarker2d {
pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
Self { length, width }
}
pub const fn length(self) -> LogicalPixels {
self.length
}
pub const fn width(self) -> LogicalPixels {
self.width
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeStyle2d {
stroke: Stroke,
width_mode: StrokeWidthMode2d,
cap: StrokeCap2d,
join: StrokeJoin2d,
miter_limit: f32,
dash: Option<StrokeDashPattern2d>,
start_marker: Option<StrokeMarker2d>,
end_marker: Option<StrokeMarker2d>,
}
impl StrokeStyle2d {
pub const fn new(width: f32, color: Color) -> Self {
Self {
stroke: Stroke::new(width, color),
width_mode: StrokeWidthMode2d::LogicalPixels,
cap: StrokeCap2d::Round,
join: StrokeJoin2d::Miter,
miter_limit: MAX_MITER_LIMIT,
dash: None,
start_marker: None,
end_marker: None,
}
}
pub const fn logical(width: LogicalPixels, color: Color) -> Self {
Self::new(width.get(), color)
}
pub const fn world(width: WorldLength, color: Color) -> Self {
let mut style = Self::new(width.get(), color);
style.width_mode = StrokeWidthMode2d::WorldUnits;
style
}
pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
self.cap = cap;
self
}
pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
self.join = join;
self
}
pub fn with_miter_limit(mut self, limit: f32) -> Result<Self, StrokeStyleError> {
if !limit.is_finite() || !(1.0..=MAX_MITER_LIMIT).contains(&limit) {
return Err(StrokeStyleError::InvalidMiterLimit);
}
self.miter_limit = limit;
Ok(self)
}
pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
self.dash = Some(dash);
self
}
pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
self.start_marker = Some(marker);
self
}
pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
self.end_marker = Some(marker);
self
}
pub const fn stroke(self) -> Stroke {
self.stroke
}
pub const fn width_mode(self) -> StrokeWidthMode2d {
self.width_mode
}
pub const fn cap(self) -> StrokeCap2d {
self.cap
}
pub const fn join(self) -> StrokeJoin2d {
self.join
}
pub const fn miter_limit(self) -> f32 {
self.miter_limit
}
pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
self.dash
}
pub const fn start_marker(self) -> Option<StrokeMarker2d> {
self.start_marker
}
pub const fn end_marker(self) -> Option<StrokeMarker2d> {
self.end_marker
}
fn is_valid(self) -> bool {
self.stroke.is_valid()
&& self.miter_limit.is_finite()
&& (1.0..=MAX_MITER_LIMIT).contains(&self.miter_limit)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeStyleError {
InvalidDashElementCount,
InvalidDashLength,
InvalidDashPhase,
InvalidDashExpansionLimit,
InvalidMiterLimit,
}
impl fmt::Display for StrokeStyleError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "invalid bounded 2D stroke style: {self:?}")
}
}
impl Error for StrokeStyleError {}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShapeStyle {
fill: Option<Fill>,
stroke: Option<Stroke>,
shadow: Option<Shadow>,
}
impl ShapeStyle {
pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
Self {
fill,
stroke,
shadow,
}
}
pub const fn fill(self) -> Option<Fill> {
self.fill
}
pub const fn stroke(self) -> Option<Stroke> {
self.stroke
}
pub const fn shadow(self) -> Option<Shadow> {
self.shadow
}
pub fn filled(color: Color) -> Self {
Self::filled_with(Fill::Solid(color))
}
pub fn filled_with(fill: Fill) -> Self {
Self {
fill: Some(fill),
stroke: None,
shadow: None,
}
}
pub fn stroked(width: f32, color: Color) -> Self {
Self {
fill: None,
stroke: Some(Stroke { width, color }),
shadow: None,
}
}
pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
}
pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
Self {
fill: Some(fill),
stroke: Some(Stroke {
width: stroke_width,
color: stroke,
}),
shadow: None,
}
}
pub fn with_shadow(mut self, shadow: Shadow) -> Self {
self.shadow = Some(shadow);
self
}
fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
return Err(SceneError::MissingStyle(primitive));
}
if self.fill.is_some_and(|fill| !fill.is_valid()) {
return Err(SceneError::InvalidFill(primitive));
}
if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
return Err(SceneError::InvalidStroke(primitive));
}
if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
return Err(SceneError::InvalidShadow(primitive));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Fill {
Solid(Color),
LinearGradient(LinearGradient),
RadialGradient(RadialGradient),
}
impl Fill {
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
pub(crate) fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
match self {
Self::Solid(color) => color,
Self::LinearGradient(gradient) => {
gradient.color_at_with_offset(world_base, world_offset)
}
Self::RadialGradient(gradient) => {
gradient.color_at_with_offset(world_base, world_offset)
}
}
}
fn is_valid(self) -> bool {
match self {
Self::Solid(color) => color.is_normalized(),
Self::LinearGradient(gradient) => gradient.is_valid(),
Self::RadialGradient(gradient) => gradient.is_valid(),
}
}
}
impl From<Color> for Fill {
fn from(color: Color) -> Self {
Self::Solid(color)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinearGradient {
start: Vec2,
end: Vec2,
start_color: Color,
end_color: Color,
}
impl LinearGradient {
pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
Self {
start,
end,
start_color,
end_color,
}
}
pub const fn start(self) -> Vec2 {
self.start
}
pub const fn end(self) -> Vec2 {
self.end
}
pub const fn start_color(self) -> Color {
self.start_color
}
pub const fn end_color(self) -> Color {
self.end_color
}
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
return self.end_color.clamp();
}
let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
let relative_x =
f64::from(world_base.x) - f64::from(self.start.x) + f64::from(world_offset.x);
let relative_y =
f64::from(world_base.y) - f64::from(self.start.y) + f64::from(world_offset.y);
let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
.clamp(0.0, 1.0) as f32;
self.start_color.interpolate(self.end_color, amount)
}
fn is_valid(self) -> bool {
self.start.is_finite()
&& self.end.is_finite()
&& self.start_color.is_normalized()
&& self.end_color.is_normalized()
&& self.start != self.end
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RadialGradient {
center: Vec2,
inner_radius: f32,
outer_radius: f32,
inner_color: Color,
outer_color: Color,
}
impl RadialGradient {
pub fn new(
center: Vec2,
inner_radius: f32,
outer_radius: f32,
inner_color: Color,
outer_color: Color,
) -> Self {
if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
Self {
center,
inner_radius: outer_radius,
outer_radius: inner_radius,
inner_color: outer_color,
outer_color: inner_color,
}
} else {
Self {
center,
inner_radius,
outer_radius,
inner_color,
outer_color,
}
}
}
pub const fn center(self) -> Vec2 {
self.center
}
pub const fn inner_radius(self) -> f32 {
self.inner_radius
}
pub const fn outer_radius(self) -> f32 {
self.outer_radius
}
pub const fn inner_color(self) -> Color {
self.inner_color
}
pub const fn outer_color(self) -> Color {
self.outer_color
}
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
return self.outer_color.clamp();
}
let radius_range = self.outer_radius - self.inner_radius;
if radius_range == 0.0 {
return self.outer_color;
}
let horizontal =
f64::from(world_base.x) - f64::from(self.center.x) + f64::from(world_offset.x);
let vertical =
f64::from(world_base.y) - f64::from(self.center.y) + f64::from(world_offset.y);
let distance = horizontal.hypot(vertical);
let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
.clamp(0.0, 1.0) as f32;
self.inner_color.interpolate(self.outer_color, amount)
}
fn is_valid(self) -> bool {
self.center.is_finite()
&& self.inner_radius.is_finite()
&& self.outer_radius.is_finite()
&& self.inner_radius >= 0.0
&& self.outer_radius >= self.inner_radius
&& self.inner_color.is_normalized()
&& self.outer_color.is_normalized()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stroke {
width: f32,
color: Color,
}
impl Stroke {
pub const fn new(width: f32, color: Color) -> Self {
Self { width, color }
}
pub const fn width(self) -> f32 {
self.width
}
pub const fn color(self) -> Color {
self.color
}
fn is_valid(self) -> bool {
self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Shadow {
offset: LogicalScreenVector,
spread: f32,
color: Color,
}
impl Shadow {
pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
Self {
offset,
spread,
color,
}
}
pub const fn offset(self) -> LogicalScreenVector {
self.offset
}
pub const fn spread(self) -> f32 {
self.spread
}
pub const fn color(self) -> Color {
self.color
}
fn is_valid(self) -> bool {
self.offset.is_finite()
&& self.spread.is_finite()
&& self.spread >= 0.0
&& (self.spread * 2.0).is_finite()
&& self.color.is_normalized()
}
}
#[cfg(test)]
mod tests {
use std::panic::{AssertUnwindSafe, catch_unwind};
use super::MAX_STROKE_DASH_SUBSEGMENTS;
use crate::{
Color, DrawCommand, Fill, Layer, LinearGradient, LogicalScreenPosition,
LogicalScreenVector, RadialGradient, Rect, Scene, SceneBudget, SceneBudgetResource,
SceneCommand, SceneError, ScenePrimitive, ScreenClipRect, ShapeStyle, StrokeCap2d,
StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeStyle2d, StrokeStyleError, Vec2,
};
use crate::{LogicalPixels, WorldLength};
const UNLIMITED: usize = usize::MAX;
const fn budget_for(
commands: usize,
points: usize,
vertices: usize,
retained_bytes: usize,
upload_bytes: usize,
batches: usize,
) -> SceneBudget {
SceneBudget::new(
commands,
points,
vertices,
retained_bytes,
UNLIMITED,
upload_bytes,
batches,
)
}
#[test]
fn scene_collects_visual_commands_only() {
let mut scene = Scene::new(Color::BLACK).unwrap();
scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
assert_eq!(scene.commands.len(), 1);
}
#[test]
fn scene_keeps_commands_sorted_by_layer() {
let mut scene = Scene::new(Color::BLACK).unwrap();
scene.circle_on_layer(
Layer::FOREGROUND,
Vec2::ZERO,
10.0,
ShapeStyle::filled(Color::WHITE),
);
scene.line_on_layer(Layer::BACKGROUND, Vec2::ZERO, Vec2::X, 1.0, Color::WHITE);
assert!(matches!(scene.commands[0].command, DrawCommand::Line(_)));
assert!(matches!(scene.commands[1].command, DrawCommand::Circle(_)));
}
#[test]
fn scene_budget_rejection_is_atomic_and_counted() {
let budget = budget_for(1, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
scene
.try_circle(Vec2::new(1.0, 2.0), 3.0, ShapeStyle::filled(Color::WHITE))
.unwrap();
let before_order = scene.commands()[0].order();
let result = scene.try_circle(Vec2::new(4.0, 5.0), 6.0, ShapeStyle::filled(Color::WHITE));
assert_eq!(
result,
Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::Commands,
limit: 1,
requested: 2,
})
);
assert_eq!(scene.command_count(), 1);
assert_eq!(scene.commands()[0].order(), before_order);
assert_eq!(scene.statistics().requested_commands(), 2);
assert_eq!(scene.statistics().accepted_commands(), 1);
assert_eq!(scene.statistics().rejected_commands(), 1);
}
#[test]
fn scene_budget_enforces_every_resource_at_insertion() {
let mut reference = Scene::new(Color::BLACK).unwrap();
reference
.try_polyline(
vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
2.0,
Color::WHITE,
)
.unwrap();
let usage = reference.statistics();
let cases = [
(
SceneBudgetResource::Points,
budget_for(
UNLIMITED,
usage.retained_points() - 1,
UNLIMITED,
UNLIMITED,
UNLIMITED,
UNLIMITED,
),
usage.retained_points(),
),
(
SceneBudgetResource::TessellatedVertices,
budget_for(
UNLIMITED,
UNLIMITED,
usage.estimated_tessellated_vertices() - 1,
UNLIMITED,
UNLIMITED,
UNLIMITED,
),
usage.estimated_tessellated_vertices(),
),
(
SceneBudgetResource::RetainedBytes,
budget_for(
UNLIMITED,
UNLIMITED,
UNLIMITED,
usage.retained_bytes() - 1,
UNLIMITED,
UNLIMITED,
),
usage.retained_bytes(),
),
(
SceneBudgetResource::UploadBytes,
budget_for(
UNLIMITED,
UNLIMITED,
UNLIMITED,
UNLIMITED,
usage.estimated_upload_bytes() - 1,
UNLIMITED,
),
usage.estimated_upload_bytes(),
),
(
SceneBudgetResource::DrawBatches,
budget_for(
UNLIMITED,
UNLIMITED,
UNLIMITED,
UNLIMITED,
UNLIMITED,
usage.estimated_draw_batches() - 1,
),
usage.estimated_draw_batches(),
),
];
for (resource, budget, requested) in cases {
let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
let result = scene.try_polyline(
vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
2.0,
Color::WHITE,
);
assert_eq!(
result,
Err(SceneError::BudgetExceeded {
resource,
limit: requested - 1,
requested,
})
);
assert_eq!(scene.command_count(), 0);
assert_eq!(scene.statistics().accepted_commands(), 0);
assert_eq!(scene.statistics().rejected_commands(), 1);
}
}
#[test]
fn exact_scene_budget_is_accepted_and_clear_preserves_limits() {
let mut reference = Scene::new(Color::BLACK).unwrap();
reference
.try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
.unwrap();
let usage = reference.statistics();
let budget = budget_for(
usage.accepted_commands(),
usage.retained_points(),
usage.estimated_tessellated_vertices(),
usage.retained_bytes(),
usage.estimated_upload_bytes(),
usage.estimated_draw_batches(),
);
let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
scene
.try_line(Vec2::ZERO, Vec2::X, 2.0, Color::WHITE)
.unwrap();
assert_eq!(scene.statistics(), usage);
scene.clear();
assert_eq!(scene.budget(), Some(budget));
assert_eq!(scene.statistics(), Default::default());
assert_eq!(scene.command_count(), 0);
}
#[test]
fn scene_allocation_budget_bounds_spare_command_capacity_atomically() {
let command_bytes = size_of::<SceneCommand>();
let too_small = SceneBudget::new(
1,
UNLIMITED,
UNLIMITED,
command_bytes,
command_bytes - 1,
UNLIMITED,
UNLIMITED,
);
let mut rejected = Scene::with_budget(Color::BLACK, too_small).unwrap();
let error = rejected
.try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
.unwrap_err();
assert!(matches!(
error,
SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit,
requested,
} if limit == command_bytes - 1 && requested >= command_bytes
));
assert_eq!(rejected.command_count(), 0);
assert_eq!(rejected.allocation_bytes(), 0);
let bounded = SceneBudget::new(
4,
UNLIMITED,
UNLIMITED,
4 * command_bytes,
4 * command_bytes,
UNLIMITED,
UNLIMITED,
);
let mut scene = Scene::with_budget(Color::BLACK, bounded).unwrap();
scene
.try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
.unwrap();
assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
scene.clear();
assert!(scene.allocation_bytes() <= bounded.max_allocation_bytes());
}
#[test]
fn batch_allocation_budget_rejects_before_consuming_unbounded_input() {
let budget = SceneBudget::new(
usize::MAX,
UNLIMITED,
UNLIMITED,
UNLIMITED,
1,
UNLIMITED,
UNLIMITED,
);
let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
let consumed = std::cell::Cell::new(0usize);
let command =
DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap();
let commands = std::iter::from_fn(|| {
consumed.set(consumed.get().saturating_add(1));
Some((Layer::DEFAULT, command.clone()))
});
assert!(matches!(
scene.try_extend_to_layers(commands),
Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit: 1,
..
})
));
assert_eq!(consumed.get(), 1);
assert_eq!(scene.command_count(), 0);
assert_eq!(scene.allocation_bytes(), 0);
}
#[test]
fn batch_insertion_sorts_once_and_is_atomic_on_budget_failure() {
let budget = budget_for(4, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED, UNLIMITED);
let mut scene = Scene::with_budget(Color::BLACK, budget).unwrap();
scene
.try_extend_to_layers([
(
Layer::FOREGROUND,
DrawCommand::circle(Vec2::new(1.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
.unwrap(),
),
(
Layer::BACKGROUND,
DrawCommand::line(Vec2::ZERO, Vec2::X, 1.0, Color::WHITE).unwrap(),
),
(
Layer::FOREGROUND,
DrawCommand::circle(Vec2::new(2.0, 0.0), 1.0, ShapeStyle::filled(Color::WHITE))
.unwrap(),
),
])
.unwrap();
assert_eq!(scene.command_count(), 3);
assert_eq!(scene.commands()[0].layer(), Layer::BACKGROUND);
assert_eq!(scene.commands()[1].order(), 0);
assert_eq!(scene.commands()[2].order(), 2);
let result = scene.try_extend_to_layers([
(
Layer::DEFAULT,
DrawCommand::circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
),
(
Layer::DEFAULT,
DrawCommand::circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE)).unwrap(),
),
]);
assert_eq!(
result,
Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::Commands,
limit: 4,
requested: 5,
})
);
assert_eq!(scene.command_count(), 3);
assert_eq!(scene.statistics().requested_commands(), 5);
assert_eq!(scene.statistics().accepted_commands(), 3);
assert_eq!(scene.statistics().rejected_commands(), 2);
}
#[test]
fn linear_gradient_samples_along_axis() {
let gradient = LinearGradient::new(Vec2::ZERO, Vec2::X, Color::BLACK, Color::WHITE);
let sampled = Fill::LinearGradient(gradient).color_at(Vec2::new(0.5, 4.0));
assert!((sampled.red() - 0.5).abs() < 0.001);
assert!((sampled.green() - 0.5).abs() < 0.001);
assert!((sampled.blue() - 0.5).abs() < 0.001);
}
#[test]
fn extreme_gradients_sample_without_f32_overflow() {
let gradient = LinearGradient::new(
Vec2::new(-f32::MAX, 0.0),
Vec2::new(f32::MAX, 0.0),
Color::BLACK,
Color::WHITE,
);
let mut scene = Scene::new(Color::BLACK).unwrap();
assert!(
scene
.try_circle(
Vec2::ZERO,
1.0,
ShapeStyle::filled_with(Fill::LinearGradient(gradient)),
)
.is_ok()
);
assert_eq!(
gradient.color_at(Vec2::ZERO),
Color::rgba(0.5, 0.5, 0.5, 1.0)
);
let radial = RadialGradient::new(
Vec2::splat(f32::MAX),
0.0,
f32::MAX,
Color::BLACK,
Color::WHITE,
);
assert_eq!(radial.color_at(Vec2::splat(-f32::MAX)), Color::WHITE);
}
#[test]
fn overflowing_circle_and_shadow_are_rejected_at_scene_boundary() {
let mut scene = Scene::new(Color::BLACK).unwrap();
assert_eq!(
scene.try_circle(
Vec2::splat(f32::MAX),
f32::MAX,
ShapeStyle::filled(Color::WHITE),
),
Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle))
);
assert_eq!(
scene.try_circle(
Vec2::ZERO,
1.0,
ShapeStyle::filled(Color::WHITE).with_shadow(super::Shadow::new(
LogicalScreenVector::new(0.0, 0.0),
f32::MAX,
Color::WHITE,
)),
),
Err(SceneError::InvalidShadow(ScenePrimitive::Circle))
);
assert_eq!(
scene.try_line(
Vec2::new(-f32::MAX, 0.0),
Vec2::new(f32::MAX, 0.0),
1.0,
Color::WHITE,
),
Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line))
);
assert_eq!(
scene.try_rect(
Rect::new(Vec2::new(-f32::MAX, 0.0), Vec2::new(f32::MAX, 1.0),),
0.0,
ShapeStyle::filled(Color::WHITE),
),
Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect))
);
}
#[test]
fn commands_capture_temporary_screen_clip() {
let mut scene = Scene::new(Color::BLACK).unwrap();
let outer = ScreenClipRect::from_min_size(
LogicalScreenPosition::new(10.0, 20.0),
LogicalScreenVector::new(100.0, 80.0),
)
.unwrap();
let inner = ScreenClipRect::from_min_size(
LogicalScreenPosition::new(50.0, 0.0),
LogicalScreenVector::new(100.0, 50.0),
)
.unwrap();
scene
.with_screen_clip(outer, |scene| {
scene
.with_screen_clip(inner, |scene| {
scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
})
.unwrap();
})
.unwrap();
scene.circle(Vec2::ZERO, 10.0, ShapeStyle::filled(Color::WHITE));
assert_eq!(
scene.commands[0].screen_clip,
Some(
ScreenClipRect::new(
LogicalScreenPosition::new(50.0, 20.0),
LogicalScreenPosition::new(110.0, 50.0),
)
.unwrap(),
)
);
assert_eq!(scene.commands[1].screen_clip, None);
}
#[test]
fn scene_rejects_invalid_primitives_before_ordering() {
let mut scene = Scene::new(Color::BLACK).unwrap();
assert!(!scene.circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)));
assert!(!scene.line(Vec2::ZERO, Vec2::X, f32::NAN, Color::WHITE));
assert!(!scene.polyline(vec![Vec2::ZERO], 1.0, Color::WHITE));
assert_eq!(scene.command_count(), 0);
assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
assert_eq!(scene.commands()[0].order(), 0);
}
#[test]
fn bounded_stroke_configuration_rejects_invalid_patterns_and_miters() {
assert_eq!(
StrokeDashPattern2d::new(&[1.0], 0.0, 4),
Err(StrokeStyleError::InvalidDashElementCount)
);
assert_eq!(
StrokeDashPattern2d::new(&[1.0, 0.0], 0.0, 4),
Err(StrokeStyleError::InvalidDashLength)
);
assert_eq!(
StrokeDashPattern2d::new(&[1.0, 1.0], f32::NAN, 4),
Err(StrokeStyleError::InvalidDashPhase)
);
assert_eq!(
StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, 0),
Err(StrokeStyleError::InvalidDashExpansionLimit)
);
assert_eq!(
StrokeDashPattern2d::new(&[1.0, 1.0], 0.0, MAX_STROKE_DASH_SUBSEGMENTS + 1,),
Err(StrokeStyleError::InvalidDashExpansionLimit)
);
assert_eq!(
StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
.with_miter_limit(0.5),
Err(StrokeStyleError::InvalidMiterLimit)
);
}
#[test]
fn dash_boundaries_must_be_representable_at_the_source_coordinate_scale() {
let dash =
StrokeDashPattern2d::new(&[f32::MIN_POSITIVE, f32::MIN_POSITIVE], 0.0, 8).unwrap();
let style = StrokeStyle2d::logical(LogicalPixels::new(1.0).unwrap(), Color::WHITE)
.with_dash_pattern(dash);
assert!(matches!(
DrawCommand::styled_line(Vec2::ZERO, Vec2::new(f32::MAX, 0.0), style),
Err(SceneError::UnrepresentableStrokePattern(
ScenePrimitive::Line,
))
));
}
#[test]
fn dash_expansion_is_rejected_atomically_at_the_scene_boundary() {
let dash = StrokeDashPattern2d::new(&[2.0, 2.0], 0.0, 2).unwrap();
let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
.with_cap(StrokeCap2d::Butt)
.with_dash_pattern(dash);
let mut scene = Scene::new(Color::BLACK).unwrap();
assert_eq!(
scene.try_styled_line(Vec2::ZERO, Vec2::new(10.0, 0.0), style),
Err(SceneError::StrokeExpansionLimitExceeded {
primitive: ScenePrimitive::Line,
limit: 2,
required: 3,
})
);
assert_eq!(scene.command_count(), 0);
assert_eq!(scene.statistics().requested_commands(), 1);
assert_eq!(scene.statistics().rejected_commands(), 1);
}
#[test]
fn scene_statistics_group_requested_accepted_and_rejected_primitives() {
let mut scene = Scene::new(Color::BLACK).unwrap();
scene
.try_circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE))
.unwrap();
assert_eq!(
scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
);
scene
.try_polyline(vec![Vec2::ZERO, Vec2::X], 1.0, Color::WHITE)
.unwrap();
let statistics = scene.statistics();
assert_eq!(statistics.requested_by_primitive().circles(), 1);
assert_eq!(statistics.requested_by_primitive().lines(), 1);
assert_eq!(statistics.requested_by_primitive().polylines(), 1);
assert_eq!(statistics.requested_by_primitive().total(), 3);
assert_eq!(statistics.accepted_by_primitive().circles(), 1);
assert_eq!(statistics.accepted_by_primitive().polylines(), 1);
assert_eq!(statistics.accepted_by_primitive().total(), 2);
assert_eq!(statistics.rejected_by_primitive().lines(), 1);
assert_eq!(statistics.rejected_by_primitive().total(), 1);
}
#[test]
fn rich_stroke_values_are_reusable_and_world_overflow_is_rejected() {
let marker = StrokeMarker2d::arrow(
LogicalPixels::new(8.0).unwrap(),
LogicalPixels::new(6.0).unwrap(),
);
let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE)
.with_cap(StrokeCap2d::Square)
.with_join(StrokeJoin2d::Bevel)
.with_start_marker(marker)
.with_end_marker(marker);
let command =
DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 1.0)], style)
.unwrap();
assert_eq!(command.estimated_tessellated_vertices(), 24);
let unsafe_world = StrokeStyle2d::world(WorldLength::new(f32::MAX).unwrap(), Color::WHITE);
assert!(matches!(
DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_world),
Err(SceneError::InvalidStroke(ScenePrimitive::Line))
));
let unsafe_logical =
StrokeStyle2d::logical(LogicalPixels::new(f32::MAX).unwrap(), Color::WHITE);
assert!(matches!(
DrawCommand::styled_line(Vec2::ZERO, Vec2::X, unsafe_logical),
Err(SceneError::InvalidStroke(ScenePrimitive::Line))
));
}
#[test]
fn polyline_rejects_zero_segments_and_numerically_ambiguous_turns() {
let style = StrokeStyle2d::logical(LogicalPixels::new(2.0).unwrap(), Color::WHITE);
assert!(matches!(
DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::ZERO, Vec2::X], style),
Err(SceneError::DegenerateGeometry(ScenePrimitive::Polyline))
));
assert!(matches!(
DrawCommand::styled_polyline(vec![Vec2::ZERO, Vec2::X, Vec2::ZERO], style),
Err(SceneError::DegenerateStrokeTurn {
primitive: ScenePrimitive::Polyline,
vertex_index: 1,
})
));
assert!(matches!(
DrawCommand::styled_polyline(
vec![Vec2::ZERO, Vec2::X, Vec2::new(0.0, 0.000_000_1)],
style,
),
Err(SceneError::DegenerateStrokeTurn {
primitive: ScenePrimitive::Polyline,
vertex_index: 1,
})
));
assert!(matches!(
DrawCommand::styled_polyline(
vec![Vec2::ZERO, Vec2::X, Vec2::new(2.0, 0.000_05)],
style,
),
Err(SceneError::DegenerateStrokeTurn {
primitive: ScenePrimitive::Polyline,
vertex_index: 1,
})
));
}
#[test]
fn background_and_clip_are_validated_when_created() {
assert!(matches!(
Scene::new(Color::rgba(f32::NAN, 0.0, 0.0, 1.0)),
Err(SceneError::InvalidBackground)
));
assert!(matches!(
Scene::new(Color::rgb(1.01, 0.0, 0.0)),
Err(SceneError::InvalidBackground)
));
assert_eq!(
ScreenClipRect::new(
LogicalScreenPosition::new(0.0, 0.0),
LogicalScreenPosition::new(0.0, 10.0),
),
Err(SceneError::InvalidScreenClip)
);
assert_eq!(
ScreenClipRect::new(
LogicalScreenPosition::new(f32::NAN, 0.0),
LogicalScreenPosition::new(10.0, 10.0),
),
Err(SceneError::InvalidScreenClip)
);
}
#[test]
fn render_bound_scene_colors_must_be_normalized() {
let mut scene = Scene::new(Color::BLACK).unwrap();
assert_eq!(
scene.try_circle(
Vec2::ZERO,
1.0,
ShapeStyle::filled(Color::rgb(2.0, 0.0, 0.0)),
),
Err(SceneError::InvalidFill(ScenePrimitive::Circle))
);
assert_eq!(
scene.try_line(Vec2::ZERO, Vec2::X, 1.0, Color::rgba(0.0, 0.0, 0.0, -0.01),),
Err(SceneError::InvalidStroke(ScenePrimitive::Line))
);
assert_eq!(scene.command_count(), 0);
}
#[test]
fn depth_does_not_reorder_commands_within_a_layer() {
let mut scene = Scene::new(Color::BLACK).unwrap();
scene
.with_depth(4.0, |scene| {
scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
})
.unwrap();
scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
assert_eq!(scene.commands()[0].depth(), 4.0);
assert_eq!(scene.commands()[1].depth(), 0.0);
}
#[test]
fn allocation_bytes_preserve_spare_command_capacity_after_clear() {
let mut scene = Scene::new(Color::BLACK).unwrap();
scene
.try_polyline(
vec![Vec2::ZERO, Vec2::X, Vec2::new(1.0, 1.0)],
1.0,
Color::WHITE,
)
.unwrap();
let allocated = scene.allocation_bytes();
assert!(allocated >= size_of::<SceneCommand>() + 3 * size_of::<Vec2>());
scene.clear();
assert_eq!(scene.statistics().retained_bytes(), 0);
assert_eq!(
scene.allocation_bytes(),
scene.commands.capacity() * size_of::<SceneCommand>()
);
assert!(scene.allocation_bytes() > 0);
}
#[test]
fn clone_recomputes_capacity_based_polyline_accounting() {
let mut points = Vec::with_capacity(1_024);
points.extend([Vec2::ZERO, Vec2::X]);
let mut scene = Scene::new(Color::BLACK).unwrap();
scene.try_polyline(points, 1.0, Color::WHITE).unwrap();
let cloned = scene.clone();
let actual_owned = cloned
.commands
.iter()
.map(|command| command.command.owned_allocation_bytes())
.fold(0usize, usize::saturating_add);
assert_eq!(cloned.owned_payload_bytes, actual_owned);
assert_eq!(
cloned.statistics.retained_bytes(),
cloned
.commands
.len()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(actual_owned)
);
assert_eq!(
cloned.allocation_bytes(),
cloned
.commands
.capacity()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(actual_owned)
);
}
#[test]
fn structured_scene_errors_preserve_rejection_reason() {
let mut scene = Scene::new(Color::BLACK).unwrap();
assert_eq!(
scene.try_circle(Vec2::ZERO, -1.0, ShapeStyle::filled(Color::WHITE)),
Err(SceneError::InvalidDimension(ScenePrimitive::Circle))
);
assert_eq!(
scene.try_line(Vec2::ZERO, Vec2::ZERO, 1.0, Color::WHITE),
Err(SceneError::DegenerateGeometry(ScenePrimitive::Line))
);
assert_eq!(
scene.try_circle(
Vec2::ZERO,
1.0,
ShapeStyle {
fill: None,
stroke: None,
shadow: None,
},
),
Err(SceneError::MissingStyle(ScenePrimitive::Circle))
);
assert_eq!(scene.command_count(), 0);
}
#[test]
fn commands_capture_depth_and_restore_it_after_unwind() {
let mut scene = Scene::new(Color::BLACK).unwrap();
let panic_result = catch_unwind(AssertUnwindSafe(|| {
let _ = scene.with_depth(4.5, |scene| {
scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE));
panic!("intentional depth unwind");
});
}));
assert!(panic_result.is_err());
scene.circle(Vec2::X, 1.0, ShapeStyle::filled(Color::WHITE));
assert_eq!(scene.commands()[0].depth(), 4.5);
assert_eq!(scene.commands()[1].depth(), 0.0);
assert_eq!(
scene.with_depth(f32::NAN, |_| {}),
Err(SceneError::NonFiniteDepth)
);
}
#[test]
fn gradients_sanitize_invalid_and_reversed_configuration() {
let invalid_linear = LinearGradient::new(
Vec2::new(f32::NAN, 0.0),
Vec2::X,
Color::BLACK,
Color::WHITE,
);
assert_eq!(invalid_linear.color_at(Vec2::ZERO), Color::WHITE);
let reversed = RadialGradient::new(Vec2::ZERO, 10.0, 5.0, Color::WHITE, Color::BLACK);
assert_eq!(reversed.inner_radius(), 5.0);
assert_eq!(reversed.outer_radius(), 10.0);
assert_eq!(reversed.color_at(Vec2::ZERO), Color::BLACK);
}
#[test]
fn tiny_nonzero_radial_range_preserves_both_color_endpoints() {
let gradient =
RadialGradient::new(Vec2::ZERO, 0.0, 0.000_000_01, Color::BLACK, Color::WHITE);
assert_eq!(gradient.color_at(Vec2::ZERO), Color::BLACK);
assert_eq!(
gradient.color_at(Vec2::new(0.000_000_01, 0.0)),
Color::WHITE
);
}
#[test]
fn temporary_screen_clip_restores_state_after_unwind() {
let mut scene = Scene::new(Color::BLACK).unwrap();
let clip = ScreenClipRect::from_min_size(
LogicalScreenPosition::new(0.0, 0.0),
LogicalScreenVector::new(100.0, 100.0),
)
.unwrap();
let panic_result = catch_unwind(AssertUnwindSafe(|| {
let _ = scene.with_screen_clip(clip, |_| panic!("intentional test panic"));
}));
assert!(panic_result.is_err());
assert!(scene.circle(Vec2::ZERO, 1.0, ShapeStyle::filled(Color::WHITE)));
assert_eq!(scene.commands()[0].screen_clip(), None);
}
}