rusterix 0.9.7

Rusterix is the game engine of Eldiron.
Documentation
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
use crate::{Command, PlayerCamera, SceneHandler, Surface, prelude::*};
use indexmap::IndexMap;
use scenevm::Atom;
use theframework::prelude::*;
use vek::Vec2;

#[derive(PartialEq)]
pub enum ClientDrawMode {
    D2,
    D3,
}

use ClientDrawMode::*;

/// Rusterix can server as a server or client or both for solo games.
pub struct Rusterix {
    pub assets: Assets,
    pub server: Server,
    pub client: Client,
    pub audio: Option<AudioEngine>,

    pub is_dirty_d2: bool,
    pub is_dirty_d3: bool,
    pub draw_mode: ClientDrawMode,

    pub player_camera: PlayerCamera,

    pub scene_handler: SceneHandler,
}

impl Default for Rusterix {
    fn default() -> Self {
        Self::new()
    }
}

impl Rusterix {
    fn apply_runtime_render_state(&mut self, map: &Map) {
        self.scene_handler.runtime_render_state = self.server.get_render_state(&map.id);
    }

    pub fn new() -> Self {
        let mut scene_handler = SceneHandler::default();

        if let Some(bytes) = crate::Embedded::get("shader/2d_shader.wgsl") {
            if let Ok(source) = std::str::from_utf8(bytes.data.as_ref()) {
                scene_handler.vm.execute(Atom::SetSource2D(source.into()));
            }
        }

        // if let Some(bytes) = crate::Embedded::get("shader/3d_shader.wgsl") {
        //     if let Ok(source) = std::str::from_utf8(bytes.data.as_ref()) {
        //         scene_handler.vm.execute(Atom::SetSource3D(source.into()));
        //     }
        // }

        Self {
            assets: Assets::default(),
            server: Server::default(),
            client: Client::default(),
            audio: AudioEngine::new().ok(),

            is_dirty_d2: true,
            is_dirty_d3: true,
            draw_mode: ClientDrawMode::D3,

            player_camera: PlayerCamera::D2,

            scene_handler,
        }
    }

    /// Set to 2D mode.
    pub fn set_d2(&mut self) {
        self.draw_mode = D2;
    }

    /// Set to 3D mode.
    pub fn set_d3(&mut self) {
        self.draw_mode = D3;
    }

    /// Set the dirty flag, i.e. scene needs to be rebuild.
    pub fn set_dirty(&mut self) {
        self.is_dirty_d2 = true;
        self.is_dirty_d3 = true;
        self.scene_handler.mark_dynamics_dirty();
    }

    /// Invalidate only dynamic overlays (entities/items/lights), keep static geometry intact.
    pub fn set_overlay_dirty(&mut self) {
        self.scene_handler.mark_dynamics_dirty();
    }

    /// Set the assets
    pub fn set_assets(&mut self, assets: Assets) {
        self.assets = assets;
        self.load_audio_assets();
    }

    fn ensure_audio_engine(&mut self) {
        if self.audio.is_none() {
            self.audio = AudioEngine::new().ok();
        }
    }

    /// Load all audio assets into the runtime audio engine cache.
    pub fn load_audio_assets(&mut self) {
        self.ensure_audio_engine();
        let Some(engine) = self.audio.as_ref() else {
            return;
        };
        engine.clear_clips();
        for (name, bytes) in &self.assets.audio {
            let _ = engine.load_clip_from_bytes(name, bytes);
        }
        for name in crate::audio::list_audio_fx_names(&self.assets.audio_fx_src) {
            if let Ok(bytes) =
                crate::audio::synthesize_audio_fx_wav(&self.assets.audio_fx_src, &name)
            {
                let _ = engine.load_clip_from_bytes(&name, &bytes);
            }
        }
    }

    /// Play one-shot audio by asset name.
    pub fn play_audio(&mut self, name: &str) -> bool {
        self.ensure_audio_engine();
        let Some(engine) = self.audio.as_ref() else {
            return false;
        };
        engine.play_one_shot(name, 1.0)
    }

