1use crate::{Camera3D, Vec3, retained::Command};
4pub use ferravex_play::particles::{
5 BeamPool, ParticlePool, ParticleView, RibbonFacing, RibbonPoint, RibbonSource, RibbonTriangle,
6 RibbonTriangles, RibbonVertex, Trail,
7};
8pub const MAX_EFFECT_VERTICES: usize = 196608;
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub enum EffectBlend {
11 #[default]
12 Alpha,
13 Additive,
14}
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub struct EffectStyle {
17 pub blend: EffectBlend,
18 pub depth_test: Option<bool>,
20 pub depth_write: bool,
22}
23#[repr(C)]
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub struct EffectBatch {
26 pub start: u32,
27 pub count: u32,
28 pub flags: u32,
29}
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub struct DrawReport {
32 pub triangles: u32,
33 pub invalid: u32,
34 pub dropped_samples: u32,
35 pub culled_samples: u32,
36 pub truncated: bool,
37}
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub struct EffectStats {
40 pub vertices: u32,
41 pub processed_triangles: u32,
42 pub invalid_triangles: u32,
43 pub truncated_calls: u32,
44 pub instanced_vertices: u32,
45 pub culled_sprites: u32,
46}
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum EffectError {
49 InvalidView,
50 InvalidStyle,
51 InvalidParticle,
52 InvalidCapacity,
53 Ribbon(ferravex_play::particles::RibbonError),
54}
55impl From<ferravex_play::particles::RibbonError> for EffectError {
56 fn from(error: ferravex_play::particles::RibbonError) -> Self {
57 Self::Ribbon(error)
58 }
59}
60pub fn stats() -> EffectStats {
61 crate::read(|s| s.effect_stats)
62}
63pub fn draw_triangles(
67 triangles: impl IntoIterator<Item = RibbonTriangle>,
68 style: EffectStyle,
69) -> DrawReport {
70 write_triangles(style, |writer| {
71 for triangle in triangles {
72 if !writer.push(triangle.vertices.map(|v| (v.position, v.color))) {
74 break;
75 }
76 }
77 })
78}
79
80pub(crate) fn write_triangles(
83 style: EffectStyle,
84 emit: impl FnOnce(&mut TriangleWriter),
85) -> DrawReport {
86 crate::edit(|s| {
87 let mut writer = TriangleWriter {
88 start: s.vertices.len() as u32,
89 s,
90 report: DrawReport::default(),
91 };
92 emit(&mut writer);
93 writer.finish(style)
94 })
95}
96
97pub(crate) struct TriangleWriter<'s> {
100 s: &'s mut crate::State,
101 start: u32,
102 report: DrawReport,
103}
104
105impl TriangleWriter<'_> {
106 #[inline]
110 pub(crate) fn push(&mut self, triangle: [([f32; 3], [f32; 4]); 3]) -> bool {
111 let s = &mut *self.s;
112 if s.effect_stats.processed_triangles as usize >= MAX_EFFECT_VERTICES / 3 {
113 if !self.report.truncated {
114 self.report.truncated = true;
115 s.effect_stats.truncated_calls = s.effect_stats.truncated_calls.saturating_add(1);
116 }
117 return false;
118 }
119 s.effect_stats.processed_triangles += 1;
120 let mut projected = [[0.; 8]; 3];
121 for (out, (position, color)) in projected.iter_mut().zip(triangle) {
122 let p = s.matrix * Vec3::from_array(position).extend(1.);
125 if !(p.is_finite() && color.iter().all(|c| c.is_finite())) {
126 self.report.invalid += 1;
127 return true;
128 }
129 *out = [
130 p.x,
131 p.y,
132 p.z,
133 p.w,
134 color[0].clamp(0., 1.),
135 color[1].clamp(0., 1.),
136 color[2].clamp(0., 1.),
137 color[3].clamp(0., 1.),
138 ];
139 }
140 s.vertices.extend_from_slice(&projected);
141 self.report.triangles += 1;
142 true
143 }
144 fn finish(self, style: EffectStyle) -> DrawReport {
145 let Self { s, start, report } = self;
146 s.effect_stats.invalid_triangles = s
147 .effect_stats
148 .invalid_triangles
149 .saturating_add(report.invalid);
150 let count = report.triangles * 3;
151 s.effect_stats.vertices += count;
152 if count > 0 {
153 let depth = style.depth_test.unwrap_or(s.depth);
154 let flags = depth as u32
155 | if style.depth_write { 0 } else { 2 }
156 | if style.blend == EffectBlend::Additive {
157 4
158 } else {
159 0
160 };
161 if style.blend == EffectBlend::Alpha && (!depth || style.depth_write) {
162 s.record_immediate(start, count, depth);
165 } else if let Some(last) = s.retained.effects.last_mut().filter(|b| {
166 b.flags == flags && s.retained.commands.last().is_some_and(|c| c.kind == 2)
167 }) {
168 last.count += count;
169 } else {
170 s.retained.commands.push(Command {
171 kind: 2,
172 index: s.retained.effects.len() as u32,
173 });
174 s.retained.effects.push(EffectBatch {
175 start,
176 count,
177 flags,
178 });
179 }
180 }
181 report
182 }
183}
184#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct BillboardView {
186 pub eye: Vec3,
187 pub right: Vec3,
188 pub up: Vec3,
189}
190impl BillboardView {
191 pub fn new(eye: Vec3, right: Vec3, up: Vec3) -> Result<Self, EffectError> {
192 if !eye.is_finite() {
193 return Err(EffectError::InvalidView);
194 }
195 let right = right.try_normalize().ok_or(EffectError::InvalidView)?;
196 let up = (up - right * up.dot(right))
197 .try_normalize()
198 .ok_or(EffectError::InvalidView)?;
199 Ok(Self { eye, right, up })
200 }
201 pub fn from_camera(camera: &Camera3D) -> Result<Self, EffectError> {
202 let forward = (camera.target - camera.position)
203 .try_normalize()
204 .ok_or(EffectError::InvalidView)?;
205 let right = forward.cross(camera.up);
206 Self::new(camera.position, right, camera.up)
207 }
208 fn normalized(self) -> Result<Self, EffectError> {
209 Self::new(self.eye, self.right, self.up)
210 }
211 fn depth(self, position: [f32; 3]) -> f32 {
212 (Vec3::from_array(position) - self.eye).dot(-self.right.cross(self.up))
213 }
214}
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
216pub enum ParticleShape {
217 Square,
218 #[default]
219 Diamond,
220 Triangle,
221}
222#[derive(Clone, Copy, Debug, PartialEq)]
223pub struct ParticleStyle {
224 pub draw: EffectStyle,
225 pub shape: ParticleShape,
226 pub stretch: f32,
228 pub max_stretch: f32,
229 pub sort_back_to_front: bool,
230}
231impl Default for ParticleStyle {
232 fn default() -> Self {
233 Self {
234 draw: EffectStyle::default(),
235 shape: ParticleShape::Diamond,
236 stretch: 0.,
237 max_stretch: 8.,
238 sort_back_to_front: true,
239 }
240 }
241}
242impl ParticleStyle {
243 fn validate(self) -> Result<Self, EffectError> {
244 if !self.stretch.is_finite()
245 || !(0.0..=100.).contains(&self.stretch)
246 || !self.max_stretch.is_finite()
247 || !(1.0..=32.).contains(&self.max_stretch)
248 {
249 Err(EffectError::InvalidStyle)
250 } else {
251 Ok(self)
252 }
253 }
254}
255#[derive(Clone, Copy)]
256struct Entry {
257 particle: ParticleView,
258 depth: f32,
259 order: u32,
260}
261pub struct ParticleRenderer {
265 scratch: Vec<Entry>,
266 capacity: usize,
267}
268impl ParticleRenderer {
269 pub fn new(capacity: usize) -> Result<Self, EffectError> {
270 if capacity > ferravex_play::particles::MAX_PARTICLES {
271 return Err(EffectError::InvalidCapacity);
272 }
273 Ok(Self {
274 scratch: Vec::with_capacity(capacity),
275 capacity,
276 })
277 }
278 pub fn capacity(&self) -> usize {
279 self.capacity
280 }
281 pub fn draw_2d(
282 &mut self,
283 pool: &ParticlePool,
284 style: ParticleStyle,
285 ) -> Result<DrawReport, EffectError> {
286 let style = style.validate()?;
287 self.prepare(pool, None, false);
288 let view = BillboardView {
289 eye: Vec3::Z,
290 right: Vec3::X,
291 up: Vec3::Y,
292 };
293 Ok(self.draw_prepared(pool, view, style))
294 }
295 pub fn draw_3d(
296 &mut self,
297 pool: &ParticlePool,
298 view: BillboardView,
299 style: ParticleStyle,
300 ) -> Result<DrawReport, EffectError> {
301 let style = style.validate()?;
302 let view = view.normalized()?;
303 self.prepare(
304 pool,
305 Some(view),
306 style.sort_back_to_front && style.draw.blend == EffectBlend::Alpha,
307 );
308 Ok(self.draw_prepared(pool, view, style))
309 }
310 fn prepare(&mut self, pool: &ParticlePool, view: Option<BillboardView>, sort: bool) {
311 self.scratch.clear();
312 self.scratch.extend(
313 pool.iter()
314 .take(self.capacity)
315 .enumerate()
316 .map(|(i, particle)| Entry {
317 depth: view.map_or(0., |v| v.depth(particle.position)),
318 particle,
319 order: i as u32,
320 }),
321 );
322 if sort {
323 self.scratch.sort_unstable_by(|a, b| {
324 b.depth
325 .total_cmp(&a.depth)
326 .then_with(|| a.order.cmp(&b.order))
327 });
328 }
329 }
330 fn draw_prepared(
331 &self,
332 pool: &ParticlePool,
333 view: BillboardView,
334 style: ParticleStyle,
335 ) -> DrawReport {
336 let mut report = crate::edit(|s| {
337 let mut report = DrawReport::default();
338 let triangles = if style.shape == ParticleShape::Triangle {
339 1
340 } else {
341 2
342 };
343 let depth = style.draw.depth_test.unwrap_or(s.depth);
344 let flags = depth as u32
345 | if style.draw.depth_write { 0 } else { 2 }
346 | if style.draw.blend == EffectBlend::Additive {
347 4
348 } else {
349 0
350 };
351 for entry in &self.scratch {
352 if s.effect_stats.processed_triangles as usize + triangles > MAX_EFFECT_VERTICES / 3
353 {
354 report.truncated = true;
355 s.effect_stats.truncated_calls =
356 s.effect_stats.truncated_calls.saturating_add(1);
357 break;
358 }
359 s.effect_stats.processed_triangles += triangles as u32;
360 let p = entry.particle;
361 let (mut right, mut up) = sprite_axes(p, view, style);
362 if style.shape == ParticleShape::Diamond {
363 let r = (right + up) * 0.5;
364 up = (up - right) * 0.5;
365 right = r;
366 }
367 let center = s.matrix * Vec3::from_array(p.position).extend(1.);
368 let right = s.matrix * right.extend(0.);
369 let up = s.matrix * up.extend(0.);
370 if !center.is_finite() || !right.is_finite() || !up.is_finite() {
371 report.invalid += triangles as u32;
372 continue;
373 }
374 if outside_clip(center.to_array(), right.to_array(), up.to_array()) {
375 report.culled_samples += 1;
376 continue;
377 }
378 let mut instance = [0.; 16];
379 instance[..4].copy_from_slice(¢er.to_array());
380 instance[4..8].copy_from_slice(&right.to_array());
381 instance[8..12].copy_from_slice(&up.to_array());
382 instance[12..].copy_from_slice(&p.color.map(|v| v.clamp(0., 1.)));
383 let first = s.retained.sprites.len() as u32;
384 if let Some(last) = s.retained.sprite_batches.last_mut().filter(|b| {
385 b.flags == flags
386 && b.triangles == triangles as u32
387 && s.retained.commands.last().is_some_and(|c| c.kind == 3)
388 }) {
389 last.count += 1;
390 } else {
391 s.retained.commands.push(Command {
392 kind: 3,
393 index: s.retained.sprite_batches.len() as u32,
394 });
395 s.retained.sprite_batches.push(SpriteBatch {
396 first,
397 count: 1,
398 flags,
399 triangles: triangles as u32,
400 });
401 }
402 s.retained.sprites.push(instance);
403 report.triangles += triangles as u32;
404 }
405 s.effect_stats.invalid_triangles = s
406 .effect_stats
407 .invalid_triangles
408 .saturating_add(report.invalid);
409 s.effect_stats.culled_sprites = s
410 .effect_stats
411 .culled_sprites
412 .saturating_add(report.culled_samples);
413 s.effect_stats.vertices += report.triangles * 3;
414 s.effect_stats.instanced_vertices += report.triangles * 3;
415 report
416 });
417 report.dropped_samples = pool.len().saturating_sub(self.scratch.len()) as u32;
418 report
419 }
420}
421fn outside_clip(center: [f32; 4], right: [f32; 4], up: [f32; 4]) -> bool {
422 let epsilon = center
423 .into_iter()
424 .chain(right)
425 .chain(up)
426 .map(|v| f64::from(v).abs())
427 .fold(1., f64::max)
428 * 1e-6;
429 for axis in 0..3 {
430 for sign in [-1., 1.] {
431 let plane = |v: [f32; 4]| f64::from(v[3]) + sign * f64::from(v[axis]);
432 if plane(center) + plane(right).abs() + plane(up).abs() < -epsilon {
433 return true;
434 }
435 }
436 }
437 false
438}
439fn sprite_axes(p: ParticleView, view: BillboardView, style: ParticleStyle) -> (Vec3, Vec3) {
440 let mut right = view.right;
441 let mut up = view.up;
442 let mut stretch = 1.;
443 if style.stretch > 0. {
444 let v = Vec3::from_array(p.velocity);
445 let x = v.dot(right);
446 let y = v.dot(up);
447 let speed = x.hypot(y);
448 if speed > 0.0001 {
449 right = (right * x + up * y) / speed;
450 up = view.right.cross(view.up).cross(right);
451 stretch = (1. + speed * style.stretch).min(style.max_stretch);
452 }
453 }
454 let (sin, cos) = p.rotation.sin_cos();
455 let r = (right * cos + up * sin) * (p.size * 0.5 * stretch);
456 let u = (up * cos - right * sin) * (p.size * 0.5);
457 (r, u)
458}
459
460pub fn particle_triangles(
462 p: ParticleView,
463 view: BillboardView,
464 style: ParticleStyle,
465) -> Result<[Option<RibbonTriangle>; 2], EffectError> {
466 if !p
467 .position
468 .into_iter()
469 .chain(p.velocity)
470 .chain(p.color)
471 .chain([p.size, p.rotation, p.normalized_age])
472 .all(f32::is_finite)
473 || p.size < 0.
474 || !(0.0..=1.).contains(&p.normalized_age)
475 {
476 return Err(EffectError::InvalidParticle);
477 }
478 let style = style.validate()?;
479 let view = view.normalized()?;
480 let (r, u) = sprite_axes(p, view, style);
481 let center = Vec3::from_array(p.position);
482 let vertex = |position: Vec3, uv| RibbonVertex {
483 position: position.to_array(),
484 color: p.color,
485 uv,
486 };
487 if style.shape == ParticleShape::Triangle {
488 return Ok([
489 Some(RibbonTriangle {
490 vertices: [
491 vertex(center + u, [0.5, 1.]),
492 vertex(center - r - u, [0., 0.]),
493 vertex(center + r - u, [1., 0.]),
494 ],
495 }),
496 None,
497 ]);
498 }
499 let points = if style.shape == ParticleShape::Diamond {
500 [center - r, center + u, center - u, center + r]
501 } else {
502 [
503 center - r + u,
504 center - r - u,
505 center + r + u,
506 center + r - u,
507 ]
508 };
509 let v = [
510 vertex(points[0], [0., 0.]),
511 vertex(points[1], [0., 1.]),
512 vertex(points[2], [1., 0.]),
513 vertex(points[3], [1., 1.]),
514 ];
515 Ok([
516 Some(RibbonTriangle {
517 vertices: [v[0], v[1], v[2]],
518 }),
519 Some(RibbonTriangle {
520 vertices: [v[2], v[1], v[3]],
521 }),
522 ])
523}
524pub fn draw_ribbon<S: RibbonSource + ?Sized>(
525 source: &S,
526 facing: RibbonFacing,
527 miter_limit: f32,
528 style: EffectStyle,
529) -> Result<DrawReport, EffectError> {
530 Ok(draw_triangles(
531 RibbonTriangles::new(source, facing, miter_limit)?,
532 style,
533 ))
534}
535pub fn draw_beams(
536 beams: &BeamPool,
537 facing: RibbonFacing,
538 style: EffectStyle,
539) -> Result<DrawReport, EffectError> {
540 RibbonTriangles::new(&[] as &[RibbonPoint], facing, 1.)?;
541 let triangles = beams.iter().flat_map(|beam| {
542 let points = beam.points();
543 let mut mesh = RibbonTriangles::new(&points, facing, 1.).expect("validated beam facing");
544 [mesh.next(), mesh.next()].into_iter().flatten()
545 });
546 Ok(draw_triangles(triangles, style))
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552 use ferravex_play::particles::ParticleDesc;
553 fn triangle() -> RibbonTriangle {
554 RibbonTriangle {
555 vertices: [
556 RibbonVertex {
557 position: [0., 0., 0.],
558 color: [1.; 4],
559 uv: [0.; 2],
560 },
561 RibbonVertex {
562 position: [10., 0., 0.],
563 color: [1.; 4],
564 uv: [0.; 2],
565 },
566 RibbonVertex {
567 position: [0., 10., 0.],
568 color: [1.; 4],
569 uv: [0.; 2],
570 },
571 ],
572 }
573 }
574 #[test]
575 fn alpha_2d_shares_geometry_but_additive_and_following_hud_preserve_order() {
576 crate::input::host_frame(1. / 60., 960, 600, || {
577 crate::clear_background(crate::BLACK);
578 crate::draw_triangle(
579 crate::Vec2::ZERO,
580 crate::Vec2::X,
581 crate::Vec2::Y,
582 crate::WHITE,
583 );
584 assert_eq!(
585 draw_triangles([triangle()], EffectStyle::default()).triangles,
586 1
587 );
588 assert_eq!(
589 draw_triangles(
590 [triangle()],
591 EffectStyle {
592 blend: EffectBlend::Additive,
593 ..Default::default()
594 }
595 )
596 .triangles,
597 1
598 );
599 crate::draw_triangle(
600 crate::Vec2::ZERO,
601 crate::Vec2::X,
602 crate::Vec2::Y,
603 crate::GREEN,
604 );
605 });
606 crate::read(|s| {
607 assert_eq!(
608 s.retained
609 .commands
610 .iter()
611 .map(|c| c.kind)
612 .collect::<Vec<_>>(),
613 [0, 2, 0]
614 );
615 assert_eq!(s.batches[0].count, 6);
616 assert_eq!(s.retained.effects[0].flags, 6);
617 assert_eq!(s.effect_stats.vertices, 6);
618 });
619 assert_eq!(std::mem::size_of::<EffectBatch>(), 12);
620 }
621 #[test]
622 fn sprite_culling_is_conservative_at_clip_edges_and_keeps_simulation_alive() {
623 let mut pool = ParticlePool::new(3);
624 for x in [0., 1.1, 100.] {
625 pool.spawn(ParticleDesc {
626 position: [x, 0., 0.],
627 start_size: 0.4,
628 ..Default::default()
629 })
630 .unwrap();
631 }
632 let mut renderer = ParticleRenderer::new(3).unwrap();
633 crate::input::host_frame(1. / 60., 960, 600, || {
634 crate::edit(|s| s.matrix = crate::Mat4::IDENTITY);
635 let report = renderer.draw_2d(&pool, ParticleStyle::default()).unwrap();
636 assert_eq!(report.culled_samples, 1);
637 assert_eq!(report.triangles, 4);
638 });
639 assert_eq!(pool.len(), 3);
640 assert_eq!(stats().culled_sprites, 1);
641 }
642 #[test]
643 fn malformed_triangles_and_frame_budget_cannot_poison_or_grow_the_stream() {
644 crate::input::host_frame(1. / 60., 960, 600, || {
645 let mut bad = triangle();
646 bad.vertices[0].position[0] = f32::NAN;
647 let r = draw_triangles([bad, triangle()], EffectStyle::default());
648 assert_eq!(r.invalid, 1);
649 assert_eq!(r.triangles, 1);
650 let r = draw_triangles(
651 std::iter::repeat_n(triangle(), MAX_EFFECT_VERTICES),
652 EffectStyle::default(),
653 );
654 assert!(r.truncated);
655 assert!(draw_triangles([triangle()], EffectStyle::default()).truncated);
656 });
657 crate::read(|s| {
658 assert_eq!(
659 s.effect_stats.processed_triangles as usize,
660 MAX_EFFECT_VERTICES / 3
661 );
662 assert_eq!(s.vertices.len(), MAX_EFFECT_VERTICES - 3);
663 assert!(s.vertices.iter().flatten().all(|v| v.is_finite()));
664 });
665 }
666 #[test]
667 fn alpha_billboards_sort_by_camera_depth_and_report_scratch_overflow() {
668 let mut pool = ParticlePool::new(3);
669 for (z, color) in [
670 (2., [0., 1., 0., 0.5]),
671 (0., [1., 0., 0., 0.5]),
672 (1., [0., 0., 1., 0.5]),
673 ] {
674 pool.spawn(ParticleDesc {
675 position: [0., 0., z],
676 start_color: color,
677 ..Default::default()
678 })
679 .unwrap();
680 }
681 let mut renderer = ParticleRenderer::new(2).unwrap();
682 crate::input::host_frame(1. / 60., 960, 600, || {
683 crate::edit(|s| s.matrix = crate::Mat4::from_scale(Vec3::new(1., 1., 0.1)));
684 let r = renderer
685 .draw_3d(
686 &pool,
687 BillboardView::new(Vec3::new(0., 0., 5.), Vec3::X, Vec3::Y).unwrap(),
688 ParticleStyle::default(),
689 )
690 .unwrap();
691 assert_eq!(r.triangles, 4);
692 assert_eq!(r.dropped_samples, 1);
693 });
694 crate::read(|s| {
695 assert_eq!(&s.retained.sprites[0][12..], [1., 0., 0., 0.5]);
696 assert_eq!(&s.retained.sprites[1][12..], [0., 1., 0., 0.5]);
697 });
698 assert!(BillboardView::new(Vec3::ZERO, Vec3::X, Vec3::X).is_err());
699 assert!(
700 renderer
701 .draw_2d(
702 &pool,
703 ParticleStyle {
704 stretch: f32::NAN,
705 ..Default::default()
706 }
707 )
708 .is_err()
709 );
710 }
711}
712
713#[repr(C)]
715#[derive(Clone, Copy, Debug, PartialEq, Eq)]
716pub struct SpriteBatch {
717 pub first: u32,
718 pub count: u32,
719 pub flags: u32,
720 pub triangles: u32,
721}
722pub const SPRITE_VERTEX_BODY: &str = r#"
723attribute vec2 a_corner;
724attribute vec4 a_center;
725attribute vec4 a_right;
726attribute vec4 a_up;
727attribute vec4 a_tint;
728varying vec4 v_color;
729void main(){gl_Position=a_center+a_right*a_corner.x+a_up*a_corner.y;v_color=a_tint;}
730"#;
731pub const SPRITE_FRAGMENT_BODY: &str = r#"
732varying vec4 v_color;
733void main(){gl_FragColor=v_color;}
734"#;