outfly/src/world.rs

460 lines
17 KiB
Rust

use crate::{actor, nature, settings};
use bevy::prelude::*;
use bevy::render::render_resource::{AsBindGroup, ShaderRef};
use bevy::math::{DVec3, I64Vec3};
use bevy::scene::{InstanceId, SceneInstance};
use bevy_xpbd_3d::prelude::*;
use bevy_xpbd_3d::plugins::sync::SyncConfig;
use std::collections::HashMap;
use std::f32::consts::PI;
use fastrand;
const ASTEROID_UPDATE_INTERVAL: f32 = 0.1; // seconds
const ASTEROID_SIZE_FACTOR: f32 = 10.0;
const RING_THICKNESS: f64 = 8.0e6;
const STARS_MAX_MAGNITUDE: f32 = 5.5;
const CENTER_WORLD_ON_PLAYER: bool = true;
const ASTEROID_SPAWN_STEP: f64 = 500.0;
const ASTEROID_VIEW_RADIUS: f64 = 3000.0;
const ASSET_ASTEROID1: &str = "models/asteroid.glb#Scene0";
const ASSET_ASTEROID2: &str = "models/asteroid2.glb#Scene0";
pub fn asset_name_to_path(name: &str) -> &'static str {
match name {
"suit" => "models/suit.glb#Scene0",
"asteroid1" => ASSET_ASTEROID1,
"asteroid2" => ASSET_ASTEROID2,
"moonlet" => "models/moonlet.glb#Scene0",
"monolith" => "models/monolith_neon.glb#Scene0",
"lightorb" => "models/lightorb.glb#Scene0",
"MeteorAceGT" => "models/MeteorAceGT.glb#Scene0",
"satellite" => "models/satellite.glb#Scene0",
"pizzeria" => "models/pizzeria2.glb#Scene0",
"pizzasign" => "models/pizzasign.glb#Scene0",
_ => "models/error.glb#Scene0",
}
}
pub struct WorldPlugin;
impl Plugin for WorldPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, handle_cheats);
app.add_systems(PostUpdate, handle_despawn);
app.add_systems(Update, spawn_despawn_asteroids);
app.add_plugins(PhysicsPlugins::default());
app.add_plugins(MaterialPlugin::<RingMaterial>::default());
//app.add_plugins(PhysicsDebugPlugin::default());
app.insert_resource(Gravity(DVec3::splat(0.0)));
app.insert_resource(AsteroidUpdateTimer(
Timer::from_seconds(ASTEROID_UPDATE_INTERVAL, TimerMode::Repeating)));
app.insert_resource(AsteroidDatabase(Vec::new()));
app.insert_resource(ActiveAsteroids(HashMap::new()));
app.add_event::<DespawnEvent>();
if CENTER_WORLD_ON_PLAYER {
// Disable bevy_xpbd's position->transform sync function
app.insert_resource(SyncConfig {
position_to_transform: false,
transform_to_position: false,
});
// Add own position->transform sync function
app.add_systems(PreUpdate, position_to_transform);
}
}
}
#[derive(Resource)] struct AsteroidUpdateTimer(Timer);
#[derive(Resource)] struct AsteroidDatabase(Vec<AsteroidData>);
#[derive(Resource)] struct ActiveAsteroids(HashMap<I64Vec3, AsteroidData>);
#[derive(Component)] struct Asteroid;
#[derive(Component)] pub struct DespawnOnPlayerDeath;
struct AsteroidData {
entity: Entity,
//viewdistance: f64,
}
#[derive(Event)]
pub struct DespawnEvent {
entity: Entity,
sceneinstance: InstanceId,
origin: I64Vec3,
}
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
pub struct RingMaterial {
alpha_mode: AlphaMode,
#[uniform(0)]
ring_radius: f32,
#[uniform(1)]
jupiter_radius: f32,
}
impl Material for RingMaterial {
fn fragment_shader() -> ShaderRef {
"shaders/jupiters_rings.wgsl".into()
}
fn alpha_mode(&self) -> AlphaMode {
self.alpha_mode
}
}
#[derive(Component)]
pub struct Star;
pub fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut materials_custom: ResMut<Assets<RingMaterial>>,
) {
// Generate starmap
let sphere_handle = meshes.add(Sphere::new(1.0));
let mut starcount = 0;
for star in nature::STARS {
let mag = star[3];
if mag > STARS_MAX_MAGNITUDE {
continue;
}
let scale_color = {|color: f32|
if mag < -20.0 {
color * 13.0f32 // Sun
} else {
color * (0.0659663 * mag * mag - 1.09862 * mag + 4.3)
}
};
let scale_size = {|mag: f32|
if mag < -20.0 {
40000.0f32 // Sun
} else {
1000.0 * (0.230299 * mag * mag - 3.09013 * mag + 15.1782)
} * 100.0
};
let (r, g, b) = nature::star_color_index_to_rgb(star[4]);
let star_color_handle = materials.add(StandardMaterial {
base_color: Color::rgb(scale_color(r), scale_color(g), scale_color(b)),
unlit: true,
..default()
});
let dist = 1e9;
commands.spawn((
Star,
PbrBundle {
mesh: sphere_handle.clone(),
material: star_color_handle.clone(),
transform: Transform::from_xyz(
dist * star[0],
dist * star[1],
dist * star[2],
)
.with_scale(Vec3::splat(scale_size(mag))),
..default()
}
));
starcount += 1;
}
info!("Generated {starcount} stars");
// Add shaded ring
let ring_radius = 229_000_000.0;
let jupiter_radius = 71_492_000.0;
commands.spawn((
MaterialMeshBundle {
mesh: meshes.add(Mesh::from(Cylinder::new(ring_radius, 1.0))),
material: materials_custom.add(RingMaterial {
alpha_mode: AlphaMode::Blend,
ring_radius: ring_radius,
jupiter_radius: jupiter_radius,
}),
..default()
},
Position::from_xyz(0.0, 0.0, 0.0),
Rotation::from(Quat::IDENTITY),
//Rotation::from(Quat::from_rotation_x(-0.3f32.to_radians())),
));
}
fn spawn_despawn_asteroids(
time: Res<Time>,
mut timer: ResMut<AsteroidUpdateTimer>,
mut commands: Commands,
q_player: Query<&Position, With<actor::PlayerCamera>>,
mut ew_despawn: EventWriter<DespawnEvent>,
mut db: ResMut<ActiveAsteroids>,
asset_server: Res<AssetServer>,
mut q_asteroid: Query<(Entity, &SceneInstance), With<Asteroid>>,
mut last_player_cell: Local<I64Vec3>,
) {
if !timer.0.tick(time.delta()).just_finished() || q_player.is_empty() {
//if q_player.is_empty() {
return;
}
let player = q_player.get_single().unwrap();
let player_cell = I64Vec3::new(
(player.x / ASTEROID_SPAWN_STEP).round() as i64,
(player.y / ASTEROID_SPAWN_STEP).round() as i64,
(player.z / ASTEROID_SPAWN_STEP).round() as i64,
);
if *last_player_cell == player_cell {
return;
}
*last_player_cell = player_cell;
// Parameters
let view_radius: f64 = ASTEROID_VIEW_RADIUS;
let step: f64 = ASTEROID_SPAWN_STEP;
let stepmax: i64 = (view_radius / step) as i64;
// Despawn far asteroids
let x_min = player_cell.x - stepmax;
let x_max = player_cell.x + stepmax;
let y_min = player_cell.y - stepmax;
let y_max = player_cell.y + stepmax;
let z_min = player_cell.z - stepmax;
let z_max = player_cell.z + stepmax;
for (origin, asteroid) in db.0.iter() {
if origin.x < x_min || origin.x > x_max
|| origin.y < y_min || origin.y > y_max
|| origin.z < z_min || origin.z > z_max
{
let mut despawning_worked = false;
for (ent, sceneinstance) in &mut q_asteroid {
if ent == asteroid.entity {
ew_despawn.send(DespawnEvent {
entity: asteroid.entity,
sceneinstance: **sceneinstance,
origin: origin.clone(),
});
despawning_worked = true;
break;
}
}
if !despawning_worked {
error!("Couldn't despawn asteroid:");
dbg!(origin);
}
}
}
// Density based on the radius alone
let radius_plane = (player.x * player.x + player.z * player.z).sqrt();
let density_r = nature::ring_density((radius_plane / 1e6) as f32);
if density_r < 0.001 {
return;
}
// Density based on radius and the vertical distance to the ring
let normalized_distance = player.y / (RING_THICKNESS / 2.0);
let density = density_r * (-4.0 * normalized_distance.powf(2.0)).exp() as f32;
if density < 0.001 {
return;
}
let mut rng = fastrand::Rng::new();
for x in -stepmax..=stepmax {
for y in -stepmax..=stepmax {
for z in -stepmax..=stepmax {
let origin = I64Vec3::new(
player_cell.x + x as i64,
player_cell.y + y as i64,
player_cell.z + z as i64,
);
if db.0.contains_key(&origin) {
// already in db, nothing to do
continue;
}
// Get a seed based on all of the origin axes
// Probably there's a faster way
rng.seed(origin.x as u64);
let seed = rng.u64(0..u64::MAX).wrapping_add(origin.y as u64);
rng.seed(seed);
let seed = rng.u64(0..u64::MAX).wrapping_add(origin.z as u64);
rng.seed(seed);
let rand_s = rng.f32();
let size_raw: f32 = (rand_s + 1e-4).powf(-0.5) as f32; // -> between ~1 and 100
let size_density = size_raw * density;
if size_density < 0.3 {
continue;
}
if size_raw < 20.0 {
let dist = player_cell.as_dvec3().distance(origin.as_dvec3());
if dist > 6.0 {
continue;
}
}
let size: f32 = ASTEROID_SIZE_FACTOR * size_density;
let rand_x = rng.f64();
let rand_y = rng.f64();
let rand_z = rng.f64();
let rand_c = rng.bool();
let class = if rand_c { 0 } else { 1 };
//let max_viewdist = ASTEROID_VIEW_RADIUS / ASTEROID_SPAWN_STEP;
let wobble = ASTEROID_SPAWN_STEP * 0.5;
let pos = DVec3::new(
origin.x as f64 * ASTEROID_SPAWN_STEP + wobble * rand_x * 2.0 - 1.0,
origin.y as f64 * ASTEROID_SPAWN_STEP + wobble * rand_y * 2.0 - 1.0,
origin.z as f64 * ASTEROID_SPAWN_STEP + wobble * rand_z * 2.0 - 1.0,
);
// Spawn
let mut entity_commands = commands.spawn((
actor::Actor::default(),
RigidBody::Dynamic,
AngularVelocity(DVec3::new(0.1, 0.1, 0.03)),
LinearVelocity(DVec3::new(0.0, 0.0, 0.35)),
Collider::sphere(1.0),
Rotation::from(Quat::from_rotation_y(-PI / 3.)),
Position::new(pos),
Asteroid,
));
let asset = match class {
0 => ASSET_ASTEROID1,
_ => ASSET_ASTEROID2,
};
entity_commands.insert(SceneBundle {
scene: asset_server.load(asset),
transform: Transform {
scale: Vec3::splat(size),
..default()
},
..default()
});
db.0.insert(origin, AsteroidData {
entity: entity_commands.id(),
//viewdistance: 99999999.0,
});
}
}
}
}
fn handle_despawn(
mut commands: Commands,
mut er_despawn: EventReader<DespawnEvent>,
mut db: ResMut<ActiveAsteroids>,
mut scene_spawner: ResMut<SceneSpawner>,
) {
for despawn in er_despawn.read() {
commands.entity(despawn.entity).despawn();
scene_spawner.despawn_instance(despawn.sceneinstance);
db.0.remove(&despawn.origin);
}
}
fn handle_cheats(
key_input: Res<ButtonInput<KeyCode>>,
mut q_player: Query<(&Transform, &mut Position, &mut LinearVelocity), With<actor::PlayerCamera>>,
mut q_life: Query<(&mut actor::LifeForm, ), With<actor::Player>>,
mut ew_playerdies: EventWriter<actor::PlayerDiesEvent>,
settings: ResMut<settings::Settings>,
) {
if q_player.is_empty() || q_life.is_empty() {
return;
}
let (trans, mut pos, mut v) = q_player.get_single_mut().unwrap();
let boost = if key_input.pressed(KeyCode::ShiftLeft) {
1e6
} else {
1e3
};
if key_input.just_pressed(settings.key_cheat_stop) {
v.0 = DVec3::ZERO;
}
if key_input.pressed(settings.key_cheat_speed) {
v.0 += DVec3::from(trans.rotation * Vec3::new(0.0, 0.0, boost));
}
if key_input.pressed(settings.key_cheat_speed_backward) {
v.0 += DVec3::from(trans.rotation * Vec3::new(0.0, 0.0, -boost));
}
if !settings.dev_mode {
return;
}
let (mut lifeform, ) = q_life.get_single_mut().unwrap();
if key_input.just_pressed(settings.key_cheat_pizza) {
pos.0 = DVec3::new(-303370.0, 0.0, -500000.0);
}
if key_input.just_pressed(settings.key_cheat_farview1) {
pos.0 = DVec3::new(-1000.0e6, 1000.0e6, -500.0e6);
}
if key_input.just_pressed(settings.key_cheat_farview2) {
pos.0 = DVec3::new(1000.0e6, 1000.0e6, -500.0e6);
}
if key_input.pressed(settings.key_cheat_adrenaline_zero) {
lifeform.adrenaline = 0.0;
}
if key_input.pressed(settings.key_cheat_adrenaline_mid) {
lifeform.adrenaline = 0.5;
}
if key_input.pressed(settings.key_cheat_adrenaline_max) {
lifeform.adrenaline = 1.0;
}
if key_input.just_pressed(settings.key_cheat_die) {
ew_playerdies.send(actor::PlayerDiesEvent);
}
}
// A variant of bevy_xpbd_3d::plugins::position_to_transform that adjusts
// the rendering position to center entities at the player camera.
// This avoids rendering glitches when very far away from the origin.
pub fn position_to_transform(
q_player: Query<&Position, With<actor::PlayerCamera>>,
mut q_trans: Query<(&'static mut Transform, &'static Position, &'static Rotation, Option<&'static Parent>)>,
parents: Query<(&'static GlobalTransform, Option<&'static Position>, Option<&'static Rotation>), With<Children>>,
) {
if let Ok(player_pos) = q_player.get_single() {
for (mut transform, pos, rot, parent) in &mut q_trans {
if let Some(parent) = parent {
if let Ok((parent_transform, parent_pos, parent_rot)) = parents.get(**parent) {
// Compute the global transform of the parent using its Position and Rotation
let parent_transform = parent_transform.compute_transform();
let parent_pos = parent_pos.map_or(parent_transform.translation, |pos| {
pos.as_vec3()
// NOTE: I commented out this because it turns a vec3 to a vec4,
// and I don't understand why bevy_xpbd would do that.
//.extend(parent_transform.translation.z)
});
let parent_rot = parent_rot.map_or(parent_transform.rotation, |rot| {
rot.as_quat()
});
let parent_scale = parent_transform.scale;
let parent_transform = Transform::from_translation(parent_pos)
.with_rotation(parent_rot)
.with_scale(parent_scale);
// The new local transform of the child body,
// computed from the its global transform and its parents global transform
let new_transform = GlobalTransform::from(
Transform::from_translation(
pos.as_vec3()
// NOTE: I commented out this because it turns a vec3 to a vec4,
// and I don't understand why bevy_xpbd would do that.
//.extend(parent_pos.z + transform.translation.z * parent_scale.z),
)
.with_rotation(rot.as_quat()),
)
.reparented_to(&GlobalTransform::from(parent_transform));
transform.translation = new_transform.translation;
transform.rotation = new_transform.rotation;
}
} else {
transform.translation = Vec3::new(
(pos.x - player_pos.x) as f32,
(pos.y - player_pos.y) as f32,
(pos.z - player_pos.z) as f32,
);
transform.rotation = rot.as_quat();
}
}
}
}