Skip to content

Commit

Permalink
Merge pull request #15 from qhdwight/0.12.1
Browse files Browse the repository at this point in the history
Update to Bevy 0.12.1
  • Loading branch information
qhdwight authored Dec 21, 2023
2 parents 64a2861 + 1602c76 commit 9bf17d5
Show file tree
Hide file tree
Showing 10 changed files with 956 additions and 721 deletions.
1,461 changes: 839 additions & 622 deletions Cargo.lock

Large diffs are not rendered by default.

17 changes: 8 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ edition = "2021"


[dependencies]
anyhow = "1.0.4"
bevy = { version = "0.11.0", features = ["serialize"] }
bevy_rapier3d = { version = "0.22.0", features = ["enhanced-determinism", "debug-render"] }
bytemuck = "1.7"
ron = "0.8.0"
toml = "0.7.3"
flagset = "0.4.3"
serde = "1.0.149"
bevy = { version = "0.12.1", features = ["serialize"] }
bevy_rapier3d = { version = "0.23.0", features = ["enhanced-determinism", "debug-render"] }
bytemuck = "1.5"
ron = "0.8"
flagset = "0.4.4"
serde = "1.0"
smartstring = { version = "1.0.1", features = ["serde"] }
wgpu = "0.16.0"
wgpu = { version = "0.17.1", features = ["naga"] }
thiserror = "1.0"

[profile.dev]
opt-level = 1
Expand Down
15 changes: 15 additions & 0 deletions assets/default.config.ron
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Config(
sensitivity: 0.001,
key_forward: W,
key_back: S,
key_left: A,
key_right: D,
key_up: Space,
key_down: ControlLeft,
key_sprint: ShiftLeft,
key_jump: Space,
key_crouch: ControlLeft,
key_fly: F,
key_reload: R,
key_fire: Q,
)
13 changes: 0 additions & 13 deletions assets/default.config.toml

This file was deleted.

24 changes: 7 additions & 17 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ extern crate core;
use std::{
f32::consts::TAU,
fmt::Write,
time::Duration,
};

