Skip to content

Commit

Permalink
Merge pull request #512 from StarArawn/move-render-settings
Browse files Browse the repository at this point in the history
Moved render settings onto entity.
  • Loading branch information
StarArawn authored Feb 11, 2024
2 parents 86549e9 + 8bbafcd commit b75d4b1
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 68 deletions.
12 changes: 6 additions & 6 deletions examples/3d_iso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {

commands.spawn(helpers::tiled::TiledMapBundle {
tiled_map: map_handle,
render_settings: TilemapRenderSettings {
// Map size is 12x12 so we'll have render chunks that are:
// 12 tiles wide and 1 tile tall.
render_chunk_size: UVec2::new(3, 1),
y_sort: true,
},
..Default::default()
});
}

fn main() {
App::new()
.insert_resource(TilemapRenderSettings {
// Map size is 12x12 so we'll have render chunks that are:
// 12 tiles wide and 1 tile tall.
render_chunk_size: UVec2::new(3, 1),
y_sort: true,
})
.add_plugins(
DefaultPlugins
.set(WindowPlugin {
Expand Down
8 changes: 4 additions & 4 deletions examples/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
texture: TilemapTexture::Single(texture_handle),
tile_size,
transform: get_tilemap_center_transform(&map_size, &grid_size, &map_type, 0.0),
render_settings: TilemapRenderSettings {
render_chunk_size: UVec2::new(256, 256),
..Default::default()
},
..Default::default()
});
}
Expand All @@ -52,10 +56,6 @@ fn main() {
})
.set(ImagePlugin::default_nearest()),
)
.insert_resource(TilemapRenderSettings {
render_chunk_size: UVec2::new(256, 256),
..Default::default()
})
.add_plugins(LogDiagnosticsPlugin::default())
.add_plugins(FrameTimeDiagnosticsPlugin)
.add_plugins(TilemapPlugin)
Expand Down
9 changes: 4 additions & 5 deletions examples/chunking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ fn spawn_chunk(commands: &mut Commands, asset_server: &AssetServer, chunk_pos: I
texture: TilemapTexture::Single(texture_handle),
tile_size: TILE_SIZE,
transform,
render_settings: TilemapRenderSettings {
render_chunk_size: RENDER_CHUNK_SIZE,
..Default::default()
},
..Default::default()
});
}
Expand Down Expand Up @@ -117,11 +121,6 @@ fn main() {
})
.set(ImagePlugin::default_nearest()),
)
// `TilemapRenderSettings` be added before the `TilemapPlugin`.
.insert_resource(TilemapRenderSettings {
render_chunk_size: RENDER_CHUNK_SIZE,
..Default::default()
})
.add_plugins(TilemapPlugin)
.insert_resource(ChunkManager::default())
.add_systems(Startup, startup)
Expand Down
10 changes: 8 additions & 2 deletions examples/helpers/tiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub struct TiledMapBundle {
pub storage: TiledLayersStorage,
pub transform: Transform,
pub global_transform: GlobalTransform,
pub render_settings: TilemapRenderSettings,
}

