flatland3-gfx 0.2.28

Flatland3 Macroquad + egui graphical play client
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Pre-connect onboarding: login / register / create character / character select.

use flatland_cli::characters::{self, CharacterSummary};
use flatland_cli::config::{SavedLogin, SessionConfig};
use flatland_cli::session_auth;
use flatland_client_lib::{api_base_url_for_host, host_override_active, ClientConfig};
use flatland_gfx_engine::GfxTheme;
use macroquad::prelude::*;
use uuid::Uuid;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
    Auth,
    CreateCharacter,
    SelectCharacter,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuthMode {
    Login,
    Register,
}

pub struct OnboardingOpts<'a> {
    pub preferred_name: Option<&'a str>,
    /// Skip auto-pick and show the character list (Switch character).
    pub force_character_select: bool,
    /// Optional status line (e.g. after a disconnect).
    pub status_hint: Option<String>,
    /// CLI `--host` is active — do not persist server to client.json.
    pub host_override: bool,
}

struct OnboardingState {
    phase: Phase,
    auth_mode: AuthMode,
    /// Game server host (DNS or IP); saved to client.json before login unless override.
    server_host: String,
    /// When true, host came from `--host` and must not write client.json.
    host_override: bool,
    email: String,
    password: String,
    show_password: bool,
    display_name: String,
    character_name: String,
    characters: Vec<CharacterSummary>,
    status: String,
    busy: bool,
    egui_configured: bool,
    preferred_name: Option<String>,
    force_character_select: bool,
    highlight_id: Option<Uuid>,
    result: Option<CharacterSummary>,
    quit: bool,
}

impl OnboardingState {
    fn new(opts: &OnboardingOpts<'_>) -> Self {
        let saved = SavedLogin::load();
        let cfg = ClientConfig::load();
        let server_host = if opts.host_override {
            std::env::var("FLATLAND_HOST_OVERRIDE").unwrap_or_else(|_| cfg.display_game_host())
        } else {
            cfg.display_game_host()
        };
        Self {
            phase: Phase::Auth,
            auth_mode: AuthMode::Login,
            server_host,
            host_override: opts.host_override,
            email: saved
                .as_ref()
                .map(|s| s.email.clone())
                .unwrap_or_default(),
            password: saved
                .as_ref()
                .map(|s| s.password.clone())
                .unwrap_or_default(),
            show_password: false,
            display_name: String::new(),
            character_name: opts.preferred_name.unwrap_or("").to_string(),
            characters: Vec::new(),
            status: if let Some(hint) = opts.status_hint.clone() {
                hint
            } else if opts.host_override {
                "CLI --host active (not saved). Sign in to play.".into()
            } else if saved.is_some() {
                "Sign in to play (saved login loaded).".into()
            } else {
                "Enter your server, then sign in or create an account.".into()
            },
            busy: false,
            egui_configured: false,
            preferred_name: opts.preferred_name.map(str::to_string),
            force_character_select: opts.force_character_select,
            highlight_id: None,
            result: None,
            quit: false,
        }
    }
}

