Skip to content

Commit

Permalink
Merge pull request #45 from BrandonDyer64/bevy-v0.10
Browse files Browse the repository at this point in the history
Bevy 0.10 support
  • Loading branch information
JonahPlusPlus authored Mar 12, 2023
2 parents 56ac530 + c7c37eb commit 4b8cfb8
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 154 deletions.
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ repository = "https://github.com/JonahPlusPlus/bevy_atmosphere"
exclude = ["/assets/", "/examples/", "/.github/"]

[dependencies]
bevy = { version = "0.9", default-features = false, features = ["bevy_asset", "bevy_render", "bevy_pbr"] }
bevy_atmosphere_macros = { path = "bevy_atmosphere_macros", version = "0.1" }
bevy = {version = "0.10", default-features = false, features = ["bevy_asset", "bevy_render", "bevy_pbr"]}
bevy_atmosphere_macros = {path = "bevy_atmosphere_macros", version = "0.1"}
cfg-if = "1.0"

[dev-dependencies]
bevy_spectator = "0.1"
bevy = { version = "0.9", features = ["bevy_core_pipeline", "x11"] } # load all in case docs.rs complains
bevy_spectator = "0.2"
bevy = { version = "0.10", features = ["bevy_core_pipeline", "x11"] } # load all in case docs.rs complains

[features]
default = ["basic", "all_models"]
Expand Down
26 changes: 10 additions & 16 deletions bevy_atmosphere_macros/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,21 +112,15 @@ pub fn derive_atmospheric(ast: syn::DeriveInput) -> Result<TokenStream> {
} else if let Some(attr_ident) = attr.path.get_ident() {
if attr_ident == EXTERNAL_ATTRIBUTE_NAME {
if shader_path != ShaderPathType::None {
return Err(Error::new_spanned(
attr,
format!("Shader path already set")
));
return Err(Error::new_spanned(attr, format!("Shader path already set")));
}

let lit_str = get_shader_path_attr(attr)?;

shader_path = ShaderPathType::External(lit_str);
} else if attr_ident == INTERNAL_ATTRIBUTE_NAME {
if shader_path != ShaderPathType::None {
return Err(Error::new_spanned(
attr,
format!("Shader path already set")
));
return Err(Error::new_spanned(attr, format!("Shader path already set")));
}

let lit_str = get_shader_path_attr(attr)?;
Expand Down Expand Up @@ -324,7 +318,6 @@ pub fn derive_atmospheric(ast: syn::DeriveInput) -> Result<TokenStream> {
}
}


// Produce impls for fields with uniform bindings
let struct_name = &ast.ident;
let mut field_struct_impls = Vec::new();
Expand Down Expand Up @@ -413,7 +406,7 @@ pub fn derive_atmospheric(ast: syn::DeriveInput) -> Result<TokenStream> {
}
}
}

let generics = ast.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

Expand Down Expand Up @@ -469,13 +462,14 @@ pub fn derive_atmospheric(ast: syn::DeriveInput) -> Result<TokenStream> {
let bind_group_layout = Self::bind_group_layout(render_device);

let mut pipeline_cache = render_app.world.resource_mut::<#render_path::render_resource::PipelineCache>();

let pipeline = pipeline_cache.queue_compute_pipeline(#render_path::render_resource::ComputePipelineDescriptor {
label: Some(Cow::from("bevy_atmosphere_compute_pipeline")),
layout: Some(vec![
layout: vec![
bind_group_layout.clone(),
image_bind_group_layout,
]),
],
push_constant_ranges: vec![],
shader: handle,
shader_defs: vec![],
entry_point: Cow::from("main"),
Expand All @@ -495,7 +489,7 @@ pub fn derive_atmospheric(ast: syn::DeriveInput) -> Result<TokenStream> {

let mut registration = type_registry.get_mut(std::any::TypeId::of::<Self>()).expect("Type not registered");
registration.insert(data);
}
}
}

