DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 7d5486e5144305656353cbfcdfd8a177c99cb88b deck-builder/client/src/main.rs -rw-r--r-- 7.1 KiB
7d5486e5Jonni Liljamo feat(client): advanced roll action, log configs 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
 * This file is part of laurelin_client
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

#![allow(clippy::too_many_arguments)]
#![allow(clippy::derivable_impls)]
#![allow(clippy::type_complexity)]

use api::user::User;
use bevy::{
    input::mouse::{MouseScrollUnit, MouseWheel},
    prelude::*,
};
use bevy_assets_bundler::*;
use bevy_editor_pls::EditorPlugin;
use bevy_egui::EguiPlugin;
use bevy_mod_picking::prelude::*;
use bevy_rapier3d::prelude::*;
use bevy_text_mesh::prelude::*;

mod api;
mod macros;
mod util;

mod plugins;

mod game_status;
use game_status::Card;

#[macro_export]
macro_rules! seed_gen {
    () => {
        fastrand::u64(u64::MIN..=u64::MAX)
    };
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, States)]
enum AppState {
    #[default]
    Menu,
    InGame,
}

fn main() {
    let key = [
        25, 221, 123, 82, 182, 95, 251, 128, 83, 192, 172, 139, 92, 102, 34, 248,
    ];
    let mut asset_bundling_options = AssetBundlingOptions::default();
    asset_bundling_options.set_encryption_key(key);
    asset_bundling_options.encode_file_names = true;
    asset_bundling_options.enabled_on_debug_build = true;

    let mut app = App::new();
    app.add_plugins(
        DefaultPlugins
            .set(WindowPlugin {
                primary_window: Some(Window {
                    title: String::from("Laurelin Client"),
                    ..Default::default()
                }),
                ..Default::default()
            })
            .build()
            .add_before::<AssetPlugin, _>(BundledAssetIoPlugin::from(asset_bundling_options)),
    );

    app.add_plugin(RapierPhysicsPlugin::<NoUserData>::default());
    app.add_plugin(TextMeshPlugin);

    app.add_plugins(DefaultPickingPlugins);

    app.insert_resource(AmbientLight {
        color: Color::ANTIQUE_WHITE,
        brightness: 0.4,
    });

    info!("laurelin client initializing");

    // dev
    app.add_plugin(RapierDebugRenderPlugin::default());
    app.add_plugin(EditorPlugin::new());
    app.insert_resource(editor_controls());

    // the egui plugin is also added by the editor plugin
    if !app.is_plugin_added::<EguiPlugin>() {
        app.add_plugin(EguiPlugin);
    }

    // clear color
    app.insert_resource(ClearColor(Color::rgb(0.53, 0.53, 0.7)));

    // yaml assets
    app.add_asset::<util::YamlAsset>()
        .init_asset_loader::<util::YamlLoader>();

    // add the top level app state
    app.add_state::<AppState>();

    // holds networking options and a request agent
    app.register_type::<NetworkingOptions>()
        .init_resource::<NetworkingOptions>();

    app.register_type::<Global>()
        .register_type::<User>()
        .init_resource::<Global>();

    // has handlers for all async tasks
    app.add_plugin(plugins::AsyncTasksPlugin);

    app.add_plugin(plugins::MenuPlugin);
    app.add_plugin(plugins::GamePlugin);

    app.add_event::<LoadCardManifestEvent>()
        .add_system(load_card_manifest.run_if(on_event::<LoadCardManifestEvent>()));
    app.add_startup_system(setup).add_system(move_camera);
    app.run();

    info!("goodbye");
}

#[derive(Component)]
struct PlayerCamera;

