shader renamed
[dd2d.git] / render.d
bloba1a160606b9f1d38b777e57272d081a07b899931
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 render is aliced;
20 //version = dont_use_vsync;
22 private:
23 import core.atomic;
24 import core.thread;
25 import core.time;
27 import std.concurrency;
29 import iv.glbinds;
30 import glutils;
31 import console;
32 import wadarc;
34 import iv.stream;
36 import d2dmap;
37 import d2dadefs;
38 //import d2dactors;
39 import d2dgfx;
40 import d2dfont;
41 import dacs;
43 import d2dunigrid;
45 // `map` is there
46 import dengapi;
48 import d2dparts;
51 // ////////////////////////////////////////////////////////////////////////// //
52 import arsd.color;
53 import arsd.png;
56 // ////////////////////////////////////////////////////////////////////////// //
57 public __gshared bool cheatNoDoors = false;
58 public __gshared bool cheatNoWallClip = false;
61 // ////////////////////////////////////////////////////////////////////////// //
62 public __gshared SimpleWindow sdwindow;
65 public enum vlWidth = 800;
66 public enum vlHeight = 800;
67 __gshared int scale = 2;
69 public int getScale () nothrow @trusted @nogc { pragma(inline, true); return scale; }
72 // ////////////////////////////////////////////////////////////////////////// //
73 __gshared bool levelLoaded = false;
76 // ////////////////////////////////////////////////////////////////////////// //
77 __gshared bool scanlines = false;
78 __gshared bool doLighting = true;
79 __gshared bool gamePaused = false;
82 // ////////////////////////////////////////////////////////////////////////// //
83 // interpolation
84 __gshared ubyte[] prevFrameActorsData;
85 __gshared uint[65536] prevFrameActorOfs; // uint.max-1: dead; uint.max: last
86 __gshared MonoTime lastthink = MonoTime.zero; // for interpolator
87 __gshared MonoTime nextthink = MonoTime.zero;
88 __gshared bool frameInterpolation = true;
91 // ////////////////////////////////////////////////////////////////////////// //
92 // attached lights
93 struct AttachedLightInfo {
94 enum Type {
95 Point,
96 Ambient,
98 Type type;
99 int x, y;
100 int w, h; // for ambient lights
101 float r, g, b;
102 bool uncolored;
103 int radius;
106 __gshared AttachedLightInfo[65536] attachedLights;
107 __gshared uint attachedLightCount = 0;
110 // ////////////////////////////////////////////////////////////////////////// //
111 enum MaxLightRadius = 255;
114 // ////////////////////////////////////////////////////////////////////////// //
115 // for light
116 __gshared FBO[MaxLightRadius+1] fboDistMap;
117 __gshared FBO fboOccluders;
118 __gshared Shader shadToPolar, shadBlur, shadBlurOcc, shadAmbient;
120 __gshared FBO fboLevel, fboLevelLight, fboOrigBack, fboLMaskSmall;
121 __gshared Shader shadScanlines;
122 __gshared Shader shadLiquidDistort;
125 // ////////////////////////////////////////////////////////////////////////// //
126 // call once!
127 public void initOpenGL () {
128 gloStackClear();
130 glEnable(GL_TEXTURE_2D);
131 glDisable(GL_LIGHTING);
132 glDisable(GL_DITHER);
133 glDisable(GL_BLEND);
134 glDisable(GL_DEPTH_TEST);
136 // create shaders
137 shadScanlines = new Shader("scanlines", loadTextFile("shaders/srscanlines.frag"));
139 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("shaders/srliquid_distort.frag"));
140 shadLiquidDistort.exec((Shader shad) {
141 shad["texLqMap"] = 0;
144 // lights
145 shadToPolar = new Shader("light_topolar", loadTextFile("shaders/srlight_trace.frag"));
146 shadToPolar.exec((Shader shad) {
147 shad["texOcc"] = 0;
148 shad["texOccFull"] = 2;
151 shadBlur = new Shader("light_blur", loadTextFile("shaders/srlight_blur.frag"));
152 shadBlur.exec((Shader shad) {
153 shad["texDist"] = 0;
154 shad["texBg"] = 1;
155 shad["texOcc"] = 2;
156 shad["texOccSmall"] = 3;
159 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("shaders/srlight_blur_occ.frag"));
160 shadBlurOcc.exec((Shader shad) {
161 shad["texLMap"] = 0;
162 shad["texBg"] = 1;
163 shad["texOcc"] = 2;
164 shad["texOccSmall"] = 3;
167 shadAmbient = new Shader("light_ambient", loadTextFile("shaders/srlight_ambient.frag"));
168 shadAmbient.exec((Shader shad) {
169 shad["texBg"] = 1;
170 shad["texOcc"] = 2;
171 shad["texOccSmall"] = 3;
174 fboOccluders = new FBO(MaxLightRadius*2, MaxLightRadius*2, Texture.Option.Clamp, Texture.Option.Linear);
175 //TODO: this sux!
176 foreach (int sz; 2..MaxLightRadius+1) {
177 fboDistMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp, Texture.Option.Linear); // create 1d distance map FBO
180 // setup matrices
181 glMatrixMode(GL_MODELVIEW);
182 glLoadIdentity();
184 loadSmFont();
185 loadAllMonsterGraphics();
189 // ////////////////////////////////////////////////////////////////////////// //
190 // should be called when OpenGL is initialized
191 void loadMap (string mapname) {
192 mapscripts.runUnloading(); // "map unloading" script
193 clearMapScripts();
195 if (map !is null) map.clear();
196 map = new LevelMap(mapname);
197 curmapname = mapname;
199 ugInit(map.width*8, map.height*8);
201 map.oglBuildMega();
202 mapTilesChanged = 0;
204 if (fboLevel !is null) fboLevel.clear();
205 if (fboLevelLight !is null) fboLevelLight.clear();
206 if (fboOrigBack !is null) fboOrigBack.clear();
207 if (fboLMaskSmall !is null) fboLMaskSmall.clear();
209 fboLevel = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // final level render will be here
210 fboLevelLight = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level lights will be rendered here
211 fboOrigBack = new FBO(map.width*8, map.height*8, Texture.Option.Nearest/*, Texture.Option.Depth*/); // background+foreground
212 fboLMaskSmall = new FBO(map.width, map.height, Texture.Option.Nearest); // small lightmask
214 shadToPolar.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8-1, map.height*8-1); });
215 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
216 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
217 shadAmbient.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
219 glActiveTexture(GL_TEXTURE0+0);
220 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
221 orthoCamera(vlWidth, vlHeight);
223 Actor.resetStorage();
225 setupMapScripts();
226 mapscripts.runInit();
227 loadMapMonsters();
228 dotInit();
229 mapscripts.runLoaded();
231 // save first snapshot
232 if (prevFrameActorsData.length == 0) prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
233 prevFrameActorOfs[] = uint.max; // just for fun
234 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
236 levelLoaded = true;
238 { import core.memory : GC; GC.collect(); }
242 // ////////////////////////////////////////////////////////////////////////// //
243 //FIXME: optimize!
244 __gshared uint mapTilesChanged = 0;
247 //WARNING! this can be called only from DACS, so we don't have to sync it!
248 public void mapDirty (uint layermask) { mapTilesChanged |= layermask; }
251 void rebuildMapMegaTextures () {
252 //fbo.replaceTexture
253 //mapTilesChanged = false;
254 //map.clearMegaTextures();
255 map.oglBuildMega(mapTilesChanged);
256 mapTilesChanged = 0;
260 // ////////////////////////////////////////////////////////////////////////// //
261 // messages
262 struct Message {
263 enum Phase { FadeIn, Stay, FadeOut }
264 Phase phase;
265 int alpha;
266 int pauseMsecs;
267 MonoTime removeTime;
268 char[256] text;
269 usize textlen;
272 private import core.sync.mutex : Mutex;
274 __gshared Message[128] messages;
275 __gshared uint messagesUsed = 0;
277 //__gshared Mutex messageLock;
278 //shared static this () { messageLock = new Mutex(); }
281 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
282 //messageLock.lock();
283 //scope(exit) messageLock.unlock();
284 if (msgtext.length == 0) return;
285 conwriteln(msgtext);
286 if (pauseMsecs <= 50) return;
287 if (messagesUsed == messages.length) {
288 // remove top message
289 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
290 messages.ptr[0].alpha = 255;
291 --messagesUsed;
293 // quick replace
294 if (!noreplace && messagesUsed == 1) {
295 switch (messages.ptr[0].phase) {
296 case Message.Phase.FadeIn:
297 messages.ptr[0].phase = Message.Phase.FadeOut;
298 break;
299 case Message.Phase.Stay:
300 messages.ptr[0].phase = Message.Phase.FadeOut;
301 messages.ptr[0].alpha = 255;
302 break;
303 default:
306 auto msg = messages.ptr+messagesUsed;
307 ++messagesUsed;
308 msg.phase = Message.Phase.FadeIn;
309 msg.alpha = 0;
310 msg.pauseMsecs = pauseMsecs;
311 // copy text
312 if (msgtext.length > msg.text.length) {
313 msg.text = msgtext[0..msg.text.length];
314 msg.textlen = msg.text.length;
315 } else {
316 msg.text[0..msgtext.length] = msgtext[];
317 msg.textlen = msgtext.length;
322 void doMessages (MonoTime curtime) {
323 //messageLock.lock();
324 //scope(exit) messageLock.unlock();
326 if (messagesUsed == 0) return;
327 glEnable(GL_BLEND);
328 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
330 Message* msg;
332 again:
333 msg = messages.ptr;
334 final switch (msg.phase) {
335 case Message.Phase.FadeIn:
336 if ((msg.alpha += 10) >= 255) {
337 msg.phase = Message.Phase.Stay;
338 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
339 goto case; // to stay
341 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
342 break;
343 case Message.Phase.Stay:
344 if (msg.removeTime <= curtime) {
345 msg.alpha = 255;
346 msg.phase = Message.Phase.FadeOut;
347 goto case; // to fade
349 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
350 break;
351 case Message.Phase.FadeOut:
352 if ((msg.alpha -= 10) <= 0) {
353 if (--messagesUsed == 0) return;
354 // remove this message
355 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
356 goto again;
358 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
359 break;
362 smDrawText(10, 10, msg.text[0..msg.textlen]);
366 // ////////////////////////////////////////////////////////////////////////// //
367 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
369 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
370 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
371 mixin(Actor.FieldGetMixin!("x", int));
372 mixin(Actor.FieldGetMixin!("y", int));
373 mixin(Actor.FieldGetMixin!("radius", int));
374 mixin(Actor.FieldGetMixin!("height", int));
375 mixin(Actor.FieldGetMixin!("flags", uint));
376 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
377 mixin(Actor.FieldGetMixin!("zAnimidx", int));
378 mixin(Actor.FieldGetMixin!("dir", uint));
379 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
380 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
381 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
383 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
384 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
385 mixin(Actor.FieldGetPtrMixin!("x", int));
386 mixin(Actor.FieldGetPtrMixin!("y", int));
387 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
388 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
389 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
390 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
391 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
392 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
393 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
396 // ////////////////////////////////////////////////////////////////////////// //
397 __gshared int vportX0, vportY0, vportX1, vportY1;
400 // ////////////////////////////////////////////////////////////////////////// //
401 void renderLightAmbient() (int lightX, int lightY, int lightW, int lightH, in auto ref SVec4F lcol) {
402 //conwriteln("!!!000: (", lightX, ",", lightY, ")-(", lightW, ",", lightH, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
403 if (lightW < 1 || lightH < 1) return;
404 int lightX1 = lightX+lightW-1;
405 int lightY1 = lightY+lightH-1;
406 // clip light to viewport
407 if (lightX < vportX0) lightX = vportX0;
408 if (lightY < vportY0) lightY = vportY0;
409 if (lightX1 > vportX1) lightX1 = vportX1;
410 if (lightY1 > vportY1) lightY1 = vportY1;
411 // is this light visible?
412 //conwriteln("!!!001: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
413 if (lightX1 < lightX || lightY1 < lightY || lightX > vportX1 || lightY > vportY1 || lightX1 < vportX0 || lightY1 < vportY0) return;
414 //conwriteln("!!!002: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
416 fboLevelLight.exec({
417 glEnable(GL_BLEND);
418 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
419 //glDisable(GL_BLEND);
420 orthoCamera(map.width*8, map.height*8);
421 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
422 shadAmbient.exec((Shader shad) {
423 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
424 //shad["lightPos"] = SVec2F(lightX, lightY);
425 glRectf(lightX, lightY, lightX1, lightY1);
431 // ////////////////////////////////////////////////////////////////////////// //
432 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
433 if (lightRadius < 2) return;
434 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
435 int lightSize = lightRadius*2;
436 // is this light visible?
437 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*8 || lightY-lightRadius >= map.height*8) return;
439 // out of viewport -- do nothing
440 if (lightX+lightRadius < vportX0 || lightY+lightRadius < vportY0) return;
441 if (lightX-lightRadius > vportX1 || lightY-lightRadius > vportY1) return;
443 if (lightX >= 0 && lightY >= 0 && lightX < map.width*8 && lightY < map.height*8 &&
444 map.teximgs[map.LightMask].imageData.colors.ptr[lightY*(map.width*8)+lightX].a > 190) return;
446 // common color for all the following
447 glDisable(GL_BLEND);
448 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
450 // build 1d distance map to fboShadowMapId
451 fboDistMap.ptr[lightRadius].exec({
452 // no need to clear it, shader will take care of that
453 shadToPolar.exec((Shader shad) {
454 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
455 shad["lightPos"] = SVec2F(lightX, lightY);
456 orthoCamera(lightSize, 1);
457 // it doesn't matter what we will draw here, so just draw filled rect
458 glRectf(0, 0, lightSize, 1);
462 // build light texture for blending
463 fboOccluders.exec({
464 // no need to clear it, shader will take care of that
465 // debug
466 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
467 //glClear(GL_COLOR_BUFFER_BIT);
468 shadBlur.exec((Shader shad) {
469 shad["lightTexSize"] = SVec2F(lightSize, MaxLightRadius*2); // x: size of distmap; y: size of this texture
470 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
471 shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
472 orthoCamera(fboOccluders.tex.width, fboOccluders.tex.height);
473 //drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
474 glBindTexture(GL_TEXTURE_2D, fboDistMap.ptr[lightRadius].tex.tid);
475 glBegin(GL_QUADS);
476 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, 0); // top-left
477 glTexCoord2f(1.0f, 0.0f); glVertex2i(lightSize, 0); // top-right
478 glTexCoord2f(1.0f, 1.0f); glVertex2i(lightSize, lightSize); // bottom-right
479 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, lightSize); // bottom-left
480 glEnd();
484 // blend light texture
485 fboLevelLight.exec({
486 glEnable(GL_BLEND);
487 //glDisable(GL_BLEND);
488 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
489 orthoCamera(fboLevelLight.tex.width, fboLevelLight.tex.height);
490 //drawAtXY(fboOccluders.tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
491 float occe = 1.0f*lightSize/(MaxLightRadius*2);
492 float occs = 1.0f-occe;
493 int x0 = lightX-lightRadius+0;
494 int y1 = lightY-lightRadius+0;
495 int x1 = lightX+lightRadius-1+1;
496 int y0 = lightY+lightRadius-1+1;
497 glBindTexture(GL_TEXTURE_2D, fboOccluders.tex.tid);
498 glBegin(GL_QUADS);
500 glTexCoord2f(0.0f, 0.0f); glVertex2i(x0, y0); // top-left
501 glTexCoord2f(occe, 0.0f); glVertex2i(x1, y0); // top-right
502 glTexCoord2f(occe, occe); glVertex2i(x1, y1); // bottom-right
503 glTexCoord2f(0.0f, occe); glVertex2i(x0, y1); // bottom-left
505 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
506 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
507 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
508 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
509 glEnd();
511 glBindTexture(GL_TEXTURE_2D, 0);
512 glRectf(x0, y0, x1, y1);
514 // and blend it again, with the shader that will touch only occluders
515 shadBlurOcc.exec((Shader shad) {
516 //shad["lightTexSize"] = SVec2F(lightSize, lightSize);
517 shad["lightTexSize"] = SVec2F(lightSize, fboOccluders.tex.height);
518 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
519 shad["lightPos"] = SVec2F(lightX, lightY);
520 //shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
521 glBindTexture(GL_TEXTURE_2D, fboOccluders.tex.tid);
522 glBegin(GL_QUADS);
523 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
524 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
525 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
526 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
527 glEnd();
528 //drawAtXY(fboOccluders.tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
534 // ////////////////////////////////////////////////////////////////////////// //
535 __gshared int testLightX = vlWidth/2, testLightY = vlHeight/2;
536 __gshared bool testLightMoved = false;
537 //__gshared int mapOfsX, mapOfsY;
538 //__gshared bool movement = false;
539 __gshared float iLiquidTime = 0.0;
540 //__gshared bool altMove = false;
543 void renderScene (MonoTime curtime) {
544 //enum BackIntens = 0.05f;
545 enum BackIntens = 0.0f;
547 gloStackClear();
548 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
549 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
552 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
553 int curfp = cast(int)((curtime-lastthink).total!"msecs");
554 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
558 int mofsx, mofsy; // camera offset, will be set in background layer builder
560 if (mapTilesChanged != 0) rebuildMapMegaTextures();
562 dotDraw(atob);
564 // build background layer
565 fboOrigBack.exec({
566 //glDisable(GL_BLEND);
567 //glClearDepth(1.0f);
568 //glDepthFunc(GL_LESS);
569 //glDepthFunc(GL_NEVER);
570 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
571 glClear(GL_COLOR_BUFFER_BIT/*|GL_DEPTH_BUFFER_BIT*/);
572 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
573 orthoCamera(map.width*8, map.height*8);
575 glEnable(GL_BLEND);
576 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
577 // draw sky
579 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
580 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2, map.MapSize*8, map.MapSize*8);
581 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
582 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*8, map.MapSize*8);
584 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*8, map.MapSize*8);
585 // draw background
586 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
587 // draw distorted liquid areas
588 shadLiquidDistort.exec((Shader shad) {
589 shad["iDistortTime"] = iLiquidTime;
590 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
592 // monsters, items; we'll do linear interpolation here
593 glColor3f(1.0f, 1.0f, 1.0f);
594 //glEnable(GL_DEPTH_TEST);
595 attachedLightCount = 0;
597 // who cares about memory?!
598 // draw order: players, items, monsters, other
599 static struct DrawInfo {
600 ActorDef adef;
601 ActorId aid;
602 int actorX, actorY;
603 @disable this (this); // no copies
605 enum { Players, Items, Monsters, Other }
606 __gshared DrawInfo[65536][4] drawlists;
607 __gshared uint[4] dlpos;
608 DrawInfo camchickdi;
610 dlpos[] = 0;
612 Actor.forEach((ActorId me) {
613 //me.fprop_0drawlistpos = 0;
614 if (auto adef = findActorDef(me)) {
615 uint dlnum = Other;
616 switch (adef.classtype.get) {
617 case "monster": dlnum = (adef.classname.get != "Player" ? Monsters : Players); break;
618 case "item": dlnum = Items; break;
619 default: dlnum = Other; break;
621 int actorX, actorY; // current actor position
623 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
624 if (frameInterpolation && ofs < uint.max-1 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
625 import core.stdc.math : roundf;
626 auto xptr = prevFrameActorsData.ptr+ofs;
627 int ox = xptr.fgetp_x;
628 int nx = me.fget_x;
629 int oy = xptr.fgetp_y;
630 int ny = me.fget_y;
631 actorX = cast(int)(ox+roundf((nx-ox)*atob));
632 actorY = cast(int)(oy+roundf((ny-oy)*atob));
633 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
634 } else {
635 actorX = me.fget_x;
636 actorY = me.fget_y;
639 if (me.id == cameraChick.id) {
640 camchickdi.adef = adef;
641 camchickdi.aid = me;
642 camchickdi.actorX = actorX;
643 camchickdi.actorY = actorY;
645 // draw sprite
646 if ((me.fget_flags&AF_NODRAW) == 0) {
647 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
648 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
649 auto dl = drawlists.ptr[dlnum].ptr+dlpos.ptr[dlnum];
650 ++dlpos.ptr[dlnum];
651 dl.adef = adef;
652 dl.aid = me;
653 dl.actorX = actorX;
654 dl.actorY = actorY;
656 // process attached lights
657 if ((me.fget_flags&AF_NOLIGHT) == 0) {
658 uint alr = me.fget_attLightRGBX;
659 bool isambient = (me.fget_classtype.get == "light" && me.fget_classname.get == "Ambient");
660 if ((alr&0xff) >= 4 || (isambient && me.fget_radius >= 1 && me.fget_height >= 1)) {
661 //if (isambient) conwriteln("isambient: ", isambient, "; x=", me.fget_x, "; y=", me.fget_y, "; w=", me.fget_radius, "; h=", me.fget_height);
662 // yep, add it
663 auto li = attachedLights.ptr+attachedLightCount;
664 ++attachedLightCount;
665 li.type = (!isambient ? AttachedLightInfo.Type.Point : AttachedLightInfo.Type.Ambient);
666 li.x = actorX+me.fget_attLightXOfs;
667 li.y = actorY+me.fget_attLightYOfs;
668 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
669 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
670 li.uncolored = true;
671 } else {
672 li.g = ((alr>>16)&0xff)/255.0f;
673 li.b = ((alr>>8)&0xff)/255.0f;
674 li.uncolored = false;
676 li.radius = (alr&0xff);
677 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
678 if (isambient) {
679 li.w = me.fget_radius;
680 li.h = me.fget_height;
684 } else {
685 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
689 // draw actor lists
690 foreach_reverse (uint dlnum; 0..drawlists.length) {
691 auto dl = drawlists.ptr[dlnum].ptr;
692 if (dlnum == Players) dl += dlpos.ptr[dlnum]-1;
693 foreach (uint idx; 0..dlpos.ptr[dlnum]) {
694 auto me = dl.aid;
695 if (auto isp = dl.adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
696 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
697 isp.drawAtXY(dl.actorX, dl.actorY);
699 if (dlnum != Players) ++dl; else --dl;
703 // camera movement
704 if (/*altMove || movement ||*/ scale == 1 || !cameraChick.valid) {
705 mofsx = 0;
706 mofsy = 0;
707 vportX0 = 0;
708 vportY0 = 0;
709 vportX1 = map.width*8;
710 vportY1 = map.height*8;
711 } else {
712 int tiltHeight = /*getMapViewHeight()*/(vlHeight/scale)/4;
713 int vy = cameraChick.looky!int;
714 if (vy < -tiltHeight) vy = -tiltHeight; else if (vy > tiltHeight) vy = tiltHeight;
715 int swdt = vlWidth/scale;
716 int shgt = vlHeight/scale;
717 int x = camchickdi.actorX-swdt/2;
718 int y = (camchickdi.actorY+vy)-shgt/2;
719 if (x < 0) x = 0; else if (x >= map.width*8-swdt) x = map.width*8-swdt-1;
720 if (y < 0) y = 0; else if (y >= map.height*8-shgt) y = map.height*8-shgt-1;
721 mofsx = x*2;
722 mofsy = y*2;
723 vportX0 = mofsx/scale;
724 vportY0 = mofsy/scale;
725 vportX1 = vportX0+vlWidth/scale;
726 vportY1 = vportY0+vlHeight/scale;
729 //glDisable(GL_DEPTH_TEST);
730 // draw dots
731 drawAtXY(texParts, 0, 0);
732 // do liquid coloring
733 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
734 // foreground -- hide secrets, draw lifts and such
735 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
739 if (doLighting) {
740 // make smaller occluder texture, so we can trace faster
741 fboLMaskSmall.exec({
742 orthoCamera(map.width, map.height);
743 drawAtXY(map.texgl.ptr[map.LightMask].tid, 0, 0, map.width, map.height);
746 // clear light layer
747 fboLevelLight.exec({
748 glDisable(GL_BLEND);
749 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
750 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
751 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
752 glClear(GL_COLOR_BUFFER_BIT);
755 // texture 1 is background
756 glActiveTexture(GL_TEXTURE0+1);
757 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
758 // texture 2 is occluders
759 glActiveTexture(GL_TEXTURE0+2);
760 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
761 // texture 3 is small occluder map
762 glActiveTexture(GL_TEXTURE0+3);
763 glBindTexture(GL_TEXTURE_2D, fboLMaskSmall.tex.tid);
764 // done texture assign
765 glActiveTexture(GL_TEXTURE0+0);
768 enum LYOfs = 1;
770 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
771 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
772 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
773 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
774 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
775 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
776 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
777 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
778 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
779 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
781 renderLight(24*8+4, (24+18)*8-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
783 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
786 // attached lights
787 foreach (ref li; attachedLights[0..attachedLightCount]) {
788 if (li.type == AttachedLightInfo.Type.Ambient) {
789 //conwriteln("ambient: x=", li.x, "; y=", li.y, "; w=", li.w, "; h=", li.h);
790 // ambient light
791 if (li.uncolored) {
792 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(0.0f, 0.0f, 0.0f, li.r));
793 } else {
794 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(li.r, li.g, li.b, 1.0f));
796 } else if (li.type == AttachedLightInfo.Type.Point) {
797 // point light
798 if (li.uncolored) {
799 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
800 } else {
801 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
807 if (testLightMoved) {
808 testLightX = testLightX/scale+mofsx/scale;
809 testLightY = testLightY/scale+mofsy/scale;
810 testLightMoved = false;
812 foreach (immutable _; 0..1) {
813 renderLight(testLightX, testLightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
817 glActiveTexture(GL_TEXTURE0+1);
818 glBindTexture(GL_TEXTURE_2D, 0);
819 glActiveTexture(GL_TEXTURE0+2);
820 glBindTexture(GL_TEXTURE_2D, 0);
821 glActiveTexture(GL_TEXTURE0+0);
824 // draw scaled level
826 shadScanlines.exec((Shader shad) {
827 shad["scanlines"] = scanlines;
828 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
829 glClear(GL_COLOR_BUFFER_BIT);
830 orthoCamera(vlWidth, vlHeight);
831 //orthoCamera(map.width*8*scale, map.height*8*scale);
832 //glMatrixMode(GL_MODELVIEW);
833 //glLoadIdentity();
834 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
835 // somehow, FBO objects are mirrored; wtf?!
836 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
837 //glLoadIdentity();
842 fboLevelLight.exec({
843 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
848 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
849 glDisable(GL_BLEND);
852 fboOrigBack.exec({
853 //auto img = smfont.ptr[0x39];
854 auto img = fftest;
855 if (img !is null) {
856 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
857 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
864 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
865 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
866 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
867 glDrawBuffers(1, buffers.ptr);
872 orthoCamera(vlWidth, vlHeight);
873 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
874 //mofsx &= ~1;
875 //mofsy &= ~1;
876 //drawAtXY(tex, -mofsx, -mofsy, map.width*8*scale, map.height*8*scale, mirrorY:true);
877 //drawAtXY(map.texgl.ptr[map.LightMask].tid, -mofsx, -mofsy, map.width*8*scale, map.height*8*scale, mirrorY:true);
878 drawAtXY(fboLMaskSmall.tex.tid, 0, 0, map.width*8, map.height*8, mirrorY:true);
880 doMessages(curtime);
884 // ////////////////////////////////////////////////////////////////////////// //
885 // returns time slept
886 int sleepAtMaxMsecs (int msecs) {
887 if (msecs > 0) {
888 import core.sys.posix.signal : timespec;
889 import core.sys.posix.time : nanosleep;
890 timespec ts = void, tpassed = void;
891 ts.tv_sec = 0;
892 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
893 nanosleep(&ts, &tpassed);
894 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
895 } else {
896 return 0;
901 // ////////////////////////////////////////////////////////////////////////// //
902 // rendering thread
903 shared int diedie = 0;
905 enum D2DFrameTime = 55; // milliseconds
906 enum MinFrameTime = 1000/60; // ~60 FPS
908 public void renderThread (Tid starterTid) {
909 enum BoolOptVarMsgMixin(string varname) =
910 "if (msg.toggle) msg.value = !"~varname~";\n"~
911 "if ("~varname~" != msg.value) "~varname~" = msg.value; else msg.showMessage = false;\n";
913 send(starterTid, 42);
914 try {
915 MonoTime curtime = MonoTime.currTime;
917 lastthink = curtime; // for interpolator
918 nextthink = curtime+dur!"msecs"(D2DFrameTime);
919 MonoTime nextvframe = curtime;
921 enum MaxFPSFrames = 16;
922 float frtimes = 0.0f;
923 int framenum = 0;
924 int prevFPS = -1;
925 int hushFrames = 6; // ignore first `hushFrames` frames overtime
926 MonoTime prevFrameStartTime = curtime;
928 bool vframeWasLost = false;
930 void resetFrameTimers () {
931 MonoTime curtime = MonoTime.currTime;
932 lastthink = curtime; // for interpolator
933 nextthink = curtime+dur!"msecs"(D2DFrameTime);
934 nextvframe = curtime;
937 void loadNewLevel (string name) {
939 if (levelLoaded) {
940 conwriteln("ERROR: can't load new levels yet");
941 return;
944 if (name.length == 0) {
945 conwriteln("ERROR: can't load empty level!");
947 conwriteln("loading map '", name, "'");
948 loadMap(name);
949 resetFrameTimers();
952 void receiveMessages () {
953 for (;;) {
954 import core.time : Duration;
955 //conwriteln("rendering thread: waiting for messages...");
956 auto got = receiveTimeout(
957 Duration.zero, // don't wait
958 (TMsgMessage msg) {
959 addMessage(msg.text[0..msg.textlen], msg.pauseMsecs, msg.noreplace);
961 (TMsgLoadLevel msg) {
962 nextmapname = null; // clear "exit" flag
963 loadNewLevel(msg.mapfile[0..msg.textlen].idup);
965 (TMsgSkipLevel msg) {
966 string mn = genNextMapName(0);
967 if (mn.length) {
968 nextmapname = null; // clear "exit" flag
969 loadNewLevel(mn);
972 (TMsgIntOption msg) {
973 final switch (msg.type) with (TMsgIntOption.Type) {
974 case Scale:
975 if (msg.value >= 1 && msg.value <= 2) scale = msg.value;
976 break;
979 (TMsgBoolOption msg) {
980 final switch (msg.type) with (TMsgBoolOption.Type) {
981 case Interpolation: mixin(BoolOptVarMsgMixin!"frameInterpolation"); break;
982 case Lighting: mixin(BoolOptVarMsgMixin!"doLighting"); break;
983 case Pause: mixin(BoolOptVarMsgMixin!"gamePaused"); break;
984 case CheatNoDoors: mixin(BoolOptVarMsgMixin!"cheatNoDoors"); break;
985 case CheatNoWallClip: mixin(BoolOptVarMsgMixin!"cheatNoWallClip"); break;
987 if (msg.showMessage) {
988 char[128] mbuf;
989 uint msgpos;
990 void putStr(T) (T s) if (is(T : const(char)[])) {
991 foreach (char ch; s) {
992 if (msgpos >= mbuf.length) break;
993 mbuf.ptr[msgpos++] = ch;
996 putStr("Option \"");
997 { import std.conv : to; putStr(to!string(msg.type)); }
998 putStr("\": O");
999 if (msg.value) putStr("N"); else putStr("FF");
1000 addMessage(mbuf[0..msgpos]);
1003 (TMsgTestLightMove msg) {
1004 testLightX = msg.x;
1005 testLightY = msg.y;
1006 testLightMoved = true;
1008 (Variant v) {
1009 conwriteln("WARNING: unknown thread message received and ignored");
1012 if (!got) {
1013 // no more messages
1014 //conwriteln("rendering thread: no more messages");
1015 break;
1018 if (nextmapname.length) {
1019 string mn = nextmapname;
1020 nextmapname = null; // clear "exit" flag
1021 loadNewLevel(mn);
1025 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1026 bool doThinkFrame () {
1027 if (curtime >= nextthink) {
1028 lastthink = curtime;
1029 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
1030 if (levelLoaded && !gamePaused) {
1031 // save snapshot and other data for interpolator
1032 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
1033 // process actors
1034 doActorsThink();
1035 dotThink();
1037 // some timing
1038 auto tm = MonoTime.currTime;
1039 int thinkTime = cast(int)((tm-curtime).total!"msecs");
1040 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
1041 curtime = tm;
1042 return true;
1043 } else {
1044 return false;
1048 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1049 bool doVFrame () {
1050 version(dont_use_vsync) {
1051 // timer
1052 enum doCheckTime = true;
1053 } else {
1054 // vsync
1055 __gshared bool prevLost = false;
1056 bool doCheckTime = vframeWasLost;
1057 if (vframeWasLost) {
1058 if (!prevLost) {
1059 { import core.stdc.stdio; printf("frame was lost!\n"); }
1061 prevLost = true;
1062 } else {
1063 prevLost = false;
1066 if (doCheckTime) {
1067 if (curtime < nextvframe) return false;
1068 version(dont_use_vsync) {
1069 if (curtime > nextvframe) {
1070 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
1071 if (overtime > 2500) {
1072 if (hushFrames) {
1073 --hushFrames;
1074 } else {
1075 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
1081 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
1082 bool ctset = false;
1084 sdwindow.mtLock();
1085 scope(exit) sdwindow.mtUnlock();
1086 ctset = sdwindow.setAsCurrentOpenGlContextNT;
1088 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1089 if (ctset) {
1090 // render scene
1091 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
1092 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1093 if (levelLoaded) {
1094 renderScene(curtime);
1095 } else {
1096 //renderLoading(curtime);
1098 sdwindow.mtLock();
1099 scope(exit) sdwindow.mtUnlock();
1100 sdwindow.swapOpenGlBuffers();
1101 glFinish();
1102 sdwindow.releaseCurrentOpenGlContext();
1103 vframeWasLost = false;
1104 } else {
1105 vframeWasLost = true;
1106 { import core.stdc.stdio; printf("xframe was lost!\n"); }
1108 curtime = MonoTime.currTime;
1109 return true;
1112 for (;;) {
1113 if (sdwindow.closed) break;
1114 if (atomicLoad(diedie) > 0) break;
1116 curtime = MonoTime.currTime;
1117 auto fstime = curtime;
1119 doThinkFrame(); // this will fix curtime if necessary
1120 if (doVFrame()) {
1121 if (!vframeWasLost) {
1122 // fps
1123 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
1124 prevFrameStartTime = curtime;
1125 frtimes += frameTime;
1126 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
1127 import std.string : format;
1128 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
1129 if (newFPS != prevFPS) {
1130 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
1131 prevFPS = newFPS;
1133 framenum = 0;
1134 frtimes = 0.0f;
1139 curtime = MonoTime.currTime;
1141 // now sleep until next "video" or "think" frame
1142 if (nextthink > curtime && nextvframe > curtime) {
1143 // let's decide
1144 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
1145 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
1146 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
1147 sleepAtMaxMsecs(sleepTime);
1148 //curtime = MonoTime.currTime;
1151 } catch (Throwable e) {
1152 // here, we are dead and fucked (the exact order doesn't matter)
1153 import core.stdc.stdlib : abort;
1154 import core.stdc.stdio : fprintf, stderr;
1155 import core.memory : GC;
1156 GC.disable(); // yeah
1157 thread_suspendAll(); // stop right here, you criminal scum!
1158 auto s = e.toString();
1159 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
1160 abort(); // die, you bitch!
1162 import core.stdc.stdio;
1163 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1164 import std.stdio : stderr;
1165 writeln(
1166 for (;;) {
1167 if (sdwindow.closed) break;
1168 if (atomicLoad(diedie) > 0) break;
1169 sleepAtMaxMsecs(100);
1173 atomicStore(diedie, 2);
1177 // ////////////////////////////////////////////////////////////////////////// //
1178 __gshared Tid renderTid;
1179 shared bool renderThreadStarted = false;
1182 public void startRenderThread () {
1183 if (!cas(&renderThreadStarted, false, true)) {
1184 assert(0, "render thread already started!");
1186 renderTid = spawn(&renderThread, thisTid);
1187 setMaxMailboxSize(renderTid, 1024, OnCrowding.throwException); //FIXME
1188 // wait for "i'm ready" signal
1189 receive(
1190 (int ok) {
1191 if (ok != 42) assert(0, "wtf?!");
1194 conwriteln("rendering thread started");
1198 // ////////////////////////////////////////////////////////////////////////// //
1199 public void closeWindow () {
1200 if (atomicLoad(diedie) != 2) {
1201 atomicStore(diedie, 1);
1202 while (atomicLoad(diedie) != 2) {}
1204 if (!sdwindow.closed) {
1205 flushGui();
1206 sdwindow.close();
1211 // ////////////////////////////////////////////////////////////////////////// //
1212 // thread messages
1215 // ////////////////////////////////////////////////////////////////////////// //
1216 struct TMsgTestLightMove {
1217 int x, y;
1220 public void postTestLightMove (int x, int y) {
1221 if (!atomicLoad(renderThreadStarted)) return;
1222 auto msg = TMsgTestLightMove(x, y);
1223 send(renderTid, msg);
1227 // ////////////////////////////////////////////////////////////////////////// //
1228 struct TMsgMessage {
1229 char[256] text;
1230 uint textlen;
1231 int pauseMsecs;
1232 bool noreplace;
1235 public void postAddMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
1236 if (!atomicLoad(renderThreadStarted)) return;
1237 if (msgtext.length > TMsgMessage.text.length) msgtext = msgtext[0..TMsgMessage.text.length];
1238 TMsgMessage msg;
1239 msg.textlen = cast(uint)msgtext.length;
1240 if (msg.textlen) msg.text[0..msg.textlen] = msgtext[0..msg.textlen];
1241 msg.pauseMsecs = pauseMsecs;
1242 msg.noreplace = noreplace;
1243 send(renderTid, msg);
1247 // ////////////////////////////////////////////////////////////////////////// //
1248 struct TMsgLoadLevel {
1249 char[1024] mapfile;
1250 uint textlen;
1253 public void postLoadLevel (const(char)[] mapfile) {
1254 if (!atomicLoad(renderThreadStarted)) return;
1255 if (mapfile.length > TMsgLoadLevel.mapfile.length) mapfile = mapfile[0..TMsgLoadLevel.mapfile.length];
1256 TMsgLoadLevel msg;
1257 msg.textlen = cast(uint)mapfile.length;
1258 if (msg.textlen) msg.mapfile[0..msg.textlen] = mapfile[0..msg.textlen];
1259 send(renderTid, msg);
1263 // ////////////////////////////////////////////////////////////////////////// //
1264 struct TMsgSkipLevel {
1267 public void postSkipLevel () {
1268 if (!atomicLoad(renderThreadStarted)) return;
1269 TMsgSkipLevel msg;
1270 send(renderTid, msg);
1274 // ////////////////////////////////////////////////////////////////////////// //
1275 struct TMsgIntOption {
1276 enum Type {
1277 Scale,
1279 Type type;
1280 int value;
1281 bool showMessage;
1285 struct TMsgBoolOption {
1286 enum Type {
1287 Interpolation,
1288 Lighting,
1289 Pause,
1290 CheatNoDoors,
1291 CheatNoWallClip,
1293 Type type;
1294 bool value;
1295 bool toggle;
1296 bool showMessage;
1300 bool strCaseEqu (const(char)[] s0, const(char)[] s1) {
1301 if (s0.length != s1.length) return false;
1302 foreach (immutable idx, char ch; s0) {
1303 if (ch >= 'A' && ch <= 'Z') ch += 32;
1304 char c1 = s1.ptr[idx];
1305 if (c1 >= 'A' && c1 <= 'Z') c1 += 32;
1306 if (ch != c1) return false;
1308 return true;
1312 public bool postToggleOption (const(char)[] name, bool showMessage=false) { pragma(inline, true); return postSetOption(name, true, showMessage:showMessage, toggle:true); }
1314 public bool postSetOption(T) (const(char)[] name, T value, bool showMessage=false, bool toggle=false) if ((is(T == int) || is(T == bool))) {
1315 if (!atomicLoad(renderThreadStarted)) return false;
1316 if (name.length == 0 || name.length > 127) return false;
1317 static if (is(T == int)) {
1318 TMsgIntOption msg;
1319 foreach (string oname; __traits(allMembers, TMsgIntOption.Type)) {
1320 if (strCaseEqu(oname, name)) {
1321 msg.type = __traits(getMember, TMsgIntOption.Type, oname);
1322 msg.value = value;
1323 msg.showMessage = showMessage;
1324 send(renderTid, msg);
1325 return true;
1328 } else static if (is(T == bool)) {
1329 TMsgBoolOption msg;
1330 foreach (string oname; __traits(allMembers, TMsgBoolOption.Type)) {
1331 if (strCaseEqu(oname, name)) {
1332 msg.type = __traits(getMember, TMsgBoolOption.Type, oname);
1333 msg.value = value;
1334 msg.toggle = toggle;
1335 msg.showMessage = showMessage;
1336 send(renderTid, msg);
1337 return true;
1340 } else {
1341 static assert(0, "invalid option type '"~T.stringof~"'");
1343 return false;