Skip to content

Commit

Permalink
Document a few modules, functions, etc. And reduce visibilities for i…
Browse files Browse the repository at this point in the history
…mplementation details/modfule-specific details behind a plugin.
  • Loading branch information
varoonp123 committed Mar 7, 2024
1 parent 68d8a51 commit af91a43
Show file tree
Hide file tree
Showing 31 changed files with 235 additions and 186 deletions.
7 changes: 4 additions & 3 deletions src/arena/barrier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ use bevy_rapier2d::prelude::*;
use std::f32::consts::FRAC_PI_2;
use thetawave_interface::{spawnable::EffectType, states::GameCleanup};

/// Tag component for arena barriers
/// Tag component for arena barriers. During the main game, there should be exactly 4 entities with
/// this component, one for each side of a rectangle.
#[derive(Component)]
pub struct ArenaBarrierComponent;

/// Spawns arena barriers
pub fn spawn_barriers_system(
/// Spawns arena barriers arranged in a centered rectangle
pub(super) fn spawn_barriers_system(
mut commands: Commands,
mut spawn_effect: EventWriter<SpawnEffectEvent>,
game_parameters: Res<GameParametersResource>,
Expand Down
61 changes: 27 additions & 34 deletions src/arena/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use bevy::prelude::*;
use bevy_rapier2d::{prelude::*, rapier::prelude::CollisionEventFlags};
use thetawave_interface::{objective::MobReachedBottomGateEvent, states::GameCleanup};

/// Despawn gate tag
/// Tag for the gate that triggers mobs to respawn (and cause something bad to happen to the
/// player). There will generally only be 1 entity with this component.
#[derive(Component)]
pub struct DespawnGateComponent;
pub(super) struct DespawnGateComponent;

/// Spawn gates for despawning entities
pub fn spawn_despawn_gates_system(mut commands: Commands) {
pub(super) fn spawn_despawn_gates_system(mut commands: Commands) {
spawn_despawn_gate(&mut commands, Vec2::new(0.0, -500.0), 1000.0, 50.0);
}

Expand All @@ -28,7 +29,7 @@ fn spawn_despawn_gate(commands: &mut Commands, position: Vec2, width: f32, heigh

/// Despawn spawnables when they intersect with despawn gates
#[allow(clippy::too_many_arguments)]
pub fn despawn_gates_system(
pub(super) fn despawn_gates_system(
mut commands: Commands,
mut collision_events: EventReader<CollisionEvent>,
despawn_gate_query: Query<Entity, With<DespawnGateComponent>>,
Expand Down Expand Up @@ -57,44 +58,36 @@ pub fn despawn_gates_system(
};

// verify the other entity is a spawnable
if spawnable_query
.iter()
.any(|spawnable_entity| spawnable_entity == *other_entity)
{
if spawnable_query.contains(*other_entity) {
// despawn the spawnable entity
commands.entity(*other_entity).despawn_recursive();

// check if the other entity is a mob
for (mob_entity, mob_component) in mob_query.iter() {
if mob_entity == *other_entity {
// send event for mob reaching bottom of arena
if let Some(defense_interaction) =
mob_component.defense_interaction.clone()
{
enemy_bottom_event.send(MobReachedBottomGateEvent {
mob_type: Some(mob_component.mob_type.clone()),
mob_segment_type: None,
defense_interaction,
});
}
if let Ok((_, mob_component)) = mob_query.get(*other_entity) {
// send event for mob reaching bottom of arena
if let Some(defense_interaction) = mob_component.defense_interaction.clone()
{
enemy_bottom_event.send(MobReachedBottomGateEvent {
mob_type: Some(mob_component.mob_type.clone()),
mob_segment_type: None,
defense_interaction,
});
}
}

// check if the other entity is a mob segment
for (mob_segment_entity, mob_segment_component) in mob_segment_query.iter() {
if mob_segment_entity == *other_entity {
// send event for mob segment reaching bottom of arena
if let Some(defense_interaction) =
mob_segment_component.defense_interaction.clone()
{
enemy_bottom_event.send(MobReachedBottomGateEvent {
mob_type: None,
mob_segment_type: Some(
mob_segment_component.mob_segment_type.clone(),
),
defense_interaction,
});
}
if let Ok((_, mob_segment_component)) = mob_segment_query.get(*other_entity) {
// send event for mob segment reaching bottom of arena
if let Some(defense_interaction) =
mob_segment_component.defense_interaction.clone()
{
enemy_bottom_event.send(MobReachedBottomGateEvent {
mob_type: None,
mob_segment_type: Some(
mob_segment_component.mob_segment_type.clone(),
),
defense_interaction,
});
}
}
}
Expand Down
10 changes: 7 additions & 3 deletions src/arena/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! `thetawave` arena module
//! Exposes a plugin that renders a rectangular boundary that the player cannot cross, but mobs
//! can. Also handles sending events when mobs reach the botton of the screen.
use bevy::prelude::*;
use thetawave_interface::{objective::MobReachedBottomGateEvent, states};
Expand All @@ -7,9 +8,12 @@ mod gate;

use crate::GameEnterSet;

pub use self::{barrier::*, gate::*};
pub use self::barrier::*;
use self::gate::{despawn_gates_system, spawn_despawn_gates_system};

pub struct ArenaPlugin;
/// Plugin that spawns a rectangular boundary for the main game play area and fires off
/// `MobReachedBottomGateEvent` at the right times
pub(super) struct ArenaPlugin;

impl Plugin for ArenaPlugin {
fn build(&self, app: &mut App) {
Expand Down
4 changes: 2 additions & 2 deletions src/assets/effect.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use bevy::prelude::*;
use bevy_asset_loader::prelude::*;
use bevy::prelude::{Handle, Image, Resource, TextureAtlasLayout};
use bevy_asset_loader::prelude::AssetCollection;

use thetawave_interface::spawnable::EffectType;

Expand Down
2 changes: 2 additions & 0 deletions src/assets/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Exposes `AssetCollection`s with handles to files in the `assets/` directory at the base of the
//! repo. These are typically all loaded into memory when the game launches.
mod audio;
mod consumable;
mod effect;
Expand Down
11 changes: 8 additions & 3 deletions src/audio/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Exposes a plugin that starts, stops, and modulates in-game audio when events are emitted
use bevy::prelude::{
in_state, not, App, EventReader, IntoSystemConfigs, Plugin, Res, Resource, Startup, Update,
};
Expand All @@ -9,7 +10,10 @@ use thetawave_interface::{

use crate::assets::GameAudioAssets;

pub struct ThetawaveAudioPlugin;
/// Starts, stops, and modulates in-game audio when we receive a
/// `thetawave_interface::audio::PlaySoundEffectEvent` or
/// `thetawave_interface::audio::ChangeBackgroundMusicEvent`.
pub(super) struct ThetawaveAudioPlugin;

impl Plugin for ThetawaveAudioPlugin {
fn build(&self, app: &mut App) {
Expand Down Expand Up @@ -38,8 +42,8 @@ pub struct MenuAudioChannel;
#[derive(Resource)]
pub struct SoundEffectsAudioChannel;

/// Sets the volume of the audio channels
pub fn set_audio_volume_system(
/// Sets the volume of the audio channels to "sane defaults"
fn set_audio_volume_system(
background_audio_channel: Res<AudioChannel<BackgroundMusicAudioChannel>>,
menu_audio_channel: Res<AudioChannel<MenuAudioChannel>>,
effects_audio_channel: Res<AudioChannel<SoundEffectsAudioChannel>>,
Expand All @@ -49,6 +53,7 @@ pub fn set_audio_volume_system(
effects_audio_channel.set_volume(0.80);
}

/// Play sound effects when we receive events. This should be called every frame for snappy audio.
fn play_sound_effect_system(
mut play_sound_event_reader: EventReader<PlaySoundEffectEvent>,
audio_channel: Res<AudioChannel<SoundEffectsAudioChannel>>,
Expand Down
22 changes: 12 additions & 10 deletions src/background/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! `thetawave` background module
//! Exposes a plugin that creates and animates an engine-assisted background that activates a
//! user's monkey brain with colors and lights.
use bevy::{
app::{App, Plugin, Update},
asset::{AssetServer, Assets, Handle},
Expand Down Expand Up @@ -44,7 +44,9 @@ use thiserror::Error;

use crate::GameEnterSet;

pub struct BackgroundPlugin;
/// Contains systems to spawn and animate the background of a rotating planet + star at the right
/// `thetawave_interface::states::AppStates`.
pub(super) struct BackgroundPlugin;

impl Plugin for BackgroundPlugin {
fn build(&self, app: &mut App) {
Expand Down Expand Up @@ -80,7 +82,7 @@ impl Plugin for BackgroundPlugin {

/// Parameters for procedurally generated 3D level backgrounds
#[derive(Resource, Deserialize)]
pub struct BackgroundsResource {
struct BackgroundsResource {
/// Intensity increase rate for star explosion effect
pub star_explode_intensity: f32,
/// Position of the quad with the background image
Expand Down Expand Up @@ -117,31 +119,31 @@ pub struct BackgroundsResource {

/// Resource to track if star explosion is happening
#[derive(Resource, Default)]
pub struct StarExplodeResource {
struct StarExplodeResource {
pub started: bool,
}

/// Component to manage movement of planets
#[derive(Reflect, Default, Component)]
#[reflect(Component)]
pub struct PlanetComponent {
struct PlanetComponent {
/// Speed of rotation about the z axis
pub rotation_speed: f32,
}

/// Component to tag star point light
#[derive(Component)]
pub struct StarLightComponent;
struct StarLightComponent;

/// Rotate planets about their z axis
pub fn rotate_planet_system(mut query: Query<(&mut Transform, &PlanetComponent)>, time: Res<Time>) {
fn rotate_planet_system(mut query: Query<(&mut Transform, &PlanetComponent)>, time: Res<Time>) {
for (mut transform, planet) in query.iter_mut() {
transform.rotation *= Quat::from_rotation_y(planet.rotation_speed * time.delta_seconds());
}
}

/// Execute the exploding star effect if the game is lost through defense being destroyed
pub fn on_defeat_star_explode_system(
fn on_defeat_star_explode_system(
mut run_end_event_reader: EventReader<RunEndEvent>,
mut point_light_query: Query<&mut PointLight, With<StarLightComponent>>,
mut star_explode_res: ResMut<StarExplodeResource>,
Expand Down Expand Up @@ -192,7 +194,7 @@ fn get_random_asset_file(path: String) -> Result<String, OurGetRandomAssetError>
}

/// Create a procedurally generated 3D background for a level
pub fn create_background_system(
fn create_background_system(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
Expand Down
7 changes: 6 additions & 1 deletion src/camera/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Exposes a plugin that sets up the 2D/3D perspective/camera and shakes the camera when an event
//! is emitted.
use crate::game;
use bevy::app::{App, Plugin, Startup, Update};
use bevy::core_pipeline::bloom::BloomPrefilterSettings;
Expand All @@ -15,8 +17,11 @@ use thetawave_interface::camera::ScreenShakeEvent;

mod screen_shake;

pub struct CameraPlugin;
pub(super) struct CameraPlugin;

/// Sets up a 2d perspective/camera of the 3d world. When this plugin is enabled, one can send
/// `thetawave_interface::camera::ScreenShakeEvent` to jolt the screen, for example, when a player
/// takes damage.
impl Plugin for CameraPlugin {
fn build(&self, app: &mut App) {
app.add_event::<ScreenShakeEvent>();
Expand Down
2 changes: 1 addition & 1 deletion src/loot/consumable.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::prelude::*;
use bevy::prelude::{EventWriter, Vec2};
use rand::Rng;
use serde::Deserialize;
use strum_macros::Display;
Expand Down
7 changes: 4 additions & 3 deletions src/loot/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use bevy::prelude::*;
//! Exposes resources with methods to compute loot drops from killed mobs.
use bevy::prelude::{App, EventWriter, Plugin, Resource, Vec2};
use ron::de::from_bytes;
use serde::Deserialize;
use std::collections::HashMap;
Expand All @@ -10,7 +11,7 @@ use crate::spawnable::SpawnConsumableEvent;

pub use self::consumable::*;

pub struct LootPlugin;
pub(super) struct LootPlugin;

impl Plugin for LootPlugin {
fn build(&self, app: &mut App) {
Expand All @@ -35,7 +36,7 @@ pub enum LootDrop {
}

impl LootDropsResource {
/// Roll for consumables from drop list
/// Roll for consumables from drop list and emit events when those rolls succeed.
pub fn spawn_loot_drops(
&self,
drop_list_type: &DropListType,
Expand Down
20 changes: 11 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
#![doc = include_str!("../README.md")]
use bevy::app::PluginGroupBuilder;
use bevy::prelude::{
AmbientLight, App, AssetPlugin, ClearColor, Color, DefaultPlugins, ImagePlugin,
IntoSystemConfigs, OnEnter, PluginGroup, ResMut, SystemSet, Vec2, Window, WindowPlugin,
};
use bevy_kira_audio::prelude::AudioPlugin;

use crate::options::display::DisplayConfig;
use bevy_rapier2d::prelude::{
NoUserData, RapierConfiguration, RapierDebugRenderPlugin, RapierPhysicsPlugin, TimestepMode,
};
use options::{generate_config_files, GameInitCLIOptions};
use thetawave_interface::states::{AppStates, GameStates};

pub const PHYSICS_SCALE: f32 = 10.0;
/// Used by a physics engine to translate physics calculations to graphics
const PHYSICS_PIXELS_PER_METER: f32 = 10.0;

mod animation;
mod arena;
Expand Down Expand Up @@ -60,29 +63,28 @@ pub enum GameUpdateSet {
}

#[cfg(not(target_arch = "wasm32"))]
fn get_display_config() -> options::DisplayConfig {
fn get_display_config() -> DisplayConfig {
use ron::de::from_str;
use std::{env::current_dir, fs::read_to_string};

let config_path = current_dir().unwrap().join("config");

from_str::<options::DisplayConfig>(&read_to_string(config_path.join("display.ron")).unwrap())
.unwrap()
from_str::<DisplayConfig>(&read_to_string(config_path.join("display.ron")).unwrap()).unwrap()
}

#[cfg(target_arch = "wasm32")]
fn get_display_config() -> options::DisplayConfig {
use options::DisplayConfig;

fn get_display_config() -> DisplayConfig {
DisplayConfig {
width: 1280.0,
height: 1024.0,
fullscreen: false,
}
}

/// The plugins we need that are "taken for granted" from the engine and basic rendering systems.
/// Using a different `PluginGroupBuilder` is basically a different runtime for the game.
fn our_default_plugins(
display_config: options::DisplayConfig,
display_config: DisplayConfig,
opts: &options::GameInitCLIOptions,
) -> PluginGroupBuilder {
let res = DefaultPlugins
Expand Down Expand Up @@ -194,7 +196,7 @@ impl PluginGroup for ThetawaveGamePlugins {
.add(misc::HealthPlugin)
.add(weapon::WeaponPlugin)
.add(
RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(PHYSICS_SCALE)
RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(PHYSICS_PIXELS_PER_METER)
.in_fixed_schedule(),
)
.add(ui::UiPlugin)
Expand Down
Loading

0 comments on commit af91a43

Please sign in to comment.