Skip to content

Commit

Permalink
Merge pull request #11 from Waridley/day_night
Browse files Browse the repository at this point in the history
Day-night cycle is now a configurable Resource
  • Loading branch information
Waridley authored Dec 16, 2023
2 parents 84ab1be + 452e585 commit 68560f1
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 18 deletions.
8 changes: 8 additions & 0 deletions .idea/runConfigurations/Cleanup.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/runConfigurations/rustfmt.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions rs/assets/shaders/skybox.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ struct SkyCube {
face_width: f32,
face_rotation: mat3x3<f32>,
rotation: mat3x3<f32>,
time_of_day: f32,
daylight: f32,
sun_position: vec3<f32>,
moon_position: vec3<f32>,
}

@group(0) @binding(0) var<uniform> cube: SkyCube;
Expand Down Expand Up @@ -48,8 +52,7 @@ fn vertex(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
let ray_dir = ray_dir(in.position.xy);
let sample_dir = cube.rotation * ray_dir;
let daytime = (sin(globals.time * 0.01) + 1.0) * 0.707;
let sample_color = vec4(normalize((sample_dir + vec3(1.0))) * (daytime * daytime), 1.0);
let sample_color = vec4(normalize((sample_dir + vec3(1.0))) * (cube.daylight), 1.0);

return sample_color;
}
2 changes: 1 addition & 1 deletion rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ pub fn run() {
player::plugin.plugfn(),
pickups::plugin.plugfn(),
settings::plugin.plugfn(),
planet::terrain::plugin.plugfn(),
planet::plugin.plugfn(),
ui::plugin.plugfn(),
))
.insert_resource(PkvStore::new_with_qualifier(
Expand Down
12 changes: 8 additions & 4 deletions rs/src/planet.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
use bevy::{
math::Vec3,
prelude::{Component, Deref, DerefMut, Vec2},
};
use crate::{planet::day_night::DayNightCycle, util::IntoFnPlugin};
use bevy::prelude::*;
use bevy_rapier3d::{na::Vector2, parry::math::Vector};
use serde::{Deserialize, Serialize};
use std::ops::{Add, Sub};

pub mod chunks;
pub mod day_night;
pub mod sky;
pub mod terrain;

pub fn plugin(app: &mut App) -> &mut App {
app.add_plugins((terrain::plugin.plugfn(), day_night::plugin.plugfn()))
.init_resource::<DayNightCycle>()
}

#[derive(
Component, Default, Debug, Copy, Clone, Deref, DerefMut, PartialEq, Serialize, Deserialize,
)]
Expand Down
52 changes: 52 additions & 0 deletions rs/src/planet/day_night.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use bevy::{prelude::*, render::extract_resource::ExtractResource};
use std::f64::consts::TAU;

pub const DAY_LENGTH_MINUTES: f64 = 20.0;
const SECS_PER_MIN: f64 = 60.0;
const DAY_LENGTH_SECS: f64 = DAY_LENGTH_MINUTES * SECS_PER_MIN;

pub fn plugin(app: &mut App) -> &mut App {
app.add_systems(Update, update_day_night)
}

#[derive(Resource, ExtractResource, Clone, Debug)]
pub struct DayNightCycle {
pub mode: DayNightMode,
pub time_of_day: f64,
pub daylight: f64,
pub sun_position: Vec3,
pub moon_position: Vec3,
}

impl Default for DayNightCycle {
fn default() -> Self {
Self {
mode: default(),
time_of_day: 0.0,
daylight: 0.0,
sun_position: Vec3::splat(1.0).normalize(),
moon_position: Vec3::splat(-1.0).normalize(),
}
}
}

#[derive(Default, Clone, Copy, Debug)]
pub enum DayNightMode {
#[default]
Running,
Forced,
}

pub fn update_day_night(mut day_night: ResMut<DayNightCycle>, t: Res<Time>) {
match day_night.mode {
DayNightMode::Running => {
let tod = (day_night.time_of_day + t.delta_seconds_f64() / DAY_LENGTH_SECS) % 1.0;
day_night.time_of_day = tod;
let cos_tod = -(tod * TAU).cos();
let tod_norm = (cos_tod + 1.0) * 0.5; // Remap to 0..=1
day_night.daylight = (((cos_tod * cos_tod) + 1.0) * 0.5) // Linger mid-day a little longer
* tod_norm * tod_norm // Make night last longer
}
DayNightMode::Forced => {}
}
}
30 changes: 20 additions & 10 deletions rs/src/planet/sky.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ use bevy::{

use bevy::{prelude::*, render::camera::ExtractedCamera};

use crate::planet::day_night::DayNightCycle;
use bevy::render::{
extract_resource::ExtractResourcePlugin,
globals::{GlobalsBuffer, GlobalsUniform},
render_graph::{
NodeRunError, OutputSlotError, RenderGraphApp, RenderGraphContext, SlotLabel, ViewNode,
Expand All @@ -57,16 +59,11 @@ pub struct SkyPlugin;

impl Plugin for SkyPlugin {
fn build(&self, app: &mut App) {
// /// Copied from Bevy source since it's not public
// const SKYBOX_SHADER_HANDLE: Handle<Shader> = Handle::weak_from_u128(55594763423201);
// let mut shaders = app.world.resource_mut::<Assets<Shader>>();
// shaders.insert(SKYBOX_SHADER_HANDLE, Shader::from_wgsl(
// include_str!("skybox.wgsl"),
// "skybox.wgsl",
// ));

app.add_plugins((ExtractComponentPlugin::<SkyShader>::default(),))
.add_systems(Update, notify_skybox_changed);
app.add_plugins((
ExtractComponentPlugin::<SkyShader>::default(),
ExtractResourcePlugin::<DayNightCycle>::default(),
))
.add_systems(Update, notify_skybox_changed);

let render_app = app.get_sub_app_mut(RenderApp).unwrap();
render_app
Expand Down Expand Up @@ -326,6 +323,7 @@ fn prepare_sky_bind_groups(
fallback_image: Res<FallbackImage>,
render_device: Res<RenderDevice>,
views: Query<(Entity, &Skybox)>,
day_night: Res<DayNightCycle>,
t: Res<Time>,
) {
let s = t.elapsed_seconds_wrapped();
Expand All @@ -352,6 +350,10 @@ fn prepare_sky_bind_groups(
face_width: skybox.size.x,
face_rotation: FACE_ROTATIONS[i],
rotation: cube_rotation,
time_of_day: day_night.time_of_day as f32,
daylight: day_night.daylight as f32,
sun_position: day_night.sun_position,
moon_position: day_night.moon_position,
}
.unprepared_bind_group(
&SkyCubeUniforms::bind_group_layout(&render_device),
Expand Down Expand Up @@ -398,4 +400,12 @@ pub struct SkyCubeUniforms {
face_rotation: Mat3,
#[uniform(0)]
rotation: Mat3,
#[uniform(0)]
time_of_day: f32,
#[uniform(0)]
daylight: f32,
#[uniform(0)]
sun_position: Vec3,
#[uniform(0)]
moon_position: Vec3,
}

0 comments on commit 68560f1

Please sign in to comment.