|
| 1 | +use std::sync::Mutex; |
| 2 | + |
| 3 | +use bevy_app::{App, Last, Plugin}; |
| 4 | +use bevy_ecs::schedule::IntoScheduleConfigs; |
| 5 | + |
| 6 | +use crate::{ |
| 7 | + config::DefaultGizmoConfigGroup, |
| 8 | + gizmos::{GizmoBuffer, Gizmos}, |
| 9 | + GizmoMeshSystems, |
| 10 | +}; |
| 11 | + |
| 12 | +static GLOBAL_GIZMO: Mutex<GizmoBuffer<DefaultGizmoConfigGroup, ()>> = |
| 13 | + Mutex::new(GizmoBuffer::new()); |
| 14 | + |
| 15 | +/// Lets you use bevy gizmos outside of systems. |
| 16 | +pub struct GlobalGizmosPlugin; |
| 17 | + |
| 18 | +impl Plugin for GlobalGizmosPlugin { |
| 19 | + fn build(&self, app: &mut App) { |
| 20 | + app.add_systems(Last, flush_global_gizmos.before(GizmoMeshSystems)); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +fn flush_global_gizmos(mut gizmos: Gizmos) { |
| 25 | + let mut buffer = GizmoBuffer::new(); |
| 26 | + { |
| 27 | + core::mem::swap(&mut buffer, &mut GLOBAL_GIZMO.lock().unwrap()); |
| 28 | + } |
| 29 | + gizmos.strip_positions.extend(buffer.strip_positions); |
| 30 | + gizmos.strip_colors.extend(buffer.strip_colors); |
| 31 | + gizmos.list_positions.extend(buffer.list_positions); |
| 32 | + gizmos.list_colors.extend(buffer.list_colors); |
| 33 | +} |
| 34 | + |
| 35 | +/// A global gizmo context for use outside of bevy systems. |
| 36 | +/// |
| 37 | +/// # Example |
| 38 | +/// ``` |
| 39 | +/// # use bevy_gizmos::prelude::*; |
| 40 | +/// # use bevy_math::prelude::*; |
| 41 | +/// # use bevy_color::palettes::basic::WHITE; |
| 42 | +/// fn draw() { |
| 43 | +/// gizmo().sphere(Isometry3d::IDENTITY, 0.5, WHITE); |
| 44 | +/// } |
| 45 | +/// ``` |
| 46 | +pub fn gizmo() -> impl core::ops::DerefMut<Target = GizmoBuffer<DefaultGizmoConfigGroup, ()>> { |
| 47 | + GlobalGizmos { |
| 48 | + guard: GLOBAL_GIZMO.lock().unwrap(), |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +struct GlobalGizmos<'a> { |
| 53 | + guard: std::sync::MutexGuard<'a, GizmoBuffer<DefaultGizmoConfigGroup, ()>>, |
| 54 | +} |
| 55 | + |
| 56 | +impl<'a> core::ops::Deref for GlobalGizmos<'a> { |
| 57 | + type Target = GizmoBuffer<DefaultGizmoConfigGroup, ()>; |
| 58 | + |
| 59 | + fn deref(&self) -> &Self::Target { |
| 60 | + &self.guard |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +impl<'a> core::ops::DerefMut for GlobalGizmos<'a> { |
| 65 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 66 | + &mut self.guard |
| 67 | + } |
| 68 | +} |
0 commit comments