    /// Play audio on a given bus/layer (e.g. "music", "sfx"), optionally looping.
    pub fn play_audio_on_bus(&mut self, name: &str, bus: &str, gain: f32, looping: bool) -> bool {
        self.ensure_audio_engine();
        let Some(engine) = self.audio.as_ref() else {
            return false;
        };
        engine.play_on_bus(name, bus, gain, looping)
    }

    /// Set per-bus volume.
    pub fn set_audio_bus_volume(&mut self, bus: &str, volume: f32) {
        self.ensure_audio_engine();
        if let Some(engine) = self.audio.as_ref() {
            engine.set_bus_volume(bus, volume);
        }
    }

    /// Get per-bus volume.
    pub fn audio_bus_volume(&self, bus: &str) -> f32 {
        if let Some(engine) = self.audio.as_ref() {
            return engine.bus_volume(bus);
        }
        1.0
    }

    /// Stop all currently playing voices on a bus/layer.
    pub fn clear_audio_bus(&mut self, bus: &str) {
        self.ensure_audio_engine();
        if let Some(engine) = self.audio.as_ref() {
            engine.clear_bus(bus);
        }
    }

    /// Stop all currently playing clip voices across all buses/layers.
    pub fn clear_all_audio(&mut self) {
        self.ensure_audio_engine();
        if let Some(engine) = self.audio.as_ref() {
            engine.clear_all_buses();
        }
    }

    /// Create the server regions.
    pub fn create_regions(&mut self) {
        for (name, map) in &self.assets.maps {
            self.server
                .create_region_instance(name.clone(), map.clone(), &self.assets, "".into());
        }
        self.server.set_state(crate::ServerState::Running);
    }

    /// Process messages from the server to be displayed on the client.
    pub fn process_messages(&mut self, map: &Map, says: Vec<crate::server::Say>) {
        self.client.process_messages(map, says);
    }

    /*
    /// Build the client scene based on the maps camera mode, or, if the game is running on the PlayerCamera.
    pub fn build_scene(
        &mut self,
        screen_size: Vec2<f32>,
        map: &Map,
        values: &ValueContainer,
        game_mode: bool,
    ) {
        if game_mode {
            if self.player_camera == PlayerCamera::D2 {
                if self.is_dirty_d2 {
                    self.client
                        .build_scene_d2(screen_size, map, &self.assets, values);
                    self.is_dirty_d2 = false;
                }
                self.set_d2();
            } else {
                if self.is_dirty_d3 {
                    self.client.build_scene_d3(map, &self.assets, values);
                    self.is_dirty_d3 = false;
                }
                self.set_d3();
            }
        } else {
            #[allow(clippy::collapsible_if)]
            if map.camera == MapCamera::TwoD {
                if self.is_dirty_d2 {
                    self.client
                        .build_scene_d2(screen_size, map, &self.assets, values);
                    self.is_dirty_d2 = false;
                }
                self.set_d2();
            } else {
                if self.is_dirty_d3 {
                    self.client.build_scene_d3(map, &self.assets, values);
                    self.is_dirty_d3 = false;
                }
                self.set_d3();
            }
        }
    }*/

    /// Apply the entities to the 3D scene.
    pub fn apply_entities_items(
        &mut self,
        screen_size: Vec2<f32>,
        map: &Map,
        edit_surface: &Option<Surface>,
        draw_sectors: bool,
    ) {
        for e in map.entities.iter() {
            if e.is_player() {
                if let Some(Value::PlayerCamera(camera)) = e.attributes.get("player_camera") {
                    if *camera != self.player_camera {
                        self.player_camera = camera.clone();
                        if self.player_camera == PlayerCamera::D3Iso {
                            self.client.camera_d3 = Box::new(D3IsoCamera::new())
                        } else if self.player_camera == PlayerCamera::D3FirstP {
                            self.client.camera_d3 = Box::new(D3FirstPCamera::new());
                        }
                    }
                    break;
                }
            }
        }
        if self.draw_mode == ClientDrawMode::D2 {
            self.apply_runtime_render_state(map);
            self.client.apply_entities_items_d2(
                screen_size,
                map,
                &self.assets,
                edit_surface,
                &mut self.scene_handler,
                draw_sectors,
            );
        } else if self.draw_mode == ClientDrawMode::D3 {
            self.client
                .apply_entities_items_d3(map, &self.assets, &mut self.scene_handler);
        }
    }

