1 /* DooM2D: Midnight on the Firing Line
2 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
3 * Understanding is not required. Only obedience.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 module glutils
is aliced
;
27 // ////////////////////////////////////////////////////////////////////////// //
28 __gshared
bool glutilsShowShaderWarnings
= false; // shut up!
31 __gshared GLuint glLastUsedTexture = 0;
33 public void useTexture (GLuint tid) {
35 if (glLastUsedTexture != tid) {
36 glLastUsedTexture = tid;
37 glBindTexture(GL_TEXTURE_2D, tid);
41 public void useTexture (Texture tex) { pragma(inline, true); useTexture(tex !is null ? tex.tid : 0); }
45 public TrueColorImage
loadPngFile (string fname
) {
46 auto fl
= openFile(fname
);
48 if (sz
< 4 || sz
> 32*1024*1024) throw new Exception("invalid png file size: '"~fname
~"'");
49 if (sz
== 0) return null;
50 auto res
= new ubyte[](cast(uint)sz
);
51 if (fl
.rawRead(res
[]).length
!= res
.length
) throw new Exception("error reading png file '"~fname
~"'");
52 return imageFromPng(readPng(res
)).getAsTrueColorImage
;
56 // ////////////////////////////////////////////////////////////////////////// //
58 abstract @property uint id () const pure nothrow @nogc;
60 final void activate () nothrow @nogc {
61 if (gloSP
>= gloStack
.length
) assert(0, "glo stack overflow");
62 gloStack
.ptr
[gloSP
++] = this;
66 final void deactivate () nothrow @nogc {
67 foreach_reverse (usize idx
; 0..gloStack
.length
) {
68 if (gloStack
.ptr
[idx
] is this) {
69 // find previous object of this type
70 foreach_reverse (usize pidx
; 0..idx
) {
71 if (typeid(gloStack
.ptr
[pidx
]) is typeid(gloStack
.ptr
[idx
])) {
72 gloStack
.ptr
[pidx
].activateObj();
73 removeFromStack(pidx
);
82 assert(0, "trying to deactivate inactive object");
86 abstract void activateObj () nothrow @nogc;
87 abstract void deactivateObj () nothrow @nogc;
91 __gshared OpenGLObject
[1024] gloStack
;
92 __gshared
uint gloSP
= 0;
95 public void gloStackClear () nothrow @nogc {
97 //glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
98 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
103 void removeFromStack (usize idx
) nothrow @nogc {
104 if (idx
>= gloSP
) return;
105 if (idx
!= gloSP
-1) {
106 import core
.stdc
.string
: memmove
;
107 memmove(gloStack
.ptr
+idx
, gloStack
.ptr
+idx
+1, (gloSP
-idx
-1)*gloStack
[0].sizeof
);
113 // ////////////////////////////////////////////////////////////////////////// //
114 public final class Texture
: OpenGLObject
{
118 override @property uint id () const pure nothrow @nogc => tid
;
120 // default: repeat, linear
128 Float
, // create floating point texture
129 Depth
, // FBO: attach depth buffer
132 this (string fname
, in Option
[] opts
...) { loadPng(fname
, opts
); }
133 this (int w
, int h
, in Option
[] opts
...) { createIntr(w
, h
, null, opts
); }
134 this (TrueColorImage aimg
, Option
[] opts
...) { createIntr(aimg
.width
, aimg
.height
, aimg
, opts
); }
135 ~this () { clear(); }
142 glDeleteTextures(1, &tid
);
151 private static void processOpt (GLuint
* wrapOpt
, GLuint
* filterOpt
, GLuint
* ttype
, in Option
[] opts
...) {
152 foreach (immutable opt
; opts
) {
153 switch (opt
) with (Option
) {
154 case Repeat
: *wrapOpt
= GL_REPEAT
; break;
155 case Clamp
: *wrapOpt
= GL_CLAMP_TO_EDGE
; break;
156 case ClampBorder
: *wrapOpt
= GL_CLAMP_TO_BORDER
; break;
157 case Linear
: *filterOpt
= GL_LINEAR
; break;
158 case Nearest
: *filterOpt
= GL_NEAREST
; break;
159 case UByte
: *ttype
= GL_UNSIGNED_BYTE
; break;
160 case Float
: *ttype
= GL_FLOAT
; break;
166 void createIntr (int w
, int h
, TrueColorImage img
, in Option
[] opts
...) {
167 import core
.stdc
.stdlib
: malloc
, free
;
172 GLuint wrapOpt
= GL_REPEAT
;
173 GLuint filterOpt
= GL_LINEAR
;
174 GLuint ttype
= GL_UNSIGNED_BYTE
;
175 processOpt(&wrapOpt
, &filterOpt
, &ttype
, opts
);
177 glGenTextures(1, &tid
);
179 auto oldtid
= boundTexture
;
181 scope(exit
) bindTexture(oldtid
);
182 glTexParameterf(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, wrapOpt
);
183 glTexParameterf(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, wrapOpt
);
184 glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, filterOpt
);
185 glTexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, filterOpt
);
186 //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
187 //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
188 GLfloat
[4] bclr
= 0.0;
189 glTexParameterfv(GL_TEXTURE_2D
, GL_TEXTURE_BORDER_COLOR
, bclr
.ptr
);
190 if (img
!is null && img
.width
== w
&& img
.height
== h
) {
191 // create straight from image
192 glTexImage2D(GL_TEXTURE_2D
, 0, (ttype
== GL_FLOAT ? GL_RGBA16F
: GL_RGBA
), w
, h
, 0, GL_RGBA
, GL_UNSIGNED_BYTE
, img
.imageData
.bytes
.ptr
);
194 // create empty texture
196 scope(exit
) if (ptr
!is null) free(ptr
);
198 import core
.stdc
.string
: memset
;
199 ptr
= cast(ubyte*)malloc(w
*h
*4);
200 if (ptr
!is null) memset(ptr
, 0, w
*h
*4);
202 glTexImage2D(GL_TEXTURE_2D
, 0, (ttype
== GL_FLOAT ? GL_RGBA16F
: GL_RGBA
), w
, h
, 0, GL_RGBA
, GL_UNSIGNED_BYTE
, ptr
);
203 if (img
!is null && img
.width
> 0 && img
.height
> 0) {
205 //TODO: dunno if it's ok to use images bigger than texture here
206 glTexSubImage2D(GL_TEXTURE_2D
, 0, 0, 0, img
.width
, img
.height
, GL_RGBA
, GL_UNSIGNED_BYTE
, img
.imageData
.bytes
.ptr
);
207 // the following is ok too
209 //glTextureSubImage2D(tid, 0, 0, 0, img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, img.imageData.bytes.ptr);
216 void setFromImage (TrueColorImage img
, int x
=0, int y
=0) {
217 if (img
is null ||
!tid || img
.height
< 1 || img
.width
< 1) return;
218 if (x
>= width || y
>= height
) return;
219 if (x
+img
.width
<= 0 || y
+img
.height
<= 0) return; //TODO: overflow
220 if (x
>= 0 && y
>= 0 && x
+img
.width
<= width
&& y
+img
.height
<= height
) {
221 // easy case, just copy it
222 glTextureSubImage2D(tid
, 0, x
, y
, img
.width
, img
.height
, GL_RGBA
, GL_UNSIGNED_BYTE
, img
.imageData
.bytes
.ptr
);
224 import core
.stdc
.stdlib
: malloc
, free
;
225 import core
.stdc
.string
: memset
, memcpy
;
226 // hard case, have to build the temp region
227 uint* src
= cast(uint*)img
.imageData
.bytes
.ptr
;
228 // calc x skip and effective width
229 int rwdt
= img
.width
;
232 src
-= x
; // as `x` is negative here
235 if (x
+rwdt
> width
) rwdt
= width
-x
;
236 // calc y skip and effective height
237 int rhgt
= img
.height
;
240 src
-= y
*img
.width
; // as `y` is negative here
243 if (y
+rhgt
> height
) rhgt
= height
-y
;
244 assert(rwdt
> 0 && rhgt
> 0);
246 scope(exit
) if (ptr
!is null) free(ptr
);
247 ptr
= cast(uint*)malloc(rwdt
*rhgt
*4);
248 if (ptr
is null) assert(0, "out of memory in `Texture.setFromImage()`");
251 foreach (immutable _
; 0..rhgt
) {
252 memcpy(d
, src
, rwdt
*4);
256 glTextureSubImage2D(tid
, 0, x
, y
, rwdt
, rhgt
, GL_RGBA
, GL_UNSIGNED_BYTE
, ptr
);
260 void loadPng (string fname
, in Option
[] opts
...) {
261 scope(failure
) clear
;
262 auto img
= loadPngFile(fname
);
263 createIntr(img
.width
, img
.height
, img
, opts
);
267 override void activateObj () nothrow @nogc { /*if (tid)*/ bindTexture(tid
); }
268 override void deactivateObj () nothrow @nogc { /*if (tid)*/ bindTexture(0); }
272 // ////////////////////////////////////////////////////////////////////////// //
273 public final class FBO
: OpenGLObject
{
279 //Texture.Option[] xopts;
281 override @property uint id () const pure nothrow @nogc => fbo
;
283 this (Texture atex
) { createWithTexture(atex
); }
285 this (int wdt
, int hgt
, Texture
.Option
[] opts
...) {
287 createWithTexture(new Texture(wdt
, hgt
, opts
), opts
);
291 //FIXME: this may be wrong, as texture may be already destroyed (and it's wrong too); we need refcount for textures
292 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_COLOR_ATTACHMENT0_EXT
, GL_TEXTURE_2D
, 0, 0);
293 glDeleteFramebuffersEXT(1, &fbo
);
300 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_COLOR_ATTACHMENT0_EXT
, GL_TEXTURE_2D
, 0, 0);
301 glDeleteFramebuffersEXT(1, &fbo
);
302 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_DEPTH_ATTACHMENT
, GL_TEXTURE_2D
, 0, 0);
303 glDeleteFramebuffersEXT(1, &fbo
);
306 if (tex
!is null) tex
.clear();
308 if (texdepth
!is null) texdepth
.clear();
313 override void activateObj () nothrow @nogc { /*if (fbo)*/ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, fbo
); }
314 override void deactivateObj () nothrow @nogc { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0); }
316 // this will deactivate current FBO!
318 void replaceTexture (Texture ntex) {
320 if (ntex !is null && ntex.tid == tex.tid) return;
322 if (ntex is null) return;
324 glGenFramebuffersEXT(1, &fbo);
325 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
326 scope(exit) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
328 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0);
329 glDeleteFramebuffersEXT(1, &fbo);
334 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex.tid, 0);
336 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
337 if (status != GL_FRAMEBUFFER_COMPLETE_EXT) assert(0, "framebuffer fucked!");
344 void createWithTexture (Texture atex
, Texture
.Option
[] opts
...) {
345 assert(atex
!is null && atex
.tid
);
348 glGenFramebuffersEXT(1, &fbo
);
349 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, fbo
);
350 scope(exit
) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
351 // attach 2D texture to this FBO
352 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT
, GL_COLOR_ATTACHMENT0_EXT
, GL_TEXTURE_2D
, tex
.tid
, 0);
353 // GL_COLOR_ATTACHMENT0_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_STENCIL_ATTACHMENT_EXT
355 void createDepth () {
357 glGenRenderbuffersEXT(1, &fboDepthId
);
358 glBindRenderbufferEXT(GL_RENDERBUFFER_EXT
, fboDepthId
);
359 glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT
, GL_DEPTH_COMPONENT
/*24*/, atex
.width
, atex
.height
);
360 // attach depth buffer to FBO
361 glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT
, GL_DEPTH_ATTACHMENT_EXT
, GL_RENDERBUFFER_EXT
, fboDepthId
);
362 // kill it (we don't need it anymore)
363 glDeleteRenderbuffersEXT(1, &fboDepthId
);
367 foreach (Texture.Option opt; opts) {
368 if (opt == Texture.Option.Depth) {
377 GLenum status
= glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT
);
378 if (status
!= GL_FRAMEBUFFER_COMPLETE_EXT
) assert(0, "framebuffer fucked!");
380 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
388 // ////////////////////////////////////////////////////////////////////////// //
389 public struct SVec2I
{ int x
, y
; }
390 public struct SVec3I
{ int x
, y
, z
; alias r
= x
; alias g
= y
; alias b
= z
; }
391 public struct SVec4I
{ int x
, y
, z
, w
; alias r
= x
; alias g
= y
; alias b
= z
; alias a
= w
; }
393 public struct SVec2F
{ float x
, y
; }
394 public struct SVec3F
{ float x
, y
, z
; alias r
= x
; alias g
= y
; alias b
= z
; }
395 public struct SVec4F
{ float x
, y
, z
, w
; alias r
= x
; alias g
= y
; alias b
= z
; alias a
= w
; }
398 public final class Shader
: OpenGLObject
{
403 override @property uint id () const pure nothrow @nogc => prg
;
405 this (string ashaderName
, const(char)[] src
) {
406 shaderName
= ashaderName
;
407 if (src
.length
> int.max
) {
408 import core
.stdc
.stdio
: printf
;
409 printf("shader '%.*s' code too long!", cast(uint)ashaderName
.length
, ashaderName
.ptr
);
412 auto shaderId
= glCreateShader(GL_FRAGMENT_SHADER
);
414 GLint slen
= cast(int)src
.length
;
415 glShaderSource(shaderId
, 1, &sptr
, &slen
);
416 glCompileShader(shaderId
);
418 glGetShaderiv(shaderId
, GL_COMPILE_STATUS
, &success
);
419 if (!success || glutilsShowShaderWarnings
) {
420 import core
.stdc
.stdio
: printf
;
421 import core
.stdc
.stdlib
: malloc
, free
;
423 glGetShaderiv(shaderId
, GL_INFO_LOG_LENGTH
, &logSize
);
425 auto logStrZ
= cast(GLchar
*)malloc(logSize
);
426 glGetShaderInfoLog(shaderId
, logSize
, null, logStrZ
);
427 printf("shader '%.*s' compilation messages:\n%s\n", cast(uint)ashaderName
.length
, ashaderName
.ptr
, logStrZ
);
431 if (!success
) assert(0);
432 prg
= glCreateProgram();
433 glAttachShader(prg
, shaderId
);
437 GLint
varId(NT
) (NT vname
) if (is(NT
== char[]) ||
is(NT
== const(char)[]) ||
is(NT
== immutable(char)[])) {
439 if (vname
.length
> 0 && vname
.length
<= 128) {
440 if (auto vi
= vname
in vars
) {
443 char[129] buf
= void;
444 buf
[0..vname
.length
] = vname
[];
445 buf
[vname
.length
] = 0;
446 id
= glGetUniformLocation(prg
, buf
.ptr
);
447 //{ import core.stdc.stdio; printf("[%.*s.%s]=%i\n", cast(uint)shaderName.length, shaderName.ptr, buf.ptr, id); }
448 static if (is(NT
== immutable(char)[])) {
449 vars
[vname
.idup
] = id
;
451 vars
[vname
.idup
] = id
;
454 import core
.stdc
.stdio
: printf
;
455 printf("shader '%.*s': unknown variable '%.*s'\n", cast(uint)shaderName
.length
, shaderName
.ptr
, cast(uint)vname
.length
, vname
.ptr
);
462 // get unified var id
463 GLint
opIndex(NT
) (NT vname
) if (is(NT
== char[]) ||
is(NT
== const(char)[]) ||
is(NT
== immutable(char)[])) {
464 auto id
= varId(vname
);
466 import core
.stdc
.stdio
: printf
;
467 printf("shader '%.*s': unknown variable '%.*s'\n", cast(uint)shaderName
.length
, shaderName
.ptr
, cast(uint)vname
.length
, vname
.ptr
);
473 private import std
.traits
;
474 void opIndexAssign(T
, NT
) (in auto ref T v
, NT vname
)
475 if (((isIntegral
!T
&& T
.sizeof
<= 4) ||
(isFloatingPoint
!T
&& T
.sizeof
== float.sizeof
) || isBoolean
!T ||
476 is(T
: SVec2I
) ||
is(T
: SVec3I
) ||
is(T
: SVec4I
) ||
477 is(T
: SVec2F
) ||
is(T
: SVec3F
) ||
is(T
: SVec4F
)) &&
478 (is(NT
== char[]) ||
is(NT
== const(char)[]) ||
is(NT
== immutable(char)[])))
480 auto id
= varId(vname
);
482 //{ import core.stdc.stdio; printf("setting '%.*s' (%d)\n", cast(uint)vname.length, vname.ptr, id); }
483 static if (isIntegral
!T || isBoolean
!T
) glUniform1i(id
, cast(int)v
);
484 else static if (isFloatingPoint
!T
) glUniform1f(id
, cast(float)v
);
485 else static if (is(SVec2I
: T
)) glUniform2i(id
, cast(int)v
.x
, cast(int)v
.y
);
486 else static if (is(SVec3I
: T
)) glUniform3i(id
, cast(int)v
.x
, cast(int)v
.y
, cast(int)v
.z
);
487 else static if (is(SVec4I
: T
)) glUniform4i(id
, cast(int)v
.x
, cast(int)v
.y
, cast(int)v
.z
, cast(int)v
.w
);
488 else static if (is(SVec2F
: T
)) glUniform2f(id
, cast(float)v
.x
, cast(float)v
.y
);
489 else static if (is(SVec3F
: T
)) glUniform3f(id
, cast(float)v
.x
, cast(float)v
.y
, cast(float)v
.z
);
490 else static if (is(SVec4F
: T
)) glUniform4f(id
, cast(float)v
.x
, cast(float)v
.y
, cast(float)v
.z
, cast(float)v
.w
);
491 else static assert(0, "wtf?!");
495 override void activateObj () nothrow @nogc { /*if (prg)*/ glUseProgram(prg
); }
496 override void deactivateObj () nothrow @nogc { glUseProgram(0); }
500 // ////////////////////////////////////////////////////////////////////////// //
501 //private import std.traits;
504 void exec(TO
) (TO obj
, scope void delegate () dg
) if (is(typeof(() { obj
.activate(); obj
.deactivate(); }))) {
506 scope(exit
) obj
.deactivate();
510 void exec(TO
, TG
) (TO obj
, scope TG dg
) if (is(typeof((TO obj
) { dg(obj
); })) && is(typeof(() { obj
.activate(); obj
.deactivate(); }))) {
512 scope(exit
) obj
.deactivate();
517 // ////////////////////////////////////////////////////////////////////////// //
518 void orthoCamera (int wdt
, int hgt
) {
519 glMatrixMode(GL_PROJECTION
); // for ortho camera
521 // left, right, bottom, top, near, far
522 //glOrtho(0, wdt, 0, hgt, -1, 1); // bottom-to-top
523 glOrtho(0, wdt
, hgt
, 0, -1, 1); // top-to-bottom
524 glViewport(0, 0, wdt
, hgt
);
526 //glTranslatef(-cx, -cy, 0.0f);
529 // origin is texture left top
530 void drawAtXY (GLuint tid
, int x
, int y
, int w
, int h
, bool mirrorX
=false, bool mirrorY
=false) {
531 if (!tid || w
< 1 || h
< 1) return;
534 if (mirrorX
) { int tmp
= x
; x
= w
; w
= tmp
; }
535 if (mirrorY
) { int tmp
= y
; y
= h
; h
= tmp
; }
538 glTexCoord2f(0.0f, 0.0f); glVertex2i(x
, y
); // top-left
539 glTexCoord2f(1.0f, 0.0f); glVertex2i(w
, y
); // top-right
540 glTexCoord2f(1.0f, 1.0f); glVertex2i(w
, h
); // bottom-right
541 glTexCoord2f(0.0f, 1.0f); glVertex2i(x
, h
); // bottom-left
546 // origin is texture center
547 void drawAtXYC (Texture tex
, int x
, int y
, bool mirrorX
=false, bool mirrorY
=false) {
548 if (tex
is null ||
!tex
.tid
) return;
551 drawAtXY(tex
.tid
, x
, y
, tex
.width
, tex
.height
, mirrorX
, mirrorY
);
555 // origin is texture left top
556 void drawAtXY (Texture tex
, int x
, int y
, bool mirrorX
=false, bool mirrorY
=false) {
557 if (tex
is null ||
!tex
.tid
) return;
558 drawAtXY(tex
.tid
, x
, y
, tex
.width
, tex
.height
, mirrorX
, mirrorY
);
562 private __gshared GLuint boundTexture
= 0;
564 // make sure that texture unit 0 is active!
565 void bindTexture (GLuint tid
) nothrow @trusted @nogc {
566 if (tid
!= boundTexture
) {
568 glBindTexture(GL_TEXTURE_2D
, tid
);