1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! Bevy plugin for rendering Bones framework games.

#![warn(missing_docs)]
// This cfg_attr is needed because `rustdoc::all` includes lints not supported on stable
#![cfg_attr(doc, allow(unknown_lints))]
#![deny(rustdoc::all)]

pub use bevy;

/// The prelude
pub mod prelude {
    pub use crate::*;
}

mod debug;
mod storage;

mod convert;
use convert::*;
mod input;
use input::*;
mod render;
use render::*;
mod ui;
use ui::*;
mod rumble;
use bevy::{log::LogPlugin, prelude::*};
use bones::GamepadsRumble;
use bones_framework::prelude as bones;
use rumble::*;

use bevy::{
    input::InputSystem,
    render::RenderApp,
    sprite::{extract_sprites, SpriteSystem},
    tasks::IoTaskPool,
    utils::Instant,
};
use std::path::{Path, PathBuf};

/// Renderer for [`bones_framework`] [`Game`][bones::Game]s using Bevy.
pub struct BonesBevyRenderer {
    /// Whether or not to load all assets on startup with a loading screen,
    /// or skip straight to running the bones game immedietally.
    pub preload: bool,
    /// Optional field to implement your own loading screen. Does nothing if [`Self::preload`] = false
    pub custom_load_progress: Option<LoadingFunction>,
    /// Whether or not to use nearest-neighbor sampling for textures.
    pub pixel_art: bool,
    /// The bones game to run.
    pub game: bones::Game,
    /// The version of the game, used for the asset loader.
    pub game_version: bones::Version,
    /// The (qualifier, organization, application) that will be used to pick a persistent storage
    /// location for the game.
    ///
    /// For example: `("org", "fishfolk", "jumpy")`
    pub app_namespace: (String, String, String),
    /// The path to load assets from.
    pub asset_dir: PathBuf,
    /// The path to load asset packs from.
    pub packs_dir: PathBuf,
}

/// Bevy resource containing the [`bones::Game`]
#[derive(Resource, Deref, DerefMut)]
pub struct BonesGame(pub bones::Game);
impl BonesGame {
    /// Shorthand for [`bones::AssetServer`] typed access to the shared resource
    pub fn asset_server(&self) -> Option<bones::Ref<bones::AssetServer>> {
        self.0.shared_resource()
    }
}

#[derive(Resource, Deref, DerefMut)]
struct LoadingContext(pub Option<LoadingFunction>);
type LoadingFunction =
    Box<dyn FnMut(&bones::AssetServer, &bevy_egui::egui::Context) + Sync + Send + 'static>;

impl BonesBevyRenderer {
    // TODO: Create a better builder pattern struct for `BonesBevyRenderer`.
    // We want to use a nice builder-pattern struct for `BonesBevyRenderer` so that it is easier
    // to set options like the `pixel_art` flag or the `game_version`.
    /// Create a new [`BonesBevyRenderer`] for the provided game.
    pub fn new(game: bones::Game) -> Self {
        BonesBevyRenderer {
            preload: true,
            pixel_art: true,
            custom_load_progress: None,
            game,
            game_version: bones::Version::new(0, 1, 0),
            app_namespace: ("local".into(), "developer".into(), "bones_demo_game".into()),
            asset_dir: PathBuf::from("assets"),
            packs_dir: PathBuf::from("packs"),
        }
    }
    /// Whether or not to load all assets on startup with a loading screen,
    /// or skip straight to running the bones game immedietally.
    pub fn preload(self, preload: bool) -> Self {
        Self { preload, ..self }
    }
    /// Insert a custom loading screen function that will be used in place of the default
    pub fn loading_screen(mut self, function: LoadingFunction) -> Self {
        self.custom_load_progress = Some(function);
        self
    }
    /// Whether or not to use nearest-neighbor sampling for textures.
    pub fn pixel_art(self, pixel_art: bool) -> Self {
        Self { pixel_art, ..self }
    }
    /// The (qualifier, organization, application) that will be used to pick a persistent storage
    /// location for the game.
    ///
    /// For example: `("org", "fishfolk", "jumpy")`
    pub fn namespace(mut self, (qualifier, organization, application): (&str, &str, &str)) -> Self {
        self.app_namespace = (qualifier.into(), organization.into(), application.into());
        self
    }
    /// The path to load assets from.
    pub fn asset_dir(self, asset_dir: PathBuf) -> Self {
        Self { asset_dir, ..self }
    }
    /// The path to load asset packs from.
    pub fn packs_dir(self, packs_dir: PathBuf) -> Self {
        Self { packs_dir, ..self }
    }
    /// Set the version of the game, used for the asset loader.
    pub fn version(self, game_version: bones::Version) -> Self {
        Self {
            game_version,
            ..self
        }
    }

