Compare commits

...

12 commits
dev ... main

Author SHA1 Message Date
WanderingPenwing f87741795f improved readme 2024-10-16 16:12:10 +02:00
WanderingPenwing 89f27f0395 added doc 2024-10-16 16:07:44 +02:00
WanderingPenwing c0103ec247 added right click rot 2024-10-08 17:25:04 +02:00
WanderingPenwing 0d0673a0af clean 2024-10-08 09:07:09 +02:00
WanderingPenwing 3430f37783 zoom 2024-10-08 08:34:02 +02:00
WanderingPenwing d07780dcdb tweaked constants 2024-10-07 22:48:07 +02:00
WanderingPenwing 9a1b13b6f9 added constellation names 2024-10-07 22:41:58 +02:00
WanderingPenwing b20579f22b explore constellations 2024-10-07 22:25:58 +02:00
WanderingPenwing 26e54d05cf opa 2024-10-07 22:12:17 +02:00
WanderingPenwing bd704008f2 better hints 2024-10-07 21:27:53 +02:00
WanderingPenwing ba17c16042 escape from play 2024-10-07 20:11:06 +02:00
WanderingPenwing 3217fbdfbe explore game state 2024-10-07 19:49:50 +02:00
8 changed files with 421 additions and 165 deletions

View file