fn setup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut lcm_ev_w: EventWriter<LoadCardManifestEvent>,
) {
    commands.insert_resource(CardManifestHandle {
        handle: asset_server.load("card_manifest.yaml"),
    });
    lcm_ev_w.send(LoadCardManifestEvent);

    commands
        .spawn((
            Camera3dBundle {
                transform: Transform {
                    translation: Vec3::new(0., 5.5, 5.8),
                    rotation: Quat::from_rotation_x(-1.2),
                    ..Default::default()
                },
                ..Default::default()
            },
            RapierPickCamera::default(),
        ))
        .insert(PlayerCamera);
}

struct LoadCardManifestEvent;

fn load_card_manifest(
    mut commands: Commands,
    yaml_assets: Res<Assets<util::YamlAsset>>,
    card_manifest_handle: Res<CardManifestHandle>,
) {
    let card_manifest_yaml: String = yaml_assets
        .get(&card_manifest_handle.handle)
        .unwrap()
        .0
        .clone();
    let card_manifest: CardManifest = serde_yaml::from_str(&card_manifest_yaml).unwrap();
    commands.insert_resource(card_manifest);
}

fn move_camera(
    time: Res<Time>,
    input: Res<Input<KeyCode>>,
    mut mouse_wheel_ev_r: EventReader<MouseWheel>,
    mut camera_query: Query<(&PlayerCamera, &mut Transform)>,
) {
    for (_camera, mut transform) in &mut camera_query {
        let mut direction = Vec3::ZERO;

        let y_modifier = 3.;
        for ev in mouse_wheel_ev_r.iter() {
            match ev.unit {
                MouseScrollUnit::Line => {
                    direction.y -= 20.0 * ev.y.signum() * y_modifier * time.delta_seconds()
                }
                MouseScrollUnit::Pixel => direction.y -= ev.y * y_modifier * time.delta_seconds(),
            }
        }

        if input.pressed(KeyCode::A) {
            direction.x -= 1.;
        }
        if input.pressed(KeyCode::D) {
            direction.x += 1.;
        }
        if input.pressed(KeyCode::W) {
            direction.z -= 1.;
        }
        if input.pressed(KeyCode::S) {
            direction.z += 1.;
        }

        let cam_speed = 4.;
        transform.translation += direction * cam_speed * time.delta_seconds();
    }
}

fn editor_controls() -> bevy_editor_pls::controls::EditorControls {
    use bevy_editor_pls::controls;

    let mut editor_controls = controls::EditorControls::default_bindings();
    editor_controls.unbind(controls::Action::PlayPauseEditor);

    editor_controls.insert(
        controls::Action::PlayPauseEditor,
        controls::Binding {
            input: controls::UserInput::Single(controls::Button::Keyboard(KeyCode::Escape)),
            conditions: vec![controls::BindingCondition::ListeningForText(false)],
        },
    );

    editor_controls
}

#[derive(Clone, Resource, Reflect)]
#[reflect(Resource)]
pub struct NetworkingOptions {
    /// api address with no trailing slash
    api_address: String,
    /// reqwest agent
    /// NOTE: mainly for the future, because it can hold cookies
    #[reflect(ignore)]
    req: reqwest::blocking::Client,
    /// feels wrong storing this here but "it's temporary"
    user_token: String,
}

impl Default for NetworkingOptions {
    fn default() -> Self {
        Self {
            api_address: "http://localhost:3000/api".to_string(),
            req: reqwest::blocking::Client::new(),
            user_token: "".to_string(),
        }
    }
}

#[derive(Resource, serde::Deserialize)]
pub struct CardManifest {
    pub version: String,
    pub cards: Vec<Card>,
}

#[derive(Resource)]
pub struct CardManifestHandle {
    pub handle: Handle<util::YamlAsset>,
}

#[derive(Resource, Reflect)]
#[reflect(Resource)]
pub struct Global {
    /// details of the logged in user
    user: Option<User>,
    /// current game id, set from browse
    cur_game_id: String,
}

impl Default for Global {
    fn default() -> Self {
        Self {
            user: None,
            cur_game_id: "".to_string(),
        }
    }
}