Arc & Rc cleanup

master
Mark 2024-02-03 21:52:42 -08:00
parent e893da01bc
commit 7ce169bbea
Signed by: Mark
GPG Key ID: C6D63995FE72FD80
11 changed files with 62 additions and 65 deletions

View File

@ -4,12 +4,12 @@ use galactica_system::data::ShipPersonality;
use galactica_system::phys::{PhysImage, PhysSim, PhysSimShipHandle, PhysStepResources}; use galactica_system::phys::{PhysImage, PhysSim, PhysSimShipHandle, PhysStepResources};
use galactica_util::timing::Timing; use galactica_util::timing::Timing;
use nalgebra::Point2; use nalgebra::Point2;
use std::rc::Rc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
pub struct Game { pub struct Game {
// Core game data // Core game data
ct: Rc<Content>, ct: Arc<Content>,
phys_sim: PhysSim, phys_sim: PhysSim,
timing: Timing, timing: Timing,
start_instant: Instant, start_instant: Instant,
@ -44,7 +44,7 @@ impl<'a> Game {
return player; return player;
} }
pub fn new(ct: Rc<Content>) -> Self { pub fn new(ct: Arc<Content>) -> Self {
let mut phys_sim = PhysSim::new(&ct, SystemHandle { index: 0 }); let mut phys_sim = PhysSim::new(&ct, SystemHandle { index: 0 });
let a = phys_sim.add_ship( let a = phys_sim.add_ship(

View File

@ -21,7 +21,7 @@ use nalgebra::Vector2;
use std::{ use std::{
fs, fs,
path::{Path, PathBuf}, path::{Path, PathBuf},
rc::Rc, sync::Arc,
time::Instant, time::Instant,
}; };
use winit::{ use winit::{
@ -113,7 +113,7 @@ fn try_main() -> Result<()> {
} }
// TODO: pretty error if missing (also in cli) // TODO: pretty error if missing (also in cli)
let content = Rc::new(Content::load_dir( let content = Arc::new(Content::load_dir(
PathBuf::from("./content"), PathBuf::from("./content"),
PathBuf::from("./assets"), PathBuf::from("./assets"),
atlas_index, atlas_index,
@ -128,12 +128,12 @@ fn try_main() -> Result<()> {
let mut game = game::Game::new(content.clone()); let mut game = game::Game::new(content.clone());
let p = game.make_player(); let p = game.make_player();
let mut player = Rc::new(PlayerAgent::new(p.0)); let mut player = Arc::new(PlayerAgent::new(p.0));
Rc::get_mut(&mut player).unwrap().set_camera_aspect( Arc::get_mut(&mut player).unwrap().set_camera_aspect(
gpu.window().inner_size().width as f32 / gpu.window().inner_size().height as f32, gpu.window().inner_size().width as f32 / gpu.window().inner_size().height as f32,
); );
let mut phys_img = Rc::new(PhysImage::new()); let mut phys_img = Arc::new(PhysImage::new());
let mut last_run = Instant::now(); let mut last_run = Instant::now();
event_loop.run(move |event, _, control_flow| { event_loop.run(move |event, _, control_flow| {
@ -162,9 +162,9 @@ fn try_main() -> Result<()> {
} }
Event::MainEventsCleared => { Event::MainEventsCleared => {
game.update_player_controls(Rc::get_mut(&mut player).unwrap()); game.update_player_controls(Arc::get_mut(&mut player).unwrap());
game.step(&phys_img); game.step(&phys_img);
game.update_image(Rc::get_mut(&mut phys_img).unwrap()); game.update_image(Arc::get_mut(&mut phys_img).unwrap());
// TODO: clean up // TODO: clean up
let player_status = { let player_status = {
@ -193,10 +193,10 @@ fn try_main() -> Result<()> {
}; };
// This must be updated BEFORE rendering! // This must be updated BEFORE rendering!
Rc::get_mut(&mut player) Arc::get_mut(&mut player)
.unwrap() .unwrap()
.step(&content, player_status); .step(&content, player_status);
Rc::get_mut(&mut player).unwrap().input.clear_inputs(); Arc::get_mut(&mut player).unwrap().input.clear_inputs();
gpu.window().request_redraw(); gpu.window().request_redraw();
} }
@ -217,39 +217,39 @@ fn try_main() -> Result<()> {
}, },
.. ..
} => { } => {
Rc::get_mut(&mut player) Arc::get_mut(&mut player)
.unwrap() .unwrap()
.input .input
.process_key(state, key); .process_key(state, key);
} }
WindowEvent::CursorMoved { position, .. } => { WindowEvent::CursorMoved { position, .. } => {
Rc::get_mut(&mut player) Arc::get_mut(&mut player)
.unwrap() .unwrap()
.input .input
.process_mouse(position); .process_mouse(position);
} }
WindowEvent::MouseInput { state, button, .. } => { WindowEvent::MouseInput { state, button, .. } => {
Rc::get_mut(&mut player) Arc::get_mut(&mut player)
.unwrap() .unwrap()
.input .input
.process_click(state, button); .process_click(state, button);
} }
WindowEvent::MouseWheel { delta, phase, .. } => { WindowEvent::MouseWheel { delta, phase, .. } => {
Rc::get_mut(&mut player) Arc::get_mut(&mut player)
.unwrap() .unwrap()
.input .input
.process_scroll(delta, phase); .process_scroll(delta, phase);
} }
WindowEvent::Resized(_) => { WindowEvent::Resized(_) => {
gpu.resize(&content); gpu.resize(&content);
Rc::get_mut(&mut player).unwrap().set_camera_aspect( Arc::get_mut(&mut player).unwrap().set_camera_aspect(
gpu.window().inner_size().width as f32 gpu.window().inner_size().width as f32
/ gpu.window().inner_size().height as f32, / gpu.window().inner_size().height as f32,
); );
} }
WindowEvent::ScaleFactorChanged { .. } => { WindowEvent::ScaleFactorChanged { .. } => {
gpu.resize(&content); gpu.resize(&content);
Rc::get_mut(&mut player).unwrap().set_camera_aspect( Arc::get_mut(&mut player).unwrap().set_camera_aspect(
gpu.window().inner_size().width as f32 gpu.window().inner_size().width as f32
/ gpu.window().inner_size().height as f32, / gpu.window().inner_size().height as f32,
); );

View File

@ -1,5 +1,3 @@
use std::{iter, rc::Rc};
use anyhow::Result; use anyhow::Result;
use bytemuck; use bytemuck;
use galactica_content::Content; use galactica_content::Content;
@ -7,6 +5,7 @@ use galactica_system::data::ShipState;
use galactica_util::to_radians; use galactica_util::to_radians;
use glyphon::{FontSystem, Resolution, SwashCache, TextAtlas, TextRenderer}; use glyphon::{FontSystem, Resolution, SwashCache, TextAtlas, TextRenderer};
use nalgebra::{Point2, Point3}; use nalgebra::{Point2, Point3};
use std::{iter, sync::Arc};
use wgpu; use wgpu;
use winit; use winit;
@ -38,7 +37,7 @@ pub struct GPUState {
impl GPUState { impl GPUState {
/// Make a new GPUState that draws on `window` /// Make a new GPUState that draws on `window`
pub async fn new(window: winit::window::Window, ct: Rc<Content>) -> Result<Self> { pub async fn new(window: winit::window::Window, ct: Arc<Content>) -> Result<Self> {
let window_size = window.inner_size(); let window_size = window.inner_size();
let window_aspect = window_size.width as f32 / window_size.height as f32; let window_aspect = window_size.width as f32 / window_size.height as f32;
@ -278,7 +277,7 @@ impl GPUState {
/// Main render function. Draws sprites on a window. /// Main render function. Draws sprites on a window.
pub fn render(&mut self, input: RenderInput) -> Result<(), wgpu::SurfaceError> { pub fn render(&mut self, input: RenderInput) -> Result<(), wgpu::SurfaceError> {
let input = Rc::new(input); let input = Arc::new(input);
// Update global values // Update global values
self.state.queue.write_buffer( self.state.queue.write_buffer(

View File

@ -1,4 +1,3 @@
use std::rc::Rc;
use wgpu; use wgpu;
use crate::vertexbuffer::VertexBuffer; use crate::vertexbuffer::VertexBuffer;
@ -16,7 +15,7 @@ pub struct PipelineBuilder<'a> {
// These must be provided // These must be provided
shader: Option<&'a str>, shader: Option<&'a str>,
format: Option<wgpu::TextureFormat>, format: Option<wgpu::TextureFormat>,
vertex_buffer: Option<&'a Rc<VertexBuffer>>, vertex_buffer: Option<&'a VertexBuffer>,
} }
impl<'a> PipelineBuilder<'a> { impl<'a> PipelineBuilder<'a> {
@ -49,7 +48,7 @@ impl<'a> PipelineBuilder<'a> {
self self
} }
pub fn set_vertex_buffer(mut self, vertex_buffer: &'a Rc<VertexBuffer>) -> Self { pub fn set_vertex_buffer(mut self, vertex_buffer: &'a VertexBuffer) -> Self {
self.vertex_buffer = Some(vertex_buffer); self.vertex_buffer = Some(vertex_buffer);
self self
} }

View File

@ -1,4 +1,4 @@
use std::rc::Rc; use std::sync::Arc;
use galactica_content::{Content, SystemHandle}; use galactica_content::{Content, SystemHandle};
use galactica_playeragent::PlayerAgent; use galactica_playeragent::PlayerAgent;
@ -13,7 +13,7 @@ pub struct RenderInput {
pub camera_pos: Vector2<f32>, pub camera_pos: Vector2<f32>,
/// Player ship data /// Player ship data
pub player: Rc<PlayerAgent>, pub player: Arc<PlayerAgent>,
/// The system we're currently in /// The system we're currently in
pub current_system: SystemHandle, pub current_system: SystemHandle,
@ -22,7 +22,7 @@ pub struct RenderInput {
pub camera_zoom: f32, pub camera_zoom: f32,
/// The world state to render /// The world state to render
pub phys_img: Rc<PhysImage>, pub phys_img: Arc<PhysImage>,
// TODO: handle overflow. is it a problem? // TODO: handle overflow. is it a problem?
/// The current time, in seconds /// The current time, in seconds
@ -32,7 +32,7 @@ pub struct RenderInput {
pub time_since_last_run: f32, pub time_since_last_run: f32,
/// Game content /// Game content
pub ct: Rc<Content>, pub ct: Arc<Content>,
/// Time we spent in each part of the game loop /// Time we spent in each part of the game loop
pub timing: Timing, pub timing: Timing,

View File

@ -3,7 +3,6 @@ use galactica_util::constants::{
OBJECT_SPRITE_INSTANCE_LIMIT, RADIALBAR_SPRITE_INSTANCE_LIMIT, UI_SPRITE_INSTANCE_LIMIT, OBJECT_SPRITE_INSTANCE_LIMIT, RADIALBAR_SPRITE_INSTANCE_LIMIT, UI_SPRITE_INSTANCE_LIMIT,
}; };
use glyphon::{FontSystem, SwashCache, TextAtlas, TextRenderer}; use glyphon::{FontSystem, SwashCache, TextAtlas, TextRenderer};
use std::rc::Rc;
use wgpu::BufferAddress; use wgpu::BufferAddress;
use winit::window::Window; use winit::window::Window;
@ -26,10 +25,10 @@ pub(crate) struct VertexBuffers {
starfield_counter: BufferAddress, starfield_counter: BufferAddress,
starfield_limit: BufferAddress, starfield_limit: BufferAddress,
object: Rc<VertexBuffer>, object: VertexBuffer,
starfield: Rc<VertexBuffer>, starfield: VertexBuffer,
ui: Rc<VertexBuffer>, ui: VertexBuffer,
radialbar: Rc<VertexBuffer>, radialbar: VertexBuffer,
} }
impl<'a> VertexBuffers { impl<'a> VertexBuffers {
@ -41,53 +40,53 @@ impl<'a> VertexBuffers {
starfield_counter: 0, starfield_counter: 0,
starfield_limit: ct.get_config().starfield_instance_limit, starfield_limit: ct.get_config().starfield_instance_limit,
object: Rc::new(VertexBuffer::new::<TexturedVertex, ObjectInstance>( object: VertexBuffer::new::<TexturedVertex, ObjectInstance>(
"object", "object",
&device, &device,
Some(SPRITE_VERTICES), Some(SPRITE_VERTICES),
Some(SPRITE_INDICES), Some(SPRITE_INDICES),
OBJECT_SPRITE_INSTANCE_LIMIT, OBJECT_SPRITE_INSTANCE_LIMIT,
)), ),
starfield: Rc::new(VertexBuffer::new::<TexturedVertex, StarfieldInstance>( starfield: VertexBuffer::new::<TexturedVertex, StarfieldInstance>(
"starfield", "starfield",
&device, &device,
Some(SPRITE_VERTICES), Some(SPRITE_VERTICES),
Some(SPRITE_INDICES), Some(SPRITE_INDICES),
ct.get_config().starfield_instance_limit, ct.get_config().starfield_instance_limit,
)), ),
ui: Rc::new(VertexBuffer::new::<TexturedVertex, UiInstance>( ui: VertexBuffer::new::<TexturedVertex, UiInstance>(
"ui", "ui",
&device, &device,
Some(SPRITE_VERTICES), Some(SPRITE_VERTICES),
Some(SPRITE_INDICES), Some(SPRITE_INDICES),
UI_SPRITE_INSTANCE_LIMIT, UI_SPRITE_INSTANCE_LIMIT,
)), ),
radialbar: Rc::new(VertexBuffer::new::<TexturedVertex, RadialBarInstance>( radialbar: VertexBuffer::new::<TexturedVertex, RadialBarInstance>(
"radial bar", "radial bar",
&device, &device,
Some(SPRITE_VERTICES), Some(SPRITE_VERTICES),
Some(SPRITE_INDICES), Some(SPRITE_INDICES),
10, 10,
)), ),
} }
} }
pub fn get_ui(&'a self) -> &'a Rc<VertexBuffer> { pub fn get_ui(&'a self) -> &'a VertexBuffer {
&self.ui &self.ui
} }
pub fn get_object(&'a self) -> &'a Rc<VertexBuffer> { pub fn get_object(&'a self) -> &'a VertexBuffer {
&self.object &self.object
} }
pub fn get_radialbar(&'a self) -> &'a Rc<VertexBuffer> { pub fn get_radialbar(&'a self) -> &'a VertexBuffer {
&self.radialbar &self.radialbar
} }
pub fn get_starfield(&'a self) -> &'a Rc<VertexBuffer> { pub fn get_starfield(&'a self) -> &'a VertexBuffer {
&self.starfield &self.starfield
} }
} }

View File

@ -1,13 +1,13 @@
use galactica_content::Content; use galactica_content::Content;
use rhai::{CustomType, TypeBuilder}; use rhai::{CustomType, TypeBuilder};
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc, sync::Arc};
use crate::ui::util::RadialBar; use crate::ui::util::RadialBar;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RadialElement { pub struct RadialElement {
pub bar: Rc<RefCell<RadialBar>>, pub bar: Rc<RefCell<RadialBar>>,
pub ct: Rc<Content>, pub ct: Arc<Content>,
} }
// TODO: remove this // TODO: remove this
@ -15,7 +15,7 @@ unsafe impl Send for RadialElement {}
unsafe impl Sync for RadialElement {} unsafe impl Sync for RadialElement {}
impl RadialElement { impl RadialElement {
pub fn new(ct: Rc<Content>, bar: Rc<RefCell<RadialBar>>) -> Self { pub fn new(ct: Arc<Content>, bar: Rc<RefCell<RadialBar>>) -> Self {
Self { ct, bar } Self { ct, bar }
} }
} }

View File

@ -1,14 +1,14 @@
use galactica_content::{resolve_edge_as_edge, Content}; use galactica_content::{resolve_edge_as_edge, Content};
use log::error; use log::error;
use rhai::{CustomType, TypeBuilder}; use rhai::{CustomType, TypeBuilder};
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc, sync::Arc};
use crate::ui::util::Sprite; use crate::ui::util::Sprite;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SpriteElement { pub struct SpriteElement {
pub sprite: Rc<RefCell<Sprite>>, pub sprite: Rc<RefCell<Sprite>>,
pub ct: Rc<Content>, pub ct: Arc<Content>,
} }
// TODO: remove this // TODO: remove this
@ -16,7 +16,7 @@ unsafe impl Send for SpriteElement {}
unsafe impl Sync for SpriteElement {} unsafe impl Sync for SpriteElement {}
impl SpriteElement { impl SpriteElement {
pub fn new(ct: Rc<Content>, sprite: Rc<RefCell<Sprite>>) -> Self { pub fn new(ct: Arc<Content>, sprite: Rc<RefCell<Sprite>>) -> Self {
Self { ct, sprite } Self { ct, sprite }
} }

View File

@ -5,14 +5,14 @@ use galactica_system::{
}; };
use log::error; use log::error;
use rhai::{CustomType, TypeBuilder}; use rhai::{CustomType, TypeBuilder};
use std::rc::Rc; use std::sync::Arc;
use crate::RenderInput; use crate::RenderInput;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ShipState { pub struct ShipState {
ship: Option<PhysSimShipHandle>, ship: Option<PhysSimShipHandle>,
input: Rc<RenderInput>, input: Arc<RenderInput>,
} }
// TODO: remove this // TODO: remove this
@ -94,7 +94,7 @@ impl CustomType for ShipState {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SystemObjectState { pub struct SystemObjectState {
object: Option<SystemObjectHandle>, object: Option<SystemObjectHandle>,
input: Rc<RenderInput>, input: Arc<RenderInput>,
} }
// TODO: remove this // TODO: remove this
@ -152,7 +152,7 @@ impl CustomType for SystemObjectState {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct State { pub struct State {
input: Rc<RenderInput>, input: Arc<RenderInput>,
} }
// TODO: remove this // TODO: remove this
@ -160,7 +160,7 @@ unsafe impl Send for State {}
unsafe impl Sync for State {} unsafe impl Sync for State {}
impl State { impl State {
pub fn new(input: Rc<RenderInput>) -> Self { pub fn new(input: Arc<RenderInput>) -> Self {
Self { input } Self { input }
} }

View File

@ -4,7 +4,7 @@ use galactica_system::phys::PhysSimShipHandle;
use glyphon::TextArea; use glyphon::TextArea;
use log::{debug, error, trace}; use log::{debug, error, trace};
use rhai::{Array, Dynamic, Engine, Map, Scope}; use rhai::{Array, Dynamic, Engine, Map, Scope};
use std::{collections::HashSet, num::NonZeroU32, rc::Rc}; use std::{collections::HashSet, num::NonZeroU32, sync::Arc};
use super::{ use super::{
api::{ api::{
@ -28,7 +28,7 @@ pub(crate) struct UiManager {
current_scene_config: SceneConfig, current_scene_config: SceneConfig,
engine: Engine, engine: Engine,
scope: Scope<'static>, scope: Scope<'static>,
ct: Rc<Content>, ct: Arc<Content>,
/// UI elements /// UI elements
elements: Vec<UiElement>, elements: Vec<UiElement>,
@ -42,7 +42,7 @@ pub(crate) struct UiManager {
} }
impl UiManager { impl UiManager {
pub fn new(ct: Rc<Content>, state: &mut RenderState) -> Self { pub fn new(ct: Arc<Content>, state: &mut RenderState) -> Self {
let scope = Scope::new(); let scope = Scope::new();
let mut engine = Engine::new_raw(); let mut engine = Engine::new_raw();
@ -70,7 +70,7 @@ impl UiManager {
pub fn set_scene( pub fn set_scene(
&mut self, &mut self,
state: &mut RenderState, state: &mut RenderState,
input: Rc<RenderInput>, input: Arc<RenderInput>,
scene: String, scene: String,
) -> Result<()> { ) -> Result<()> {
if !self.ct.get_config().ui_scenes.contains_key(&scene) { if !self.ct.get_config().ui_scenes.contains_key(&scene) {
@ -207,7 +207,7 @@ impl UiManager {
} }
/// Draw all ui elements /// Draw all ui elements
pub fn draw(&mut self, input: Rc<RenderInput>, state: &mut RenderState) -> Result<()> { pub fn draw(&mut self, input: Arc<RenderInput>, state: &mut RenderState) -> Result<()> {
// Initialize start scene if we haven't yet // Initialize start scene if we haven't yet
if self.current_scene.is_none() { if self.current_scene.is_none() {
self.set_scene( self.set_scene(
@ -372,7 +372,7 @@ impl UiManager {
fn handle_action( fn handle_action(
&mut self, &mut self,
state: &mut RenderState, state: &mut RenderState,
input: Rc<RenderInput>, input: Arc<RenderInput>,
action: SceneAction, action: SceneAction,
) -> Result<bool> { ) -> Result<bool> {
Ok(match action { Ok(match action {

View File

@ -1,4 +1,4 @@
use std::rc::Rc; use std::sync::Arc;
use galactica_content::Content; use galactica_content::Content;
use galactica_util::timing::Timing; use galactica_util::timing::Timing;
@ -6,7 +6,7 @@ use galactica_util::timing::Timing;
/// External resources we need to compute time steps /// External resources we need to compute time steps
pub struct PhysStepResources<'a> { pub struct PhysStepResources<'a> {
/// Game content /// Game content
pub ct: Rc<Content>, pub ct: Arc<Content>,
/// Length of time step /// Length of time step
pub t: f32, pub t: f32,