@ -5,3 +5,15 @@ A Stellarium game made for The icam Game jam 2024, using the Bevy game engine
Star data from : [YaleBrightStarCatalog (Bretton Wade)](https://github.com/brettonw/YaleBrightStarCatalog/blob/master/bsc5-short.json) (MIT License, Copyright (c) 2016 Bretton Wade) Star data from : [YaleBrightStarCatalog (Bretton Wade)](https://github.com/brettonw/YaleBrightStarCatalog/blob/master/bsc5-short.json) (MIT License, Copyright (c) 2016 Bretton Wade)
Constellation data from :[Lizard Tail (Isana Kashiwai)](https://www.lizard-tail.com/isana/lab/starlitnight/) Constellation data from :[Lizard Tail (Isana Kashiwai)](https://www.lizard-tail.com/isana/lab/starlitnight/)
## Tips
There is one information that is not yet explained in the game : you can left click and drag to move around.
## Demo
You can check it out [on my website](https://www.penwing.org/assets/games/Astraea/web/index.html)
but here is a sneak peek :
![](doc/screenshot.png)

BIN
doc/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

7
doc/todo Normal file
View file

@ -0,0 +1,7 @@
#music
zoom - web
right drag to rotate
baby gyroscope
rounded corners buttons
star temperature

11
doc/waswm-proecedure Normal file
View file

@ -0,0 +1,11 @@
nix develop
cargo build --release --target wasm32-unknown-unknown
exit
----
nix-shell -p wasm-bindgen-cli --argstr nixpkgs https://nixos.org/channels/nixpkgs-unstable
wasm-bindgen target/wasm32-unknown-unknown/release/astraea.wasm --out-dir ./out --target web
exit
-----
cd out/
nix-shell -p python3
python3 -m http.server

View file

@ -1,19 +1,82 @@
use bevy::prelude::*; use bevy::prelude::*;
use bevy::input::mouse::MouseScrollUnit;
use bevy::input::mouse::MouseWheel;
use std::f32::consts::{E, PI};
use crate::Player; use crate::Player;
use crate::GameState;
use crate::ConstellationModel;
use crate::Sky;
use crate::MainGame;
use crate::spawn_cons_lines;
use crate::CONS_VIEW_RADIUS;
use crate::MOVE_SPEED;
use crate::ROT_SPEED;
#[derive(Component)]
pub struct InfoLabel;
pub fn setup (
sky : Res<Sky>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for constellation in sky.content.iter() {
spawn_cons_lines(&mut commands, &mut meshes, &mut materials, constellation.clone());
}
let centered_container_node = NodeBundle {
style: Style {
position_type: PositionType::Absolute,
width: Val::Percent(100.0),
top: Val::Px(20.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
};
let info_label_node = TextBundle::from_section(
"info",
TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 20.0,
color: Color::srgb(0.7, 0.7, 0.7),
..default()
},
);
let centered_container = commands.spawn(centered_container_node).id();
let info_label = commands.spawn((info_label_node, MainGame, InfoLabel)).id();
commands.entity(centered_container).push_children(&[info_label]);
}
pub fn player_mouse_move ( pub fn player_mouse_move (
buttons: Res<ButtonInput<MouseButton>>, buttons: Res<ButtonInput<MouseButton>>,
mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>, mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>,
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>, window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
ui_query: Query<&Interaction, With<Button>>,
) { ) {
for interaction in ui_query.iter() {
if *interaction == Interaction::Pressed {
// Button clicked
return;
}
}
let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else { let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else {
return; return;
}; };
let local_transform = &global_transform.compute_transform(); let local_transform = &global_transform.compute_transform();
if !buttons.pressed(MouseButton::Left) { if !buttons.pressed(MouseButton::Left) {
player.dragging_pos = None; player.l_drag_pos = None;
return; return;
} }
@ -23,8 +86,8 @@ pub fn player_mouse_move (
return; return;
}; };
let Some(old_cursor) = player.dragging_pos else { let Some(old_cursor) = player.l_drag_pos else {
player.dragging_pos = Some(new_cursor); player.l_drag_pos = Some(new_cursor);
return; return;
}; };
@ -43,7 +106,96 @@ pub fn player_mouse_move (
let delta_rotation = rotate_to_align(new_ray, old_ray); let delta_rotation = rotate_to_align(new_ray, old_ray);
player.target_rotation = Some(delta_rotation * local_transform.rotation ); player.target_rotation = Some(delta_rotation * local_transform.rotation );
player.dragging_pos = Some(new_cursor); player.l_drag_pos = Some(new_cursor);
}
pub fn player_mouse_rotate (
buttons: Res<ButtonInput<MouseButton>>,
mut player_query: Query<(&mut Player, &mut GlobalTransform)>,
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
ui_query: Query<&Interaction, With<Button>>,
) {
for interaction in ui_query.iter() {
if *interaction == Interaction::Pressed {
// Button clicked
return;
}
}
let Ok((mut player, global_transform)) = player_query.get_single_mut() else {
return;
};
let local_transform = &global_transform.compute_transform();
if !buttons.pressed(MouseButton::Right) {
player.r_drag_pos = None;
return;
}
let window = window_query.single();
let Some(new_cursor) = window.cursor_position() else {
return;
};
let Some(old_cursor) = player.r_drag_pos else {
player.r_drag_pos = Some(new_cursor);
return;
};
if old_cursor.distance(new_cursor) < 1.0 {
return;
}
let center = Vec2::new(window.width()/2.0, window.height()/2.0);
let old_vec = old_cursor - center;
let new_vec = new_cursor - center;
if new_vec.length() < f32::EPSILON || old_vec.length() < f32::EPSILON {
player.r_drag_pos = Some(new_cursor);
return;
}
let angle = (old_vec.dot(new_vec) / (old_vec.length() * new_vec.length())).acos() * ROT_SPEED;
let signed_angle = if old_vec.perp_dot(new_vec) < 0.0 {
angle
} else {
-angle
};
let delta_rotation = Quat::from_axis_angle(local_transform.forward().into(), signed_angle);
player.target_rotation = Some(delta_rotation * local_transform.rotation);
player.r_drag_pos = Some(new_cursor);
}
pub fn zoom(
mut evr_scroll: EventReader<MouseWheel>,
mut projection_query: Query<&mut Projection, With<Player>>,
) {
let Ok(mut projection) = projection_query.get_single_mut() else {
//info!("no camera projection");
return;
};
let Projection::Perspective(ref mut perspective) = *projection else {
//info!("no camera perspective");
return;
};
for ev in evr_scroll.read() {
match ev.unit {
MouseScrollUnit::Line => {
perspective.fov = (0.6*PI).min((0.02*PI).max(perspective.fov * 0.9_f32.powf(ev.y)));
//info!("Scroll (line units): vertical: {}, horizontal: {}", ev.y, ev.x);
}
MouseScrollUnit::Pixel => {
//info!("Scroll (pixel units): vertical: {}, horizontal: {}", ev.y, ev.x);
}
}
}
} }
fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat { fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
@ -60,7 +212,7 @@ fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
} }
let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0); let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0);
let angle_of_rotation = dot_product.acos() * 6.0; let angle_of_rotation = dot_product.acos() * MOVE_SPEED;
if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() { if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() {
return Quat::IDENTITY; return Quat::IDENTITY;
@ -68,3 +220,80 @@ fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
Quat::from_axis_angle(axis_of_rotation, angle_of_rotation) Quat::from_axis_angle(axis_of_rotation, angle_of_rotation)
} }
pub fn rotate_camera(
mut player_query : Query<(&mut Player, &mut Transform)>
) {
let Ok((mut player, mut transform)) = player_query.get_single_mut() else {
return;
};
let Some(target_rotation) = player.target_rotation else {
return;
};
let current_rotation = transform.rotation;
transform.rotation = current_rotation.slerp(target_rotation, 0.1);
if transform.rotation.angle_between(target_rotation) < 0.01 {
player.target_rotation = None;
}
}
pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>,
mut game_state: ResMut<NextState<GameState>>,
//mut player_query: Query<(&mut Player, &mut Transform)>,
) {
if keys.just_pressed(KeyCode::Escape) {
game_state.set(GameState::Start);
}
}
pub fn constellation_opacity(
mut materials: ResMut<Assets<StandardMaterial>>,
player_query: Query<(&Player, &Camera, &GlobalTransform)>,
constellation_query: Query<(&Handle<StandardMaterial>, &ConstellationModel)>, // Query all constellation lines
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
mut info_label_query: Query<&mut Text, With<InfoLabel>>,
) {
let (_player, camera, global_transform) = player_query.single();
let window = window_query.single();
let Some(cursor_position) = window.cursor_position() else {
return;
};
let Some(mouse_ray) = camera.viewport_to_world(&global_transform, cursor_position) else {
return;
};
let cursor_global_pos = mouse_ray.get_point(1.0);
let mut closest_const_name: String = "".into();
let mut closest_const_pos: Vec3 = Vec3::ZERO;
for (material_handle, constellation_model) in constellation_query.iter() {
let Some(material) = materials.get_mut(material_handle) else {
continue;
};
let distance = constellation_model.center.distance(cursor_global_pos);
let exponent = -(2.0 * distance / CONS_VIEW_RADIUS).powi(2);
let opa = E.powf(exponent);
material.base_color = Color::srgba(opa, opa, opa, opa); // Set the alpha channel to adjust transparency
if distance < closest_const_pos.distance(cursor_global_pos) {
closest_const_name = constellation_model.name.clone();
closest_const_pos = constellation_model.center;
}
}
let Ok(mut info_label) = info_label_query.get_single_mut() else {
return;
};
info_label.sections[0].value = closest_const_name;
}

