migration to dynamic asset loading

This commit is contained in:
2024-07-25 00:09:27 -04:00
parent deb778d6af
commit f6e24f437a
11 changed files with 93 additions and 109 deletions

16
Cargo.lock generated
View File

@@ -481,7 +481,9 @@ dependencies = [
"anyhow", "anyhow",
"bevy", "bevy",
"bevy_asset_loader_derive", "bevy_asset_loader_derive",
"bevy_common_assets",
"path-slash", "path-slash",
"serde",
] ]
[[package]] [[package]]
@@ -541,6 +543,19 @@ dependencies = [
"wgpu-types", "wgpu-types",
] ]
[[package]]
name = "bevy_common_assets"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f631ce2863f3b6f1af3fa24143363b9fbd21c44218caad495a17b83e6968256"
dependencies = [
"anyhow",
"bevy",
"ron",
"serde",
"thiserror",
]
[[package]] [[package]]
name = "bevy_core" name = "bevy_core"
version = "0.14.0" version = "0.14.0"
@@ -5297,6 +5312,7 @@ dependencies = [
"asset_loader", "asset_loader",
"bevy", "bevy",
"bevy-inspector-egui", "bevy-inspector-egui",
"bevy_asset_loader",
"noise 0.9.0", "noise 0.9.0",
"rayon", "rayon",
"serde", "serde",

View File

@@ -13,6 +13,10 @@ serde_json = "1.0.115"
asset_loader = { path = "../asset_loader" } asset_loader = { path = "../asset_loader" }
rayon = "1.10.0" rayon = "1.10.0"
bevy-inspector-egui = "0.25.0" bevy-inspector-egui = "0.25.0"
bevy_asset_loader = { version = "0.21.0", features = [
"standard_dynamic_assets",
"3d",
] }
[features] [features]
tracing = ["bevy/trace_tracy"] tracing = ["bevy/trace_tracy"]

View File

@@ -4,6 +4,43 @@ use bevy::{asset::Asset, reflect::TypePath, render::render_resource::encase::rts
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{biome_asset::BiomeAsset, map::biome_map::BiomeData}; use crate::{biome_asset::BiomeAsset, map::biome_map::BiomeData};
use bevy_asset_loader::prelude::*;
#[derive(AssetCollection, Debug, Clone, Resource)]
pub struct BiomePainterAsset {
// #[serde(skip)]
#[asset(key = "biomes", collection(typed))]
pub biomes: Vec<Handle<BiomeAsset>>,
// pub biomes_path: Vec<String>,
}
impl BiomePainterAsset {
pub fn sample_biome(&self, assets: &Assets<BiomeAsset>, data: &BiomeData) -> AssetId<BiomeAsset> {
assert!(self.biomes.length() != 0, "There are no biomes");
let mut biome = self.biomes.first().unwrap().id();
let mut dist = f32::INFINITY;
for b in &self.biomes {
let asset = assets.get(b.id()).unwrap();
let d = asset.distance(data.into());
if d < dist {
biome = b.id();
dist = d;
}
}
return biome;
}
pub fn build(&self, assets: &Assets<BiomeAsset>) -> BiomePainter {
let mut biomes = Vec::with_capacity(self.biomes.len());
for b in &self.biomes {
let asset = assets.get(b.id()).unwrap();
biomes.push(asset.clone());
}
return BiomePainter { biomes };
}
}
#[derive(Resource)] #[derive(Resource)]
pub struct BiomePainter { pub struct BiomePainter {

View File

@@ -16,7 +16,7 @@ bevy_rapier3d = { version = "0.27.0", features = ["simd-stable", "parallel"] }
rayon = "1.10.0" rayon = "1.10.0"
buildings = { path = "../buildings" } buildings = { path = "../buildings" }
shared = { path = "../shared" } shared = { path = "../shared" }
bevy_asset_loader = "0.21.0" bevy_asset_loader = {version ="0.21.0", features = ["standard_dynamic_assets", "3d"]}
[features] [features]
tracing = ["bevy/trace_tracy", "world_generation/tracing", "buildings/tracing"] tracing = ["bevy/trace_tracy", "world_generation/tracing", "buildings/tracing"]

View File

@@ -1,33 +0,0 @@
#[derive(AssetCollection, Serialize, Deserialize, Debug, TypePath, Asset, Clone)]
pub struct BiomePainterAsset {
#[asset(path)]
pub biomes: Vec<Handle<BiomeAsset>>,
}
impl BiomePainterAsset {
pub fn sample_biome(&self, assets: &Assets<BiomeAsset>, data: &BiomeData) -> AssetId<BiomeAsset> {
assert!(self.biomes.length() != 0, "There are no biomes");
let mut biome = self.biomes.first().unwrap().id();
let mut dist = f32::INFINITY;
for b in &self.biomes {
let asset = assets.get(b.id()).unwrap();
let d = asset.distance(data.into());
if d < dist {
biome = b.id();
dist = d;
}
}
return biome;
}
pub fn build(&self, assets: &Assets<BiomeAsset>) -> BiomePainter {
let mut biomes = Vec::with_capacity(self.biomes.len());
for b in &self.biomes {
let asset = assets.get(b.id()).unwrap();
biomes.push(asset.clone());
}
return BiomePainter { biomes };
}
}

View File

@@ -1 +0,0 @@
pub mod biome_painer;

View File

@@ -11,7 +11,6 @@ mod phos;
mod prelude; mod prelude;
mod shader_extensions; mod shader_extensions;
mod utlis; mod utlis;
pub mod assets;
fn main() { fn main() {
App::new() App::new()

View File

@@ -5,6 +5,8 @@ use bevy::{
pbr::{ExtendedMaterial, NotShadowCaster}, pbr::{ExtendedMaterial, NotShadowCaster},
prelude::*, prelude::*,
}; };
use bevy_asset_loader::prelude::*;
use bevy_inspector_egui::quick::ResourceInspectorPlugin; use bevy_inspector_egui::quick::ResourceInspectorPlugin;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use shared::states::{AssetLoadState, GameplayState, MenuState}; use shared::states::{AssetLoadState, GameplayState, MenuState};
@@ -31,21 +33,18 @@ use crate::{
}, },
}; };
use super::{ use super::{chunk_rebuild::ChunkRebuildPlugin, terraforming_test::TerraFormingTestPlugin};
chunk_rebuild::ChunkRebuildPlugin, prelude::CurrentBiomePainter, terraforming_test::TerraFormingTestPlugin,
};
pub struct MapInitPlugin; pub struct MapInitPlugin;
impl Plugin for MapInitPlugin { impl Plugin for MapInitPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.insert_state(GeneratorState::Startup); app.insert_state(GeneratorState::Startup);
app.insert_state(AssetLoadState::StartLoading); app.insert_state(AssetLoadState::Loading);
//Assets //Assets
app.add_plugins(TileAssetPlugin); app.add_plugins(TileAssetPlugin);
app.add_plugins(TileMapperAssetPlugin); app.add_plugins(TileMapperAssetPlugin);
app.add_plugins(BiomePainterPlugin);
app.add_plugins(BiomeAssetPlugin); app.add_plugins(BiomeAssetPlugin);
app.add_plugins(ResourceInspectorPlugin::<GenerationConfig>::default()); app.add_plugins(ResourceInspectorPlugin::<GenerationConfig>::default());
@@ -62,19 +61,33 @@ impl Plugin for MapInitPlugin {
}, },
)); ));
//app.add_systems(Startup, (load_textures, load_tiles).in_set(AssetLoaderSet)); app.configure_loading_state(
//app.configure_sets(Startup, AssetLoaderSet.run_if(in_state(AssetLoadState::StartLoading))); LoadingStateConfig::new(AssetLoadState::Loading)
.with_dynamic_assets_file::<StandardDynamicAssetCollection>("phos.assets.ron")
.load_collection::<ChunkAtlas>(),
);
app.add_systems(Startup, load_textures.run_if(in_state(AssetLoadState::FinalizeAssets)));
app.add_systems( app.add_systems(
Update, Update,
create_heightmap.run_if(in_state(GeneratorState::GenerateHeightmap)), create_heightmap.run_if(in_state(GeneratorState::GenerateHeightmap)),
); );
app.add_systems(Update, check_asset_load.run_if(in_state(AssetLoadState::Loading))); // app.add_systems(
// Update,
// check_asset_load.run_if(in_state(AssetLoadState::FinalizeAssets)),
// );
app.add_systems( app.add_systems(
Update, Update,
(finalize_texture, finalize_biome_painter).run_if(in_state(AssetLoadState::FinalizeAssets)), (finalize_texture, finalize_biome_painter).run_if(in_state(AssetLoadState::FinalizeAssets)),
); );
app.add_systems(
Update,
finalize_biome_painter
.run_if(in_state(AssetLoadState::FinalizeAssets))
.run_if(in_state(AssetLoadState::LoadComplete)),
);
app.add_systems(Update, despawn_map.run_if(in_state(GeneratorState::Regenerate))); app.add_systems(Update, despawn_map.run_if(in_state(GeneratorState::Regenerate)));
app.add_systems( app.add_systems(
Update, Update,
@@ -87,9 +100,6 @@ impl Plugin for MapInitPlugin {
} }
} }
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
struct AssetLoaderSet;
#[derive(Resource, Reflect, Default)] #[derive(Resource, Reflect, Default)]
#[reflect(Resource)] #[reflect(Resource)]
struct WaterInspect(Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>); struct WaterInspect(Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>);
@@ -118,60 +128,16 @@ fn load_textures(
atlas.water_material = water_material; atlas.water_material = water_material;
} }
fn load_tiles(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut next_state: ResMut<NextState<AssetLoadState>>,
) {
let handle: Handle<BiomePainterAsset> = asset_server.load("biome_painters/terra.biomes.json");
commands.insert_resource(CurrentBiomePainter { handle });
next_state.set(AssetLoadState::Loading);
}
fn check_asset_load(
asset_server: Res<AssetServer>,
atlas: Res<ChunkAtlas>,
painter: Res<CurrentBiomePainter>,
painter_load: Res<BiomePainterLoadState>,
biome_load: Res<BiomeAssetLoadState>,
tile_load: Res<TileAssetLoadState>,
mapper_load: Res<TileMapperLoadState>,
mut next_state: ResMut<NextState<AssetLoadState>>,
) {
if !painter_load.is_all_loaded()
|| !tile_load.is_all_loaded()
|| !mapper_load.is_all_loaded()
|| !biome_load.is_all_loaded()
{
return;
}
if asset_server.load_state(atlas.handle.id()) != LoadState::Loaded {
return;
}
if asset_server.load_state(painter.handle.id()) != LoadState::Loaded {
return;
}
next_state.set(AssetLoadState::FinalizeAssets);
}
fn finalize_biome_painter( fn finalize_biome_painter(
mut commands: Commands, mut commands: Commands,
mut next_generator_state: ResMut<NextState<GeneratorState>>, mut next_generator_state: ResMut<NextState<GeneratorState>>,
painter: Res<CurrentBiomePainter>, biome_painter: Res<BiomePainterAsset>,
painter_load: Res<BiomePainterLoadState>, biomes: Res<Assets<BiomeAsset>>,
biome_load: Res<BiomeAssetLoadState>,
biome_painters: Res<Assets<BiomePainterAsset>>,
biome_assets: Res<Assets<BiomeAsset>>,
) { ) {
if !painter_load.is_all_loaded() || !biome_load.is_all_loaded() { let biome_painter = biome_painter.build(&biomes);
return;
}
let painter_asset = biome_painters.get(painter.handle.id()).unwrap();
let biome_painter = painter_asset.build(&biome_assets);
commands.insert_resource(biome_painter); commands.insert_resource(biome_painter);
next_generator_state.set(GeneratorState::GenerateHeightmap); next_generator_state.set(GeneratorState::GenerateHeightmap);
println!("Finalize Biome");
} }
fn finalize_texture( fn finalize_texture(
@@ -180,6 +146,7 @@ fn finalize_texture(
mut chunk_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, ChunkMaterial>>>, mut chunk_materials: ResMut<Assets<ExtendedMaterial<StandardMaterial, ChunkMaterial>>>,
mut next_load_state: ResMut<NextState<AssetLoadState>>, mut next_load_state: ResMut<NextState<AssetLoadState>>,
) { ) {
println!("Finalize Tex");
let image = images.get_mut(atlas.handle.id()).unwrap(); let image = images.get_mut(atlas.handle.id()).unwrap();
let array_layers = image.height() / image.width(); let array_layers = image.height() / image.width();

View File

@@ -1,7 +1,2 @@
use bevy::prelude::*; use bevy::prelude::*;
use world_generation::biome_painter::BiomePainterAsset; use world_generation::biome_painter::BiomePainterAsset;
#[derive(Resource)]
pub struct CurrentBiomePainter {
pub handle: Handle<BiomePainterAsset>,
}

View File

@@ -19,14 +19,6 @@ pub struct PhosGamePlugin;
impl Plugin for PhosGamePlugin { impl Plugin for PhosGamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins((
PhosCameraPlugin,
MapInitPlugin,
RenderDistancePlugin,
// BuildingPugin,
DespawnPuglin,
));
app.insert_state(AssetLoadState::Loading); app.insert_state(AssetLoadState::Loading);
app.insert_state(MenuState::Loading); app.insert_state(MenuState::Loading);
app.insert_state(GameplayState::Waiting); app.insert_state(GameplayState::Waiting);
@@ -35,6 +27,14 @@ impl Plugin for PhosGamePlugin {
LoadingState::new(AssetLoadState::Loading).continue_to_state(AssetLoadState::FinalizeAssets), LoadingState::new(AssetLoadState::Loading).continue_to_state(AssetLoadState::FinalizeAssets),
); );
app.add_plugins((
PhosCameraPlugin,
MapInitPlugin,
RenderDistancePlugin,
// BuildingPugin,
DespawnPuglin,
));
//Systems - Startup //Systems - Startup
app.add_systems(Startup, init_game); app.add_systems(Startup, init_game);

View File

@@ -9,7 +9,7 @@ use crate::shader_extensions::water_material::WaterMaterial;
#[derive(AssetCollection, Resource, Default)] #[derive(AssetCollection, Resource, Default)]
pub struct ChunkAtlas { pub struct ChunkAtlas {
#[asset(path = "textures/world/Terra.png")] #[asset(key = "chunk_atlas")]
pub handle: Handle<Image>, pub handle: Handle<Image>,
pub chunk_material_handle: Handle<ExtendedMaterial<StandardMaterial, ChunkMaterial>>, pub chunk_material_handle: Handle<ExtendedMaterial<StandardMaterial, ChunkMaterial>>,
pub water_material: Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>, pub water_material: Handle<ExtendedMaterial<StandardMaterial, WaterMaterial>>,