struct BytesResourceReader {
Expand Down Expand Up @@ -200,7 +201,11 @@ pub fn process_loaded_maps(
mut map_events: EventReader<AssetEvent<TiledMap>>,
maps: Res<Assets<TiledMap>>,
tile_storage_query: Query<(Entity, &TileStorage)>,
mut map_query: Query<(&Handle<TiledMap>, &mut TiledLayersStorage)>,
mut map_query: Query<(
&Handle<TiledMap>,
&mut TiledLayersStorage,
&TilemapRenderSettings,
)>,
new_maps: Query<&Handle<TiledMap>, Added<Handle<TiledMap>>>,
) {
let mut changed_maps = Vec::<AssetId<TiledMap>>::default();
Expand Down Expand Up @@ -230,7 +235,7 @@ pub fn process_loaded_maps(
}

for changed_map in changed_maps.iter() {
for (map_handle, mut layer_storage) in map_query.iter_mut() {
for (map_handle, mut layer_storage, render_settings) in map_query.iter_mut() {
// only deal with currently changed map
if map_handle.id() != *changed_map {
continue;
Expand Down Expand Up @@ -382,6 +387,7 @@ pub fn process_loaded_maps(
layer_index as f32,
) * Transform::from_xyz(offset_x, -offset_y, 0.0),
map_type,
render_settings: *render_settings,
..Default::default()
});

Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use map::{
TilemapGridSize, TilemapSize, TilemapSpacing, TilemapTexture, TilemapTextureSize,
TilemapTileSize, TilemapType,
};
use prelude::TilemapId;
use prelude::{TilemapId, TilemapRenderSettings};
#[cfg(feature = "render")]
use render::material::{MaterialTilemap, StandardTilemapMaterial};
use tiles::{
Expand Down Expand Up @@ -114,6 +114,7 @@ pub struct MaterialTilemapBundle<M: MaterialTilemap> {
pub tile_size: TilemapTileSize,
pub transform: Transform,
pub global_transform: GlobalTransform,
pub render_settings: TilemapRenderSettings,
/// User indication of whether an entity is visible
pub visibility: Visibility,
/// Algorithmically-computed indication of whether an entity is visible and should be extracted
Expand All @@ -138,6 +139,7 @@ pub struct StandardTilemapBundle {
pub tile_size: TilemapTileSize,
pub transform: Transform,
pub global_transform: GlobalTransform,
pub render_settings: TilemapRenderSettings,
/// User indication of whether an entity is visible
pub visibility: Visibility,
/// Algorithmically-computed indication of whether an entity is visible and should be extracted
Expand Down
30 changes: 15 additions & 15 deletions src/map/mod.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
use bevy::asset::Assets;
use bevy::ecs::entity::{EntityMapper, MapEntities};
use bevy::ecs::reflect::ReflectMapEntities;
use bevy::prelude::{ReflectComponent, Res, ResMut, Resource};
use bevy::prelude::{ReflectComponent, Res, ResMut};
use bevy::render::render_resource::TextureUsages;
use bevy::{
math::{UVec2, Vec2},
prelude::{Component, Entity, Handle, Image, Reflect},
};

/// The default chunk_size (in tiles) used per mesh.
pub const CHUNK_SIZE_2D: UVec2 = UVec2::from_array([64, 64]);

/// Custom parameters for the render pipeline.
///
/// It must be added as a resource before [`TilemapPlugin`](crate::TilemapPlugin). For example:
/// ```ignore
/// App::new()
/// .insert_resource(WindowDescriptor {
/// width: 1270.0,
/// height: 720.0,
/// })
/// .insert_resource(TilemapRenderSettings {
/// render_chunk_size: UVec2::new(32, 32),
/// })
/// .add_plugin(TilemapPlugin)
/// .run();
/// ```
#[derive(Resource, Debug, Default, Copy, Clone)]
/// It must be added as a component to the tilemap entity.
#[derive(Component, Debug, Copy, Clone)]
pub struct TilemapRenderSettings {
/// Dimensions of a "chunk" in tiles. Chunks are grouping of tiles combined and rendered as a
/// single mesh by the render pipeline.
Expand All @@ -41,6 +32,15 @@ pub struct TilemapRenderSettings {
pub y_sort: bool,
}

impl Default for TilemapRenderSettings {
fn default() -> Self {
Self {
render_chunk_size: CHUNK_SIZE_2D,
y_sort: false,
}
}
}

/// A component which stores a reference to the tilemap entity.
#[derive(Component, Reflect, Clone, Copy, Debug, Hash)]
#[reflect(Component, MapEntities)]
Expand Down
12 changes: 12 additions & 0 deletions src/render/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ use crate::{
FrustumCulling, TilemapGridSize, TilemapTileSize,
};

use super::RenderChunkSize;

#[derive(Resource, Default, Clone, Debug)]
pub struct RenderChunk2dStorage {
chunks: HashMap<u32, HashMap<UVec3, RenderChunk2d>>,
Expand Down Expand Up @@ -51,6 +53,8 @@ impl RenderChunk2dStorage {
transform: GlobalTransform,
visibility: &InheritedVisibility,
frustum_culling: &FrustumCulling,
render_size: RenderChunkSize,
y_sort: bool,
) -> &mut RenderChunk2d {
let pos = position.xyz();

Expand Down Expand Up @@ -86,6 +90,8 @@ impl RenderChunk2dStorage {
transform,
visibility.get(),
**frustum_culling,
render_size,
y_sort,
);
self.entity_to_chunk.insert(chunk_entity, pos);
chunk_storage.insert(pos, chunk);
Expand Down Expand Up @@ -208,6 +214,8 @@ pub struct RenderChunk2d {
pub dirty_mesh: bool,
pub visible: bool,
pub frustum_culling: bool,
pub render_size: RenderChunkSize,
pub y_sort: bool,
}

impl RenderChunk2d {
Expand All @@ -227,6 +235,8 @@ impl RenderChunk2d {
global_transform: GlobalTransform,
visible: bool,
frustum_culling: bool,
render_size: RenderChunkSize,
y_sort: bool,
) -> Self {
let position = chunk_index_to_world_space(index.xy(), size_in_tiles, &grid_size, &map_type);
let local_transform = Transform::from_translation(position.extend(0.0));
Expand Down Expand Up @@ -258,6 +268,8 @@ impl RenderChunk2d {
tiles: vec![None; (size_in_tiles.x * size_in_tiles.y) as usize],
visible,
frustum_culling,
render_size,
y_sort,
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/render/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use bevy::render::render_resource::TextureFormat;
use bevy::{math::Vec4, prelude::*, render::Extract, utils::HashMap};

use crate::prelude::TilemapGridSize;
use crate::prelude::TilemapRenderSettings;
use crate::render::{DefaultSampler, SecondsSinceStartup};
use crate::tiles::AnimatedTile;
use crate::tiles::TilePosOld;
Expand Down Expand Up @@ -68,6 +69,7 @@ pub struct ExtractedTilemapBundle {
map_size: TilemapSize,
visibility: InheritedVisibility,
frustum_culling: FrustumCulling,
render_settings: TilemapRenderSettings,
}

#[derive(Component)]
Expand Down Expand Up @@ -220,6 +222,7 @@ pub fn extract(
&TilemapSize,
&InheritedVisibility,
&FrustumCulling,
&TilemapRenderSettings,
)>,
>,
changed_tilemap_query: Extract<
Expand All @@ -236,6 +239,7 @@ pub fn extract(
Changed<TilemapSize>,
Changed<InheritedVisibility>,
Changed<FrustumCulling>,
Changed<TilemapRenderSettings>,
)>,
>,
>,
Expand Down Expand Up @@ -300,6 +304,7 @@ pub fn extract(
map_size: *data.7,
visibility: *data.8,
frustum_culling: *data.9,
render_settings: *data.10,
},
),
);
Expand Down Expand Up @@ -335,6 +340,7 @@ pub fn extract(
map_size: *data.7,
visibility: *data.8,
frustum_culling: *data.9,
render_settings: *data.10,
},
),
);
Expand All @@ -345,7 +351,7 @@ pub fn extract(
extracted_tilemaps.drain().map(|kv| kv.1).collect();

// Extracts tilemap textures.
for (entity, _, tile_size, tile_spacing, _, _, texture, _, _, _) in tilemap_query.iter() {
for (entity, _, tile_size, tile_spacing, _, _, texture, _, _, _, _) in tilemap_query.iter() {
if texture.verify_ready(&images) {
extracted_tilemap_textures.push((
entity,
Expand Down
4 changes: 1 addition & 3 deletions src/render/material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use super::{
draw::DrawTilemapMaterial,
pipeline::{TilemapPipeline, TilemapPipelineKey},
queue::{ImageBindGroups, TilemapViewBindGroup},
RenderYSort,
};

#[cfg(not(feature = "atlas"))]
Expand Down Expand Up @@ -362,7 +361,6 @@ fn prepare_material_tilemap<M: MaterialTilemap>(

#[allow(clippy::too_many_arguments)]
pub fn queue_material_tilemap_meshes<M: MaterialTilemap>(
y_sort: Res<RenderYSort>,
chunk_storage: Res<RenderChunk2dStorage>,
transparent_2d_draw_functions: Res<DrawFunctions<Transparent2d>>,
render_device: Res<RenderDevice>,
Expand Down Expand Up @@ -455,7 +453,7 @@ pub fn queue_material_tilemap_meshes<M: MaterialTilemap>(
bind_group_data: material.key.clone(),
},
);
let z = if **y_sort {
let z = if chunk.y_sort {
transform.translation.z
+ (1.0
- (transform.translation.y
Expand Down
35 changes: 7 additions & 28 deletions src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ use bevy::{
#[cfg(not(feature = "atlas"))]
use bevy::render::renderer::RenderDevice;

use crate::render::{
material::{MaterialTilemapPlugin, StandardTilemapMaterial},
prepare::{MeshUniformResource, TilemapUniformResource},
};
use crate::tiles::{TilePos, TileStorage};
use crate::{
prelude::{TilemapRenderSettings, TilemapTexture},
tiles::{TilePos, TileStorage},
prelude::TilemapTexture,
render::{
material::{MaterialTilemapPlugin, StandardTilemapMaterial},
prepare::{MeshUniformResource, TilemapUniformResource},
},
};

use self::{
Expand All @@ -49,9 +49,6 @@ use self::extract::ExtractedTilemapTexture;
#[cfg(not(feature = "atlas"))]
pub(crate) use self::texture_array_cache::TextureArrayCache;

/// The default chunk_size (in tiles) used per mesh.
const CHUNK_SIZE_2D: UVec2 = UVec2::from_array([64, 64]);

#[derive(Copy, Clone, Debug, Component)]
pub(crate) struct ExtractedFilterMode(FilterMode);

Expand All @@ -62,7 +59,7 @@ pub struct DefaultSampler(ImageSamplerDescriptor);
///
/// Initialized from [`TilemapRenderSettings`](crate::map::TilemapRenderSettings) resource, if
/// provided. Otherwise, defaults to `64 x 64`.
#[derive(Resource, Debug, Copy, Clone, Deref)]
#[derive(Debug, Copy, Clone, Deref)]
pub(crate) struct RenderChunkSize(UVec2);

impl RenderChunkSize {
Expand All @@ -85,13 +82,6 @@ impl RenderChunkSize {
}
}

/// Sorts chunks using Y sort during render.
///
/// Initialized from [`TilemapRenderSettings`](crate::map::TilemapRenderSettings) resource, if
/// provided. Otherwise, defaults to false.
#[derive(Resource, Debug, Copy, Clone, Deref)]
pub struct RenderYSort(bool);

pub struct TilemapRenderingPlugin;

#[derive(Resource, Default, Deref, DerefMut)]
Expand Down Expand Up @@ -129,15 +119,6 @@ impl Plugin for TilemapRenderingPlugin {
}

fn finish(&self, app: &mut App) {
// Extract the chunk size from the TilemapRenderSettings used to initialize the
// ChunkCoordinate resource to insert into the render pipeline
let (chunk_size, y_sort) = {
match app.world.get_resource::<TilemapRenderSettings>() {
Some(settings) => (settings.render_chunk_size, settings.y_sort),
None => (CHUNK_SIZE_2D, false),
}
};

let sampler = app.get_added_plugins::<ImagePlugin>().first().map_or_else(
|| ImagePlugin::default_nearest().default_sampler,
|plugin| plugin.default_sampler.clone(),
Expand Down Expand Up @@ -242,8 +223,6 @@ impl Plugin for TilemapRenderingPlugin {

render_app
.insert_resource(DefaultSampler(sampler))
.insert_resource(RenderChunkSize(chunk_size))
.insert_resource(RenderYSort(y_sort))
.insert_resource(RenderChunk2dStorage::default())
.insert_resource(SecondsSinceStartup(0.0))
.add_systems(
Expand Down
Loading

0 comments on commit b75d4b1

Please sign in to comment.