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 blit_pooled_frame(&mut self, rect: Rect, lease: &PooledFrameLease) {
91 let frame_ref: PooledFrameRef = lease.to_frame_ref();
92 self.blit_pooled_frame_ref(rect, &frame_ref);
93 }
94
95 pub fn blit_pooled_frame_ref(&mut self, rect: Rect, frame: &PooledFrameRef) {
103 let Self {
104 bounds,
105 display_list,
106 ..
107 } = self;
108 let world: Rect = Rect::new(
109 bounds.get_x() + rect.get_x(),
110 bounds.get_y() + rect.get_y(),
111 rect.get_width(),
112 rect.get_height(),
113 );
114 display_list.push(DrawCommand::SharedImage {
115 rect: world,
116 width: frame.get_width(),
117 height: frame.get_height(),
118 pixels: frame.shared_pixels(),
119 radius: CornerRadius::default(),
120 });
121 }
122
123 #[must_use]
133 pub fn viewport_size(&self) -> Size {
134 let Self { bounds, .. } = self;
135 Size::new(bounds.get_width(), bounds.get_height())
136 }
137
138 pub fn clear(&mut self, color: Color) {
145 let Self {
146 bounds,
147 display_list,
148 ..
149 } = self;
150 display_list.push(DrawCommand::FillRoundedRect {
151 rect: *bounds,
152 color,
153 radius: CornerRadius::default(),
154 border: Border::default(),
155 });
156 }
157
158 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
166 self.fill_rounded_rect(rect, color, 0.0);
167 }
168
169 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
178 let Self {
179 bounds,
180 display_list,
181 ..
182 } = self;
183 let world: Rect = Rect::new(
184 bounds.get_x() + rect.get_x(),
185 bounds.get_y() + rect.get_y(),
186 rect.get_width(),
187 rect.get_height(),
188 );
189 display_list.push(DrawCommand::FillRoundedRect {
190 rect: world,
191 color,
192 radius: CornerRadius::all(radius),
193 border: Border::default(),
194 });
195 }
196
197 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
206 let Self {
207 bounds,
208 display_list,
209 ..
210 } = self;
211 let world: Rect = Rect::new(
212 bounds.get_x() + rect.get_x(),
213 bounds.get_y() + rect.get_y(),
214 rect.get_width(),
215 rect.get_height(),
216 );
217 display_list.push(DrawCommand::FillRoundedRect {
218 rect: world,
219 color: COLOR_TRANSPARENT,
220 radius: CornerRadius::default(),
221 border: Border::new(stroke_width, color),
222 });
223 }
224
225 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
234 let Self {
235 bounds,
236 display_list,
237 ..
238 } = self;
239 let world: Point = Point::new(
240 bounds.get_x() + center.get_x(),
241 bounds.get_y() + center.get_y(),
242 );
243 display_list.push(DrawCommand::Circle {
244 center: world,
245 radius,
246 color,
247 });
248 }
249
250 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
258 let Self {
259 bounds,
260 display_list,
261 ..
262 } = self;
263 let world: Rect = Rect::new(
264 bounds.get_x() + rect.get_x(),
265 bounds.get_y() + rect.get_y(),
266 rect.get_width(),
267 rect.get_height(),
268 );
269 display_list.push(DrawCommand::Image {
270 rect: world,
271 buffer,
272 radius: CornerRadius::default(),
273 });
274 }
275
276 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
286 let Self {
287 bounds,
288 display_list,
289 ..
290 } = self;
291 display_list.push(DrawCommand::Line {
292 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
293 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
294 color,
295 width,
296 });
297 }
298
299 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
309 let Self {
310 bounds,
311 display_list,
312 ..
313 } = self;
314 let mut style: TextStyle = TextStyle::default();
315 style.set_font_size(font_size);
316 style.set_color(color);
317 display_list.push(DrawCommand::TextRun {
318 rect: Rect::new(
319 bounds.get_x() + position.get_x(),
320 bounds.get_y() + position.get_y(),
321 (bounds.get_width() - position.get_x()).max(0.0),
322 font_size * 1.6,
323 ),
324 text,
325 style,
326 });
327 }
328
329 pub fn draw_text_str(&mut self, position: Point, text: &str, font_size: f32, color: Color) {
339 let Self {
340 bounds,
341 display_list,
342 ..
343 } = self;
344 let pooled: String = display_list.alloc_text(text);
345 let mut style: TextStyle = TextStyle::default();
346 style.set_font_size(font_size);
347 style.set_color(color);
348 display_list.push(DrawCommand::TextRun {
349 rect: Rect::new(
350 bounds.get_x() + position.get_x(),
351 bounds.get_y() + position.get_y(),
352 (bounds.get_width() - position.get_x()).max(0.0),
353 font_size * 1.6,
354 ),
355 text: pooled,
356 style,
357 });
358 }
359
360 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
368 let Self {
369 bounds,
370 display_list,
371 ..
372 } = self;
373 let world: Rect = Rect::new(
374 bounds.get_x() + rect.get_x(),
375 bounds.get_y() + rect.get_y(),
376 rect.get_width(),
377 rect.get_height(),
378 );
379 display_list.push(DrawCommand::Image {
380 rect: world,
381 buffer,
382 radius: CornerRadius::default(),
383 });
384 }
385
386 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
396 let Self {
397 bounds,
398 display_list,
399 ..
400 } = self;
401 let ox: f32 = bounds.get_x();
402 let oy: f32 = bounds.get_y();
403 display_list.push(DrawCommand::Triangle {
404 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
405 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
406 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
407 color,
408 });
409 }
410
411 pub fn draw_sprite_frame(
421 &mut self,
422 sheet: &SpriteSheet,
423 frame_index: u32,
424 rect: Rect,
425 tint: Color,
426 ) {
427 let src_rect: Rect = sheet.frame_rect(frame_index);
428 let Self {
429 bounds,
430 display_list,
431 ..
432 } = self;
433 display_list.push(DrawCommand::SpriteRegion {
434 rect: Rect::new(
435 bounds.get_x() + rect.get_x(),
436 bounds.get_y() + rect.get_y(),
437 rect.get_width(),
438 rect.get_height(),
439 ),
440 buffer: sheet.get_texture().clone(),
441 src_rect,
442 tint,
443 });
444 }
445
446 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
454 let vp: Size = self.viewport_size();
455 let vis: Rect = camera.visible_world_rect(vp);
456 let ts: f32 = tilemap.get_tile_size();
457 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
458 camera.projection_params(vp);
459 let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
460 let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
461 let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
462 let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
463 let tile_px: f32 = (ts * zoom).max(1.0);
464 if tilemap.has_fresh_chunk_cache() {
465 for chunk in tilemap.cached_chunks().iter() {
466 if chunk.get_max_col() <= min_c
467 || chunk.get_min_col() >= max_c
468 || chunk.get_max_row() <= min_r
469 || chunk.get_min_row() >= max_r
470 {
471 continue;
472 }
473 for run in chunk.get_runs().iter() {
474 let r: usize = run.get_row();
475 if r < min_r || r >= max_r {
476 continue;
477 }
478 let c0: usize = run.get_col().max(min_c);
479 let c1: usize = (run.get_col() + run.get_span_cols()).min(max_c);
480 if c0 >= c1 {
481 continue;
482 }
483 let sx: f32 = ((c0 as f32) * ts - cam_x) * zoom + half_w;
484 let sy: f32 = ((r as f32) * ts - cam_y) * zoom + half_h;
485 let run_w: f32 = ((c1 - c0) as f32) * tile_px + 0.5;
486 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), run.get_color());
487 }
488 }
489 return;
490 }
491 let palette: &[TilePaletteEntry] = tilemap.get_palette().as_slice();
492 for row in min_r..max_r {
493 let sy: f32 = ((row as f32) * ts - cam_y) * zoom + half_h;
494 let mut col: usize = min_c;
495 while col < max_c {
496 let tid: u16 = tilemap.tile_at(col, row);
497 if tid == 0 {
498 col += 1;
499 continue;
500 }
501 let Some(entry) = palette.get(tid as usize) else {
502 col += 1;
503 continue;
504 };
505 let color: Color = entry.get_color();
506 let start_col: usize = col;
507 col += 1;
508 while col < max_c {
509 let next_tid: u16 = tilemap.tile_at(col, row);
510 if next_tid == 0 {
511 break;
512 }
513 let same_color: bool = palette
514 .get(next_tid as usize)
515 .is_some_and(|e: &TilePaletteEntry| e.get_color() == color);
516 if !same_color {
517 break;
518 }
519 col += 1;
520 }
521 let sx: f32 = ((start_col as f32) * ts - cam_x) * zoom + half_w;
522 let run_w: f32 = ((col - start_col) as f32) * tile_px + 0.5;
523 self.fill_rect(Rect::new(sx, sy, run_w, tile_px + 0.5), color);
524 }
525 }
526 }
527
528 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
540 let vp: Size = self.viewport_size();
541 let vis: Rect = camera.visible_world_rect(vp);
542 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
543 camera.projection_params(vp);
544 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
545 for (idx, ent) in world.get_entities().iter().enumerate() {
546 if !ent.get_alive() {
547 continue;
548 }
549 let Some(sp) = ent.sprite_component() else {
550 continue;
551 };
552 if !sp.get_visible() {
553 continue;
554 }
555 if ent.world_bounds().intersect(vis).is_none() {
556 continue;
557 }
558 draw_order.push((sp.get_z_order(), idx));
559 }
560 draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
561 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
562 });
563 let rendered: usize = draw_order.len();
564 for (_, idx) in draw_order.into_iter() {
565 let ent: &EntityRecord = &world.get_entities()[idx];
566 let Some(sp) = ent.sprite_component() else {
567 continue;
568 };
569 let tr: EntityTransform = ent.get_transform();
570 let pos: Point = tr.get_position();
571 let center: Point = Point::new(
572 (pos.get_x() - cam_x) * zoom + half_w,
573 (pos.get_y() - cam_y) * zoom + half_h,
574 );
575 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
576 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
577 match sp.get_shape() {
578 EntityVisualShape::Rect => {
579 let rect: Rect =
580 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
581 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
582 if sp.get_accent().get_a() > 0 {
583 self.stroke_rect(rect, 1.5, sp.get_accent());
584 }
585 }
586 EntityVisualShape::Circle => {
587 let r: f32 = (w.min(h) * 0.5).max(1.0);
588 self.fill_circle(center, r, sp.get_color());
589 if sp.get_accent().get_a() > 0 && r > 3.0 {
590 self.fill_circle(center, r * 0.45, sp.get_accent());
591 }
592 }
593 EntityVisualShape::Triangle => {
594 let ang: f32 = tr.get_rotation_rad();
595 let cos_a: f32 = ang.cos();
596 let sin_a: f32 = ang.sin();
597 let rx: f32 = w * 0.55;
598 let ry: f32 = h * 0.48;
599 let nose: Point =
600 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
601 let left: Point = Point::new(
602 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
603 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
604 );
605 let right: Point = Point::new(
606 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
607 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
608 );
609 self.fill_triangle(nose, left, right, sp.get_color());
610 if sp.get_accent().get_a() > 0 {
611 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
612 }
613 }
614 EntityVisualShape::Diamond => {
615 let hw: f32 = w * 0.5;
616 let hh: f32 = h * 0.5;
617 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
618 let right: Point = Point::new(center.get_x() + hw, center.get_y());
619 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
620 let left: Point = Point::new(center.get_x() - hw, center.get_y());
621 self.fill_triangle(top, right, bottom, sp.get_color());
622 self.fill_triangle(top, bottom, left, sp.get_color());
623 if sp.get_accent().get_a() > 0 {
624 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
625 }
626 }
627 }
628 }
629 rendered
630 }
631
632 pub fn render_snapshot_world(
644 &mut self,
645 world: &GameWorld,
646 snapshot: &World2DSnapshot,
647 ) -> usize {
648 let camera: Camera2D = snapshot.get_camera();
649 let vp: Size = self.viewport_size();
650 let vis: Rect = camera.visible_world_rect(vp);
651 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
652 camera.projection_params(vp);
653 let poses: &[EntityPose2D] = snapshot.get_entities().as_slice();
654 let records: &[EntityRecord] = world.get_entities().as_slice();
655 let mut stack_order: [(i32, usize); 128] = [(0, 0); 128];
656 let mut stack_len: usize = 0;
657 let mut heap_order: Vec<(i32, usize)> = Vec::new();
658 for (idx, pose) in poses.iter().enumerate() {
659 if !pose.get_alive() {
660 continue;
661 }
662 let Some(ent) = records.get(idx) else {
663 continue;
664 };
665 if ent.get_id() != pose.get_id() {
666 continue;
667 }
668 let Some(sp) = ent.sprite_component() else {
669 continue;
670 };
671 if !sp.get_visible() {
672 continue;
673 }
674 let tr: EntityTransform = pose.get_transform();
675 let pos: Point = tr.get_position();
676 let bw: f32 = sp.get_size().get_width() * tr.get_scale().get_width();
677 let bh: f32 = sp.get_size().get_height() * tr.get_scale().get_height();
678 let bounds: Rect = Rect::new(pos.get_x() - bw * 0.5, pos.get_y() - bh * 0.5, bw, bh);
679 if bounds.intersect(vis).is_none() {
680 continue;
681 }
682 let item: (i32, usize) = (sp.get_z_order(), idx);
683 if heap_order.is_empty() && stack_len < stack_order.len() {
684 stack_order[stack_len] = item;
685 stack_len += 1;
686 } else {
687 if heap_order.is_empty() {
688 heap_order.reserve(poses.len());
689 heap_order.extend_from_slice(&stack_order[..stack_len]);
690 }
691 heap_order.push(item);
692 }
693 }
694 let order_slice: &mut [(i32, usize)] = if heap_order.is_empty() {
695 &mut stack_order[..stack_len]
696 } else {
697 heap_order.as_mut_slice()
698 };
699 order_slice.sort_unstable_by(|a: &(i32, usize), b: &(i32, usize)| {
700 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
701 });
702 let rendered: usize = order_slice.len();
703 for &(_, idx) in order_slice.iter() {
704 let ent: &EntityRecord = &records[idx];
705 let Some(sp) = ent.sprite_component() else {
706 continue;
707 };
708 let tr: EntityTransform = poses[idx].get_transform();
709 let pos: Point = tr.get_position();
710 let center: Point = Point::new(
711 (pos.get_x() - cam_x) * zoom + half_w,
712 (pos.get_y() - cam_y) * zoom + half_h,
713 );
714 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
715 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
716 match sp.get_shape() {
717 EntityVisualShape::Rect => {
718 let rect: Rect =
719 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
720 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
721 if sp.get_accent().get_a() > 0 {
722 self.stroke_rect(rect, 1.5, sp.get_accent());
723 }
724 }
725 EntityVisualShape::Circle => {
726 let r: f32 = (w.min(h) * 0.5).max(1.0);
727 self.fill_circle(center, r, sp.get_color());
728 if sp.get_accent().get_a() > 0 && r > 3.0 {
729 self.fill_circle(center, r * 0.45, sp.get_accent());
730 }
731 }
732 EntityVisualShape::Triangle => {
733 let ang: f32 = tr.get_rotation_rad();
734 let cos_a: f32 = ang.cos();
735 let sin_a: f32 = ang.sin();
736 let rx: f32 = w * 0.55;
737 let ry: f32 = h * 0.48;
738 let nose: Point =
739 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
740 let left: Point = Point::new(
741 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
742 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
743 );
744 let right: Point = Point::new(
745 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
746 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
747 );
748 self.fill_triangle(nose, left, right, sp.get_color());
749 if sp.get_accent().get_a() > 0 {
750 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
751 }
752 }
753 EntityVisualShape::Diamond => {
754 let hw: f32 = w * 0.5;
755 let hh: f32 = h * 0.5;
756 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
757 let right: Point = Point::new(center.get_x() + hw, center.get_y());
758 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
759 let left: Point = Point::new(center.get_x() - hw, center.get_y());
760 self.fill_triangle(top, right, bottom, sp.get_color());
761 self.fill_triangle(top, bottom, left, sp.get_color());
762 if sp.get_accent().get_a() > 0 {
763 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
764 }
765 }
766 }
767 }
768 rendered
769 }
770
771 pub fn render_interpolated_world(
785 &mut self,
786 world: &GameWorld,
787 prev: &World2DSnapshot,
788 curr: &World2DSnapshot,
789 alpha: f32,
790 ) -> usize {
791 let interp: World2DSnapshot = prev.interpolate(curr, alpha);
792 self.render_snapshot_world(world, &interp)
793 }
794
795 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
807 let vp: Size = self.viewport_size();
808 let vis: Rect = camera.visible_world_rect(vp);
809 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
810 camera.projection_params(vp);
811 let n: usize = particles.get_active_count();
812 let mut count: usize = 0;
813 for i in 0..n {
814 let pos: Point = Point::new(particles.pos_x[i], particles.pos_y[i]);
815 if !vis.contains(pos) {
816 continue;
817 }
818 let t: f32 = (particles.age[i] / particles.lifetime[i].max(0.001)).clamp(0.0, 1.0);
819 let s0: f32 = particles.start_size[i];
820 let s1: f32 = particles.end_size[i];
821 let r: f32 = ((s0 + (s1 - s0) * t) * zoom).max(0.8);
822 let col: Color = particles.start_color[i].lerp(particles.end_color[i], t);
823 if col.get_a() == 0 {
824 continue;
825 }
826 let screen: Point = Point::new(
827 (pos.get_x() - cam_x) * zoom + half_w,
828 (pos.get_y() - cam_y) * zoom + half_h,
829 );
830 self.fill_circle(screen, r, col);
831 count += 1;
832 }
833 count
834 }
835
836 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
844 let vp: Size = self.viewport_size();
845 let vis: Rect = camera.visible_world_rect(vp);
846 let (cam_x, cam_y, zoom, half_w, half_h): (f32, f32, f32, f32, f32) =
847 camera.projection_params(vp);
848 for ent in world.get_entities().iter() {
849 if !ent.get_alive() {
850 continue;
851 }
852 let Some(col) = ent.collider_component() else {
853 continue;
854 };
855 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
856 if aabb.intersect(vis).is_none() {
857 continue;
858 }
859 let tl_x: f32 = (aabb.get_x() - cam_x) * zoom + half_w;
860 let tl_y: f32 = (aabb.get_y() - cam_y) * zoom + half_h;
861 let color: Color = if col.get_is_trigger() {
862 Color::rgba(250, 204, 21, 180)
863 } else {
864 Color::rgba(34, 197, 94, 180)
865 };
866 self.stroke_rect(
867 Rect::new(
868 tl_x,
869 tl_y,
870 aabb.get_width() * zoom,
871 aabb.get_height() * zoom,
872 ),
873 1.0,
874 color,
875 );
876 }
877 }
878}
879
880impl GameEngineHost {
882 #[must_use]
893 pub fn new<S>(scene: S, fixed_dt: f32) -> Self
894 where
895 S: GameScene + 'static,
896 {
897 Self {
898 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
899 input: Rc::new(RefCell::new(InputState::new())),
900 scene: Rc::new(RefCell::new(scene)),
901 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
902 last_gpu_composite: Rc::new(RefCell::new(None)),
903 paused: Rc::new(Cell::new(false)),
904 }
905 }
906
907 #[must_use]
917 pub fn last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
918 self.get_last_gpu_composite()
919 .try_borrow()
920 .ok()
921 .and_then(|g: Ref<'_, Option<GpuCompositeDescriptor>>| *g)
922 }
923
924 #[must_use]
934 pub fn take_last_gpu_composite(&self) -> Option<GpuCompositeDescriptor> {
935 self.get_last_gpu_composite()
936 .try_borrow_mut()
937 .ok()
938 .and_then(|mut g: RefMut<'_, Option<GpuCompositeDescriptor>>| g.take())
939 }
940
941 pub fn set_paused(&self, paused: bool) {
948 self.get_paused().set(paused);
949 }
950
951 #[must_use]
961 pub fn is_paused(&self) -> bool {
962 self.get_paused().get()
963 }
964
965 #[must_use]
976 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
977 let mut rects: Vec<Rect> = Vec::new();
978 let _: bool = self.collect_active_viewport_bounds(tree, &mut rects);
979 rects
980 }
981
982 pub fn collect_active_viewport_bounds(&self, tree: &SceneTree, out: &mut Vec<Rect>) -> bool {
994 if self.is_paused() {
995 return false;
996 }
997 let start_len: usize = out.len();
998 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
999 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
1000 for (_, id) in nodes.iter() {
1001 if tree.is_node_visible(*id)
1002 && let Some(bounds) = tree.node_screen_bounds(*id)
1003 && bounds.get_width() > 0.0
1004 && bounds.get_height() > 0.0
1005 {
1006 out.push(bounds);
1007 }
1008 }
1009 }
1010 out.len() > start_len
1011 }
1012
1013 pub fn ingest_event(&self, event: &WindowEvent) {
1020 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1021 input.ingest(event);
1022 }
1023 }
1024
1025 pub fn step_ns(&self, dt_ns: u64) -> u32 {
1036 if self.is_paused() {
1037 return 0;
1038 }
1039 let (steps, fixed_dt, dt_secs): (u32, f32, f32) = match self.get_clock().try_borrow_mut() {
1040 Ok(mut clock) => {
1041 let s: u32 = clock.tick_ns(dt_ns);
1042 (s, clock.get_fixed_dt(), clock.get_delta_secs())
1043 }
1044 Err(_) => (0, 1.0 / 60.0, ((dt_ns as f64) / 1_000_000_000.0) as f32),
1045 };
1046 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1047 self.mark_viewports_dirty();
1048 steps
1049 }
1050
1051 pub fn step(&self, dt_secs: f32) -> u32 {
1062 if self.is_paused() {
1063 return 0;
1064 }
1065 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
1066 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
1067 Err(_) => (0, 1.0 / 60.0),
1068 };
1069 self.dispatch_step_with_counts(steps, fixed_dt, dt_secs);
1070 self.mark_viewports_dirty();
1071 steps
1072 }
1073
1074 fn dispatch_step_with_counts(&self, steps: u32, fixed_dt: f32, dt_secs: f32) {
1083 let Self { scene, .. } = self;
1084 if let Ok(mut game) = scene.try_borrow_mut() {
1085 let input_copy: InputState = self
1086 .get_input()
1087 .try_borrow()
1088 .map(|r: Ref<'_, InputState>| *r)
1089 .unwrap_or_default();
1090 if steps == 0 {
1091 game.update(dt_secs, &input_copy);
1092 } else {
1093 game.fixed_update(fixed_dt, &input_copy);
1094 if let Ok(mut input_mut) = self.get_input().try_borrow_mut() {
1095 input_mut.begin_frame();
1096 }
1097 let cleared: InputState = input_copy.without_edges();
1098 for _ in 1..steps {
1099 game.fixed_update(fixed_dt, &cleared);
1100 }
1101 game.update(dt_secs, &cleared);
1102 }
1103 } else if steps > 0
1104 && let Ok(mut input) = self.get_input().try_borrow_mut()
1105 {
1106 input.begin_frame();
1107 }
1108 }
1109
1110 pub fn mark_viewports_dirty(&self) {
1116 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1117 nodes.retain(|(scene_handle, node_id): &(SceneHandle, NodeId)| {
1118 let (alive, visible): (bool, bool) = scene_handle.with_read(
1119 |tree: &SceneTree| -> (bool, bool) {
1120 let exists: bool = tree.get_node(*node_id).is_some();
1121 let vis: bool = exists
1122 && tree.is_node_visible(*node_id)
1123 && tree
1124 .node_screen_bounds(*node_id)
1125 .is_some_and(|b: Rect| b.get_width() > 0.0 && b.get_height() > 0.0);
1126 (exists, vis)
1127 },
1128 (false, false),
1129 );
1130 if visible {
1131 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
1132 }
1133 alive
1134 });
1135 }
1136 }
1137
1138 pub fn step_paced(&self, decision: &PacingDecision) -> u32 {
1149 match decision.get_action() {
1150 PacingAction::StepAndRender => self.step_ns(decision.get_sim_dt_ns()),
1151 PacingAction::RenderWithoutSimAdvance => {
1152 self.mark_viewports_dirty();
1153 0
1154 }
1155 PacingAction::DeferToNextVsync
1156 | PacingAction::WaitInFlight
1157 | PacingAction::SkipUserCap => 0,
1158 }
1159 }
1160
1161 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
1169 if let Ok(mut input) = self.get_input().try_borrow_mut() {
1170 input.set_virtual_stick(dx, dy);
1171 }
1172 }
1173
1174 pub fn press_key(&self, code: KeyCode) {
1181 self.ingest_event(&WindowEvent::KeyDown(
1182 WindowId::new(1),
1183 KeyEvent::new(code, Modifiers::default(), false),
1184 ));
1185 }
1186
1187 pub fn release_key(&self, code: KeyCode) {
1194 self.ingest_event(&WindowEvent::KeyUp(
1195 WindowId::new(1),
1196 KeyEvent::new(code, Modifiers::default(), false),
1197 ));
1198 }
1199
1200 #[must_use]
1214 pub fn mount_viewport(&self, style: Style) -> NodeId {
1215 let Self {
1216 clock,
1217 scene,
1218 last_gpu_composite,
1219 ..
1220 } = self;
1221 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
1222 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
1223 let gpu_out_c: Rc<RefCell<Option<GpuCompositeDescriptor>>> = last_gpu_composite.clone();
1224 let mut ctx: Context = current_context();
1225 let node: NodeId = ctx.canvas(
1226 style,
1227 move |bounds: Rect, display_list: &mut DisplayList| {
1228 let alpha: f32 = clock_c
1229 .try_borrow()
1230 .map(|c: Ref<'_, FrameClock>| c.get_alpha())
1231 .unwrap_or(1.0);
1232 if let Ok(mut game) = scene_c.try_borrow_mut() {
1233 let mut render_ctx: GameRenderContext<'_> =
1234 GameRenderContext::new(bounds, display_list);
1235 game.render(alpha, &mut render_ctx);
1236 let gpu_target: Option<GpuCompositeDescriptor> =
1237 render_ctx.take_gpu_composite_target();
1238 if let Ok(mut slot) = gpu_out_c.try_borrow_mut() {
1239 *slot = gpu_target;
1240 }
1241 }
1242 },
1243 );
1244 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
1245 nodes.retain(|(sh, nid): &(SceneHandle, NodeId)| {
1246 sh.with_read(|tree: &SceneTree| tree.get_node(*nid).is_some(), false)
1247 });
1248 nodes.push((ctx.get_scene().clone(), node));
1249 }
1250 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
1251 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1252 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
1253 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
1254 let host_move: Self = self.clone();
1255 let host_up: Self = self.clone();
1256 ctx.on_pointer_down(node, move |ev: &UiEvent| {
1257 if let UiEventKind::PointerDown(pt) = ev.get_kind()
1258 && let Ok(mut guard) = origin_down.try_borrow_mut()
1259 {
1260 *guard = Some(*pt);
1261 }
1262 });
1263 ctx.on_pointer_move(node, move |ev: &UiEvent| {
1264 if let UiEventKind::PointerMove(pt) = ev.get_kind()
1265 && let Ok(guard) = origin_move.try_borrow()
1266 && let Some(orig) = *guard
1267 {
1268 let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
1269 let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
1270 host_move.set_virtual_stick(dx, dy);
1271 }
1272 });
1273 ctx.on_pointer_up(node, move |_: &UiEvent| {
1274 if let Ok(mut guard) = origin_up.try_borrow_mut() {
1275 *guard = None;
1276 }
1277 host_up.set_virtual_stick(0.0, 0.0);
1278 });
1279 node
1280 }
1281}