View file

@ -1,5 +1,4 @@
use bevy::prelude::*; use bevy::prelude::*;
use std::f64::consts::PI;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use rand::RngCore; use rand::RngCore;
@ -8,9 +7,7 @@ use crate::GameState;
use crate::MainGame; use crate::MainGame;
use crate::Sky; use crate::Sky;
use crate::Constellation; use crate::Constellation;
use crate::ConstellationLine; use crate::ConstellationModel;
use crate::PlayerState;
use crate::GameData;
use crate::celestial_to_cartesian; use crate::celestial_to_cartesian;
use crate::spawn_cons_lines; use crate::spawn_cons_lines;
@ -31,6 +28,37 @@ pub struct ScoreLabel;
#[derive(Component)] #[derive(Component)]
pub struct HintLabel; pub struct HintLabel;
#[derive(Resource)]
pub struct GameData {
content: Vec<String>,
pub score: usize,
health: usize,
state: PlayerState,
target_cons_name: Option<String>,
target_cons_focused: bool,
}
impl Default for GameData {
fn default() -> Self {
GameData {
content: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
target_cons_focused: false,
}
}
}
#[derive(Default, PartialEq, Debug)]
enum PlayerState {
#[default]
Playing,
Hinted,
Answered,
}
pub fn setup( pub fn setup(
mut commands: Commands, mut commands: Commands,
mut game_data: ResMut<GameData>, mut game_data: ResMut<GameData>,
@ -172,106 +200,81 @@ pub fn setup(
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<&mut Player>,
mut game_data: ResMut<GameData>, mut game_data: ResMut<GameData>,
sky: Res<Sky>, sky: Res<Sky>,
text_query: Query<&mut Text, With<AnswerButton>>, text_query: Query<&mut Text, With<AnswerButton>>,
button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
constellation_line_query : Query<(Entity, &ConstellationLine)>, constellation_line_query : Query<(Entity, &ConstellationModel)>,
commands: Commands, mut game_state: ResMut<NextState<GameState>>,
game_state: ResMut<NextState<GameState>>, mut commands: Commands,
meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
) { ) {
let Ok((mut player, mut transform)) = player_query.get_single_mut() else { let Ok(mut player) = player_query.get_single_mut() else {
return return
}; };
if player.l_drag_pos.is_some() || player.r_drag_pos.is_some() {
game_data.target_cons_focused = false;
}
if keys.just_pressed(KeyCode::Space) || game_data.target_cons_name.is_none() { if keys.just_pressed(KeyCode::Space) || game_data.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state, game_data); choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state, game_data);
return return
} }
let mut rotation = Quat::IDENTITY; if keys.just_pressed(KeyCode::Escape) {
game_state.set(GameState::Start);
}
if keys.pressed(KeyCode::KeyA) { if keys.pressed(KeyCode::KeyI) {
rotation *= Quat::from_rotation_y((PI / 60.0) as f32); if game_data.state != PlayerState::Playing {
} info!("Invalid state : {:?}", game_data.state);
}
if keys.pressed(KeyCode::KeyD) { let Some(target_cons) = game_data.target_cons_name.clone() else {
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); return;
} };
game_data.state = PlayerState::Hinted;
if keys.pressed(KeyCode::KeyI) && game_data.state == PlayerState::Playing { spawn_cons_lines(&mut commands, &mut meshes, &mut materials, sky.get_constellation(&target_cons));
if let Some(target_cons) = game_data.target_cons_name.clone() { return;
game_data.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return
}
} }
if rotation != Quat::IDENTITY {
transform.rotation *= rotation;
player.target_rotation = None;
}
if keys.pressed(KeyCode::KeyR) {
if let Some(target_constellation_name) = game_data.target_cons_name.clone() {
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
player.target_rotation = Some(constellation_center(target_constellation));
}
}
if keys.pressed(KeyCode::KeyW) { if keys.pressed(KeyCode::KeyW) {
let target_constellation_name: String = "Ursa Minor".into(); game_data.target_cons_focused = true;
let Some(target_constellation_name) = game_data.target_cons_name.clone() else {
return;
};
let mut target_constellation = sky.content[0].clone(); let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() { for constellation in sky.content.clone() {
if constellation.name == target_constellation_name { if constellation.name == target_constellation_name {
target_constellation = constellation target_constellation = constellation
} }
} }
player.target_rotation = Some(constellation_center(target_constellation)); player.target_rotation = Some(constellation_center(target_constellation));
}
if let Some(target_rotation) = player.target_rotation {
let current_rotation = transform.rotation;
transform.rotation = current_rotation.slerp(target_rotation, 0.1);
if transform.rotation.angle_between(target_rotation) < 0.01 {
player.target_rotation = None;
}
} }
} }
pub fn ui_labels( pub fn ui_labels(
mut param_set: ParamSet<( mut label_query: Query<(&mut Text, Option<&HealthLabel>, Option<&ScoreLabel>, Option<&HintLabel>)>,
Query<&mut Text, With<HealthLabel>>,
Query<&mut Text, With<ScoreLabel>>,
Query<&mut Text, With<HintLabel>>,
)>,
game_data: Res<GameData> game_data: Res<GameData>
) { ) {
if let Ok(mut health_text) = param_set.p0().get_single_mut() {
health_text.sections[0].value = "# ".repeat(game_data.health);
}
if let Ok(mut score_text) = param_set.p1().get_single_mut() { for (mut text, health_label, score_label, hint_label) in label_query.iter_mut() {
score_text.sections[0].value = format!("{}", game_data.score); if health_label.is_some() {
} text.sections[0].value = "# ".repeat(game_data.health);
} else if score_label.is_some() {
if let Ok(mut hint_text) = param_set.p2().get_single_mut() { text.sections[0].value = format!("{}", game_data.score);
if game_data.state == PlayerState::Answered { } else if hint_label.is_some() {
hint_text.sections[0].value = "press space to continue".into(); if !game_data.target_cons_focused {
} else { text.sections[0].value = "press z to re-center".into();
hint_text.sections[0].value = "press i to get an hint".into(); } else if game_data.state == PlayerState::Playing {
text.sections[0].value = "press i to get an hint".into();
} else if game_data.state == PlayerState::Answered {
text.sections[0].value = "press space to continue".into();
} else {
text.sections[0].value = "guess the constellation".into();
}
} }
} }
} }
@ -289,9 +292,9 @@ pub fn ui_buttons(
>, >,
mut text_query: Query<&mut Text, With<AnswerButton>>, mut text_query: Query<&mut Text, With<AnswerButton>>,
mut game_data: ResMut<GameData>, mut game_data: ResMut<GameData>,
commands: Commands, mut commands: Commands,
meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
sky: Res<Sky> sky: Res<Sky>
) { ) {
if game_data.state == PlayerState::Answered { if game_data.state == PlayerState::Answered {
@ -322,7 +325,7 @@ pub fn ui_buttons(
}; };
if game_data.state == PlayerState::Playing { if game_data.state == PlayerState::Playing {
spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone()); spawn_cons_lines(&mut commands, &mut meshes, &mut materials, sky.get_constellation(&target_cons));
} }
if target_cons == selected_cons { if target_cons == selected_cons {
@ -368,7 +371,7 @@ fn choose_constellation(
sky: Res<Sky>, sky: Res<Sky>,
mut text_query: Query<&mut Text, With<AnswerButton>>, mut text_query: Query<&mut Text, With<AnswerButton>>,
mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
constellation_line_query : Query<(Entity, &ConstellationLine)>, constellation_line_query : Query<(Entity, &ConstellationModel)>,
mut commands: Commands, mut commands: Commands,
mut game_state: ResMut<NextState<GameState>>, mut game_state: ResMut<NextState<GameState>>,
mut game_data: ResMut<GameData>, mut game_data: ResMut<GameData>,
@ -408,6 +411,7 @@ fn choose_constellation(
} }
game_data.state = PlayerState::Playing; game_data.state = PlayerState::Playing;
game_data.target_cons_focused = true;
} }
fn constellation_center(target_constellation: Constellation) -> Quat { fn constellation_center(target_constellation: Constellation) -> Quat {

View file

@ -10,6 +10,8 @@ mod start_state;
mod game_state; mod game_state;
mod explo_state; mod explo_state;
use game_state::GameData;
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15); const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15);
const RIGHT_BUTTON: Color = Color::srgb(0.15, 0.50, 0.15); const RIGHT_BUTTON: Color = Color::srgb(0.15, 0.50, 0.15);
@ -18,6 +20,9 @@ const EASYNESS: f32 = 1.5;
const MAX_STAR_SIZE: f32 = 0.63; const MAX_STAR_SIZE: f32 = 0.63;
const STAR_SCALE: f32 = 0.02; const STAR_SCALE: f32 = 0.02;
const SKY_RADIUS: f32 = 4.0; const SKY_RADIUS: f32 = 4.0;
const CONS_VIEW_RADIUS: f32 = 0.8;
const MOVE_SPEED: f32 = 12.0;
const ROT_SPEED: f32 = 9.0;
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
struct StarData { struct StarData {
@ -52,16 +57,16 @@ impl Sky {
for cons in self.content.clone() { for cons in self.content.clone() {
cons_names.push(cons.name.clone()); cons_names.push(cons.name.clone());
} }
return cons_names; cons_names
} }
fn get_constellation(&self, name: &str) -> Constellation { fn get_constellation(&self, name: &str) -> Constellation {
for cons in self.content.clone() { for cons in self.content.clone() {
if &cons.name == name { if cons.name == name {
return cons; return cons;
} }
} }
return self.content[0].clone(); self.content[0].clone()
} }
} }
@ -92,7 +97,10 @@ struct StarPos {
struct Star; struct Star;
#[derive(Component)] #[derive(Component)]
struct ConstellationLine; struct ConstellationModel {
name: String,
center: Vec3,
}
#[derive(Component)] #[derive(Component)]
struct StartMenu; struct StartMenu;
@ -106,42 +114,15 @@ struct GameOver;
#[derive(Component, Default)] #[derive(Component, Default)]
struct Player { struct Player {
target_rotation: Option<Quat>, target_rotation: Option<Quat>,
dragging_pos: Option<Vec2>, r_drag_pos: Option<Vec2>,
} l_drag_pos: Option<Vec2>,
#[derive(Resource)]
struct GameData {
content: Vec<String>,
score: usize,
health: usize,
state: PlayerState,
target_cons_name: Option<String>,
}
impl Default for GameData {
fn default() -> Self {
GameData {
content: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
}
}
}
#[derive(Default, PartialEq)]
enum PlayerState {
#[default]
Playing,
Hinted,
Answered,
} }
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)] #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
enum GameState { enum GameState {
#[default] #[default]
Start, Start,
Explo,
Game, Game,
End, End,
} }
@ -160,44 +141,51 @@ fn main() {
.add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>) .add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>)
.add_systems(OnEnter(GameState::Game), game_state::setup) .add_systems(OnEnter(GameState::Game), game_state::setup)
.add_systems(Update, game_state::player_interact.run_if(in_state(GameState::Game))) .add_systems(Update, game_state::player_interact.run_if(in_state(GameState::Game)))
.add_systems(Update, explo_state::player_mouse_move.run_if(in_state(GameState::Game))) .add_systems(Update, explo_state::player_mouse_move.run_if(in_state(GameState::Game).or_else(in_state(GameState::Explo))))
.add_systems(Update, game_state::ui_buttons.run_if(in_state(GameState::Game))) .add_systems(Update, explo_state::player_mouse_rotate.run_if(in_state(GameState::Game).or_else(in_state(GameState::Explo))))
.add_systems(Update, explo_state::rotate_camera.run_if(in_state(GameState::Game).or_else(in_state(GameState::Explo))))
.add_systems(Update, explo_state::zoom.run_if(in_state(GameState::Game).or_else(in_state(GameState::Explo))))
.add_systems(Update, game_state::ui_buttons.run_if(in_state(GameState::Game)))
.add_systems(Update, game_state::ui_labels.run_if(in_state(GameState::Game))) .add_systems(Update, game_state::ui_labels.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>) .add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>)
.add_systems(OnEnter(GameState::End), end_state::setup) .add_systems(OnEnter(GameState::End), end_state::setup)
.add_systems(Update, end_state::player_interact.run_if(in_state(GameState::End))) .add_systems(Update, end_state::player_interact.run_if(in_state(GameState::End)))
.add_systems(OnExit(GameState::End), despawn_screen::<GameOver>) .add_systems(OnExit(GameState::End), despawn_screen::<GameOver>)
.add_systems(OnEnter(GameState::Explo), explo_state::setup)
.add_systems(Update, explo_state::player_interact.run_if(in_state(GameState::Explo)))
.add_systems(Update, explo_state::constellation_opacity.run_if(in_state(GameState::Explo)))
.add_systems(OnExit(GameState::Explo), despawn_screen::<MainGame>)
.run(); .run();
} }
fn spawn_cons_lines( fn spawn_cons_lines(
mut commands: Commands, commands: &mut Commands,
mut meshes: ResMut<Assets<Mesh>>, meshes: &mut ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, materials: &mut ResMut<Assets<StandardMaterial>>,
sky: Res<Sky>, target_constellation: Constellation,
target_constellation_name: String,
) { ) {
let line_material = materials.add(StandardMaterial { let line_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(0.5, 0.5, 1.0), emissive: LinearRgba::rgb(0.5, 0.5, 1.0),
alpha_mode: AlphaMode::Blend,
..default() ..default()
}); });
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation;
}
}
let mut vertices : Vec<Vec3> = vec![]; let mut vertices : Vec<Vec3> = vec![];
let mut avg_pos : Vec3 = Vec3::ZERO;
let num_lines = target_constellation.lines.len();
for line in target_constellation.lines { for line in target_constellation.lines {
for star_index in line { for star_index in line {
let star = target_constellation.stars[star_index as usize].clone(); let star = target_constellation.stars[star_index as usize].clone();
vertices.push(celestial_to_cartesian(star.rah, star.dec)); let star_pos = celestial_to_cartesian(star.rah, star.dec);
vertices.push(star_pos);
avg_pos += star_pos;
} }
} }
avg_pos /= 2.0 * num_lines as f32;
let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD); let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices); mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
@ -208,7 +196,10 @@ fn spawn_cons_lines(
transform: Transform::default(), transform: Transform::default(),
..default() ..default()
}, },
ConstellationLine, ConstellationModel {
name: target_constellation.name,
center: avg_pos,
},
MainGame MainGame
)); ));
} }
@ -220,7 +211,8 @@ fn star_setup(
) { ) {
commands.insert_resource(ClearColor(Color::BLACK)); commands.insert_resource(ClearColor(Color::BLACK));
let stars = get_stars().unwrap(); let stars: Vec<StarData> = serde_json::from_str(include_str!("../data/stars.json")).expect("no star json provided");
let star_mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap()); let star_mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
@ -260,14 +252,6 @@ fn star_setup(
)); ));
} }
fn get_stars() -> std::io::Result<Vec<StarData>> {
let data = include_str!("../data/stars.json");
let stars: Vec<StarData> = serde_json::from_str(&data).unwrap();
Ok(stars)
}
fn star_position(star_data: StarData) -> Vec3 { fn star_position(star_data: StarData) -> Vec3 {
// Convert declination to decimal degrees // Convert declination to decimal degrees
let text_ra = star_data.ra; let text_ra = star_data.ra;
@ -303,15 +287,7 @@ fn celestial_to_cartesian(rah: f64, ded: f64) -> Vec3 {
} }
fn cons_setup(mut sky: ResMut<Sky>) { fn cons_setup(mut sky: ResMut<Sky>) {
sky.content = get_cons().unwrap(); sky.content = serde_json::from_str(include_str!("../data/constellations.json")).expect("no constellation json provided");
}
fn get_cons() -> std::io::Result<Vec<Constellation>> {
let data = include_str!("../data/constellations.json");
let sky_data: Vec<Constellation> = serde_json::from_str(&data).unwrap();
Ok(sky_data)
} }
// Generic system that takes a component as a parameter, and will despawn all entities with that component // Generic system that takes a component as a parameter, and will despawn all entities with that component

View file

@ -19,48 +19,62 @@ pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
pub fn setup( pub fn setup(
mut commands: Commands, mut commands: Commands,
) { ) {
let container_node = NodeBundle { let main_container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), width: Val::Percent(100.0),
height: Val::Percent(100.0), height: Val::Percent(100.0),
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center,
align_items: AlignItems::Center, align_items: AlignItems::Center,
..default() ..default()
}, },
..default() ..default()
}; };
let container = commands.spawn(container_node).id(); let main_container = commands.spawn(main_container_node).id();
let top_text_style = TextStyle { let title_text_style = TextStyle {
font_size: 50.0, font_size: 50.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
..default() ..default()
}; };
let bottom_text_style = TextStyle { let start_text_style = TextStyle {
font_size: 30.0, font_size: 30.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default() ..default()
}; };
let top_text_node = TextBundle::from_section( let explo_text_style = TextStyle {
font_size: 30.0,
color: Color::srgb(0.4,0.4,0.4),
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default()
};
let title_text_node = TextBundle::from_section(
"Astraea", "Astraea",
top_text_style, title_text_style,
); );
let bottom_text_node = TextBundle::from_section( let start_text_node = TextBundle::from_section(
"Press Space to Begin", "Press Space to Begin",
bottom_text_style, start_text_style,
); );
let top_text = commands.spawn((top_text_node, StartMenu)).id(); let explo_text_node = TextBundle::from_section(
let bottom_text = commands.spawn((bottom_text_node, StartMenu)).id(); "Press E to Explore",
explo_text_style,
);
commands.entity(container).push_children(&[top_text, bottom_text]); let title_text = commands.spawn((title_text_node, StartMenu)).id();
let start_text = commands.spawn((start_text_node, StartMenu)).id();
let explo_text = commands.spawn((explo_text_node, StartMenu)).id();
commands.entity(main_container).push_children(&[title_text, start_text, explo_text]);
} }
pub fn player_interact( pub fn player_interact(
@ -69,10 +83,13 @@ pub fn player_interact(
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>,
) { ) {
if keys.just_pressed(KeyCode::Space) { if keys.just_pressed(KeyCode::Space) {
info!("start space");
game_state.set(GameState::Game); game_state.set(GameState::Game);
} }
if keys.just_pressed(KeyCode::KeyE) {
game_state.set(GameState::Explo);
}
if let Ok((_player, mut transform)) = player_query.get_single_mut() { if let Ok((_player, mut transform)) = player_query.get_single_mut() {
let mut rotation = Quat::IDENTITY; let mut rotation = Quat::IDENTITY;
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32); rotation *= Quat::from_rotation_y((PI / 6000.0) as f32);