1use super::*;
2
3impl<'a> GameRenderContext<'a> {
5 pub fn new(bounds: Rect, display_list: &'a mut DisplayList) -> Self {
16 Self {
17 bounds,
18 display_list,
19 gpu_composite: None,
20 }
21 }
22
23 pub fn composite_gpu_texture(&mut self, rect: Rect, handle: GpuTextureHandle) -> bool {
35 if !handle.is_valid() {
36 return false;
37 }
38 let Self {
39 bounds,
40 gpu_composite,
41 ..
42 } = self;
43 let world: Rect = Rect::new(
44 bounds.get_x() + rect.get_x(),
45 bounds.get_y() + rect.get_y(),
46 rect.get_width(),
47 rect.get_height(),
48 );
49 *gpu_composite = Some(GpuCompositeDescriptor::new(world, handle, 0, true));
50 true
51 }
52
53 #[must_use]
63 pub fn gpu_composite_target(&self) -> Option<GpuCompositeDescriptor> {
64 let Self { gpu_composite, .. } = self;
65 *gpu_composite
66 }
67
68 #[must_use]
78 pub fn take_gpu_composite_target(&mut self) -> Option<GpuCompositeDescriptor> {
79 let Self { gpu_composite, .. } = self;
80 gpu_composite.take()
81 }
82
83 pub fn compose_shared_gpu_surface(
95 &mut self,
96 surface: &mut GpuSharedSurface,
97 compositor_device_id: u64,
98 ) -> SharedGpuCompositeReceipt {
99 surface.compose_frame(compositor_device_id, self)
100 }
101
102 pub fn blit_pooled_frame(&mut self, rect: Rect, lease: &PooledFrameLease) {
110 let frame_ref: PooledFrameRef = lease.to_frame_ref();
111 self.blit_pooled_frame_ref(rect, &frame_ref);
112 }
113
114 pub fn blit_pooled_frame_ref(&mut self, rect: Rect, frame: &PooledFrameRef) {
122 let Self {
123 bounds,
124 display_list,
125 ..
126 } = self;
127 let world: Rect = Rect::new(
128 bounds.get_x() + rect.get_x(),
129 bounds.get_y() + rect.get_y(),
130 rect.get_width(),
131 rect.get_height(),
132 );
133 display_list.push(DrawCommand::SharedImage {
134 rect: world,
135 width: frame.get_width(),
136 height: frame.get_height(),
137 pixels: frame.shared_pixels(),
138 radius: CornerRadius::default(),
139 });
140 }
141
142 #[must_use]
152 pub fn viewport_size(&self) -> Size {
153 let Self { bounds, .. } = self;
154 Size::new(bounds.get_width(), bounds.get_height())
155 }
156
157 #[must_use]
167 pub fn scale_factor(&self) -> f32 {
168 let Self { display_list, .. } = self;
169 let raw: f32 = display_list.get_scale_factor();
170 if raw.is_finite() && raw > 0.0 {
171 raw.clamp(0.5, 6.0)
172 } else {
173 1.0
174 }
175 }
176
177 pub fn clear(&mut self, color: Color) {
184 let Self {
185 bounds,
186 display_list,
187 ..
188 } = self;
189 display_list.push(DrawCommand::FillRoundedRect {
190 rect: *bounds,
191 color,
192 radius: CornerRadius::default(),
193 border: Border::default(),
194 });
195 }
196
197 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
205 self.fill_rounded_rect(rect, color, 0.0);
206 }
207
208 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
217 let Self {
218 bounds,
219 display_list,
220 ..
221 } = self;
222 let world: Rect = Rect::new(
223 bounds.get_x() + rect.get_x(),
224 bounds.get_y() + rect.get_y(),
225 rect.get_width(),
226 rect.get_height(),
227 );
228 display_list.push(DrawCommand::FillRoundedRect {
229 rect: world,
230 color,
231 radius: CornerRadius::all(radius),
232 border: Border::default(),
233 });
234 }
235
236 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
245 let Self {
246 bounds,
247 display_list,
248 ..
249 } = self;
250 let world: Rect = Rect::new(
251 bounds.get_x() + rect.get_x(),
252 bounds.get_y() + rect.get_y(),
253 rect.get_width(),
254 rect.get_height(),
255 );
256 display_list.push(DrawCommand::FillRoundedRect {
257 rect: world,
258 color: COLOR_TRANSPARENT,
259 radius: CornerRadius::default(),
260 border: Border::new(stroke_width, color),
261 });
262 }
263
264 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
273 let Self {
274 bounds,
275 display_list,
276 ..
277 } = self;
278 let world: Point = Point::new(
279 bounds.get_x() + center.get_x(),
280 bounds.get_y() + center.get_y(),
281 );
282 display_list.push(DrawCommand::Circle {
283 center: world,
284 radius,
285 color,
286 });
287 }
288
289 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
297 let Self {
298 bounds,
299 display_list,
300 ..
301 } = self;
302 let world: Rect = Rect::new(
303 bounds.get_x() + rect.get_x(),
304 bounds.get_y() + rect.get_y(),
305 rect.get_width(),
306 rect.get_height(),
307 );
308 display_list.push(DrawCommand::Image {
309 rect: world,
310 buffer,
311 radius: CornerRadius::default(),
312 });
313 }
314
315 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
325 let Self {
326 bounds,
327 display_list,
328 ..
329 } = self;
330 display_list.push(DrawCommand::Line {
331 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
332 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
333 color,
334 width,
335 });
336 }
337
338 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
348 let Self {
349 bounds,
350 display_list,
351 ..
352 } = self;
353 let mut style: TextStyle = TextStyle::default();
354 style.set_font_size(font_size);
355 style.set_color(color);
356 display_list.push(DrawCommand::TextRun {
357 rect: Rect::new(
358 bounds.get_x() + position.get_x(),
359 bounds.get_y() + position.get_y(),
360 (bounds.get_width() - position.get_x()).max(0.0),
361 font_size * 1.6,
362 ),
363 text,
364 style,
365 });
366 }
367
368 pub fn draw_text_str(&mut self, position: Point, text: &str, font_size: f32, color: Color) {
378 let Self {
379 bounds,
380 display_list,
381 ..
382 } = self;
383 let pooled: String = display_list.alloc_text(text);
384 let mut style: TextStyle = TextStyle::default();
385 style.set_font_size(font_size);
386 style.set_color(color);
387 display_list.push(DrawCommand::TextRun {
388 rect: Rect::new(
389 bounds.get_x() + position.get_x(),
390 bounds.get_y() + position.get_y(),
391 (bounds.get_width() - position.get_x()).max(0.0),
392 font_size * 1.6,
393 ),
394 text: pooled,
395 style,
396 });
397 }
398
399 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
407 let Self {
408 bounds,
409 display_list,
410 ..
411 } = self;
412 let world: Rect = Rect::new(
413 bounds.get_x() + rect.get_x(),
414 bounds.get_y() + rect.get_y(),
415 rect.get_width(),
416 rect.get_height(),
417 );
418 display_list.push(DrawCommand::Image {
419 rect: world,
420 buffer,
421 radius: CornerRadius::default(),
422 });
423 }
424
425 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
435 let Self {
436 bounds,
437 display_list,
438 ..
439 } = self;
440 let ox: f32 = bounds.get_x();
441 let oy: f32 = bounds.get_y();
442 display_list.push(DrawCommand::Triangle {
443 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
444 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
445 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
446 color,
447 });
448 }
449
450 pub fn draw_sprite_frame(
460 &mut self,
461 sheet: &SpriteSheet,
462 frame_index: u32,
463 rect: Rect,
464 tint: Color,
465 ) {
466 let src_rect: Rect = sheet.frame_rect(frame_index);
467 let Self {
468 bounds,
469 display_list,
470 ..
471 } = self;
472 display_list.push(DrawCommand::SpriteRegion {
473 rect: Rect::new(
474 bounds.get_x() + rect.get_x(),
475 bounds.get_y() + rect.get_y(),
476 rect.get_width(),
477 rect.get_height(),
478 ),
479 buffer: sheet.get_texture().clone(),
480 src_rect,
481 tint,
482 });
483 }
484
485 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
493 let box_size: Size = self.viewport_size();
494 let vis: Rect = camera.visible_world_rect(box_size);
495 let timestamp_val: f32 = tilemap.get_tile_size();
496 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
497 camera.projection_params(box_size);
498 let min_c: usize = (vis.get_x() / timestamp_val).floor().max(0.0) as usize;
499 let max_c: usize =
500 ((vis.right() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_columns());
501 let min_r: usize = (vis.get_y() / timestamp_val).floor().max(0.0) as usize;
502 let max_r: usize =
503 ((vis.bottom() / timestamp_val).ceil().max(0.0) as usize).min(tilemap.get_rows());
504 let tile_px: f32 = (timestamp_val * zoom).max(1.0);
505 if tilemap.has_fresh_chunk_cache() {
506 for chunk in tilemap.cached_chunks().iter() {
507 if chunk.get_max_col() <= min_c
508 || chunk.get_min_col() >= max_c
509 || chunk.get_max_row() <= min_r
510 || chunk.get_min_row() >= max_r
511 {
512 continue;
513 }
514 for run in chunk.get_runs().iter() {
515 let red_val: usize = run.get_row();
516 if red_val < min_r || red_val >= max_r {
517 continue;
518 }
519 let c0: usize = run.get_col().max(min_c);
520 let c1: usize = (run.get_col() + run.get_span_cols()).min(max_c);
521 if c0 >= c1 {
522 continue;
523 }
524 let sx: f32 = ((c0 as f32) * timestamp_val - cam_x) * zoom + half_w;
525 let sy: f32 = ((red_val as f32) * timestamp_val - cam_y) * zoom + half_h;
526 let run_w: f32 = ((c1 - c0) as f32) * tile_px + 0.5;
527 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), run.get_color());
528 }
529 }
530 return;
531 }
532 let palette: &[TilePaletteEntry] = tilemap.get_palette().as_slice();
533 for row in min_r..max_r {
534 let sy: f32 = ((row as f32) * timestamp_val - cam_y) * zoom + half_h;
535 let mut col: usize = min_c;
536 while col < max_c {
537 let tid: u16 = tilemap.tile_at(col, row);
538 if tid == 0 {
539 col += 1;
540 continue;
541 }
542 let Some(entry) = palette.get(tid as usize) else {
543 col += 1;
544 continue;
545 };
546 let color: Color = entry.get_color();
547 let start_col: usize = col;
548 col += 1;
549 while col < max_c {
550 let next_tid: u16 = tilemap.tile_at(col, row);
551 if next_tid == 0 {
552 break;
553 }
554 let same_color: bool = palette
555 .get(next_tid as usize)
556 .is_some_and(|event_ref: &TilePaletteEntry| event_ref.get_color() == color);
557 if !same_color {
558 break;
559 }
560 col += 1;
561 }
562 let sx: f32 = ((start_col as f32) * timestamp_val - cam_x) * zoom + half_w;
563 let run_w: f32 = ((col - start_col) as f32) * tile_px + 0.5;
564 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), color);
565 }
566 }
567 }
568
569 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
581 let box_size: Size = self.viewport_size();
582 let vis: Rect = camera.visible_world_rect(box_size);
583 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
584 camera.projection_params(box_size);
585 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
586 for (idx, ent) in world.get_entities().iter().enumerate() {
587 if !ent.get_alive() {
588 continue;
589 }
590 let Some(sp) = ent.sprite_component() else {
591 continue;
592 };
593 if !sp.get_visible() {
594 continue;
595 }
596 if ent.world_bounds().intersect(vis).is_none() {
597 continue;
598 }
599 draw_order.push((sp.get_z_order(), idx));
600 }
601 draw_order.sort_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
602 alpha_val
603 .0
604 .cmp(&blue_val.0)
605 .then_with(|| alpha_val.1.cmp(&blue_val.1))
606 });
607 let rendered: usize = draw_order.len();
608 for (_, idx) in draw_order.into_iter() {
609 let ent: &EntityRecord = &world.get_entities()[idx];
610 let Some(sp) = ent.sprite_component() else {
611 continue;
612 };
613 let transform_val: EntityTransform = ent.get_transform();
614 let pos: Point = transform_val.get_position();
615 let center: Point = Point::new(
616 (pos.get_x() - cam_x) * zoom + half_w,
617 (pos.get_y() - cam_y) * zoom + half_h,
618 );
619 let width_val: f32 =
620 sp.get_size().get_width() * transform_val.get_scale().get_width() * zoom;
621 let height_val: f32 =
622 sp.get_size().get_height() * transform_val.get_scale().get_height() * zoom;
623 match sp.get_shape() {
624 EntityVisualShape::Rect => {
625 let rect: Rect = Rect::new(
626 center.get_x() - width_val * 0.5,
627 center.get_y() - height_val * 0.5,
628 width_val,
629 height_val,
630 );
631 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
632 if sp.get_accent().get_alpha() > 0 {
633 self.stroke_rect(rect, 1.5, sp.get_accent());
634 }
635 }
636 EntityVisualShape::Circle => {
637 let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
638 self.fill_circle(center, red_val, sp.get_color());
639 if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
640 self.fill_circle(center, red_val * 0.45, sp.get_accent());
641 }
642 }
643 EntityVisualShape::Triangle => {
644 let ang: f32 = transform_val.get_rotation_rad();
645 let cos_a: f32 = ang.cos();
646 let sin_a: f32 = ang.sin();
647 let rx: f32 = width_val * 0.55;
648 let ry: f32 = height_val * 0.48;
649 let nose: Point =
650 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
651 let left: Point = Point::new(
652 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
653 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
654 );
655 let right: Point = Point::new(
656 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
657 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
658 );
659 self.fill_triangle(nose, left, right, sp.get_color());
660 if sp.get_accent().get_alpha() > 0 {
661 self.fill_circle(
662 center,
663 (width_val.min(height_val) * 0.16).max(2.0),
664 sp.get_accent(),
665 );
666 }
667 }
668 EntityVisualShape::Diamond => {
669 let hw: f32 = width_val * 0.5;
670 let hh: f32 = height_val * 0.5;
671 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
672 let right: Point = Point::new(center.get_x() + hw, center.get_y());
673 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
674 let left: Point = Point::new(center.get_x() - hw, center.get_y());
675 self.fill_triangle(top, right, bottom, sp.get_color());
676 self.fill_triangle(top, bottom, left, sp.get_color());
677 if sp.get_accent().get_alpha() > 0 {
678 self.fill_circle(
679 center,
680 (width_val.min(height_val) * 0.18).max(2.0),
681 sp.get_accent(),
682 );
683 }
684 }
685 }
686 }
687 rendered
688 }
689
690 pub fn render_snapshot_world(
702 &mut self,
703 world: &GameWorld,
704 snapshot: &World2DSnapshot,
705 ) -> usize {
706 let camera: Camera2D = snapshot.get_camera();
707 let box_size: Size = self.viewport_size();
708 let vis: Rect = camera.visible_world_rect(box_size);
709 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
710 camera.projection_params(box_size);
711 let poses: &[EntityPose2D] = snapshot.get_entities().as_slice();
712 let records: &[EntityRecord] = world.get_entities().as_slice();
713 let mut stack_order: [(i32, usize); 128] = [(0, 0); 128];
714 let mut stack_len: usize = 0;
715 let mut heap_order: Vec<(i32, usize)> = Vec::new();
716 for (idx, pose) in poses.iter().enumerate() {
717 if !pose.get_alive() {
718 continue;
719 }
720 let Some(ent) = records.get(idx) else {
721 continue;
722 };
723 if ent.get_id() != pose.get_id() {
724 continue;
725 }
726 let Some(sp) = ent.sprite_component() else {
727 continue;
728 };
729 if !sp.get_visible() {
730 continue;
731 }
732 let transform_val: EntityTransform = pose.get_transform();
733 let pos: Point = transform_val.get_position();
734 let border_width: f32 =
735 sp.get_size().get_width() * transform_val.get_scale().get_width();
736 let bh: f32 = sp.get_size().get_height() * transform_val.get_scale().get_height();
737 let bounds: Rect = Rect::new(
738 pos.get_x() - border_width * 0.5,
739 pos.get_y() - bh * 0.5,
740 border_width,
741 bh,
742 );
743 if bounds.intersect(vis).is_none() {
744 continue;
745 }
746 let item: (i32, usize) = (sp.get_z_order(), idx);
747 if heap_order.is_empty() && stack_len < stack_order.len() {
748 stack_order[stack_len] = item;
749 stack_len += 1;
750 } else {
751 if heap_order.is_empty() {
752 heap_order.reserve(poses.len());
753 heap_order.extend_from_slice(&stack_order[..stack_len]);
754 }
755 heap_order.push(item);
756 }
757 }
758 let order_slice: &mut [(i32, usize)] = if heap_order.is_empty() {
759 &mut stack_order[..stack_len]
760 } else {
761 heap_order.as_mut_slice()
762 };
763 order_slice.sort_unstable_by(|alpha_val: &(i32, usize), blue_val: &(i32, usize)| {
764 alpha_val
765 .0
766 .cmp(&blue_val.0)
767 .then_with(|| alpha_val.1.cmp(&blue_val.1))
768 });
769 let rendered: usize = order_slice.len();
770 for &(_, idx) in order_slice.iter() {
771 let ent: &EntityRecord = &records[idx];
772 let Some(sp) = ent.sprite_component() else {
773 continue;
774 };
775 let object_transform: EntityTransform = poses[idx].get_transform();
776 let pos: Point = object_transform.get_position();
777 let center: Point = Point::new(
778 (pos.get_x() - cam_x) * zoom + half_w,
779 (pos.get_y() - cam_y) * zoom + half_h,
780 );
781 let width_val: f32 =
782 sp.get_size().get_width() * object_transform.get_scale().get_width() * zoom;
783 let height_val: f32 =
784 sp.get_size().get_height() * object_transform.get_scale().get_height() * zoom;
785 match sp.get_shape() {
786 EntityVisualShape::Rect => {
787 let rect: Rect = Rect::new(
788 center.get_x() - width_val * 0.5,
789 center.get_y() - height_val * 0.5,
790 width_val,
791 height_val,
792 );
793 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
794 if sp.get_accent().get_alpha() > 0 {
795 self.stroke_rect(rect, 1.5, sp.get_accent());
796 }
797 }
798 EntityVisualShape::Circle => {
799 let red_val: f32 = (width_val.min(height_val) * 0.5).max(1.0);
800 self.fill_circle(center, red_val, sp.get_color());
801 if sp.get_accent().get_alpha() > 0 && red_val > 3.0 {
802 self.fill_circle(center, red_val * 0.45, sp.get_accent());
803 }
804 }
805 EntityVisualShape::Triangle => {
806 let ang: f32 = object_transform.get_rotation_rad();
807 let cos_a: f32 = ang.cos();
808 let sin_a: f32 = ang.sin();
809 let rx: f32 = width_val * 0.55;
810 let ry: f32 = height_val * 0.48;
811 let nose: Point =
812 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
813 let left: Point = Point::new(
814 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
815 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
816 );
817 let right: Point = Point::new(
818 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
819 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
820 );
821 self.fill_triangle(nose, left, right, sp.get_color());
822 if sp.get_accent().get_alpha() > 0 {
823 self.fill_circle(
824 center,
825 (width_val.min(height_val) * 0.16).max(2.0),
826 sp.get_accent(),
827 );
828 }
829 }
830 EntityVisualShape::Diamond => {
831 let hw: f32 = width_val * 0.5;
832 let hh: f32 = height_val * 0.5;
833 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
834 let right: Point = Point::new(center.get_x() + hw, center.get_y());
835 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
836 let left: Point = Point::new(center.get_x() - hw, center.get_y());
837 self.fill_triangle(top, right, bottom, sp.get_color());
838 self.fill_triangle(top, bottom, left, sp.get_color());
839 if sp.get_accent().get_alpha() > 0 {
840 self.fill_circle(
841 center,
842 (width_val.min(height_val) * 0.18).max(2.0),
843 sp.get_accent(),
844 );
845 }
846 }
847 }
848 }
849 rendered
850 }
851
852 pub fn render_interpolated_world(
866 &mut self,
867 world: &GameWorld,
868 prev: &World2DSnapshot,
869 curr: &World2DSnapshot,
870 alpha: f32,
871 ) -> usize {
872 let interp: World2DSnapshot = prev.interpolate(curr, alpha);
873 self.render_snapshot_world(world, &interp)
874 }
875
876 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
888 let box_size: Size = self.viewport_size();
889 let vis: Rect = camera.visible_world_rect(box_size);
890 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
891 camera.projection_params(box_size);
892 let item_count: usize = particles.get_active_count();
893 let mut count: usize = 0;
894 for item_index in 0..item_count {
895 let pos: Point = Point::new(particles.pos_x[item_index], particles.pos_y[item_index]);
896 if !vis.contains(pos) {
897 continue;
898 }
899 let blend_factor: f32 = (particles.age[item_index]
900 / particles.lifetime[item_index].max(0.001))
901 .clamp(0.0, 1.0);
902 let s0: f32 = particles.start_size[item_index];
903 let s1: f32 = particles.end_size[item_index];
904 let red_val: f32 = ((s0 + (s1 - s0) * blend_factor) * zoom).max(0.8);
905 let col: Color = particles.start_color[item_index]
906 .lerp(particles.end_color[item_index], blend_factor);
907 if col.get_alpha() == 0 {
908 continue;
909 }
910 let screen: Point = Point::new(
911 (pos.get_x() - cam_x) * zoom + half_w,
912 (pos.get_y() - cam_y) * zoom + half_h,
913 );
914 self.fill_circle(screen, red_val, col);
915 count += 1;
916 }
917 count
918 }
919
920 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
928 let box_size: Size = self.viewport_size();
929 let vis: Rect = camera.visible_world_rect(box_size);
930 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
931 camera.projection_params(box_size);
932 for ent in world.get_entities().iter() {
933 if !ent.get_alive() {
934 continue;
935 }
936 let Some(col) = ent.collider_component() else {
937 continue;
938 };
939 let bounds_rect: Rect = col.world_bounds(ent.get_transform().get_position());
940 if bounds_rect.intersect(vis).is_none() {
941 continue;
942 }
943 let tl_x: f32 = (bounds_rect.get_x() - cam_x) * zoom + half_w;
944 let tl_y: f32 = (bounds_rect.get_y() - cam_y) * zoom + half_h;
945 let color: Color = if col.get_is_trigger() {
946 Color::rgba(250, 204, 21, 180)
947 } else {
948 Color::rgba(34, 197, 94, 180)
949 };
950 self.stroke_rect(
951 Rect::new(
952 tl_x,
953 tl_y,
954 bounds_rect.get_width() * zoom,
955 bounds_rect.get_height() * zoom,
956 ),
957 1.0,
958 color,
959 );
960 }
961 }
962}
963
964impl GameEngineHost {
966 #[must_use]
977 pub fn new<TextValue>(scene: TextValue, fixed_dt: f32) -> Self
978 where
979 TextValue: GameScene + 'static,
980 {
981 Self {
982 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
983 input: Rc::new(RefCell::new(InputState::new())),
984 scene: Rc::new(RefCell::new(scene)),
985 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
986 last_gpu_composite: Rc::new(RefCell::new(None)),
987 paused: Rc::new(Cell::new(false)),
988 }
989 }
990
991 #[must_use]
1001 pub fn last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1002 self.get_last_gpu_composite()
1003 .try_borrow()
1004 .ok()
1005 .and_then(|green_val: Ref<'_, Option<GpuCompositeDescriptor>>| *green_val)
1006 }
1007
1008 #[must_use]
1018 pub fn take_last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
1019 self.get_last_gpu_composite()
1020 .try_borrow_mut()
1021 .ok()
1022 .and_then(|mut green_val: RefMut<'_, Option<GpuCompositeDescriptor>>| green_val.take())
1023 }
1024
1025 pub fn set_paused(&self, paused: bool) {
1032 self.get_paused().set(paused);
1033 }
1034
1035 #[must_use]
1045 pub fn is_paused(&self) -> bool {
1046 self.get_paused().get()
1047 }
1048
1049 #[must_use]
1060 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
1061 let mut rects: Vec<Rect> = Vec::new();
1062 let _: bool = self.collect_active_viewport_bounds(tree, &mut rects);
1063 rects
1064 }
1065
1066 pub fn collect_active_viewport_bounds(&self, tree: &SceneTree, out: &mut Vec<Rect>) -> bool {
1078 if self.is_paused() {
1079 return false;
1080 }
1081 let start_len: usize = out.len();
1082 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1083 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
1084 for (_, id) in nodes.iter() {
1085 if tree.is_node_visible(*id)
1086 && let Some(bounds) = tree.node_screen_bounds(*id)
1087 && bounds.get_width() > 0.0
1088 && bounds.get_height() > 0.0
1089 {
1090 out.push(bounds);
1091 }
1092 }
1093 }
1094 out.len() > start_len
1095 }
1096
1097 pub fn ingest_event(&self, event: &WindowEvent) {
1104 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1105 input.ingest(event);
1106 }
1107 }
1108
1109 pub fn step_ns(&self, dt_ns: u64) -> u32 {
1120 if self.is_paused() {
1121 return 0;
1122 }
1123 let (steps, fixed_dt, dt_secs): (u32, f32, f32) = match self.get_clock().try_borrow_mut() {
1124 Ok(mut clock) => {
1125 let source_val: u32 = clock.tick_ns(dt_ns);
1126 (source_val, clock.get_fixed_dt(), clock.get_delta_secs())
1127 }
1128 Err(_) => (0, 1.0 / 60.0, ((dt_ns as f64) / 1_000_000_000.0) as f32),
1129 };
1130 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1131 self.mark_viewports_dirty();
1132 steps
1133 }
1134
1135 pub fn step_decoupled_ns(&self, present_dt_ns: u64) -> SimPresentFrame {
1146 if self.is_paused() {
1147 let alpha: f32 = self
1148 .get_clock()
1149 .try_borrow()
1150 .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1151 .unwrap_or(0.0);
1152 let fixed_dt: f32 = self
1153 .get_clock()
1154 .try_borrow()
1155 .map(|color_item: Ref<'_, FrameClock>| color_item.get_fixed_dt())
1156 .unwrap_or(1.0 / 60.0);
1157 return SimPresentFrame::new(0, alpha, fixed_dt, 0.0, true, false);
1158 }
1159 let (steps, fixed_dt, dt_secs, alpha, hit_clamp): (u32, f32, f32, f32, bool) =
1160 match self.get_clock().try_borrow_mut() {
1161 Ok(mut clock) => {
1162 let fixed_ns: u64 = clock.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
1163 let max_sub: u32 = clock.get_max_substeps().max(1);
1164 let pre_acc: u64 = clock.get_accumulator_ns();
1165 let clamped_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
1166 let uncapped: u64 = pre_acc.saturating_add(clamped_ns) / fixed_ns;
1167 let clamped: bool =
1168 present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped > (max_sub as u64);
1169 let source_val: u32 = clock.tick_ns(present_dt_ns);
1170 (
1171 source_val,
1172 clock.get_fixed_dt(),
1173 clock.get_delta_secs(),
1174 clock.get_alpha(),
1175 clamped,
1176 )
1177 }
1178 Err(_) => (
1179 0,
1180 1.0 / 60.0,
1181 ((present_dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
1182 0.0,
1183 false,
1184 ),
1185 };
1186 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1187 self.mark_viewports_dirty();
1188 SimPresentFrame::new(steps, alpha, fixed_dt, dt_secs, steps == 0, hit_clamp)
1189 }
1190
1191 pub fn step(&self, dt_secs: f32) -> u32 {
1202 if self.is_paused() {
1203 return 0;
1204 }
1205 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
1206 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
1207 Err(_) => (0, 1.0 / 60.0),
1208 };
1209 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1210 self.mark_viewports_dirty();
1211 steps
1212 }
1213
1214 fn dispatch_step_with_counts(&self, steps: u32, fixed_dt: f32, dt_secs: f32) {
1223 let Self { scene, .. } = self;
1224 if let Ok(mut game) = scene.try_borrow_mut() {
1225 let input_copy: InputState = self
1226 .get_input()
1227 .try_borrow()
1228 .map(|red_val: Ref<'_, InputState>| *red_val)
1229 .unwrap_or_default();
1230 if steps == 0 {
1231 game.update(dt_secs, &input_copy);
1232 } else {
1233 game.fixed_update(fixed_dt, &input_copy);
1234 if let Ok(mut input_mut) = self.get_input().try_borrow_mut() {
1235 input_mut.begin_frame();
1236 }
1237 let cleared: InputState = input_copy.without_edges();
1238 for _ in 1..steps {
1239 game.fixed_update(fixed_dt, &cleared);
1240 }
1241 game.update(dt_secs, &cleared);
1242 }
1243 } else if steps > 0
1244 && let Ok(mut input) = self.get_input().try_borrow_mut()
1245 {
1246 input.begin_frame();
1247 }
1248 }
1249
1250 pub fn mark_viewports_dirty(&self) {
1256 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1257 nodes.retain(|(scene_handle, node_id): &(SceneHandle, NodeId)| {
1258 let (alive, visible): (bool, bool) = scene_handle.with_read(
1259 |tree: &SceneTree| -> (bool, bool) {
1260 let exists: bool = tree.get_node(*node_id).is_some();
1261 let vis: bool = exists
1262 && tree.is_node_visible(*node_id)
1263 && tree.node_screen_bounds(*node_id).is_some_and(
1264 |rect_bounds: Rect| {
1265 rect_bounds.get_width() > 0.0 && rect_bounds.get_height() > 0.0
1266 },
1267 );
1268 (exists, vis)
1269 },
1270 (false, false),
1271 );
1272 if visible {
1273 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
1274 }
1275 alive
1276 });
1277 }
1278 }
1279
1280 pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
1291 match decision.get_action() {
1292 PacingAction::StepAndRender => self.step_ns(decision.get_sim_dt_ns()),
1293 PacingAction::RenderWithoutSimAdvance => {
1294 self.mark_viewports_dirty();
1295 0
1296 }
1297 PacingAction::DeferToNextVsync
1298 | PacingAction::WaitInFlight
1299 | PacingAction::SkipUserCap => 0,
1300 }
1301 }
1302
1303 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
1311 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1312 input.set_virtual_stick(dx, dy);
1313 }
1314 }
1315
1316 pub fn press_key(&self, code: KeyCode) {
1323 self.ingest_event(&WindowEvent::KeyDown(
1324 WindowId::new(1),
1325 KeyEvent::new(code, Modifiers::default(), false),
1326 ));
1327 }
1328
1329 pub fn release_key(&self, code: KeyCode) {
1336 self.ingest_event(&WindowEvent::KeyUp(
1337 WindowId::new(1),
1338 KeyEvent::new(code, Modifiers::default(), false),
1339 ));
1340 }
1341
1342 #[must_use]
1356 pub fn mount_viewport(&self, style: Style) -> NodeId {
1357 let Self {
1358 clock,
1359 scene,
1360 last_gpu_composite,
1361 ..
1362 } = self;
1363 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
1364 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
1365 let gpu_out_c: Rc<RefCell<Option<GpuCompositeDescriptor>>> = last_gpu_composite.clone();
1366 let mut ctx: Context = current_context();
1367 let node: NodeId = ctx.canvas(
1368 style,
1369 move |bounds: Rect, display_list: &mut DisplayList| {
1370 let alpha: f32 = clock_c
1371 .try_borrow()
1372 .map(|char_item: Ref<'_, FrameClock>| char_item.get_alpha())
1373 .unwrap_or(1.0);
1374 if let Ok(mut game) = scene_c.try_borrow_mut() {
1375 let mut render_ctx: GameRenderContext<'_> =
1376 GameRenderContext::new(bounds, display_list);
1377 game.render(alpha, &mut render_ctx);
1378 let gpu_target: Option<GpuCompositeDescriptor> =
1379 render_ctx.take_gpu_composite_target();
1380 if let Ok(mut slot) = gpu_out_c.try_borrow_mut() {
1381 *slot = gpu_target;
1382 }
1383 }
1384 },
1385 );
1386 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1387 nodes.retain(|(sh, nid): &(SceneHandle, NodeId)| {
1388 sh.with_read(|tree: &SceneTree| tree.get_node(*nid).is_some(), false)
1389 });
1390 nodes.push((ctx.get_scene().clone(), node));
1391 }
1392 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
1393 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1394 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1395 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
1396 let host_move: Self = self.clone();
1397 let host_up: Self = self.clone();
1398 ctx.on_pointer_down(node, move |ui_event: &UiEvent| {
1399 if let UiEventKind::PointerDown(sample_point) = ui_event.get_kind()
1400 && let Ok(mut guard) = origin_down.try_borrow_mut()
1401 {
1402 *guard = Some(*sample_point);
1403 }
1404 });
1405 ctx.on_pointer_move(node, move |interaction_event: &UiEvent| {
1406 if let UiEventKind::PointerMove(target_point) = interaction_event.get_kind()
1407 && let Ok(guard) = origin_move.try_borrow()
1408 && let Some(orig) = *guard
1409 {
1410 let dx: f32 = ((target_point.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
1411 let dy: f32 = ((target_point.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
1412 host_move.set_virtual_stick(dx, dy);
1413 }
1414 });
1415 ctx.on_pointer_up(node, move |_: &UiEvent| {
1416 if let Ok(mut guard) = origin_up.try_borrow_mut() {
1417 *guard = None;
1418 }
1419 host_up.set_virtual_stick(0.0, 0.0);
1420 });
1421 node
1422 }
1423}