~starkingdoms/starkingdoms

ref: f6a4a4cbf42b10fc967ec425dd01205622442e8f starkingdoms/crates/unified/src/client/crafting/ui.rs -rw-r--r-- 13.9 KiB
f6a4a4cbghostly_zsh feat: crafting removes resources from the ship now 19 hours 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use std::collections::HashMap;

use bevy::{input_focus::{AutoFocus, InputFocus}, ui::RelativeCursorPosition};

use crate::{attachment::PartInShip, client::colors, config::recipe::RecipesConfig, ecs::{CanCraft, CraftPartRequest, CraftingUi, Drill, MainCamera, Me, Part, SingleStorage, ToggleDrillEvent}, prelude::*};

pub fn crafting_ui_plugin(app: &mut App) {
    app.init_resource::<RecipeCollection>();
    app.add_systems(Startup, load_recipes);
    app.add_systems(PreUpdate, (initial_create_recipe_list, update_recipe_list));
    app.add_systems(Update, (close_button, drill_button, drill_state_change,
            single_storage_display, recipe_buttons));
}

#[derive(Component)]
struct CloseButton(Entity); // stores corresponding menu entity
#[derive(Component, Clone)]
struct PreviousInteraction(Interaction);
#[derive(Component)]
struct DrillButton(Entity); // stores corresponding part
#[derive(Component)]
struct SingleStorageDisplay(Entity); // stores corresponding part
#[derive(Component)]
struct RecipesHolder(Entity); // stores corresponding part
#[derive(Component)]
struct PendingRecipesHolder(Entity); // stores corresponding part
#[derive(Resource, Default)]
struct RecipeCollection {
    handle: Option<Handle<RecipesConfig>>,
}
// TODO: use recipe inputs for client-side validation?
#[derive(Component, Clone)]
struct RecipeElement(Entity, String, HashMap<String, u32>); // stores corresponding part and recipe's part name and inputs

fn load_recipes(asset_server: Res<AssetServer>, mut recipe_collection: ResMut<RecipeCollection>) {
    recipe_collection.handle = Some(asset_server.load("config/recipes.rc.toml"));
}

pub fn open_crafting_ui(
    ev: On<Pointer<Press>>,
    crafting_parts: Query<(Entity, &Transform, Option<&Drill>, Option<&SingleStorage>), (With<PartInShip>, With<CanCraft>)>,
    hearty: Query<(Entity, &Transform, Option<&Drill>, Option<&SingleStorage>), (With<Me>, With<CanCraft>)>,
    camera: Single<(Entity, &Camera, &GlobalTransform), (With<MainCamera>, Without<PartInShip>)>,
    commands: Commands,
) {
    if matches!(ev.button, PointerButton::Secondary) {
        let (entity, transform, drill, single_storage) = if let Ok(part) = crafting_parts.get(ev.entity) {
            part
        } else if let Ok(part) = hearty.get(ev.entity) {
            part
        } else {
            return
        };
        // we have our crafting entity!
        // now make the ui
        setup_ui(entity, transform, commands, camera, drill, single_storage);
    }
}

fn setup_ui(
    parent_part: Entity,
    parent_transform: &Transform,
    mut commands: Commands,
    camera: Single<(Entity, &Camera, &GlobalTransform), (With<MainCamera>, Without<PartInShip>)>,
    drill: Option<&Drill>,
    single_storage: Option<&SingleStorage>,
) {
    let parent_pos = camera.1.world_to_viewport(camera.2, parent_transform.translation).unwrap();
    let entity = commands.spawn((
        UiTargetCamera(camera.0),
        Node {
            position_type: PositionType::Absolute,
            left: Val::Px(parent_pos.x),
            top: Val::Px(parent_pos.y),
            width: Val::Px(200.0),
            height: Val::Px(100.0),
            display: Display::Flex,
            flex_direction: FlexDirection::Column,
            ..default()
        },
        AutoFocus,
        CraftingUi,
        BackgroundColor(colors::MANTLE),
        RelativeCursorPosition::default(),
    ))
    .with_children(|parent| {
        parent.spawn((
            Node {
                width: Val::Px(25.0),
                height: Val::Px(25.0),
                justify_content: JustifyContent::Center,
                align_content: AlignContent::Center,
                ..Default::default()
            },
            Button,
            BackgroundColor(colors::RED),
            CloseButton(parent.target_entity()),
            PreviousInteraction(Interaction::None),
        ))
        .with_children(|parent| {
            parent.spawn((
                Node {
                    ..Default::default()
                },
                Text::new("x"),
            ));
        });
        // only add the drill button if the part is a drill
        if let Some(drill) = drill {
            parent.spawn((
                Node {
                    width: Val::Px(100.0),
                    height: Val::Px(30.0),
                    ..Default::default()
                },
                Button,
                DrillButton(parent_part),
                BackgroundColor(colors::CRUST),
                PreviousInteraction(Interaction::None),
            ))
            .with_children(|parent| {
                parent.spawn((
                    Node {
                        ..Default::default()
                    },
                    TextLayout::new(Justify::Center, LineBreak::WordBoundary),
                    TextFont {
                        font_size: 10.0,
                        ..Default::default()
                    },
                    Text::new(get_drill_text(drill)),
                ));
            });
        }
        // only add storage if the part has single storage
        if let Some(single_storage) = single_storage {
            parent.spawn((
                Node {
                    ..Default::default()
                },
                TextFont {
                    font_size: 10.0,
                    ..Default::default()
                },
                Text::new(format!("{}: {}", single_storage.resource_name, single_storage.stored)),
                SingleStorageDisplay(parent_part),
            ));
        }
        // assume CanCraft for now (THIS WILL CHANGE)
        parent.spawn((
            Node {
                display: Display::Flex,
                flex_direction: FlexDirection::Column,
                ..Default::default()
            },
            PendingRecipesHolder(parent_part),
        ));
    });
}

