-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathsamples_cpp.cpp
More file actions
1697 lines (1624 loc) · 58.9 KB
/
samples_cpp.cpp
File metadata and controls
1697 lines (1624 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* libtcod CPP samples
* This code demonstrates various usages of libtcod modules
* It's in the public domain.
*/
// uncomment this to disable SDL sample (might cause compilation issues on some systems)
// #define NO_SDL_SAMPLE
#define SDL_MAIN_USE_CALLBACKS
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <libtcod.hpp>
#include <libtcod/timer.hpp>
#include <memory>
#include <string>
#include <vector>
// Return true if string ends with suffix.
bool str_ends_with(std::string_view string, std::string_view suffix) {
if (suffix.length() > string.length()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), string.rbegin());
}
// Abstract class for samples.
class Sample {
public:
virtual ~Sample() = default;
virtual void on_enter() = 0;
virtual void on_event(SDL_Event& event) = 0;
virtual void on_draw(tcod::Console& console) = 0;
};
// a sample has a name and a rendering function
typedef struct sample_t {
std::string name;
std::shared_ptr<Sample> sample;
} sample_t;
// sample screen size
static constexpr auto SAMPLE_SCREEN_WIDTH = 46;
static constexpr auto SAMPLE_SCREEN_HEIGHT = 20;
// sample screen position
static constexpr auto SAMPLE_SCREEN_X = 20;
static constexpr auto SAMPLE_SCREEN_Y = 10;
static constexpr auto WHITE = tcod::ColorRGB{255, 255, 255};
static constexpr auto BLACK = tcod::ColorRGB{0, 0, 0};
static constexpr auto GREY = tcod::ColorRGB{127, 127, 127};
static constexpr auto LIGHT_BLUE = tcod::ColorRGB{63, 63, 255};
static constexpr auto LIGHT_YELLOW = tcod::ColorRGB{255, 255, 63};
static float delta_time; // Global delta time.
// clang-format off
static constexpr const char* SAMPLE_MAP[] = {
"##############################################",
"####################### #################",
"##################### # ###############",
"###################### ### ###########",
"################## ##### ####",
"################ ######## ###### ####",
"############### #################### ####",
"################ ###### ##",
"######## ####### ###### # # # ##",
"######## ###### ### ##",
"######## ##",
"#### ###### ### # # # ##",
"#### ### ########## #### ##",
"#### ### ########## ###########=##########",
"#### ################## ##### #####",
"#### ### #### ##### #####",
"#### # #### #####",
"######## # #### ##### #####",
"######## ##### ####################",
"##############################################",
};
// clang-format on
// Global variables.
static tcod::Context g_context; // A global tcod context object.
static auto g_console = tcod::Console{80, 50}; // The main console to be presented.
static int g_current_sample = 0; // index of the current sample
TCOD_ContextParams g_context_params{}; // The active context parameters. Saved so that they can be modified.
static tcod::Tileset g_tileset; // The currently active tileset.
// The offscreen console in which the samples are rendered
static tcod::Console g_sample_console(SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT);
// ***************************
// true colors sample
// ***************************
class TrueColors : public Sample {
public:
void on_enter() override {};
void on_event(SDL_Event&) override {}
void on_draw(tcod::Console& console) override {
const float t = SDL_GetTicks() * 0.001f;
// Return noise sample as a 0 to 255 value.
auto get_value = [&](std::array<float, 2> xy) {
return static_cast<uint8_t>(((noise_.get(xy.data(), TCOD_NOISE_DEFAULT) + 1.0f) * 0.5f) * 255.5f);
};
// Return an RGB color from an index.
auto get_color = [&](float x) -> tcod::ColorRGB {
return {get_value({t, x}), get_value({t, x + 1000}), get_value({t, x + 2000})};
};
// Generate color corners from noise samples.
const auto colors = std::array<tcod::ColorRGB, 4>{get_color(0), get_color(1), get_color(2), get_color(3)};
// ==== scan the whole screen, interpolating corner colors ====
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
const float y_coef = static_cast<float>(y) / (SAMPLE_SCREEN_HEIGHT - 1);
// get the current column top and bottom colors
const auto left = tcod::ColorRGB{TCODColor::lerp(colors[TOPLEFT], colors[BOTTOMLEFT], y_coef)};
const auto right = tcod::ColorRGB{TCODColor::lerp(colors[TOPRIGHT], colors[BOTTOMRIGHT], y_coef)};
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const float x_coef = static_cast<float>(x) / (SAMPLE_SCREEN_WIDTH - 1);
// get the current cell color
auto curColor = tcod::ColorRGB{TCODColor::lerp(left, right, x_coef)};
console.at({x, y}).bg = curColor;
}
}
// ==== print the text with a random color ====
// get the background color at the text position
auto textColor = tcod::ColorRGB{console.at({SAMPLE_SCREEN_WIDTH / 2, 5}).bg};
// and invert it
textColor.r = 255 - textColor.r;
textColor.g = 255 - textColor.g;
textColor.b = 255 - textColor.b;
// put random text (for performance tests)
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
auto col = tcod::ColorRGB{console.at({x, y}).bg};
col = tcod::ColorRGB{TCODColor::lerp(col, BLACK, 0.5f)};
console.at({x, y}).ch = TCODRandom::getInstance()->getInt('a', 'z');
console.at({x, y}).fg = col;
}
}
// the background behind the text is slightly darkened using the BKGND_MULTIPLY flag
tcod::print_rect(
console,
{1, 5, SAMPLE_SCREEN_WIDTH - 2, SAMPLE_SCREEN_HEIGHT - 1},
"The Doryen library uses 24 bits colors, for both background and foreground.",
textColor,
GREY,
TCOD_CENTER,
TCOD_BKGND_MULTIPLY);
}
private:
enum { TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT };
TCODNoise noise_{2, TCOD_NOISE_SIMPLEX}; // Noise for random colors.
};
// ***************************
// offscreen console sample
// ***************************
class OffscreenConsole : public Sample {
public:
static constexpr auto FRAME_DECOR_SINGLE_PIPE =
std::array<int, 9>{0x250C, 0x2500, 0x2510, 0x2502, 0x20, 0x2502, 0x2514, 0x2500, 0x2518};
OffscreenConsole() {
tcod::draw_frame(
secondary,
{0, 0, SAMPLE_SCREEN_WIDTH / 2, SAMPLE_SCREEN_HEIGHT / 2},
FRAME_DECOR_SINGLE_PIPE,
std::nullopt,
std::nullopt);
tcod::print_rect(
secondary,
{1, 2, SAMPLE_SCREEN_WIDTH / 2 - 2, SAMPLE_SCREEN_HEIGHT / 2},
"You can render to an offscreen console and blit in on another one, simulating alpha transparency.",
std::nullopt,
std::nullopt,
TCOD_CENTER);
}
void on_enter() override {
counter = SDL_GetTicks();
screenshot = g_sample_console; // get a "screenshot" of the current sample screen
}
void on_event(SDL_Event&) override {}
void on_draw(tcod::Console& console) override {
if (SDL_GetTicks() >= counter + 1000) { // Once every second.
counter = SDL_GetTicks();
x_ += x_dir_;
y_ += y_dir_;
if (x_ == SAMPLE_SCREEN_WIDTH / 2 + 5) {
x_dir_ = -1;
} else if (x_ == -5) {
x_dir_ = 1;
}
if (y_ == SAMPLE_SCREEN_HEIGHT / 2 + 5) {
y_dir_ = -1;
} else if (y_ == -5) {
y_dir_ = 1;
}
}
console = screenshot; // restore the initial screen
tcod::blit(console, secondary, {x_, y_}, {}, 1.0f, 0.75f); // blit the overlapping screen
}
private:
uint64_t counter;
tcod::Console screenshot{SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT};
tcod::Console secondary{SAMPLE_SCREEN_WIDTH / 2, SAMPLE_SCREEN_HEIGHT / 2}; // second screen
int x_ = 0; // secondary screen position
int y_ = 0;
int x_dir_ = 1; // movement direction
int y_dir_ = 1;
};
// ***************************
// line drawing sample
// ***************************
class LineDrawingSample : public Sample {
public:
LineDrawingSample() : background_{SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT} {
// initialize the colored background
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
background_.at({x, y}).bg = tcod::ColorRGB{
static_cast<uint8_t>(x * 255 / (SAMPLE_SCREEN_WIDTH - 1)),
static_cast<uint8_t>((x + y) * 255 / (SAMPLE_SCREEN_WIDTH - 1 + SAMPLE_SCREEN_HEIGHT - 1)),
static_cast<uint8_t>(y * 255 / (SAMPLE_SCREEN_HEIGHT - 1)),
};
}
}
}
void on_enter() override {}
void on_event(SDL_Event& event) override {
switch (event.type) {
case SDL_EVENT_KEY_DOWN:
switch (event.key.key) {
case SDLK_RETURN:
case SDLK_RETURN2:
case SDLK_KP_ENTER:
// switch to the next blending mode
++blend_flag_;
if ((blend_flag_ & 0xff) > TCOD_BKGND_ALPH) blend_flag_ = TCOD_BKGND_NONE;
break;
default:
break;
}
break;
default:
break;
}
}
void on_draw(tcod::Console& console) override {
if ((blend_flag_ & 0xff) == TCOD_BKGND_ALPH) {
// for the alpha mode, update alpha every frame
const auto alpha = float{(1.0f + cosf(SDL_GetTicks() / 1000.0f * 2.0f)) / 2.0f};
blend_flag_ = TCOD_BKGND_ALPHA(alpha);
} else if ((blend_flag_ & 0xff) == TCOD_BKGND_ADDA) {
// for the add alpha mode, update alpha every frame
const auto alpha = float{(1.0f + cosf(SDL_GetTicks() / 1000.0f * 2.0f)) / 2.0f};
blend_flag_ = TCOD_BKGND_ADDALPHA(alpha);
}
// blit the background
console = background_;
// render the gradient
const auto rect_y = static_cast<int>((SAMPLE_SCREEN_HEIGHT - 2) * ((1.0f + cosf(SDL_GetTicks() / 1000.0f)) / 2.0f));
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const auto col = tcod::ColorRGB{
static_cast<uint8_t>(x * 255 / SAMPLE_SCREEN_WIDTH),
static_cast<uint8_t>(x * 255 / SAMPLE_SCREEN_WIDTH),
static_cast<uint8_t>(x * 255 / SAMPLE_SCREEN_WIDTH),
};
tcod::draw_rect(console, {x, rect_y, 1, 3}, 0, std::nullopt, col, static_cast<TCOD_bkgnd_flag_t>(blend_flag_));
}
// calculate the segment ends
const float angle = SDL_GetTicks() / 1000.0f * 2.0f;
const int xo = static_cast<int>(SAMPLE_SCREEN_WIDTH / 2 * (1 + cosf(angle)));
const int yo = static_cast<int>(SAMPLE_SCREEN_HEIGHT / 2 + sinf(angle) * SAMPLE_SCREEN_WIDTH / 2);
const int xd = static_cast<int>(SAMPLE_SCREEN_WIDTH / 2 * (1 - cosf(angle)));
const int yd = static_cast<int>(SAMPLE_SCREEN_HEIGHT / 2 - sinf(angle) * SAMPLE_SCREEN_WIDTH / 2);
// render the line
for (const auto xy : tcod::BresenhamLine({xo, yo}, {xd, yd})) {
if (console.in_bounds(xy)) {
TCOD_console_set_char_background(
console.get(), xy.at(0), xy.at(1), LIGHT_BLUE, static_cast<TCOD_bkgnd_flag_t>(blend_flag_));
}
}
// print the current flag
tcod::print(
console,
{2, 2},
tcod::stringf("%s (ENTER to change)", flag_names_.at(blend_flag_ & 0xff)),
WHITE,
std::nullopt);
}
private:
tcod::Console background_{SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT}; // The background of this sample.
int blend_flag_ = TCOD_BKGND_SET; // current blending mode
// Readable names for the blend modes.
static constexpr auto flag_names_ = std::array<const char*, 13>{
"TCOD_BKGND_NONE",
"TCOD_BKGND_SET",
"TCOD_BKGND_MULTIPLY",
"TCOD_BKGND_LIGHTEN",
"TCOD_BKGND_DARKEN",
"TCOD_BKGND_SCREEN",
"TCOD_BKGND_COLOR_DODGE",
"TCOD_BKGND_COLOR_BURN",
"TCOD_BKGND_ADD",
"TCOD_BKGND_ADDALPHA",
"TCOD_BKGND_BURN",
"TCOD_BKGND_OVERLAY",
"TCOD_BKGND_ALPHA",
};
};
// ***************************
// noise sample
// ***************************
class NoiseSample : public Sample {
public:
void on_enter() override {}
void on_event(SDL_Event& event) override {
switch (event.type) {
case SDL_EVENT_KEY_DOWN:
switch (event.key.key) {
case SDLK_E: // increase hurst
hurst_ += 0.1f;
noise_ = TCODNoise(2, hurst_, lacunarity_);
break;
case SDLK_D: // decrease hurst
hurst_ -= 0.1f;
noise_ = TCODNoise(2, hurst_, lacunarity_);
break;
case SDLK_R: // increase lacunarity
lacunarity_ += 0.5f;
noise_ = TCODNoise(2, hurst_, lacunarity_);
break;
case SDLK_F: // decrease lacunarity
lacunarity_ -= 0.5f;
noise_ = TCODNoise(2, hurst_, lacunarity_);
break;
case SDLK_T: // increase octaves
octaves_ += 0.5f;
break;
case SDLK_G: // decrease octaves
octaves_ -= 0.5f;
break;
case SDLK_Y: // increase zoom
zoom += 0.2f;
break;
case SDLK_H: // decrease zoom
zoom -= 0.2f;
break;
default:
const auto set_func = [&](int n) {
if (0 <= n && n < 9) func_ = n;
};
set_func(event.key.key - SDLK_1);
set_func(event.key.key - SDLK_KP_1);
break;
}
break;
default:
break;
}
}
void on_draw(tcod::Console& console) override {
static const std::vector<std::string> funcName = {
"1 : perlin noise ",
"2 : simplex noise ",
"3 : wavelet noise ",
"4 : perlin fbm ",
"5 : perlin turbulence ",
"6 : simplex fbm ",
"7 : simplex turbulence ",
"8 : wavelet fbm ",
"9 : wavelet turbulence ",
};
// texture animation
const float dx = SDL_GetTicks() * 0.0005f;
const float dy = dx;
// render the 2d noise function
for (int y = 0; y < 2 * SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < 2 * SAMPLE_SCREEN_WIDTH; ++x) {
const float f[2] = {zoom * x / (2 * SAMPLE_SCREEN_WIDTH) + dx, zoom * y / (2 * SAMPLE_SCREEN_HEIGHT) + dy};
float value = 0.0f;
switch (func_) {
case PERLIN:
value = noise_.get(f, TCOD_NOISE_PERLIN);
break;
case SIMPLEX:
value = noise_.get(f, TCOD_NOISE_SIMPLEX);
break;
case WAVELET:
value = noise_.get(f, TCOD_NOISE_WAVELET);
break;
case FBM_PERLIN:
value = noise_.getFbm(f, octaves_, TCOD_NOISE_PERLIN);
break;
case TURBULENCE_PERLIN:
value = noise_.getTurbulence(f, octaves_, TCOD_NOISE_PERLIN);
break;
case FBM_SIMPLEX:
value = noise_.getFbm(f, octaves_, TCOD_NOISE_SIMPLEX);
break;
case TURBULENCE_SIMPLEX:
value = noise_.getTurbulence(f, octaves_, TCOD_NOISE_SIMPLEX);
break;
case FBM_WAVELET:
value = noise_.getFbm(f, octaves_, TCOD_NOISE_WAVELET);
break;
case TURBULENCE_WAVELET:
value = noise_.getTurbulence(f, octaves_, TCOD_NOISE_WAVELET);
break;
}
const auto c = static_cast<uint8_t>((value + 1.0f) / 2.0f * 255);
// use a bluish color
img_.putPixel(x, y, tcod::ColorRGB{static_cast<uint8_t>(c / 2), static_cast<uint8_t>(c / 2), c});
}
}
// blit the noise image on the console with subcell resolution
tcod::draw_quartergraphics(console, img_);
// draw a transparent rectangle
tcod::draw_rect(console, {2, 2, 23, (func_ <= WAVELET ? 10 : 13)}, 0, std::nullopt, GREY, TCOD_BKGND_MULTIPLY);
for (int y = 2; y < 2 + (func_ <= WAVELET ? 10 : 13); ++y) {
for (int x = 2; x < 2 + 23; ++x) {
console.at({x, y}).fg.r /= 2;
console.at({x, y}).fg.g /= 2;
console.at({x, y}).fg.b /= 2;
}
}
// draw the text
for (int curfunc = PERLIN; curfunc <= TURBULENCE_WAVELET; ++curfunc) {
const auto fg = curfunc == func_ ? WHITE : GREY;
const auto bg = curfunc == func_ ? std::optional{LIGHT_BLUE} : std::nullopt;
tcod::print(g_sample_console, {2, 2 + curfunc}, funcName.at(curfunc), fg, bg);
}
// draw parameters
tcod::print(g_sample_console, {2, 11}, tcod::stringf("Y/H : zoom (%2.1f)", zoom), WHITE, std::nullopt);
if (func_ > WAVELET) {
tcod::print(g_sample_console, {2, 12}, tcod::stringf("E/D : hurst (%2.1f)", hurst_), WHITE, std::nullopt);
tcod::print(
g_sample_console, {2, 13}, tcod::stringf("R/F : lacunarity (%2.1f)", lacunarity_), WHITE, std::nullopt);
tcod::print(g_sample_console, {2, 14}, tcod::stringf("T/G : octaves (%2.1f)", octaves_), WHITE, std::nullopt);
}
}
private:
enum {
PERLIN,
SIMPLEX,
WAVELET,
FBM_PERLIN,
TURBULENCE_PERLIN,
FBM_SIMPLEX,
TURBULENCE_SIMPLEX,
FBM_WAVELET,
TURBULENCE_WAVELET
}; // which function we render
int func_ = PERLIN;
float octaves_ = 4.0f;
float hurst_ = TCOD_NOISE_DEFAULT_HURST;
float lacunarity_ = TCOD_NOISE_DEFAULT_LACUNARITY;
float zoom = 3.0f;
TCODNoise noise_{2, hurst_, lacunarity_};
TCODImage img_{SAMPLE_SCREEN_WIDTH * 2, SAMPLE_SCREEN_HEIGHT * 2};
};
// ***************************
// fov sample
// ***************************
static constexpr auto CHAR_WINDOW = 0x2550; // "═" glyph.
static constexpr std::array<const char*, 14> algo_names{
"BASIC ",
"DIAMOND ",
"SHADOW ",
"PERMISSIVE0 ",
"PERMISSIVE1 ",
"PERMISSIVE2 ",
"PERMISSIVE3 ",
"PERMISSIVE4 ",
"PERMISSIVE5 ",
"PERMISSIVE6 ",
"PERMISSIVE7 ",
"PERMISSIVE8 ",
"RESTRICTIVE ",
"SYMMETRIC_SHADOWCAST",
};
class FOVSample : public Sample {
public:
FOVSample() {
// initialize the map for the fov toolkit
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
if (SAMPLE_MAP[y][x] == ' ')
map_.setProperties(x, y, true, true); // ground
else if (SAMPLE_MAP[y][x] == '=')
map_.setProperties(x, y, true, false); // window
}
}
}
void on_enter() override {}
/// Attempt to move the player.
void try_move(int dx, int dy) noexcept {
const int dest_x = px_ + dx;
const int dest_y = py_ + dy;
if (SAMPLE_MAP[dest_y][dest_x] == ' ') {
px_ = dest_x;
py_ = dest_y;
}
}
void on_event(SDL_Event& event) override {
switch (event.type) {
case SDL_EVENT_KEY_DOWN:
switch (event.key.key) {
case SDLK_I:
try_move(0, -1); // player move north
break;
case SDLK_K:
try_move(0, 1); // player move south
break;
case SDLK_J:
try_move(-1, 0); // player move west
break;
case SDLK_L:
try_move(1, 0); // player move east
break;
case SDLK_T:
torch_ = !torch_; // enable/disable the torch fx
break;
case SDLK_W:
light_walls_ = !light_walls_;
break;
case SDLK_EQUALS:
case SDLK_KP_PLUS:
algonum_ = (algonum_ + 1) % NB_FOV_ALGORITHMS;
break;
case SDLK_KP_MINUS:
case SDLK_MINUS:
algonum_ = (algonum_ + NB_FOV_ALGORITHMS - 1) % NB_FOV_ALGORITHMS;
break;
default:
break;
}
break;
default:
break;
}
}
void on_draw(tcod::Console& console) override {
static constexpr auto TORCH_RADIUS = 10.0f;
static constexpr auto SQUARED_TORCH_RADIUS = (TORCH_RADIUS * TORCH_RADIUS);
static constexpr auto darkWall = tcod::ColorRGB{0, 0, 100};
static constexpr auto lightWall = tcod::ColorRGB{130, 110, 50};
static constexpr auto darkGround = tcod::ColorRGB{50, 50, 150};
static constexpr auto lightGround = tcod::ColorRGB{200, 180, 50};
// draw the help text & player @
console.clear({0x20, BLACK, BLACK});
tcod::print(
console,
{1, 0},
tcod::stringf(
"IJKL : move around\nT : torch fx %s\nW : light walls %s\n+-: algo %s",
torch_ ? "on " : "off",
light_walls_ ? "on " : "off",
algo_names.at(algonum_)),
WHITE,
std::nullopt);
console.at({px_, py_}).ch = '@';
// draw windows
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
if (SAMPLE_MAP[y][x] == '=') {
console.at({x, y}).ch = CHAR_WINDOW;
}
}
}
// calculate the field of view from the player position
map_.computeFov(px_, py_, torch_ ? (int)(TORCH_RADIUS) : 0, light_walls_, (TCOD_fov_algorithm_t)algonum_);
// torch position & intensity variation
float dx = 0.0f, dy = 0.0f, di = 0.0f;
if (torch_) {
// slightly change the perlin noise parameter
torch_x_ += 0.2f;
// randomize the light position between -1.5 and 1.5
float tdx = torch_x_ + 20.0f;
dx = noise_.get(&tdx) * 1.5f;
tdx += 30.0f;
dy = noise_.get(&tdx) * 1.5f;
// randomize the light intensity between -0.2 and 0.2
di = 0.2f * noise_.get(&torch_x_);
}
// draw the dungeon
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const bool visible = map_.isInFov(x, y);
const bool wall = SAMPLE_MAP[y][x] == '#';
if (!visible) {
console.at({x, y}).bg = wall ? darkWall : darkGround;
} else {
tcod::ColorRGB light;
if (!torch_) {
light = wall ? lightWall : lightGround;
} else {
// torch flickering fx
tcod::ColorRGB base = (wall ? darkWall : darkGround);
light = (wall ? lightWall : lightGround);
// cell distance to torch (squared)
const float r = (float)((x - px_ + dx) * (x - px_ + dx) + (y - py_ + dy) * (y - py_ + dy));
if (r < SQUARED_TORCH_RADIUS) {
// l = 1.0 at player position, 0.0 at a radius of 10 cells
const float l = std::clamp((SQUARED_TORCH_RADIUS - r) / SQUARED_TORCH_RADIUS + di, 0.0f, 1.0f);
// interpolate the color
base = tcod::ColorRGB{TCODColor::lerp(base, light, l)};
}
light = base;
}
console.at({x, y}).bg = light;
}
}
}
}
private:
int px_ = 20, py_ = 10; // player position
bool torch_ = false; // torch fx on ?
TCODMap map_{SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT};
TCODNoise noise_{1}; // 1d noise used for the torch flickering
bool light_walls_ = true;
int algonum_ = 0;
float torch_x_ = 0.0f; // torch light position in the perlin noise
};
// ***************************
// image sample
// ***************************
class ImageSample : public Sample {
public:
ImageSample() { img_.setKeyColor(BLACK); }
void on_enter() override {}
void on_event(SDL_Event&) override {}
void on_draw(tcod::Console& console) override {
console.clear();
const float x = SAMPLE_SCREEN_WIDTH / 2 + cosf(SDL_GetTicks() / 1000.0f) * 10.0f;
const float y = (float)(SAMPLE_SCREEN_HEIGHT / 2);
const float scale_x = 0.2f + 1.8f * (1.0f + cosf(SDL_GetTicks() / 1000.0f / 2.0f)) / 2.0f;
const float scale_y = scale_x;
const float angle = SDL_GetTicks() / 1000.0f;
const uint64_t elapsed = SDL_GetTicks() / 2000;
if (elapsed & 1) {
// split the color channels of circle.png
// the red channel
tcod::draw_rect(console, {0, 3, 15, 15}, 0, std::nullopt, {{255, 0, 0}});
circle_.blitRect(console, 0, 3, -1, -1, TCOD_BKGND_MULTIPLY);
// the green channel
tcod::draw_rect(console, {15, 3, 15, 15}, 0, std::nullopt, {{0, 255, 0}});
circle_.blitRect(console, 15, 3, -1, -1, TCOD_BKGND_MULTIPLY);
// the blue channel
tcod::draw_rect(console, {30, 3, 15, 15}, 0, std::nullopt, {{0, 0, 255}});
circle_.blitRect(console, 30, 3, -1, -1, TCOD_BKGND_MULTIPLY);
} else {
// render circle.png with normal blitting
circle_.blitRect(console, 0, 3, -1, -1, TCOD_BKGND_SET);
circle_.blitRect(console, 15, 3, -1, -1, TCOD_BKGND_SET);
circle_.blitRect(console, 30, 3, -1, -1, TCOD_BKGND_SET);
}
img_.blit(console, x, y, TCOD_BKGND_SET, scale_x, scale_y, angle);
}
private:
TCODImage img_{"data/img/skull.png"};
TCODImage circle_{"data/img/circle.png"};
};
// ***************************
// mouse sample
// ***************************/
class MouseSample : public Sample {
public:
void on_enter() override {
SDL_WarpMouseInWindow(NULL, 320, 200);
SDL_ShowCursor();
last_motion_ = SDL_Event{};
}
void on_event(SDL_Event& event) override {
switch (event.type) {
case SDL_EVENT_KEY_DOWN:
switch (event.key.key) {
case SDLK_1:
case SDLK_KP_1:
SDL_HideCursor();
break;
case SDLK_2:
case SDLK_KP_2:
SDL_ShowCursor();
break;
default:
break;
}
break;
case SDL_EVENT_MOUSE_MOTION:
last_motion_ = event; // Track mouse motion.
break;
default:
break;
}
}
void on_draw(tcod::Console& console) override {
auto last_tile = last_motion_; // SDL event to be converted into tile coordinates.
g_context.convert_event_coordinates(last_tile);
auto sdl_window = g_context.get_sdl_window();
const auto window_flags = sdl_window ? SDL_GetWindowFlags(sdl_window) : 0;
const auto& mouse = last_motion_.motion;
const auto& mouse_tile = last_tile.motion;
const auto state = SDL_GetMouseState(nullptr, nullptr);
console.clear({0x20, LIGHT_YELLOW, GREY});
tcod::print(
console,
{1, 1},
tcod::stringf(
"%s\n"
"Mouse pixel position : %4dx%4d %s\n"
"Mouse pixel motion : %4dx%4d\n"
"Mouse tile : %4dx%4d\n"
"Mouse tile motion : %4dx%4d\n"
"Left button : %s\n"
"Right button : %s\n"
"Middle button : %s\n",
window_flags & SDL_WINDOW_INPUT_FOCUS ? "" : "APPLICATION INACTIVE",
mouse.x,
mouse.y,
window_flags & SDL_WINDOW_MOUSE_FOCUS ? "" : "OUT OF FOCUS",
mouse.xrel,
mouse.yrel,
mouse_tile.x,
mouse_tile.y,
mouse_tile.xrel,
mouse_tile.yrel,
(state & SDL_BUTTON_LMASK) ? " ON" : "OFF",
(state & SDL_BUTTON_RMASK) ? " ON" : "OFF",
(state & SDL_BUTTON_MMASK) ? " ON" : "OFF"),
std::nullopt,
std::nullopt);
tcod::print(console, {1, 10}, "1 : Hide cursor\n2 : Show cursor", std::nullopt, std::nullopt);
}
private:
bool left_button = false, right_button = false, middle_button = false;
SDL_Event last_motion_{};
};
// ***************************
// path sample
// ***************************
class PathfinderSample : public Sample {
public:
PathfinderSample() {
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
if (SAMPLE_MAP[y][x] == ' ')
map_.setProperties(x, y, true, true); // ground
else if (SAMPLE_MAP[y][x] == '=')
map_.setProperties(x, y, true, false); // window
}
}
}
void on_enter() override {}
/// Attempt to move the player.
void try_move(int dx, int dy) noexcept {
const int dest_x = player_x_ + dx;
const int dest_y = player_y_ + dy;
if (SAMPLE_MAP[dest_y][dest_x] == ' ') {
player_x_ = dest_x;
player_y_ = dest_y;
}
}
void on_event(SDL_Event& event) override {
g_context.convert_event_coordinates(event);
switch (event.type) {
case SDL_EVENT_KEY_DOWN:
switch (event.key.key) {
case SDLK_I:
dest_y_ -= 1; // destination move north
break;
case SDLK_K:
dest_y_ += 1; // destination move south
break;
case SDLK_J:
dest_x_ -= 1; // destination move west
break;
case SDLK_L:
dest_x_ += 1; // destination move east
break;
case SDLK_TAB: // Toggle pathfinder.
case SDLK_KP_TAB:
using_astar_ = !using_astar_;
break;
default:
break;
}
break;
case SDL_EVENT_MOUSE_MOTION: {
const auto dest_x = (int)event.motion.x - SAMPLE_SCREEN_X;
const auto dest_y = (int)event.motion.y - SAMPLE_SCREEN_Y;
if (0 <= dest_x && dest_x < SAMPLE_SCREEN_WIDTH && 0 <= dest_y && dest_y < SAMPLE_SCREEN_HEIGHT) {
dest_x_ = dest_x;
dest_y_ = dest_y;
}
} break;
default:
break;
}
dest_x_ = std::clamp(dest_x_, 0, SAMPLE_SCREEN_WIDTH - 1);
dest_y_ = std::clamp(dest_y_, 0, SAMPLE_SCREEN_HEIGHT - 1);
}
void on_draw(tcod::Console& console) override {
static constexpr auto darkWall = tcod::ColorRGB{0, 0, 100};
static constexpr auto darkGround = tcod::ColorRGB{50, 50, 150};
static constexpr auto lightGround = tcod::ColorRGB{200, 180, 50};
// draw the help text & player @
console.clear();
console.at({dest_x_, dest_y_}).ch = '+';
console.at({player_x_, player_y_}).ch = '@';
tcod::print(console, {1, 1}, "IJKL / mouse :\nmove destination\nTAB : A*/dijkstra", WHITE, std::nullopt);
tcod::print(console, {1, 4}, using_astar_ ? "Using : A*" : "Using : Dijkstra", WHITE, std::nullopt);
// draw windows
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
if (SAMPLE_MAP[y][x] == '=') {
console.at({x, y}).ch = CHAR_WINDOW;
}
}
}
// Recalculate the path.
if (using_astar_) {
path_.compute(player_x_, player_y_, dest_x_, dest_y_);
} else {
dijkstra_dist_ = 0.0f;
// compute the distance grid
dijkstra_.compute(player_x_, player_y_);
// get the maximum distance (needed for ground shading only)
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const float d = dijkstra_.getDistance(x, y);
if (d > dijkstra_dist_) dijkstra_dist_ = d;
}
}
// compute the path
dijkstra_.setPath(dest_x_, dest_y_);
}
// draw the dungeon
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const bool wall = SAMPLE_MAP[y][x] == '#';
g_sample_console.at({x, y}).bg = wall ? darkWall : darkGround;
}
}
// draw the path
if (using_astar_) {
for (int i = 0; i < path_.size(); ++i) {
int x, y;
path_.get(i, &x, &y);
g_sample_console.at({x, y}).bg = lightGround;
}
} else {
for (int y = 0; y < SAMPLE_SCREEN_HEIGHT; ++y) {
for (int x = 0; x < SAMPLE_SCREEN_WIDTH; ++x) {
const bool wall = SAMPLE_MAP[y][x] == '#';
if (!wall) {
const float d = dijkstra_.getDistance(x, y);
g_sample_console.at({x, y}).bg =
tcod::ColorRGB{TCODColor::lerp(lightGround, darkGround, 0.9f * d / dijkstra_dist_)};
}
}
}
for (int i = 0; i < dijkstra_.size(); ++i) {
int x, y;
dijkstra_.get(i, &x, &y);
g_sample_console.at({x, y}).bg = lightGround;
}
}
// move the creature
busy_ -= delta_time;
if (busy_ <= 0.0f) {
busy_ = 0.2f;
if (using_astar_) {
if (!path_.isEmpty()) {
path_.walk(&player_x_, &player_y_, true);
}
} else {
if (!dijkstra_.isEmpty()) {
dijkstra_.walk(&player_x_, &player_y_);
}
}
}
}
private:
int player_x_ = 20, player_y_ = 10; // player position
int dest_x_ = 24, dest_y_ = 1; // destination
TCODMap map_{SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT};
TCODPath path_{&map_};
TCODDijkstra dijkstra_{&map_};
bool using_astar_ = true;
float dijkstra_dist_ = 0;
float busy_ = 0;
};
// ***************************
// bsp sample
// ***************************
static int bspDepth = 8;
static int minRoomSize = 4;
static bool randomRoom = false; // a room fills a random part of the node or the maximum available space ?
static bool roomWalls = true; // if true, there is always a wall on north & west side of a room
typedef char map_t[SAMPLE_SCREEN_WIDTH][SAMPLE_SCREEN_HEIGHT];
// draw a vertical line
void vline(map_t* map, int x, int y1, int y2) {
int y = y1;
int dy = (y1 > y2 ? -1 : 1);
(*map)[x][y] = ' ';
if (y1 == y2) return;
do {
y += dy;
(*map)[x][y] = ' ';
} while (y != y2);
}
// draw a vertical line up until we reach an empty space
void vline_up(map_t* map, int x, int y) {
while (y >= 0 && (*map)[x][y] != ' ') {
(*map)[x][y] = ' ';
y--;
}
}
// draw a vertical line down until we reach an empty space
void vline_down(map_t* map, int x, int y) {
while (y < SAMPLE_SCREEN_HEIGHT && (*map)[x][y] != ' ') {
(*map)[x][y] = ' ';
y++;
}
}
// draw a horizontal line
void hline(map_t* map, int x1, int y, int x2) {
int x = x1;
int dx = (x1 > x2 ? -1 : 1);
(*map)[x][y] = ' ';
if (x1 == x2) return;
do {
x += dx;
(*map)[x][y] = ' ';
} while (x != x2);
}
// draw a horizontal line left until we reach an empty space
void hline_left(map_t* map, int x, int y) {
while (x >= 0 && (*map)[x][y] != ' ') {
(*map)[x][y] = ' ';
x--;
}
}
// draw a horizontal line right until we reach an empty space
void hline_right(map_t* map, int x, int y) {
while (x < SAMPLE_SCREEN_WIDTH && (*map)[x][y] != ' ') {
(*map)[x][y] = ' ';
x++;
}
}
// the class building the dungeon from the bsp nodes
class BspListener : public ITCODBspCallback {
public:
bool visitNode(TCODBsp* node, void* userData) {
map_t* map = (map_t*)userData;
if (node->isLeaf()) {
// calculate the room size
int minx = node->x + 1;
int maxx = node->x + node->w - 1;
int miny = node->y + 1;
int maxy = node->y + node->h - 1;
if (!roomWalls) {
if (minx > 1) minx--;
if (miny > 1) miny--;