1use ferravex_math::{Quat, Vec3};
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum BuildError {
9 Invalid,
10 Capacity,
11}
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct BoxPiece {
14 pub center: Vec3,
15 pub half_extents: Vec3,
16 pub rotation: Quat,
17 pub material: u16,
18}
19impl BoxPiece {
20 pub fn bounds(self) -> (Vec3, Vec3) {
21 let h = (self.rotation * Vec3::X).abs() * self.half_extents.x
22 + (self.rotation * Vec3::Y).abs() * self.half_extents.y
23 + (self.rotation * Vec3::Z).abs() * self.half_extents.z;
24 (self.center - h, self.center + h)
25 }
26}
27#[derive(Clone, Debug)]
50pub struct EnvironmentPlan {
51 pieces: Vec<BoxPiece>,
52 capacity: usize,
53}
54fn dimension(v: f32) -> bool {
55 v.is_finite() && (0.001..=1000.).contains(&v)
56}
57impl EnvironmentPlan {
58 pub fn new(capacity: usize) -> Result<Self, BuildError> {
59 if capacity == 0 || capacity > 1024 {
60 return Err(BuildError::Capacity);
61 }
62 Ok(Self {
63 pieces: Vec::with_capacity(capacity),
64 capacity,
65 })
66 }
67 pub fn pieces(&self) -> &[BoxPiece] {
68 &self.pieces
69 }
70
71 pub fn piece_count(&self) -> usize {
73 self.pieces.len()
74 }
75
76 pub fn capacity(&self) -> usize {
78 self.capacity
79 }
80
81 pub fn remaining_capacity(&self) -> usize {
83 self.capacity - self.piece_count()
84 }
85
86 pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
89 let mut pieces = self.pieces.iter();
90 let first = pieces.next()?.bounds();
91 Some(pieces.fold(first, |(min, max), piece| {
92 let (piece_min, piece_max) = piece.bounds();
93 (min.min(piece_min), max.max(piece_max))
94 }))
95 }
96
97 pub fn stairs_piece_count(count: u16) -> Result<usize, BuildError> {
100 if !(1..=128).contains(&count) {
101 return Err(BuildError::Invalid);
102 }
103 Ok(usize::from(count))
104 }
105
106 pub fn bridge_piece_count(segments: u16) -> Result<usize, BuildError> {
110 if !(1..=128).contains(&segments) {
111 return Err(BuildError::Invalid);
112 }
113 Ok(3 + 2 * (usize::from(segments) + 1))
114 }
115
116 pub fn append_atomic(
151 &mut self,
152 build: impl FnOnce(&mut Self) -> Result<(), BuildError>,
153 ) -> Result<(), BuildError> {
154 let remaining = self.remaining_capacity();
155 let mut group = Self {
156 pieces: Vec::with_capacity(remaining),
157 capacity: remaining,
158 };
159 build(&mut group)?;
160 if group.piece_count() > remaining {
161 return Err(BuildError::Capacity);
162 }
163 self.pieces.extend_from_slice(group.pieces());
164 Ok(())
165 }
166
167 fn validate(&self, origin: Vec3, dimensions: &[f32], count: usize) -> Result<(), BuildError> {
168 if !origin.is_finite()
169 || origin.abs().max_element() > 100000.
170 || !dimensions.iter().all(|v| dimension(*v))
171 {
172 return Err(BuildError::Invalid);
173 }
174 if count > self.remaining_capacity() {
175 return Err(BuildError::Capacity);
176 }
177 Ok(())
178 }
179 pub fn stairs(
181 &mut self,
182 origin: Vec3,
183 width: f32,
184 rise: f32,
185 run: f32,
186 count: u16,
187 material: u16,
188 ) -> Result<(), BuildError> {
189 let pieces = Self::stairs_piece_count(count)?;
190 self.validate(origin, &[width, rise, run], pieces)?;
191 for i in 0..count {
192 let h = rise * f32::from(i + 1);
193 self.pieces.push(BoxPiece {
194 center: origin + Vec3::new(0., h * 0.5, (f32::from(i) + 0.5) * run),
195 half_extents: Vec3::new(width * 0.5, h * 0.5, run * 0.5),
196 rotation: Quat::IDENTITY,
197 material,
198 });
199 }
200 Ok(())
201 }
202 pub fn ramp(
204 &mut self,
205 origin: Vec3,
206 width: f32,
207 rise: f32,
208 run: f32,
209 thickness: f32,
210 material: u16,
211 ) -> Result<(), BuildError> {
212 self.validate(origin, &[width, rise, run, thickness], 1)?;
213 self.pieces.push(BoxPiece {
214 center: origin + Vec3::new(0., rise * 0.5, run * 0.5),
215 half_extents: Vec3::new(width * 0.5, thickness * 0.5, rise.hypot(run) * 0.5),
216 rotation: Quat::from_rotation_x(-rise.atan2(run)),
217 material,
218 });
219 Ok(())
220 }
221 pub fn bridge(
224 &mut self,
225 origin: Vec3,
226 width: f32,
227 length: f32,
228 height: f32,
229 segments: u16,
230 material: u16,
231 ) -> Result<(), BuildError> {
232 let count = Self::bridge_piece_count(segments)?;
233 self.validate(origin, &[width, length, height], count)?;
234 self.pieces.push(BoxPiece {
235 center: origin + Vec3::new(0., height, 0.),
236 half_extents: Vec3::new(width * 0.5, 0.12, length * 0.5),
237 rotation: Quat::IDENTITY,
238 material,
239 });
240 for side in [-1., 1.] {
241 let x = side * width * 0.5;
242 self.pieces.push(BoxPiece {
243 center: origin + Vec3::new(x, height + 0.9, 0.),
244 half_extents: Vec3::new(0.06, 0.06, length * 0.5),
245 rotation: Quat::IDENTITY,
246 material,
247 });
248 for i in 0..=segments {
249 self.pieces.push(BoxPiece {
250 center: origin
251 + Vec3::new(
252 x,
253 (height + 1.) * 0.5,
254 (f32::from(i) / f32::from(segments) - 0.5) * length,
255 ),
256 half_extents: Vec3::new(0.07, (height + 1.) * 0.5, 0.07),
257 rotation: Quat::IDENTITY,
258 material,
259 });
260 }
261 }
262 Ok(())
263 }
264}
265#[cfg(test)]
266mod tests {
267 use super::*;
268 #[test]
269 fn stairs_and_ramp_have_matching_authored_endpoints() {
270 let mut p = EnvironmentPlan::new(16).unwrap();
271 p.stairs(Vec3::ZERO, 2., 0.2, 0.5, 6, 0).unwrap();
272 assert!((p.pieces()[5].bounds().1.y - 1.2).abs() < 1e-6);
273 p.ramp(Vec3::ZERO, 2., 1.2, 3., 0.2, 1).unwrap();
274 let r = p.pieces()[6];
275 let axis = r.rotation * Vec3::Z * r.half_extents.z;
276 assert!((r.center - axis).length() < 1e-5);
277 assert!((r.center + axis - Vec3::new(0., 1.2, 3.)).length() < 1e-5);
278 }
279 #[test]
280 fn rejected_builds_are_transactional_and_plans_repeat() {
281 let mut p = EnvironmentPlan::new(5).unwrap();
282 p.stairs(Vec3::ZERO, 2., 0.2, 0.5, 3, 0).unwrap();
283 let old = p.pieces().to_vec();
284 assert_eq!(
285 p.bridge(Vec3::ZERO, 2., 3., 1., 2, 0),
286 Err(BuildError::Capacity)
287 );
288 assert_eq!(p.pieces(), old);
289 assert_eq!(
290 p.ramp(Vec3::ZERO, 2., f32::NAN, 3., 0.2, 0),
291 Err(BuildError::Invalid)
292 );
293 assert_eq!(p.pieces(), old);
294 }
295
296 #[test]
297 fn checked_counts_match_builders_at_exact_capacity() {
298 for count in [1, 2, 64, 128] {
299 let stairs = EnvironmentPlan::stairs_piece_count(count).unwrap();
300 assert_eq!(stairs, usize::from(count));
301 let mut plan = EnvironmentPlan::new(stairs).unwrap();
302 plan.stairs(Vec3::ZERO, 2., 0.25, 0.5, count, 17).unwrap();
303 assert_eq!(plan.piece_count(), stairs);
304 assert_eq!(plan.remaining_capacity(), 0);
305 assert!(plan.pieces().iter().all(|piece| piece.material == 17));
306
307 let bridge = EnvironmentPlan::bridge_piece_count(count).unwrap();
308 assert_eq!(bridge, 5 + 2 * usize::from(count));
309 let mut plan = EnvironmentPlan::new(bridge).unwrap();
310 plan.bridge(Vec3::ZERO, 2., 4., 1., count, 23).unwrap();
311 assert_eq!(plan.piece_count(), bridge);
312 assert_eq!(plan.remaining_capacity(), 0);
313 assert!(plan.pieces().iter().all(|piece| piece.material == 23));
314 }
315 for count in [0, 129, u16::MAX] {
316 assert_eq!(
317 EnvironmentPlan::stairs_piece_count(count),
318 Err(BuildError::Invalid)
319 );
320 assert_eq!(
321 EnvironmentPlan::bridge_piece_count(count),
322 Err(BuildError::Invalid)
323 );
324 }
325 }
326
327 type Build = fn(&mut EnvironmentPlan) -> Result<(), BuildError>;
328
329 #[test]
330 fn every_builder_rejects_capacity_without_changing_existing_geometry() {
331 let builds: [Build; 3] = [
332 |p| p.stairs(Vec3::ZERO, 2., 0.25, 0.5, 1, 0),
333 |p| p.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 0),
334 |p| p.bridge(Vec3::ZERO, 2., 4., 1., 1, 0),
335 ];
336 let mut plan = EnvironmentPlan::new(1).unwrap();
337 plan.ramp(Vec3::Y, 2., 1., 3., 0.2, 19).unwrap();
338 let before = plan.pieces().to_vec();
339 let bounds = plan.bounds();
340 for build in builds {
341 assert_eq!(build(&mut plan), Err(BuildError::Capacity));
342 assert_eq!(plan.pieces(), before);
343 assert_eq!(plan.bounds(), bounds);
344 assert_eq!((plan.capacity(), plan.remaining_capacity()), (1, 0));
345 }
346 }
347
348 #[test]
349 fn invalid_geometry_and_counts_take_precedence_even_when_full() {
350 let builds: [Build; 9] = [
351 |p| p.stairs(Vec3::ZERO, 0., 0.25, 0.5, 1, 0),
352 |p| p.stairs(Vec3::ZERO, 2., 0.25, 0.5, 129, 0),
353 |p| p.stairs(Vec3::splat(f32::NAN), 2., 0.25, 0.5, 1, 0),
354 |p| p.ramp(Vec3::ZERO, 2., -1., 3., 0.2, 0),
355 |p| p.ramp(Vec3::ZERO, 2., 1., 3., f32::INFINITY, 0),
356 |p| p.ramp(Vec3::splat(100001.), 2., 1., 3., 0.2, 0),
357 |p| p.bridge(Vec3::ZERO, 2., 1001., 1., 1, 0),
358 |p| p.bridge(Vec3::ZERO, 2., 4., 1., 0, 0),
359 |p| p.bridge(Vec3::splat(f32::NEG_INFINITY), 2., 4., 1., 1, 0),
360 ];
361 let mut plan = EnvironmentPlan::new(1).unwrap();
362 plan.ramp(Vec3::Y, 2., 1., 3., 0.2, 19).unwrap();
363 let before = plan.pieces().to_vec();
364 for build in builds {
365 assert_eq!(build(&mut plan), Err(BuildError::Invalid));
366 assert_eq!(plan.pieces(), before);
367 }
368 }
369
370 #[test]
371 fn compound_failure_rolls_back_earlier_successes_for_each_shape() {
372 let builds: [(Build, BuildError); 6] = [
373 (
374 |p| p.stairs(Vec3::ZERO, 2., 0.25, 0.5, 5, 0),
375 BuildError::Capacity,
376 ),
377 (
378 |p| p.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 0),
379 BuildError::Capacity,
380 ),
381 (
382 |p| p.bridge(Vec3::ZERO, 2., 4., 1., 1, 0),
383 BuildError::Capacity,
384 ),
385 (
386 |p| p.stairs(Vec3::ZERO, 2., f32::NAN, 0.5, 2, 0),
387 BuildError::Invalid,
388 ),
389 (
390 |p| p.ramp(Vec3::ZERO, 2., 1., 0., 0.2, 0),
391 BuildError::Invalid,
392 ),
393 (
394 |p| p.bridge(Vec3::ZERO, 2., 4., -1., 1, 0),
395 BuildError::Invalid,
396 ),
397 ];
398 let mut plan = EnvironmentPlan::new(5).unwrap();
399 plan.ramp(Vec3::Y, 2., 1., 3., 0.2, 19).unwrap();
400 let before = plan.pieces().to_vec();
401 let bounds = plan.bounds();
402 for (build, error) in builds {
403 assert_eq!(
404 plan.append_atomic(|group| {
405 assert_eq!(group.piece_count(), 0);
406 assert_eq!(group.bounds(), None);
407 assert_eq!(group.capacity(), 4);
408 group.stairs(Vec3::ZERO, 2., 0.25, 0.5, 3, 1)?;
409 group.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 2)?;
410 build(group)
411 }),
412 Err(error)
413 );
414 assert_eq!(plan.pieces(), before);
415 assert_eq!(plan.bounds(), bounds);
416 assert_eq!((plan.capacity(), plan.remaining_capacity()), (5, 4));
417 }
418 plan.append_atomic(|p| p.stairs(Vec3::ZERO, 2., 0.25, 0.5, 4, 1))
420 .unwrap();
421 assert_eq!(plan.remaining_capacity(), 0);
422 }
423
424 fn compound(plan: &mut EnvironmentPlan) -> Result<(), BuildError> {
425 plan.stairs(Vec3::new(1., 2., 3.), 2., 0.25, 0.5, 3, 4)?;
426 plan.ramp(Vec3::new(-4., -2., -1.), 2., 1.5, 3., 0.2, 5)?;
427 plan.bridge(Vec3::new(6., -1., 2.), 4., 8., 2., 2, 6)
428 }
429
430 #[test]
431 fn successful_compound_preserves_piece_order_materials_and_geometry() {
432 let mut plan = EnvironmentPlan::new(15).unwrap();
433 plan.stairs(Vec3::ZERO, 2., 0.25, 0.5, 2, 3).unwrap();
434 let mut direct = plan.clone();
435 compound(&mut direct).unwrap();
436 let storage = plan.pieces().as_ptr();
437 plan.append_atomic(compound).unwrap();
438 assert_eq!(plan.pieces(), direct.pieces());
439 assert_eq!(plan.bounds(), direct.bounds());
440 assert_eq!((plan.piece_count(), plan.remaining_capacity()), (15, 0));
441 assert_eq!(plan.pieces().as_ptr(), storage);
442 }
443
444 #[test]
445 fn compound_cannot_bypass_destination_capacity_by_replacing_staging_plan() {
446 let mut plan = EnvironmentPlan::new(2).unwrap();
447 plan.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 0).unwrap();
448 let before = plan.pieces().to_vec();
449 assert_eq!(
450 plan.append_atomic(|group| {
451 *group = EnvironmentPlan::new(1024)?;
452 group.stairs(Vec3::ZERO, 2., 0.25, 0.5, 2, 1)
453 }),
454 Err(BuildError::Capacity)
455 );
456 assert_eq!(plan.pieces(), before);
457 assert_eq!((plan.capacity(), plan.remaining_capacity()), (2, 1));
458 }
459
460 #[test]
461 fn callback_error_and_unwind_do_not_change_the_destination() {
462 let mut plan = EnvironmentPlan::new(8).unwrap();
463 plan.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 0).unwrap();
464 let before = plan.pieces().to_vec();
465 assert_eq!(
466 plan.append_atomic(|group| {
467 group.stairs(Vec3::ZERO, 2., 0.25, 0.5, 2, 1)?;
468 Err(BuildError::Invalid)
469 }),
470 Err(BuildError::Invalid)
471 );
472 assert_eq!(plan.pieces(), before);
473 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
474 let _ = plan.append_atomic(|group| {
475 group.stairs(Vec3::ZERO, 2., 0.25, 0.5, 2, 1)?;
476 panic!("authoring callback failed");
477 });
478 }));
479 assert!(result.is_err());
480 assert_eq!(plan.pieces(), before);
481 assert_eq!((plan.capacity(), plan.remaining_capacity()), (8, 7));
482 }
483
484 #[test]
485 fn empty_compounds_are_noops_even_on_full_plans() {
486 let mut plan = EnvironmentPlan::new(1).unwrap();
487 assert_eq!(plan.bounds(), None);
488 plan.append_atomic(|_| Ok(())).unwrap();
489 assert_eq!(plan.piece_count(), 0);
490 plan.ramp(Vec3::ZERO, 2., 1., 3., 0.2, 0).unwrap();
491 let before = plan.pieces().to_vec();
492 plan.append_atomic(|group| {
493 assert_eq!(group.capacity(), 0);
494 assert_eq!(group.remaining_capacity(), 0);
495 assert_eq!(group.bounds(), None);
496 group.append_atomic(|_| Ok(()))
497 })
498 .unwrap();
499 assert_eq!(plan.pieces(), before);
500 assert_eq!(plan.remaining_capacity(), 0);
501 }
502
503 #[test]
504 fn aggregate_bounds_enclose_rotated_corners_and_all_bridge_solids() {
505 let mut plan = EnvironmentPlan::new(13).unwrap();
506 compound(&mut plan).unwrap();
507 let mut min = Vec3::splat(f32::INFINITY);
508 let mut max = Vec3::splat(f32::NEG_INFINITY);
509 for piece in plan.pieces() {
510 for x in [-1., 1.] {
511 for y in [-1., 1.] {
512 for z in [-1., 1.] {
513 let corner = piece.center
514 + piece.rotation * (piece.half_extents * Vec3::new(x, y, z));
515 min = min.min(corner);
516 max = max.max(corner);
517 }
518 }
519 }
520 }
521 let (bounds_min, bounds_max) = plan.bounds().unwrap();
522 assert!((bounds_min - min).abs().max_element() < 1e-5);
523 assert!((bounds_max - max).abs().max_element() < 1e-5);
524
525 let mut bridge = EnvironmentPlan::new(9).unwrap();
526 let origin = Vec3::new(-3., 4., 5.);
527 bridge.bridge(origin, 4., 6., 2., 2, 0).unwrap();
528 let (min, max) = bridge.bounds().unwrap();
529 assert!((min - (origin + Vec3::new(-2.07, 0., -3.07))).length() < 1e-5);
530 assert!((max - (origin + Vec3::new(2.07, 3., 3.07))).length() < 1e-5);
531 }
532}