/// Run interactive onboarding when needed.
///
/// Returns `Some(character)` when the session path chose a character.
/// Returns `None` when `FLATLAND_API_TOKEN` is set (caller uses CLI resolve).
///
/// Macroquad’s executor is not Tokio — all control-plane HTTP must go through
/// `rt.block_on`, never `.await` on reqwest futures here.
pub async fn run(opts: OnboardingOpts<'_>) -> anyhow::Result<Option<CharacterSummary>> {
    if session_auth::has_api_token() {
        return Ok(None);
    }

    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;

    let mut state = OnboardingState::new(&opts);

    if opts.force_character_select {
        let session_ok = rt.block_on(session_auth::session_is_valid())
            || rt.block_on(session_auth::try_restore_expired_session());
        if session_ok {
            match rt.block_on(enter_character_phase(&mut state)) {
                Ok(Some(chosen)) => return Ok(Some(chosen)),
                Ok(None) => {}
                Err(err) => {
                    state.status = err.to_string();
                    state.phase = Phase::Auth;
                }
            }
        } else {
            state.status = "Session expired — sign in again.".into();
            state.phase = Phase::Auth;
        }
    } else if !rt.block_on(session_auth::needs_interactive_login()) {
        match rt.block_on(enter_character_phase(&mut state)) {
            Ok(Some(chosen)) => return Ok(Some(chosen)),
            Ok(None) => {}
            Err(err) => {
                state.status = err.to_string();
                state.phase = Phase::Auth;
            }
        }
    }

    while state.result.is_none() && !state.quit {
        clear_background(Color::from_rgba(8, 9, 12, 255));

        let mut submit = false;
        let mut switch_login = false;
        let mut switch_register = false;
        let mut selected: Option<usize> = None;

        egui_macroquad::ui(|ctx| {
            if !state.egui_configured {
                flatland_gfx_engine::configure_egui(ctx);
                state.egui_configured = true;
            }
            draw_panel(
                ctx,
                &mut state,
                &mut submit,
                &mut switch_login,
                &mut switch_register,
                &mut selected,
            );
        });
        egui_macroquad::draw();

        // Prevent typed login chars from sitting in Macroquad's queue until play starts.
        flatland_gfx_engine::drain_pending_input();

        if is_key_pressed(KeyCode::Escape) {
            anyhow::bail!("onboarding cancelled");
        }

        if switch_login {
            state.auth_mode = AuthMode::Login;
            state.status = "Sign in with email and password.".into();
        }
        if switch_register {
            state.auth_mode = AuthMode::Register;
            state.status = "Create an account, then make a character.".into();
        }

        if let Some(idx) = selected {
            if let Some(c) = state.characters.get(idx).cloned() {
                let _ = characters::remember_character(c.id);
                state.result = Some(c);
            }
        }

        if submit && !state.busy {
            state.busy = true;
            state.status = "Working…".into();
            match state.phase {
                Phase::Auth => {
                    let auth_result = (|| {
                        let api = if state.host_override || host_override_active() {
                            api_base_url_for_host(state.server_host.trim())?
                        } else {
                            let mut cfg = ClientConfig::load();
                            cfg.set_game_host(state.server_host.trim())?;
                            cfg.api_base_url()
                        };
                        match state.auth_mode {
                            AuthMode::Login => {
                                let email = state.email.clone();
                                let password = state.password.clone();
                                rt.block_on(session_auth::login(&email, &password, &api))
                            }
                            AuthMode::Register => {
                                let email = state.email.clone();
                                let password = state.password.clone();
                                let display_name = state.display_name.clone();
                                rt.block_on(session_auth::register(
                                    &email,
                                    &password,
                                    &display_name,
                                    &api,
                                ))
                            }
                        }
                    })();
                    match auth_result {
                        Ok(()) => match rt.block_on(enter_character_phase(&mut state)) {
                            Ok(Some(chosen)) => state.result = Some(chosen),
                            Ok(None) => {}
                            Err(err) => state.status = err.to_string(),
                        },
                        Err(err) => state.status = err.to_string(),
                    }
                }
                Phase::CreateCharacter => {
                    let name = state.character_name.clone();
                    match rt.block_on(characters::create_character(&name)) {
                        Ok(created) => {
                            state.status = format!("Created {}.", created.name);
                            state.result = Some(created);
                        }
                        Err(err) => state.status = err.to_string(),
                    }
                }
                Phase::SelectCharacter => {}
            }
            state.busy = false;
        }

        next_frame().await;
    }

    if state.quit {
        anyhow::bail!("onboarding cancelled");
    }

    // Flush leftovers so the first play frames don't treat password letters as hotkeys.
    for _ in 0..2 {
        flatland_gfx_engine::drain_pending_input();
        next_frame().await;
    }
    flatland_gfx_engine::drain_pending_input();

    Ok(state.result)
}

/// After a valid session: create / select / auto-pick (only when exactly one character).
///
/// With **two or more** characters we always show the select screen — `--name` and
/// last-played only highlight a suggestion; they do not skip the picker.
async fn enter_character_phase(
    state: &mut OnboardingState,
) -> anyhow::Result<Option<CharacterSummary>> {
    let list = characters::list_characters().await?;
    state.characters = list.clone();
    state.highlight_id = resolve_highlight(&list, state.preferred_name.as_deref());

    if list.is_empty() {
        if let Some(preferred) = state
            .preferred_name
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            state.character_name = preferred.to_string();
            state.status = format!("Create character \"{preferred}\" to continue.");
        } else {
            state.status = "Create your first character.".into();
        }
        state.phase = Phase::CreateCharacter;
        return Ok(None);
    }

    if list.len() == 1 && !state.force_character_select {
        let only = list[0].clone();
        let _ = characters::remember_character(only.id);
        return Ok(Some(only));
    }

    state.phase = Phase::SelectCharacter;
    state.status = match state.highlight_id.and_then(|id| list.iter().find(|c| c.id == id)) {
        Some(c) => format!("Select a character (last / suggested: {}).", c.name),
        None => "Select a character.".into(),
    };
    Ok(None)
}

