-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
context.cc
1849 lines (1635 loc) · 67.5 KB
/
context.cc
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
// Copyright (C) 2016-2019 Google Inc.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
////////////////////////////////////////////////////////////////////////////////
#include "deepmind/engine/context.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "deepmind/engine/context_actions.h"
#include "deepmind/engine/context_entities.h"
#include "deepmind/engine/context_events.h"
#include "deepmind/engine/context_game.h"
#include "deepmind/engine/context_observations.h"
#include "deepmind/engine/context_pickups.h"
#include "deepmind/engine/lua_image.h"
#include "deepmind/engine/lua_maze_generation.h"
#include "deepmind/engine/lua_random.h"
#include "deepmind/engine/lua_text_level_maker.h"
#include "deepmind/include/deepmind_calls.h"
#include "deepmind/include/deepmind_hooks.h"
#include "deepmind/include/deepmind_model_getters.h"
#include "deepmind/level_generation/compile_map.h"
#include "deepmind/lua/bind.h"
#include "deepmind/lua/call.h"
#include "deepmind/lua/class.h"
#include "deepmind/lua/lua.h"
#include "deepmind/lua/n_results_or.h"
#include "deepmind/lua/push.h"
#include "deepmind/lua/push_script.h"
#include "deepmind/lua/read.h"
#include "deepmind/lua/stack_resetter.h"
#include "deepmind/lua/table_ref.h"
#include "deepmind/lua/vm.h"
#include "deepmind/model_generation/lua_model.h"
#include "deepmind/model_generation/lua_transform.h"
#include "deepmind/model_generation/model.h"
#include "deepmind/model_generation/model_getters.h"
#include "deepmind/model_generation/model_lua.h"
#include "deepmind/tensor/lua_tensor.h"
#include "deepmind/tensor/tensor_view.h"
#include "public/file_reader_types.h"
#include "public/level_cache_types.h"
#include "third_party/rl_api/env_c_api.h"
using deepmind::lab::Context;
extern "C" {
static void add_setting(void* userdata, const char* key, const char* value) {
return static_cast<Context*>(userdata)->AddSetting(key, value);
}
static void set_level_cache_settings(
void* userdata, bool local, bool global,
DeepMindLabLevelCacheParams level_cache_params) {
return static_cast<Context*>(userdata)->SetLevelCacheSetting(
local, global, level_cache_params);
}
static void set_level_name(void* userdata, const char* level_name) {
static_cast<Context*>(userdata)->SetLevelName(level_name);
}
static void set_level_directory(void* userdata, const char* level_directory) {
static_cast<Context*>(userdata)->SetLevelDirectory(level_directory);
}
static int init(void* userdata) {
return static_cast<Context*>(userdata)->Init();
}
static int start(void* userdata, int episode, int seed) {
return static_cast<Context*>(userdata)->Start(episode, seed);
}
static const char* error_message(void* userdata) {
return static_cast<Context*>(userdata)->ErrorMessage();
}
static void set_error_message(void* userdata, const char* error_message) {
static_cast<Context*>(userdata)->SetErrorMessage(error_message);
}
static int map_loaded(void* userdata) {
return static_cast<Context*>(userdata)->MapLoaded();
}
static const char* replace_command_line(void* userdata,
const char* old_commandline) {
return static_cast<Context*>(userdata)->GetCommandLine(old_commandline);
}
static const char* get_temporary_folder(void* userdata) {
return static_cast<Context*>(userdata)->TempDirectory().c_str();
}
static const char* next_map(void* userdata) {
return static_cast<Context*>(userdata)->NextMap();
}
static void update_inventory(void* userdata, bool is_spawning, bool is_bot,
int player_id, int gadget_count,
int gadget_inventory[], int persistent_count,
int persistents[], int stat_count,
int stat_inventory[], int powerup_count,
int powerup_time[], int gadget_held, float height,
float position[3], float velocity[3],
float view_angles[3]) {
static_cast<Context*>(userdata)->UpdateInventory(
is_spawning, is_bot, player_id, gadget_count, gadget_inventory,
persistent_count, persistents, stat_count, stat_inventory, powerup_count,
powerup_time, gadget_held, height, position, velocity, view_angles);
}
static int game_type(void* userdata) {
return static_cast<Context*>(userdata)->GameType();
}
static char team_select(void* userdata, int player_id,
const char* player_name) {
return static_cast<Context*>(userdata)->TeamSelect(player_id, player_name);
}
static bool update_player_info(void* userdata, int player_id, char* info,
int info_size) {
return static_cast<Context*>(userdata)->UpdatePlayerInfo(player_id, info,
info_size);
}
static bool has_alt_cameras(void* userdata) {
return static_cast<Context*>(userdata)->HasAltCameras();
}
static void set_has_alt_cameras(void* userdata, bool has_alt_camera) {
static_cast<Context*>(userdata)->SetHasAltCameras(has_alt_camera);
}
static void custom_view(void* userdata, int* width, int* height,
float position[3], float view_angles[3],
bool* render_player) {
static_cast<Context*>(userdata)->Game().GetCustomView(
width, height, position, view_angles, render_player);
}
static int run_lua_snippet(void* userdata, const char* command) {
std::size_t command_len = std::strlen(command);
return static_cast<Context*>(userdata)->RunLuaSnippet(command, command_len);
}
static void set_native_app(void* userdata, bool v) {
return static_cast<Context*>(userdata)->SetNativeApp(v);
}
static bool get_native_app(void* userdata) {
return static_cast<Context*>(userdata)->NativeApp();
}
static void set_mixer_seed(void* userdata, int v) {
return static_cast<Context*>(userdata)->SetMixerSeed(
static_cast<std::uint32_t>(v));
}
static void set_actions(void* userdata, double look_down_up,
double look_left_right, signed char move_back_forward,
signed char strafe_left_right, signed char crouch_jump,
int buttons_down) {
return static_cast<Context*>(userdata)->SetActions(
look_down_up, look_left_right, move_back_forward, strafe_left_right,
crouch_jump, buttons_down);
}
static void get_actions(void* userdata, double* look_down_up,
double* look_left_right, signed char* move_back_forward,
signed char* strafe_left_right,
signed char* crouch_jump, int* buttons_down) {
return static_cast<Context*>(userdata)->GetActions(
look_down_up, look_left_right, move_back_forward, strafe_left_right,
crouch_jump, buttons_down);
}
static int update_spawn_vars(void* userdata, char* spawn_var_chars,
int* num_spawn_var_chars,
int spawn_var_offsets[][2], int* num_spawn_vars) {
return static_cast<Context*>(userdata)->MutablePickups()->UpdateSpawnVars(
spawn_var_chars, num_spawn_var_chars, spawn_var_offsets, num_spawn_vars);
}
static int make_extra_entities(void* userdata) {
return static_cast<Context*>(userdata)->MutablePickups()->MakeExtraEntities();
}
static void read_extra_entity(void* userdata, int entity_index,
char* spawn_var_chars, int* num_spawn_var_chars,
int spawn_var_offsets[][2], int* num_spawn_vars) {
return static_cast<Context*>(userdata)->MutablePickups()->ReadExtraEntity(
entity_index, spawn_var_chars, num_spawn_var_chars, spawn_var_offsets,
num_spawn_vars);
}
static int dynamic_spawn_entity_count(void* userdata) {
return static_cast<Context*>(userdata)->Pickups().DynamicSpawnEntityCount();
}
static void read_dynamic_spawn_entity(void* userdata, int entity_index,
char* spawn_var_chars,
int* num_spawn_var_chars,
int spawn_var_offsets[][2],
int* num_spawn_vars) {
static_cast<Context*>(userdata)->Pickups().ReadDynamicSpawnEntity(
entity_index, spawn_var_chars, num_spawn_var_chars, spawn_var_offsets,
num_spawn_vars);
}
static void clear_dynamic_spawn_entities(void* userdata) {
static_cast<Context*>(userdata)
->MutablePickups()
->ClearDynamicSpawnEntities();
}
static int register_dynamic_items(void* userdata) {
return static_cast<Context*>(userdata)
->MutablePickups()
->RegisterDynamicItems();
}
static void read_dynamic_item_name(void* userdata, int item_index,
char* item_name) {
static_cast<Context*>(userdata)->Pickups().ReadDynamicItemName(item_index,
item_name);
}
static bool find_item(void* userdata, const char* class_name, int* index) {
return static_cast<Context*>(userdata)->MutablePickups()->FindItem(class_name,
index);
}
static int item_count(void* userdata) {
return static_cast<const Context*>(userdata)->Pickups().ItemCount();
}
static bool item(void* userdata, int index,
char* item_name, int max_item_name,
char* class_name, int max_class_name,
char* model_name, int max_model_name,
int* quantity, int* type, int* tag, int* move_type) {
return static_cast<const Context*>(userdata)->Pickups().GetItem(
index, item_name, max_item_name, class_name, max_class_name, model_name,
max_model_name, quantity, type, tag, move_type);
}
static void clear_items(void* userdata) {
static_cast<Context*>(userdata)->MutablePickups()->ClearItems();
}
static bool find_model(void* userdata, const char* model_name) {
return static_cast<Context*>(userdata)->FindModel(model_name);
}
static void model_getters(void* userdata, DeepmindModelGetters* model_getters,
void** model_data) {
static_cast<Context*>(userdata)->GetModelGetters(model_getters, model_data);
}
static void clear_model(void* userdata) {
static_cast<Context*>(userdata)->ClearModel();
}
static bool map_finished(void* userdata) {
return static_cast<Context*>(userdata)->Game().MapFinished();
}
static void set_map_finished(void* userdata, bool map_finished) {
static_cast<Context*>(userdata)->MutableGame()->SetMapFinished(map_finished);
}
static bool can_pickup(void* userdata, int entity_id, int player_id) {
return static_cast<Context*>(userdata)->MutablePickups()->CanPickup(
entity_id, player_id);
}
static bool override_pickup(void* userdata, int entity_id, int* respawn,
int player_id) {
return static_cast<Context*>(userdata)->MutablePickups()->OverridePickup(
entity_id, respawn, player_id);
}
static bool can_trigger(void* userdata, int entity_id, const char* target_name,
int player_id) {
return static_cast<Context*>(userdata)->CanTrigger(entity_id, target_name,
player_id);
}
static bool override_trigger(void* userdata, int entity_id,
const char* target_name, int player_id) {
return static_cast<Context*>(userdata)->OverrideTrigger(
entity_id, target_name, player_id);
}
static void trigger_lookat(void* userdata, int entity_id, bool looked_at,
const float position[3], int player_id) {
static_cast<Context*>(userdata)->TriggerLookat(entity_id, looked_at, position,
player_id);
}
static int reward_override(void* userdata, const char* reason_opt,
int player_id, int team,
const int* other_player_id_opt,
const float* origin_opt, int score) {
return static_cast<Context*>(userdata)->RewardOverride(
reason_opt, player_id, team, other_player_id_opt, origin_opt, score);
}
static void add_score(void* userdata, int player_id, double reward) {
static_cast<Context*>(userdata)->AddScore(player_id, reward);
}
static int make_random_seed(void* userdata) {
return static_cast<Context*>(userdata)->MakeRandomSeed();
}
static double has_episode_finished(void* userdata,
double elapsed_episode_time_seconds) {
return static_cast<Context*>(userdata)->HasEpisodeFinished(
elapsed_episode_time_seconds);
}
static void add_bots(void* userdata) {
return static_cast<Context*>(userdata)->AddBots();
}
static bool modify_rgba_texture(void* userdata, const char* name,
unsigned char* data, int width, int height) {
return static_cast<Context*>(userdata)->ModifyRgbaTexture(name, data, width,
height);
}
static bool replace_model_name(void* userdata, const char* name, char* new_name,
int new_name_size, char* texture_prefix,
int texture_prefix_size) {
return static_cast<Context*>(userdata)->ReplaceModelName(
name, new_name, new_name_size, texture_prefix, texture_prefix_size);
}
static bool replace_texture_name(void* userdata, const char* name,
char* new_name, int max_size) {
return static_cast<Context*>(userdata)->ReplaceTextureName(name, new_name,
max_size);
}
static bool load_texture(void* userdata, const char* name,
unsigned char** pixels, int* width, int* height,
void* (*allocator)(int size)) {
return static_cast<Context*>(userdata)->LoadTexture(name, pixels, width,
height, allocator);
}
static int custom_observation_count(void* userdata) {
return static_cast<const Context*>(userdata)->Observations().Count();
}
static const char* custom_observation_name(void* userdata, int idx) {
return static_cast<const Context*>(userdata)->Observations().Name(idx);
}
static void custom_observation_spec(void* userdata, int idx,
EnvCApi_ObservationSpec* spec) {
static_cast<const Context*>(userdata)->Observations().Spec(idx, spec);
}
static void custom_observation(void* userdata, int idx,
EnvCApi_Observation* observation) {
return static_cast<Context*>(userdata)->MutableObservations()->Observation(
idx, observation);
}
static int custom_action_discrete_count(void* userdata) {
return static_cast<Context*>(userdata)->CustomActions().DiscreteCount();
}
static const char* custom_action_discrete_name(void* userdata, int idx) {
return static_cast<Context*>(userdata)->CustomActions().DiscreteName(idx);
}
static void custom_action_discrete_bounds(void* userdata, int idx,
int* min_value_out,
int* max_value_out) {
return static_cast<Context*>(userdata)->CustomActions().DiscreteBounds(
idx, min_value_out, max_value_out);
}
static void custom_action_discrete_apply(void* userdata, const int* actions) {
return static_cast<Context*>(userdata)
->MutableCustomActions()
->DiscreteApply(actions);
}
static void player_state(void* userdata, const float origin[3],
const float velocity[3], const float viewangles[3],
float height, const float eyePos[3], int team_score,
int other_team_score, int player_id, bool teleported,
int timestamp_msec) {
return static_cast<Context*>(userdata)->MutableGame()->SetPlayerState(
origin, velocity, viewangles, height, eyePos, team_score,
other_team_score, player_id, teleported, timestamp_msec);
}
static void issue_console_commands(void* userdata) {
return static_cast<Context*>(userdata)->MutableGame()->IssueConsoleCommands();
}
static int make_screen_messages(void* userdata, int screen_width,
int screen_height, int line_height,
int string_buffer_size) {
return static_cast<Context*>(userdata)->MakeScreenMessages(
screen_width, screen_height, line_height, string_buffer_size);
}
static void get_screen_message(void* userdata, int message_id, char* buffer,
int* x, int* y, int* align_l0_r1_c2,
int* shadow, float rgba[4]) {
static_cast<Context*>(userdata)->GetScreenMessage(
message_id, buffer, x, y, align_l0_r1_c2, shadow, rgba);
}
static int make_filled_rectangles(void* userdata, int screen_width,
int screen_height) {
return static_cast<Context*>(userdata)->MakeFilledRectangles(screen_width,
screen_height);
}
static void get_filled_rectangle(void* userdata, int rectangle_id, int* x,
int* y, int* width, int* height,
float rgba[4]) {
static_cast<Context*>(userdata)->GetFilledRectangle(rectangle_id, x, y, width,
height, rgba);
}
static void lua_mover(void* userdata, int entity_id,
const float entity_position[3],
const float player_position[3],
const float player_velocity[3],
float player_position_delta[3],
float player_velocity_delta[3]) {
static_cast<Context*>(userdata)->CustomPlayerMovement(
entity_id, entity_position, player_position, player_velocity,
player_position_delta, player_velocity_delta);
}
static void game_event(void* userdata, const char* event_name, int count,
const float* data) {
static_cast<Context*>(userdata)->GameEvent(event_name, count, data);
}
static void make_pk3_from_map(void* userdata, const char* map_path,
const char* map_name, bool gen_aas) {
static_cast<Context*>(userdata)->MakePk3FromMap(map_path, map_name, gen_aas);
}
static void events_clear(void* userdata) {
static_cast<Context*>(userdata)->MutableEvents()->Clear();
}
static int events_type_count(void* userdata) {
return static_cast<const Context*>(userdata)->Events().TypeCount();
}
static const char* events_type_name(void* userdata, int event_type_idx) {
return static_cast<const Context*>(userdata)->Events().TypeName(
event_type_idx);
}
static int events_count(void* userdata) {
return static_cast<const Context*>(userdata)->Events().Count();
}
static void events_export(void* userdata, int event_idx, EnvCApi_Event* event) {
static_cast<Context*>(userdata)->MutableEvents()->Export(event_idx, event);
}
static void entities_clear(void* userdata) {
static_cast<Context*>(userdata)->MutableGameEntities()->Clear();
}
static void entities_add(void* userdata, int entity_id, int user_id, int type,
int flags, float position[3], const char* classname) {
static_cast<Context*>(userdata)->MutableGameEntities()->Add(
entity_id, user_id, type, flags, position, classname);
}
static void new_client_info(void* userdata, int player_id,
const char* player_name, const char* player_model) {
static_cast<Context*>(userdata)->NewClientInfo(player_id, player_name,
player_model);
}
static EnvCApi_PropertyResult write_property(void* context, const char* key,
const char* value) {
return static_cast<Context*>(context)->WriteProperty(key, value);
}
static EnvCApi_PropertyResult read_property(void* context, const char* key,
const char** value) {
return static_cast<Context*>(context)->ReadProperty(key, value);
}
static EnvCApi_PropertyResult list_property(
void* context, void* userdata, const char* list_key,
void (*prop_callback)(void* userdata, const char* key,
EnvCApi_PropertyAttributes flags)) {
return static_cast<Context*>(context)->ListProperty(userdata, list_key,
prop_callback);
}
} // extern "C"
namespace deepmind {
namespace lab {
namespace {
constexpr char kGameScriptPath[] = "/baselab/game_scripts";
constexpr char kLevelDirectory[] = "levels";
constexpr double kDefaultEpisodeLengthSeconds = 5 * 30.0;
constexpr const char* const kTeamNames[] = {
"free",
"red",
"blue",
"spectator"
};
lua::NResultsOr MapMakerModule(lua_State* L) {
if (auto* ctx =
static_cast<Context*>(lua_touserdata(L, lua_upvalueindex(1)))) {
LuaTextLevelMaker::CreateObject(
L, ctx->ExecutableRunfiles(), ctx->TempDirectory(),
ctx->UseLocalLevelCache(), ctx->UseGlobalLevelCache(),
ctx->LevelCacheParams(), ctx->MixerSeed());
return 1;
} else {
return "Missing context!";
}
}
lua::NResultsOr ModelModule(lua_State* L) {
if (const auto* calls = static_cast<const DeepmindCalls*>(
lua_touserdata(L, lua_upvalueindex(1)))) {
LuaModel::CreateObject(L, calls);
return 1;
} else {
return "Missing context!";
}
}
} // namespace
Context::Context(lua::Vm lua_vm, const char* executable_runfiles,
const DeepmindCalls* calls, DeepmindHooks* hooks,
DeepmindFileReaderType* file_reader_override,
const DeepMindReadOnlyFileSystem* read_only_file_system,
const char* temp_folder)
: lua_vm_(std::move(lua_vm)),
native_app_(false),
actions_{},
mixer_seed_(0),
level_cache_params_{},
game_(executable_runfiles, calls, file_reader_override,
read_only_file_system, temp_folder != nullptr ? temp_folder : ""),
has_alt_cameras_(false) {
CHECK(lua_vm_ != nullptr);
hooks->add_setting = add_setting;
hooks->set_level_cache_settings = set_level_cache_settings;
hooks->set_level_name = set_level_name;
hooks->set_level_directory = set_level_directory;
hooks->start = start;
hooks->map_loaded = map_loaded;
hooks->init = init;
hooks->error_message = error_message;
hooks->set_error_message = set_error_message;
hooks->replace_command_line = replace_command_line;
hooks->next_map = next_map;
hooks->game_type = game_type;
hooks->team_select = team_select;
hooks->update_player_info = update_player_info;
hooks->run_lua_snippet = run_lua_snippet;
hooks->set_native_app = set_native_app;
hooks->get_native_app = get_native_app;
hooks->set_mixer_seed = set_mixer_seed;
hooks->set_actions = set_actions;
hooks->get_actions = get_actions;
hooks->find_model = find_model;
hooks->model_getters = model_getters;
hooks->clear_model = clear_model;
hooks->map_finished = map_finished;
hooks->set_map_finished = set_map_finished;
hooks->can_pickup = can_pickup;
hooks->override_pickup = override_pickup;
hooks->can_trigger = can_trigger;
hooks->override_trigger = override_trigger;
hooks->trigger_lookat = trigger_lookat;
hooks->reward_override = reward_override;
hooks->add_score = add_score;
hooks->make_random_seed = make_random_seed;
hooks->has_episode_finished = has_episode_finished;
hooks->add_bots = add_bots;
hooks->replace_model_name = replace_model_name;
hooks->replace_texture_name = replace_texture_name;
hooks->load_texture = load_texture;
hooks->modify_rgba_texture = modify_rgba_texture;
hooks->custom_observation_count = custom_observation_count;
hooks->custom_observation_name = custom_observation_name;
hooks->custom_observation_spec = custom_observation_spec;
hooks->custom_observation = custom_observation;
hooks->custom_action_discrete_count = custom_action_discrete_count;
hooks->custom_action_discrete_name = custom_action_discrete_name;
hooks->custom_action_discrete_bounds = custom_action_discrete_bounds;
hooks->custom_action_discrete_apply = custom_action_discrete_apply;
hooks->player_state = player_state;
hooks->make_screen_messages = make_screen_messages;
hooks->get_screen_message = get_screen_message;
hooks->make_filled_rectangles = make_filled_rectangles;
hooks->get_filled_rectangle = get_filled_rectangle;
hooks->get_temporary_folder = get_temporary_folder;
hooks->make_pk3_from_map = make_pk3_from_map;
hooks->lua_mover = lua_mover;
hooks->game_event = game_event;
hooks->pickups.update_spawn_vars = update_spawn_vars;
hooks->pickups.make_extra_entities = make_extra_entities;
hooks->pickups.read_extra_entity = read_extra_entity;
hooks->pickups.find_item = find_item;
hooks->pickups.item_count = item_count;
hooks->pickups.item = item;
hooks->pickups.clear_items = clear_items;
hooks->pickups.dynamic_spawn_entity_count = dynamic_spawn_entity_count;
hooks->pickups.read_dynamic_spawn_entity = read_dynamic_spawn_entity;
hooks->pickups.clear_dynamic_spawn_entities = clear_dynamic_spawn_entities;
hooks->pickups.register_dynamic_items = register_dynamic_items;
hooks->pickups.read_dynamic_item_name = read_dynamic_item_name;
hooks->events.clear = events_clear;
hooks->events.type_count = events_type_count;
hooks->events.type_name = events_type_name;
hooks->events.count = events_count;
hooks->events.export_event = events_export;
hooks->entities.clear = entities_clear;
hooks->entities.add = entities_add;
hooks->update_inventory = update_inventory;
hooks->set_has_alt_cameras = set_has_alt_cameras;
hooks->has_alt_cameras = has_alt_cameras;
hooks->custom_view = custom_view;
hooks->issue_console_commands = issue_console_commands;
hooks->new_client_info = new_client_info;
hooks->properties.read = read_property;
hooks->properties.write = write_property;
hooks->properties.list = list_property;
}
void Context::AddSetting(const char* key, const char* value) {
settings_.emplace(key, value);
}
void Context::SetLevelName(std::string level_name) {
level_name_ = std::move(level_name);
}
void Context::SetLevelDirectory(std::string level_directory) {
level_directory_ = std::move(level_directory);
}
std::string Context::GetLevelPath() {
if (level_name_.empty() ||
(level_name_.length() > 4 &&
level_name_.compare(level_name_.length() - 4, 4, ".lua", 4) == 0)) {
return level_name_;
} else {
if (!level_directory_.empty()) {
if (level_directory_[0] == '/') {
return absl::StrCat(level_directory_, "/", level_name_, ".lua");
} else {
return absl::StrCat(ExecutableRunfiles(), kGameScriptPath, "/",
kLevelDirectory, "/", level_directory_, "/",
level_name_, ".lua");
}
} else {
return absl::StrCat(ExecutableRunfiles(), kGameScriptPath, "/",
kLevelDirectory, "/", level_name_, ".lua");
}
}
}
int Context::Init() {
// Clear texture handles from previous levels and initialise temp folder.
int init_code = MutableGame()->Init();
if (init_code != 0) {
return init_code;
}
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
std::string level_path = GetLevelPath();
if (level_path.empty()) {
error_message_ = "Missing level script must set setting 'levelName'!";
return 1;
}
auto result = lua::PushScriptFile(L, level_path);
if (!result.ok()) {
error_message_ = absl::StrCat("Level not found: ", result.error());
return 1;
}
std::string scripts_folder =
absl::StrCat(ExecutableRunfiles(), kGameScriptPath);
lua_vm_.AddPathToSearchers(scripts_folder);
// Add the current running script to the search path.
auto last_slash_pos = level_path.find_last_of('/');
if (last_slash_pos != std::string::npos) {
auto running_level_folder = level_path.substr(0, last_slash_pos);
lua_vm_.AddPathToSearchers(running_level_folder);
}
void* readonly_fs =
const_cast<DeepMindReadOnlyFileSystem*>(Game().ReadOnlyFileSystem());
lua_vm_.AddCModuleToSearchers("dmlab.system.image", LuaImageRequire,
{readonly_fs});
lua_vm_.AddCModuleToSearchers("dmlab.system.tensor",
tensor::LuaTensorConstructors, {readonly_fs});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.maze_generation", &lua::Bind<LuaMazeGeneration::Require>,
{reinterpret_cast<void*>(static_cast<std::uintptr_t>(mixer_seed_))});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.map_maker", &lua::Bind<MapMakerModule>, {this});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.game", &lua::Bind<ContextGame::Module>, {MutableGame()});
lua_vm_.AddCModuleToSearchers("dmlab.system.events",
&lua::Bind<ContextEvents::Module>,
{MutableEvents()});
lua_vm_.AddCModuleToSearchers("dmlab.system.game_entities",
&lua::Bind<ContextEntities::Module>,
{MutableGameEntities()});
lua_vm_.AddCModuleToSearchers("dmlab.system.pickups_spawn",
&lua::Bind<ContextPickups::Module>,
{MutablePickups()});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.random", &lua::Bind<LuaRandom::Require>,
{UserPrbg(),
reinterpret_cast<void*>(static_cast<std::uintptr_t>(mixer_seed_))});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.model", &lua::Bind<ModelModule>,
{const_cast<DeepmindCalls*>(Game().Calls())});
lua_vm_.AddCModuleToSearchers(
"dmlab.system.transform", LuaTransform::Require);
lua::Push(L, level_path);
result = lua::Call(L, 1);
if (!result.ok()) {
error_message_ = result.error();
return 1;
}
if (result.n_results() != 1) {
error_message_ =
"Lua script must return only a table or userdata with metatable.";
return 1;
}
if (!IsFound(lua::Read(L, -1, &script_table_ref_))) {
error_message_ = absl::StrCat(
"Lua script must return a table or userdata with metatable. Actually "
"returned : '",
lua::ToString(L, -1), "'");
return 1;
}
lua_settop(L, 0); // CallInit expects an empty Lua stack.
int err = CallInit();
if (err != 0) return err;
MutablePickups()->SetScriptTableRef(script_table_ref_);
err = MutableObservations()->ReadSpec(script_table_ref_);
if (err != 0) return err;
return MutableCustomActions()->ReadSpec(script_table_ref_);
}
int Context::Start(int episode, int seed) {
EnginePrbg()->seed(static_cast<std::uint64_t>(seed) ^
(static_cast<std::uint64_t>(mixer_seed_) << 32));
MutableGame()->NextMap();
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("start");
if (!lua_isnil(L, -2)) {
lua::Push(L, episode);
lua::Push(L, static_cast<double>(MakeRandomSeed()));
auto result = lua::Call(L, 3);
if (!result.ok()) {
error_message_ = result.error();
return 1;
}
}
return 0;
}
int Context::MapLoaded() {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("mapLoaded");
if (!lua_isnil(L, -2)) {
auto result = lua::Call(L, 1);
if (!result.ok()) {
error_message_ = result.error();
return 1;
}
}
return 0;
}
bool Context::HasEpisodeFinished(double elapsed_episode_time_seconds) {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("hasEpisodeFinished");
if (lua_isnil(L, -2)) {
return elapsed_episode_time_seconds >= kDefaultEpisodeLengthSeconds;
}
lua::Push(L, elapsed_episode_time_seconds);
auto result = lua::Call(L, 2);
CHECK(result.ok()) << "[hasEpisodeFinished] - " << result.error();
CHECK(result.n_results() == 1) << "[hasEpisodeFinished] - Expect single "
"return value of true or false.";
bool finish_episode = false;
CHECK(IsFound(lua::Read(L, -1, &finish_episode)))
<< "[hasEpisodeFinished] - Must return a boolean.";
return finish_episode;
}
const char* Context::GetCommandLine(const char* old_commandline) {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("commandLine");
if (!lua_isnil(L, -2)) {
lua::Push(L, old_commandline);
auto result = lua::Call(L, 2);
CHECK(result.ok()) << result.error();
CHECK_EQ(1, result.n_results()) << "'commandLine' must return a string.";
CHECK(IsFound(lua::Read(L, -1, &command_line_)))
<< "'commandLine' must return a string: Found " << lua::ToString(L, -1);
return command_line_.c_str();
} else {
return old_commandline;
}
}
int Context::RunLuaSnippet(const char* buf, std::size_t buf_len) {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
int out = 0;
lua::NResultsOr result = lua::PushScript(L, buf, buf_len, "snippet");
if (result.ok()) {
lua::Push(L, script_table_ref_);
result = lua::Call(L, 1);
if (result.ok() && result.n_results() != 0) {
CHECK(!IsTypeMismatch(lua::Read(L, -1, &out)));
}
}
CHECK(result.ok()) << result.error();
std::cout << std::flush;
return out;
}
const char* Context::NextMap() {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("nextMap");
CHECK(!lua_isnil(L, -2)) << "Missing Lua function nextMap";
auto result = lua::Call(L, 1);
CHECK(result.ok()) << result.error();
CHECK_EQ(1, result.n_results()) << "'nextMap' must return one string.";
CHECK(IsFound(lua::Read(L, -1, &map_name_)))
<< "'nextMap' must return one string: Found " << lua::ToString(L, -1);
MutableGame()->NextMap();
return map_name_.c_str();
}
void Context::UpdateInventory(bool is_spawning, bool is_bot, int player_id,
int gadget_count, int gadget_inventory[],
int persistent_count, int persistents[],
int stat_count, int stat_inventory[],
int powerup_count, int powerup_time[],
int gadget_held, float height, float position[3],
float velocity[3], float view_angles[3]) {
const char* update_type = is_spawning ? "spawnInventory" : "updateInventory";
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction(update_type);
if (lua_isnil(L, -2)) {
return;
}
auto table = lua::TableRef::Create(L);
table.Insert("isBot", is_bot);
table.Insert("playerId", player_id + 1);
table.Insert("amounts", absl::MakeConstSpan(gadget_inventory, gadget_count));
table.Insert("stats", absl::MakeConstSpan(stat_inventory, stat_count));
table.Insert("persistents",
absl::MakeConstSpan(persistents, persistent_count));
table.Insert("powerups", absl::MakeConstSpan(powerup_time, powerup_count));
table.Insert("position", absl::MakeConstSpan(position, 3));
table.Insert("velocity", absl::MakeConstSpan(velocity, 3));
table.Insert("angles", absl::MakeConstSpan(view_angles, 3));
table.Insert("height", height);
table.Insert("gadget", gadget_held + 1);
lua::Push(L, table);
auto result = lua::Call(L, 2);
CHECK(result.ok()) << "[" << update_type << "] - " << result.error();
if (result.n_results() > 0) {
CHECK_EQ(1, result.n_results())
<< "[" << update_type << "] - Must return table or nil!";
if (!lua_isnil(L, -1)) {
CHECK(IsFound(lua::Read(L, -1, &table)))
<< "[" << update_type << "] - Must return table or nil!";
CHECK(IsFound(table.LookUp(
"amounts", absl::MakeSpan(gadget_inventory, gadget_count))))
<< "[" << update_type << "] - Table missing 'amounts'!";
CHECK(IsFound(
table.LookUp("stats", absl::MakeSpan(stat_inventory, stat_count))))
<< "[" << update_type << "] - Table missing 'stats'!";
}
}
}
int Context::GameType() {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("gameType");
if (lua_isnil(L, -2)) {
return 0; // GT_FFA from bg_public.
} else {
auto result = lua::Call(L, 1);
CHECK(result.ok()) << "[gameType] - " << result.error();
int game_type = 0;
CHECK(IsFound(lua::Read(L, -1, &game_type)))
<< "[gameType] - must return integer; actual \"" << lua::ToString(L, -1)
<< "\"";
CHECK_LT(game_type, 8)
<< "[gameType] - must return integer less than 8; actual \""
<< game_type << "\"";
return game_type;
}
}
bool Context::UpdatePlayerInfo(int player_id, char* info, int info_size) {
lua_State* L = lua_vm_.get();
lua::StackResetter stack_resetter(L);
script_table_ref_.PushMemberFunction("playerModel");
if (!lua_isnil(L, -2)) {
lua::Push(L, player_id + 1);
absl::flat_hash_map<std::string, absl::string_view> player_info =
absl::StrSplit(info + 1, '\\');
lua::Push(L, player_info["name"]);
lua::Push(L, player_info["model"]);
auto result = lua::Call(L, 4);
CHECK(result.ok()) << result.error();
if (result.n_results() > 0) {
absl::string_view model;
lua::Read(L, -1, &model);
auto& current = player_info["model"];
bool model_changed = current != model;