Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
kayhhh committed Sep 22, 2024
1 parent 7a4ee52 commit 9963e91
Show file tree
Hide file tree
Showing 12 changed files with 167 additions and 173 deletions.
1 change: 1 addition & 0 deletions crates/unavi-app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ pub async fn start(db: Surreal<Db>, opts: StartOptions) {
primary_window: Some(Window {
prevent_default_event_handling: true,
title: "UNAVI".to_string(),
name: Some("unavi".to_string()),
..default()
}),
..default()
Expand Down
93 changes: 46 additions & 47 deletions crates/unavi-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,35 @@ use surrealdb::Surreal;
use tracing::Level;
use unavi_app::StartOptions;

#[cfg(not(target_family = "wasm"))]
fn main() {
use surrealdb::engine::local::Mem;
use unavi_app::native::{db::get_filesystem_db, update::check_for_updates};

let args = Args::parse();

if !args.no_update {
if let Err(e) = check_for_updates() {
panic!("Failed to update: {}", e);
};
}

let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Failed to build tokio runtime");

rt.block_on(async {
let db = match args.storage {
Storage::Filesystem => get_filesystem_db().await,
Storage::Memory => Surreal::new::<Mem>(()).await,
}
.expect("Failed to create SurrealDB");

unavi_app::start(db, args.to_options()).await;
});
}

#[cfg(target_family = "wasm")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub async fn start() {
Expand Down Expand Up @@ -40,9 +69,7 @@ pub async fn start() {
.await
.expect("Failed to create SurrealDB.");

let opts = args_to_options(args);

unavi_app::start(db, opts).await;
unavi_app::start(db, args.to_options()).await;
}

#[cfg(target_family = "wasm")]
Expand Down Expand Up @@ -71,6 +98,22 @@ struct Args {
xr: bool,
}

impl Args {
fn to_options(&self) -> StartOptions {
let log_level = match self.log_level {
LogLevel::Info => Level::INFO,
LogLevel::Debug => Level::DEBUG,
LogLevel::Trace => Level::TRACE,
};

StartOptions {
debug_physics: self.debug_physics,
log_level,
xr: self.xr,
}
}
}

#[derive(ValueEnum, Clone, Debug, Default)]
enum LogLevel {
#[default]
Expand All @@ -84,47 +127,3 @@ pub enum Storage {
Filesystem,
Memory,
}

#[cfg(not(target_family = "wasm"))]
fn main() {
use surrealdb::engine::local::Mem;
use unavi_app::native::{db::get_filesystem_db, update::check_for_updates};

let args = Args::parse();

if !args.no_update {
if let Err(e) = check_for_updates() {
panic!("Failed to update: {}", e);
};
}

let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Failed to build tokio runtime");

rt.block_on(async {
let db = match args.storage {
Storage::Filesystem => get_filesystem_db().await,
Storage::Memory => Surreal::new::<Mem>(()).await,
}
.expect("Failed to create SurrealDB");

let opts = args_to_options(args);
unavi_app::start(db, opts).await;
});
}

fn args_to_options(args: Args) -> StartOptions {
let log_level = match args.log_level {
LogLevel::Info => Level::INFO,
LogLevel::Debug => Level::DEBUG,
LogLevel::Trace => Level::TRACE,
};

StartOptions {
debug_physics: args.debug_physics,
log_level,
xr: args.xr,
}
}
24 changes: 12 additions & 12 deletions crates/unavi-avatar/src/fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,6 @@ use bevy::prelude::*;
use bevy_vrm::loader::Vrm;
use unavi_constants::player::{PLAYER_HEIGHT, PLAYER_WIDTH};

#[derive(Component, Default)]
pub struct FallbackAvatar;

#[derive(Resource, Deref)]
pub struct FallbackMaterial(Handle<StandardMaterial>);

#[derive(Resource, Deref)]
pub struct FallbackMesh(Handle<Mesh>);

pub fn init_fallback_assets(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
Expand Down Expand Up @@ -41,9 +32,6 @@ pub fn remove_fallback_avatar(
}
}

#[derive(Component)]
pub struct FallbackChild;

pub fn spawn_fallback_children(
fallback_material: Res<FallbackMaterial>,
fallback_mesh: Res<FallbackMesh>,
Expand Down Expand Up @@ -85,6 +73,18 @@ pub fn despawn_fallback_children(
}
}

#[derive(Component, Default)]
pub struct FallbackAvatar;

#[derive(Resource, Deref)]
pub struct FallbackMaterial(Handle<StandardMaterial>);

#[derive(Resource, Deref)]
pub struct FallbackMesh(Handle<Mesh>);

#[derive(Component)]
pub struct FallbackChild;

#[cfg(test)]
mod tests {
use super::*;
Expand Down
8 changes: 4 additions & 4 deletions crates/unavi-avatar/src/velocity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ pub struct AverageVelocity {
pub alpha: f32,
pub initialized: bool,
pub prev_translation: Vec3,
/// If None, will use the current entity.
/// The target entity to track the velocity of.
/// If set to None, the current entity will be used.
pub target: Option<Entity>,
pub velocity: Vec3,
}
Expand All @@ -35,9 +35,9 @@ pub fn calc_average_velocity(
for (entity, mut avg) in velocities.iter_mut() {
let target = avg.target.unwrap_or(entity);

let Ok(transform) = transforms.get(target) else {
continue;
};
let transform = transforms
.get(target)
.expect("Velocity target has no transform");

if !avg.initialized {
avg.prev_translation.clone_from(&transform.translation);
Expand Down
20 changes: 8 additions & 12 deletions crates/unavi-player/src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,12 @@ pub(crate) fn setup_first_person(
) {
for event in events.read() {
if let AssetEvent::LoadedWithDependencies { id } = event {
for (avatar_ent, handle_vrm) in avatars.iter() {
if handle_vrm.id() != *id {
continue;
}
let (ent, _) = avatars
.iter()
.find(|(_, handle)| handle.id() == *id)
.expect("Avatar not found");

writer.send(SetupFirstPerson(avatar_ent));
}
writer.send(SetupFirstPerson(ent));
}
}
}
Expand All @@ -164,11 +163,10 @@ pub(crate) fn calc_eye_offset(
}

for ent in to_calc.iter() {
let Ok(handle_scene) = scenes.get(*ent) else {
continue;
};
let handle_scene = scenes.get(*ent).expect("Scene handle not found");

let Some(scene) = scene_assets.get_mut(handle_scene) else {
// Asset might not be loaded yet.
continue;
};

Expand Down Expand Up @@ -280,9 +278,7 @@ pub(crate) fn rotate_avatar_head(
mut commands: Commands,
) {
for (head, offset) in avatars.iter() {
let Ok((mut head_tr, base)) = bones.get_mut(head.0) else {
continue;
};
let (mut head_tr, base) = bones.get_mut(head.0).expect("Avatar head bone not found");

let Some(base) = base else {
commands
Expand Down
2 changes: 2 additions & 0 deletions crates/unavi-player/src/controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub fn move_player(
mut players: Query<(&Transform, &mut LocalPlayer, &mut TnuaController)>,
time: Res<Time>,
) {
debug_assert!(*last_time > 0.0);

for (transform, mut player, mut controller) in players.iter_mut() {
let dir_forward = transform.rotation.mul_vec3(Vec3::NEG_Z);
let dir_left = transform.rotation.mul_vec3(Vec3::NEG_X);
Expand Down
14 changes: 7 additions & 7 deletions crates/unavi-player/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,13 @@ pub fn handle_raycast_input(
};

if hit.entity == ent {
if let Err(e) = handler.send(ScriptInputEvent::Raycast {
action,
origin: translation,
orientation: rotation,
}) {
error!("Failed to send script input event: {}", e);
};
handler
.send(ScriptInputEvent::Raycast {
action,
origin: translation,
orientation: rotation,
})
.expect("Failed to send script input event");
break;
}
}
Expand Down
26 changes: 14 additions & 12 deletions crates/unavi-player/src/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,21 @@ fn set_menu_animation(
mut animation_players: Query<(&mut TargetAnimationWeights, &Parent)>,
players: Query<&Children, With<LocalPlayer>>,
) {
for children in players.iter() {
for child in children.iter() {
if let Ok(avatar_ent) = avatars.get(*child) {
for (mut targets, parent) in animation_players.iter_mut() {
if parent.get() != avatar_ent {
continue;
}
let Ok(children) = players.get_single() else {
return;
};

if *open {
targets.insert(AnimationName::Menu, 1.0);
} else {
targets.remove(&AnimationName::Menu);
}
for child in children.iter() {
if let Ok(avatar_ent) = avatars.get(*child) {
for (mut targets, parent) in animation_players.iter_mut() {
if parent.get() != avatar_ent {
continue;
}

if *open {
targets.insert(AnimationName::Menu, 1.0);
} else {
targets.remove(&AnimationName::Menu);
}
}
}
Expand Down
11 changes: 2 additions & 9 deletions crates/unavi-scripting/src/api/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::cell::Cell;

use bevy::{
log::{debug, warn},
prelude::*,
};
use bevy::{log::debug, prelude::*};
use wasm_bridge::component::{Resource, ResourceTable, ResourceTableError};

/// A `Cell<usize>` used for reference counting.
Expand Down Expand Up @@ -34,11 +31,7 @@ pub trait RefCount {
fn decrement(&self) -> usize {
let count = self.ref_count();
let val = count.get();

if val == 0 {
warn!("Cannot decrement, ref_count already at 0");
return 0;
}
debug_assert!(val > 0, "Cannot decrement, ref count already at 0");

let new = val - 1;
count.set(new);
Expand Down
Loading

0 comments on commit 9963e91

Please sign in to comment.