fn resolve_highlight(list: &[CharacterSummary], preferred_name: Option<&str>) -> Option<Uuid> {
    if let Some(raw) = preferred_name.map(str::trim).filter(|s| !s.is_empty()) {
        if let Some(found) = list.iter().find(|c| c.name == raw) {
            return Some(found.id);
        }
    }
    if let Ok(session) = SessionConfig::load() {
        if let Some(id) = session.last_character_id {
            if list.iter().any(|c| c.id == id) {
                return Some(id);
            }
        }
    }
    None
}

fn draw_panel(
    ctx: &egui::Context,
    state: &mut OnboardingState,
    submit: &mut bool,
    switch_login: &mut bool,
    switch_register: &mut bool,
    selected: &mut Option<usize>,
) {
    let theme = GfxTheme::default();
    let screen = ctx.screen_rect();
    let width = (screen.width() * 0.42).clamp(360.0, 520.0);
    let height = match state.phase {
        Phase::Auth if state.auth_mode == AuthMode::Register => 540.0,
        Phase::Auth => 520.0,
        Phase::CreateCharacter => 300.0,
        Phase::SelectCharacter => (280.0 + state.characters.len() as f32 * 36.0).min(520.0),
    };

    egui::Window::new(match state.phase {
        Phase::Auth => match state.auth_mode {
            AuthMode::Login => "Flatland3 — Sign in",
            AuthMode::Register => "Flatland3 — Create account",
        },
        Phase::CreateCharacter => "Flatland3 — Create character",
        Phase::SelectCharacter => "Flatland3 — Select character",
    })
    .title_bar(false)
    .collapsible(false)
    .resizable(false)
    .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
    .default_size(egui::vec2(width, height))
    .frame(flatland_gfx_engine::ui::card_frame(&theme))
    .show(ctx, |ui| {
        ui.set_min_size(egui::vec2(width - 24.0, height - 48.0));
        let title = match state.phase {
            Phase::Auth => match state.auth_mode {
                AuthMode::Login => "Sign in",
                AuthMode::Register => "Create account",
            },
            Phase::CreateCharacter => "Create character",
            Phase::SelectCharacter => "Select character",
        };
        flatland_gfx_engine::ui::draw_card_header(ui, &theme, title, Some("Flatland3"));
        ui.add_space(6.0);
        ui.add_enabled_ui(!state.busy, |ui| {
            match state.phase {
                Phase::Auth => draw_auth(ui, state, submit, switch_login, switch_register),
                Phase::CreateCharacter => draw_create_character(ui, state, submit),
                Phase::SelectCharacter => draw_select_character(ui, state, selected),
            }
        });
        ui.add_space(8.0);
        if !state.status.is_empty() {
            let color = if state.busy {
                theme.accent
            } else {
                theme.selected
            };
            ui.colored_label(color, &state.status);
        }
        flatland_gfx_engine::ui::draw_keybind_footer(
            ui,
            &theme,
            &[
                flatland_gfx_engine::ui::Keybind::new("Enter", "continue"),
                flatland_gfx_engine::ui::Keybind::new("Esc", "quit"),
            ],
        );
    });
}