use bevy::{
asset::ChangeWatcher,
diagnostic::DiagnosticsStore,
diagnostic::FrameTimeDiagnosticsPlugin,
prelude::*,
Expand Down Expand Up @@ -46,19 +44,14 @@ fn main() {
..default()
})
.add_plugins((
DefaultPlugins.set(AssetPlugin {
watch_for_changes: Some(ChangeWatcher {
delay: Duration::from_millis(100),
}),
..default()
}),
DefaultPlugins.set(AssetPlugin::default()),
RapierPhysicsPlugin::<NoUserData>::default(),
VoxelsPlugin,
FrameTimeDiagnosticsPlugin::default(),
InventoryPlugin,
))
.add_asset::<Config>()
.init_asset_loader::<ConfigAssetLoader>()
.register_asset_loader(ConfigAssetLoader)
.init_asset::<Config>()
.add_systems(Startup, (setup_sys, spawn_ui_sys, spawn_voxel_sys, spawn_player_sys))
.add_systems(PreUpdate, player_input_system)
.add_systems(Update, (
Expand All @@ -77,7 +70,7 @@ fn setup_sys(
) {
// println!("{}", toml::to_string(&Config::default()).unwrap());

let config: Handle<Config> = asset_server.load("default.config.toml");
let config: Handle<Config> = asset_server.load("default.config.ron");
commands.insert_resource(ConfigState { handle: config });

commands.spawn(DirectionalLightBundle {
Expand Down Expand Up @@ -114,8 +107,7 @@ fn setup_sys(
GlobalTransform::default(),
Collider::ball(0.5),
Sensor,
Visibility::Visible,
ComputedVisibility::default(),
VisibilityBundle::default(),
ItemPickup { item_name: ItemName::from("rifle") },
)
).with_children(|parent| {
Expand Down Expand Up @@ -210,10 +202,8 @@ fn spawn_player_sys(mut commands: Commands) {
RigidBody::Dynamic,
Sleeping::disabled(),
LockedAxes::ROTATION_LOCKED,
ReadMassProperties(MassProperties {
mass: 1.0,
..default()
}),
AdditionalMassProperties::Mass(1.0),
ReadMassProperties::default(),
GravityScale(0.0),
Ccd { enabled: true },
TransformBundle::from(Transform::from_xyz(4.0, 18.0, 4.0)),
Expand Down
2 changes: 1 addition & 1 deletion src/qgame/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub fn player_move_sys(
let groups = QueryFilter::default().exclude_collider(entity);

if let Some((_handle, hit)) = physics_context.cast_shape(
pos, rot, cast_vel, &cast_capsule, max_dist, groups,
pos, rot, cast_vel, &cast_capsule, max_dist, true, groups,
) {
ground_hit = Some(hit);
}
Expand Down
38 changes: 24 additions & 14 deletions src/qgame/input.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
use std::f32::consts::FRAC_PI_2;
use std::str::from_utf8;

use bevy::{
asset::{AssetLoader, LoadContext, LoadedAsset},
asset::{
AssetLoader,
AsyncReadExt,
io::Reader,
LoadContext,
},
input::mouse::MouseMotion,
prelude::*,
reflect::TypePath,
reflect::TypeUuid,
utils::BoxedFuture,
window::CursorGrabMode,
};
use bevy::window::CursorGrabMode;
use flagset::{flags, FlagSet};
use serde::{Deserialize, Serialize};

use crate::RonLoaderError;

flags! {
pub enum PlayerInputFlags: u32 {
Jump,
Expand All @@ -32,8 +37,7 @@ pub struct PlayerInput {
pub wanted_item_slot: Option<u8>,
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize, TypeUuid, TypePath)]
#[uuid = "9ac18a62-063a-4fa1-9575-d295ce69997b"]
#[derive(Asset, Copy, Clone, Debug, PartialEq, Serialize, Deserialize, TypePath)]
pub struct Config {
pub sensitivity: f32,
pub key_forward: KeyCode,
Expand Down Expand Up @@ -116,7 +120,7 @@ pub fn player_input_system(
let window = window.single_mut();
if window.focused {
let mut mouse_delta = Vec2::ZERO;
for mouse_event in mouse_events.iter() {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
mouse_delta *= config.sensitivity;
Expand Down Expand Up @@ -150,19 +154,25 @@ pub fn player_input_system(
pub struct ConfigAssetLoader;

impl AssetLoader for ConfigAssetLoader {
type Asset = Config;
type Settings = ();
type Error = RonLoaderError;

fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<(), anyhow::Error>> {
reader: &'a mut Reader,
_settings: &'a Self::Settings,
_load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<Config, Self::Error>> {
Box::pin(async move {
let asset: Config = toml::from_str(from_utf8(bytes)?)?;
load_context.set_default_asset(LoadedAsset::new(asset));
Ok(())
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = ron::de::from_bytes::<Config>(&bytes)?;
Ok(asset)
})
}

fn extensions(&self) -> &[&str] {
&["config.toml"]
&["config.ron"]
}
}
50 changes: 28 additions & 22 deletions src/qgame/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@ use std::{
option::Option,
time::Duration,
};
use std::str::from_utf8;

use bevy::{
asset::{AssetLoader, LoadContext, LoadedAsset},
asset::{
AssetLoader,
AsyncReadExt,
io::Reader,
LoadContext,
},
prelude::*,
reflect::TypePath,
reflect::TypeUuid,
utils::{BoxedFuture, HashMap},
};
use bevy_rapier3d::prelude::*;
use serde::{Deserialize, Serialize};
use smartstring::alias::String;

use crate::{PlayerInput, PlayerInputFlags};
use crate::{PlayerInput, PlayerInputFlags, RonLoaderError};

const EQUIPPING_STATE: &str = "equipping";
const EQUIPPED_STATE: &str = "equipped";
Expand All @@ -36,25 +39,22 @@ pub struct ItemStateProps {
pub is_persistent: bool,
}

#[derive(Serialize, Deserialize, TypeUuid, TypePath)]
#[uuid = "2cc54620-95c6-4522-b40e-0a4991ebae5f"]
#[derive(Serialize, Deserialize, TypePath)]
pub struct ItemProps {
pub name: ItemName,
pub move_factor: f32,
pub states: HashMap<ItemStateName, ItemStateProps>,
pub equip_states: HashMap<EquipStateName, ItemStateProps>,
}

#[derive(Serialize, Deserialize, TypeUuid, TypePath)]
#[uuid = "46e9c7af-27c2-4560-86e7-df48f9e84729"]
#[derive(Serialize, Deserialize, TypePath)]
pub struct WeaponProps {
pub damage: u16,
pub headshot_factor: f32,
pub item_props: ItemProps,
}

#[derive(Serialize, Deserialize, TypeUuid, TypePath)]
#[uuid = "df56751c-7560-420d-b480-eb8fb6f9b9bf"]
#[derive(Asset, Serialize, Deserialize, TypePath)]
pub struct GunProps {
pub mag_size: u16,
pub starting_ammo_in_reserve: u16,
Expand Down Expand Up @@ -103,27 +103,33 @@ pub struct Inventory {
pub struct InventoryPlugin;

impl Plugin for InventoryPlugin {
fn build(&self, app: &mut App) {}
fn build(&self, _app: &mut App) {}
}

#[derive(Default)]
pub struct ConfigAssetLoader;
pub struct GunPropsAssetLoader;

impl AssetLoader for GunPropsAssetLoader {
type Asset = GunProps;
type Settings = ();
type Error = RonLoaderError;

impl AssetLoader for ConfigAssetLoader {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<(), anyhow::Error>> {
reader: &'a mut Reader,
_settings: &'a Self::Settings,
_load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<GunProps, Self::Error>> {
Box::pin(async move {
let asset: GunProps = toml::from_str(from_utf8(bytes)?)?;
load_context.set_default_asset(LoadedAsset::new(asset));
Ok(())
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset: GunProps = ron::de::from_bytes(&bytes)?;
Ok(asset)
})
}

fn extensions(&self) -> &[&str] {
&["config.toml"]
&["config.ron"]
}
}

Expand All @@ -136,7 +142,7 @@ impl AssetLoader for ConfigAssetLoader {

pub fn modify_equip_state_sys(
time: Res<Time>,
asset_server: Res<AssetServer>,
_asset_server: Res<AssetServer>,
mut inv_query: Query<(&PlayerInput, &mut Inventory)>,
mut item_query: Query<&mut Item>,
) {
Expand Down Expand Up @@ -379,7 +385,7 @@ pub fn render_inventory_sys(
if let Ok(item) = item_query.get(*item_ent) {
let is_equipped = inv.equipped_slot == Some(item.inv_slot);
let mut transform = Transform::default();
let scene_handle = asset_server.load(format!("models/{}.glb#Scene0", item.name).as_str());
let scene_handle = asset_server.load(format!("models/{}.glb#Scene0", item.name));
if is_equipped {
transform = camera_query.single().mul_transform(Transform::from_xyz(0.4, -0.3, -1.0));
}
Expand Down
13 changes: 12 additions & 1 deletion src/qgame/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use bevy::{
renderer::{RenderDevice, RenderQueue},
},
};
use thiserror::Error;

pub use controller::*;
pub use input::*;
Expand All @@ -23,6 +24,16 @@ mod inventory;
mod lookup;
mod voxel;

#[derive(Debug, Error)]
pub enum RonLoaderError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
RonSpannedError(#[from] ron::error::SpannedError),
#[error(transparent)]
LoadDirectError(#[from] bevy::asset::LoadDirectError),
}

pub struct BufVec<T: Pod> {
read_only: bool,
buffer_capacity: usize,
Expand All @@ -44,7 +55,7 @@ pub fn create_staging_buffer(read_only: bool, size: usize, device: &RenderDevice
})
}

pub fn create_buffer(read_only: bool, size: usize, device: &RenderDevice) -> Buffer {
pub fn create_buffer(_read_only: bool, size: usize, device: &RenderDevice) -> Buffer {
// let mut usage = BufferUsages::STORAGE | if read_only {
// BufferUsages::COPY_SRC
// } else {
Expand Down
Loading

0 comments on commit 9bf17d5

Please sign in to comment.