    /// Build the client scene in D2.
    pub fn build_custom_scene_d2(
        &mut self,
        screen_size: Vec2<f32>,
        map: &Map,
        values: &ValueContainer,
        edit_surface: &Option<Surface>,
        draw_sectors: bool,
    ) {
        self.client.build_custom_scene_d2(
            screen_size,
            map,
            &self.assets,
            values,
            edit_surface,
            &mut self.scene_handler,
            draw_sectors,
        );
    }

    /// Builds the entities and items w/o changing char positions
    pub fn build_entities_items_d3(&mut self, map: &Map) {
        self.client.builder_d3.build_entities_items(
            map,
            self.client.camera_d3.as_ref(),
            &self.assets,
            &mut self.client.scene,
            &mut self.scene_handler,
        );
    }

    /// Build runtime 3D dynamic overlays (characters/items/lights) into SceneVM.
    pub fn build_dynamics_3d(&mut self, map: &Map, animation_frame: usize) {
        let camera = self.client.camera_d3.as_ref();
        self.scene_handler
            .build_dynamics_3d(map, camera, animation_frame, &self.assets);
    }

    /// Build runtime 2D dynamic overlays (characters/items/lights) into SceneVM.
    pub fn build_dynamics_2d(&mut self, map: &Map, animation_frame: usize) {
        self.scene_handler
            .build_dynamics_2d(map, animation_frame, &self.assets);
    }

    /// Build the client scene in D3.
    pub fn build_custom_scene_d3(&mut self, map: &Map, values: &ValueContainer) {
        self.client.build_custom_scene_d3(map, &self.assets, values);
    }

    /// Draw the client custom scene in 2D.
    pub fn draw_custom_d2(&mut self, map: &Map, pixels: &mut [u8], width: usize, height: usize) {
        self.apply_runtime_render_state(map);
        self.client.draw_custom_d2(
            map,
            pixels,
            width,
            height,
            &self.assets,
            &mut self.scene_handler,
        );
    }

    /// Draw the client scene in 2D.
    pub fn draw_d2(&mut self, map: &Map, pixels: &mut [u8], width: usize, height: usize) {
        self.apply_runtime_render_state(map);
        self.client.draw_d2(
            map,
            pixels,
            width,
            height,
            &self.assets,
            &mut self.scene_handler,
        );
    }

    /// Draw the client scene in 3D
    pub fn draw_d3(&mut self, map: &Map, pixels: &mut [u8], width: usize, height: usize) {
        self.apply_runtime_render_state(map);
        self.client.draw_d3(
            map,
            pixels,
            width,
            height,
            &self.assets,
            &mut self.scene_handler,
        );
    }

    /// Draw the client scene.
    pub fn draw_scene(&mut self, map: &Map, pixels: &mut [u8], width: usize, height: usize) {
        match self.draw_mode {
            D2 => {
                self.apply_runtime_render_state(map);
                self.client.draw_d2(
                    map,
                    pixels,
                    width,
                    height,
                    &self.assets,
                    &mut self.scene_handler,
                );
            }
            D3 => {
                self.apply_runtime_render_state(map);
                self.client.draw_d3(
                    map,
                    pixels,
                    width,
                    height,
                    &self.assets,
                    &mut self.scene_handler,
                );
            }
        }
    }

    /// Set up the client for processing the game.
    pub fn setup_client(&mut self) -> Vec<Command> {
        let cmds = self.client.setup(&mut self.assets, &mut self.scene_handler);
        self.load_audio_assets();
        cmds
    }

