-
Notifications
You must be signed in to change notification settings - Fork 128
/
pixmappresenter.d
1175 lines (950 loc) · 28.7 KB
/
pixmappresenter.d
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
/+
== pixmappresenter ==
Copyright Elias Batek (0xEAB) 2023 - 2024.
Distributed under the Boost Software License, Version 1.0.
+/
/++
$(B Pixmap Presenter) is a high-level display library for one specific scenario:
Blitting fully-rendered frames to the screen.
This is useful for software-rendered applications.
Think of old-skool games, emulators etc.
This library builds upon [arsd.simpledisplay] and [arsd.color].
It wraps a [arsd.simpledisplay.SimpleWindow|SimpleWindow] and displays the provided frame data.
Each frame is automatically centered on, and optionally scaled to, the carrier window.
This processing is done with hardware acceleration (OpenGL).
Later versions might add a software-mode.
Several $(B scaling) modes are supported.
Most notably [pixmappresenter.Scaling.contain|contain] that scales pixmaps to the window’s current size
while preserving the original aspect ratio.
See [Scaling] for details.
$(PITFALL
This module is $(B work in progress).
API is subject to changes until further notice.
)
## Usage examples
### Basic usage
This example displays a blue frame that increases in color intensity,
then jumps back to black and the process repeats.
---
void main() {
// Internal resolution of the images (“frames”) we will render.
// From the PixmapPresenter’s perspective,
// these are the “fully-rendered frames” that it will blit to screen.
// They may be up- & down-scaled to the window’s actual size
// (according to the chosen scaling mode) by the presenter.
const resolution = Size(240, 120);
// Let’s create a new presenter.
// (For more fine-grained control there’s also a constructor overload that
// accepts a [PresenterConfig] instance).
auto presenter = new PixmapPresenter(
"Demo", // window title
resolution, // internal resolution
Size(960, 480), // initial window size (optional; default: =resolution)
);
// This variable will be “shared” across events (and frames).
int blueChannel = 0;
// Run the eventloop.
// The callback delegate will get executed every ~16ms (≙ ~60FPS) and schedule a redraw.
presenter.eventLoop(16, delegate() {
// Update the pixmap (“framebuffer”) here…
// Construct an RGB color value.
auto color = Pixel(0x00, 0x00, blueChannel);
// For demo purposes, apply it to the whole pixmap.
presenter.framebuffer.clear(color);
// Increment the amount of blue to be used by the next frame.
++blueChannel;
// reset if greater than 0xFF (=ubyte.max)
if (blueChannel > 0xFF)
blueChannel = 0;
});
}
---
### Minimal example
---
void main() {
auto pmp = new PixmapPresenter("My Pixmap App", Size(640, 480));
pmp.framebuffer.clear(rgb(0xFF, 0x00, 0x99));
pmp.eventLoop();
}
---
### Advanced example
---
import arsd.pixmappresenter;
int main() {
// Internal resolution of the images (“frames”) we will render.
// For further details, check out the “Basic usage” example.
const resolution = Size(240, 120);
// Configure our presenter in advance.
auto cfg = PresenterConfig();
cfg.window.title = "Demo II";
cfg.window.size = Size(960, 480);
cfg.renderer.resolution = resolution;
cfg.renderer.scaling = Scaling.integer; // integer scaling
// → The frame on-screen will
// always have a size that is a
// multiple of the internal
// resolution.
// → Also check out the
// `intHybrid` scaling mode.
// The gentle reader might have noticed that integer scaling will result
// in a padding/border area around the image for most window sizes.
// How about changing its color?
cfg.renderer.background = ColorF(Pixel.white);
// Let’s instantiate a new presenter with the previously created config.
auto presenter = new PixmapPresenter(cfg);
// Start with a green frame, so we can easily observe what’s going on.
presenter.framebuffer.clear(rgb(0x00, 0xDD, 0x00));
int line = 0;
ubyte color = 0;
byte colorDelta = 2;
// Run the eventloop.
// Note how the callback delegate returns a [LoopCtrl] instance.
return presenter.eventLoop(delegate() {
// Determine the start and end index of the current line in the
// framebuffer.
immutable x0 = line * resolution.width;
immutable x1 = x0 + resolution.width;
// Change the color of the current line
presenter.framebuffer.data[x0 .. x1] = rgb(color, color, 0xFF);
// Determine the color to use for the next line
// (to be applied on the next update).
color += colorDelta;
if (color == 0x00)
colorDelta = 2;
else if (color >= 0xFE)
colorDelta = -2;
// Increment the line counter; reset to 0 once we’ve reached the
// end of the framebuffer (=the final/last line).
++line;
if (line == resolution.height)
line = 0;
// Schedule a redraw in ~16ms.
return LoopCtrl.redrawIn(16);
}, delegate(MouseEvent ev) {
// toggle fullscreen mode on double-click
if (ev.doubleClick) {
presenter.toggleFullscreen();
}
});
}
---
+/
module arsd.pixmappresenter;
import arsd.core;
/++
While publicly importing `arsd.simpledisplay` is not actually necessary,
most real-world code would eventually import said module as well anyway.
More importantly, this public import prevents users from facing certain
symbol clashes in their code that would occur in modules importing both
`pixmappresenter` and `simpledisplay`.
For instance both of these modules happen to define different types
as `Pixmap`.
+/
public import arsd.simpledisplay;
///
public import arsd.pixmappaint;
/*
## TODO
- More comprehensive documentation
- Additional renderer implementations:
- a `ScreenPainter`-based renderer
- Minimum window size
- to ensure `Scaling.integer` doesn’t break “unexpectedly”
- More control over timing
- that’s a simpledisplay thing, though
*/
///
alias Pixmap = arsd.pixmappaint.Pixmap;
///
alias WindowResizedCallback = void delegate(Size);
// is the Timer class available on this platform?
private enum hasTimer = is(arsd.simpledisplay.Timer == class);
// resolve symbol clash on “Timer” (arsd.core vs arsd.simpledisplay)
static if (hasTimer) {
private alias Timer = arsd.simpledisplay.Timer;
}
// viewport math
private @safe pure nothrow @nogc {
// keep aspect ratio (contain)
bool karContainNeedsDownscaling(const Size drawing, const Size canvas) {
return (drawing.width > canvas.width)
|| (drawing.height > canvas.height);
}
// keep aspect ratio (contain)
int karContainScalingFactorInt(const Size drawing, const Size canvas) {
const int w = canvas.width / drawing.width;
const int h = canvas.height / drawing.height;
return (w < h) ? w : h;
}
// keep aspect ratio (contain; FP variant)
float karContainScalingFactorF(const Size drawing, const Size canvas) {
const w = float(canvas.width) / float(drawing.width);
const h = float(canvas.height) / float(drawing.height);
return (w < h) ? w : h;
}
// keep aspect ratio (cover)
float karCoverScalingFactorF(const Size drawing, const Size canvas) {
const w = float(canvas.width) / float(drawing.width);
const h = float(canvas.height) / float(drawing.height);
return (w > h) ? w : h;
}
Size deltaPerimeter(const Size a, const Size b) {
return Size(
a.width - b.width,
a.height - b.height,
);
}
Point offsetCenter(const Size drawing, const Size canvas) {
auto delta = canvas.deltaPerimeter(drawing);
return (castTo!Point(delta) >> 1);
}
}
///
struct Viewport {
Size size; ///
Point offset; ///
}
/++
Calls `glViewport` with the data from the provided [Viewport].
+/
void glViewportPMP(const ref Viewport vp) {
glViewport(vp.offset.x, vp.offset.y, vp.size.width, vp.size.height);
}
/++
Calculates the dimensions and position of the viewport for the provided config.
$(TIP
Primary use case for this is [PixmapRenderer] implementations.
)
+/
Viewport calculateViewport(const ref PresenterConfig config) @safe pure nothrow @nogc {
Size size;
final switch (config.renderer.scaling) {
case Scaling.none:
size = config.renderer.resolution;
break;
case Scaling.stretch:
size = config.window.size;
break;
case Scaling.contain:
const float scaleF = karContainScalingFactorF(config.renderer.resolution, config.window.size);
size = Size(
castTo!int(scaleF * config.renderer.resolution.width),
castTo!int(scaleF * config.renderer.resolution.height),
);
break;
case Scaling.integer:
const int scaleI = karContainScalingFactorInt(config.renderer.resolution, config.window.size);
size = (config.renderer.resolution * scaleI);
break;
case Scaling.intHybrid:
if (karContainNeedsDownscaling(config.renderer.resolution, config.window.size)) {
goto case Scaling.contain;
}
goto case Scaling.integer;
case Scaling.cover:
const float fillF = karCoverScalingFactorF(config.renderer.resolution, config.window.size);
size = Size(
castTo!int(fillF * config.renderer.resolution.width),
castTo!int(fillF * config.renderer.resolution.height),
);
break;
}
const Point offset = offsetCenter(size, config.window.size);
return Viewport(size, offset);
}
/++
Scaling/Fit Modes
Each scaling modes has unique behavior for different window-size to pixmap-size ratios.
$(NOTE
Unfortunately, there are no universally applicable naming conventions for these modes.
In fact, different implementations tend to contradict each other.
)
$(SMALL_TABLE
Mode feature matrix
Mode | Aspect Ratio | Pixel Ratio | Cropping | Border | Comment(s)
`none` | preserved | preserved | yes | 4 | Crops if the `window.size < pixmap.size`.
`stretch` | no | no | no | none |
`contain` | preserved | no | no | 2 | Letterboxing/Pillarboxing
`integer` | preserved | preserved | no | 4 | Works only if `window.size >= pixmap.size`.
`intHybrid` | preserved | when up | no | 4 or 2 | Hybrid: int upscaling, decimal downscaling
`cover` | preserved | no | yes | none |
)
$(NOTE
Integer scaling – Note that the resulting integer ratio of a window smaller than a pixmap is `0`.
Use `intHybrid` to prevent the pixmap from disappearing on disproportionately small window sizes.
It uses $(I integer)-mode for upscaling and the regular $(I contain)-mode for downscaling.
)
$(SMALL_TABLE
Feature | Definition
Aspect Ratio | Whether the original aspect ratio (width ÷ height) of the input frame is preserved
Pixel Ratio | Whether the orignal pixel ratio (= square) is preserved
Cropping | Whether the outer areas of the input frame might get cut off
Border | The number of padding-areas/borders that can potentially appear around the frame
)
For your convience, aliases matching the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
CSS property are provided, too. These are prefixed with `css`.
Currently there is no equivalent for `scale-down` as it does not appear to be particularly useful here.
+/
enum Scaling {
none = 0, ///
stretch, ///
contain, ///
integer, ///
intHybrid, ///
cover, ///
// aliases
center = none, ///
keepAspectRatio = contain, ///
// CSS `object-fit` style aliases
cssNone = none, /// equivalent CSS: `object-fit: none;`
cssContain = contain, /// equivalent CSS: `object-fit: contain;`
cssFill = stretch, /// equivalent CSS: `object-fit: fill;`
cssCover = cover, /// equivalent CSS: `object-fit: cover;`
}
///
enum ScalingFilter {
nearest, /// nearest neighbor → blocky/pixel’ish
linear, /// (bi-)linear interpolation → smooth/blurry
}
///
struct PresenterConfig {
Window window; ///
Renderer renderer; ///
///
static struct Renderer {
/++
Internal resolution
+/
Size resolution;
/++
Scaling method
to apply when `window.size` != `resolution`
+/
Scaling scaling = Scaling.keepAspectRatio;
/++
Filter
+/
ScalingFilter filter = ScalingFilter.nearest;
/++
Background color
+/
ColorF background = ColorF(0.0f, 0.0f, 0.0f, 1.0f);
///
void setPixelPerfect() {
scaling = Scaling.integer;
filter = ScalingFilter.nearest;
}
}
///
static struct Window {
///
string title = "ARSD Pixmap Presenter";
///
Size size;
/++
Window corner style
$(NOTE
At the time of writing, this is only implemented on Windows.
It has no effect elsewhere for now but does no harm either.
Windows: Requires Windows 11 or later.
)
History:
Added September 10, 2024.
+/
CornerStyle corners = CornerStyle.rectangular;
}
}
// undocumented
struct PresenterObjectsContainer {
Pixmap framebuffer;
SimpleWindow window;
PresenterConfig config;
}
///
struct WantsOpenGl {
ubyte vMaj; /// Major version
ubyte vMin; /// Minor version
bool compat; /// Compatibility profile? → true = Compatibility Profile; false = Core Profile
@safe pure nothrow @nogc:
/// Is OpenGL wanted?
bool wanted() const {
return vMaj > 0;
}
}
/++
Renderer abstraction
A renderer scales, centers and blits pixmaps to screen.
+/
interface PixmapRenderer {
/++
Does this renderer use OpenGL?
Returns:
Whether the renderer requires an OpenGL-enabled window
and which version is expected.
+/
public WantsOpenGl wantsOpenGl() @safe pure nothrow @nogc;
/++
Setup function
Called once during setup.
Perform initialization tasks in here.
$(NOTE
The final thing a setup function does
is usually to call `reconfigure()` on the renderer.
)
Params:
container = Pointer to the [PresenterObjectsContainer] of the presenter. To be stored for later use.
+/
public void setup(PresenterObjectsContainer* container);
/++
Reconfigures the renderer
Called upon configuration changes.
The new config can be found in the [PresenterObjectsContainer] received during `setup()`.
+/
public void reconfigure();
/++
Schedules a redraw
+/
public void redrawSchedule();
/++
Triggers a redraw
+/
public void redrawNow();
}
/++
OpenGL 3.0 implementation of a [PixmapRenderer]
+/
final class OpenGl3PixmapRenderer : PixmapRenderer {
private {
PresenterObjectsContainer* _poc;
GLfloat[16] _vertices;
OpenGlShader _shader;
GLuint _vao;
GLuint _vbo;
GLuint _ebo;
GLuint _texture = 0;
}
///
public this() {
}
public WantsOpenGl wantsOpenGl() @safe pure nothrow @nogc {
return WantsOpenGl(3, 0, false);
}
public void setup(PresenterObjectsContainer* pro) {
_poc = pro;
_poc.window.suppressAutoOpenglViewport = true;
_poc.window.visibleForTheFirstTime = &this.visibleForTheFirstTime;
_poc.window.redrawOpenGlScene = &this.redrawOpenGlScene;
}
private {
void visibleForTheFirstTime() {
_poc.window.setAsCurrentOpenGlContext();
gl3.loadDynamicLibrary();
this.compileLinkShader();
this.setupVertexObjects();
this.reconfigure();
}
void redrawOpenGlScene() {
glClearColor(
_poc.config.renderer.background.r,
_poc.config.renderer.background.g,
_poc.config.renderer.background.b,
_poc.config.renderer.background.a
);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _texture);
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0, 0,
_poc.config.renderer.resolution.width, _poc.config.renderer.resolution.height,
GL_RGBA, GL_UNSIGNED_BYTE,
castTo!(void*)(_poc.framebuffer.data.ptr)
);
glUseProgram(_shader.shaderProgram);
glBindVertexArray(_vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, null);
}
}
private {
void compileLinkShader() {
_shader = new OpenGlShader(
OpenGlShader.Source(GL_VERTEX_SHADER, `
#version 330 core
layout (location = 0) in vec2 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 TexCoord;
void main() {
gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
TexCoord = aTexCoord;
}
`),
OpenGlShader.Source(GL_FRAGMENT_SHADER, `
#version 330 core
out vec4 FragColor;
in vec2 TexCoord;
uniform sampler2D sampler;
void main() {
FragColor = texture(sampler, TexCoord);
}
`),
);
}
void setupVertexObjects() {
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);
glGenBuffers(1, &_vbo);
glGenBuffers(1, &_ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
glBufferDataSlice(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferDataSlice(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * GLfloat.sizeof, null);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * GLfloat.sizeof, castTo!(void*)(2 * GLfloat.sizeof));
glEnableVertexAttribArray(1);
}
void setupTexture() {
if (_texture == 0) {
glGenTextures(1, &_texture);
}
glBindTexture(GL_TEXTURE_2D, _texture);
final switch (_poc.config.renderer.filter) with (ScalingFilter) {
case nearest:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case linear:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA8,
_poc.config.renderer.resolution.width, _poc.config.renderer.resolution.height,
0,
GL_RGBA, GL_UNSIGNED_BYTE,
null
);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
public void reconfigure() {
const Viewport viewport = calculateViewport(_poc.config);
glViewportPMP(viewport);
this.setupTexture();
}
void redrawSchedule() {
_poc.window.redrawOpenGlSceneSoon();
}
void redrawNow() {
_poc.window.redrawOpenGlSceneNow();
}
private {
static immutable GLfloat[] vertices = [
//dfmt off
// positions // texture coordinates
1.0f, 1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 0.0f,
//dfmt on
];
static immutable GLuint[] indices = [
//dfmt off
0, 1, 3,
1, 2, 3,
//dfmt on
];
}
}
/++
Legacy OpenGL (1.x) renderer implementation
Uses what is often called the $(I Fixed Function Pipeline).
+/
final class OpenGl1PixmapRenderer : PixmapRenderer {
private {
PresenterObjectsContainer* _poc;
GLuint _texture = 0;
}
public @safe pure nothrow @nogc {
///
this() {
}
WantsOpenGl wantsOpenGl() pure nothrow @nogc @safe {
return WantsOpenGl(1, 1, true);
}
}
public void setup(PresenterObjectsContainer* poc) {
_poc = poc;
_poc.window.suppressAutoOpenglViewport = true;
_poc.window.visibleForTheFirstTime = &this.visibleForTheFirstTime;
_poc.window.redrawOpenGlScene = &this.redrawOpenGlScene;
}
private {
void visibleForTheFirstTime() {
//_poc.window.setAsCurrentOpenGlContext();
// ↑-- reconfigure() does this, too.
// |-- Uncomment if this functions does something else in the future.
this.reconfigure();
}
void setupTexture() {
if (_texture == 0) {
glGenTextures(1, &_texture);
}
glBindTexture(GL_TEXTURE_2D, _texture);
final switch (_poc.config.renderer.filter) with (ScalingFilter) {
case nearest:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case linear:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA8,
_poc.config.renderer.resolution.width,
_poc.config.renderer.resolution.height,
0,
GL_RGBA, GL_UNSIGNED_BYTE,
null
);
glBindTexture(GL_TEXTURE_2D, 0);
}
void setupMatrix() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(
0, _poc.config.renderer.resolution.width,
_poc.config.renderer.resolution.height, 0,
-1, 1
);
//glMatrixMode(GL_MODELVIEW);
}
void redrawOpenGlScene() {
glClearColor(
_poc.config.renderer.background.r,
_poc.config.renderer.background.g,
_poc.config.renderer.background.b,
_poc.config.renderer.background.a,
);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, _texture);
glEnable(GL_TEXTURE_2D);
{
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0, 0,
_poc.config.renderer.resolution.width, _poc.config.renderer.resolution.height,
GL_RGBA, GL_UNSIGNED_BYTE,
castTo!(void*)(_poc.framebuffer.data.ptr)
);
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
glVertex2i(0, 0);
glTexCoord2f(0, 1);
glVertex2i(0, _poc.config.renderer.resolution.height);
glTexCoord2f(1, 1);
glVertex2i(_poc.config.renderer.resolution.width, _poc.config.renderer.resolution.height);
glTexCoord2f(1, 0);
glVertex2i(_poc.config.renderer.resolution.width, 0);
}
glEnd();
}
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
public void reconfigure() {
_poc.window.setAsCurrentOpenGlContext();
const Viewport viewport = calculateViewport(_poc.config);
glViewportPMP(viewport);
this.setupTexture();
this.setupMatrix();
}
public void redrawSchedule() {
_poc.window.redrawOpenGlSceneSoon();
}
public void redrawNow() {
_poc.window.redrawOpenGlSceneNow();
}
}
///
struct LoopCtrl {
int interval; /// in milliseconds
bool redraw; ///
///
@disable this();
@safe pure nothrow @nogc:
private this(int interval, bool redraw) {
this.interval = interval;
this.redraw = redraw;
}
///
static LoopCtrl waitFor(int intervalMS) {
return LoopCtrl(intervalMS, false);
}
///
static LoopCtrl redrawIn(int intervalMS) {
return LoopCtrl(intervalMS, true);
}
}
/++
Pixmap Presenter window
A high-level window class that displays fully-rendered frames in the form of [Pixmap|Pixmaps].
The pixmap will be centered and (optionally) scaled.
+/
final class PixmapPresenter {
private {
PresenterObjectsContainer* _poc;
PixmapRenderer _renderer;
static if (hasTimer) {
Timer _timer;
}
WindowResizedCallback _onWindowResize;
}
// ctors
public {
///
this(const PresenterConfig config, bool useOpenGl = true) {
if (useOpenGl) {
this(config, new OpenGl3PixmapRenderer());
} else {
assert(false, "Not implemented");
}
}
///
this(const PresenterConfig config, PixmapRenderer renderer) {
_renderer = renderer;
// create software framebuffer
auto framebuffer = Pixmap.makeNew(config.renderer.resolution);
// OpenGL?
auto openGlOptions = OpenGlOptions.no;
const openGl = _renderer.wantsOpenGl;
if (openGl.wanted) {
setOpenGLContextVersion(openGl.vMaj, openGl.vMin);
openGLContextCompatible = openGl.compat;
openGlOptions = OpenGlOptions.yes;
}
// spawn window
auto window = new SimpleWindow(
config.window.size,
config.window.title,
openGlOptions,
Resizability.allowResizing,
);
window.windowResized = &this.windowResized;
window.cornerStyle = config.window.corners;
// alloc objects
_poc = new PresenterObjectsContainer(
framebuffer,
window,
config,
);
_renderer.setup(_poc);
}
}
// additional convenience ctors
public {
///
this(
string title,
const Size resolution,
const Size initialWindowSize,
Scaling scaling = Scaling.contain,
ScalingFilter filter = ScalingFilter.nearest,
) {
auto cfg = PresenterConfig();
cfg.window.title = title;
cfg.renderer.resolution = resolution;
cfg.window.size = initialWindowSize;
cfg.renderer.scaling = scaling;
cfg.renderer.filter = filter;
this(cfg);
}
///
this(
string title,
const Size resolution,
Scaling scaling = Scaling.contain,
ScalingFilter filter = ScalingFilter.nearest,
) {
this(title, resolution, resolution, scaling, filter,);
}
}
// public functions
public {
/++
Runs the event loop (with a pulse timer)
A redraw will be scheduled automatically each pulse.
+/
int eventLoop(T...)(long pulseTimeout, void delegate() onPulse, T eventHandlers) {
// run event-loop with pulse timer
return _poc.window.eventLoop(
pulseTimeout,
delegate() { onPulse(); this.scheduleRedraw(); },
eventHandlers,
);
}
//dfmt off
/++
Runs the event loop
Redraws have to manually scheduled through [scheduleRedraw] when using this overload.
+/
int eventLoop(T...)(T eventHandlers) if (
(T.length == 0) || (is(T[0] == delegate) && !is(typeof(() { return T[0](); }()) == LoopCtrl))
) {
return _poc.window.eventLoop(eventHandlers);