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 }
20 }
21
22 #[must_use]
32 pub fn viewport_size(&self) -> Size {
33 let Self { bounds, .. } = self;
34 Size::new(bounds.get_width(), bounds.get_height())
35 }
36
37 pub fn clear(&mut self, color: Color) {
44 let Self {
45 bounds,
46 display_list,
47 } = self;
48 display_list.push(DrawCommand::FillRoundedRect {
49 rect: *bounds,
50 color,
51 radius: CornerRadius::default(),
52 border: Border::default(),
53 });
54 }
55
56 pub fn fill_rect(&mut self, rect: Rect, color: Color) {
64 self.fill_rounded_rect(rect, color, 0.0);
65 }
66
67 pub fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
76 let Self {
77 bounds,
78 display_list,
79 } = self;
80 let world: Rect = Rect::new(
81 bounds.get_x() + rect.get_x(),
82 bounds.get_y() + rect.get_y(),
83 rect.get_width(),
84 rect.get_height(),
85 );
86 display_list.push(DrawCommand::FillRoundedRect {
87 rect: world,
88 color,
89 radius: CornerRadius::all(radius),
90 border: Border::default(),
91 });
92 }
93
94 pub fn stroke_rect(&mut self, rect: Rect, stroke_width: f32, color: Color) {
103 let Self {
104 bounds,
105 display_list,
106 } = self;
107 let world: Rect = Rect::new(
108 bounds.get_x() + rect.get_x(),
109 bounds.get_y() + rect.get_y(),
110 rect.get_width(),
111 rect.get_height(),
112 );
113 display_list.push(DrawCommand::FillRoundedRect {
114 rect: world,
115 color: COLOR_TRANSPARENT,
116 radius: CornerRadius::default(),
117 border: Border::new(stroke_width, color),
118 });
119 }
120
121 pub fn fill_circle(&mut self, center: Point, radius: f32, color: Color) {
130 let Self {
131 bounds,
132 display_list,
133 } = self;
134 let world: Point = Point::new(
135 bounds.get_x() + center.get_x(),
136 bounds.get_y() + center.get_y(),
137 );
138 display_list.push(DrawCommand::Circle {
139 center: world,
140 radius,
141 color,
142 });
143 }
144
145 pub fn draw_image(&mut self, rect: Rect, buffer: ImageBuffer) {
153 let Self {
154 bounds,
155 display_list,
156 } = self;
157 let world: Rect = Rect::new(
158 bounds.get_x() + rect.get_x(),
159 bounds.get_y() + rect.get_y(),
160 rect.get_width(),
161 rect.get_height(),
162 );
163 display_list.push(DrawCommand::Image {
164 rect: world,
165 buffer,
166 radius: CornerRadius::default(),
167 });
168 }
169
170 pub fn draw_line(&mut self, from: Point, to: Point, width: f32, color: Color) {
180 let Self {
181 bounds,
182 display_list,
183 } = self;
184 display_list.push(DrawCommand::Line {
185 from: Point::new(bounds.get_x() + from.get_x(), bounds.get_y() + from.get_y()),
186 to: Point::new(bounds.get_x() + to.get_x(), bounds.get_y() + to.get_y()),
187 color,
188 width,
189 });
190 }
191
192 pub fn draw_text(&mut self, position: Point, text: String, font_size: f32, color: Color) {
202 let Self {
203 bounds,
204 display_list,
205 } = self;
206 let mut style: TextStyle = TextStyle::default();
207 style.set_font_size(font_size);
208 style.set_color(color);
209 display_list.push(DrawCommand::TextRun {
210 rect: Rect::new(
211 bounds.get_x() + position.get_x(),
212 bounds.get_y() + position.get_y(),
213 (bounds.get_width() - position.get_x()).max(0.0),
214 font_size * 1.6,
215 ),
216 text,
217 style,
218 });
219 }
220
221 pub fn blit_framebuffer(&mut self, rect: Rect, buffer: ImageBuffer) {
229 let Self {
230 bounds,
231 display_list,
232 } = self;
233 let world: Rect = Rect::new(
234 bounds.get_x() + rect.get_x(),
235 bounds.get_y() + rect.get_y(),
236 rect.get_width(),
237 rect.get_height(),
238 );
239 display_list.push(DrawCommand::Image {
240 rect: world,
241 buffer,
242 radius: CornerRadius::default(),
243 });
244 }
245
246 pub fn fill_triangle(&mut self, p0: Point, p1: Point, p2: Point, color: Color) {
256 let Self {
257 bounds,
258 display_list,
259 } = self;
260 let ox: f32 = bounds.get_x();
261 let oy: f32 = bounds.get_y();
262 display_list.push(DrawCommand::Triangle {
263 p0: Point::new(ox + p0.get_x(), oy + p0.get_y()),
264 p1: Point::new(ox + p1.get_x(), oy + p1.get_y()),
265 p2: Point::new(ox + p2.get_x(), oy + p2.get_y()),
266 color,
267 });
268 }
269
270 pub fn draw_sprite_frame(
280 &mut self,
281 sheet: &SpriteSheet,
282 frame_index: u32,
283 rect: Rect,
284 tint: Color,
285 ) {
286 let src_rect: Rect = sheet.frame_rect(frame_index);
287 let Self {
288 bounds,
289 display_list,
290 } = self;
291 display_list.push(DrawCommand::SpriteRegion {
292 rect: Rect::new(
293 bounds.get_x() + rect.get_x(),
294 bounds.get_y() + rect.get_y(),
295 rect.get_width(),
296 rect.get_height(),
297 ),
298 buffer: sheet.get_texture().clone(),
299 src_rect,
300 tint,
301 });
302 }
303
304 pub fn render_tilemap(&mut self, tilemap: &TileMap, camera: &Camera2D) {
312 let vp: Size = self.viewport_size();
313 let vis: Rect = camera.visible_world_rect(vp);
314 let ts: f32 = tilemap.get_tile_size();
315 let zoom: f32 = camera.get_zoom().max(0.25);
316 let min_c: usize = (vis.get_x() / ts).floor().max(0.0) as usize;
317 let max_c: usize = ((vis.right() / ts).ceil().max(0.0) as usize).min(tilemap.get_columns());
318 let min_r: usize = (vis.get_y() / ts).floor().max(0.0) as usize;
319 let max_r: usize = ((vis.bottom() / ts).ceil().max(0.0) as usize).min(tilemap.get_rows());
320 let tile_px: f32 = (ts * zoom).max(1.0);
321 for row in min_r..max_r {
322 for col in min_c..max_c {
323 let tid: u16 = tilemap.tile_at(col, row);
324 if tid == 0 {
325 continue;
326 }
327 let Some(entry) = tilemap.get_palette().get(tid as usize) else {
328 continue;
329 };
330 let world_pt: Point = Point::new((col as f32) * ts, (row as f32) * ts);
331 let screen_pt: Point = camera.world_to_screen(world_pt, vp);
332 let tile_rect: Rect = Rect::new(
333 screen_pt.get_x(),
334 screen_pt.get_y(),
335 tile_px + 0.5,
336 tile_px + 0.5,
337 );
338 self.fill_rect(tile_rect, entry.get_color());
339 }
340 }
341 }
342
343 pub fn render_world(&mut self, world: &GameWorld, camera: &Camera2D) -> usize {
355 let vp: Size = self.viewport_size();
356 let vis: Rect = camera.visible_world_rect(vp);
357 let zoom: f32 = camera.get_zoom().max(0.25);
358 let mut draw_order: Vec<(i32, usize)> = Vec::with_capacity(world.get_live_count());
359 for (idx, ent) in world.get_entities().iter().enumerate() {
360 if !ent.get_alive() {
361 continue;
362 }
363 let Some(sp) = ent.sprite_component() else {
364 continue;
365 };
366 if !sp.get_visible() {
367 continue;
368 }
369 if ent.world_bounds().intersect(vis).is_none() {
370 continue;
371 }
372 draw_order.push((sp.get_z_order(), idx));
373 }
374 draw_order.sort_by(|a: &(i32, usize), b: &(i32, usize)| {
375 a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
376 });
377 let rendered: usize = draw_order.len();
378 for (_, idx) in draw_order.into_iter() {
379 let ent: &EntityRecord = &world.get_entities()[idx];
380 let Some(sp) = ent.sprite_component() else {
381 continue;
382 };
383 let tr: EntityTransform = ent.get_transform();
384 let center: Point = camera.world_to_screen(tr.get_position(), vp);
385 let w: f32 = sp.get_size().get_width() * tr.get_scale().get_width() * zoom;
386 let h: f32 = sp.get_size().get_height() * tr.get_scale().get_height() * zoom;
387 match sp.get_shape() {
388 EntityVisualShape::Rect => {
389 let rect: Rect =
390 Rect::new(center.get_x() - w * 0.5, center.get_y() - h * 0.5, w, h);
391 self.fill_rounded_rect(rect, sp.get_color(), sp.get_corner_radius() * zoom);
392 if sp.get_accent().get_a() > 0 {
393 self.stroke_rect(rect, 1.5, sp.get_accent());
394 }
395 }
396 EntityVisualShape::Circle => {
397 let r: f32 = (w.min(h) * 0.5).max(1.0);
398 self.fill_circle(center, r, sp.get_color());
399 if sp.get_accent().get_a() > 0 && r > 3.0 {
400 self.fill_circle(center, r * 0.45, sp.get_accent());
401 }
402 }
403 EntityVisualShape::Triangle => {
404 let ang: f32 = tr.get_rotation_rad();
405 let cos_a: f32 = ang.cos();
406 let sin_a: f32 = ang.sin();
407 let rx: f32 = w * 0.55;
408 let ry: f32 = h * 0.48;
409 let nose: Point =
410 Point::new(center.get_x() + cos_a * rx, center.get_y() + sin_a * rx);
411 let left: Point = Point::new(
412 center.get_x() - cos_a * (rx * 0.72) - sin_a * ry,
413 center.get_y() - sin_a * (rx * 0.72) + cos_a * ry,
414 );
415 let right: Point = Point::new(
416 center.get_x() - cos_a * (rx * 0.72) + sin_a * ry,
417 center.get_y() - sin_a * (rx * 0.72) - cos_a * ry,
418 );
419 self.fill_triangle(nose, left, right, sp.get_color());
420 if sp.get_accent().get_a() > 0 {
421 self.fill_circle(center, (w.min(h) * 0.16).max(2.0), sp.get_accent());
422 }
423 }
424 EntityVisualShape::Diamond => {
425 let hw: f32 = w * 0.5;
426 let hh: f32 = h * 0.5;
427 let top: Point = Point::new(center.get_x(), center.get_y() - hh);
428 let right: Point = Point::new(center.get_x() + hw, center.get_y());
429 let bottom: Point = Point::new(center.get_x(), center.get_y() + hh);
430 let left: Point = Point::new(center.get_x() - hw, center.get_y());
431 self.fill_triangle(top, right, bottom, sp.get_color());
432 self.fill_triangle(top, bottom, left, sp.get_color());
433 if sp.get_accent().get_a() > 0 {
434 self.fill_circle(center, (w.min(h) * 0.18).max(2.0), sp.get_accent());
435 }
436 }
437 }
438 }
439 rendered
440 }
441
442 pub fn render_particles(&mut self, particles: &ParticleSystem, camera: &Camera2D) -> usize {
454 let vp: Size = self.viewport_size();
455 let vis: Rect = camera.visible_world_rect(vp);
456 let zoom: f32 = camera.get_zoom().max(0.25);
457 let mut count: usize = 0;
458 for p in particles.get_pool().iter() {
459 if !p.get_active() {
460 continue;
461 }
462 let pos: Point = p.get_position();
463 if !vis.contains(pos) {
464 continue;
465 }
466 let t: f32 = (p.get_age() / p.get_lifetime().max(0.001)).clamp(0.0, 1.0);
467 let r: f32 = ((p.get_start_size() + (p.get_end_size() - p.get_start_size()) * t)
468 * zoom)
469 .max(0.8);
470 let col: Color = p.get_start_color().lerp(p.get_end_color(), t);
471 if col.get_a() == 0 {
472 continue;
473 }
474 let screen: Point = camera.world_to_screen(pos, vp);
475 self.fill_circle(screen, r, col);
476 count += 1;
477 }
478 count
479 }
480
481 pub fn draw_debug_colliders(&mut self, world: &GameWorld, camera: &Camera2D) {
489 let vp: Size = self.viewport_size();
490 let vis: Rect = camera.visible_world_rect(vp);
491 let zoom: f32 = camera.get_zoom().max(0.25);
492 for ent in world.get_entities().iter() {
493 if !ent.get_alive() {
494 continue;
495 }
496 let Some(col) = ent.collider_component() else {
497 continue;
498 };
499 let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
500 if aabb.intersect(vis).is_none() {
501 continue;
502 }
503 let tl: Point = camera.world_to_screen(Point::new(aabb.get_x(), aabb.get_y()), vp);
504 let color: Color = if col.get_is_trigger() {
505 Color::rgba(250, 204, 21, 180)
506 } else {
507 Color::rgba(34, 197, 94, 180)
508 };
509 self.stroke_rect(
510 Rect::new(
511 tl.get_x(),
512 tl.get_y(),
513 aabb.get_width() * zoom,
514 aabb.get_height() * zoom,
515 ),
516 1.0,
517 color,
518 );
519 }
520 }
521}
522
523impl GameEngineHost {
525 #[must_use]
536 pub fn new<S>(scene: S, fixed_dt: f32) -> Self
537 where
538 S: GameScene + 'static,
539 {
540 Self {
541 clock: Rc::new(RefCell::new(FrameClock::new(fixed_dt, 8))),
542 input: Rc::new(RefCell::new(InputState::new())),
543 scene: Rc::new(RefCell::new(scene)),
544 viewport_nodes: Rc::new(RefCell::new(Vec::new())),
545 paused: Rc::new(Cell::new(false)),
546 }
547 }
548
549 pub fn set_paused(&self, paused: bool) {
556 self.get_paused().set(paused);
557 }
558
559 #[must_use]
569 pub fn is_paused(&self) -> bool {
570 self.get_paused().get()
571 }
572
573 #[must_use]
584 pub fn active_viewport_bounds(&self, tree: &SceneTree) -> Vec<Rect> {
585 if self.is_paused() {
586 return Vec::new();
587 }
588 let mut rects: Vec<Rect> = Vec::new();
589 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
590 nodes.retain(|(_, id): &(SceneHandle, NodeId)| tree.get_node(*id).is_some());
591 for (_, id) in nodes.iter() {
592 if tree.is_node_visible(*id)
593 && let Some(bounds) = tree.node_screen_bounds(*id)
594 && bounds.get_width() > 0.0
595 && bounds.get_height() > 0.0
596 {
597 rects.push(bounds);
598 }
599 }
600 }
601 rects
602 }
603
604 pub fn ingest_event(&self, event: &WindowEvent) {
611 if let Ok(mut input) = self.get_input().try_borrow_mut() {
612 input.ingest(event);
613 }
614 }
615
616 pub fn step(&self, dt_secs: f32) -> u32 {
627 if self.is_paused() {
628 return 0;
629 }
630 let (steps, fixed_dt): (u32, f32) = match self.get_clock().try_borrow_mut() {
631 Ok(mut clock) => (clock.tick(dt_secs), clock.get_fixed_dt()),
632 Err(_) => (0, 1.0 / 60.0),
633 };
634 let input_snapshot: InputState = self
635 .get_input()
636 .try_borrow()
637 .map(|guard: Ref<'_, InputState>| guard.clone())
638 .unwrap_or_default();
639 let Self { scene, .. } = self;
640 if let Ok(mut game) = scene.try_borrow_mut() {
641 for _ in 0..steps {
642 game.fixed_update(fixed_dt, &input_snapshot);
643 }
644 game.update(dt_secs, &input_snapshot);
645 }
646 if let Ok(mut input) = self.get_input().try_borrow_mut() {
647 input.begin_frame();
648 }
649 if let Ok(nodes) = self.get_viewport_nodes().try_borrow() {
650 for (scene_handle, node_id) in nodes.iter() {
651 scene_handle.mark_dirty(*node_id, DIRTY_PAINT);
652 }
653 }
654 steps
655 }
656
657 pub fn set_virtual_stick(&self, dx: f32, dy: f32) {
665 if let Ok(mut input) = self.get_input().try_borrow_mut() {
666 input.set_virtual_stick(dx, dy);
667 }
668 }
669
670 pub fn press_key(&self, code: KeyCode) {
677 self.ingest_event(&WindowEvent::KeyDown(
678 WindowId::new(1),
679 KeyEvent::new(code, Modifiers::default(), false),
680 ));
681 }
682
683 pub fn release_key(&self, code: KeyCode) {
690 self.ingest_event(&WindowEvent::KeyUp(
691 WindowId::new(1),
692 KeyEvent::new(code, Modifiers::default(), false),
693 ));
694 }
695
696 #[must_use]
710 pub fn mount_viewport(&self, style: Style) -> NodeId {
711 let Self { clock, scene, .. } = self;
712 let clock_c: Rc<RefCell<FrameClock>> = clock.clone();
713 let scene_c: Rc<RefCell<dyn GameScene>> = scene.clone();
714 let mut ctx: Context = current_context();
715 let node: NodeId = ctx.canvas(
716 style,
717 move |bounds: Rect, display_list: &mut DisplayList| {
718 let alpha: f32 = clock_c
719 .try_borrow()
720 .map(|c: Ref<'_, FrameClock>| c.get_alpha())
721 .unwrap_or(1.0);
722 if let Ok(mut game) = scene_c.try_borrow_mut() {
723 let mut render_ctx: GameRenderContext<'_> =
724 GameRenderContext::new(bounds, display_list);
725 game.render(alpha, &mut render_ctx);
726 }
727 },
728 );
729 if let Ok(mut nodes) = self.get_viewport_nodes().try_borrow_mut() {
730 nodes.push((ctx.get_scene().clone(), node));
731 }
732 let drag_origin: Rc<RefCell<Option<Point>>> = Rc::new(RefCell::new(None));
733 let origin_down: Rc<RefCell<Option<Point>>> = drag_origin.clone();
734 let origin_move: Rc<RefCell<Option<Point>>> = drag_origin.clone();
735 let origin_up: Rc<RefCell<Option<Point>>> = drag_origin;
736 let host_move: Self = self.clone();
737 let host_up: Self = self.clone();
738 ctx.on_pointer_down(node, move |ev: &UiEvent| {
739 if let UiEventKind::PointerDown(pt) = ev.get_kind()
740 && let Ok(mut guard) = origin_down.try_borrow_mut()
741 {
742 *guard = Some(*pt);
743 }
744 });
745 ctx.on_pointer_move(node, move |ev: &UiEvent| {
746 if let UiEventKind::PointerMove(pt) = ev.get_kind()
747 && let Ok(guard) = origin_move.try_borrow()
748 && let Some(orig) = *guard
749 {
750 let dx: f32 = ((pt.get_x() - orig.get_x()) / 48.0).clamp(-1.0, 1.0);
751 let dy: f32 = ((pt.get_y() - orig.get_y()) / 48.0).clamp(-1.0, 1.0);
752 host_move.set_virtual_stick(dx, dy);
753 }
754 });
755 ctx.on_pointer_up(node, move |_: &UiEvent| {
756 if let Ok(mut guard) = origin_up.try_borrow_mut() {
757 *guard = None;
758 }
759 host_up.set_virtual_stick(0.0, 0.0);
760 });
761 node
762 }
763}