fn draw_auth(
    ui: &mut egui::Ui,
    state: &mut OnboardingState,
    submit: &mut bool,
    switch_login: &mut bool,
    switch_register: &mut bool,
) {
    ui.horizontal(|ui| {
        let login_sel = state.auth_mode == AuthMode::Login;
        let register_sel = state.auth_mode == AuthMode::Register;
        if ui
            .add_sized(
                egui::vec2(120.0, 28.0),
                egui::SelectableLabel::new(login_sel, "Login"),
            )
            .clicked()
        {
            *switch_login = true;
        }
        if ui
            .add_sized(
                egui::vec2(140.0, 28.0),
                egui::SelectableLabel::new(register_sel, "Register"),
            )
            .clicked()
        {
            *switch_register = true;
        }
    });
    ui.add_space(8.0);

    ui.label("Server");
    ui.add_enabled_ui(!state.host_override, |ui| {
        ui.add(
            egui::TextEdit::singleline(&mut state.server_host)
                .desired_width(f32::INFINITY)
                .hint_text("server1.flatland3.com  or  127.0.0.1"),
        );
    });
    let host_hint = if state.host_override {
        "CLI --host — gateway 7373 · API 7380 (not saved to client.json)"
    } else {
        "Gateway 7373 · API 7380 (saved before sign-in)"
    };
    ui.label(egui::RichText::new(host_hint).small().weak());
    ui.add_space(6.0);

    ui.label("Email");
    ui.add(
        egui::TextEdit::singleline(&mut state.email)
            .desired_width(f32::INFINITY)
            .hint_text("you@example.com"),
    );
    ui.label("Password");
    ui.horizontal(|ui| {
        let edit = egui::TextEdit::singleline(&mut state.password)
            .password(!state.show_password)
            .desired_width(ui.available_width() - 72.0);
        ui.add(edit);
        let reveal_label = if state.show_password { "Hide" } else { "Show" };
        if ui.button(reveal_label).clicked() {
            state.show_password = !state.show_password;
        }
    });
    if state.auth_mode == AuthMode::Register {
        ui.label("Display name");
        ui.add(
            egui::TextEdit::singleline(&mut state.display_name)
                .desired_width(f32::INFINITY)
                .hint_text("Shown on your account"),
        );
    }

    ui.add_space(12.0);
    let label = match state.auth_mode {
        AuthMode::Login => "Sign in",
        AuthMode::Register => "Create account",
    };
    if ui
        .add_sized(
            egui::vec2(ui.available_width(), 32.0),
            egui::Button::new(label),
        )
        .clicked()
        || ui.input(|i| i.key_pressed(egui::Key::Enter))
    {
        *submit = true;
    }

    ui.add_space(10.0);
    match state.auth_mode {
        AuthMode::Login => {
            ui.vertical_centered(|ui| {
                ui.label(egui::RichText::new("Need an account?").weak());
                if ui
                    .add(
                        egui::Button::new(
                            egui::RichText::new("Need an Account — Register")
                                .strong()
                                .size(14.0),
                        )
                        .fill(egui::Color32::from_rgb(55, 90, 70)),
                    )
                    .clicked()
                {
                    *switch_register = true;
                }
            });
        }
        AuthMode::Register => {
            ui.vertical_centered(|ui| {
                ui.label(egui::RichText::new("Already registered?").weak());
                if ui.link("Back to Login").clicked() {
                    *switch_login = true;
                }
            });
        }
    }
}

fn draw_create_character(ui: &mut egui::Ui, state: &mut OnboardingState, submit: &mut bool) {
    ui.label("Choose a character name (letters, digits, _ and -).");
    ui.add_space(8.0);
    ui.label("Name");
    ui.add(
        egui::TextEdit::singleline(&mut state.character_name)
            .desired_width(f32::INFINITY)
            .hint_text("Traveler"),
    );
    ui.add_space(12.0);
    if ui
        .add_sized(
            egui::vec2(ui.available_width(), 32.0),
            egui::Button::new("Create character"),
        )
        .clicked()
        || ui.input(|i| i.key_pressed(egui::Key::Enter))
    {
        *submit = true;
    }
}

fn draw_select_character(
    ui: &mut egui::Ui,
    state: &mut OnboardingState,
    selected: &mut Option<usize>,
) {
    ui.label("Choose which character to play. Your choice is remembered next time.");
    ui.add_space(8.0);
    egui::ScrollArea::vertical().show(ui, |ui| {
        for (idx, c) in state.characters.iter().enumerate() {
            let suggested = state.highlight_id == Some(c.id);
            let label = if suggested {
                format!("{}", c.name)
            } else {
                c.name.clone()
            };
            let button = if suggested {
                egui::Button::new(egui::RichText::new(label).strong())
            } else {
                egui::Button::new(label)
            };
            if ui
                .add_sized(egui::vec2(ui.available_width(), 28.0), button)
                .clicked()
            {
                *selected = Some(idx);
            }
        }
    });
}