fn initial_create_recipe_list(
    mut commands: Commands,
    added_recipes_holders: Query<(Entity, &PendingRecipesHolder)>,
    recipe_collection: ResMut<RecipeCollection>,
    recipes_config: Res<Assets<RecipesConfig>>,
) {
    if let Some(strong_recipes_config) = recipes_config.get(&recipe_collection.handle.clone().unwrap()) {
        for (recipe_holder, pending_recipes_holder) in &added_recipes_holders {
            let mut recipe_holder = commands.get_entity(recipe_holder).unwrap();
            create_recipe_list(pending_recipes_holder.0, &mut recipe_holder, strong_recipes_config);
            recipe_holder
                .insert(RecipesHolder(pending_recipes_holder.0))
                .remove::<PendingRecipesHolder>();
        }
    }
}
fn update_recipe_list(
    mut ev_config: MessageReader<AssetEvent<RecipesConfig>>,
    recipe_collection: ResMut<RecipeCollection>,
    assets: ResMut<Assets<RecipesConfig>>,
    mut commands: Commands,
    recipes_holders: Query<(Entity, &RecipesHolder)>,
) {
    let Some(handle) = recipe_collection.handle.as_ref() else {
        return
    };

    for ev in ev_config.read() {
        if let AssetEvent::Modified { id } = ev {
            if *id == handle.id() {
                debug!("recipe list config modified - reloading lists");
                let strong_recipes_config = assets.get(*id).unwrap();
                for (recipe_holder_entity, recipes_holder) in &recipes_holders {
                    let mut recipe_holder = commands.get_entity(recipe_holder_entity).unwrap();
                    recipe_holder.despawn_children();
                    create_recipe_list(recipes_holder.0, &mut recipe_holder, strong_recipes_config);
                }
            }
        }
    }
}
fn create_recipe_list(
    parent_entity: Entity,
    recipe_holder: &mut EntityCommands,
    strong_recipes_config: &RecipesConfig,
) {
    let mut ui_recipes = Vec::new();
    for (module_name, recipes) in &strong_recipes_config.recipes {
        for recipe in recipes {
            let resource_list = recipe.inputs.iter()
                .map(|(resource_name, quantity)| format!("{} {}", quantity, resource_name))
                .collect::<Vec<_>>().join(", ");
            ui_recipes.push((
                recipe.order,
                (Node {
                    width: Val::Auto,
                    ..Default::default()
                },
                RecipeElement(parent_entity, module_name.clone(), recipe.inputs.clone()),
                BackgroundColor(colors::MANTLE),
                PreviousInteraction(Interaction::None),
                Button),
                (Node {
                    ..Default::default()
                },
                TextFont {
                    font_size: 10.0,
                    ..Default::default()
                },
                Text::new(format!("{}: {}", module_name, resource_list))),
            ));
        }
    }
    // ordering stuff
    ui_recipes.sort_by(|a, b| a.0.cmp(&b.0));
    recipe_holder.with_children(move |parent| {
        for recipe in ui_recipes {
            parent.spawn(recipe.1.clone())
                .with_child(recipe.2);
        }
    });
}
fn recipe_buttons(
    mut interaction_query: Query<(&Interaction, &mut PreviousInteraction, &mut BackgroundColor, &RecipeElement),
        Changed<Interaction>>,
    mut crafting_message_writer: MessageWriter<CraftPartRequest>,
) {
    for (interaction, mut previous_interaction, mut color, recipe) in &mut interaction_query {
        match *interaction {
            Interaction::Pressed => {
                *color = colors::SURFACE_1.into();
            }
            Interaction::Hovered => {
                *color = colors::SURFACE_0.into();
                if previous_interaction.0 == Interaction::Pressed {
                    // released
                    crafting_message_writer.write(CraftPartRequest {
                        crafting_part: recipe.0,
                        crafted_part: recipe.1.clone(),
                        inputs: recipe.2.clone(),
                    });
                }
            }
            Interaction::None => {
                *color = colors::MANTLE.into();
            }
        }
        previous_interaction.0 = *interaction;
    }
}

