forked from Lasercake/Lasercake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1192 lines (1084 loc) · 45.9 KB
/
main.cpp
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 Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#if 0
#include "tests/test_main.hpp"
int main(int argc, char** argv) {
return lasercake_test_main(argc, argv);
}
#else
// BOOST_SYSTEM_NO_DEPRECATED prevents some deprecated members with global constructors.
#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED
#endif
#include "config.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#if LASERCAKE_USE_QT
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtCore/QMetaEnum>
#include <QtCore/QLocale>
#include <QtCore/QTimer>
#include <QtGui/QFontDatabase>
#endif
#include <iomanip>
#include <sstream>
#include <locale>
#ifdef LASERCAKE_HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#ifndef BOOST_CHRONO_HEADER_ONLY
#define BOOST_CHRONO_HEADER_ONLY
#endif
#include <boost/chrono.hpp>
#include <boost/chrono/process_cpu_clocks.hpp>
#include <boost/chrono/thread_clock.hpp>
#include <boost/scope_exit.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop
#include "main.hpp"
#include "world.hpp"
#include "specific_worlds.hpp"
#include "specific_object_types.hpp"
#include "tests/test_main.hpp"
#include "cmake_config.hpp"
namespace /* anonymous */ {
namespace chrono = boost::chrono;
int64_t get_this_process_mem_usage_megabytes() {
#if defined(LASERCAKE_HAVE_SYS_RESOURCE_H)
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
#if defined(__APPLE__) || defined(__MACOSX__)
return ru.ru_maxrss / (1024*1024);
#else
return ru.ru_maxrss / 1024;
#endif
#else
return 0;
#endif
}
microseconds_t get_this_thread_microseconds() {
#if defined(BOOST_CHRONO_HAS_THREAD_CLOCK)
return chrono::duration_cast<chrono::microseconds>(chrono::thread_clock::now().time_since_epoch()).count();
#else
return 0;
#endif
}
microseconds_t get_this_process_microseconds() {
#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS)
return chrono::duration_cast<chrono::microseconds>(chrono::process_real_cpu_clock::now().time_since_epoch()).count();
#else
return 0;
#endif
}
microseconds_t get_monotonic_microseconds() {
return chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count();
}
// Usage example:
// LOG << std::setw(6) << (ostream_bundle() << "foo" << 564) << std::endl;
struct ostream_bundle : std::ostream {
template<typename T> ostream_bundle& operator<<(T const& t) { ss_ << t; return *this; }
std::string str() { return ss_.str(); }
private:
std::stringstream ss_;
};
std::ostream& operator<<(ostream_bundle& os, ostream_bundle& b) { return os << b.str(); }
std::ostream& operator<<(std::ostream& os, ostream_bundle& b) { return os << b.str(); }
// show_decimal(1234567, 1000, 10) --> "1234.5"
template<typename Integral, typename Integral2>
std::string show_decimal(Integral us, Integral2 divisor, int places, std::locale const& locale = std::locale()) {
Integral divisordivisor = 1;
for(int i = 0; i < places; ++i) { divisordivisor *= 10; }
return (ostream_bundle()
<< (us / divisor)
<< std::use_facet< std::numpunct<char> >(locale).decimal_point()
<< std::setfill('0') << std::setw(places) << std::abs(us / (divisor / divisordivisor) % divisordivisor)
).str();
}
std::string show_microseconds(microseconds_t us) {
return show_decimal(us, 1000, 1);
}
std::string show_microseconds_per_frame_as_fps(microseconds_t monotonic_microseconds_for_frame) {
std::string frames_per_second_str = " inf ";
if(monotonic_microseconds_for_frame > 0) {
const int64_t frames_per_kilosecond = 1000000000 / monotonic_microseconds_for_frame;
frames_per_second_str = show_decimal(frames_per_kilosecond, 1000, 2);
}
return frames_per_second_str;
}
object_identifier init_test_world_and_return_our_robot(
world& w, bool crazy_lasers, std::string scenario, bool log_microseconds = true) {
const vector3<distance> laser_loc = world_center_fine_coords
+ vector3<distance>(10LL*tile_width + 2*fine_distance_units,
10LL*tile_width + 2*fine_distance_units,
10LL*tile_width + 2*fine_distance_units);
const shared_ptr<robot> baz (new robot(
(scenario == "playground") ? (world_center_fine_coords + vector3<distance>(4*tile_width, 8*tile_width, 6*tile_width)) : (laser_loc - vector3<distance>(0, 0, tile_width*2)),
(scenario == "playground") ? vector3<distance>(-4*tile_width, -8*tile_width, -2*tile_width) : vector3<distance>((5<<9)*fine_distance_units, (3<<9)*fine_distance_units, 0 /*TODO UNITS make class vector3_direction*/)));
const object_identifier robot_id = w.try_create_object(baz); // we just assume that this works
//const shared_ptr<autorobot> aur (new autorobot(
// get_min_containing_tile_coordinates(laser_loc - vector3<distance>(tile_width*4,tile_width*4,tile_width*2)),
// vector3<distance>((5<<9)*fine_distance_units, (3<<9)*fine_distance_units, 0 /*TODO UNITS make class vector3_direction*/)));
//w.try_create_object(aur); // we just assume that this works
if(crazy_lasers) {
const shared_ptr<laser_emitter> foo (new laser_emitter(
laser_loc,
vector3<distance>(5*fine_distance_units, 3*fine_distance_units, 1*fine_distance_units /*TODO UNITS make class vector3_direction*/)));
const shared_ptr<laser_emitter> bar (new laser_emitter(
laser_loc + vector3<distance>(0,0,tile_width*2),
vector3<distance>(5*fine_distance_units, 4*fine_distance_units, -1*fine_distance_units /*TODO UNITS make class vector3_direction*/)));
w.try_create_object(foo);
w.try_create_object(bar);
}
if (scenario == "playground") {
w.try_create_object(shared_ptr<object>(new refinery(world_center_tile_coords)));
for (tile_coordinate_signed_type i = 0; i < 20; ++i) {
w.try_create_object(shared_ptr<object>(new conveyor_belt(world_center_tile_coords + vector3<tile_coordinate_signed_type>(2+i, 0, 0))));
if (i < 12) {
w.try_create_object(shared_ptr<object>(new conveyor_belt(world_center_tile_coords + vector3<tile_coordinate_signed_type>(-2-i, 0, 0))));
}
if (i < 5) {
w.try_create_object(shared_ptr<object>(new conveyor_belt(world_center_tile_coords + vector3<tile_coordinate_signed_type>(0, 2+i, 0), yplus)));
}
if (i < 5) {
w.try_create_object(shared_ptr<object>(new conveyor_belt(world_center_tile_coords + vector3<tile_coordinate_signed_type>(2+20, i, 0), yplus)));
}
}
}
// HACK - TODO remove at least the second effect
// This hack has two effects:
// Generating all the worldblocks near the start right away
// and
// (BIG HACK)
// making water (that's near enough to the start) start out ungroupable
// which helps us e.g. start with a pillar of water in the air that's about to fall,
// so we can test how that physics works.
{
if(log_microseconds) {
LOG << "\nInit: ";
}
const microseconds_t microseconds_before_init = get_this_process_microseconds();
vector<tile_location> tiles_near_start;
// I choose these distances big enough that, as of the time of writing this comment,
// the GLOBAL view won't have to realize any new tiles in order to make a complete cycle
// around world-center. This is an interim way to get rid of that annoying lag, at the cost
// of a bit more of annoying startup time.
const bounding_box initial_area = bounding_box::min_and_max(
world_center_fine_coords - vector3<distance>(tile_width*80,tile_width*80,tile_width*80),
world_center_fine_coords + vector3<distance>(tile_width*80,tile_width*80,tile_width*80)
);
w.ensure_realization_of_space(initial_area, FULL_REALIZATION);
w.get_tiles_exposed_to_collision_within(tiles_near_start,
get_tile_bbox_containing_all_tiles_intersecting_fine_bbox(initial_area));
for (tile_location loc : tiles_near_start) {
if (loc.stuff_at().contents() == GROUPABLE_WATER) {
w.replace_substance(loc, GROUPABLE_WATER, UNGROUPABLE_WATER);
}
}
const microseconds_t microseconds_after_init = get_this_process_microseconds();
const microseconds_t microseconds_for_init = microseconds_after_init - microseconds_before_init;
if(log_microseconds) {
LOG << show_microseconds(microseconds_for_init) << " ms\n";
}
}
return robot_id;
}
std::string get_world_ztree_debug_info(world const& w) {
std::stringstream world_ztree_debug_info;
// hack to print this debug info occasionally
if(w.game_time_elapsed() % (5*seconds * identity(time_units / seconds))
< (1*seconds*identity(time_units / seconds) / 15)) {
//world_ztree_debug_info << "tiles:";
//w.tiles_exposed_to_collision().print_debug_summary_information(world_ztree_debug_info);
world_ztree_debug_info << "objects:";
w.objects_exposed_to_collision().print_debug_summary_information(world_ztree_debug_info);
}
else {
// zobj = ztree objects
world_ztree_debug_info //<< "t:" << w.tiles_exposed_to_collision().size()
<< "o:" << w.objects_exposed_to_collision().size() << " zobj; ";
}
return world_ztree_debug_info.str();
}
} /* end anonymous namespace */
// LasercakeSimulator:
//
// When exiting the program, we implicitly roughly terminate the simulation
// thread by calling C's exit() without stopping or waiting for that thread.
//
// The thread has no side effects visible outside the
// program, so this doesn't lead to visible race conditions.
//
// (
// This might even be safe if we were not exiting the program
// (via e.g. simulator_thread_->terminate()):
// The simulation thread refers to no global data
// (except for implementations of e.g. borrowed_bitset, hmm)
// and has no side effects
// (except for Qt inter-thread communication; what if terminating
// it leaves a Qt-implementation mutex in a wrong state? Hmm.
// This could be impossiblified by using lock-free communication
// between ours and the sim thread).
// )
LasercakeSimulator::LasercakeSimulator(QObject* parent) : QObject(parent) {}
void LasercakeSimulator::init(worldgen_ptr worldgen, config_struct config) {
const microseconds_t microseconds_before_initing = get_this_thread_microseconds();
world_ptr_.reset(new world(worldgen));
const object_identifier robot_id = init_test_world_and_return_our_robot(*world_ptr_, config.crazy_lasers, config.scenario, config.show_frame_timing);
currently_focused_object_ = robot_id;
view_ptr_.reset(new view_on_the_world(world_center_fine_coords));
view_ptr_->drawing_debug_stuff = config.initially_drawing_debug_stuff;
const microseconds_t microseconds_after_initing = get_this_thread_microseconds();
microseconds_last_sim_frame_took_ = microseconds_after_initing - microseconds_before_initing; //hack?
}
//TODO have each keypress have a time_unit as well.
//It implicitly computes up to the latest frame for which it
//has input, currently.
//Possibly-a-bad-idea: we could compute ahead assuming that
//the same set of keys are going to stay pressed, and backtrack
//and re-simulate if that doesn't turn out to be the case.
//for now, just assume updates are in the usual time-steps (bogus)
void LasercakeSimulator::new_input_as_of(time_unit /*moment*/, input_news_t input_news) {
//(TODO?) we don't currently respect the given moment to simulate up to
const microseconds_t microseconds_before_simulating = get_this_thread_microseconds();
unordered_map<object_identifier, input_news_t> targeted_input;
targeted_input[currently_focused_object_] = input_news;
world_ptr_->update(targeted_input);
const microseconds_t microseconds_after_simulating = get_this_thread_microseconds();
microseconds_last_sim_frame_took_ = microseconds_after_simulating - microseconds_before_simulating;
#if LASERCAKE_USE_QT
Q_EMIT sim_frame_done(world_ptr_->game_time_elapsed());
#endif
}
// TODO think about that input_news argument and the timing of when it's read etc.
void LasercakeSimulator::prepare_graphics(input_news_t input_since_last_prepare, distance view_radius, bool actually_prepare_graphics) {
const microseconds_t microseconds_before_drawing = get_this_thread_microseconds();
gl_data_ptr_t gl_data_ptr(new gl_data_t());
if(actually_prepare_graphics) {
const int32_t num_tab_presses = input_since_last_prepare.num_times_pressed("tab");
for(int32_t i = 0; i != num_tab_presses; ++i) {
//TODO better than O(N) (or worse, O(N * num tab presses!)
objects_map<object>::type const& objects = world_ptr_->get_objects();
//restrict to autonomous objs perhaps?
object_identifier best = currently_focused_object_; //the worst best
for(auto const& p : objects) {
if(boost::dynamic_pointer_cast<object_with_eye_direction>(p.second)) {
if(p.first > currently_focused_object_) {
if(best <= currently_focused_object_ || p.first < best) {
best = p.first;
}
}
else if(best <= currently_focused_object_ && p.first < best) {
best = p.first;
}
}
}
currently_focused_object_ = best;
}
//hmm
view_ptr_->input(input_since_last_prepare);
view_ptr_->prepare_gl_data(*world_ptr_, gl_data_preparation_config(view_radius, currently_focused_object_), *gl_data_ptr);
}
const microseconds_t microseconds_after_drawing = get_this_thread_microseconds();
const microseconds_t microseconds_for_drawing = microseconds_after_drawing - microseconds_before_drawing;
const frame_output_t output = {
gl_data_ptr,
microseconds_for_drawing,
microseconds_last_sim_frame_took_,
get_world_ztree_debug_info(*world_ptr_)
};
#if LASERCAKE_USE_QT
Q_EMIT frame_output_ready(world_ptr_->game_time_elapsed(), output);
#endif
}
namespace /*anonymous*/ {
// Boost doesn't appear to provide a reverse-sense bool switch, so:
boost::program_options::typed_value<bool>* bool_switch_off(bool* v = nullptr) {
using boost::program_options::typed_value;
typed_value<bool>* result = new typed_value<bool>(v);
result->default_value(true);
result->implicit_value(false);
result->zero_tokens();
return result;
}
} /* end anonymous namespace */
int debug_test_sim_avoiding_qt_and_trying_to_be_very_deterministic(config_struct config) {
LOG << "Constructing worldgen\n";
const worldgen_ptr worldgen = make_world_building_func(config.scenario);
assert(worldgen);
LOG << "Constructing world\n";
world w(worldgen);
LOG << "Initing world\n";
const object_identifier robot_id = init_test_world_and_return_our_robot(w, config.crazy_lasers, config.scenario, false);
shared_ptr<view_on_the_world> view_ptr;
if(config.run_drawing_code) {
LOG << "Initing graphics-prep code\n";
view_ptr.reset(new view_on_the_world(world_center_fine_coords));
view_ptr->drawing_debug_stuff = config.initially_drawing_debug_stuff;
}
LOG << "Beginning simulating\n";
int64_t frame = 0;
const unordered_map<object_identifier, input_news_t> there_aint_any_input;
while(config.exit_after_frames != frame) {
++frame;
w.update(there_aint_any_input);
if(config.run_drawing_code) {
LOG << "end sim; " << std::flush;
{
gl_data_ptr_t gl_data_ptr(new gl_data_t());
view_ptr->prepare_gl_data(w, gl_data_preparation_config(config.view_radius, robot_id), *gl_data_ptr);
}
}
LOG << "end frame " << frame << std::endl;
}
LOG << "Ending simulating\n";
return 0;
}
bool str_prefixes(const char* prefix, const char* str) {
while(*prefix != '\0') {
if(*prefix != *str) { return false; }
++prefix; ++str;
}
return true;
}
int main(int argc, char** argv)
{
try {
std::locale::global(std::locale(""));
}
catch(std::runtime_error&) {
LOG << "Can't find your default locale; not setting locale" << std::endl;
}
LOG << std::boolalpha;
// When starting Lasercake from an OS X bundle, OS X passes the command-line
// option -psn_0_349875 (the number varies). So we explicitly ignore that
// option rather than misinterpret it as the short flags p, s, n, _, 0, etc.
// Since -_ isn't a flag, this won't interfere with any regular command-line
// usages. TODO: should we move Qt's parsing up to here instead
// (QApplication qapp(argc, argv); and use qapp.arguments())? But then we'd
// need to extract the arguments to pass to Boost Program Options
// (Qt doesn't yet have its own arg parser library); and -Q/--avoid-qt
// wouldn't quite work. Should we instead complicate bundle creation with
// a wrapper shell script for the executable? But Qt ought to receive the
// -psn_ argument so we can't just delete it there.
std::vector<std::string> args_sanitized;
for(int i = 1; i < argc; ++i) {
if(!str_prefixes("-psn_", argv[i])) {
args_sanitized.push_back(argv[i]);
}
}
config_struct config;
{
namespace po = boost::program_options;
po::positional_options_description p;
p.add("scenario", 1);
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("version", "show version information")
("view-radius,v", po::value<uint32_t>()->default_value(120), "view radius, in tile_widths") //TODO - in meters?
("crazy-lasers,l", po::bool_switch(&config.crazy_lasers), "start with some lasers firing in lots of random directions")
("initially-drawing-debug-stuff,d", po::bool_switch(&config.initially_drawing_debug_stuff), "initially drawing debug stuff")
("scenario", po::value<std::string>(&config.scenario), "which scenario to run (also accepted with --scenario omitted)")
("exit-after-frames,e", po::value<int64_t>(&config.exit_after_frames)->default_value(-1), "debug: exit after n frames (negative: never)")
("no-gui,n", bool_switch_off(&config.have_gui), "debug: don't run the GUI")
("sim-only,s", bool_switch_off(&config.run_drawing_code), "debug: don't draw/render at all")
("avoid-qt,Q", "debug: don't call Qt at all (implies --no-gui and --no-threads; attempts to be even more deterministic than normal)")
("max-framerate", po::value<int64_t>(&config.max_frames_per_seconds)->default_value(60), "Limit frame-rate")
("no-frame-timing", bool_switch_off(&config.show_frame_timing), "don't log timing info each frame")
("no-threads", "debug: don't use threads even when supported")
("no-sim-thread", bool_switch_off(&config.use_simulation_thread), "debug: don't use a thread for the simulation")
("no-opengl-thread", bool_switch_off(&config.use_opengl_thread), "debug: use a thread for the OpenGL calls")
#if !LASERCAKE_NO_SELF_TESTS
("run-self-tests", "alternate run mode: run Lasercake's self-tests")
#endif
;
po::variables_map vm;
po::store(po::command_line_parser(args_sanitized).
options(desc).positional(p).run(), vm);
po::notify(vm);
config.view_radius =
physical_quantity<lint64_t, tile_widths_t>(
vm["view-radius"].as<uint32_t>() * tile_widths)
* identity(fine_distance_units / tile_widths);
if(!config.run_drawing_code) {
config.have_gui = false;
}
if(vm.count("no-threads")) {
config.use_simulation_thread = false;
config.use_opengl_thread = false;
}
if(vm.count("help")) {
std::cout << "Lasercake " << LASERCAKE_VERSION_DESC << "\n\n";
std::cout << desc << std::endl;
std::cout << "Scenario names:";
for(auto const& name : scenario_names()) {
std::cout << "\n " << name;
}
std::cout << std::endl;
exit(0);
}
if(vm.count("version")) {
std::cout << "Lasercake " << LASERCAKE_VERSION_DESC << "\n";
// do the sizeof because gcc and clang disagree on `cc -m32 -dumpmachine`.
std::cout << "built on " << __DATE__ << " by " << LASERCAKE_COMPILER_DESC << "\n";
std::cout << "for " << LASERCAKE_TARGET_DESC << " with " << sizeof(void*) << "-byte pointers\n";
std::cout << std::endl;
exit(0);
}
#if !LASERCAKE_NO_SELF_TESTS
if(vm.count("run-self-tests")) {
return lasercake_test_main(argc, argv);
}
#endif
if(!vm.count("scenario")) {
LOG << "You didn't give an argument saying which scenario to use! Using default value...\n";
config.scenario = "playground";
}
if(vm.count("avoid-qt")) {
config.have_gui = false;
return debug_test_sim_avoiding_qt_and_trying_to_be_very_deterministic (config);
}
}
#if LASERCAKE_USE_QT
QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
QApplication qapp(argc, argv);
if(config.have_gui) {
if (!QGLFormat::hasOpenGL()) {
LOG << "OpenGL capabilities not found; giving up." << std::endl;
exit(1);
}
}
qRegisterMetaType<worldgen_ptr>("worldgen_ptr");
qRegisterMetaType<input_news_t>("input_news_t");
qRegisterMetaType<frame_output_t>("input_representation::key_change_t");
qRegisterMetaType<frame_output_t>("frame_output_t");
qRegisterMetaType<gl_data_ptr_t>("gl_data_ptr_t");
qRegisterMetaType<config_struct>("config_struct");
qRegisterMetaType<distance>("distance");
qRegisterMetaType<time_unit>("time_unit");
QFontDatabase::addApplicationFont(":/resources/VC_Granger_ch8plus.ttf");
QFontDatabase::addApplicationFont(":/resources/VC_Luna.ttf");
QFontDatabase::addApplicationFont(":/resources/VC_Slytherin.ttf");
QFontDatabase::addApplicationFont(":/resources/VC_Gryffindor.ttf");
#endif
LasercakeController controller(config);
// We call exit() here rather than return so that 'controller' is not
// destroyed in the process of exiting the program.
// This makes Qt emit fewer warnings; probably makes quitting a bit faster;
// and we make sure not to use the destructor for any critical
// end-of-process stuff (if there even is any currently).
#if LASERCAKE_USE_QT
const int exitcode = qapp.exec();
#endif
LOG << "Qt main loop has ended; " << std::flush;
if(false) {
// Currently it seems better not to do this than to do this,
// on the whole, in terms of adverse side-effects on various
// platforms.
LOG << "terminating simulation thread; " << std::flush;
controller.killSimulator();
}
LOG << "calling exit()." << std::endl;
#if LASERCAKE_USE_QT
exit(exitcode);
#else
exit(0);
#endif
}
microseconds_t LasercakeGLThread::gl_render(gl_data_ptr_t& gl_data_ptr, LasercakeGLWidget& gl_widget, QSize viewport_size) {
#if LASERCAKE_USE_QT
gl_widget.makeCurrent();
BOOST_SCOPE_EXIT((&gl_widget)) {
gl_widget.doneCurrent();
} BOOST_SCOPE_EXIT_END
#endif
// (should we measure time just here or include more of the loop?)
// (Is monotonic appropriate? Consider GL semantics: the implementation is
// free to fork more threads, and/or wait for the GPU without consuming CPU,
// etc [mine seems to do both somewhat].)
const microseconds_t microseconds_before_gl = get_monotonic_microseconds();
gl_renderer_.output_gl_data_to_OpenGL(
*gl_data_ptr,
viewport_size.width(),
viewport_size.height(),
&gl_widget,
gl_thread_data_->interrupt
);
if(!gl_thread_data_->interrupt.load()) {
//TODO measure the microseconds ~here~ in the different configurations. e.g. should the before/after here be split across threads?
//gl_data_ptr.reset(); // but if the deletion does happen now, it'll be in this thread, now, delaying swapBuffers etc :(
// but it's a good time and CPU(cache) to delete the data on...
#if LASERCAKE_USE_QT
gl_widget.swapBuffers();
#endif
}
const microseconds_t microseconds_after_gl = get_monotonic_microseconds();
return microseconds_after_gl - microseconds_before_gl;
}
void LasercakeGLWidget::invoke_render_() {
if(!has_quit_) {
if(use_separate_gl_thread_) {
#if LASERCAKE_USE_QT
gl_thread_data_->wait_for_instruction.wakeAll();
#endif
}
else {
gl_thread_data_->microseconds_last_gl_render_took =
thread_.gl_render(gl_thread_data_->current_data, *this, gl_thread_data_->viewport_size);
}
}
}
LasercakeGLWidget::LasercakeGLWidget(bool use_separate_gl_thread, QWidget* parent)
: QGLWidget(parent),
input_is_grabbed_(false),
use_separate_gl_thread_(use_separate_gl_thread),
has_quit_(false) {
#if LASERCAKE_USE_QT
QObject::connect(
QCoreApplication::instance(), SIGNAL(aboutToQuit()),
this, SLOT(prepare_to_cleanly_close_()));
setFocusPolicy(Qt::ClickFocus);
//TODO setWindowFlags(), setWindow*()?
//TODO do we want to request/check anything about the GL context?
setWindowTitle("Lasercake");
// default window size to 2/3 of available screen width and height
const QRect approximateAvailableScreenArea = QApplication::desktop()->availableGeometry();
resize(approximateAvailableScreenArea.width()*2/3, approximateAvailableScreenArea.height()*2/3);
setAutoBufferSwap(false);
setAutoFillBackground(false);
#endif
gl_thread_data_.reset(new gl_thread_data_t);
gl_thread_data_->current_data.reset(new gl_data_t());
#if LASERCAKE_USE_QT
const QSize viewport_size = size();
#else
const QSize viewport_size = QSize(300, 300); //todo
#endif
gl_thread_data_->viewport_size = viewport_size;
gl_thread_data_->microseconds_last_gl_render_took = 0;
gl_thread_data_->quit_now = false;
gl_thread_data_->interrupt.store(false);
gl_thread_data_->revision = 0;
++gl_thread_data_->revision; //display right away!
thread_.gl_widget_ = this;
thread_.gl_thread_data_ = gl_thread_data_;
if(use_separate_gl_thread_) {
thread_.last_revision_ = 0;
thread_.microseconds_this_gl_render_took_ = 0;
#if LASERCAKE_USE_QT
thread_.start();
#endif
}
else {
gl_thread_data_->microseconds_last_gl_render_took =
thread_.gl_render(gl_thread_data_->current_data, *this, viewport_size);
}
}
void LasercakeGLWidget::update_gl_data(gl_data_ptr_t data) {
{
#if LASERCAKE_USE_QT
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
#endif
gl_thread_data_->current_data = data;
++gl_thread_data_->revision;
}
invoke_render_();
}
microseconds_t LasercakeGLWidget::get_last_gl_render_microseconds() {
#if LASERCAKE_USE_QT
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
#endif
return gl_thread_data_->microseconds_last_gl_render_took;
}
void LasercakeGLThread::run() {
assert(gl_thread_data_->interrupt.load() == false);
while(true) {
gl_data_ptr_t gl_data_ptr;
QSize viewport_size;
{
#if LASERCAKE_USE_QT
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
#endif
gl_thread_data_->microseconds_last_gl_render_took = microseconds_this_gl_render_took_;
#if LASERCAKE_USE_QT
if(last_revision_ == gl_thread_data_->revision) {
gl_thread_data_->wait_for_instruction.wait(&gl_thread_data_->gl_data_lock);
}
#endif
if(gl_thread_data_->quit_now) {
LOG << "Releasing OpenGL state... " << std::flush;
#if LASERCAKE_USE_QT
gl_renderer_.fini();
#endif
LOG << "Done releasing OpenGL state. " << std::flush;
return;
}
gl_data_ptr = gl_thread_data_->current_data;
last_revision_ = gl_thread_data_->revision;
viewport_size = gl_thread_data_->viewport_size;
}
microseconds_this_gl_render_took_ =
this->gl_render(gl_data_ptr, *gl_widget_, viewport_size);
}
}
#if LASERCAKE_USE_QT
void LasercakeGLWidget::resizeEvent(QResizeEvent*) {
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
gl_thread_data_->viewport_size = size();
}
void LasercakeGLWidget::paintEvent(QPaintEvent*) {
{
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
++gl_thread_data_->revision;
}
invoke_render_();
}
#endif
void LasercakeGLWidget::prepare_to_cleanly_close_() {
if(!has_quit_) {
// Send debug messages in case waiting for any of these
// operations freezes, so that people can tell exactly what
// happened.
// Just in case closing doesn't cause the OS to
// release a mouse grab, we do so explicitly.
if(input_is_grabbed_) {
LOG << "Ungrabbing input... " << std::flush;
#if LASERCAKE_USE_QT
ungrab_input_();
#endif
LOG << "Done ungrabbing input. " << std::endl;
}
// Some OpenGL implementations don't like being
// silently terminated, because they are poorly tested
// piles of looming kernel-exploitation vulnerabilities.
//
// Anyway, waiting for the GL thread to reach a stopping point
// seems to be useful for system stability.
// TODO should we catch signals like Ctrl-C
// in order to clean up even in their wake?
LOG << (use_separate_gl_thread_ ? "Quitting OpenGL thread... "
: "Releasing OpenGL state... ") << std::flush;
#if LASERCAKE_USE_QT
{
QMutexLocker lock(&gl_thread_data_->gl_data_lock);
gl_thread_data_->quit_now = true;
++gl_thread_data_->revision;
}
if(use_separate_gl_thread_) {
gl_thread_data_->interrupt.store(true);
gl_thread_data_->wait_for_instruction.wakeAll();
thread_.wait();
}
else {
thread_.gl_renderer_.fini();
}
#endif
LOG << (use_separate_gl_thread_ ? "Done quitting OpenGL thread. "
: "Done releasing OpenGL state. ") << std::flush;
LOG << std::endl;
has_quit_ = true;
}
}
#if LASERCAKE_USE_QT
void LasercakeGLWidget::closeEvent(QCloseEvent* event) {
prepare_to_cleanly_close_();
QGLWidget::closeEvent(event);
}
// Don't let QEvent::event() steal tab keys or such, throwing
// off our counts of which keys are pressed. If we want such
// behaviour in this widget we shall implement it ourself.
bool LasercakeGLWidget::event(QEvent* event) {
switch (event->type()) {
case QEvent::KeyPress:
key_change_((QKeyEvent*)event, true);
return true;
case QEvent::KeyRelease:
key_change_((QKeyEvent*)event, false);
return true;
default:
return QGLWidget::event(event);
}
}
namespace /*anonymous*/ {
//hack for using Qt non-public API:
//(http://kunalmaemo.blogspot.com/2010/05/enum-value-to-string-in-qt.html)
struct StaticQtMetaObject : QObject {
static QMetaObject const& get() {return staticQtMetaObject;}
};
// This implementation semantic is probably a hack, but will do for now.
// TODO if the wire or especially the user comes to depend
// on these names, think more seriously about them.
// Also consider the e.g. sequence on a US keyboard
// PRESS Shift
// PRESS /? --> text ?, key /
// RELEASE Shift
// RELEASE /? --> text /, key /
// So for single-key type things, we can't easily rely on
// event->text() at all.
// input_representation::key_type could *be* Qt::Key reasonably.
// There probably also needs to be a text entry *mode*...
// and I don't know enough about what it's like for e.g. Chinese keyboards.
input_representation::key_type q_key_event_to_input_rep_key_type(QKeyEvent* event) {
QString as_text;// = event->text();
//if(as_text.isEmpty() || QRegExp("[[:graph:]].*").exactMatch(as_text)) {
QMetaObject const& staticQtMetaObject = StaticQtMetaObject::get();
const int key_index = staticQtMetaObject.indexOfEnumerator("Key");
const QMetaEnum key_meta_enum = staticQtMetaObject.enumerator(key_index);
QString keyString = key_meta_enum.valueToKey(event->key());
keyString.replace("Key_","");
as_text = keyString;
//}
QString lowercase_text = QApplication::keyboardInputLocale().toLower(as_text);
input_representation::key_type result(lowercase_text.toUtf8().constData());
return result;
}
}
void LasercakeGLWidget::toggle_fullscreen() {
setWindowState(windowState() ^ Qt::WindowFullScreen);
}
void LasercakeGLWidget::toggle_fullscreen(bool fullscreen) {
if(fullscreen) { setWindowState(windowState() | Qt::WindowFullScreen); }
else { setWindowState(windowState() & ~Qt::WindowFullScreen); }
}
namespace {
input_representation::key_type mouse_button_to_input_rep(Qt::MouseButton button) {
switch (button) {
case Qt::NoButton: caller_error("invalidly pressed/released Qt::NoButton");
case Qt::LeftButton: return input_representation::left_mouse_button;
case Qt::RightButton: return input_representation::right_mouse_button;
case Qt::MiddleButton: return input_representation::middle_mouse_button;
// Are these the correct numbers?
case Qt::XButton1: return input_representation::mouse_button_n(4);
case Qt::XButton2: return input_representation::mouse_button_n(5);
default:
LOG << "Unknown mouse button that Qt calls " << button << "\n";
// give it some name anyhow, even if it's the same name
// for all unknown buttons
return input_representation::mouse_button_n(6);
}
}
}
void LasercakeGLWidget::mousePressEvent(QMouseEvent* event) {
if(!input_is_grabbed_) {
global_cursor_pos_ = event->globalPos();
grab_input_();
}
else {
key_change_(-event->button(), mouse_button_to_input_rep(event->button()), true);
}
QGLWidget::mousePressEvent(event);
}
void LasercakeGLWidget::mouseReleaseEvent(QMouseEvent* event) {
key_change_(-event->button(), mouse_button_to_input_rep(event->button()), false);
QGLWidget::mouseReleaseEvent(event);
}
void LasercakeGLWidget::grab_input_() {
if(!has_quit_) {
input_is_grabbed_ = true;
setMouseTracking(true);
grabMouse(QCursor(Qt::BlankCursor));
}
}
void LasercakeGLWidget::ungrab_input_() {
if(input_is_grabbed_) {
setMouseTracking(false);
releaseMouse();
input_is_grabbed_ = false;
}
}
void LasercakeGLWidget::mouseMoveEvent(QMouseEvent* event) {
const QPoint new_global_cursor_pos = event->globalPos();
const QPoint displacement = new_global_cursor_pos - global_cursor_pos_;
QApplication::desktop()->cursor().setPos(global_cursor_pos_);
input_rep_mouse_displacement_ += input_representation::mouse_displacement_t(
displacement.x(), -displacement.y());
}
void LasercakeGLWidget::key_change_(
qt_key_type_ qkey,
input_representation::key_type ikey,
bool pressed) {
const input_representation::key_change_t input_rep_key_change(
ikey, (pressed ? input_representation::PRESSED : input_representation::RELEASED));
if(pressed) {
// Have the input_representation believe there's only one of each key,
// for its sanity.
if(keys_currently_pressed_.find(qkey) == keys_currently_pressed_.end()) {
//TODO use the Qt key enumeration in input_representation too
//as it's much more complete than anything we'll ever have.
input_rep_key_activity_.push_back(input_rep_key_change);
input_rep_keys_currently_pressed_.insert(ikey);
Q_EMIT key_changed(input_rep_key_change);
}
keys_currently_pressed_.insert(qkey);
}
else {
const auto iter = keys_currently_pressed_.find(qkey);
if(iter == keys_currently_pressed_.end()) {
// This could happen if they focus this window while holding
// a key down, and it not be a bug, so it's a bit silly to
// log this.
//LOG << "Key released but never pressed: " << qkey << " (" << q_key_event_to_input_rep_key_type(event) << ")\n";
}
else {
keys_currently_pressed_.erase(iter);
if(keys_currently_pressed_.find(qkey) == keys_currently_pressed_.end()) {
input_rep_key_activity_.push_back(input_rep_key_change);
input_rep_keys_currently_pressed_.erase(ikey);
Q_EMIT key_changed(input_rep_key_change);
}
}
}
}
void LasercakeGLWidget::key_change_(QKeyEvent* event, bool pressed) {
if(event->isAutoRepeat()) {
// If we someday allow key compression, this won't be a sensible way to stop auto-repeat:
// "Note that if the event is a multiple-key compressed event that is partly due to auto-repeat, this function could return either true or false indeterminately."
return;
}
if(pressed) {
//TODO why handle window things here but other things in LasercakeController::key_changed?
switch(event->key()) {
case Qt::Key_Escape:
ungrab_input_();
return;
case Qt::Key_Q:
case Qt::Key_W:
if((event->modifiers() & Qt::ControlModifier)) {
close();
return;
}
break;
case Qt::Key_F11:
toggle_fullscreen();
return;
case Qt::Key_F:
// F11 does Exposé stuff in OS X, and Command-Shift-F seems to be
// the "fullscreen" convention there.
// (Qt maps OSX command-key to Qt::Key_Control.)
if((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::ControlModifier)) {
toggle_fullscreen();
return;
}
break;
}
}
const input_representation::key_type input_rep_key = q_key_event_to_input_rep_key_type(event);
key_change_(event->key(), input_rep_key, pressed);
}
void LasercakeGLWidget::focusOutEvent(QFocusEvent*) {
for(auto key : input_rep_keys_currently_pressed_) {
const input_representation::key_change_t key_change(key, input_representation::RELEASED);
input_rep_key_activity_.push_back(key_change);
Q_EMIT key_changed(key_change);
}
input_rep_keys_currently_pressed_.clear();
keys_currently_pressed_.clear();
}
#endif
input_representation::input_news_t LasercakeGLWidget::get_input_news()const {
input_representation::input_news_t result(
input_rep_keys_currently_pressed_, input_rep_key_activity_, input_rep_mouse_displacement_);
return result;
}
void LasercakeGLWidget::clear_input_news() {
input_rep_key_activity_.clear();
input_rep_mouse_displacement_ = input_representation::mouse_displacement_t();
}
void LasercakeController::key_changed(input_representation::key_change_t key_change) {
// Handle things that shouldn't wait until the next time (if any)
// that the simulation thread gives us data.
if(key_change.second == input_representation::PRESSED) {
input_representation::key_type const& k = key_change.first;
if(k == "p") {
paused_ = !paused_;
steps_queued_to_do_while_paused_ = 0;
if(config_.have_gui) {
gl_widget_->clear_input_news();
}
if(!paused_) {