    /// Return a bevy [`App`] configured to run the bones game.
    pub fn app(mut self) -> App {
        let mut app = App::new();

        // Initialize Bevy plugins we use
        let mut plugins = DefaultPlugins
            .set(WindowPlugin {
                primary_window: Some(Window {
                    fit_canvas_to_parent: true,
                    ..default()
                }),
                ..default()
            })
            .disable::<LogPlugin>()
            .build();
        if self.pixel_art {
            plugins = plugins.set(ImagePlugin::default_nearest());
            // app.insert_resource(Msaa::Off);
        }

        app.add_plugins(plugins).add_plugins((
            bevy_egui::EguiPlugin,
            bevy_prototype_lyon::plugin::ShapePlugin,
            debug::BevyDebugPlugin,
        ));
        if self.pixel_art {
            app.insert_resource({
                let mut egui_settings = bevy_egui::EguiSettings::default();
                egui_settings.use_nearest_descriptor();
                egui_settings
            });
        }
        app.init_resource::<BonesImageIds>();

        if let Some(mut asset_server) = self.game.shared_resource_mut::<bones::AssetServer>() {
            asset_server.set_game_version(self.game_version);
            asset_server.set_io(asset_io(&self.asset_dir, &self.packs_dir));

            if self.preload {
                // Spawn the task to load game assets
                let s = asset_server.clone();
                IoTaskPool::get()
                    .spawn(async move {
                        s.load_assets().await.unwrap();
                    })
                    .detach();
            }

            // Enable asset hot reload.
            asset_server.watch_for_changes();
        }

        // Configure and load the persitent storage
        let mut storage = bones::Storage::with_backend(Box::new(storage::StorageBackend::new(
            &self.app_namespace.0,
            &self.app_namespace.1,
            &self.app_namespace.2,
        )));
        storage.load();
        self.game.insert_shared_resource(storage);
        self.game
            .insert_shared_resource(bones::EguiTextures::default());

        // Insert rumble resource and add system
        self.game.init_shared_resource::<GamepadsRumble>();
        app.add_systems(
            Update,
            handle_bones_rumble.run_if(assets_are_loaded.or_else(move || !self.preload)),
        );

        // Insert empty inputs that will be updated by the `insert_bones_input` system later.
        self.game.init_shared_resource::<bones::KeyboardInputs>();
        self.game.init_shared_resource::<bones::MouseInputs>();
        self.game.init_shared_resource::<bones::GamepadInputs>();

        #[cfg(not(target_arch = "wasm32"))]
        {
            self.game.init_shared_resource::<bones::ExitBones>();
            app.add_systems(Update, handle_exits);
        }

        // Insert the bones data
        app.insert_resource(BonesGame(self.game))
            .insert_resource(LoadingContext(self.custom_load_progress))
            .init_resource::<BonesGameEntity>();

        // Add the world sync systems
        app.add_systems(
            PreUpdate,
            (
                setup_egui,
                get_bones_input.pipe(insert_bones_input).after(InputSystem),
                get_mouse_position
                    .pipe(insert_mouse_position)
                    .after(InputSystem),
                egui_input_hook,
            )
                .chain()
                .run_if(assets_are_loaded.or_else(move || !self.preload))
                .after(bevy_egui::EguiSet::ProcessInput)
                .before(bevy_egui::EguiSet::BeginFrame),
        );

        if self.preload {
            app.add_systems(Update, asset_load_status.run_if(assets_not_loaded));
        }
        app.add_systems(
            Update,
            (
                load_egui_textures,
                sync_bones_window,
                handle_asset_changes,
                // Run world simulation
                step_bones_game,
                // Synchronize bones render components with the Bevy world.
                (
                    sync_egui_settings,
                    sync_clear_color,
                    sync_cameras,
                    sync_bones_path2ds,
                ),
            )
                .chain()
                .run_if(assets_are_loaded.or_else(move || !self.preload))
                .run_if(egui_ctx_initialized),
        );

        if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
            render_app.add_systems(
                ExtractSchedule,
                (extract_bones_sprites, extract_bones_tilemaps)
                    .in_set(SpriteSystem::ExtractSprites)
                    .after(extract_sprites),
            );
        }

        app
    }
}