fn drill_button(
    mut interaction_query: Query<
        (
            &Interaction,
            &mut PreviousInteraction,
            &mut BackgroundColor,
            &DrillButton,
            &mut Button,
            &Children,
        ),
        Changed<Interaction>,
    >,
    mut toggle_drill_writer: MessageWriter<ToggleDrillEvent>,
    mut text_query: Query<&mut Text>,
    drills: Query<&Drill>,
) {
    for (interaction, mut previous_interaction, mut color, drill_button, mut button, children) in &mut interaction_query {
        match *interaction {
            Interaction::Pressed => {
                *color = colors::SURFACE_1.into();
            }
            Interaction::Hovered => {
                *color = colors::SURFACE_0.into();
                if previous_interaction.0 == Interaction::Pressed {
                    // released
                    let mut text = text_query.get_mut(children[0]).unwrap();
                    let Ok(drill) = drills.get(drill_button.0) else {
                        error!("A former drill is now not a drill, causing a problem in the drill button");
                        previous_interaction.0 = *interaction;
                        return
                    };
                    // don't allow drill toggling while not on a planet
                    if drill.on_planet.is_none() { return }
                    // the text is flipped because drill.drilling is an old value,
                    // which was now toggled
                    if drill.drilling {
                        **text = "Start Drill".to_string();
                    } else {
                        **text = "Stop Drill".to_string();
                    }
                    toggle_drill_writer.write(ToggleDrillEvent { drill_entity: drill_button.0 });
                }
            }
            Interaction::None => {
                *color = colors::CRUST.into();
            }
        }
        previous_interaction.0 = *interaction;
    }
}
fn drill_state_change(
    drills: Query<&Drill, Changed<Drill>>,
    drill_buttons: Query<(&DrillButton, &Children)>,
    mut text_query: Query<&mut Text>,
) {
    for (drill_button, children) in &drill_buttons {
        let Ok(drill) = drills.get(drill_button.0) else {
            continue
        };

        let mut text = text_query.get_mut(children[0]).unwrap();
        **text = get_drill_text(drill);
    }
}
fn get_drill_text(drill: &Drill) -> String {
    if drill.on_planet.is_some() {
        if drill.drilling {
            "Stop Drill".to_string()
        } else {
            "Start Drill".to_string()
        }
    } else {
        "Drill not on planet".to_string()
    }
}
fn single_storage_display(
    mut single_storage_display_query: Query<(&mut Text, &SingleStorageDisplay)>,
    part_query: Query<&SingleStorage, With<Part>>,
) {
    for (mut text, single_storage_display) in &mut single_storage_display_query {
        let single_storage = part_query.get(single_storage_display.0).expect("In single_storage_display, the entity didn't match a storage.");
        **text = format!("{}: {}", single_storage.resource_name, single_storage.stored);
    }
}

fn close_button(
    mut commands: Commands,
    mut interaction_query: Query<
        (&Interaction, &mut PreviousInteraction, &mut BackgroundColor, &CloseButton, &mut Button),
        Changed<Interaction>,
    >,
    mouse: Res<ButtonInput<MouseButton>>,
) {
    for (interaction, mut previous_interaction, mut color,
        close_button, mut button) in &mut interaction_query
    {
        match *interaction {
            Interaction::Pressed => {
                *color = colors::MAROON.into();
            }
            Interaction::Hovered => {
                *color = colors::PINK.into();
                if previous_interaction.0 == Interaction::Pressed {
                    commands.entity(close_button.0).despawn();
                }
            }
            Interaction::None => {
                *color = colors::RED.into();
            }
        }
        previous_interaction.0 = *interaction;
    }
}