-
Notifications
You must be signed in to change notification settings - Fork 0
/
olcPixelGameEngine.h
2465 lines (2109 loc) · 79.1 KB
/
olcPixelGameEngine.h
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
/*
olcPixelGameEngine.h
+-------------------------------------------------------------+
| OneLoneCoder Pixel Game Engine v1.21 |
| "Like the command prompt console one, but not..." - javidx9 |
+-------------------------------------------------------------+
What is this?
~~~~~~~~~~~~~
The olcConsoleGameEngine has been a surprising and wonderful success for me,
and I'm delighted how people have reacted so positively towards it, so thanks
for that.
However, there are limitations that I simply cannot avoid. Firstly, I need to
maintain several different versions of it to accommodate users on Windows7,
8, 10, Linux, Mac, Visual Studio & Code::Blocks. Secondly, this year I've been
pushing the console to the limits of its graphical capabilities and the effect
is becoming underwhelming. The engine itself is not slow at all, but the process
that Windows uses to draw the command prompt to the screen is, and worse still,
it's dynamic based upon the variation of character colours and glyphs. Sadly
I have no control over this, and recent videos that are extremely graphical
(for a command prompt :P ) have been dipping to unacceptable framerates. As
the channel has been popular with aspiring game developers, I'm concerned that
the visual appeal of the command prompt is perhaps limited to us oldies, and I
dont want to alienate younger learners. Finally, I'd like to demonstrate many
more algorithms and image processing that exist in the graphical domain, for
which the console is insufficient.
For this reason, I have created olcPixelGameEngine! The look and feel to the
programmer is almost identical, so all of my existing code from the videos is
easily portable, and the programmer uses this file in exactly the same way. But
I've decided that rather than just build a command prompt emulator, that I
would at least harness some modern(ish) portable technologies.
As a result, the olcPixelGameEngine supports 32-bit colour, is written in a
cross-platform style, uses modern(ish) C++ conventions and most importantly,
renders much much faster. I will use this version when my applications are
predominantly graphics based, but use the console version when they are
predominantly text based - Don't worry, loads more command prompt silliness to
come yet, but evolution is important!!
License (OLC-3)
~~~~~~~~~~~~~~~
Copyright 2018 - 2019 OneLoneCoder.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions or derivations of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions or derivative works in binary form must reproduce the above
copyright notice. This list of conditions and the following disclaimer must be
reproduced in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Links
~~~~~
YouTube: https://www.youtube.com/javidx9
https://www.youtube.com/javidx9extra
Discord: https://discord.gg/WhwHUMV
Twitter: https://www.twitter.com/javidx9
Twitch: https://www.twitch.tv/javidx9
GitHub: https://www.github.com/onelonecoder
Homepage: https://www.onelonecoder.com
Patreon: https://www.patreon.com/javidx9
Relevant Videos
~~~~~~~~~~~~~~~
https://youtu.be/kRH6oJLFYxY Introducing olcPixelGameEngine
Compiling in Linux
~~~~~~~~~~~~~~~~~~
You will need a modern C++ compiler, so update yours!
To compile use the command:
g++ -o YourProgName YourSource.cpp -lX11 -lGL -lpthread -lpng -lstdc++fs
On some Linux configurations, the frame rate is locked to the refresh
rate of the monitor. This engine tries to unlock it but may not be
able to, in which case try launching your program like this:
vblank_mode=0 ./YourProgName
Compiling in Code::Blocks on Windows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Well I wont judge you, but make sure your Code::Blocks installation
is really up to date - you may even consider updating your C++ toolchain
to use MinGW32-W64.
Guide for installing recent GCC for Windows:
https://www.msys2.org/
Guide for configuring code::blocks:
https://solarianprogrammer.com/2019/11/05/install-gcc-windows/
https://solarianprogrammer.com/2019/11/16/install-codeblocks-gcc-windows-build-c-cpp-fortran-programs/
Add these libraries to "Linker Options":
user32 gdi32 opengl32 gdiplus Shlwapi stdc++fs
Set these compiler options: -std=c++17
Ports
~~~~~
olc::PixelGameEngine has been ported and tested with varying degrees of
success to: WinXP, Win7, Win8, Win10, Various Linux, Rapberry Pi,
Chromebook, Playstation Portable (PSP) and Nintendo Switch. If you are
interested in the details of these ports, come and visit the Discord!
Thanks
~~~~~~
I'd like to extend thanks to Eremiell, slavka, gurkanctn, Phantim, IProgramInCPP
JackOJC, KrossX, Huhlig, Dragoneye, Appa, JustinRichardsMusic, SliceNDice
Ralakus, Gorbit99, raoul, joshinils, benedani & MagetzUb for advice, ideas and
testing, and I'd like to extend my appreciation to the 107K YouTube followers,
56 Patreons and 5.2K Discord server members who give me the motivation to keep
going with all this :D
Significant Contributors: @MaGetzUb, @slavka, @Dragoneye & @Gorbit99
Special thanks to those who bring gifts!
GnarGnarHead.......Domina
Gorbit99...........Bastion, Ori & The Blind Forest
Marti Morta........Gris
Special thanks to my Patreons too - I wont name you on here, but I've
certainly enjoyed my tea and flapjacks :D
Author
~~~~~~
David Barr, aka javidx9, �OneLoneCoder 2018, 2019
*/
//////////////////////////////////////////////////////////////////////////////////////////
/* Example Usage (main.cpp)
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
// Override base class with your custom functionality
class Example : public olc::PixelGameEngine
{
public:
Example()
{
sAppName = "Example";
}
public:
bool OnUserCreate() override
{
// Called once at the start, so create things here
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
// called once per frame, draws random coloured pixels
for (int x = 0; x < ScreenWidth(); x++)
for (int y = 0; y < ScreenHeight(); y++)
Draw(x, y, olc::Pixel(rand() % 255, rand() % 255, rand()% 255));
return true;
}
};
int main()
{
Example demo;
if (demo.Construct(256, 240, 4, 4))
demo.Start();
return 0;
}
*/
#ifndef OLC_PGE_DEF
#define OLC_PGE_DEF
#if defined(_WIN32) // WINDOWS specific includes ==============================================
// Link to libraries
#ifndef __MINGW32__
#pragma comment(lib, "user32.lib") // Visual Studio Only
#pragma comment(lib, "gdi32.lib") // For other Windows Compilers please add
#pragma comment(lib, "opengl32.lib") // these libs to your linker input
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "Shlwapi.lib")
#else
// In Code::Blocks
#if !defined _WIN32_WINNT
#ifdef HAVE_MSMF
#define _WIN32_WINNT 0x0600 // Windows Vista
#else
#define _WIN32_WINNT 0x0500 // Windows 2000
#endif
#endif
#endif
// Include WinAPI
//#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <gdiplus.h>
#include <Shlwapi.h>
// OpenGL Extension
#include <GL/gl.h>
typedef BOOL(WINAPI wglSwapInterval_t) (int interval);
static wglSwapInterval_t *wglSwapInterval;
#endif
#ifdef __linux__ // LINUX specific includes ==============================================
#include <GL/gl.h>
#include <GL/glx.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <png.h>
typedef int(glSwapInterval_t) (Display *dpy, GLXDrawable drawable, int interval);
static glSwapInterval_t *glSwapIntervalEXT;
#endif
// Standard includes
#include <cmath>
#include <cstdint>
#include <string>
#include <iostream>
#include <streambuf>
#include <sstream>
#include <chrono>
#include <vector>
#include <list>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <fstream>
#include <map>
#include <functional>
#include <algorithm>
#if __cplusplus >= 201703L
// C++17 onwards
#include <filesystem>
namespace _gfs = std::filesystem;
#else
// Older "Modern" C++ :P
#include <experimental/filesystem>
namespace _gfs = std::experimental::filesystem::v1;
#endif
#undef min
#undef max
#define UNUSED(x) (void)(x)
namespace olc // All OneLoneCoder stuff will now exist in the "olc" namespace
{
struct Pixel
{
union
{
uint32_t n = 0xFF000000;
struct
{
uint8_t r; uint8_t g; uint8_t b; uint8_t a;
};
};
Pixel();
Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255);
Pixel(uint32_t p);
enum Mode { NORMAL, MASK, ALPHA, CUSTOM };
bool operator==(const Pixel& p) const;
bool operator!=(const Pixel& p) const;
};
// Some constants for symbolic naming of Pixels
static const Pixel
WHITE(255, 255, 255),
GREY(192, 192, 192), DARK_GREY(128, 128, 128), VERY_DARK_GREY(64, 64, 64),
RED(255, 0, 0), DARK_RED(128, 0, 0), VERY_DARK_RED(64, 0, 0),
YELLOW(255, 255, 0), DARK_YELLOW(128, 128, 0), VERY_DARK_YELLOW(64, 64, 0),
GREEN(0, 255, 0), DARK_GREEN(0, 128, 0), VERY_DARK_GREEN(0, 64, 0),
CYAN(0, 255, 255), DARK_CYAN(0, 128, 128), VERY_DARK_CYAN(0, 64, 64),
BLUE(0, 0, 255), DARK_BLUE(0, 0, 128), VERY_DARK_BLUE(0, 0, 64),
MAGENTA(255, 0, 255), DARK_MAGENTA(128, 0, 128), VERY_DARK_MAGENTA(64, 0, 64),
BLACK(0, 0, 0),
BLANK(0, 0, 0, 0);
enum rcode
{
FAIL = 0,
OK = 1,
NO_FILE = -1,
};
//==================================================================================
template <class T>
struct v2d_generic
{
T x = 0;
T y = 0;
inline v2d_generic() : x(0), y(0) { }
inline v2d_generic(T _x, T _y) : x(_x), y(_y) { }
inline v2d_generic(const v2d_generic& v) : x(v.x), y(v.y){ }
inline T mag() { return sqrt(x * x + y * y); }
inline T mag2() { return x * x + y * y; }
inline v2d_generic norm() { T r = 1 / mag(); return v2d_generic(x*r, y*r); }
inline v2d_generic perp() { return v2d_generic(-y, x); }
inline T dot(const v2d_generic& rhs) { return this->x * rhs.x + this->y * rhs.y; }
inline T cross(const v2d_generic& rhs) { return this->x * rhs.y - this->y * rhs.x; }
inline v2d_generic operator + (const v2d_generic& rhs) const { return v2d_generic(this->x + rhs.x, this->y + rhs.y);}
inline v2d_generic operator - (const v2d_generic& rhs) const { return v2d_generic(this->x - rhs.x, this->y - rhs.y);}
inline v2d_generic operator * (const T& rhs) const { return v2d_generic(this->x * rhs, this->y * rhs); }
inline v2d_generic operator / (const T& rhs) const { return v2d_generic(this->x / rhs, this->y / rhs); }
inline v2d_generic& operator += (const v2d_generic& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; }
inline v2d_generic& operator -= (const v2d_generic& rhs) { this->x -= rhs.x; this->y -= rhs.y; return *this; }
inline v2d_generic& operator *= (const T& rhs) { this->x *= rhs; this->y *= rhs; return *this; }
inline v2d_generic& operator /= (const T& rhs) { this->x /= rhs; this->y /= rhs; return *this; }
inline T& operator [] (std::size_t i) { return *((T*)this + i); /* <-- D'oh :( */ }
inline operator v2d_generic<int>() const { return { static_cast<int32_t>(this->x), static_cast<int32_t>(this->y) }; }
inline operator v2d_generic<float>() const { return { static_cast<float>(this->x), static_cast<float>(this->y) }; }
};
template<class T> inline v2d_generic<T> operator * (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator * (const double& lhs, const v2d_generic<T>& rhs){ return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator * (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs * rhs.x, lhs * rhs.y); }
template<class T> inline v2d_generic<T> operator / (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
template<class T> inline v2d_generic<T> operator / (const double& lhs, const v2d_generic<T>& rhs){ return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
template<class T> inline v2d_generic<T> operator / (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>(lhs / rhs.x, lhs / rhs.y); }
typedef v2d_generic<int32_t> vi2d;
typedef v2d_generic<float> vf2d;
typedef v2d_generic<double> vd2d;
//=============================================================
struct HWButton
{
bool bPressed = false; // Set once during the frame the event occurs
bool bReleased = false; // Set once during the frame the event occurs
bool bHeld = false; // Set true for all frames between pressed and released events
};
//=============================================================
struct ResourceBuffer : public std::streambuf
{
ResourceBuffer(std::ifstream &ifs, uint32_t offset, uint32_t size);
std::vector<char> vMemory;
};
class ResourcePack : public std::streambuf
{
public:
ResourcePack();
~ResourcePack();
bool AddFile(const std::string& sFile);
bool LoadPack(const std::string& sFile, const std::string& sKey);
bool SavePack(const std::string& sFile, const std::string& sKey);
ResourceBuffer GetFileBuffer(const std::string& sFile);
bool Loaded();
private:
struct sResourceFile { uint32_t nSize; uint32_t nOffset; };
std::map<std::string, sResourceFile> mapFiles;
std::ifstream baseFile;
const std::string scramble(const std::string& data, const std::string& key);
std::string makeposix(const std::string& path);
};
//=============================================================
// A bitmap-like structure that stores a 2D array of Pixels
class Sprite
{
public:
Sprite();
Sprite(std::string sImageFile, olc::ResourcePack *pack = nullptr);
Sprite(int32_t w, int32_t h);
~Sprite();
public:
olc::rcode LoadFromFile(std::string sImageFile, olc::ResourcePack *pack = nullptr);
olc::rcode LoadFromPGESprFile(std::string sImageFile, olc::ResourcePack *pack = nullptr);
olc::rcode SaveToPGESprFile(std::string sImageFile);
public:
int32_t width = 0;
int32_t height = 0;
enum Mode { NORMAL, PERIODIC };
public:
void SetSampleMode(olc::Sprite::Mode mode = olc::Sprite::Mode::NORMAL);
Pixel GetPixel(int32_t x, int32_t y);
bool SetPixel(int32_t x, int32_t y, Pixel p);
Pixel Sample(float x, float y);
Pixel SampleBL(float u, float v);
Pixel* GetData();
private:
Pixel *pColData = nullptr;
Mode modeSample = Mode::NORMAL;
#ifdef OLC_DBG_OVERDRAW
public:
static int nOverdrawCount;
#endif
};
//=============================================================
enum Key
{
NONE,
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
K0, K1, K2, K3, K4, K5, K6, K7, K8, K9,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
UP, DOWN, LEFT, RIGHT,
SPACE, TAB, SHIFT, CTRL, INS, DEL, HOME, END, PGUP, PGDN,
BACK, ESCAPE, RETURN, ENTER, PAUSE, SCROLL,
NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9,
NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL,
};
//=============================================================
class PixelGameEngine
{
public:
PixelGameEngine();
public:
olc::rcode Construct(uint32_t screen_w, uint32_t screen_h, uint32_t pixel_w, uint32_t pixel_h, bool full_screen = false, bool vsync = false);
olc::rcode Start();
public: // Override Interfaces
// Called once on application startup, use to load your resources
virtual bool OnUserCreate();
// Called every frame, and provides you with a time per frame value
virtual bool OnUserUpdate(float fElapsedTime);
// Called once on application termination, so you can be a clean coder
virtual bool OnUserDestroy();
public: // Hardware Interfaces
// Returns true if window is currently in focus
bool IsFocused();
// Get the state of a specific keyboard button
HWButton GetKey(Key k);
// Get the state of a specific mouse button
HWButton GetMouse(uint32_t b);
// Get Mouse X coordinate in "pixel" space
int32_t GetMouseX();
// Get Mouse Y coordinate in "pixel" space
int32_t GetMouseY();
// Get Mouse Wheel Delta
int32_t GetMouseWheel();
public: // Utility
// Returns the width of the screen in "pixels"
int32_t ScreenWidth();
// Returns the height of the screen in "pixels"
int32_t ScreenHeight();
// Returns the width of the currently selected drawing target in "pixels"
int32_t GetDrawTargetWidth();
// Returns the height of the currently selected drawing target in "pixels"
int32_t GetDrawTargetHeight();
// Returns the currently active draw target
Sprite* GetDrawTarget();
public: // Draw Routines
// Specify which Sprite should be the target of drawing functions, use nullptr
// to specify the primary screen
void SetDrawTarget(Sprite *target);
// Change the pixel mode for different optimisations
// olc::Pixel::NORMAL = No transparency
// olc::Pixel::MASK = Transparent if alpha is < 255
// olc::Pixel::ALPHA = Full transparency
void SetPixelMode(Pixel::Mode m);
Pixel::Mode GetPixelMode();
// Use a custom blend function
void SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel& pSource, const olc::Pixel& pDest)> pixelMode);
// Change the blend factor form between 0.0f to 1.0f;
void SetPixelBlend(float fBlend);
// Offset texels by sub-pixel amount (advanced, do not use)
void SetSubPixelOffset(float ox, float oy);
// Draws a single Pixel
virtual bool Draw(int32_t x, int32_t y, Pixel p = olc::WHITE);
bool Draw(const olc::vi2d& pos, Pixel p = olc::WHITE);
// Draws a line from (x1,y1) to (x2,y2)
void DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF);
void DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF);
// Draws a circle located at (x,y) with radius
void DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF);
void DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF);
// Fills a circle located at (x,y) with radius
void FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE);
void FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE);
// Draws a rectangle at (x,y) to (x+w,y+h)
void DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
void DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE);
// Fills a rectangle at (x,y) to (x+w,y+h)
void FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE);
void FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE);
// Draws a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
void DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE);
// Flat fills a triangle between points (x1,y1), (x2,y2) and (x3,y3)
void FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE);
void FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE);
// Draws an entire sprite at location (x,y)
void DrawSprite(int32_t x, int32_t y, Sprite *sprite, uint32_t scale = 1);
void DrawSprite(const olc::vi2d& pos, Sprite *sprite, uint32_t scale = 1);
// Draws an area of a sprite at location (x,y), where the
// selected area is (ox,oy) to (ox+w,oy+h)
void DrawPartialSprite(int32_t x, int32_t y, Sprite *sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale = 1);
void DrawPartialSprite(const olc::vi2d& pos, Sprite *sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale = 1);
// Draws a single line of text
void DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1);
void DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1);
// Clears entire draw target to Pixel
void Clear(Pixel p);
// Resize the primary screen sprite
void SetScreenSize(int w, int h);
public: // Branding
std::string sAppName;
private: // Inner mysterious workings
Sprite *pDefaultDrawTarget = nullptr;
Sprite *pDrawTarget = nullptr;
Pixel::Mode nPixelMode = Pixel::NORMAL;
float fBlendFactor = 1.0f;
uint32_t nScreenWidth = 256;
uint32_t nScreenHeight = 240;
uint32_t nPixelWidth = 4;
uint32_t nPixelHeight = 4;
int32_t nMousePosX = 0;
int32_t nMousePosY = 0;
int32_t nMouseWheelDelta = 0;
int32_t nMousePosXcache = 0;
int32_t nMousePosYcache = 0;
int32_t nMouseWheelDeltaCache = 0;
int32_t nWindowWidth = 0;
int32_t nWindowHeight = 0;
int32_t nViewX = 0;
int32_t nViewY = 0;
int32_t nViewW = 0;
int32_t nViewH = 0;
bool bFullScreen = false;
float fPixelX = 1.0f;
float fPixelY = 1.0f;
float fSubPixelOffsetX = 0.0f;
float fSubPixelOffsetY = 0.0f;
bool bHasInputFocus = false;
bool bHasMouseFocus = false;
bool bEnableVSYNC = false;
float fFrameTimer = 1.0f;
int nFrameCount = 0;
Sprite *fontSprite = nullptr;
std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> funcPixelMode;
static std::map<size_t, uint8_t> mapKeys;
bool pKeyNewState[256]{ 0 };
bool pKeyOldState[256]{ 0 };
HWButton pKeyboardState[256];
bool pMouseNewState[5]{ 0 };
bool pMouseOldState[5]{ 0 };
HWButton pMouseState[5];
#if defined(_WIN32)
HDC glDeviceContext = nullptr;
HGLRC glRenderContext = nullptr;
#endif
#if defined(__linux__)
GLXContext glDeviceContext = nullptr;
GLXContext glRenderContext = nullptr;
#endif
GLuint glBuffer;
void EngineThread();
// If anything sets this flag to false, the engine
// "should" shut down gracefully
static std::atomic<bool> bAtomActive;
// Common initialisation functions
void olc_UpdateMouse(int32_t x, int32_t y);
void olc_UpdateMouseWheel(int32_t delta);
void olc_UpdateWindowSize(int32_t x, int32_t y);
void olc_UpdateViewport();
bool olc_OpenGLCreate();
void olc_ConstructFontSheet();
#if defined(_WIN32)
// Windows specific window handling
HWND olc_hWnd = nullptr;
HWND olc_WindowCreate();
std::wstring wsAppName;
static LRESULT CALLBACK olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
#if defined(__linux__)
// Non-Windows specific window handling
Display* olc_Display = nullptr;
Window olc_WindowRoot;
Window olc_Window;
XVisualInfo* olc_VisualInfo;
Colormap olc_ColourMap;
XSetWindowAttributes olc_SetWindowAttribs;
Display* olc_WindowCreate();
#endif
};
class PGEX
{
friend class olc::PixelGameEngine;
protected:
static PixelGameEngine* pge;
};
//=============================================================
}
#endif // OLC_PGE_DEF
/*
Object Oriented Mode
~~~~~~~~~~~~~~~~~~~~
If the olcPixelGameEngine.h is called from several sources it can cause
multiple definitions of objects. To prevent this, ONLY ONE of the pathways
to including this file must have OLC_PGE_APPLICATION defined before it. This prevents
the definitions being duplicated.
If all else fails, create a file called "olcPixelGameEngine.cpp" with the following
two lines. Then you can just #include "olcPixelGameEngine.h" as normal without worrying
about defining things. Dont forget to include that cpp file as part of your build!
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
*/
#ifdef OLC_PGE_APPLICATION
#undef OLC_PGE_APPLICATION
namespace olc
{
Pixel::Pixel()
{
r = 0; g = 0; b = 0; a = 255;
}
Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)
{
r = red; g = green; b = blue; a = alpha;
}
Pixel::Pixel(uint32_t p)
{
n = p;
}
bool Pixel::operator==(const Pixel& p) const
{
return n == p.n;
}
bool Pixel::operator!=(const Pixel& p) const
{
return n != p.n;
}
//==========================================================
#if defined(_WIN32)
std::wstring ConvertS2W(std::string s)
{
#ifdef __MINGW32__
wchar_t *buffer = new wchar_t[s.length() + 1];
mbstowcs(buffer, s.c_str(), s.length());
buffer[s.length()] = L'\0';
#else
int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0);
wchar_t* buffer = new wchar_t[count];
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count);
#endif
std::wstring w(buffer);
delete[] buffer;
return w;
}
#endif
Sprite::Sprite()
{
pColData = nullptr;
width = 0;
height = 0;
}
Sprite::Sprite(std::string sImageFile, olc::ResourcePack *pack)
{
LoadFromFile(sImageFile, pack);
}
Sprite::Sprite(int32_t w, int32_t h)
{
if(pColData) delete[] pColData;
width = w; height = h;
pColData = new Pixel[width * height];
for (int32_t i = 0; i < width*height; i++)
pColData[i] = Pixel();
}
Sprite::~Sprite()
{
if (pColData) delete pColData;
}
olc::rcode Sprite::LoadFromPGESprFile(std::string sImageFile, olc::ResourcePack *pack)
{
if (pColData) delete[] pColData;
auto ReadData = [&](std::istream &is)
{
is.read((char*)&width, sizeof(int32_t));
is.read((char*)&height, sizeof(int32_t));
pColData = new Pixel[width * height];
is.read((char*)pColData, width * height * sizeof(uint32_t));
};
// These are essentially Memory Surfaces represented by olc::Sprite
// which load very fast, but are completely uncompressed
if (pack == nullptr)
{
std::ifstream ifs;
ifs.open(sImageFile, std::ifstream::binary);
if (ifs.is_open())
{
ReadData(ifs);
return olc::OK;
}
else
return olc::FAIL;
}
else
{
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
std::istream is(&rb);
ReadData(is);
}
return olc::FAIL;
}
olc::rcode Sprite::SaveToPGESprFile(std::string sImageFile)
{
if (pColData == nullptr) return olc::FAIL;
std::ofstream ofs;
ofs.open(sImageFile, std::ifstream::binary);
if (ofs.is_open())
{
ofs.write((char*)&width, sizeof(int32_t));
ofs.write((char*)&height, sizeof(int32_t));
ofs.write((char*)pColData, width*height*sizeof(uint32_t));
ofs.close();
return olc::OK;
}
return olc::FAIL;
}
#if defined(__linux__)
void pngReadStream(png_structp pngPtr, png_bytep data, png_size_t length)
{
png_voidp a = png_get_io_ptr(pngPtr);
((std::istream*)a)->read((char*)data, length);
}
#endif
olc::rcode Sprite::LoadFromFile(std::string sImageFile, olc::ResourcePack *pack)
{
UNUSED(pack);
#if defined(_WIN32)
Gdiplus::Bitmap *bmp = nullptr;
if (pack != nullptr)
{
// Load sprite from input stream
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
bmp = Gdiplus::Bitmap::FromStream(SHCreateMemStream((BYTE*)rb.vMemory.data(), rb.vMemory.size()));
}
else
{
// Load sprite from file
bmp = Gdiplus::Bitmap::FromFile(ConvertS2W(sImageFile).c_str());
}
if (bmp == nullptr) return olc::NO_FILE;
width = bmp->GetWidth();
height = bmp->GetHeight();
pColData = new Pixel[width * height];
for(int x=0; x<width; x++)
for (int y = 0; y < height; y++)
{
Gdiplus::Color c;
bmp->GetPixel(x, y, &c);
SetPixel(x, y, Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha()));
}
delete bmp;
return olc::OK;
#endif
#if defined(__linux__)
////////////////////////////////////////////////////////////////////////////
// Use libpng, Thanks to Guillaume Cottenceau
// https://gist.github.com/niw/5963798
// Also reading png from streams
// http://www.piko3d.net/tutorials/libpng-tutorial-loading-png-files-from-streams/
png_structp png;
png_infop info;
auto loadPNG = [&]()
{
png_read_info(png, info);
png_byte color_type;
png_byte bit_depth;
png_bytep *row_pointers;
width = png_get_image_width(png, info);
height = png_get_image_height(png, info);
color_type = png_get_color_type(png, info);
bit_depth = png_get_bit_depth(png, info);
if (bit_depth == 16) png_set_strip_16(png);
if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png);
if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
if (color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_PALETTE)
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
png_read_update_info(png, info);
row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height);
for (int y = 0; y < height; y++) {
row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info));
}
png_read_image(png, row_pointers);
////////////////////////////////////////////////////////////////////////////
// Create sprite array
pColData = new Pixel[width * height];
// Iterate through image rows, converting into sprite format
for (int y = 0; y < height; y++)
{
png_bytep row = row_pointers[y];
for (int x = 0; x < width; x++)
{
png_bytep px = &(row[x * 4]);
SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3]));
}
}
};
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png) goto fail_load;
info = png_create_info_struct(png);
if (!info) goto fail_load;
if (setjmp(png_jmpbuf(png))) goto fail_load;
if (pack == nullptr)
{
FILE* f = fopen(sImageFile.c_str(), "rb");
if (!f) return olc::NO_FILE;
png_init_io(png, f);
loadPNG();
fclose(f);
}
else
{
ResourceBuffer rb = pack->GetFileBuffer(sImageFile);
std::istream is(&rb);
png_set_read_fn(png, (png_voidp)&is, pngReadStream);
loadPNG();
}
return olc::OK;
fail_load:
width = 0;
height = 0;
pColData = nullptr;
return olc::FAIL;
#endif
}
void Sprite::SetSampleMode(olc::Sprite::Mode mode)
{
modeSample = mode;
}
Pixel Sprite::GetPixel(int32_t x, int32_t y)
{
if (modeSample == olc::Sprite::Mode::NORMAL)
{
if (x >= 0 && x < width && y >= 0 && y < height)
return pColData[y*width + x];
else
return Pixel(0, 0, 0, 0);
}
else
{
return pColData[abs(y%height)*width + abs(x%width)];
}
}
bool Sprite::SetPixel(int32_t x, int32_t y, Pixel p)
{
#ifdef OLC_DBG_OVERDRAW
nOverdrawCount++;
#endif
if (x >= 0 && x < width && y >= 0 && y < height)
{
pColData[y*width + x] = p;
return true;
}
else
return false;
}
Pixel Sprite::Sample(float x, float y)
{
int32_t sx = std::min((int32_t)((x * (float)width)), width - 1);
int32_t sy = std::min((int32_t)((y * (float)height)), height - 1);
return GetPixel(sx, sy);
}
Pixel Sprite::SampleBL(float u, float v)
{
u = u * width - 0.5f;
v = v * height - 0.5f;
int x = (int)floor(u); // cast to int rounds toward zero, not downward
int y = (int)floor(v); // Thanks @joshinils
float u_ratio = u - x;
float v_ratio = v - y;
float u_opposite = 1 - u_ratio;
float v_opposite = 1 - v_ratio;
olc::Pixel p1 = GetPixel(std::max(x, 0), std::max(y, 0));
olc::Pixel p2 = GetPixel(std::min(x + 1, (int)width - 1), std::max(y, 0));
olc::Pixel p3 = GetPixel(std::max(x, 0), std::min(y + 1, (int)height - 1));
olc::Pixel p4 = GetPixel(std::min(x + 1, (int)width - 1), std::min(y + 1, (int)height - 1));
return olc::Pixel(
(uint8_t)((p1.r * u_opposite + p2.r * u_ratio) * v_opposite + (p3.r * u_opposite + p4.r * u_ratio) * v_ratio),
(uint8_t)((p1.g * u_opposite + p2.g * u_ratio) * v_opposite + (p3.g * u_opposite + p4.g * u_ratio) * v_ratio),
(uint8_t)((p1.b * u_opposite + p2.b * u_ratio) * v_opposite + (p3.b * u_opposite + p4.b * u_ratio) * v_ratio));
}
Pixel* Sprite::GetData() { return pColData; }
//==========================================================
// Resource Packs - Allows you to store files in one large
// scrambled file
ResourceBuffer::ResourceBuffer(std::ifstream &ifs, uint32_t offset, uint32_t size)
{