fn bind_group_layout(render_device: &#render_path::renderer::RenderDevice) -> #render_path::render_resource::BindGroupLayout {
Expand Down Expand Up @@ -538,7 +532,7 @@ struct BindingIndexOptions {

/// Represents the arguments for the `external` and `internal` binding attributes
struct ShaderPathMeta {
lit_str: syn::LitStr
lit_str: syn::LitStr,
}

impl Parse for BindingMeta {
Expand Down Expand Up @@ -574,7 +568,7 @@ impl Parse for UniformBindingMeta {
impl Parse for ShaderPathMeta {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
lit_str: input.parse()?
lit_str: input.parse()?,
})
}
}
Expand Down
3 changes: 2 additions & 1 deletion deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ yanked = "deny"
notice = "deny"
ignore = [
"RUSTSEC-2020-0056", # ignore stdweb (from gilrs)
"RUSTSEC-2021-0139" # ignore ansi_term until there is a replacement
"RUSTSEC-2021-0139", # ignore ansi_term until there is a replacement
"RUSTSEC-2022-0048", # ignore xml-rs as it is needed by winit
]

[licenses]
Expand Down
2 changes: 1 addition & 1 deletion examples/cycle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bevy_spectator::*;

fn main() {
App::new()
.insert_resource(Msaa { samples: 4 })
.insert_resource(Msaa::Sample4)
.insert_resource(AtmosphereModel::default()) // Default Atmosphere material, we can edit it to simulate another planet
.insert_resource(CycleTimer(Timer::new(
bevy::utils::Duration::from_millis(50), // Update our atmosphere every 50ms (in a real game, this would be much slower, but for the sake of an example we use a faster update)
Expand Down
38 changes: 18 additions & 20 deletions examples/splitscreen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ use bevy::{
core_pipeline::clear_color::ClearColorConfig,
prelude::*,
render::{camera::Viewport, view::RenderLayers},
window::{WindowId, WindowResized},
window::WindowResized,
};
use bevy_atmosphere::prelude::*;
use bevy_spectator::*;

fn main() {
println!("Demonstrates using `AtmosphereCamera.render_layers` to have multiple skyboxes in the scene at once\n\t- E: Switch camera");
App::new()
.insert_resource(Msaa { samples: 4 })
.insert_resource(Msaa::Sample4)
.insert_resource(AtmosphereModel::new(Nishita {
rayleigh_coefficient: Vec3::new(22.4e-6, 5.5e-6, 13.0e-6), // Change rayleigh coefficient to change color
..default()
Expand All @@ -34,7 +34,7 @@ fn setup(
) {
// Plane
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Plane { size: 100.0 })),
mesh: meshes.add(Mesh::from(shape::Plane::from_size(100.0))),
material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()),
..default()
});
Expand Down Expand Up @@ -74,7 +74,7 @@ fn setup(
transform: Transform::from_xyz(100.0, 50.0, 150.0).looking_at(Vec3::ZERO, Vec3::Y),
camera: Camera {
// Renders the right camera after the left camera, which has a default priority of 0
priority: 1,
order: 1,
..default()
},
camera_3d: Camera3d {
Expand All @@ -100,7 +100,7 @@ struct LeftCamera;
struct RightCamera;

fn set_camera_viewports(
windows: Res<Windows>,
windows: Query<&Window>,
mut resize_events: EventReader<WindowResized>,
mut left_camera: Query<&mut Camera, (With<LeftCamera>, Without<RightCamera>)>,
mut right_camera: Query<&mut Camera, With<RightCamera>>,
Expand All @@ -109,22 +109,20 @@ fn set_camera_viewports(
// so then each camera always takes up half the screen.
// A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
for resize_event in resize_events.iter() {
if resize_event.id == WindowId::primary() {
let window = windows.primary();
let mut left_camera = left_camera.single_mut();
left_camera.viewport = Some(Viewport {
physical_position: UVec2::new(0, 0),
physical_size: UVec2::new(window.physical_width() / 2, window.physical_height()),
..default()
});
let window = windows.get(resize_event.window).unwrap();
let mut left_camera = left_camera.single_mut();
left_camera.viewport = Some(Viewport {
physical_position: UVec2::new(0, 0),
physical_size: UVec2::new(window.physical_width() / 2, window.physical_height()),
..default()
});

let mut right_camera = right_camera.single_mut();
right_camera.viewport = Some(Viewport {
physical_position: UVec2::new(window.physical_width() / 2, 0),
physical_size: UVec2::new(window.physical_width() / 2, window.physical_height()),
..default()
});
}
let mut right_camera = right_camera.single_mut();
right_camera.viewport = Some(Viewport {
physical_position: UVec2::new(window.physical_width() / 2, 0),
physical_size: UVec2::new(window.physical_width() / 2, window.physical_height()),
..default()
});
}
}

Expand Down
36 changes: 15 additions & 21 deletions src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use bevy::{
prelude::*,
render::{
extract_resource::{ExtractResource, ExtractResourcePlugin},
render_asset::{PrepareAssetLabel, RenderAssets},
render_asset::{PrepareAssetSet, RenderAssets},
render_graph::{self, RenderGraph},
render_resource::{
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout,
Expand All @@ -19,7 +19,7 @@ use bevy::{
},
renderer::RenderDevice,
texture::FallbackImage,
Extract, RenderApp, RenderStage,
Extract, RenderApp, RenderSet,
},
};

Expand Down Expand Up @@ -139,24 +139,18 @@ impl Plugin for AtmospherePipelinePlugin {
.init_resource::<CachedAtmosphereModelMetadata>()
.init_resource::<AtmosphereImageBindGroupLayout>()
.init_resource::<Events<AtmosphereUpdateEvent>>()
.add_system_to_stage(RenderStage::Extract, extract_atmosphere_resources)
.add_system_to_stage(
RenderStage::Prepare,
Events::<AtmosphereUpdateEvent>::update_system,
)
.add_system_to_stage(
RenderStage::Prepare,
.add_system(extract_atmosphere_resources.in_schedule(ExtractSchedule))
.add_system(Events::<AtmosphereUpdateEvent>::update_system.in_set(RenderSet::Prepare))
.add_system(
prepare_atmosphere_assets
.label(PrepareAssetLabel::PostAssetPrepare)
.after(PrepareAssetLabel::AssetPrepare),
.in_set(PrepareAssetSet::PostAssetPrepare)
.after(PrepareAssetSet::AssetPrepare),
)
.add_system_to_stage(RenderStage::Queue, queue_atmosphere_bind_group);
.add_system(queue_atmosphere_bind_group.in_set(RenderSet::Queue));

let mut render_graph = render_app.world.resource_mut::<RenderGraph>();
render_graph.add_node(NAME, AtmosphereNode::default());
render_graph
.add_node_edge(NAME, bevy::render::main_graph::node::CAMERA_DRIVER)
.unwrap();
render_graph.add_node_edge(NAME, bevy::render::main_graph::node::CAMERA_DRIVER);
}
}

Expand Down Expand Up @@ -323,6 +317,7 @@ pub const ATMOSPHERE_IMAGE_TEXTURE_DESCRIPTOR: fn(u32) -> TextureDescriptor<'sta
usage: TextureUsages::COPY_DST
| TextureUsages::STORAGE_BINDING
| TextureUsages::TEXTURE_BINDING,
view_formats: &[TextureFormat::Rgba16Float],
};

/// Whenever settings changed, the texture view needs to be updated to use the new texture.
Expand Down Expand Up @@ -504,12 +499,11 @@ impl render_graph::Node for AtmosphereNode {
data.pipeline
};

let mut pass =
render_context
.command_encoder
.begin_compute_pass(&ComputePassDescriptor {
label: Some("atmosphere_pass"),
});
let mut pass = render_context.command_encoder().begin_compute_pass(
&ComputePassDescriptor {
label: Some("atmosphere_pass"),
},
);

pass.set_bind_group(0, &bind_groups.0, &[]);
pass.set_bind_group(1, &bind_groups.1, &[]);
Expand Down
13 changes: 5 additions & 8 deletions src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,8 @@ impl Plugin for AtmospherePlugin {

#[cfg(feature = "detection")]
{
app.add_system_set_to_stage(
CoreStage::PostUpdate,
SystemSet::new()
.with_system(atmosphere_insert)
.with_system(atmosphere_remove),
app.add_systems(
(atmosphere_insert, atmosphere_remove).in_base_set(CoreSet::PostUpdate),
);
}

Expand Down Expand Up @@ -106,7 +103,7 @@ fn atmosphere_insert(
commands
.entity(camera)
.insert(VisibilityBundle {
visibility: Visibility { is_visible: true },
visibility: Visibility::Visible,
..default()
})
.with_children(|c| {
Expand Down Expand Up @@ -137,9 +134,9 @@ fn atmosphere_remove(
mut commands: Commands,
parents: Query<&Children>,
atmosphere_skyboxes: Query<Entity, With<AtmosphereSkyBox>>,
atmosphere_cameras: RemovedComponents<AtmosphereCamera>,
mut atmosphere_cameras: RemovedComponents<AtmosphereCamera>,
) {
for camera in &atmosphere_cameras {
for camera in &mut atmosphere_cameras {
#[cfg(feature = "bevy/trace")]
trace!("Removing skybox from camera entity (ID:{:?})", camera);
let Ok(children) = parents.get(camera) else {
Expand Down
18 changes: 9 additions & 9 deletions src/shaders/nishita.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ struct Nishita {
mie_direction: f32,
}

let PI: f32 = 3.141592653589793;
let ISTEPS: u32 = 16u;
let JSTEPS: u32 = 8u;
const PI: f32 = 3.141592653589793;
const ISTEPS: u32 = 16u;
const JSTEPS: u32 = 8u;

fn rsi(rd: vec3<f32>, r0: vec3<f32>, sr: f32) -> vec2<f32> {
// ray-sphere intersection that assumes
Expand Down Expand Up @@ -42,7 +42,7 @@ fn render_nishita(r: vec3<f32>, r0: vec3<f32>, p_sun: vec3<f32>, i_sun: f32, r_p

// Calculate the step size of the primary ray.
var p = rsi(r, r0, r_atmos);
if (p.x > p.y) { return vec3<f32>(0f); }
if p.x > p.y { return vec3<f32>(0f); }
p.y = min(p.y, rsi(r, r0, r_planet).x);
let i_step_size = (p.y - p.x) / f32(ISTEPS);

Expand Down Expand Up @@ -131,12 +131,12 @@ var image: texture_storage_2d_array<rgba16float, write>;
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) invocation_id: vec3<u32>, @builtin(num_workgroups) num_workgroups: vec3<u32>) {
let size = textureDimensions(image).x;
let scale = f32(size)/2f;
let dir = vec2<f32>((f32(invocation_id.x)/scale) - 1f, (f32(invocation_id.y)/scale) - 1f);
let scale = f32(size) / 2f;

let dir = vec2<f32>((f32(invocation_id.x) / scale) - 1f, (f32(invocation_id.y) / scale) - 1f);

var ray: vec3<f32>;

switch invocation_id.z {
case 0u {
ray = vec3<f32>(1f, -dir.y, -dir.x); // +X
Expand All @@ -159,7 +159,7 @@ fn main(@builtin(global_invocation_id) invocation_id: vec3<u32>, @builtin(num_wo
}

let render = render_nishita(
ray,
ray,
nishita.ray_origin,
nishita.sun_position,
nishita.sun_intensity,
Expand Down
6 changes: 4 additions & 2 deletions src/skybox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use bevy::{
reflect::TypeUuid,
render::{
mesh::{Indices, Mesh, MeshVertexBufferLayout, PrimitiveTopology},
render_resource::{AsBindGroup, RenderPipelineDescriptor, ShaderRef},
render_resource::{AsBindGroup, RenderPipelineDescriptor, ShaderDefVal, ShaderRef},
},
};

Expand Down Expand Up @@ -52,7 +52,9 @@ impl Material for SkyBoxMaterial {
#[cfg(feature = "dithering")]
if key.bind_group_data.dithering {
if let Some(fragment) = &mut descriptor.fragment {
fragment.shader_defs.push(String::from("DITHER"));
fragment
.shader_defs
.push(ShaderDefVal::Bool(String::from("DITHER"), true));
}
}

Expand Down
Loading

0 comments on commit 4b8cfb8

Please sign in to comment.