    /// Draw the game as the client sees it.
    pub fn draw_game(
        &mut self,
        map: &Map,
        messages: Vec<crate::server::Message>,
        says: Vec<crate::server::Say>,
        choices: Vec<crate::MultipleChoice>,
    ) {
        self.apply_runtime_render_state(map);
        self.client.process_messages(map, says);
        self.client.draw_game(
            map,
            &self.assets,
            messages,
            choices,
            &mut self.scene_handler,
        );
    }

    /// Prepare the game scene in SceneVM for direct window presentation.
    /// This avoids CPU readback and lets a caller present with SceneVM's native window path.
    pub fn prepare_game_scene_for_present(&mut self, map: &Map, size: (u32, u32)) -> bool {
        self.apply_runtime_render_state(map);
        self.client
            .prepare_scenevm_direct(map, &self.assets, &mut self.scene_handler, size)
    }

    /// Render only UI/screen widgets into a transparent overlay RGBA buffer.
    pub fn draw_ui_overlay_only(
        &mut self,
        map: &Map,
        messages: Vec<crate::server::Message>,
        choices: Vec<crate::MultipleChoice>,
        width: u32,
        height: u32,
    ) -> &TheRGBABuffer {
        self.apply_runtime_render_state(map);
        self.client
            .draw_ui_overlay_only(map, &self.assets, messages, choices, width, height)
    }

    /// Get first game widget rect in viewport coordinates.
    pub fn game_widget_rect(&self) -> Option<crate::Rect> {
        self.client.game_widget_rect()
    }

    /// Get presentation transform from viewport coordinates into a target surface.
    pub fn presentation_transform_for_surface(&self, size: (u32, u32)) -> (f32, f32, f32) {
        self.client
            .presentation_transform_for_surface(size.0, size.1)
    }

    /// Clear active say bubbles from the client.
    pub fn clear_say_messages(&mut self) {
        self.client.clear_say_messages();
    }

    /// Send a touch dragged event to the client.
    pub fn client_touch_dragged(&mut self, coord: Vec2<i32>, map: &Map) {
        self.client
            .touch_dragged(coord, map, &mut self.scene_handler);
    }

    /// Send a touch hover event to the client.
    pub fn client_touch_hover(&mut self, coord: Vec2<i32>, map: &Map) {
        self.client.touch_hover(coord, map, &mut self.scene_handler);
    }

    /// Update the server messages.
    pub fn update_server(&mut self) -> Option<String> {
        self.server.update(&mut self.assets)
    }

    /// Update the tiles
    pub fn set_tiles(&mut self, textures: IndexMap<Uuid, Tile>, editor: bool) {
        let mut all_tiles = textures;

        // Register synthetic 1x1 tiles for all palette indices so PaletteIndex sources
        // always resolve to real atlas/tile-list entries.
        for (idx, col_opt) in self.assets.palette.colors.iter().enumerate() {
            let Some(col) = col_opt else {
                continue;
            };
            let tile_id = Uuid::from_u128(0x50414C455454455F0000000000000000u128 | idx as u128);
            let [roughness, metallic, opacity, emissive] = self
                .assets
                .palette_materials
                .get(idx)
                .copied()
                .unwrap_or([0.5, 0.0, 1.0, 0.0]);
            let tile = all_tiles.entry(tile_id).or_insert_with(|| {
                let mut t = Tile::from_texture(Texture::from_color(col.to_u8_array()));
                t.id = tile_id;
                t
            });
            for texture in &mut tile.textures {
                texture.set_materials_all(roughness, metallic, opacity, emissive);
            }
        }

        self.scene_handler.build_atlas(&all_tiles, editor);
        self.assets.set_tiles(all_tiles);
        let palette: Vec<vek::Vec4<f32>> = self
            .assets
            .palette
            .colors
            .iter()
            .map(|entry| {
                if let Some(col) = entry {
                    let [r, g, b, a] = col.to_array();
                    let to_linear = |c: f32| c.max(0.0).powf(2.2);
                    vek::Vec4::new(to_linear(r), to_linear(g), to_linear(b), a)
                } else {
                    vek::Vec4::zero()
                }
            })
            .collect();
        self.scene_handler.vm.execute(Atom::SetPalette(palette));
        self.scene_handler.clear_runtime_scene();
    }
}