-
Notifications
You must be signed in to change notification settings - Fork 78
/
level_runner.cpp
2159 lines (1825 loc) · 62.3 KB
/
level_runner.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 (C) 2003-2014 by David White <davewx7@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <math.h>
#include <climits>
#include <boost/algorithm/string/replace.hpp>
#include "CameraObject.hpp"
#include "Canvas.hpp"
#include "Font.hpp"
#include "DisplayDevice.hpp"
#include "ModelMatrixScope.hpp"
#include "WindowManager.hpp"
#include "background_task_pool.hpp"
#include "base64.hpp"
#include "clipboard.hpp"
#include "collision_utils.hpp"
#include "controls.hpp"
#include "custom_object.hpp"
#include "custom_object_functions.hpp"
#include "debug_console.hpp"
#include "draw_scene.hpp"
#ifndef NO_EDITOR
#include "editor.hpp"
#endif
#include "filesystem.hpp"
#include "formatter.hpp"
#include "formula_profiler.hpp"
#include "formula_callable.hpp"
#include "http_client.hpp"
#ifdef TARGET_BLACKBERRY
#include "userevents.h"
#endif
#include "input.hpp"
#include "joystick.hpp"
#include "json_parser.hpp"
#include "level_runner.hpp"
#include "light.hpp"
#include "load_level.hpp"
#include "message_dialog.hpp"
#include "module.hpp"
#include "object_events.hpp"
#include "pause_game_dialog.hpp"
#include "player_info.hpp"
#include "preferences.hpp"
#include "profile_timer.hpp"
#include "screen_handling.hpp"
#include "settings_dialog.hpp"
#include "sound.hpp"
#include "stats.hpp"
#include "surface_cache.hpp"
#include "tbs_internal_server.hpp"
#include "theme_imgui.hpp"
#include "user_voxel_object.hpp"
#include "utils.hpp"
#include "variant_utils.hpp"
#include "globals.h"
extern bool g_mouse_event_swallowed;
extern std::map<std::string, variant> g_user_info_registry;
PREF_STRING(editor_object, "", "Object to use for the editor");
extern bool g_particle_editor;
extern int g_vsync;
void auto_select_resolution(const KRE::WindowPtr& wm, int& width, int& height, bool reduce, bool isFullscreen);
namespace
{
PREF_STRING(play_music_function, "", "");
void play_music_track(EntityPtr obj, const std::string& track)
{
if(g_play_music_function.empty() == false) {
ASSERT_LOG(obj.get(), "No object to play music");
static game_logic::FormulaPtr ffl(new game_logic::Formula(variant(g_play_music_function), &get_custom_object_functions_symbol_table()));
game_logic::MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable);
callable->add("music", variant(track));
callable->add("obj", variant(obj.get()));
variant cmd = ffl->execute(*callable);
obj->executeCommand(cmd);
} else {
sound::play_music(track);
}
}
std::vector<std::pair<std::function<void()>,void*>> process_functions;
std::deque<std::function<void()>> asynchronous_work_items_;
PREF_BOOL(editor_pause, false, "If true, the editor auto pauses when started");
PREF_INT(time_quota_async_work_items, 10, "Number of milliseconds allowed each frame for asynchronous/background work items to run");
PREF_BOOL(allow_debug_console_clicking, true, "Allow clicking on objects in the debug console to select them");
PREF_BOOL(reload_modified_objects, false, "Reload object definitions when their file is modified on disk");
PREF_INT(mouse_drag_threshold, 5, "Threshold for how much motion can take place in a mouse drag");
PREF_FLOAT(global_scale, 1.0f, "Global scale value.");
PREF_BOOL(allow_builtin_settings_dialog, true, "Allow the builtin Anura settings dialog");
PREF_INT(max_frame_skips, 3, "Maximum frames to skip due to performance");
PREF_STRING(editor_controller, "", "Object used when the editor is started");
PREF_BOOL_PERSISTENT(skip_odd_frames, false, "Skips every other frame");
PREF_BOOL(theme_imgui_ui, false, "Displays a dialog to customize the ImGui User Interface.");
LevelRunner* current_level_runner = nullptr;
class current_level_runner_scope
{
LevelRunner* old_;
public:
current_level_runner_scope(LevelRunner* value)
: old_(current_level_runner)
{
current_level_runner = value;
}
~current_level_runner_scope() {
current_level_runner = old_;
}
};
struct upload_screenshot_info
{
upload_screenshot_info()
: error(false), done(false), client(new http_client("www.theargentlark.com", "80"))
{
client->set_timeout_and_retry();
}
void finished(std::string response, bool is_error) {
LOG_INFO("Finished(" << is_error << ", " << response << ")");
result = response;
error = is_error;
done = true;
}
std::string result;
bool error;
bool done;
ffl::IntrusivePtr<http_client> client;
};
void upload_screenshot(std::string file, std::shared_ptr<upload_screenshot_info> info)
{
// XXX we should read the server address from some sort of configuration file.
using std::placeholders::_1;
std::string user_parm;
if(g_user_info_registry["user"].is_string()) {
user_parm = "&user=" + g_user_info_registry["user"].as_string();
}
info->client->send_request("POST /cgi-bin/upload-screenshot.pl?module=" + module::get_module_name() + user_parm,
base64::b64encode(sys::read_file(file)),
std::bind(&upload_screenshot_info::finished, info.get(), _1, false),
std::bind(&upload_screenshot_info::finished, info.get(), _1, true),
[](size_t,size_t,bool){});
while(!info->done) {
info->client->process();
}
}
void done_upload_screenshot(std::shared_ptr<upload_screenshot_info> info)
{
try {
if(info->error == false) {
LOG_INFO("DONE UPLOAD SCREENSHOT (" << info->result << ")");
variant v = json::parse(info->result, json::JSON_PARSE_OPTIONS::NO_PREPROCESSOR);
debug_console::addMessage(formatter() << "Uploaded screenshot to " << v["url"].as_string() << " (set url in clipboard)");;
copy_to_clipboard(v["url"].as_string());
}
} catch(...) {
info->error = true;
}
if(info->error) {
debug_console::addMessage("error uploading screenshot");
}
}
int skipping_game = 0;
int global_pause_time;
typedef std::function<void(const Level&, screen_position&, float)> TransitionFn;
//prepare to call transition_scene by making sure that frame buffers are
//filled with the image of the screen.
void prepare_transition_scene(Level& lvl, screen_position& screen_pos)
{
draw_scene(lvl, screen_pos);
KRE::WindowManager::getMainWindow()->swap();
}
void transition_scene(Level& lvl, screen_position& screen_pos, bool transition_out, const std::string& transition_type)
{
const int num_frames = lvl.setup_level_transition(transition_type);
if(lvl.player()) {
lvl.player()->getEntity().setInvisible(true);
}
Level::set_level_transition_ratio(decimal(0.0f));
const int start_time = profile::get_tick_time();
auto wnd = KRE::WindowManager::getMainWindow();
for(int n = 0; n <= num_frames; ++n) {
Level::set_level_transition_ratio(decimal(static_cast<float>(n)/static_cast<float>(num_frames)));
lvl.process_draw();
render_scene(lvl, screen_pos);
KRE::WindowManager::getMainWindow()->swap();
const int target_end_time = start_time + (n+1)*preferences::frame_time_millis();
const int current_time = profile::get_tick_time();
const int skip_time = target_end_time - current_time;
if(skip_time > 0) {
profile::delay(skip_time);
}
}
Level::set_level_transition_ratio(decimal(0.0f));
if(lvl.player()) {
lvl.player()->getEntity().setInvisible(false);
}
}
void fade_scene(const Level& lvl, screen_position& screen_pos, float fade)
{
auto& gs = graphics::GameScreen::get();
KRE::Canvas::getInstance()->drawSolidRect(rect(0,0,gs.getVirtualWidth(),gs.getVirtualHeight()),KRE::Color(0.0f, 0.0f, 0.0f, 0.5f*fade));
}
void flip_scene(const Level& lvl, screen_position& screen_pos, float amount)
{
screen_pos.flip_rotate = static_cast<int>(amount*1000);
draw_scene(lvl, screen_pos);
}
void show_end_game()
{
auto& gs = graphics::GameScreen::get();
const std::string msg = "to be continued...";
auto t = KRE::Font::getInstance()->renderText(msg, KRE::Color::colorWhite(), 48);
auto wnd = KRE::WindowManager::getMainWindow();
auto canvas = KRE::Canvas::getInstance();
const int xpos = gs.getVirtualWidth()/2 - t->width()/2;
const int ypos = gs.getVirtualHeight()/2 - t->height()/2;
for(unsigned n = 0; n <= msg.size(); ++n) {
const float percent = static_cast<float>(n)/static_cast<float>(msg.size());
canvas->drawSolidRect(rect(0, 0, gs.getVirtualWidth(), gs.getVirtualHeight()), KRE::Color::colorBlack());
canvas->blitTexture(t, rect(0,0,static_cast<int>(percent*gs.getVirtualWidth()),0), 0,
rect(xpos, ypos,static_cast<int>(t->width()*percent), t->height()));
wnd->swap();
profile::delay(40);
}
bool done = false;
while(!done) {
SDL_Event event;
while(input::sdl_poll_event(&event)) {
switch(event.type) {
case SDL_QUIT:
case SDL_KEYDOWN:
done = true;
break;
}
}
joystick::update();
for(int n = 0; n != 6; ++n) {
if(joystick::button(n)) {
done = true;
}
}
}
}
}
namespace {
int TranslateCoordinatesPhysicalToVirtual(int pos, int virt, int phys) {
return (pos * virt) / phys;
}
}
void mapSDLEventScreenCoordinatesToVirtual(SDL_Event& event)
{
switch(event.type) {
case SDL_MOUSEMOTION: {
auto& gs = graphics::GameScreen::get();
event.motion.x = TranslateCoordinatesPhysicalToVirtual(event.motion.x, gs.getVirtualWidth(), gs.getWidth());
event.motion.y = TranslateCoordinatesPhysicalToVirtual(event.motion.y, gs.getVirtualHeight(), gs.getHeight());
event.motion.xrel = TranslateCoordinatesPhysicalToVirtual(event.motion.xrel, gs.getVirtualWidth(), gs.getWidth());
event.motion.yrel = TranslateCoordinatesPhysicalToVirtual(event.motion.yrel, gs.getVirtualHeight(), gs.getHeight());
break;
}
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP: {
auto& gs = graphics::GameScreen::get();
event.button.x = TranslateCoordinatesPhysicalToVirtual(event.button.x, gs.getVirtualWidth(), gs.getWidth());
event.button.y = TranslateCoordinatesPhysicalToVirtual(event.button.y, gs.getVirtualHeight(), gs.getHeight());
break;
}
}
}
void addProcessFunction(std::function<void()> fn, void* tag)
{
process_functions.emplace_back(fn, tag);
}
void removeProcessFunction(void* tag)
{
process_functions.erase(std::remove_if(process_functions.begin(), process_functions.end(), [&tag](const std::pair<std::function<void()>,void*>& p) { return p.second == tag; }), process_functions.end());
}
void addAsynchronousWorkItem(std::function<void()> fn)
{
asynchronous_work_items_.push_back(fn);
}
void begin_skipping_game()
{
++skipping_game;
}
void end_skipping_game()
{
skipping_game = 0;
}
bool is_skipping_game()
{
return skipping_game > 0;
}
// XXX We should handle the window resize event in the WindowManager code
void video_resize(const SDL_Event &event)
{
if(preferences::get_screen_mode() == preferences::ScreenMode::WINDOWED) {
int width = event.window.data1;
int height = event.window.data2;
const float aspect = graphics::GameScreen::get().getAspectRatio();
const float wa = static_cast<float>(width) * aspect;
const float ha = static_cast<float>(height) * aspect;
if(graphics::GameScreen::get().getSquareArea() < width * height) {
//making the window larger
if(ha > static_cast<float>(width)) {
width = static_cast<int>(ha);
} else if(ha < static_cast<float>(width)) {
height = static_cast<int>(wa);
}
} else {
//making the window smaller
if(ha > static_cast<float>(width)) {
height = static_cast<int>(wa);
} else if(ha < static_cast<float>(width)) {
width = static_cast<int>(ha);
}
}
//make sure we don't have some ugly fractional aspect ratio
while(static_cast<float>(width)/static_cast<float>(height) != aspect) {
++width;
height = static_cast<int>(static_cast<float>(width)/aspect);
}
// XXX If we're in the editor this isn't right.
graphics::GameScreen::get().setDimensions(width, height);
KRE::WindowManager::getMainWindow()->notifyNewWindowSize(width, height);
}
}
void LevelRunner::video_resize_event(const SDL_Event &event)
{
// event.window.data1/event.window.data2 may not reflect the correct window size.
static const int WindowResizeEventID = get_object_event_id("window_resize");
game_logic::MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable);
callable->add("width", variant(KRE::WindowManager::getMainWindow()->width()));
callable->add("height", variant(KRE::WindowManager::getMainWindow()->height()));
std::vector<EntityPtr> chars = lvl_->get_chars();
for(EntityPtr e : chars) {
e->handleEvent(WindowResizeEventID, callable.get());
}
}
void LevelRunner::on_player_set(EntityPtr e)
{
#ifndef NO_EDITOR
if(console_.get()) {
console_->setFocus(e);
}
#endif
}
#if 0
void LevelRunner::handle_mouse_over_voxel_objects(const SDL_Event &event,
const std::vector<voxel::UserVoxelObjectPtr>& voxel_objs,
game_logic::MapFormulaCallablePtr callable,
const int basic_evt,
const int catch_all_event)
{
static const int MouseEnterID = get_object_event_id("mouse_enter");
static const int MouseLeaveID = get_object_event_id("mouse_leave");
if(!lvl_->iso_world()) {
return;
}
std::set<voxel::UserVoxelObjectPtr> mouse_in;
for(auto obj : voxel_objs) {
if(event.type == SDL_MOUSEBUTTONDOWN) {
} else if(event.type == SDL_MOUSEMOTION) {
if(obj->is_mouseover_object() == false) {
obj->set_mouseover_object();
obj->handleEvent(MouseEnterID, callable.get());
}
mouse_in.insert(obj);
}
obj->handleEvent(basic_evt, callable.get());
}
for(auto obj : lvl_->iso_world()->getObjects()) {
obj->handleEvent(catch_all_event, callable.get());
if(event.type == SDL_MOUSEMOTION) {
if(mouse_in.find(obj) == mouse_in.end() && obj->is_mouseover_object()) {
obj->set_mouseover_object(false);
obj->handleEvent(MouseLeaveID, callable.get());
}
}
}
}
#endif
bool LevelRunner::handle_mouse_events(const SDL_Event &event)
{
static const int MouseDownEventID = get_object_event_id("mouse_down");
static const int MouseUpEventID = get_object_event_id("mouse_up");
static const int MouseMoveEventID = get_object_event_id("mouse_move");
static const int MouseDownEventAllID = get_object_event_id("mouse_down*");
static const int MouseUpEventAllID = get_object_event_id("mouse_up*");
static const int MouseMoveEventAllID = get_object_event_id("mouse_move*");
static const int MouseEnterID = get_object_event_id("mouse_enter");
static const int MouseLeaveID = get_object_event_id("mouse_leave");
static const int MouseClickID = get_object_event_id("click");
//static const int MouseDblClickID = get_object_event_id("dblclick");
static const int MouseDragID = get_object_event_id("drag");
static const int MouseDragStartID = get_object_event_id("drag_start");
static const int MouseDragEndID = get_object_event_id("drag_end");
static const int MouseWheelID = get_object_event_id("mouse_wheel");
g_mouse_event_swallowed = false;
if(paused) {
// skip mouse event handling when paused.
// XXX: when we become unpaused we need to reset the state of drag operations
// and partial clicks.
return false;
}
const int DragThresholdPx = g_mouse_drag_threshold;
switch(event.type)
{
case SDL_MOUSEWHEEL: {
game_logic::MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable);
callable->add("yscroll", variant(event.wheel.y));
std::vector<EntityPtr> chars = lvl_->get_active_chars();
for(auto e : chars) {
e->handleEvent(MouseWheelID, callable.get());
}
break;
}
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
mouse_drag_count_ = 0;
case SDL_MOUSEMOTION: {
int x, mx = event.type == SDL_MOUSEMOTION ? event.motion.x : event.button.x;
int y, my = event.type == SDL_MOUSEMOTION ? event.motion.y : event.button.y;
int event_type = event.type;
int event_button_button = event.button.button;
x = mx;
y = my;
const int basic_evt = event_type == SDL_MOUSEBUTTONDOWN
? MouseDownEventID
: event_type == SDL_MOUSEMOTION
? MouseMoveEventID : MouseUpEventID;
const int catch_all_event = event_type == SDL_MOUSEBUTTONDOWN
? MouseDownEventAllID
: event_type == SDL_MOUSEMOTION
? MouseMoveEventAllID : MouseUpEventAllID;
Uint8 button_state = input::sdl_get_mouse_state(0,0);
x += last_draw_position().x/100;
y += last_draw_position().y/100;
game_logic::MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable);
callable->add("mouse_x", variant(x));
callable->add("mouse_y", variant(y));
if(event_type != SDL_MOUSEMOTION) {
callable->add("mouse_button", variant(event_button_button));
} else {
callable->add("mouse_button", variant(button_state));
}
std::vector<EntityPtr> wcs;
std::vector<variant> items;
// Grab characters around point, z-order sort them, so that when
// we process them we go from highest to lowest, allowing a higher
// object to swallow an event before the lower ones get it.
std::vector<EntityPtr> cs = lvl_->get_characters_at_point(x, y, last_draw_position().x/100, last_draw_position().y/100);
cs.insert(cs.end(), wcs.begin(), wcs.end());
//zorder_compare sorts lowest-to-highest, so we do that
//then reverse.
std::sort(cs.begin(), cs.end(), zorder_compare);
std::reverse(cs.begin(), cs.end());
bool handled = false;
bool click_handled = false;
std::set<EntityPtr> mouse_in;
for(auto& it : cs) {
EntityPtr& e = it;
rect m_area = e->getMouseOverArea();
m_area += point(e->x(), e->y());
// n.b. mouse_over_area is relative to the object.
if(m_area.w() != 0) {
point p(x,y);
if(e->useAbsoluteScreenCoordinates()) {
p = point(mx + lvl_->absolute_object_adjust_x(),my + lvl_->absolute_object_adjust_y());
}
if(pointInRect(p, m_area) == false) {
continue;
}
}
rect clip_area;
if(e->getClipArea(&clip_area)) {
point p(x,y);
if(e->useAbsoluteScreenCoordinates()) {
int xadj = 0, yadj = 0;
auto& gs = graphics::GameScreen::get();
if(gs.getVirtualWidth() > lvl_->boundaries().w()) {
xadj = (gs.getVirtualWidth() - lvl_->boundaries().w());
}
if(gs.getVirtualHeight() > lvl_->boundaries().h()) {
yadj = (gs.getVirtualHeight() - lvl_->boundaries().h());
}
p = point(mx + lvl_->absolute_object_adjust_x() - xadj,my + lvl_->absolute_object_adjust_y() - yadj);
}
if(pointInRect(p, clip_area) == false) {
continue;
}
}
if(event_type == SDL_MOUSEBUTTONDOWN) {
e->setMouseButtons(e->getMouseButtons() | SDL_BUTTON(event_button_button));
} else if(event_type == SDL_MOUSEMOTION) {
mouse_drag_count_ += abs(event.motion.xrel) + abs(event.motion.yrel);
// handling for mouse_enter
if(e->isMouseOverEntity() == false) {
if((e->getMouseoverDelay() == 0 || static_cast<unsigned>(lvl_->cycle()) > e->getMouseoverTriggerCycle())) {
e->handleEvent(MouseEnterID, callable.get());
e->setMouseOverEntity();
} else if(e->getMouseoverTriggerCycle() == std::numeric_limits<int>::max()) {
e->setMouseoverTriggerCycle(e->getMouseoverDelay() + lvl_->cycle());
}
}
mouse_in.insert(e);
}
if(e->isMouseOverEntity() || basic_evt != MouseMoveEventID) {
//only give mouse move events if we've actually
//recordered a mouse_enter event.
handled |= e->handleEvent(basic_evt, callable.get());
}
if(event_type == SDL_MOUSEBUTTONUP && mouse_clicking_ && !click_handled && e->isBeingDragged() == false && mouse_drag_count_ <= DragThresholdPx) {
e->handleEvent(MouseClickID, callable.get());
if(g_mouse_event_swallowed) {
click_handled = true;
g_mouse_event_swallowed = false;
}
}
items.emplace_back(e.get());
}
// Handling for "catch all" mouse events.
callable->add("handled", variant::from_bool(handled));
variant obj_ary(&items);
callable->add("objects_under_mouse", obj_ary);
std::vector<EntityPtr> level_chars(Level::current().get_chars());
//make events happen with highest zorder objects first.
std::sort(level_chars.begin(), level_chars.end(), zorder_compare);
std::reverse(level_chars.begin(), level_chars.end());
bool drag_handled = false;
for(EntityPtr object : level_chars) {
if(object) {
object->handleEvent(catch_all_event, callable.get());
// drag handling
if(event_type == SDL_MOUSEBUTTONUP && !drag_handled) {
object->setMouseButtons(object->getMouseButtons() & ~SDL_BUTTON(event_button_button));
if(object->getMouseButtons() == 0 && object->isBeingDragged()) {
object->handleEvent(MouseDragEndID, callable.get());
object->setBeingDragged(false);
if(g_mouse_event_swallowed) {
drag_handled = true;
g_mouse_event_swallowed = false;
}
}
} else if(event_type == SDL_MOUSEMOTION && !drag_handled) {
// drag check.
if(object->isBeingDragged()) {
if(object->getMouseButtons() & button_state) {
object->handleEvent(MouseDragID, callable.get());
} else {
object->handleEvent(MouseDragEndID, callable.get());
object->setBeingDragged(false);
}
if(g_mouse_event_swallowed) {
drag_handled = true;
g_mouse_event_swallowed = false;
}
} else if(object->getMouseButtons() & button_state && mouse_drag_count_ > object->mouseDragThreshold(DragThresholdPx)) {
// start drag.
object->handleEvent(MouseDragStartID, callable.get());
object->setBeingDragged();
if(g_mouse_event_swallowed) {
drag_handled = true;
g_mouse_event_swallowed = false;
}
}
}
}
}
if(event_type == SDL_MOUSEMOTION) {
// handling for mouse_leave
level_chars = Level::current().get_chars();
//make events happen with highest zorder objects first.
std::sort(level_chars.begin(), level_chars.end(), zorder_compare);
std::reverse(level_chars.begin(), level_chars.end());
for(const EntityPtr& e : level_chars) {
if(!e) {
continue;
}
rect m_area = e->getMouseOverArea();
m_area += point(e->x(), e->y());
bool has_m_area = m_area.w() != 0;
point p(x,y);
if(e->useAbsoluteScreenCoordinates()) {
p = point(mx + lvl_->absolute_object_adjust_x(),my + lvl_->absolute_object_adjust_y());
}
if(mouse_in.find(e) == mouse_in.end()) {
e->setMouseoverTriggerCycle(std::numeric_limits<int>::max());
}
if(mouse_in.find(e) == mouse_in.end()) {
if(has_m_area == false) {
if(e->isMouseOverEntity()) {
e->handleEvent(MouseLeaveID, callable.get());
e->setMouseOverEntity(false);
}
} else {
if(pointInRect(p, m_area) == false && e->isMouseOverEntity()) {
e->handleEvent(MouseLeaveID, callable.get());
e->setMouseOverEntity(false);
}
}
}
}
}
if(event.type == SDL_MOUSEMOTION && mouse_drag_count_ <= DragThresholdPx) {
break;
}
mouse_clicking_ = event.type == SDL_MOUSEBUTTONDOWN;
break;
} //end mouse motion event case
}
return false;
}
extern bool g_enable_graphical_fonts;
void LevelRunner::show_pause_title()
{
if(!editor_ && g_enable_graphical_fonts) {
set_scene_title("Paused\n\n\n(ctrl-p)", paused ? std::numeric_limits<int>::max() : 25);
}
}
LevelRunner* LevelRunner::getCurrent()
{
return current_level_runner;
}
LevelRunner::LevelRunner(LevelPtr& lvl, std::string& level_cfg, std::string& original_level_cfg)
: lvl_(lvl),
level_cfg_(level_cfg),
original_level_cfg_(original_level_cfg),
#ifndef NO_EDITOR
history_trails_state_id_(-1),
object_reloads_state_id_(-1),
tile_rebuild_state_id_(-1),
#endif
editor_(nullptr)
{
quit_ = false;
force_return_ = false;
current_second_ = time(nullptr);
current_max_ = 0;
next_max_ = 0;
current_fps_ = 0;
next_fps_ = 0;
current_cycles_ = 0;
next_cycles_ = 0;
current_delay_ = 0;
next_delay_ = 0;
current_draw_ = 0;
next_draw_ = 0;
current_flip_ = 0;
next_flip_ = 0;
current_process_ = 0;
next_process_ = 0;
current_events_ = 0;
nskip_draw_ = 0;
cycle = 0;
die_at = -1;
paused = false;
done = false;
start_time_ = profile::get_tick_time();
pause_time_ = -global_pause_time;
mouse_clicking_ = false;
mouse_drag_count_ = 0;
}
void LevelRunner::start_editor()
{
#ifndef NO_EDITOR
if(!editor_) {
controls::control_backup_scope ctrl_backup;
editor_ = editor::get_editor(lvl_->id().c_str());
editor_resolution_manager_.reset(new EditorResolutionManager(editor_->xres(), editor_->yres()));
editor_->set_playing_level(lvl_);
editor_->setup_for_editing();
lvl_->set_editor();
lvl_->setAsCurrentLevel();
lvl_->player()->getEntity().handleEvent("open_editor");
initHistorySlider();
if(g_editor_object.empty() == false) {
ffl::IntrusivePtr<CustomObject> obj(new CustomObject(g_editor_object, 0, 0, 1));
obj->construct();
lvl_->add_character(obj);
}
if(g_editor_pause) {
start_editor();
}
} else {
//Pause the game and set the level to its original
//state if the user presses ctrl+e twice.
paused = !paused;
show_pause_title();
editor_->reset_playing_level(false);
last_draw_position().init = false;
initHistorySlider();
if(!paused) {
controls::read_until(lvl_->cycle());
}
}
#endif
}
void LevelRunner::close_editor()
{
LOG_DEBUG("LevelRunner::close_editor()");
#ifndef NO_EDITOR
if(editor_->mouselook_mode()) {
SDL_SetRelativeMouseMode(SDL_FALSE);
}
editor_ = nullptr;
editor_resolution_manager_.reset();
history_slider_.reset();
history_button_.reset();
history_trails_.clear();
lvl_->mutateValue("zoom", variant(1));
lvl_->set_editor(false);
lvl_->player()->getEntity().handleEvent("close_editor");
paused = false;
show_pause_title();
// controls::read_until(lvl_->cycle());
initHistorySlider();
#endif
}
bool LevelRunner::play_level()
{
const current_level_runner_scope current_level_runner_setter(this);
sound::stop_looped_sounds(nullptr);
lvl_->setAsCurrentLevel();
bool reversing = false;
if(preferences::edit_on_start()) {
start_editor();
}
if(!lvl_->music().empty()) {
EntityPtr e;
if(lvl_->player()) {
e = EntityPtr(&lvl_->player()->getEntity());
}
play_music_track(e, lvl_->music());
}
while(!done && !quit_ && !force_return_) {
const Uint8 *key = SDL_GetKeyboardState(nullptr);
if(key[SDL_SCANCODE_T] && preferences::record_history()
#ifndef NO_EDITOR
&& (!editor_ || !editor_->hasKeyboardFocus())
&& (!console_ || !console_->hasKeyboardFocus())
#endif
) {
if(!reversing) {
pause_time_ -= profile::get_tick_time();
}
reverse_cycle();
reversing = true;
} else {
if(reversing) {
controls::read_until(lvl_->cycle());
pause_time_ += profile::get_tick_time();
}
reversing = false;
bool res = play_cycle();
if(!res) {
return quit_;
}
if(preferences::record_history()) {
lvl_->backup();
}
}
}
std::vector<EntityPtr> chars = lvl_->get_chars();
for(EntityPtr e : chars) {
e->handleEvent(OBJECT_EVENT_BEING_REMOVED);
}
return quit_;
}
namespace
{
std::set<std::string> g_levels_modified;
void level_file_modified(std::string lvl_path)
{
g_levels_modified.insert(lvl_path);
}
}
void process_tbs_matchmaking_server();
bool LevelRunner::play_cycle()
{
formula_profiler::pump();
const int start_cycle_time = profile::get_tick_time();
auto wnd = KRE::WindowManager::getMainWindow();
static SettingsDialog settingsDialog;
for(auto& p : process_functions) {
p.first();
}
const preferences::alt_frame_time_scope alt_frame_time_scoper(preferences::has_alt_frame_time() && SDL_GetModState()&KMOD_ALT);
if(controls::first_invalid_cycle() >= 0) {
lvl_->replay_from_cycle(controls::first_invalid_cycle());
controls::mark_valid();
}
background_task_pool::pump();
performance_data current_perf(current_max_,current_fps_,50,0,0,0,0,0,CustomObject::events_handled_per_second,"");
if(preferences::internal_tbs_server()) {
tbs::internal_server::process();
}
process_tbs_matchmaking_server();
if(controls::num_players() > 1) {
lvl_->backup();
}
std::unique_ptr<controls::local_controls_lock> controls_lock;
#ifndef NO_EDITOR
if((editor_ && editor_->hasKeyboardFocus()) ||
(console_ && console_->hasKeyboardFocus())) {
controls_lock.reset(new controls::local_controls_lock);
}
if(editor_ && lvl_->player() == nullptr && !paused) {
//force the game to paused in the editor with no player.
paused = true;
}
static bool pumped_file_mods = false;
if(editor_ || console_ || pumped_file_mods || g_reload_modified_objects) {
sys::pump_file_modifications();
pumped_file_mods = true;
}
if(!editor_ && g_reload_modified_objects) {
CustomObjectType::reloadModifiedCode();
}
if(editor_) {
controls::control_backup_scope ctrl_backup;
auto& gs = graphics::GameScreen::get();
editor_->setPos(last_draw_position().x/100 - (editor_->zoom() - 1) * gs.getVirtualWidth()/2,
last_draw_position().y/100 - (editor_->zoom() - 1) * gs.getVirtualHeight()/2);
//editor_->setPos(last_draw_position().x/100 - (editor_->zoom()-1)*(gs.getVirtualWidth()-editor::sidebar_width())/2, last_draw_position().y/100 - (editor_->zoom()-1)*(gs.getVirtualHeight())/2);
editor_->process();
lvl_->complete_rebuild_tiles_in_background();
lvl_->setAsCurrentLevel();
lvl_->mutateValue("zoom", variant(decimal(1.0/editor_->zoom())));
CustomObjectType::reloadModifiedCode();
// XXX graphics::texture::clear_modified_files_from_cache();
if(lvl_->cycle()%25 == 0) {
Background::loadModifiedBackgrounds();
}