fn egui_ctx_initialized(game: Res<BonesGame>) -> bool {
    game.shared_resource::<bones::EguiCtx>().is_some()
}

fn assets_are_loaded(game: Res<BonesGame>) -> bool {
    // Game is not required to have AssetServer, so default to true.
    game.asset_server()
        .as_ref()
        .map(|x| x.load_progress.is_finished())
        .unwrap_or(true)
}

fn assets_not_loaded(game: Res<BonesGame>) -> bool {
    game.asset_server()
        .as_ref()
        .map(|x| !x.load_progress.is_finished())
        .unwrap_or(true)
}

/// A [`bones::AssetIo`] configured for web and local file access
pub fn asset_io(asset_dir: &Path, packs_dir: &Path) -> impl bones::AssetIo + 'static {
    #[cfg(not(target_arch = "wasm32"))]
    {
        bones::FileAssetIo::new(asset_dir, packs_dir)
    }
    #[cfg(target_arch = "wasm32")]
    {
        let _ = asset_dir;
        let _ = packs_dir;
        let window = web_sys::window().unwrap();
        let path = window.location().pathname().unwrap();
        let base = path.rsplit_once('/').map(|x| x.0).unwrap_or(&path);
        bones::WebAssetIo::new(&format!("{base}/assets"))
    }
}

fn asset_load_status(
    game: Res<BonesGame>,
    mut custom_load_context: ResMut<LoadingContext>,
    mut egui_query: Query<&mut bevy_egui::EguiContext, With<Window>>,
) {
    let Some(asset_server) = &game.asset_server() else {
        return;
    };

    let mut ctx = egui_query.single_mut();
    if let Some(function) = &mut **custom_load_context {
        (function)(asset_server, ctx.get_mut());
    } else {
        default_load_progress(asset_server, ctx.get_mut());
    }
}

fn load_egui_textures(
    mut has_initialized: Local<bool>,
    game: ResMut<BonesGame>,
    mut bones_image_ids: ResMut<BonesImageIds>,
    mut bevy_images: ResMut<Assets<Image>>,
    mut bevy_egui_textures: ResMut<bevy_egui::EguiUserTextures>,
) {
    if !*has_initialized {
        *has_initialized = true;
    } else {
        return;
    }
    if let Some(asset_server) = &game.asset_server() {
        let bones_egui_textures_cell = game.shared_resource_cell::<bones::EguiTextures>().unwrap();
        // TODO: Avoid doing this every frame when there have been no assets loaded.
        // We should should be able to use the asset load progress event listener to detect newly
        // loaded assets that will need to be handled.
        let mut bones_egui_textures = bones_egui_textures_cell.borrow_mut().unwrap();
        // Take all loaded image assets and conver them to external images that reference bevy handles
        bones_image_ids.load_bones_images(
            asset_server,
            &mut bones_egui_textures,
            &mut bevy_images,
            &mut bevy_egui_textures,
        );
    }
}

/// System to step the bones simulation.
fn step_bones_game(world: &mut World) {
    world.resource_scope(|world: &mut World, mut game: Mut<BonesGame>| {
        let time = world.get_resource::<Time>().unwrap();
        game.step(time.last_update().unwrap_or_else(Instant::now));
    });
}

/// System for handling asset changes in the bones asset server
pub fn handle_asset_changes(
    game: ResMut<BonesGame>,
    mut bevy_images: ResMut<Assets<Image>>,
    mut bevy_egui_textures: ResMut<bevy_egui::EguiUserTextures>,
    mut bones_image_ids: ResMut<BonesImageIds>,
) {
    if let Some(mut asset_server) = game.shared_resource_mut::<bones::AssetServer>() {
        asset_server.handle_asset_changes(|asset_server, handle| {
            let mut bones_egui_textures =
                game.shared_resource_mut::<bones::EguiTextures>().unwrap();
            let Some(mut asset) = asset_server.get_asset_untyped_mut(handle) else {
                // There was an issue loading the asset. The error will have been logged.
                return;
            };

            // TODO: hot reload changed fonts.

            if let Ok(image) = asset.data.try_cast_mut::<bones::Image>() {
                bones_image_ids.load_bones_image(
                    handle.typed(),
                    image,
                    &mut bones_egui_textures,
                    &mut bevy_images,
                    &mut bevy_egui_textures,
                );
            }
        })
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn handle_exits(game: Res<BonesGame>, mut exits: EventWriter<bevy::app::AppExit>) {
    if **game.shared_resource::<bones::ExitBones>().unwrap() {
        exits.send(bevy::app::AppExit);
    }
}