`convar` API
[dd2d.git] / render.d
blob5468edef64a8b24c1e03932c4b2a48ba8764df87
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.vfs.augs;
36 import d2dmap;
37 import d2dadefs;
38 import d2dimage;
39 import d2dfont;
40 import dacs;
42 import d2dunigrid;
44 // `map` is there
45 import dengapi;
47 import d2dparts;
50 // ////////////////////////////////////////////////////////////////////////// //
51 import arsd.color;
52 import arsd.png;
55 // ////////////////////////////////////////////////////////////////////////// //
56 public __gshared bool cheatNoDoors = false;
57 public __gshared bool cheatNoWallClip = false;
60 // ////////////////////////////////////////////////////////////////////////// //
61 public __gshared SimpleWindow sdwindow;
64 public enum vlWidth = 800;
65 public enum vlHeight = 800;
66 __gshared int scale = 2;
68 public int getScale () nothrow @trusted @nogc { pragma(inline, true); return scale; }
71 // ////////////////////////////////////////////////////////////////////////// //
72 __gshared bool levelLoaded = false;
75 // ////////////////////////////////////////////////////////////////////////// //
76 __gshared bool scanlines = false;
77 __gshared bool doLighting = true;
78 __gshared bool gamePaused = false;
79 __gshared bool rConsoleVisible = false;
80 __gshared int rConsoleHeight = 16*3;
81 shared bool editMode = false;
82 shared bool vquitRequested = false;
84 public @property bool inEditMode () nothrow @trusted @nogc { import core.atomic; return atomicLoad(editMode); }
85 @property void inEditMode (bool v) nothrow @trusted @nogc { import core.atomic; atomicStore(editMode, v); }
87 public @property bool quitRequested () nothrow @trusted @nogc { import core.atomic; return atomicLoad(vquitRequested); }
88 public @property bool conVisible () nothrow @trusted @nogc { return rConsoleVisible; }
91 // ////////////////////////////////////////////////////////////////////////// //
92 __gshared char[] concmdbuf;
93 __gshared uint concmdbufpos;
94 private import core.sync.mutex : Mutex;
95 shared static this () { concmdbuf.length = 65536; }
97 __gshared char[4096] concli = 0;
98 __gshared uint conclilen = 0;
100 __gshared char[4096][128] concmdhistory = void;
101 __gshared int conhisidx = -1;
102 shared static this () { foreach (ref hb; concmdhistory) hb[] = 0; }
104 __gshared int conskiplines = 0;
107 const(char)[] conhisAt (int idx) {
108 if (idx < 0 || idx >= concmdhistory.length) return null;
109 const(char)[] res = concmdhistory.ptr[idx][];
110 usize pos = 0;
111 while (pos < res.length && res.ptr[pos]) ++pos;
112 return res[0..pos];
116 int conhisFind (const(char)[] cmd) {
117 while (cmd.length && cmd[$-1] <= 32) cmd = cmd[0..$-1];
118 if (cmd.length > concmdhistory.ptr[0].length) cmd = cmd[0..concmdhistory.ptr[0].length];
119 if (cmd.length == 0) return -1;
120 foreach (int idx; 0..cast(int)concmdhistory.length) {
121 auto c = conhisAt(idx);
122 while (c.length > 0 && c[$-1] <= 32) c = c[0..$-1];
123 if (c == cmd) return idx;
125 return -1;
129 void conhisAdd (const(char)[] cmd) {
130 while (cmd.length && cmd[$-1] <= 32) cmd = cmd[0..$-1];
131 if (cmd.length > concmdhistory.ptr[0].length) cmd = cmd[0..concmdhistory.ptr[0].length];
132 if (cmd.length == 0) return;
133 auto idx = conhisFind(cmd);
134 if (idx >= 0) {
135 // remove command
136 foreach (immutable c; idx+1..concmdhistory.length) concmdhistory.ptr[c-1][] = concmdhistory.ptr[c][];
138 // make room
139 foreach (immutable c; 1..concmdhistory.length; reverse) concmdhistory.ptr[c][] = concmdhistory.ptr[c-1][];
140 concmdhistory.ptr[0][] = 0;
141 concmdhistory.ptr[0][0..cmd.length] = cmd[];
145 void concmdAdd (const(char)[] s) {
146 if (s.length) {
147 if (concmdbuf.length-concmdbufpos < s.length+1) {
148 concmdbuf.assumeSafeAppend.length += s.length-(concmdbuf.length-concmdbufpos)+512;
150 if (concmdbufpos > 0 && concmdbuf[concmdbufpos-1] != '\n') concmdbuf.ptr[concmdbufpos++] = '\n';
151 concmdbuf[concmdbufpos..concmdbufpos+s.length] = s[];
152 concmdbufpos += s.length;
156 // `null`: no more
157 void concmdDoAll () {
158 if (concmdbufpos == 0) return;
159 scope(exit) concmdbufpos = 0;
160 auto ebuf = concmdbufpos;
161 const(char)[] s = concmdbuf[0..concmdbufpos];
162 for (;;) {
163 while (s.length) {
164 auto cmd = conGetCommand(s);
165 if (cmd is null) break;
166 try {
167 conExecute(cmd);
168 } catch (Exception e) {
169 conwriteln("***ERROR: ", e.msg);
172 if (concmdbufpos <= ebuf) break;
173 s = concmdbuf[ebuf..concmdbufpos];
174 ebuf = concmdbufpos;
179 void concliChar (char ch) {
180 __gshared int prevWasEmptyAndTab = 0;
182 cbufLock();
183 scope(exit) cbufUnlock();
184 //conLastChange = 0;
186 // autocomplete
187 if (ch == 9) {
188 if (conclilen == 0) {
189 if (++prevWasEmptyAndTab < 2) return;
190 } else {
191 prevWasEmptyAndTab = 0;
193 if (conclilen > 0) {
194 string minPfx = null;
195 // find longest command
196 foreach (auto name; conByCommand) {
197 if (name.length >= conclilen && name.length > minPfx.length && name[0..conclilen] == concli[0..conclilen]) minPfx = name;
199 //conwriteln("longest command: [", minPfx, "]");
200 // find longest prefix
201 foreach (auto name; conByCommand) {
202 if (name.length < conclilen) continue;
203 if (name[0..conclilen] != concli[0..conclilen]) continue;
204 usize pos = 0;
205 while (pos < name.length && pos < minPfx.length && minPfx.ptr[pos] == name.ptr[pos]) ++pos;
206 if (pos < minPfx.length) minPfx = minPfx[0..pos];
208 if (minPfx.length > concli.length) minPfx = minPfx[0..concli.length];
209 //conwriteln("longest prefix : [", minPfx, "]");
210 if (minPfx.length >= conclilen) {
211 // wow!
212 bool doRet = (minPfx.length > conclilen);
213 conLastChange = 0;
214 concli[0..minPfx.length] = minPfx[];
215 conclilen = cast(uint)minPfx.length;
216 if (conclilen < concli.length && conHasCommand(minPfx)) {
217 concli.ptr[conclilen++] = ' ';
218 doRet = true;
220 if (doRet) return;
223 // nope, print all available commands
224 bool needDelimiter = true;
225 foreach (auto name; conByCommand) {
226 if (conclilen > 0) {
227 if (name.length < conclilen) continue;
228 if (name[0..conclilen] != concli[0..conclilen]) continue;
230 if (needDelimiter) { conwriteln("----------------"); needDelimiter = false; }
231 conwriteln(name);
233 return;
235 // process other keys
236 prevWasEmptyAndTab = 0;
237 // remove last char
238 if (ch == 8) {
239 if (conclilen > 0) { conLastChange = 0; --conclilen; }
240 return;
242 // execute command
243 if (ch == 13) {
244 if (conskiplines) { conskiplines = 0; conLastChange = 0; }
245 if (conclilen > 0) {
246 conLastChange = 0;
247 conhisidx = -1;
248 conhisAdd(concli[0..conclilen]);
249 concmdAdd(concli[0..conclilen]);
250 conclilen = 0;
252 return;
254 // ^Y
255 if (ch == 25) {
256 if (conclilen > 0) { conLastChange = 0; conclilen = 0; }
257 return;
259 // up
260 if (ch == '\x01') {
261 ++conhisidx;
262 auto cmd = conhisAt(conhisidx);
263 if (cmd.length == 0) {
264 --conhisidx;
265 } else {
266 concli[0..cmd.length] = cmd[];
267 conclilen = cast(uint)cmd.length;
268 conLastChange = 0;
270 return;
272 // down
273 if (ch == '\x02') {
274 --conhisidx;
275 auto cmd = conhisAt(conhisidx);
276 if (cmd.length == 0 && conhisidx < -1) {
277 ++conhisidx;
278 } else {
279 concli[0..cmd.length] = cmd[];
280 conclilen = cast(uint)cmd.length;
281 conLastChange = 0;
283 return;
285 // page up
286 if (ch == '\x03') {
287 int lnx = (rConsoleHeight-4)/conCharHeight-2;
288 if (lnx < 1) lnx = 1;
289 conskiplines += lnx;
290 conLastChange = 0;
291 return;
293 // page down
294 if (ch == '\x04') {
295 if (conskiplines > 0) {
296 int lnx = (rConsoleHeight-4)/conCharHeight-2;
297 if (lnx < 1) lnx = 1;
298 if ((conskiplines -= lnx) < 0) conskiplines = 0;
299 conLastChange = 0;
301 return;
303 // other
304 if (ch < ' ' || ch > 127) return;
305 if (ch == '`' && conclilen == 0) { concmd("r_console ona"); return; }
306 if (conclilen >= concli.length) return;
307 concli.ptr[conclilen++] = ch;
308 conLastChange = 0;
312 // ////////////////////////////////////////////////////////////////////////// //
313 shared static this () {
314 conRegVar!doLighting("r_lighting", "dynamic lighting");
315 conRegVar!gamePaused("g_pause", "pause game");
316 conRegVar!rConsoleVisible("r_console", "console visibility");
317 conRegVar!rConsoleHeight(16*3, vlHeight, "r_conheight");
318 rConsoleHeight = vlHeight-vlHeight/3;
319 rConsoleHeight = vlHeight/2;
320 conRegVar!frameInterpolation("r_interpolation", "interpolate camera and sprite movement");
321 conRegVar!scale(1, 2, "r_scale");
322 conRegFunc!({
323 cheatNoDoors = !cheatNoDoors;
324 if (cheatNoDoors) conwriteln("player ignores doors"); else conwriteln("player respects doors");
325 })("nodoorclip", "ignore doors");
326 conRegFunc!({
327 cheatNoWallClip = !cheatNoWallClip;
328 if (cheatNoWallClip) conwriteln("player ignores walls"); else conwriteln("player respects walls");
329 })("nowallclip", "ignore walls");
330 conRegFunc!({
331 import core.atomic;
332 atomicStore(vquitRequested, true);
333 })("quit", "quit game");
334 conRegFunc!((const(char)[] msg, int pauseMsecs=3000, bool noreplace=false) {
335 char[256] buf;
336 auto s = buf.conFormatStr(msg);
337 if (s.length) postAddMessage(s, pauseMsecs, noreplace);
338 })("hudmsg", "show hud message; hudmsg msg [pausemsecs [noreplace]]");
342 // ////////////////////////////////////////////////////////////////////////// //
343 // interpolation
344 __gshared ubyte[] prevFrameActorsData;
345 __gshared uint[65536] prevFrameActorOfs; // uint.max-1: dead; uint.max: last
346 __gshared MonoTime lastthink = MonoTime.zero; // for interpolator
347 __gshared MonoTime nextthink = MonoTime.zero;
348 __gshared bool frameInterpolation = true;
351 // ////////////////////////////////////////////////////////////////////////// //
352 // attached lights
353 struct AttachedLightInfo {
354 enum Type {
355 Point,
356 Ambient,
358 Type type;
359 int x, y;
360 int w, h; // for ambient lights
361 float r, g, b;
362 bool uncolored;
363 int radius;
366 __gshared AttachedLightInfo[65536] attachedLights;
367 __gshared uint attachedLightCount = 0;
370 // ////////////////////////////////////////////////////////////////////////// //
371 enum MaxLightRadius = 255;
374 // ////////////////////////////////////////////////////////////////////////// //
375 // for light
376 __gshared FBO[MaxLightRadius+1] fboDistMap;
377 __gshared FBO fboOccluders;
378 __gshared Shader shadToPolar, shadBlur, shadBlurOcc, shadAmbient;
379 __gshared TrueColorImage editorImg;
380 __gshared FBO fboEditor;
381 __gshared FBO fboConsole;
382 __gshared Texture texSigil;
384 __gshared FBO fboLevel, fboLevelLight, fboOrigBack, fboLMaskSmall;
385 __gshared Shader shadScanlines;
386 __gshared Shader shadLiquidDistort;
389 // ////////////////////////////////////////////////////////////////////////// //
390 // call once!
391 public void initOpenGL () {
392 gloStackClear();
394 glEnable(GL_TEXTURE_2D);
395 glDisable(GL_LIGHTING);
396 glDisable(GL_DITHER);
397 glDisable(GL_BLEND);
398 glDisable(GL_DEPTH_TEST);
400 // create shaders
401 shadScanlines = new Shader("scanlines", loadTextFile("shaders/srscanlines.frag"));
403 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("shaders/srliquid_distort.frag"));
404 shadLiquidDistort.exec((Shader shad) {
405 shad["texLqMap"] = 0;
408 // lights
409 shadToPolar = new Shader("light_trace", loadTextFile("shaders/srlight_trace.frag"));
410 shadToPolar.exec((Shader shad) {
411 shad["texOcc"] = 0;
412 shad["texOccFull"] = 2;
413 shad["texOccSmall"] = 3;
416 shadBlur = new Shader("light_blur", loadTextFile("shaders/srlight_blur.frag"));
417 shadBlur.exec((Shader shad) {
418 shad["texDist"] = 0;
419 shad["texBg"] = 1;
420 shad["texOcc"] = 2;
421 shad["texOccSmall"] = 3;
424 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("shaders/srlight_blur_occ.frag"));
425 shadBlurOcc.exec((Shader shad) {
426 shad["texLMap"] = 0;
427 shad["texBg"] = 1;
428 shad["texOcc"] = 2;
429 shad["texOccSmall"] = 3;
432 shadAmbient = new Shader("light_ambient", loadTextFile("shaders/srlight_ambient.frag"));
433 shadAmbient.exec((Shader shad) {
434 shad["texBg"] = 1;
435 shad["texOcc"] = 2;
436 shad["texOccSmall"] = 3;
439 fboOccluders = new FBO(MaxLightRadius*2, MaxLightRadius*2, Texture.Option.Clamp, Texture.Option.Linear);
440 //TODO: this sux!
441 foreach (int sz; 2..MaxLightRadius+1) {
442 fboDistMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp, Texture.Option.Linear); // create 1d distance map FBO
445 editorImg = new TrueColorImage(vlWidth, vlHeight);
446 editorImg.imageData.colors[] = Color(0, 0, 0, 0);
447 fboEditor = new FBO(vlWidth, vlHeight, Texture.Option.Nearest);
449 texSigil = new Texture("console/sigil_of_baphomet.png", Texture.Option.Nearest);
450 fboConsole = new FBO(vlWidth, vlHeight, Texture.Option.Nearest);
451 loadConFont();
453 // setup matrices
454 glMatrixMode(GL_MODELVIEW);
455 glLoadIdentity();
457 loadSmFont();
458 loadBfFont();
459 loadAllMonsterGraphics();
463 // ////////////////////////////////////////////////////////////////////////// //
464 __gshared ulong conLastChange = 0;
466 void renderConsoleFBO () {
467 enum XOfs = 2;
468 if (conLastChange == cbufLastChange) return;
469 cbufLock();
470 scope(exit) cbufUnlock();
471 // rerender console
472 conLastChange = cbufLastChange;
473 //foreach (auto s; conbufLinesRev) stdout.writeln(s, "|");
474 int skipLines = conskiplines;
475 fboConsole.exec((FBO me) {
476 bindTexture(0);
477 orthoCamera(me.width, me.height);
478 // clear it
479 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
480 glClear(GL_COLOR_BUFFER_BIT);
482 glDisable(GL_BLEND);
483 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
484 glRectf(0, 0, me.width-1, me.height-1);
486 // text
487 glEnable(GL_BLEND);
488 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
489 // draw sigil
490 glColor4f(1.0f, 1.0f, 1.0f, 0.2f);
491 drawAtXY(texSigil, (me.width-texSigil.width)/2, (vlHeight-rConsoleHeight)/2+(me.height-texSigil.height)/2);
492 // draw command line
493 int y = me.height-conCharHeight-2;
495 glPushMatrix();
496 scope(exit) glPopMatrix();
497 glTranslatef(XOfs, y, 0);
498 int w = conCharWidth('>');
499 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
500 conDrawChar('>');
501 uint spos = conclilen;
502 while (spos > 0) {
503 char ch = concli.ptr[spos-1];
504 if (w+conCharWidth(ch) > me.width-XOfs*2-12) break;
505 w += conCharWidth(ch);
506 --spos;
508 glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
509 foreach (char ch; concli[spos..conclilen]) conDrawChar(ch);
510 // cursor
511 bindTexture(0);
512 glColor4f(1.0f, 0.5f, 0.0f, 1.0f);
513 glRectf(0, 0, 12, 16);
514 y -= conCharHeight;
516 // draw console text
517 glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
518 glPushMatrix();
519 scope(exit) glPopMatrix();
520 glTranslatef(XOfs, y, 0);
522 void putLine(T) (auto ref T line, usize pos=0) {
523 if (y+conCharHeight <= 0) return;
524 int w = XOfs;
525 usize sp = pos;
526 while (sp < line.length) {
527 char ch = line[sp++];
528 int cw = conCharWidth(ch);
529 if ((w += cw) > me.width-XOfs) { w -= cw; --sp; break; }
531 if (sp < line.length) putLine(line, sp); // recursive put tail
532 // draw line
533 if (skipLines-- <= 0) {
534 while (pos < sp) conDrawChar(line[pos++]);
535 glPopMatrix();
536 glPushMatrix();
537 y -= conCharHeight;
538 glTranslatef(XOfs, y, 0);
542 foreach (auto line; conbufLinesRev) {
543 putLine(line);
544 if (y+conCharHeight <= 0) break;
550 // ////////////////////////////////////////////////////////////////////////// //
551 // should be called when OpenGL is initialized
552 void loadMap (string mapname) {
553 mapscripts.runUnloading(); // "map unloading" script
554 clearMapScripts();
556 if (map !is null) map.clear();
557 map = new LevelMap(mapname);
558 curmapname = mapname;
560 ugInit(map.width*TileSize, map.height*TileSize);
562 map.oglBuildMega();
563 mapTilesChanged = 0;
565 if (fboLevel !is null) fboLevel.clear();
566 if (fboLevelLight !is null) fboLevelLight.clear();
567 if (fboOrigBack !is null) fboOrigBack.clear();
568 if (fboLMaskSmall !is null) fboLMaskSmall.clear();
570 fboLevel = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // final level render will be here
571 fboLevelLight = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // level lights will be rendered here
572 fboOrigBack = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest/*, Texture.Option.Depth*/); // background+foreground
573 fboLMaskSmall = new FBO(map.width, map.height, Texture.Option.Nearest); // small lightmask
575 shadToPolar.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize-1, map.height*TileSize-1); });
576 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
577 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
578 shadAmbient.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
580 glActiveTexture(GL_TEXTURE0+0);
581 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
582 orthoCamera(vlWidth, vlHeight);
584 Actor.resetStorage();
586 setupMapScripts();
587 mapscripts.runInit();
588 loadMapMonsters();
589 dotInit();
590 mapscripts.runLoaded();
592 // save first snapshot
593 if (prevFrameActorsData.length == 0) prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
594 prevFrameActorOfs[] = uint.max; // just for fun
595 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
597 levelLoaded = true;
599 { import core.memory : GC; GC.collect(); }
603 // ////////////////////////////////////////////////////////////////////////// //
604 //FIXME: optimize!
605 __gshared uint mapTilesChanged = 0;
608 //WARNING! this can be called only from DACS, so we don't have to sync it!
609 public void mapDirty (uint layermask) { mapTilesChanged |= layermask; }
612 void rebuildMapMegaTextures () {
613 //fbo.replaceTexture
614 //mapTilesChanged = false;
615 //map.clearMegaTextures();
616 map.oglBuildMega(mapTilesChanged);
617 mapTilesChanged = 0;
618 dotsAwake(); // let dormant dots fall
622 // ////////////////////////////////////////////////////////////////////////// //
623 // messages
624 struct Message {
625 enum Phase { FadeIn, Stay, FadeOut }
626 Phase phase;
627 int alpha;
628 int pauseMsecs;
629 MonoTime removeTime;
630 char[256] text;
631 usize textlen;
634 //private import core.sync.mutex : Mutex;
636 __gshared Message[128] messages;
637 __gshared uint messagesUsed = 0;
639 //__gshared Mutex messageLock;
640 //shared static this () { messageLock = new Mutex(); }
643 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
644 //messageLock.lock();
645 //scope(exit) messageLock.unlock();
646 if (msgtext.length == 0) return;
647 conwriteln(msgtext);
648 if (pauseMsecs <= 50) return;
649 if (messagesUsed == messages.length) {
650 // remove top message
651 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
652 messages.ptr[0].alpha = 255;
653 --messagesUsed;
655 // quick replace
656 if (!noreplace && messagesUsed == 1) {
657 switch (messages.ptr[0].phase) {
658 case Message.Phase.FadeIn:
659 messages.ptr[0].phase = Message.Phase.FadeOut;
660 break;
661 case Message.Phase.Stay:
662 messages.ptr[0].phase = Message.Phase.FadeOut;
663 messages.ptr[0].alpha = 255;
664 break;
665 default:
668 auto msg = messages.ptr+messagesUsed;
669 ++messagesUsed;
670 msg.phase = Message.Phase.FadeIn;
671 msg.alpha = 0;
672 msg.pauseMsecs = pauseMsecs;
673 // copy text
674 if (msgtext.length > msg.text.length) {
675 msg.text = msgtext[0..msg.text.length];
676 msg.textlen = msg.text.length;
677 } else {
678 msg.text[0..msgtext.length] = msgtext[];
679 msg.textlen = msgtext.length;
684 void doMessages (MonoTime curtime) {
685 //messageLock.lock();
686 //scope(exit) messageLock.unlock();
688 if (messagesUsed == 0) return;
689 glEnable(GL_BLEND);
690 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
692 Message* msg;
694 again:
695 msg = messages.ptr;
696 final switch (msg.phase) {
697 case Message.Phase.FadeIn:
698 if ((msg.alpha += 10) >= 255) {
699 msg.phase = Message.Phase.Stay;
700 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
701 goto case; // to stay
703 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
704 break;
705 case Message.Phase.Stay:
706 if (msg.removeTime <= curtime) {
707 msg.alpha = 255;
708 msg.phase = Message.Phase.FadeOut;
709 goto case; // to fade
711 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
712 break;
713 case Message.Phase.FadeOut:
714 if ((msg.alpha -= 10) <= 0) {
715 if (--messagesUsed == 0) return;
716 // remove this message
717 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
718 goto again;
720 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
721 break;
724 smDrawText(10, 10, msg.text[0..msg.textlen]);
728 // ////////////////////////////////////////////////////////////////////////// //
729 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
731 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
732 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
733 mixin(Actor.FieldGetMixin!("x", int));
734 mixin(Actor.FieldGetMixin!("y", int));
735 mixin(Actor.FieldGetMixin!("s", int));
736 mixin(Actor.FieldGetMixin!("radius", int));
737 mixin(Actor.FieldGetMixin!("height", int));
738 mixin(Actor.FieldGetMixin!("flags", uint));
739 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
740 mixin(Actor.FieldGetMixin!("zAnimidx", int));
741 mixin(Actor.FieldGetMixin!("dir", uint));
742 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
743 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
744 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
746 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
747 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
748 mixin(Actor.FieldGetPtrMixin!("x", int));
749 mixin(Actor.FieldGetPtrMixin!("y", int));
750 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
751 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
752 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
753 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
754 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
755 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
756 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
759 // ////////////////////////////////////////////////////////////////////////// //
760 __gshared int vportX0, vportY0, vportX1, vportY1;
763 // ////////////////////////////////////////////////////////////////////////// //
764 void renderLightAmbient() (int lightX, int lightY, int lightW, int lightH, in auto ref SVec4F lcol) {
765 //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));
766 if (lightW < 1 || lightH < 1) return;
767 int lightX1 = lightX+lightW-1;
768 int lightY1 = lightY+lightH-1;
769 // clip light to viewport
770 if (lightX < vportX0) lightX = vportX0;
771 if (lightY < vportY0) lightY = vportY0;
772 if (lightX1 > vportX1) lightX1 = vportX1;
773 if (lightY1 > vportY1) lightY1 = vportY1;
774 // is this light visible?
775 //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));
776 if (lightX1 < lightX || lightY1 < lightY || lightX > vportX1 || lightY > vportY1 || lightX1 < vportX0 || lightY1 < vportY0) return;
777 //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));
779 fboLevelLight.exec({
780 bindTexture(0);
781 glEnable(GL_BLEND);
782 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
783 //glDisable(GL_BLEND);
784 orthoCamera(map.width*TileSize, map.height*TileSize);
785 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
786 shadAmbient.exec((Shader shad) {
787 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
788 //shad["lightPos"] = SVec2F(lightX, lightY);
789 glRectf(lightX, lightY, lightX1, lightY1);
795 // ////////////////////////////////////////////////////////////////////////// //
796 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
797 if (lightRadius < 2) return;
798 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
799 int lightSize = lightRadius*2;
800 // is this light visible?
801 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*TileSize || lightY-lightRadius >= map.height*TileSize) return;
803 // out of viewport -- do nothing
804 if (lightX+lightRadius < vportX0 || lightY+lightRadius < vportY0) return;
805 if (lightX-lightRadius > vportX1 || lightY-lightRadius > vportY1) return;
807 if (lightX >= 0 && lightY >= 0 && lightX < map.width*TileSize && lightY < map.height*TileSize &&
808 map.teximgs[map.LightMask].imageData.colors.ptr[lightY*(map.width*TileSize)+lightX].a > 190) return;
810 // common color for all the following
811 glDisable(GL_BLEND);
812 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
814 // build 1d distance map to fboShadowMapId
815 fboDistMap.ptr[lightRadius].exec({
816 // no need to clear it, shader will take care of that
817 shadToPolar.exec((Shader shad) {
818 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
819 shad["lightPos"] = SVec2F(lightX, lightY);
820 orthoCamera(lightSize, 1);
821 // it doesn't matter what we will draw here, so just draw filled rect
822 glRectf(0, 0, lightSize, 1);
826 // build light texture for blending
827 fboOccluders.exec({
828 // no need to clear it, shader will take care of that
829 // debug
830 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
831 //glClear(GL_COLOR_BUFFER_BIT);
832 shadBlur.exec((Shader shad) {
833 shad["lightTexSize"] = SVec2F(lightSize, MaxLightRadius*2); // x: size of distmap; y: size of this texture
834 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
835 shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
836 orthoCamera(fboOccluders.tex.width, fboOccluders.tex.height);
837 //drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
838 bindTexture(fboDistMap.ptr[lightRadius].tex.tid);
839 glBegin(GL_QUADS);
840 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, 0); // top-left
841 glTexCoord2f(1.0f, 0.0f); glVertex2i(lightSize, 0); // top-right
842 glTexCoord2f(1.0f, 1.0f); glVertex2i(lightSize, lightSize); // bottom-right
843 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, lightSize); // bottom-left
844 glEnd();
848 // blend light texture
849 fboLevelLight.exec({
850 glEnable(GL_BLEND);
851 //glDisable(GL_BLEND);
852 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
853 orthoCamera(fboLevelLight.tex.width, fboLevelLight.tex.height);
854 //drawAtXY(fboOccluders.tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
855 float occe = 1.0f*lightSize/(MaxLightRadius*2);
856 float occs = 1.0f-occe;
857 int x0 = lightX-lightRadius+0;
858 int y1 = lightY-lightRadius+0;
859 int x1 = lightX+lightRadius-1+1;
860 int y0 = lightY+lightRadius-1+1;
861 bindTexture(fboOccluders.tex.tid);
862 glBegin(GL_QUADS);
864 glTexCoord2f(0.0f, 0.0f); glVertex2i(x0, y0); // top-left
865 glTexCoord2f(occe, 0.0f); glVertex2i(x1, y0); // top-right
866 glTexCoord2f(occe, occe); glVertex2i(x1, y1); // bottom-right
867 glTexCoord2f(0.0f, occe); glVertex2i(x0, y1); // bottom-left
869 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
870 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
871 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
872 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
873 glEnd();
875 bindTexture(0);
876 glRectf(x0, y0, x1, y1);
878 // and blend it again, with the shader that will touch only occluders
879 shadBlurOcc.exec((Shader shad) {
880 //shad["lightTexSize"] = SVec2F(lightSize, lightSize);
881 shad["lightTexSize"] = SVec2F(lightSize, fboOccluders.tex.height);
882 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
883 shad["lightPos"] = SVec2F(lightX, lightY);
884 //shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
885 bindTexture(fboOccluders.tex.tid);
886 glBegin(GL_QUADS);
887 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
888 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
889 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
890 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
891 glEnd();
892 //drawAtXY(fboOccluders.tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
898 // ////////////////////////////////////////////////////////////////////////// //
899 __gshared int testLightX = vlWidth/2, testLightY = vlHeight/2;
900 __gshared bool testLightMoved = false;
901 //__gshared int mapOfsX, mapOfsY;
902 //__gshared bool movement = false;
903 __gshared float iLiquidTime = 0.0;
904 //__gshared bool altMove = false;
907 void renderScene (MonoTime curtime) {
908 //enum BackIntens = 0.05f;
909 enum BackIntens = 0.0f;
911 gloStackClear();
912 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
913 if (gamePaused || inEditMode) atob = 1.0f;
914 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
917 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
918 int curfp = cast(int)((curtime-lastthink).total!"msecs");
919 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
923 int mofsx, mofsy; // camera offset, will be set in background layer builder
925 if (mapTilesChanged != 0) rebuildMapMegaTextures();
927 // build background layer
928 fboOrigBack.exec({
929 //glDisable(GL_BLEND);
930 //glClearDepth(1.0f);
931 //glDepthFunc(GL_LESS);
932 //glDepthFunc(GL_NEVER);
933 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
934 glClear(GL_COLOR_BUFFER_BIT/*|GL_DEPTH_BUFFER_BIT*/);
935 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
936 orthoCamera(map.width*TileSize, map.height*TileSize);
938 glEnable(GL_BLEND);
939 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
940 // draw sky
942 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
943 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
944 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
945 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
947 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*TileSize, map.MapSize*TileSize);
948 // draw background
949 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
950 // draw distorted liquid areas
951 shadLiquidDistort.exec((Shader shad) {
952 shad["iDistortTime"] = iLiquidTime;
953 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
955 // monsters, items; we'll do linear interpolation here
956 glColor3f(1.0f, 1.0f, 1.0f);
957 //glEnable(GL_DEPTH_TEST);
958 attachedLightCount = 0;
960 // who cares about memory?!
961 // draw order: players, items, monsters, other
962 static struct DrawInfo {
963 ActorDef adef;
964 ActorId aid;
965 int actorX, actorY;
966 @disable this (this); // no copies
968 enum { Pixels, Players, Items, Monsters, Other }
969 __gshared DrawInfo[65536][4] drawlists;
970 __gshared uint[4] dlpos;
971 DrawInfo camchickdi;
973 dlpos[] = 0;
975 Actor.forEach((ActorId me) {
976 //me.fprop_0drawlistpos = 0;
977 if (auto adef = findActorDef(me)) {
978 uint dlnum = Other;
979 switch (adef.classtype.get) {
980 case "monster": dlnum = (adef.classname.get != "Player" ? Monsters : Players); break;
981 case "item": dlnum = Items; break;
982 default: dlnum = Other; break;
984 if (me.fget_flags&AF_PIXEL) dlnum = Pixels;
985 int actorX, actorY; // current actor position
987 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
988 if (frameInterpolation && ofs < uint.max-1 && (me.fget_flags&AF_TELEPORT) == 0 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
989 import core.stdc.math : roundf;
990 auto xptr = prevFrameActorsData.ptr+ofs;
991 int ox = xptr.fgetp_x;
992 int nx = me.fget_x;
993 int oy = xptr.fgetp_y;
994 int ny = me.fget_y;
995 actorX = cast(int)(ox+roundf((nx-ox)*atob));
996 actorY = cast(int)(oy+roundf((ny-oy)*atob));
997 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
998 } else {
999 actorX = me.fget_x;
1000 actorY = me.fget_y;
1003 if (me.id == cameraChick.id) {
1004 camchickdi.adef = adef;
1005 camchickdi.aid = me;
1006 camchickdi.actorX = actorX;
1007 camchickdi.actorY = actorY;
1009 // draw sprite
1010 if ((me.fget_flags&AF_NODRAW) == 0) {
1011 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
1012 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
1013 auto dl = drawlists.ptr[dlnum].ptr+dlpos.ptr[dlnum];
1014 ++dlpos.ptr[dlnum];
1015 dl.adef = adef;
1016 dl.aid = me;
1017 dl.actorX = actorX;
1018 dl.actorY = actorY;
1020 // process attached lights
1021 if ((me.fget_flags&AF_NOLIGHT) == 0) {
1022 uint alr = me.fget_attLightRGBX;
1023 bool isambient = (me.fget_classtype.get == "light" && me.fget_classname.get == "Ambient");
1024 if ((alr&0xff) >= 4 || (isambient && me.fget_radius >= 1 && me.fget_height >= 1)) {
1025 //if (isambient) conwriteln("isambient: ", isambient, "; x=", me.fget_x, "; y=", me.fget_y, "; w=", me.fget_radius, "; h=", me.fget_height);
1026 // yep, add it
1027 auto li = attachedLights.ptr+attachedLightCount;
1028 ++attachedLightCount;
1029 li.type = (!isambient ? AttachedLightInfo.Type.Point : AttachedLightInfo.Type.Ambient);
1030 li.x = actorX+me.fget_attLightXOfs;
1031 li.y = actorY+me.fget_attLightYOfs;
1032 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
1033 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
1034 li.uncolored = true;
1035 } else {
1036 li.g = ((alr>>16)&0xff)/255.0f;
1037 li.b = ((alr>>8)&0xff)/255.0f;
1038 li.uncolored = false;
1040 li.radius = (alr&0xff);
1041 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
1042 if (isambient) {
1043 li.w = me.fget_radius;
1044 li.h = me.fget_height;
1048 } else {
1049 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
1053 // draw actor lists
1054 foreach_reverse (uint dlnum; 0..drawlists.length) {
1055 if (dlnum == Pixels) continue;
1056 auto dl = drawlists.ptr[dlnum].ptr;
1057 if (dlnum == Players) dl += dlpos.ptr[dlnum]-1;
1058 foreach (uint idx; 0..dlpos.ptr[dlnum]) {
1059 auto me = dl.aid;
1060 if (auto isp = dl.adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
1061 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
1062 isp.drawAtXY(dl.actorX, dl.actorY);
1064 if (dlnum != Players) ++dl; else --dl;
1067 // draw pixels
1068 if (dlpos[Pixels]) {
1069 bindTexture(0);
1070 bool pointsStarted = false;
1071 Color lastColor = Color(0, 0, 0, 0);
1072 auto dl = drawlists.ptr[Pixels].ptr;
1073 foreach (uint idx; 0..dlpos.ptr[Pixels]) {
1074 auto me = dl.aid;
1075 auto s = me.fget_s;
1076 if (s < 0 || s > 255) continue; //FIXME
1077 Color clr = d2dpal.ptr[s&0xff];
1078 if (clr.a == 0) continue;
1079 if (clr != lastColor) {
1080 if (pointsStarted) glEnd();
1081 glColor4f(clr.r/255.0f, clr.g/255.0f, clr.b/255.0f, clr.a/255.0f);
1082 lastColor = clr;
1083 pointsStarted = false;
1085 if (!pointsStarted) {
1086 glBegin(GL_POINTS);
1087 pointsStarted = true;
1089 glVertex2i(dl.actorX, dl.actorY);
1090 ++dl;
1092 if (pointsStarted) {
1093 glEnd();
1094 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1098 // camera movement
1099 if (/*altMove || movement ||*/ scale == 1 || !cameraChick.valid) {
1100 mofsx = 0;
1101 mofsy = 0;
1102 vportX0 = 0;
1103 vportY0 = 0;
1104 vportX1 = map.width*TileSize;
1105 vportY1 = map.height*TileSize;
1106 } else {
1107 int tiltHeight = /*getMapViewHeight()*/(vlHeight/scale)/4;
1108 int vy = cameraChick.looky!int;
1109 if (vy < -tiltHeight) vy = -tiltHeight; else if (vy > tiltHeight) vy = tiltHeight;
1110 int swdt = vlWidth/scale;
1111 int shgt = vlHeight/scale;
1112 int x = camchickdi.actorX-swdt/2;
1113 int y = (camchickdi.actorY+vy)-shgt/2;
1114 if (x < 0) x = 0; else if (x >= map.width*TileSize-swdt) x = map.width*TileSize-swdt-1;
1115 if (y < 0) y = 0; else if (y >= map.height*TileSize-shgt) y = map.height*TileSize-shgt-1;
1116 mofsx = x*2;
1117 mofsy = y*2;
1118 vportX0 = mofsx/scale;
1119 vportY0 = mofsy/scale;
1120 vportX1 = vportX0+vlWidth/scale;
1121 vportY1 = vportY0+vlHeight/scale;
1124 //glDisable(GL_DEPTH_TEST);
1125 // draw dots
1126 dotDraw(atob);
1127 // do liquid coloring
1128 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
1129 // foreground -- hide secrets, draw lifts and such
1130 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
1133 enum r = 255;
1134 enum g = 0;
1135 enum b = 0;
1136 enum a = 255;
1137 bindTexture(0);
1138 glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
1139 glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
1140 if (cameraChick.valid) {
1141 glBegin(GL_POINTS);
1142 glVertex2i(camchickdi.actorX, camchickdi.actorY-70);
1143 glEnd();
1144 //glRectf(camchickdi.actorX, camchickdi.actorY-70, camchickdi.actorX+4, camchickdi.actorY-70+4);
1146 //glRectf(0, 0, 300, 300);
1147 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1153 if (doLighting) {
1154 glDisable(GL_BLEND);
1155 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1157 // make smaller occluder texture, so we can trace faster
1158 //assert(fboLMaskSmall.tex.width == map.width);
1159 //assert(fboLMaskSmall.tex.height == map.height);
1160 fboLMaskSmall.exec({
1161 orthoCamera(map.width, map.height);
1162 drawAtXY(map.texgl.ptr[map.LightMask].tid, 0, 0, map.width, map.height, mirrorY:true);
1165 // clear light layer
1166 fboLevelLight.exec({
1167 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1168 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
1169 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
1170 glClear(GL_COLOR_BUFFER_BIT);
1173 // texture 1 is background
1174 glActiveTexture(GL_TEXTURE0+1);
1175 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
1176 // texture 2 is occluders
1177 glActiveTexture(GL_TEXTURE0+2);
1178 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
1179 // texture 3 is small occluder map
1180 glActiveTexture(GL_TEXTURE0+3);
1181 glBindTexture(GL_TEXTURE_2D, fboLMaskSmall.tex.tid);
1182 // done texture assign
1183 glActiveTexture(GL_TEXTURE0+0);
1186 enum LYOfs = 1;
1188 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1189 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1190 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1191 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1192 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1193 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1194 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1195 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1196 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1197 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1199 renderLight(24*TileSize+4, (24+18)*TileSize-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
1201 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1204 foreach (; 0..1) {
1205 // attached lights
1206 foreach (ref li; attachedLights[0..attachedLightCount]) {
1207 if (li.type == AttachedLightInfo.Type.Ambient) {
1208 //conwriteln("ambient: x=", li.x, "; y=", li.y, "; w=", li.w, "; h=", li.h);
1209 // ambient light
1210 if (li.uncolored) {
1211 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(0.0f, 0.0f, 0.0f, li.r));
1212 } else {
1213 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(li.r, li.g, li.b, 1.0f));
1215 } else if (li.type == AttachedLightInfo.Type.Point) {
1216 // point light
1217 if (li.uncolored) {
1218 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
1219 } else {
1220 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
1227 if (testLightMoved) {
1228 testLightX = testLightX/scale+mofsx/scale;
1229 testLightY = testLightY/scale+mofsy/scale;
1230 testLightMoved = false;
1232 foreach (immutable _; 0..1) {
1233 renderLight(testLightX, testLightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
1237 glActiveTexture(GL_TEXTURE0+1);
1238 glBindTexture(GL_TEXTURE_2D, 0);
1239 glActiveTexture(GL_TEXTURE0+2);
1240 glBindTexture(GL_TEXTURE_2D, 0);
1241 glActiveTexture(GL_TEXTURE0+3);
1242 glBindTexture(GL_TEXTURE_2D, 0);
1243 glActiveTexture(GL_TEXTURE0+0);
1246 // draw scaled level
1248 shadScanlines.exec((Shader shad) {
1249 shad["scanlines"] = scanlines;
1250 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1251 glClear(GL_COLOR_BUFFER_BIT);
1252 orthoCamera(vlWidth, vlHeight);
1253 //orthoCamera(map.width*TileSize*scale, map.height*TileSize*scale);
1254 //glMatrixMode(GL_MODELVIEW);
1255 //glLoadIdentity();
1256 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
1257 // somehow, FBO objects are mirrored; wtf?!
1258 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1259 //glLoadIdentity();
1264 fboLevelLight.exec({
1265 smDrawText(map.width*TileSize/2, map.height*TileSize/2, "Testing...");
1270 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1272 glDisable(GL_BLEND);
1275 fboOrigBack.exec({
1276 //auto img = smfont.ptr[0x39];
1277 auto img = fftest;
1278 if (img !is null) {
1279 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
1280 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
1287 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
1288 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1289 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1290 glDrawBuffers(1, buffers.ptr);
1295 orthoCamera(vlWidth, vlHeight);
1296 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
1297 drawAtXY(tex, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1299 if (levelLoaded) {
1300 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1301 //orthoCamera(map.width*TileSize, map.height*TileSize);
1302 glEnable(GL_BLEND);
1303 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1304 hudScripts.runDraw();
1307 //drawAtXY(map.texgl.ptr[map.LightMask].tid, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1308 //drawAtXY(fboLMaskSmall.tex.tid, 0, 0, map.width*TileSize, map.height*TileSize);
1310 if (inEditMode) {
1311 glEnable(GL_BLEND);
1312 //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1313 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1314 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1315 editorUpdateImage();
1316 fboEditor.tex.setFromImage(editorImg);
1317 drawAtXY(fboEditor.tex, 0, 0);
1318 glDisable(GL_BLEND);
1321 doMessages(curtime);
1323 if (rConsoleVisible) {
1324 renderConsoleFBO();
1325 orthoCamera(vlWidth, vlHeight);
1326 glEnable(GL_BLEND);
1327 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1328 glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
1329 drawAtXY(fboConsole.tex, 0, rConsoleHeight-vlHeight, mirrorY:true);
1334 // ////////////////////////////////////////////////////////////////////////// //
1335 // returns time slept
1336 int sleepAtMaxMsecs (int msecs) {
1337 if (msecs > 0) {
1338 import core.sys.posix.signal : timespec;
1339 import core.sys.posix.time : nanosleep;
1340 timespec ts = void, tpassed = void;
1341 ts.tv_sec = 0;
1342 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
1343 nanosleep(&ts, &tpassed);
1344 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
1345 } else {
1346 return 0;
1351 // ////////////////////////////////////////////////////////////////////////// //
1352 mixin(import("editor.d"));
1355 // ////////////////////////////////////////////////////////////////////////// //
1356 // rendering thread
1357 shared int diedie = 0;
1359 enum D2DFrameTime = 55; // milliseconds
1360 enum MinFrameTime = 1000/60; // ~60 FPS
1362 public void renderThread (Tid starterTid) {
1363 enum BoolOptVarMsgMixin(string varname) =
1364 "if (msg.toggle) msg.value = !"~varname~";\n"~
1365 "if ("~varname~" != msg.value) "~varname~" = msg.value; else msg.showMessage = false;\n";
1367 send(starterTid, 42);
1368 try {
1369 MonoTime curtime = MonoTime.currTime;
1371 lastthink = curtime; // for interpolator
1372 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1373 MonoTime nextvframe = curtime;
1375 enum MaxFPSFrames = 16;
1376 float frtimes = 0.0f;
1377 int framenum = 0;
1378 int prevFPS = -1;
1379 int hushFrames = 6; // ignore first `hushFrames` frames overtime
1380 MonoTime prevFrameStartTime = curtime;
1382 bool vframeWasLost = false;
1384 void resetFrameTimers () {
1385 MonoTime curtime = MonoTime.currTime;
1386 lastthink = curtime; // for interpolator
1387 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1388 nextvframe = curtime;
1391 void loadNewLevel (string name) {
1393 if (levelLoaded) {
1394 conwriteln("ERROR: can't load new levels yet");
1395 return;
1398 if (name.length == 0) {
1399 conwriteln("ERROR: can't load empty level!");
1401 conwriteln("loading map '", name, "'");
1402 loadMap(name);
1403 resetFrameTimers();
1406 conRegFunc!({
1407 string mn = genNextMapName(0);
1408 if (mn.length) {
1409 nextmapname = null; // clear "exit" flag
1410 loadNewLevel(mn);
1411 } else {
1412 conwriteln("can't skip level");
1414 })("skiplevel", "skip current level");
1416 conRegFunc!({
1417 inEditMode = !inEditMode;
1418 if (inEditMode) sdwindow.hideCursor(); else sdwindow.showCursor();
1419 })("ed_toggle", "toggle editor");
1421 conRegFunc!({
1422 if (inEditMode) {
1423 inEditMode = false;
1424 sdwindow.showCursor();
1426 })("ed_exit", "exit from editor");
1428 conRegFunc!((string mapname) {
1429 nextmapname = null; // clear "exit" flag
1430 loadNewLevel(mapname);
1431 })("map", "load map");
1433 void receiveMessages () {
1434 for (;;) {
1435 import core.time : Duration;
1436 //conwriteln("rendering thread: waiting for messages...");
1437 auto got = receiveTimeout(
1438 Duration.zero, // don't wait
1439 (TMsgMessage msg) {
1440 addMessage(msg.text[0..msg.textlen], msg.pauseMsecs, msg.noreplace);
1442 (TMsgTestLightMove msg) {
1443 testLightX = msg.x;
1444 testLightY = msg.y;
1445 testLightMoved = true;
1447 (TMsgMouseEvent msg) { editorMouseEvent(msg); },
1448 (TMsgKeyEvent msg) { editorKeyEvent(msg); },
1449 (TMsgChar msg) { concliChar(msg.ch); },
1450 (Variant v) {
1451 conwriteln("WARNING: unknown thread message received and ignored");
1454 if (!got) {
1455 // no more messages
1456 //conwriteln("rendering thread: no more messages");
1457 break;
1460 if (nextmapname.length) {
1461 string mn = nextmapname;
1462 nextmapname = null; // clear "exit" flag
1463 loadNewLevel(mn);
1467 void processConsoleCommands () {
1468 cbufLock();
1469 scope(exit) cbufUnlock();
1470 concmdDoAll();
1473 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1474 bool doThinkFrame () {
1475 if (curtime >= nextthink) {
1476 lastthink = curtime;
1477 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
1478 if (levelLoaded) {
1479 // save snapshot and other data for interpolator
1480 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
1481 if (!gamePaused && !inEditMode) {
1482 // process actors
1483 doActorsThink();
1484 dotThink();
1487 // some timing
1488 auto tm = MonoTime.currTime;
1489 int thinkTime = cast(int)((tm-curtime).total!"msecs");
1490 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
1491 curtime = tm;
1492 return true;
1493 } else {
1494 return false;
1498 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1499 bool doVFrame () {
1500 version(dont_use_vsync) {
1501 // timer
1502 enum doCheckTime = true;
1503 } else {
1504 // vsync
1505 __gshared bool prevLost = false;
1506 bool doCheckTime = vframeWasLost;
1507 if (vframeWasLost) {
1508 if (!prevLost) {
1509 { import core.stdc.stdio; printf("frame was lost!\n"); }
1511 prevLost = true;
1512 } else {
1513 prevLost = false;
1516 if (doCheckTime) {
1517 if (curtime < nextvframe) return false;
1518 version(dont_use_vsync) {
1519 if (curtime > nextvframe) {
1520 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
1521 if (overtime > 2500) {
1522 if (hushFrames) {
1523 --hushFrames;
1524 } else {
1525 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
1531 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
1532 bool ctset = false;
1534 sdwindow.mtLock();
1535 scope(exit) sdwindow.mtUnlock();
1536 ctset = sdwindow.setAsCurrentOpenGlContextNT;
1538 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1539 if (ctset) {
1540 // render scene
1541 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
1542 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1543 processConsoleCommands();
1544 if (levelLoaded) {
1545 renderScene(curtime);
1546 } else {
1547 //renderLoading(curtime);
1549 sdwindow.mtLock();
1550 scope(exit) sdwindow.mtUnlock();
1551 sdwindow.swapOpenGlBuffers();
1552 glFinish();
1553 sdwindow.releaseCurrentOpenGlContext();
1554 vframeWasLost = false;
1555 } else {
1556 vframeWasLost = true;
1557 { import core.stdc.stdio; printf("xframe was lost!\n"); }
1559 curtime = MonoTime.currTime;
1560 return true;
1563 for (;;) {
1564 if (sdwindow.closed) break;
1565 if (atomicLoad(diedie) > 0) break;
1567 curtime = MonoTime.currTime;
1568 auto fstime = curtime;
1570 doThinkFrame(); // this will fix curtime if necessary
1571 if (doVFrame()) {
1572 if (!vframeWasLost) {
1573 // fps
1574 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
1575 prevFrameStartTime = curtime;
1576 frtimes += frameTime;
1577 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
1578 import std.string : format;
1579 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
1580 if (newFPS != prevFPS) {
1581 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
1582 prevFPS = newFPS;
1584 framenum = 0;
1585 frtimes = 0.0f;
1590 curtime = MonoTime.currTime;
1592 // now sleep until next "video" or "think" frame
1593 if (nextthink > curtime && nextvframe > curtime) {
1594 // let's decide
1595 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
1596 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
1597 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
1598 sleepAtMaxMsecs(sleepTime);
1599 //curtime = MonoTime.currTime;
1602 } catch (Throwable e) {
1603 // here, we are dead and fucked (the exact order doesn't matter)
1604 import core.stdc.stdlib : abort;
1605 import core.stdc.stdio : fprintf, stderr;
1606 import core.memory : GC;
1607 GC.disable(); // yeah
1608 thread_suspendAll(); // stop right here, you criminal scum!
1609 auto s = e.toString();
1610 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
1611 abort(); // die, you bitch!
1613 import core.stdc.stdio;
1614 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1615 import std.stdio : stderr;
1616 writeln(
1617 for (;;) {
1618 if (sdwindow.closed) break;
1619 if (atomicLoad(diedie) > 0) break;
1620 sleepAtMaxMsecs(100);
1624 atomicStore(diedie, 2);
1628 // ////////////////////////////////////////////////////////////////////////// //
1629 __gshared Tid renderTid;
1630 shared bool renderThreadStarted = false;
1633 public void startRenderThread () {
1634 if (!cas(&renderThreadStarted, false, true)) {
1635 assert(0, "render thread already started!");
1637 renderTid = spawn(&renderThread, thisTid);
1638 setMaxMailboxSize(renderTid, 1024, OnCrowding.throwException); //FIXME
1639 // wait for "i'm ready" signal
1640 receive(
1641 (int ok) {
1642 if (ok != 42) assert(0, "wtf?!");
1645 conwriteln("rendering thread started");
1649 // ////////////////////////////////////////////////////////////////////////// //
1650 public void closeWindow () {
1651 if (atomicLoad(diedie) != 2) {
1652 atomicStore(diedie, 1);
1653 while (atomicLoad(diedie) != 2) {}
1655 if (!sdwindow.closed) {
1656 flushGui();
1657 sdwindow.close();
1662 // ////////////////////////////////////////////////////////////////////////// //
1663 // thread messages
1666 // ////////////////////////////////////////////////////////////////////////// //
1667 struct TMsgMouseEvent {
1668 MouseEventType type;
1669 int x, y;
1670 int dx, dy;
1671 MouseButton button; /// See $(LREF MouseButton)
1672 int modifierState; /// See $(LREF ModifierState)
1675 public void postMouseEvent() (in auto ref MouseEvent evt) {
1676 if (!atomicLoad(renderThreadStarted)) return;
1677 TMsgMouseEvent msg;
1678 msg.type = evt.type;
1679 msg.x = evt.x;
1680 msg.y = evt.y;
1681 msg.dx = evt.dx;
1682 msg.dy = evt.dy;
1683 msg.button = evt.button;
1684 msg.modifierState = evt.modifierState;
1685 send(renderTid, msg);
1689 // ////////////////////////////////////////////////////////////////////////// //
1690 struct TMsgKeyEvent {
1691 Key key;
1692 uint hardwareCode;
1693 bool pressed;
1694 dchar character;
1695 uint modifierState;
1698 public void postKeyEvent() (in auto ref KeyEvent evt) {
1699 if (!atomicLoad(renderThreadStarted)) return;
1700 TMsgKeyEvent msg;
1701 msg.key = evt.key;
1702 msg.pressed = evt.pressed;
1703 msg.character = evt.character;
1704 msg.modifierState = evt.modifierState;
1705 send(renderTid, msg);
1709 // ////////////////////////////////////////////////////////////////////////// //
1710 struct TMsgTestLightMove {
1711 int x, y;
1714 public void postTestLightMove (int x, int y) {
1715 if (!atomicLoad(renderThreadStarted)) return;
1716 auto msg = TMsgTestLightMove(x, y);
1717 send(renderTid, msg);
1721 // ////////////////////////////////////////////////////////////////////////// //
1722 struct TMsgMessage {
1723 char[256] text;
1724 uint textlen;
1725 int pauseMsecs;
1726 bool noreplace;
1729 public void postAddMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
1730 if (!atomicLoad(renderThreadStarted)) return;
1731 if (msgtext.length > TMsgMessage.text.length) msgtext = msgtext[0..TMsgMessage.text.length];
1732 TMsgMessage msg;
1733 msg.textlen = cast(uint)msgtext.length;
1734 if (msg.textlen) msg.text[0..msg.textlen] = msgtext[0..msg.textlen];
1735 msg.pauseMsecs = pauseMsecs;
1736 msg.noreplace = noreplace;
1737 send(renderTid, msg);
1741 // ////////////////////////////////////////////////////////////////////////// //
1742 struct TMsgChar {
1743 char ch;
1746 public void postChar (char ch) {
1747 if (!atomicLoad(renderThreadStarted)) return;
1748 TMsgChar msg;
1749 msg.ch = ch;
1750 send(renderTid, msg);
1754 // ////////////////////////////////////////////////////////////////////////// //
1755 // add console command to execution queue
1756 public void concmd (const(char)[] cmd) {
1757 //if (!atomicLoad(renderThreadStarted)) return;
1758 cbufLock();
1759 scope(exit) cbufUnlock();
1760 concmdAdd(cmd);
1763 // get console variable value; doesn't do complex conversions!
1764 public T convar(T) (const(char)[] s) {
1765 cbufLock();
1766 scope(exit) cbufUnlock();
1767 return conGetVar!T(s);
1770 // set console variable value; doesn't do complex conversions!
1771 public void convar(T) (const(char)[] s, T val) {
1772 cbufLock();
1773 scope(exit) cbufUnlock();
1774 conSetVar!T(s, val);