Repository navigation
Expand file tree
/
Copy pathpresentation.zig
More file actions
2477 lines (2382 loc) · 131 KB
/
Copy pathpresentation.zig
File metadata and controls
2477 lines (2382 loc) · 131 KB
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The presentation side of mods' scripts ([#498](https://github.com/OpenReliant/openreliant/issues/498)):
//! player and menu scripts, which decide what the player sees, hears and does, in a Luau state of
//! their own.
//!
//! - A mod's `Menu` scripts start as OpenReliant starts, and run until it quits, in the menus and
//! over the missions.
//! - Its `Player` scripts start as a game starts, and stop as it ends, as the global scripts do.
//! - Both get `on_frame` each frame drawn, even while the game is paused; `on_key_press` and
//! `on_key_release` as keys go down and up; `on_action` as the controls bound to an action are
//! used in flight; `on_window_resized` as the window changes size; `on_room_changed` as the
//! player moves through the carrier's rooms; and `on_music_changed` as the music changes.
//! - They play sounds and music (`audio.zig`). Sounds started by player scripts stop when the game
//! ends, and sounds started by menu scripts stop when the menu scripts reload.
//! - They draw over the flight display and the menus (`drawing.zig`), and change the game only by
//! sending events to the global scripts (`core.send_global_event`), which wait until the game
//! next runs and then have their data copied into the game's state, as it would be sent to
//! another machine (`Presentation.sendEvents`).
//!
//! If no mod has player or menu scripts, no Luau state is created.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const log = std.log.scoped(.scripts);
const openreliant = @import("openreliant");
const engine = openreliant.engine;
const mods = engine.game.bigfile.mods;
const Mod = mods.Mod;
const create = engine.game.create;
const hud = engine.game.hud;
const camera = engine.game.camera;
const hog_snd = engine.game.hog_snd;
const input = engine.input;
const mod_options = engine.game.interface.mod_options;
const rooms = engine.game.interface.rooms;
const postprocessing = @import("postprocessing.zig");
const shaders = @import("shaders.zig");
const game_modes = @import("game_modes.zig");
const front_end = @import("front_end.zig");
const interf = engine.genilib.interf;
const srtexture = engine.surrender.surrenderlib.srtexture;
const controls = engine.input.controls;
const device = engine.surrender.srd3d.device;
const engine_hooks = engine.hooks;
const script = @import("script.zig");
const runtime = @import("runtime.zig");
const Runtime = runtime.Runtime;
const records = @import("records.zig");
const packages = @import("packages.zig");
const objects = @import("objects.zig");
const interfaces = @import("interfaces.zig");
const running = @import("running.zig");
const drawing = @import("drawing.zig");
const audio = @import("audio.zig");
const data = @import("data.zig");
const events = @import("events.zig");
const api = @import("api.zig");
const Call = api.Call;
const load = @import("load.zig");
const game_module = @import("game.zig");
/// Limits for player and menu scripts: 100 milliseconds per call, and 64 MiB per mod, as for the
/// game's.
pub const limits: runtime.Limits = .{ .time = .fromMilliseconds(100), .memory = runtime.memory_per_mod };
/// The scripts of each kind that runs on the presentation side.
const Place = enum { menu, player };
/// The kinds of keys a keyboard reports, by scan code (`input.Key`).
const key_codes = std.math.maxInt(@typeInfo(input.Key).@"enum".tag_type) + 1;
/// What the driver tells the scripts of a frame.
pub const Host = struct {
/// The seconds of real time since the last frame.
seconds: f32,
/// The keyboard, the joystick and the bindings.
devices: *input.Devices,
/// The window's size in pixels.
window: [2]u32,
/// What each layer is drawn on this frame; null for one that isn't shown.
views: std.EnumArray(drawing.Which, ?drawing.View) = .initFill(null),
/// The camera, while a mission is shown.
camera: ?Camera = null,
/// The flight display's state and the player's, which `openreliant.hud` reads, while a
/// mission is shown.
flight: ?Flight = null,
/// The sound, where any is heard.
sound: ?*hog_snd.Sound = null,
/// The scene 3D sounds play in, during a mission.
scene: ?hog_snd.Scene = null,
/// Whether the player is flying, which is when the controls' actions mean anything.
flying: bool = false,
/// Where the player is in the carrier's rooms, while they're on screen (`openreliant.rooms`).
rooms: ?Rooms = null,
pub const Rooms = struct {
carrier: rooms.Carrier,
/// The view the player stands in, or walks into, by its index in the rooms' views,
/// counting from 0 (`records.room_views` counts from 1).
view: u8,
/// The place whose screen shows, or the news report while it plays; null while the player
/// walks the rooms.
place: ?rooms.Place = null,
/// The page the CD player shows, while it's open.
cd_player_page: ?usize = null,
};
pub const Flight = struct {
hud: *const hud.State,
/// What drawing keeps of the display, as it last drew it: what flashed, where each
/// instrument drew, and how far the launch's caption has typed.
drawing: *const hud.Drawing,
player: *const input.Player,
/// What the display's frame draws the clock, the view's name, the caption and the status
/// lights from (`hud.Frame`): the time played, the game's variables, last frame's view, the
/// game's strings, and whether the game is a network one.
play: engine.game.main.PlayTime = .{},
variables: ?*const engine.vm.Variables = null,
last_view: camera.View = .cockpit,
strings: ?*const engine.game.language.Language = null,
multiplayer: bool = false,
/// The ship whose line the radio's window names, which the radar marks
/// (`radio.Radio.speakingShip`); none for nobody's.
speaker: ?u16 = null,
/// The string of the speaker's name the radio's window writes (`radio.Radio.shownName`);
/// none while it writes none.
speaker_name: ?u16 = null,
};
pub const Camera = struct {
/// The camera, which cuts to a script's switch of view at once and asks the game for it
/// (`camera.Camera.ask`).
camera: *camera.Camera,
/// The drawn frame's copy of the view (`main.Drawn.player`), which a script's switch of view
/// switches at once, and which the switch goes by.
viewing: *camera.Viewing,
bounds: camera.Viewing.Bounds = .{},
/// The time the camera's views switch by (`main.Clock.viewTime`).
now: u32,
/// The player's ship, which a view follows unless a script names another object.
player: u16,
};
};
/// Where the player is in the rooms, as `on_room_changed` tells it: the view, and the place whose
/// screen shows.
const Room = struct {
view: u8,
place: ?rooms.Place,
};
/// The presentation side of mods' scripts.
pub const Presentation = struct {
gpa: Allocator,
runtime: *Runtime,
runner: running.Runner,
lists: std.EnumArray(Place, running.List) = .initFill(.empty),
layers: std.EnumArray(drawing.Which, drawing.Layer) = .initFill(.{}),
assets: drawing.Assets = .{},
/// The menu scripts' screens that stand in for the front end's own (`front_end.zig`).
standing: front_end.Standing = .{},
/// What each layer is drawn on this frame.
views: std.EnumArray(drawing.Which, ?drawing.View) = .initFill(null),
/// What the driver told of the last frame, which the packages reach the game through.
host: ?Host = null,
/// The game's scripts while a game runs, which the scripts' events go to.
game: ?*game_module.Game = null,
/// The events the scripts sent to the game's scripts since the game last ran, whose data is
/// still in this state (`sendEvents`).
waiting: events.Events,
/// The keys held, which presses and releases are told against.
keys: std.bit_set.Static(key_codes) = .empty,
/// The actions whose controls were held last frame.
actions: std.EnumSet(controls.Action) = .empty,
/// The window's size last frame.
window: ?[2]u32 = null,
/// Where the player was in the rooms last frame; null while they weren't on screen.
room: ?Room = null,
/// The page a script asked the CD player to turn to (`rooms.set_cd_player_page`), until the CD
/// player takes it (`takeCdPlayerPage`).
cd_player_request: ?usize = null,
/// The script sounds and their cache.
sounds: audio.Sounds = .{},
/// The path of the piece of music that was playing last frame, for detecting changes
/// (`on_music_changed`); null if none was.
music: ?hog_snd.Music.Path = null,
/// Starts the `Menu` scripts of `opened`, which can read `held`, the records. `version` is
/// OpenReliant's version. Returns null if no mod has player or menu scripts.
pub fn start(gpa: Allocator, io: Io, opened: []const Mod, held: *records.Records, version: []const u8, shared: runtime.Shared) Allocator.Error!?*Presentation {
const any = for (opened) |*mod| {
if (hasScripts(mod)) break true;
} else false;
if (!any) return null;
const shown = try gpa.create(Presentation);
const scripts = Runtime.create(gpa, io, opened, .{ .side = .presentation, .limits = limits, .seed = load.seed, .version = version, .shared = shared }) catch |err| {
gpa.destroy(shown);
return err;
};
shown.* = .{ .gpa = gpa, .runtime = scripts, .runner = undefined, .waiting = .{ .gpa = gpa, .runtime = scripts } };
shown.runner = .init(gpa, scripts, &shown.lists.values);
errdefer shown.stop();
const state = scripts.state;
records.register(state);
records.push(state, held, false);
scripts.setPackage(.records);
packages.push(scripts);
objects.register(scripts);
interfaces.Interfaces.register(state);
shown.runner.interfaces.push(state);
scripts.setPackage(.interfaces);
scripts.presentation = shown;
scripts.runner = &shown.runner;
try shown.startScripts(.menu, false);
return shown;
}
/// Stops the scripts, as OpenReliant quits.
pub fn stop(shown: *Presentation) void {
shown.waiting.deinit();
shown.runner.deinit();
shown.sounds.deinit(shown.gpa);
for (&shown.layers.values) |*layer| layer.deinit(shown.gpa);
shown.assets.deinit(shown.gpa);
shown.standing.deinit(shown.gpa);
shown.runtime.destroy();
shown.gpa.destroy(shown);
}
/// Reads the folder mods' scripts again, and starts the menu scripts again, with `on_init`, as
/// the console's `reload` does. The player scripts start again with the game's
/// (`startGame`).
pub fn reload(shown: *Presentation) Allocator.Error!void {
shown.runner.stopAll(shown.lists.getPtr(.menu));
shown.sounds.stop(.menu);
try shown.runtime.recompileFolders();
try shown.startScripts(.menu, false);
}
/// The presentation side whose script makes `call`. Raises an error from a game script.
pub fn of(call: Call) *Presentation {
return call.runtime().presentation orelse call.raise("only player and menu scripts can use it", .{});
}
/// What the driver told of the last frame. Raises an error before the first.
pub fn hostOf(call: Call) Host {
return of(call).host orelse call.raise("can only be used once frames are drawn", .{});
}
/// Starts the scripts each mod lists for `place`, in load order.
fn startScripts(shown: *Presentation, comptime place: Place, loading: bool) Allocator.Error!void {
for (shown.runtime.mods, 0..) |*mod, at| {
var listed = listedScripts(mod, place);
if (listed.next() == null) continue;
listed = listedScripts(mod, place);
const context = try shown.runtime.open(@intCast(at), familyOf(place), null);
while (listed.next()) |name| _ = try shown.runner.start(shown.lists.getPtr(place), context, name, false, null, loading);
}
}
/// Starts the `Player` scripts as a game starts, with `game`, the game's scripts if any mod
/// has some, and `all`, the game's objects; `loading` as `Game.start` has it.
pub fn startGame(shown: *Presentation, game: ?*game_module.Game, all: *create.Objects, loading: bool) Allocator.Error!void {
shown.endGame();
shown.game = game;
shown.runtime.objects = all;
try shown.startScripts(.player, loading);
}
/// Stops the `Player` scripts as the game ends.
pub fn endGame(shown: *Presentation) void {
shown.resetRegisteredCamera();
shown.runner.stopAll(shown.lists.getPtr(.player));
shown.sounds.stop(.player);
shown.runtime.mod_shaders.forgetGiven();
shown.runtime.dropPlayerSelf();
shown.waiting.clear();
shown.game = null;
shown.runtime.objects = null;
}
/// Points the player scripts' `self` at the mission's player ship, then tells the scripts that
/// `mission` has started.
pub fn missionStarted(shown: *Presentation, mission: engine_hooks.Mission) void {
shown.runtime.followPlayer();
shown.runner.callAll(.on_mission_start, .{ .mission = mission });
}
/// Tells the scripts that the mission has ended as `outcome` says.
pub fn missionEnded(shown: *Presentation, outcome: engine_hooks.Outcome) void {
shown.resetRegisteredCamera();
shown.runner.callAll(.on_mission_end, .{ .outcome = outcome });
}
/// A mission transition must not keep a camera callback's subject from the previous scene.
fn resetRegisteredCamera(shown: *Presentation) void {
shown.runtime.registries.resetCamera(shown.runtime);
}
/// Sets what compiles and draws the scripts' post effects, or null for nothing
/// (`postprocessing.Registry.setHost`). Call it with null before the host is destroyed.
pub fn setEffectHost(shown: *Presentation, host: ?postprocessing.EffectHost) void {
shown.runtime.post_effects.setHost(host);
}
/// Gives the objects of `all`, the drawn frame's copy, the surface functions the player
/// scripts gave them (`shaders.Registry.dress`), once the scripts' frame has run.
pub fn dressObjects(shown: *Presentation, all: *create.Objects) void {
shown.runtime.mod_shaders.dress(all);
}
/// The menu scripts' screens that stand in for the front end's own, as the front end reaches
/// them (`front_end.scripted`).
pub fn scripted(shown: *Presentation) @import("openreliant").engine.genilib.interf.Scripted {
return front_end.scripted(shown);
}
/// The movie a menu script asked to play (`ui.play_movie`), if one did, which stays valid until
/// the next is asked for.
pub fn takeMovie(shown: *Presentation) ?[]const u8 {
return front_end.takeMovie(shown);
}
/// Sets what compiles and draws the scripts' surface and lighting functions, or null for nothing
/// (`shaders.Registry.setHost`). Call it with null before the host is destroyed.
pub fn setShaderHost(shown: *Presentation, host: ?shaders.ShaderHost) void {
shown.runtime.mod_shaders.setHost(host);
}
/// What finds the surface functions the planets name for their atmospheres
/// (`shaders.Registry.surfaceNames`).
pub fn surfaceNames(shown: *Presentation) openreliant.engine.game.create.atmosphere.SurfaceNames {
return shown.runtime.mod_shaders.surfaceNames();
}
/// The passes of the post effects the scripts have enabled, in the order they draw.
pub fn effectPasses(shown: *const Presentation, buffer: *[postprocessing.max_effects]postprocessing.Pass) []const postprocessing.Pass {
return shown.runtime.post_effects.passes(buffer);
}
/// The page a script asked the CD player to turn to since the CD player last took one; null
/// for none.
pub fn takeCdPlayerPage(shown: *Presentation) ?usize {
defer shown.cd_player_request = null;
return shown.cd_player_request;
}
/// Tells the scripts of the mod `mod` that the player set its option `option` to `value`.
pub fn optionChanged(shown: *Presentation, mod: []const u8, option: []const u8, value: mod_options.Value) void {
shown.runner.callMod(mod, .on_option_changed, .{ .key = option, .value = value });
}
/// Tells the scripts that `key` went down or up. A key held down that the window repeats is
/// told once.
pub fn key(shown: *Presentation, pressed: input.Key, down: bool) void {
const code = @backingInt(pressed);
if (shown.keys.isSet(code) == down) return;
shown.keys.setValue(code, down);
shown.runtime.registries.input(shown.runtime, pressed, down);
if (down) {
shown.runner.callAll(.on_key_press, .{ .key = pressed });
} else {
shown.runner.callAll(.on_key_release, .{ .key = pressed });
}
}
/// Runs a frame of the scripts: clears the last frame's drawing, reports changes to the window
/// size, the player's place in the rooms, the music and the actions used, then calls
/// `on_frame`.
pub fn frame(shown: *Presentation, host: Host) void {
shown.host = host;
shown.views = host.views;
for (&shown.layers.values) |*layer| layer.clear();
shown.assets.startFrame();
shown.sounds.forgetEnded();
if (shown.window) |last| {
if (!std.mem.eql(u32, &last, &host.window)) shown.runner.callAll(.on_window_resized, .{ .width = host.window[0], .height = host.window[1] });
}
shown.window = host.window;
const room: ?Room = if (host.rooms) |where| .{ .view = where.view, .place = where.place } else null;
if (!std.meta.eql(room, shown.room)) {
shown.room = room;
shown.runner.callAll(.on_room_changed, if (room) |now| .{ .view = @as(u32, now.view) + 1, .place = now.place } else .{ .view = null, .place = null });
}
shown.tellMusic(if (host.sound) |sound| sound.pieceOn() else null);
var held: std.EnumSet(controls.Action) = .empty;
if (host.flying) {
for (std.enums.values(controls.Action)) |action| {
if (!host.devices.active(action, false)) continue;
held.insert(action);
if (!shown.actions.contains(action)) shown.runner.callAll(.on_action, .{ .action = @tagName(action) });
}
}
shown.actions = held;
const registry = &shown.runtime.input_actions;
host.devices.mod_actions = registry;
// Callbacks may register or close contexts; fixed entry slots keep the walk valid.
const count = registry.count;
for (0..count) |index| {
if (registry.pressed(index, host.devices, host.flying)) {
// A handler can reload registration slots. Keep this event's name stable.
const name = registry.entries[index].name;
shown.runner.callAll(.on_action, .{ .action = std.mem.sliceTo(&name, 0) });
}
}
shown.runner.advance(host.seconds);
shown.runner.callAll(.on_frame, .{ .seconds = host.seconds });
shown.runtime.registries.frame(shown.runtime, host.seconds);
}
/// Calls `on_music_changed` if the piece playing, given by its `path` or null for none, differs
/// from last frame's.
fn tellMusic(shown: *Presentation, path: ?[]const u8) void {
if (samePiece(path, if (shown.music) |*last| last.slice() else null)) return;
shown.music = if (path) |playing| .of(playing) else null;
shown.runner.callAll(.on_music_changed, .{ .piece = if (path) |playing| hog_snd.pieceName(playing) else null });
}
/// Where the mods' displays put the game's instruments of the flight display this frame, and
/// which they stand in for: none while the display's layer isn't shown, as the displays don't
/// draw then.
pub fn instrumentPlacements(shown: *const Presentation) std.EnumArray(hud.Instrument, hud.Placement) {
if (shown.views.get(.hud) == null) return .initFill(.{});
return shown.runtime.registries.placements();
}
/// Where the displays put the parts of the game's instruments this frame
/// (`hud.Frame.parts`).
pub fn partPlacements(shown: *const Presentation) std.EnumArray(hud.parts.Part, hud.parts.Placement) {
if (shown.views.get(.hud) == null) return .initFill(.{});
return shown.runtime.registries.partPlacements();
}
/// Draws what the scripts drew on `which` this frame into `into`, where it's shown. `sight`
/// places what they drew in the world. First, the pictures taken out of the cache are freed
/// (`drawing.Assets.release`).
pub fn draw(shown: *Presentation, which: drawing.Which, into: device.Device, sight: ?hud.Sight) Allocator.Error!void {
shown.assets.release(shown.gpa);
const view = shown.views.get(which) orelse return;
try shown.layers.getPtrConst(which).draw(into, view, sight);
}
/// `core.send_global_event` from a player or menu script: the event waits until the game
/// next runs, when it goes to the game's scripts (`sendEvents`). Takes `payload` over.
pub fn sendToGame(shown: *Presentation, call: Call, name: []const u8, payload: data.Data) void {
if (shown.game == null) {
shown.runtime.release(payload.ref);
call.raise("events can only be sent while a game runs", .{});
}
shown.waiting.send(call, .global, name, payload);
}
/// Hands the events the scripts sent since the game last ran over to the game's scripts, in the
/// order they were sent, with their data copied into the game's state (`data.transfer`). The
/// game's next update delivers them (`events.zig`). The driver calls it before the game runs
/// again, so the game's scripts get the events at the same update as if they had gone over at
/// once.
pub fn sendEvents(shown: *Presentation) void {
var sent = shown.waiting.take();
defer sent.deinit(shown.gpa);
for (sent.items) |event| {
defer shown.runtime.release(event.data.ref);
const game = shown.game orelse continue;
shown.handOver(game, event) catch log.warn("out of memory sending the event {s}", .{event.name.slice()});
}
}
/// Queues `event` for `game`'s scripts, with its data copied into the game's state.
fn handOver(shown: *Presentation, game: *game_module.Game, event: events.Pending) Allocator.Error!void {
const copied = data.transfer(shown.runtime.state, event.data.ref, game.runtime) orelse return error.OutOfMemory;
try game.runner.events.add(.{ .to = event.to, .name = event.name, .data = .{ .ref = copied } });
}
};
/// Whether the music paths `one` and `other` name the same piece, ignoring case as Windows does.
/// Two nulls, for no music, count as the same.
fn samePiece(one: ?[]const u8, other: ?[]const u8) bool {
const first = one orelse return other == null;
const second = other orelse return false;
return std.ascii.eqlIgnoreCase(first, second);
}
test samePiece {
try std.testing.expect(samePiece(null, null));
try std.testing.expect(samePiece("music\\New_Pensive.wav", "MUSIC\\new_pensive.wav"));
try std.testing.expect(!samePiece("music\\one.wav", null));
try std.testing.expect(!samePiece(null, "music\\one.wav"));
try std.testing.expect(!samePiece("music\\one.wav", "music\\two.wav"));
}
/// The family of the scripts of `place`.
fn familyOf(place: Place) script.Family {
return switch (place) {
.menu => .menu,
.player => .player,
};
}
/// Whether `mod` lists player or menu scripts.
fn hasScripts(mod: *const Mod) bool {
for (std.enums.values(Place)) |place| {
var listed = listedScripts(mod, place);
if (listed.next() != null) return true;
}
return false;
}
/// The scripts `mod` lists for `place`, in order.
fn listedScripts(mod: *const Mod, place: Place) script.List {
const kind: script.Kind = switch (place) {
.menu => .menu,
.player => .player,
};
return .of(mod.manifest.value(script.section, kind.key()) orelse "");
}
/// Player and menu scripts from the mods `made`, each a folder of files, and the game's scripts
/// over a mission that holds the player's Predator.
const Fixture = struct {
tmp: std.testing.TmpDir,
mods: mods.Mods,
arena: std.heap.ArenaAllocator,
held: records.Records,
mission: engine.game.gameobj.testing.Mission,
shown: *Presentation,
devices: input.Devices = .{},
font: hud.Opened,
/// Where the frames have the player in the rooms; null while they aren't on screen.
rooms: ?Host.Rooms = null,
/// The sound system for the frames, if any.
sound: ?*hog_snd.Sound = null,
fn init(fixture: *Fixture, made: []const struct { []const u8, []const struct { []const u8, []const u8 } }) !void {
return fixture.initShared(made, .{});
}
/// `init`, with what the mods share; where it has a registry of options, the load scripts run
/// first, to declare the pages the others read.
fn initShared(fixture: *Fixture, made: []const struct { []const u8, []const struct { []const u8, []const u8 } }, shared: runtime.Shared) !void {
const gpa = std.testing.allocator;
const io = std.testing.io;
fixture.* = .{ .tmp = std.testing.tmpDir(.{ .iterate = true }), .mods = undefined, .arena = .init(gpa), .held = undefined, .mission = undefined, .shown = undefined, .font = .open(try openreliant.fnt.Font.parse(comptime openreliant.fnt.testing.font(false)), null) };
errdefer fixture.tmp.cleanup();
errdefer fixture.arena.deinit();
try load.testing.makeMods(io, fixture.tmp.dir, made);
fixture.mods = try .open(gpa, io, fixture.tmp.dir, null);
errdefer fixture.mods.close(gpa);
fixture.held = try load.testing.records3(fixture.arena.allocator());
try fixture.mission.init(gpa);
errdefer fixture.mission.deinit();
_ = try fixture.mission.add(.of(.predator), @splat(0));
if (shared.option_pages != null) try load.run(gpa, io, fixture.mods.list, &fixture.held, "0.7.0", shared);
fixture.shown = (try Presentation.start(gpa, io, fixture.mods.list, &fixture.held, "0.7.0", shared)).?;
}
fn deinit(fixture: *Fixture) void {
fixture.shown.stop();
fixture.mission.deinit();
fixture.arena.deinit();
fixture.mods.close(std.testing.allocator);
fixture.tmp.cleanup();
}
/// A frame of `seconds`, in a window of `window`, with the menus shown, and the player where
/// `rooms` says.
fn frame(fixture: *Fixture, seconds: f32, window: [2]u32) void {
var host: Host = .{ .seconds = seconds, .devices = &fixture.devices, .window = window, .rooms = fixture.rooms, .sound = fixture.sound };
host.views.set(.ui, .{ .font = &fixture.font, .gpa = std.testing.allocator, .screen = window, .scale = 2 });
fixture.shown.frame(host);
}
};
test "menu actions dispatch qualified press edges in flight and close on reload" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nMenu=a.luau\n" },
.{
"a.luau",
\\local input = require("openreliant.input")
\\local action = input.register_action("pulse", {label = "Pulse", key = "f12", modifier = "shift"})
\\local count = 0
\\assert(action == "a:pulse")
\\assert(not pcall(function() input.register_action("pulse", {label = "Duplicate"}) end))
\\return {engine_handlers = {on_action = function(name)
\\ if name == action then
\\ count += 1; assert(count == 1 and input.action_down(action) and input.action_down("pulse"))
\\ end
\\end, on_frame = function()
\\ require("openreliant.ui").text(vector.zero, tostring(count))
\\end}}
},
},
}});
defer fixture.deinit();
const index = fixture.shown.runtime.input_actions.find("a:pulse").?;
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .flying = true };
fixture.shown.frame(host);
fixture.devices.keyboard.down[@backingInt(input.Key.f12)] = true;
fixture.devices.keyboard.down[input.scan.left_shift] = true;
fixture.shown.frame(host);
try std.testing.expect(fixture.shown.runtime.input_actions.entries[index].held);
try std.testing.expectEqualStrings("1", fixture.shown.layers.get(.ui).text.items);
fixture.shown.frame(host);
host.flying = false;
fixture.shown.frame(host);
try std.testing.expect(!fixture.shown.runtime.input_actions.entries[index].held);
try fixture.shown.reload();
host.flying = true;
fixture.shown.frame(host);
try std.testing.expect(!fixture.shown.runtime.input_actions.entries[index].ready);
}
test "registered views, displays and screens execute and close with their contexts" {
const gpa = std.testing.allocator;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\nMenu=menu.luau\n" },
.{
"player.luau",
\\local camera = require("openreliant.camera")
\\local hud = require("openreliant.hud")
\\local util = require("openreliant.util")
\\local view = camera.register_view("follow", {letterbox = true, frame = function(ship, seconds)
\\ return {position = ship.position + vector.create(0, -50, -100), orientation = util.from_angles(vector.zero)}
\\end})
\\hud.register_display("status", {frame = function() hud.text(vector.zero, "registered display") end})
\\-- Within the mod, its own names work as well as the qualified ones.
\\assert(hud.set_display_enabled("status", true) and hud.set_display_enabled("a:status", true))
\\assert(not hud.set_display_enabled("b:status", true) and not hud.set_display_enabled("no such", true))
\\return {engine_handlers = {on_frame = function()
\\ assert(camera.set_view("follow") and camera.view == view)
\\ assert(camera.set_view(view))
\\ assert(camera.view == view)
\\end}}
},
.{
"menu.luau",
\\local ui = require("openreliant.ui")
\\local screen = ui.register_screen("panel", {frame = function() ui.text(vector.zero, "registered screen") end,
\\ key = function(key, down) if key == "escape" and down then assert(ui.show_screen(nil)) end end})
\\assert(ui.show_screen("panel") and ui.show_screen(screen))
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 } };
const layer: drawing.View = .{ .font = &fixture.font, .gpa = gpa, .screen = .{ 640, 480 }, .scale = 1 };
host.views.set(.hud, layer);
host.views.set(.ui, layer);
fixture.shown.frame(host);
try std.testing.expectEqualStrings("registered display", fixture.shown.layers.get(.hud).text.items);
try std.testing.expectEqualStrings("registered screen", fixture.shown.layers.get(.ui).text.items);
try engine.surrender.math.testing.expectVector(.{ 0, -50, -100 }, view.place.position);
try std.testing.expectEqual(engine.game.camera.letterbox, view.bars);
fixture.shown.key(.escape, true);
try std.testing.expectEqual(null, fixture.shown.runtime.registries.selected_screen);
fixture.shown.endGame();
try std.testing.expectEqual(engine.game.camera.View.cockpit, viewing.view);
try std.testing.expectEqual(null, fixture.shown.runtime.registries.find(.display, "a:status"));
try fixture.shown.reload();
try std.testing.expect(fixture.shown.runtime.registries.find(.screen, "a:panel") != null);
}
test "a display stands in for the game's instruments and reads what they show" {
const gpa = std.testing.allocator;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\n" },
.{
"player.luau",
\\local hud = require("openreliant.hud")
\\local frames = 0
\\hud.register_display("radar", {replaces = {"gunnery", "radar"}, layout = {clock = {offset = vector.create(10, -5, 0), scale = 1.5}},
\\ parts = {radio_speaker = {offset = vector.create(4, 0, 0), align = "right", text = "COMMS"}, radio_face = {scale = 2, hidden = true}}, frame = function()
\\ frames += 1
\\ if frames == 3 then error("broken") end
\\end})
\\assert(not pcall(hud.register_display, "bad", {replaces = {"nothing"}, frame = function() end}))
\\assert(not pcall(hud.register_display, "small", {layout = {clock = {scale = 0}}, frame = function() end}))
\\assert(not pcall(hud.register_display, "where", {layout = {nothing = {scale = 2}}, frame = function() end}))
\\-- A picture takes no text, a part must be one of the game's, and its text short enough.
\\assert(not pcall(hud.register_display, "face", {parts = {radio_face = {text = "x"}}, frame = function() end}))
\\assert(not pcall(hud.register_display, "part", {parts = {nothing = {scale = 2}}, frame = function() end}))
\\assert(not pcall(hud.register_display, "long", {parts = {radio_speaker = {text = string.rep("x", 65)}}, frame = function() end}))
\\return {engine_handlers = {on_frame = function()
\\ local guns, missiles, radar, target = hud.guns, hud.missiles, hud.radar, hud.target
\\ hud.text(vector.zero, string.format("%s %s %d %s %d %s %d %d %s %s %d %d %s", tostring(hud.instruments_shown),
\\ table.concat(hud.replaced, ","), radar.range, tostring(radar.zooming), hud.kills, missiles.armed,
\\ missiles.left, #missiles.ring, table.concat(hud.open_windows, ","), tostring(guns.all), target.component,
\\ hud.bounds("radar").right, tostring(hud.bounds("clock"))))
\\ hud.text(vector.zero, string.format("|%d %s %s", hud.part_bounds("radio_speaker").right, hud.speaker_name, tostring(hud.part_bounds("radio_face"))))
\\end}}
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
var state: hud.State = .{};
var hud_drawing: hud.Drawing = .{};
state.radar_range = 1;
state.missiles.entries[0] = .{ .count = 2, .type = .of(.screamer) };
state.missiles.entries[1] = .{ .count = 4, .type = .of(.raptor) };
state.missiles.armed = 1;
state.windows.status.getPtr(.gunnery).phase = .open;
state.target = .{ .target = .at(0, 3), .slot = 0 };
hud_drawing.bounds.set(.radar, .{ .left = 1, .top = 2, .right = 30, .bottom = 40 });
hud_drawing.part_bounds.set(.radio_speaker, .{ .left = 5, .top = 6, .right = 50, .bottom = 16 });
var player: input.Player = .{};
player.kills.count = 7;
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
var strings_table: [2][]const u8 = .{ "", "Moose" };
const strings: engine.game.language.Language = .{ .strings = &strings_table };
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 }, .flight = .{ .hud = &state, .drawing = &hud_drawing, .player = &player, .strings = &strings, .speaker_name = 2 } };
host.views.set(.hud, .{ .font = &fixture.font, .gpa = gpa, .screen = .{ 640, 480 }, .scale = 1 });
fixture.shown.frame(host);
// The scripts read the replaced instruments in the game's order, as the display has them.
const placed = fixture.shown.instrumentPlacements();
try std.testing.expect(placed.get(.radar).hidden and placed.get(.gunnery).hidden and !placed.get(.clock).hidden);
try std.testing.expectEqual(hud.Placement{ .offset = .{ 10, -5 }, .scale = 1.5 }, placed.get(.clock));
try std.testing.expectEqualStrings("true radar,gunnery 1 false 7 raptor 4 2 gunnery true 3 30 nil|50 Moose nil", fixture.shown.layers.get(.hud).text.items);
// The parts it places: the speaker's name moved, aligned right and given other words, and the
// face drawn larger, but hidden.
const parts = fixture.shown.partPlacements();
const speaker = parts.get(.radio_speaker);
try std.testing.expectEqual(hud.Placement{ .offset = .{ 4, 0 } }, speaker.place);
try std.testing.expectEqual(hud.Align.right, speaker.alignment.?);
try std.testing.expectEqualStrings("COMMS", speaker.words.?.slice());
try std.testing.expectEqual(hud.Placement{ .scale = 2, .hidden = true }, parts.get(.radio_face).place);
// While the display's layer isn't shown, the displays don't draw, and the instruments are as
// the game has them.
var shut = host;
shut.views.set(.hud, null);
fixture.shown.frame(shut);
try std.testing.expectEqual(hud.Placement{}, fixture.shown.instrumentPlacements().get(.radar));
// As its frame fails, the game's instruments come back as they were.
fixture.shown.frame(host);
try std.testing.expect(fixture.shown.instrumentPlacements().get(.radar).hidden);
fixture.shown.frame(host);
try std.testing.expectEqual(hud.Placement{}, fixture.shown.instrumentPlacements().get(.radar));
try std.testing.expectEqual(hud.Placement{}, fixture.shown.instrumentPlacements().get(.clock));
fixture.shown.endGame();
}
test "a display changes its layout after it registers" {
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\n" },
.{
"player.luau",
\\local hud = require("openreliant.hud")
\\hud.register_display("radio", {layout = {clock = {scale = 2}}, parts = {radio_face = {scale = 2}}, frame = function() end})
\\-- The layout follows the window, and the parts stay, as the table leaves them out.
\\assert(hud.set_display_layout("radio", {layout = {clock = {offset = vector.create(5, 0, 0)}}}))
\\-- A mistake changes nothing, and a name not registered isn't one.
\\assert(not pcall(hud.set_display_layout, "radio", {layout = {clock = {scale = 0}}, parts = {}}))
\\assert(not pcall(hud.set_display_layout, "radio", {placement = {}}))
\\assert(not hud.set_display_layout("b:radio", {}) and not hud.set_display_layout("nothing", {}))
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
defer fixture.shown.endGame();
// The displays place the instruments while the flight display's layer shows.
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 } };
host.views.set(.hud, .{ .font = &fixture.font, .gpa = std.testing.allocator, .screen = .{ 640, 480 }, .scale = 1 });
fixture.shown.frame(host);
try std.testing.expectEqual(hud.Placement{ .offset = .{ 5, 0 } }, fixture.shown.instrumentPlacements().get(.clock));
try std.testing.expectEqual(hud.Placement{ .scale = 2 }, fixture.shown.partPlacements().get(.radio_face).place);
}
test "a display reads the cockpit's instruments in any view" {
const gpa = std.testing.allocator;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\n" },
.{
"player.luau",
\\local hud = require("openreliant.hud")
\\return {engine_handlers = {on_frame = function()
\\ local g, s, c = hud.gauges, hud.ship_status, hud.clock
\\ hud.text(vector.zero, string.format("%d %d %.2f %.2f %.2f %.2f %s|%d %d %d %d %d %d|%d %d|%s|%d:%02d|%s|%s|%d %d",
\\ g.speed, g.asked, g.speed_share, g.throttle_share, g.throttle_brightness, g.charge, tostring(g.nova),
\\ s.shields.left, s.shields.aft, s.armor.left, s.armor.right, s.reserve_fore, s.reserve_aft,
\\ hud.fuel, hud.countermeasures, table.concat(hud.lights, ","), c.minutes, c.seconds,
\\ hud.view_name, hud.caption, #hud.view_name, #hud.caption))
\\end}}
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
const all = fixture.mission.objects;
all.mission_number = 1;
const slot = fixture.mission.slot(0);
const combat = slot.combat.?;
// Half throttle at a quarter of its top speed, and its guns half charged.
slot.object.throttle = 0.5;
slot.object.speed = slot.flight.?.max_speed / 4;
slot.object.gun_charge = combat.gun_energy / 2;
slot.object.afterburner_fuel = 7 * engine.game.main.ticks_per_second + 50;
slot.object.countermeasures = 12;
slot.object.reverse_thrust = true;
// Full shields, its left armour down to two arcs' worth, and five arcs' worth shifted fore.
slot.object.shields = .all(combat.fullShields());
slot.object.armor = .all(combat.fullArmor());
slot.object.armor.left = @floatFromInt(combat.armor_class * 2);
var player: input.Player = .{};
player.matching_speed = true;
player.shield_reserves = .{ .fore = 5 * @as(f32, @floatFromInt(combat.shield_power)) };
var state: hud.State = .{};
var hud_drawing: hud.Drawing = .{};
state.smart_targeting = true;
state.showIcon(.ecm, .flash);
state.devices.getPtr(.cloak).setting = .absent;
state.caption = .{ .on = true };
hud_drawing.caption = .{ .shown = 6 };
// The strings for the date of mission 1 and the name of the chase view.
var strings_table: [1000][]const u8 = @splat(" ");
strings_table[hud.Caption.date(1).? - 1] = "Mai 3\xE9";
const chase_name = engine.game.camera.View.chase.name().?;
strings_table[chase_name - 1] = "Chase";
const strings: engine.game.language.Language = .{ .strings = &strings_table };
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
viewing.view = .chase;
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 }, .flight = .{
.hud = &state,
.drawing = &hud_drawing,
.player = &player,
.play = .{ .minutes = 3, .seconds = 7 },
.last_view = .chase,
.strings = &strings,
} };
host.views.set(.hud, .{ .font = &fixture.font, .gpa = gpa, .screen = .{ 640, 480 }, .scale = 1 });
fixture.shown.frame(host);
const asked, const made = hud.Cluster.Gauges.of(slot).?.figures();
var expected: [256]u8 = undefined;
// In the chase view, where the game draws none of them, the readings are as the instruments
// would show them; the caption has typed the date's six letters, the last from the game's code
// page, which takes two bytes in UTF-8 and goes back to one as the display draws it.
const text = try std.mem.print(&expected, "{d} {d} 0.25 0.50 0.75 0.50 false|5 5 1 5 4 0|7 12|match_speed,smart_targeting,ecm,reverse_thrust|3:07|Chase|Mai 3\xE9|5 7", .{ made, asked });
try std.testing.expectEqualStrings(text, fixture.shown.layers.get(.hud).text.items);
fixture.shown.endGame();
}
test "a display reads the radar's contacts and the target display" {
const gpa = std.testing.allocator;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\n" },
.{
"player.luau",
\\local hud = require("openreliant.hud")
\\return {engine_handlers = {on_frame = function()
\\ local contact, shown = hud.radar.contacts[1], hud.target_display
\\ hud.text(vector.zero, string.format("%d %d %s %d %d %d|%s %s %s %d %d %d %d %s %s %.2f %s %s",
\\ #hud.radar.contacts, contact.object.slot, contact.look, contact.at.x, contact.at.y, contact.height,
\\ shown.form, shown.name, tostring(shown.pilot), shown.range, shown.speed, shown.shields.left,
\\ shown.armor.aft, shown.subtarget_class, shown.subtarget, shown.subtarget_armor, tostring(shown.hull),
\\ table.concat(shown.hits, ",")))
\\end}}
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
const all = fixture.mission.objects;
// A hostile Sabre ahead, which is the player's target and the display's, its type named.
const sabre = try fixture.mission.add(.of(.sabre), .{ 0, 0, 40000 });
const slot = fixture.mission.slot(sabre);
slot.object.flags.targetable = true;
slot.object.side = .hostile;
fixture.mission.tables.combat[engine.game.gameobj.Type.of(.sabre).number()].name = 700;
var strings_table: [2000][]const u8 = @splat(" ");
strings_table[700 - 1] = "Sabre";
// The player's order picks out its engine, a quarter of whose armour is left.
var part: engine.game.objects.Model.Part = .{ .hidden = false, .parent = null, .origin = @splat(0), .object = .{ .flags = .{}, .position = @splat(0), .radius = 0, .levels = &.{} } };
part.class = .engine;
part.component_armor = 200;
part.armor = 50;
slot.components[0] = ∂
slot.object.component_count = 1;
fixture.mission.slot(0).orders[0].target = .at(sabre, 0);
strings_table[hud.target_display.named(.engine).?.name - 1] = "Engine";
// Its pilot, as the game gives a hostile ship until the mission names another.
strings_table[hud.target_display.pilotName(all, slot).? - 1] = "Ace";
const strings: engine.game.language.Language = .{ .strings = &strings_table };
var state: hud.State = .{};
var hud_drawing: hud.Drawing = .{};
state.target = .{ .target = .at(sabre, null), .slot = sabre };
// Its fore quadrant flashes on its schematic.
hud_drawing.flashes.target_hits = .initOne(.fore);
var player: input.Player = .{};
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 }, .flight = .{ .hud = &state, .drawing = &hud_drawing, .player = &player, .strings = &strings } };
host.views.set(.hud, .{ .font = &fixture.font, .gpa = gpa, .screen = .{ 640, 480 }, .scale = 1 });
fixture.shown.frame(host);
// The radar shows the Sabre alone, as the target, up the screen; the target display its name,
// its pilot's, its range, its rings, its engine and the hit on it, and no hull bar, the Sabre
// having no model.
var contacts: hud.Radar.Contacts = .of(all, state.radar_range, null);
const contact = contacts.next().?;
const facts: hud.target_display.Facts = .of(all, sabre);
const rings = hud.ShipStatus.rings(slot).?;
const form = hud.target_display.Form.of(hud.targetWindow(slot)).?;
var expected: [256]u8 = undefined;
const text = try std.mem.print(&expected, "1 {d} target {d} {d} {d}|{s} Sabre Ace {d} {d} {d} {d} engine Engine 0.26 nil fore", .{
sabre, contact.at[0], contact.at[1], contact.height,
@tagName(form), facts.range, facts.speed, std.math.clamp(rings.shields[0], 0, hud.ShipStatus.arc_levels),
std.math.clamp(rings.armor[3], 0, hud.ShipStatus.arc_levels),
});
try std.testing.expectEqualStrings(text, fixture.shown.layers.get(.hud).text.items);
try std.testing.expect(contact.at[1] < 0);
fixture.shown.endGame();
}
test "a display reads the windows and the display's text" {
const gpa = std.testing.allocator;
var fixture: Fixture = undefined;
try fixture.init(&.{.{
"a",
&.{
.{ "mod.ini", "[Scripts]\nPlayer=player.luau\n" },
.{
"player.luau",
\\local hud = require("openreliant.hud")
\\return {engine_handlers = {on_frame = function()
\\ local d, p, w, o = hud.damage, hud.power, hud.wingmen, hud.objectives
\\ hud.text(vector.zero, string.format("%.2f %.2f %.2f|%d %d %d|%d %d %d %.2f|%d %d %s %s %d %s|%s|%s|%s|%s|%s",
\\ d.weapons, d.engines, d.shields, p.shields, p.weapons, p.engines,
\\ #w, w[1].object.slot, w[1].number, w[1].armor,
\\ o.showing, #o.list, o.list[1].name, tostring(o.list[1].current), o.list[2].number, tostring(o.list[2].name),
\\ table.concat(hud.comms, ","), table.concat(hud.messages, ","), hud.subtitle, hud.key_prompt,
\\ hud.jump_prompt))
\\ hud.power_ball(vector.create(10, 20, 0), vector.create(40, 30, 0), {alpha = 0.5})
\\ hud.power_ball(vector.zero)
\\end}}
},
},
}});
defer fixture.deinit();
try fixture.shown.startGame(null, fixture.mission.objects, false);
const all = fixture.mission.objects;
const slot = fixture.mission.slot(0);
// The player's ship: its systems worn, its power shifted, and the only ship of its wing.
slot.object.gun_condition = 0.25;
slot.object.armor_speed_factor = 0.5;
slot.object.shield_condition = 1;
slot.object.power_setting = .{ .x = 0.2, .y = -0.1, .z = 0 };
engine.game.mission.listPlayerWing(all, &.{0});
// Objectives: the first current, the second listed with no name, the rest hidden; the window
// shows the second.
var state: hud.State = .{};
const hud_drawing: hud.Drawing = .{};
const names: hud.Objectives.Names = .{ "Patrol", null, null, null, null, null, null, null, null, null };
state.objectives.own = &names;
state.objectives.states[0] = .current;
state.objectives.states[1] = .listed;
state.objectives.shown = 1;
state.messages.add("Bogey", 0);
state.subtitle.show(5);
state.key_prompt.action = .comms_window;
var player: input.Player = .{};
player.menu.items[0] = .{ .label = .{ .string = 4 }, .page = .top, .addressed = -1 };
player.menu.count = 1;
var variables: engine.vm.Variables = .{};
variables.ready.jump = .shown;
var strings_table: [10][]const u8 = @splat(" ");
strings_table[4 - 1] = "Target";
strings_table[5 - 1] = "Sub";
const strings: engine.game.language.Language = .{ .strings = &strings_table };
var view: engine.game.camera.Camera = .{};
var viewing: engine.game.camera.Viewing = .{};
var host: Host = .{ .seconds = 0.04, .devices = &fixture.devices, .window = .{ 640, 480 }, .camera = .{ .camera = &view, .viewing = &viewing, .now = 1, .player = 0 }, .flight = .{
.hud = &state,
.drawing = &hud_drawing,
.player = &player,
.variables = &variables,