-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathEngine.cpp
More file actions
1468 lines (1318 loc) · 38.9 KB
/
Copy pathEngine.cpp
File metadata and controls
1468 lines (1318 loc) · 38.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
#include "Engine.h"
#include "GameUtil.h"
#include "SDL3_image/SDL_image.h"
#include "UIRenderer.h"
#include "strfunc.h"
#ifdef __ANDROID__
#include "ZipFile2.h"
#endif
#include <cmath>
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#pragma comment(lib, "user32.lib")
#endif
//#include "opencv4/opencv2/opencv.hpp"
Engine::Engine()
{
}
Engine::~Engine()
{
destroy();
}
#ifdef __ANDROID__
void Engine::extractAssetsIfNeeded()
{
const std::string external = SDL_GetAndroidExternalStoragePath();
const std::string dest = "/sdcard/kys-cpp/game/";
const std::string marker = dest + ".game_extracted";
auto create_parent_dirs = [](const std::string& path) {
size_t pos = path.find('/', 1);
while (pos != std::string::npos)
{
SDL_CreateDirectory(path.substr(0, pos).c_str());
pos = path.find('/', pos + 1);
}
SDL_CreateDirectory(path.c_str());
};
if (filefunc::fileExist(marker))
{
return;
}
SDL_Log("kys-cpp: extracting game assets to %s ...", dest.c_str());
SDL_IOStream* io = SDL_IOFromFile("game.zip", "rb");
if (!io)
{
SDL_Log("kys-cpp: cannot open game.zip from assets: %s", SDL_GetError());
return;
}
Sint64 size = SDL_GetIOSize(io);
std::string buf(size, '\0');
SDL_ReadIO(io, buf.data(), (size_t)size);
SDL_CloseIO(io);
const std::string tmp_zip = external + "/.game_tmp.zip";
filefunc::writeFile(buf.c_str(), (int)buf.size(), tmp_zip);
{
ZipFile2 zip;
zip.openRead(tmp_zip);
if (!zip.opened())
{
SDL_Log("kys-cpp: cannot open temp zip at %s", tmp_zip.c_str());
return;
}
for (const auto& f : zip.getFileNames())
{
std::string normalized = f;
for (char& c : normalized)
{
if (c == '\\')
{
c = '/';
}
}
if (normalized.empty() || normalized.back() == '/')
{
continue;
}
const std::string out_path = dest + normalized;
const size_t slash = out_path.rfind('/');
if (slash != std::string::npos)
{
create_parent_dirs(out_path.substr(0, slash));
}
const auto data = zip.readFile(f);
filefunc::writeFile(data.c_str(), (int)data.size(), out_path);
}
}
remove(tmp_zip.c_str());
filefunc::writeFile("ok", 2, marker);
SDL_Log("kys-cpp: assets extracted successfully.");
}
#endif
int Engine::init(void* handle /*= nullptr*/, int handle_type /*= 0*/, int maximized, const std::string& str, int fullscreen)
{
if (inited_)
{
return 0;
}
inited_ = true;
texture_top_left_highlight_enabled_ = GameUtil::getInstance()->getInt("game", "texture_top_left_highlight", 1) != 0;
#ifdef __ANDROID__
SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight");
#endif
#ifndef _WINDLL
if (!SDL_Init(SDL_INIT_EVENTS | SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMEPAD | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_SENSOR))
{
return -1;
}
#endif
window_mode_ = handle_type;
auto create_window = [&]() -> Window*
{
if (handle)
{
#ifdef _WIN32
if (handle_type == 0)
{
Prop props;
props.set(SDL_PROP_WINDOW_CREATE_WIN32_HWND_POINTER, handle);
return SDL_CreateWindowWithProperties(props.id());
}
#endif
return (Window*)handle;
}
Prop props;
props.set(SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true);
props.set(SDL_PROP_WINDOW_CREATE_MAXIMIZED_BOOLEAN, maximized);
#ifdef __ANDROID__
props.set(SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN, true);
#else
props.set(SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN, fullscreen != 0);
#endif
props.set(SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, ui_w_);
props.set(SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, ui_h_);
props.set(SDL_PROP_WINDOW_CREATE_TITLE_STRING, title_.c_str());
return SDL_CreateWindowWithProperties(props.id());
};
window_ = create_window();
if (!window_)
{
return -1;
}
#ifndef _WINDLL
SDL_ShowWindow(window_);
SDL_RaiseWindow(window_);
#endif
renderer_ = SDL_GetRenderer(window_);
std::print("{}\n", SDL_GetError());
if (renderer_ == nullptr)
{
Prop props;
props.set(SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, window_);
std::vector<std::string> renderer_candidates;
auto add_renderer_candidate = [&renderer_candidates](const std::string& name)
{
if (name.empty()) { return; }
for (auto& existing : renderer_candidates)
{
if (existing == name) { return; }
}
renderer_candidates.push_back(name);
};
if (!str.empty())
{
auto str1 = strfunc::toLowerCase(str);
for (auto s : strfunc::splitString(str1, ","))
{
add_renderer_candidate(strfunc::trim(s));
}
}
#ifdef _WIN32
add_renderer_candidate("direct3d12");
add_renderer_candidate("direct3d");
#else
add_renderer_candidate("gpu");
add_renderer_candidate("opengles2");
#endif
add_renderer_candidate("opengl");
add_renderer_candidate("software");
for (auto& candidate : renderer_candidates)
{
SDL_SetHint(SDL_HINT_RENDER_DRIVER, candidate.c_str());
renderer_ = SDL_CreateRendererWithProperties(props.id());
if (renderer_)
{
std::print("Renderer fallback selected: {}\n", candidate);
renderer_self_ = true;
break;
}
}
if (renderer_ == nullptr)
{
renderer_ = SDL_CreateRendererWithProperties(props.id());
renderer_self_ = renderer_ != nullptr;
}
}
if (renderer_ == nullptr)
{
std::print("Failed to create renderer: {}\n", SDL_GetError());
return -1;
}
std::print("Renderer name: {}\n", SDL_GetRendererName(renderer_));
max_texture_size_ = (int)SDL_GetNumberProperty(SDL_GetRendererProperties(renderer_), SDL_PROP_RENDERER_MAX_TEXTURE_SIZE_NUMBER, 0);
std::print("Max texture size: {}\n", max_texture_size_);
//SDL_SetDefaultTextureScaleMode(renderer_, SDL_SCALEMODE_PIXELART);
//SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
//SDL_EventState(SDL_EVENT_DROP_FILE, SDL_ENABLE);
//屏蔽触摸板
//SDL_EventState(SDL_EVENT_FINGER_UP, SDL_DISABLE);
//SDL_EventState(SDL_EVENT_FINGER_DOWN, SDL_DISABLE);
//SDL_EventState(SDL_EVENT_FINGER_MOTION, SDL_DISABLE);
//手柄
checkGameControllers();
int num_touch = 0;
SDL_GetTouchDevices(&num_touch);
std::print("Found {} touch(es)\n", num_touch);
rect_ = { 0, 0, ui_w_, ui_h_ };
renderPresent();
TTF_Init();
#ifdef _MSC_VER
RECT r;
SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID)&r, 0);
int w = GetSystemMetrics(SM_CXEDGE);
int h = GetSystemMetrics(SM_CYEDGE);
min_x_ = r.left + w;
min_y_ = r.top + h + GetSystemMetrics(SM_CYCAPTION);
max_x_ = r.right - w;
max_y_ = r.bottom - h;
#else
Rect r;
SDL_GetDisplayBounds(0, &r);
min_x_ = r.x;
min_y_ = r.y;
max_x_ = r.w + r.x;
max_y_ = r.h + r.y;
#endif
square_ = createRectTexture(100, 100, 0);
std::print("maximum width and height are: {}, {}\n", max_x_, max_y_);
createMainTexture(SDL_PixelFormat(0), TEXTUREACCESS_TARGET, ui_w_, ui_h_);
return 0;
}
int Engine::getWindowWidth() const
{
int w, h;
getWindowSize(w, h);
return w;
}
int Engine::getWindowHeight() const
{
int w, h;
getWindowSize(w, h);
return h;
}
void Engine::setWindowIsMaximized(bool b) const
{
if (b)
{
SDL_MaximizeWindow(window_);
}
else
{
SDL_RestoreWindow(window_);
}
}
void Engine::setWindowSize(int w, int h)
{
if (getWindowIsMaximized())
{
return;
}
if (rotation_ == 90 || rotation_ == 270)
{
std::swap(w, h);
}
if (w <= 0 || h <= 0)
{
return;
}
//w = 1920;
//h = 1080;
win_w_ = std::min(max_x_ - min_x_, w);
win_h_ = std::min(max_y_ - min_y_, h);
double ratio;
ratio = std::min(1.0 * win_w_ / w, 1.0 * win_h_ / h);
win_w_ = w * ratio;
win_h_ = h * ratio;
//std::print("{}, {}, {}, {}, {}\n", win_w_, win_h_, w, h, ratio);
if (!window_)
{
return;
}
SDL_SetWindowSize(window_, win_w_, win_h_);
setPresentPosition(tex_);
SDL_ShowWindow(window_);
SDL_RaiseWindow(window_);
SDL_GetWindowSize(window_, &win_w_, &win_h_);
//std::print("{}, {}, {}, {}, {}\n", win_w_, win_h_, w, h, ratio);
//resetWindowsPosition();
//renderPresent();
}
void Engine::setWindowPosition(int x, int y) const
{
int w, h;
getWindowSize(w, h);
if (x == WINDOWPOS_CENTERED)
{
x = min_x_ + (max_x_ - min_x_ - w) / 2;
}
if (y == WINDOWPOS_CENTERED)
{
y = min_y_ + (max_y_ - min_y_ - h) / 2;
}
SDL_SetWindowPosition(window_, x, y);
}
void Engine::createMainTexture(PixelFormat pixfmt, TextureAccess a, int w, int h)
{
resetRenderTarget();
if (tex_)
{
SDL_DestroyTexture(tex_);
}
if (pixfmt < 0)
{
tex_ = createRenderedTexture(w, h);
}
else
{
tex_ = createTexture(pixfmt, a, w, h);
}
setPresentPosition(tex_);
}
void Engine::resizeMainTexture(int w, int h) const
{
float w0, h0;
uint32_t pix_fmt;
if (!SDL_GetTextureSize(tex_, &w0, &h0))
{
if (int(w0) != w || int(h0) != h)
{
//createMainTexture(pix_fmt, w, h);
}
}
}
//创建一个专用于画场景的,后期放大
void Engine::createAssistTexture(const std::string& name, int w, int h)
{
//tex_ = createYUVTexture(w, h);
auto& tex = tex_map_[name];
if (tex)
{
SDL_DestroyTexture(tex);
}
int64_t pixfmt = 0;
SDL_GetNumberProperty(SDL_GetTextureProperties(tex_), SDL_PROP_TEXTURE_FORMAT_NUMBER, pixfmt);
tex = createTexture((SDL_PixelFormat)pixfmt, TEXTUREACCESS_TARGET, w, h);
//tex_ = createRenderedTexture(768, 480);
//SDL_SetTextureBlendMode(tex2_, SDL_BLENDMODE_BLEND);
}
bool Engine::resizeRenderTexturesToWindow()
{
if (!window_ || !tex_)
{
return false;
}
int windowW = 0;
int windowH = 0;
getWindowSize(windowW, windowH);
if (windowW <= 0 || windowH <= 0)
{
return false;
}
const int baseUiW = std::max(1, base_ui_w_);
const int baseUiH = std::max(1, base_ui_h_);
const double windowAspect = static_cast<double>(windowW) / windowH;
const double baseAspect = static_cast<double>(baseUiW) / baseUiH;
int newUiW = baseUiW;
int newUiH = baseUiH;
if (windowAspect >= baseAspect)
{
newUiW = std::max(baseUiW, static_cast<int>(std::round(windowAspect * baseUiH)));
}
else
{
newUiH = std::max(baseUiH, static_cast<int>(std::round(baseUiW / windowAspect)));
}
bool resized = false;
if (newUiW != ui_w_ || newUiH != ui_h_)
{
ui_w_ = newUiW;
ui_h_ = newUiH;
createMainTexture(SDL_PixelFormat(0), TEXTUREACCESS_TARGET, ui_w_, ui_h_);
resized = true;
}
auto sceneTexture = tex_map_.find("scene");
if (sceneTexture != tex_map_.end() && sceneTexture->second)
{
int sceneW = 0;
int sceneH = 0;
getTextureSize(sceneTexture->second, sceneW, sceneH);
const int newSceneH = std::max(1, sceneH > 0 ? sceneH : newUiH);
const int newSceneW = std::max(1, static_cast<int>(std::round(static_cast<double>(windowW) * newSceneH / windowH)));
if (newSceneW != sceneW || newSceneH != sceneH)
{
createAssistTexture("scene", newSceneW, newSceneH);
resized = true;
}
}
setPresentPosition(tex_);
return resized;
}
void Engine::setPresentPosition(Texture* tex)
{
if (!tex)
{
return;
}
int w_dst = 0, h_dst = 0;
int w_src = 0, h_src = 0;
getWindowSize(w_dst, h_dst);
getTextureSize(tex, w_src, h_src);
w_src *= ratio_x_;
h_src *= ratio_y_;
if (keep_ratio_)
{
if (w_src == 0 || h_src == 0)
{
return;
}
double ratio = std::min(1.0 * w_dst / w_src, 1.0 * h_dst / h_src);
if (rotation_ == 90 || rotation_ == 270)
{
ratio = std::min(1.0 * w_dst / h_src, 1.0 * h_dst / w_src);
}
rect_.x = (w_dst - w_src * ratio) / 2;
rect_.y = (h_dst - h_src * ratio) / 2;
rect_.w = w_src * ratio;
rect_.h = h_src * ratio;
}
else
{
//unfinshed
rect_.x = 0;
rect_.y = 0;
rect_.w = w_dst;
rect_.h = h_dst;
if (rotation_ == 90 || rotation_ == 270)
{
rect_.x = (h_dst - w_dst) / 2;
rect_.y = (w_dst - h_dst) / 2;
rect_.w = h_dst;
rect_.h = w_dst;
}
}
}
Texture* Engine::createTexture(PixelFormat pix_fmt, TextureAccess a, int w, int h) const
{
if (pix_fmt == SDL_PIXELFORMAT_UNKNOWN)
{
pix_fmt = SDL_PIXELFORMAT_RGBA8888;
}
if (max_texture_size_ > 0)
{
w = std::min(w, max_texture_size_);
h = std::min(h, max_texture_size_);
}
return SDL_CreateTexture(renderer_, pix_fmt, (SDL_TextureAccess)a, w, h);
}
Texture* Engine::createYUVTexture(int w, int h) const
{
return SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, w, h);
}
void Engine::updateYUVTexture(Texture* t, uint8_t* data0, int size0, uint8_t* data1, int size1, uint8_t* data2, int size2)
{
SDL_UpdateYUVTexture(t, nullptr, data0, size0, data1, size1, data2, size2);
}
Texture* Engine::createTexture(int w, int h)
{
return SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, w, h);
}
Texture* Engine::createRenderedTexture(int w, int h)
{
if (max_texture_size_ > 0)
{
w = std::min(w, max_texture_size_);
h = std::min(h, max_texture_size_);
}
return SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h);
}
void Engine::updateTexture(Texture* t, uint8_t* buffer, int pitch)
{
SDL_UpdateTexture(t, nullptr, buffer, pitch);
}
int Engine::lockTexture(Texture* t, Rect* r, void** pixel, int* pitch)
{
return SDL_LockTexture(t, r, pixel, pitch);
}
void Engine::unlockTexture(Texture* t)
{
SDL_UnlockTexture(t);
}
void Engine::renderPresent() const
{
//renderMainTextureToWindow();
SDL_RenderPresent(renderer_);
SDL_RenderClear(renderer_);
//setRenderMainTexture();
}
void Engine::renderTexture(Texture* t /*= nullptr*/, double angle)
{
FRect rectf;
SDL_RectToFRect(&rect_, &rectf);
SDL_RenderTextureRotated(renderer_, t, nullptr, &rectf, angle, nullptr, SDL_FLIP_NONE);
render_times_++;
}
void Engine::renderTexture(Texture* t, int x, int y, int w, int h, double angle, int inPresent)
{
if (inPresent == 1)
{
x += rect_.x;
y += rect_.y;
}
int w0, h0;
getTextureSize(t, w0, h0);
if (w < 0)
{
w = w0;
}
if (h < 0)
{
h = h0;
}
Rect r = { x, y, w, h };
renderTexture(t, nullptr, &r, angle);
}
void Engine::renderTexture(Texture* t, Rect* rect0, Rect* rect1, double angle, int inPresent /*= 0*/)
{
FRect rect0f, rect1f;
FRect *rect0f_ptr = nullptr, *rect1f_ptr = nullptr;
if (rect0)
{
SDL_RectToFRect(rect0, &rect0f);
rect0f_ptr = &rect0f;
}
if (rect1)
{
SDL_RectToFRect(rect1, &rect1f);
rect1f_ptr = &rect1f;
}
SDL_RenderTextureRotated(renderer_, t, rect0f_ptr, rect1f_ptr, angle, nullptr, SDL_FLIP_NONE);
render_times_++;
}
void Engine::renderTexture(Texture* t, Rect* rect0, const std::vector<FPoint>& v, const std::vector<FPoint>& v2)
{
if (!t || v.size() < 4)
{
if (rect0)
{
renderTexture(t, rect0, rect0);
}
else
{
renderTexture(t);
}
return;
}
float tw = 1.0f, th = 1.0f;
SDL_GetTextureSize(t, &tw, &th);
FPoint src[4];
if (v2.size() >= 4)
{
for (int i = 0; i < 4; i++)
{
src[i] = v2[i];
}
}
else if (rect0)
{
src[0] = { float(rect0->x), float(rect0->y) };
src[1] = { float(rect0->x + rect0->w), float(rect0->y) };
src[2] = { float(rect0->x + rect0->w), float(rect0->y + rect0->h) };
src[3] = { float(rect0->x), float(rect0->y + rect0->h) };
}
else
{
src[0] = { 0, 0 };
src[1] = { tw, 0 };
src[2] = { tw, th };
src[3] = { 0, th };
}
SDL_Vertex vertices[4];
for (int i = 0; i < 4; i++)
{
vertices[i].position = v[i];
vertices[i].tex_coord = { src[i].x / tw, src[i].y / th };
vertices[i].color = { 1.0f, 1.0f, 1.0f, 1.0f };
}
int indices[6] = { 0, 1, 2, 2, 3, 0 };
SDL_RenderGeometry(renderer_, t, vertices, 4, indices, 6);
render_times_++;
}
void Engine::renderTextureMesh(Texture* t, const std::vector<FPoint>& v, const std::vector<FPoint>& v2,
const std::vector<Color>& colors, const std::vector<int>& indices, float top_left_brightness)
{
if (v.empty() || v.size() != v2.size() || indices.empty())
{
return;
}
float tw = 1.0f, th = 1.0f;
if (t)
{
SDL_GetTextureSize(t, &tw, &th);
}
std::vector<SDL_Vertex> vertices(v.size());
bool use_vertex_colors = colors.size() == v.size();
for (size_t i = 0; i < v.size(); i++)
{
vertices[i].position = v[i];
vertices[i].tex_coord = { v2[i].x / tw, v2[i].y / th };
if (use_vertex_colors)
{
vertices[i].color = {
colors[i].r / 255.0f,
colors[i].g / 255.0f,
colors[i].b / 255.0f,
colors[i].a / 255.0f
};
}
else
{
vertices[i].color = { 1.0f, 1.0f, 1.0f, 1.0f };
}
}
SDL_RenderGeometry(renderer_, t, vertices.data(), int(vertices.size()), indices.data(), int(indices.size()));
render_times_++;
if (texture_top_left_highlight_enabled_ && top_left_brightness > 0.0f)
{
float min_x = v[0].x;
float max_x = v[0].x;
float min_y = v[0].y;
float max_y = v[0].y;
for (const auto& point : v)
{
min_x = (std::min)(min_x, point.x);
max_x = (std::max)(max_x, point.x);
min_y = (std::min)(min_y, point.y);
max_y = (std::max)(max_y, point.y);
}
float width = (std::max)(1.0f, max_x - min_x);
float height = (std::max)(1.0f, max_y - min_y);
for (auto& vertex : vertices)
{
float left_weight = (max_x - vertex.position.x) / width;
float top_weight = (max_y - vertex.position.y) / height;
float brightness = top_left_brightness * std::clamp(left_weight, 0.0f, 1.0f) * std::clamp(top_weight, 0.0f, 1.0f);
vertex.color = { brightness, brightness, brightness, 1.0f };
}
SDL_BlendMode previous_blend = SDL_BLENDMODE_BLEND;
SDL_GetTextureBlendMode(t, &previous_blend);
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_ADD);
SDL_RenderGeometry(renderer_, t, vertices.data(), int(vertices.size()), indices.data(), int(indices.size()));
SDL_SetTextureBlendMode(t, previous_blend);
render_times_++;
}
}
void Engine::renderTextureLight(Texture* t, Rect* rect0, Rect* rect1, const std::vector<Color>& colors,
const std::vector<float>& brightness_v, double angle)
{
if (!t || !rect1)
{
return;
}
int w = rect1->w;
int h = rect1->h;
int w0, h0;
getTextureSize(t, w0, h0);
if (w < 0)
{
w = w0;
}
if (h < 0)
{
h = h0;
}
float x0 = float(rect1->x);
float y0 = float(rect1->y);
float x1 = x0 + w;
float y1 = y0 + h;
float tex_x0 = rect0 ? float(rect0->x) : 0.0f;
float tex_y0 = rect0 ? float(rect0->y) : 0.0f;
float tex_x1 = tex_x0 + (rect0 ? rect0->w : w0);
float tex_y1 = tex_y0 + (rect0 ? rect0->h : h0);
float tw = 1.0f, th = 1.0f;
float tw_f, th_f;
SDL_GetTextureSize(t, &tw_f, &th_f);
tw = tw_f;
th = th_f;
auto color_to_fcolor = [](const Color& c) -> SDL_FColor
{
return { float(c.r) / 255.0f, float(c.g) / 255.0f, float(c.b) / 255.0f, float(c.a) / 255.0f };
};
SDL_FColor default_color = { 1.0f, 1.0f, 1.0f, 1.0f };
SDL_Vertex vertices[4];
// colors 的顺序对应四个顶点:
// colors[0] -> 左上(x0, y0)
// colors[1] -> 右上(x1, y0)
// colors[2] -> 右下(x1, y1)
// colors[3] -> 左下(x0, y1)
// 若未提供某个索引的颜色,则该顶点使用默认白色。
vertices[0].position = { x0, y0 };
vertices[0].tex_coord = { tex_x0 / tw, tex_y0 / th };
vertices[0].color = colors.size() > 0 ? color_to_fcolor(colors[0]) : default_color;
vertices[1].position = { x1, y0 };
vertices[1].tex_coord = { tex_x1 / tw, tex_y0 / th };
vertices[1].color = colors.size() > 1 ? color_to_fcolor(colors[1]) : default_color;
vertices[2].position = { x1, y1 };
vertices[2].tex_coord = { tex_x1 / tw, tex_y1 / th };
vertices[2].color = colors.size() > 2 ? color_to_fcolor(colors[2]) : default_color;
vertices[3].position = { x0, y1 };
vertices[3].tex_coord = { tex_x0 / tw, tex_y1 / th };
vertices[3].color = colors.size() > 3 ? color_to_fcolor(colors[3]) : default_color;
if (angle != 0)
{
const double pi = 3.14159265358979323846;
const float rad = float(angle * pi / 180.0);
const float c = float(std::cos(rad));
const float s = float(std::sin(rad));
const float cx = x0 + w * 0.5f;
const float cy = y0 + h * 0.5f;
for (auto& v : vertices)
{
float rx = v.position.x - cx;
float ry = v.position.y - cy;
v.position.x = cx + rx * c - ry * s;
v.position.y = cy + rx * s + ry * c;
}
}
int indices[6] = { 0, 1, 2, 2, 3, 0 };
SDL_RenderGeometry(renderer_, t, vertices, 4, indices, 6);
render_times_++;
if (!brightness_v.empty())
{
float b[4] = { 0, 0, 0, 0 };
for (int i = 0; i < 4; i++)
{
if (i < (int)brightness_v.size())
{
b[i] = (std::max)(0.0f, brightness_v[i]);
}
}
if (!texture_top_left_highlight_enabled_)
{
b[0] = 0.0f;
}
float max_b = (std::max)((std::max)(b[0], b[1]), (std::max)(b[2], b[3]));
int full_pass = int(std::floor(max_b));
float remain = max_b - full_pass;
SDL_BlendMode prev_blend = SDL_BLENDMODE_BLEND;
SDL_GetTextureBlendMode(t, &prev_blend);
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_ADD);
auto do_add_pass = [&](float pass_base)
{
SDL_Vertex add_vertices[4] = { vertices[0], vertices[1], vertices[2], vertices[3] };
for (int i = 0; i < 4; i++)
{
float k = b[i] - pass_base;
if (k > 1.0f) { k = 1.0f; }
if (k < 0.0f) { k = 0.0f; }
add_vertices[i].color = { k, k, k, 1.0f };
}
SDL_RenderGeometry(renderer_, t, add_vertices, 4, indices, 6);
render_times_++;
};
for (int p = 0; p < full_pass; p++)
{
do_add_pass(float(p));
}
if (remain > 0.0f)
{
do_add_pass(float(full_pass));
}
SDL_SetTextureBlendMode(t, prev_blend);
}
}
void Engine::destroy() const
{
destroyTexture(tex_);
for (auto& [k, tex] : tex_map_)
{
destroyTexture(tex);
}
if (renderer_self_)
{
SDL_DestroyRenderer(renderer_);
}
if (window_mode_ == 0)
{
SDL_DestroyWindow(window_);
}
#ifndef _WINDLL
SDL_Quit();
#endif
}
bool Engine::isFullScreen()
{
uint32_t state = SDL_GetWindowFlags(window_);
full_screen_ = (state & SDL_WINDOW_FULLSCREEN);
return full_screen_;
}
void Engine::setFullScreen(bool b)
{
full_screen_ = b;
SDL_SetWindowFullscreen(window_, full_screen_);
renderClear();
}
void Engine::toggleFullscreen()
{
setFullScreen(!isFullScreen());
}
Texture* Engine::loadImage(const std::string& filename, int as_white)
{
//std::print("%s", filename.c_str());
//屏蔽libpng的错误输出
DisableStream d(stderr);
auto sur = IMG_Load(filename.c_str());
if (!sur) { return nullptr; }
if (as_white) { toWhite(sur); }
auto tex = SDL_CreateTextureFromSurface(renderer_, sur);
SDL_DestroySurface(sur);
return tex;
}
Texture* Engine::loadImageFromMemory(const std::string& content, int as_white) const
{
auto rw = SDL_IOFromConstMem(content.data(), content.size());
auto sur = IMG_Load_IO(rw, 1);
if (!sur) { return nullptr; }
if (as_white) { toWhite(sur); }
auto tex = SDL_CreateTextureFromSurface(renderer_, sur);
SDL_DestroySurface(sur);
return tex;
}
void Engine::toWhite(Surface* sur)
{
if (sur->format != SDL_PIXELFORMAT_RGBA8888)
{
auto sur2 = SDL_ConvertSurface(sur, SDL_PIXELFORMAT_RGBA8888);
SDL_DestroySurface(sur);
sur = sur2;
}
for (int y = 0; y < sur->h; y++)
{
for (int x = 0; x < sur->w; x++)
{
uint8_t r, g, b, a;
if (!SDL_ReadSurfacePixel(sur, x, y, &r, &g, &b, &a))
{
continue;
}
SDL_WriteSurfacePixel(sur, x, y, 255, 255, 255, a);
}
}
}
bool Engine::setKeepRatio(bool b)
{
return keep_ratio_ = b;
}
Texture* Engine::transRGBABitmapToTexture(const uint8_t* src, uint32_t color, int w, int h, int stride) const
{
auto s = SDL_CreateSurface(w, h, SDL_PIXELFORMAT_RGBA8888);
SDL_FillSurfaceRect(s, nullptr, color);
auto p = (uint8_t*)s->pixels;
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
p[4 * (y * w + x)] = src[y * stride + x];
}
}
auto t = SDL_CreateTextureFromSurface(renderer_, s);
SDL_DestroySurface(s);
setTextureBlendMode(t);
setTextureAlphaMod(t, 192);
return t;
}
void Engine::resetWindowPosition()
{
int x, y, w, h, x0, y0;