forked from minetest/minetest
-
Notifications
You must be signed in to change notification settings - Fork 10
/
game.cpp
4458 lines (3720 loc) · 129 KB
/
game.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
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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 "game.h"
#include <iomanip>
#include <cmath>
#include "client/renderingengine.h"
#include "camera.h"
#include "client.h"
#include "client/clientevent.h"
#include "client/gameui.h"
#include "client/inputhandler.h"
#include "client/tile.h" // For TextureSource
#include "client/keys.h"
#include "client/joystick_controller.h"
#include "clientmap.h"
#include "clouds.h"
#include "config.h"
#include "content_cao.h"
#include "content/subgames.h"
#include "client/event_manager.h"
#include "fontengine.h"
#include "itemdef.h"
#include "log.h"
#include "filesys.h"
#include "gameparams.h"
#include "gettext.h"
#include "gui/guiChatConsole.h"
#include "gui/guiFormSpecMenu.h"
#include "gui/guiKeyChangeMenu.h"
#include "gui/guiPasswordChange.h"
#include "gui/guiVolumeChange.h"
#include "gui/mainmenumanager.h"
#include "gui/profilergraph.h"
#include "mapblock.h"
#include "minimap.h"
#include "nodedef.h" // Needed for determining pointing to nodes
#include "nodemetadata.h"
#include "particles.h"
#include "porting.h"
#include "profiler.h"
#include "raycast.h"
#include "server.h"
#include "settings.h"
#include "shader.h"
#include "sky.h"
#include "translation.h"
#include "util/basic_macros.h"
#include "util/directiontables.h"
#include "util/pointedthing.h"
#include "util/quicktune_shortcutter.h"
#include "irrlicht_changes/static_text.h"
#include "irr_ptr.h"
#include "version.h"
#include "script/scripting_client.h"
#include "hud.h"
#if USE_SOUND
#include "client/sound_openal.h"
#else
#include "client/sound.h"
#endif
/*
Text input system
*/
struct TextDestNodeMetadata : public TextDest
{
TextDestNodeMetadata(v3s16 p, Client *client)
{
m_p = p;
m_client = client;
}
// This is deprecated I guess? -celeron55
void gotText(const std::wstring &text)
{
std::string ntext = wide_to_utf8(text);
infostream << "Submitting 'text' field of node at (" << m_p.X << ","
<< m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
StringMap fields;
fields["text"] = ntext;
m_client->sendNodemetaFields(m_p, "", fields);
}
void gotText(const StringMap &fields)
{
m_client->sendNodemetaFields(m_p, "", fields);
}
v3s16 m_p;
Client *m_client;
};
struct TextDestPlayerInventory : public TextDest
{
TextDestPlayerInventory(Client *client)
{
m_client = client;
m_formname.clear();
}
TextDestPlayerInventory(Client *client, const std::string &formname)
{
m_client = client;
m_formname = formname;
}
void gotText(const StringMap &fields)
{
m_client->sendInventoryFields(m_formname, fields);
}
Client *m_client;
};
struct LocalFormspecHandler : public TextDest
{
LocalFormspecHandler(const std::string &formname)
{
m_formname = formname;
}
LocalFormspecHandler(const std::string &formname, Client *client):
m_client(client)
{
m_formname = formname;
}
void gotText(const StringMap &fields)
{
if (m_formname == "MT_PAUSE_MENU") {
if (fields.find("btn_sound") != fields.end()) {
g_gamecallback->changeVolume();
return;
}
if (fields.find("btn_key_config") != fields.end()) {
g_gamecallback->keyConfig();
return;
}
if (fields.find("btn_exit_menu") != fields.end()) {
g_gamecallback->disconnect();
return;
}
if (fields.find("btn_exit_os") != fields.end()) {
g_gamecallback->exitToOS();
#ifndef __ANDROID__
RenderingEngine::get_raw_device()->closeDevice();
#endif
return;
}
if (fields.find("btn_change_password") != fields.end()) {
g_gamecallback->changePassword();
return;
}
return;
}
if (m_formname == "MT_DEATH_SCREEN") {
assert(m_client != 0);
m_client->sendRespawn();
return;
}
if (m_client->modsLoaded())
m_client->getScript()->on_formspec_input(m_formname, fields);
}
Client *m_client = nullptr;
};
/* Form update callback */
class NodeMetadataFormSource: public IFormSource
{
public:
NodeMetadataFormSource(ClientMap *map, v3s16 p):
m_map(map),
m_p(p)
{
}
const std::string &getForm() const
{
static const std::string empty_string = "";
NodeMetadata *meta = m_map->getNodeMetadata(m_p);
if (!meta)
return empty_string;
return meta->getString("formspec");
}
virtual std::string resolveText(const std::string &str)
{
NodeMetadata *meta = m_map->getNodeMetadata(m_p);
if (!meta)
return str;
return meta->resolveString(str);
}
ClientMap *m_map;
v3s16 m_p;
};
class PlayerInventoryFormSource: public IFormSource
{
public:
PlayerInventoryFormSource(Client *client):
m_client(client)
{
}
const std::string &getForm() const
{
LocalPlayer *player = m_client->getEnv().getLocalPlayer();
return player->inventory_formspec;
}
Client *m_client;
};
class NodeDugEvent: public MtEvent
{
public:
v3s16 p;
MapNode n;
NodeDugEvent(v3s16 p, MapNode n):
p(p),
n(n)
{}
MtEvent::Type getType() const
{
return MtEvent::NODE_DUG;
}
};
class SoundMaker
{
ISoundManager *m_sound;
const NodeDefManager *m_ndef;
public:
bool makes_footstep_sound;
float m_player_step_timer;
float m_player_jump_timer;
SimpleSoundSpec m_player_step_sound;
SimpleSoundSpec m_player_leftpunch_sound;
SimpleSoundSpec m_player_rightpunch_sound;
SoundMaker(ISoundManager *sound, const NodeDefManager *ndef):
m_sound(sound),
m_ndef(ndef),
makes_footstep_sound(true),
m_player_step_timer(0.0f),
m_player_jump_timer(0.0f)
{
}
void playPlayerStep()
{
if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
m_player_step_timer = 0.03;
if (makes_footstep_sound)
m_sound->playSound(m_player_step_sound);
}
}
void playPlayerJump()
{
if (m_player_jump_timer <= 0.0f) {
m_player_jump_timer = 0.2f;
m_sound->playSound(SimpleSoundSpec("player_jump", 0.5f));
}
}
static void viewBobbingStep(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->playPlayerStep();
}
static void playerRegainGround(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->playPlayerStep();
}
static void playerJump(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->playPlayerJump();
}
static void cameraPunchLeft(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->m_sound->playSound(sm->m_player_leftpunch_sound);
}
static void cameraPunchRight(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->m_sound->playSound(sm->m_player_rightpunch_sound);
}
static void nodeDug(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
NodeDugEvent *nde = (NodeDugEvent *)e;
sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug);
}
static void playerDamage(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5));
}
static void playerFallingDamage(MtEvent *e, void *data)
{
SoundMaker *sm = (SoundMaker *)data;
sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5));
}
void registerReceiver(MtEventManager *mgr)
{
mgr->reg(MtEvent::VIEW_BOBBING_STEP, SoundMaker::viewBobbingStep, this);
mgr->reg(MtEvent::PLAYER_REGAIN_GROUND, SoundMaker::playerRegainGround, this);
mgr->reg(MtEvent::PLAYER_JUMP, SoundMaker::playerJump, this);
mgr->reg(MtEvent::CAMERA_PUNCH_LEFT, SoundMaker::cameraPunchLeft, this);
mgr->reg(MtEvent::CAMERA_PUNCH_RIGHT, SoundMaker::cameraPunchRight, this);
mgr->reg(MtEvent::NODE_DUG, SoundMaker::nodeDug, this);
mgr->reg(MtEvent::PLAYER_DAMAGE, SoundMaker::playerDamage, this);
mgr->reg(MtEvent::PLAYER_FALLING_DAMAGE, SoundMaker::playerFallingDamage, this);
}
void step(float dtime)
{
m_player_step_timer -= dtime;
m_player_jump_timer -= dtime;
}
};
// Locally stored sounds don't need to be preloaded because of this
class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
{
std::set<std::string> m_fetched;
private:
void paths_insert(std::set<std::string> &dst_paths,
const std::string &base,
const std::string &name)
{
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
}
public:
void fetchSounds(const std::string &name,
std::set<std::string> &dst_paths,
std::set<std::string> &dst_datas)
{
if (m_fetched.count(name))
return;
m_fetched.insert(name);
paths_insert(dst_paths, porting::path_share, name);
paths_insert(dst_paths, porting::path_user, name);
}
};
typedef s32 SamplerLayer_t;
class GameGlobalShaderConstantSetter : public IShaderConstantSetter
{
Sky *m_sky;
Client *m_client;
bool *m_force_fog_off;
f32 *m_fog_range;
bool m_fog_enabled;
CachedPixelShaderSetting<float, 4> m_sky_bg_color;
CachedPixelShaderSetting<float> m_fog_distance;
CachedVertexShaderSetting<float> m_animation_timer_vertex;
CachedPixelShaderSetting<float> m_animation_timer_pixel;
CachedPixelShaderSetting<float, 3> m_day_light;
CachedPixelShaderSetting<float, 4> m_star_color;
CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
CachedPixelShaderSetting<float, 3> m_minimap_yaw;
CachedPixelShaderSetting<float, 3> m_camera_offset_pixel;
CachedPixelShaderSetting<float, 3> m_camera_offset_vertex;
CachedPixelShaderSetting<SamplerLayer_t> m_texture0;
CachedPixelShaderSetting<SamplerLayer_t> m_texture1;
CachedPixelShaderSetting<SamplerLayer_t> m_texture2;
CachedPixelShaderSetting<SamplerLayer_t> m_texture3;
CachedPixelShaderSetting<float, 2> m_texel_size0;
std::array<float, 2> m_texel_size0_values;
CachedPixelShaderSetting<float> m_exposure_factor_pixel;
float m_user_exposure_factor;
bool m_bloom_enabled;
CachedPixelShaderSetting<float> m_bloom_intensity_pixel;
float m_bloom_intensity;
CachedPixelShaderSetting<float> m_bloom_radius_pixel;
float m_bloom_radius;
public:
void onSettingsChange(const std::string &name)
{
if (name == "enable_fog")
m_fog_enabled = g_settings->getBool("enable_fog");
if (name == "exposure_factor")
m_user_exposure_factor = g_settings->getFloat("exposure_factor", 0.1f, 10.0f);
if (name == "bloom_intensity")
m_bloom_intensity = g_settings->getFloat("bloom_intensity", 0.01f, 1.0f);
if (name == "bloom_radius")
m_bloom_radius = g_settings->getFloat("bloom_radius", 1.0f, 64.0f);
}
static void settingsCallback(const std::string &name, void *userdata)
{
reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
}
void setSky(Sky *sky) { m_sky = sky; }
GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
f32 *fog_range, Client *client) :
m_sky(sky),
m_client(client),
m_force_fog_off(force_fog_off),
m_fog_range(fog_range),
m_sky_bg_color("skyBgColor"),
m_fog_distance("fogDistance"),
m_animation_timer_vertex("animationTimer"),
m_animation_timer_pixel("animationTimer"),
m_day_light("dayLight"),
m_star_color("starColor"),
m_eye_position_pixel("eyePosition"),
m_eye_position_vertex("eyePosition"),
m_minimap_yaw("yawVec"),
m_camera_offset_pixel("cameraOffset"),
m_camera_offset_vertex("cameraOffset"),
m_texture0("texture0"),
m_texture1("texture1"),
m_texture2("texture2"),
m_texture3("texture3"),
m_texel_size0("texelSize0"),
m_exposure_factor_pixel("exposureFactor"),
m_bloom_intensity_pixel("bloomIntensity"),
m_bloom_radius_pixel("bloomRadius")
{
g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
g_settings->registerChangedCallback("exposure_factor", settingsCallback, this);
g_settings->registerChangedCallback("bloom_intensity", settingsCallback, this);
g_settings->registerChangedCallback("bloom_radius", settingsCallback, this);
m_fog_enabled = g_settings->getBool("enable_fog");
m_user_exposure_factor = g_settings->getFloat("exposure_factor", 0.1f, 10.0f);
m_bloom_enabled = g_settings->getBool("enable_bloom");
m_bloom_intensity = g_settings->getFloat("bloom_intensity", 0.01f, 1.0f);
m_bloom_radius = g_settings->getFloat("bloom_radius", 1.0f, 64.0f);
}
~GameGlobalShaderConstantSetter()
{
g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
}
void onSetConstants(video::IMaterialRendererServices *services) override
{
// Background color
video::SColor bgcolor = m_sky->getBgColor();
video::SColorf bgcolorf(bgcolor);
float bgcolorfa[4] = {
bgcolorf.r,
bgcolorf.g,
bgcolorf.b,
bgcolorf.a,
};
m_sky_bg_color.set(bgcolorfa, services);
// Fog distance
float fog_distance = 10000 * BS;
if (m_fog_enabled && !*m_force_fog_off)
fog_distance = *m_fog_range;
m_fog_distance.set(&fog_distance, services);
u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
video::SColorf sunlight;
get_sunlight_color(&sunlight, daynight_ratio);
float dnc[3] = {
sunlight.r,
sunlight.g,
sunlight.b };
m_day_light.set(dnc, services);
video::SColorf star_color = m_sky->getCurrentStarColor();
float clr[4] = {star_color.r, star_color.g, star_color.b, star_color.a};
m_star_color.set(clr, services);
u32 animation_timer = m_client->getEnv().getFrameTime() % 1000000;
float animation_timer_f = (float)animation_timer / 100000.f;
m_animation_timer_vertex.set(&animation_timer_f, services);
m_animation_timer_pixel.set(&animation_timer_f, services);
float eye_position_array[3];
v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
epos.getAs3Values(eye_position_array);
m_eye_position_pixel.set(eye_position_array, services);
m_eye_position_vertex.set(eye_position_array, services);
if (m_client->getMinimap()) {
float minimap_yaw_array[3];
v3f minimap_yaw = m_client->getMinimap()->getYawVec();
minimap_yaw.getAs3Values(minimap_yaw_array);
m_minimap_yaw.set(minimap_yaw_array, services);
}
float camera_offset_array[3];
v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS);
offset.getAs3Values(camera_offset_array);
m_camera_offset_pixel.set(camera_offset_array, services);
m_camera_offset_vertex.set(camera_offset_array, services);
SamplerLayer_t tex_id;
tex_id = 0;
m_texture0.set(&tex_id, services);
tex_id = 1;
m_texture1.set(&tex_id, services);
tex_id = 2;
m_texture2.set(&tex_id, services);
tex_id = 3;
m_texture3.set(&tex_id, services);
m_texel_size0.set(m_texel_size0_values.data(), services);
float exposure_factor = RenderingEngine::DEFAULT_EXPOSURE_FACTOR * m_user_exposure_factor;
if (std::isnan(exposure_factor))
exposure_factor = RenderingEngine::DEFAULT_EXPOSURE_FACTOR;
m_exposure_factor_pixel.set(&exposure_factor, services);
if (m_bloom_enabled) {
m_bloom_intensity_pixel.set(&m_bloom_intensity, services);
m_bloom_radius_pixel.set(&m_bloom_radius, services);
}
}
void onSetMaterial(const video::SMaterial &material)
{
video::ITexture *texture = material.getTexture(0);
if (texture) {
core::dimension2du size = texture->getSize();
m_texel_size0_values[0] = 1.f / size.Width;
m_texel_size0_values[1] = 1.f / size.Height;
}
else {
m_texel_size0_values[0] = 0.f;
m_texel_size0_values[1] = 0.f;
}
}
};
class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
{
Sky *m_sky;
bool *m_force_fog_off;
f32 *m_fog_range;
Client *m_client;
std::vector<GameGlobalShaderConstantSetter *> created_nosky;
public:
GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
f32 *fog_range, Client *client) :
m_sky(NULL),
m_force_fog_off(force_fog_off),
m_fog_range(fog_range),
m_client(client)
{}
void setSky(Sky *sky) {
m_sky = sky;
for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
ggscs->setSky(m_sky);
}
created_nosky.clear();
}
virtual IShaderConstantSetter* create()
{
auto *scs = new GameGlobalShaderConstantSetter(
m_sky, m_force_fog_off, m_fog_range, m_client);
if (!m_sky)
created_nosky.push_back(scs);
return scs;
}
};
#ifdef HAVE_TOUCHSCREENGUI
#define SIZE_TAG "size[11,5.5]"
#else
#define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
#endif
/****************************************************************************
****************************************************************************/
const static float object_hit_delay = 0.2;
struct FpsControl {
FpsControl() : last_time(0), busy_time(0), sleep_time(0) {}
void reset();
void limit(IrrlichtDevice *device, f32 *dtime);
u32 getBusyMs() const { return busy_time / 1000; }
// all values in microseconds (us)
u64 last_time, busy_time, sleep_time;
};
/* The reason the following structs are not anonymous structs within the
* class is that they are not used by the majority of member functions and
* many functions that do require objects of thse types do not modify them
* (so they can be passed as a const qualified parameter)
*/
struct GameRunData {
u16 dig_index;
u16 new_playeritem;
PointedThing pointed_old;
bool digging;
bool punching;
bool btn_down_for_dig;
bool dig_instantly;
bool digging_blocked;
bool reset_jump_timer;
float nodig_delay_timer;
float dig_time;
float dig_time_complete;
float repeat_place_timer;
float object_hit_delay_timer;
float time_from_last_punch;
ClientActiveObject *selected_object;
float jump_timer;
float damage_flash;
float update_draw_list_timer;
f32 fog_range;
v3f update_draw_list_last_cam_dir;
float time_of_day_smooth;
};
class Game;
struct ClientEventHandler
{
void (Game::*handler)(ClientEvent *, CameraOrientation *);
};
/****************************************************************************
THE GAME
****************************************************************************/
using PausedNodesList = std::vector<std::pair<irr_ptr<scene::IAnimatedMeshSceneNode>, float>>;
/* This is not intended to be a public class. If a public class becomes
* desirable then it may be better to create another 'wrapper' class that
* hides most of the stuff in this class (nothing in this class is required
* by any other file) but exposes the public methods/data only.
*/
class Game {
public:
Game();
~Game();
bool startup(bool *kill,
InputHandler *input,
RenderingEngine *rendering_engine,
const GameStartData &game_params,
std::string &error_message,
bool *reconnect,
ChatBackend *chat_backend);
void run();
void shutdown();
protected:
// Basic initialisation
bool init(const std::string &map_dir, const std::string &address,
u16 port, const SubgameSpec &gamespec);
bool initSound();
bool createSingleplayerServer(const std::string &map_dir,
const SubgameSpec &gamespec, u16 port);
// Client creation
bool createClient(const GameStartData &start_data);
bool initGui();
// Client connection
bool connectToServer(const GameStartData &start_data,
bool *connect_ok, bool *aborted);
bool getServerContent(bool *aborted);
// Main loop
void updateInteractTimers(f32 dtime);
bool checkConnection();
bool handleCallbacks();
void processQueues();
void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
void updateDebugState();
void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
void updateProfilerGraphs(ProfilerGraph *graph);
// Input related
void processUserInput(f32 dtime);
void processKeyInput();
void processItemSelection(u16 *new_playeritem);
void dropSelectedItem(bool single_item = false);
void openInventory();
void openConsole(float scale, const wchar_t *line=NULL);
void toggleFreeMove();
void toggleFreeMoveAlt();
void togglePitchMove();
void toggleFast();
void toggleNoClip();
void toggleCinematic();
void toggleBlockBounds();
void toggleAutoforward();
void toggleMinimap(bool shift_pressed);
void toggleFog();
void toggleDebug();
void toggleUpdateCamera();
void increaseViewRange();
void decreaseViewRange();
void toggleFullViewRange();
void checkZoomEnabled();
void updateCameraDirection(CameraOrientation *cam, float dtime);
void updateCameraOrientation(CameraOrientation *cam, float dtime);
void updatePlayerControl(const CameraOrientation &cam);
void step(f32 dtime);
void processClientEvents(CameraOrientation *cam);
void updateCamera(f32 dtime);
void updateSound(f32 dtime);
void processPlayerInteraction(f32 dtime, bool show_hud);
/*!
* Returns the object or node the player is pointing at.
* Also updates the selected thing in the Hud.
*
* @param[in] shootline the shootline, starting from
* the camera position. This also gives the maximal distance
* of the search.
* @param[in] liquids_pointable if false, liquids are ignored
* @param[in] look_for_object if false, objects are ignored
* @param[in] camera_offset offset of the camera
* @param[out] selected_object the selected object or
* NULL if not found
*/
PointedThing updatePointedThing(
const core::line3d<f32> &shootline, bool liquids_pointable,
bool look_for_object, const v3s16 &camera_offset);
void handlePointingAtNothing(const ItemStack &playerItem);
void handlePointingAtNode(const PointedThing &pointed,
const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
const v3f &player_position, bool show_debug);
void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
const ItemStack &selected_item, const ItemStack &hand_item, f32 dtime);
void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
const CameraOrientation &cam);
void updateShadows();
// Misc
void showOverlayMessage(const char *msg, float dtime, int percent,
bool draw_clouds = true);
static void settingChangedCallback(const std::string &setting_name, void *data);
void readSettings();
inline bool isKeyDown(GameKeyType k)
{
return input->isKeyDown(k);
}
inline bool wasKeyDown(GameKeyType k)
{
return input->wasKeyDown(k);
}
inline bool wasKeyPressed(GameKeyType k)
{
return input->wasKeyPressed(k);
}
inline bool wasKeyReleased(GameKeyType k)
{
return input->wasKeyReleased(k);
}
#ifdef __ANDROID__
void handleAndroidChatInput();
#endif
private:
struct Flags {
bool force_fog_off = false;
bool disable_camera_update = false;
};
void showDeathFormspec();
void showPauseMenu();
void pauseAnimation();
void resumeAnimation();
// ClientEvent handlers
void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_HandleParticleEvent(ClientEvent *event,
CameraOrientation *cam);
void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetSun(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetMoon(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_SetStars(ClientEvent *event, CameraOrientation *cam);
void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
CameraOrientation *cam);
void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
void updateChat(f32 dtime);
bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item,
const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed,
const NodeMetadata *meta);
static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
f32 getSensitivityScaleFactor() const;
InputHandler *input = nullptr;
Client *client = nullptr;
Server *server = nullptr;
IWritableTextureSource *texture_src = nullptr;
IWritableShaderSource *shader_src = nullptr;
// When created, these will be filled with data received from the server
IWritableItemDefManager *itemdef_manager = nullptr;
NodeDefManager *nodedef_manager = nullptr;
GameOnDemandSoundFetcher soundfetcher; // useful when testing
ISoundManager *sound = nullptr;
bool sound_is_dummy = false;
SoundMaker *soundmaker = nullptr;
ChatBackend *chat_backend = nullptr;
LogOutputBuffer m_chat_log_buf;
EventManager *eventmgr = nullptr;
QuicktuneShortcutter *quicktune = nullptr;
std::unique_ptr<GameUI> m_game_ui;
GUIChatConsole *gui_chat_console = nullptr; // Free using ->Drop()
MapDrawControl *draw_control = nullptr;
Camera *camera = nullptr;
Clouds *clouds = nullptr; // Free using ->Drop()
Sky *sky = nullptr; // Free using ->Drop()
Hud *hud = nullptr;
Minimap *mapper = nullptr;
// Map server hud ids to client hud ids
std::unordered_map<u32, u32> m_hud_server_to_client;
GameRunData runData;
Flags m_flags;
/* 'cache'
This class does take ownership/responsibily for cleaning up etc of any of
these items (e.g. device)
*/
IrrlichtDevice *device;
RenderingEngine *m_rendering_engine;
video::IVideoDriver *driver;
scene::ISceneManager *smgr;
bool *kill;
std::string *error_message;
bool *reconnect_requested;
scene::ISceneNode *skybox;
PausedNodesList paused_animated_nodes;
bool simple_singleplayer_mode;
/* End 'cache' */
/* Pre-calculated values
*/
int crack_animation_length;
IntervalLimiter profiler_interval;
/*
* TODO: Local caching of settings is not optimal and should at some stage
* be updated to use a global settings object for getting thse values
* (as opposed to the this local caching). This can be addressed in
* a later release.
*/
bool m_cache_doubletap_jump;
bool m_cache_enable_clouds;
bool m_cache_enable_joysticks;
bool m_cache_enable_particles;
bool m_cache_enable_fog;
bool m_cache_enable_noclip;
bool m_cache_enable_free_move;
f32 m_cache_mouse_sensitivity;
f32 m_cache_joystick_frustum_sensitivity;
f32 m_repeat_place_time;
f32 m_cache_cam_smoothing;
f32 m_cache_fog_start;
bool m_invert_mouse = false;
bool m_first_loop_after_window_activation = false;
bool m_camera_offset_changed = false;
bool m_does_lost_focus_pause_game = false;
// if true, (almost) the whole game is paused
// this happens in pause menu in singleplayer
bool m_is_paused = false;
#if IRRLICHT_VERSION_MT_REVISION < 5
int m_reset_HW_buffer_counter = 0;
#endif
#ifdef HAVE_TOUCHSCREENGUI
bool m_cache_hold_aux1;
bool m_touch_use_crosshair;
inline bool isNoCrosshairAllowed() {
return !m_touch_use_crosshair && camera->getCameraMode() == CAMERA_MODE_FIRST;
}
#endif
#ifdef __ANDROID__
bool m_android_chat_open;
#endif
};
Game::Game() :
m_chat_log_buf(g_logger),
m_game_ui(new GameUI())
{
g_settings->registerChangedCallback("doubletap_jump",
&settingChangedCallback, this);
g_settings->registerChangedCallback("enable_clouds",
&settingChangedCallback, this);
g_settings->registerChangedCallback("doubletap_joysticks",
&settingChangedCallback, this);
g_settings->registerChangedCallback("enable_particles",