trap switches
[dd2d.git] / render.d
blob3e0846f616a25be0f5e6b8a72507fe2484a21306
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;
21 //version = old_light;
23 private:
24 import core.atomic;
25 import core.thread;
26 import core.time;
28 import std.concurrency;
30 import iv.glbinds;
31 import glutils;
32 import console;
33 import wadarc;
35 import iv.stream;
37 import d2dmap;
38 import d2dadefs;
39 //import d2dactors;
40 import d2dgfx;
41 import d2dfont;
42 import dacs;
44 import d2dunigrid;
46 // `map` is there
47 import dengapi;
49 import d2dparts;
52 // ////////////////////////////////////////////////////////////////////////// //
53 import arsd.color;
54 import arsd.png;
57 // ////////////////////////////////////////////////////////////////////////// //
58 public __gshared bool cheatNoDoors = false;
59 public __gshared bool cheatNoWallClip = false;
62 // ////////////////////////////////////////////////////////////////////////// //
63 public __gshared SimpleWindow sdwindow;
66 public enum vlWidth = 800;
67 public enum vlHeight = 800;
68 __gshared int scale = 2;
70 public int getScale () nothrow @trusted @nogc { pragma(inline, true); return scale; }
73 // ////////////////////////////////////////////////////////////////////////// //
74 __gshared bool levelLoaded = false;
77 // ////////////////////////////////////////////////////////////////////////// //
78 __gshared bool scanlines = false;
79 __gshared bool doLighting = true;
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 __gshared int[2] mapViewPosX, mapViewPosY; // [0]: previous frame -- for interpolator
94 // this should be screen center
95 public void setMapViewPos (int x, int y) {
96 if (map is null) {
97 mapViewPosX[] = 0;
98 mapViewPosY[] = 0;
99 return;
101 int swdt = vlWidth/scale;
102 int shgt = vlHeight/scale;
103 x -= swdt/2;
104 y -= shgt/2;
105 if (x < 0) x = 0; else if (x >= map.width*8-swdt) x = map.width*8-swdt-1;
106 if (y < 0) y = 0; else if (y >= map.height*8-shgt) y = map.height*8-shgt-1;
107 mapViewPosX[1] = x*scale;
108 mapViewPosY[1] = y*scale;
112 // ////////////////////////////////////////////////////////////////////////// //
113 // attached lights
114 struct AttachedLightInfo {
115 int x, y;
116 float r, g, b;
117 bool uncolored;
118 int radius;
121 __gshared AttachedLightInfo[65536] attachedLights;
122 __gshared uint attachedLightCount = 0;
125 // ////////////////////////////////////////////////////////////////////////// //
126 enum MaxLightRadius = 512;
129 // ////////////////////////////////////////////////////////////////////////// //
130 // for light
131 __gshared FBO[MaxLightRadius+1] fboOccluders, fboDistMap;
132 __gshared Shader shadToPolar, shadBlur, shadBlurOcc;
134 __gshared FBO fboLevel, fboLevelLight, fboOrigBack;
135 __gshared Shader shadScanlines;
136 __gshared Shader shadLiquidDistort;
139 // ////////////////////////////////////////////////////////////////////////// //
140 // call once!
141 public void initOpenGL () {
142 gloStackClear();
144 glEnable(GL_TEXTURE_2D);
145 glDisable(GL_LIGHTING);
146 glDisable(GL_DITHER);
147 glDisable(GL_BLEND);
148 glDisable(GL_DEPTH_TEST);
150 // create shaders
151 shadScanlines = new Shader("scanlines", loadTextFile("data/shaders/srscanlines.frag"));
153 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("data/shaders/srliquid_distort.frag"));
154 shadLiquidDistort.exec((Shader shad) {
155 shad["texLqMap"] = 0;
158 // lights
159 version(old_light) {
160 shadToPolar = new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar.frag"));
161 } else {
162 shadToPolar = new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar_new.frag"));
164 shadToPolar.exec((Shader shad) {
165 shad["texOcc"] = 0;
166 shad["texOccFull"] = 2;
169 shadBlur = new Shader("light_blur", loadTextFile("data/shaders/srlight_blur.frag"));
170 shadBlur.exec((Shader shad) {
171 shad["texDist"] = 0;
172 shad["texBg"] = 1;
173 shad["texOcc"] = 2;
176 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("data/shaders/srlight_blur_occ.frag"));
177 shadBlurOcc.exec((Shader shad) {
178 shad["texLMap"] = 0;
179 shad["texBg"] = 1;
180 shad["texOcc"] = 2;
183 //TODO: this sux!
184 foreach (int sz; 2..MaxLightRadius+1) {
185 fboOccluders[sz] = new FBO(sz*2, sz*2, Texture.Option.Clamp, Texture.Option.Linear); // create occluders FBO
186 fboDistMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp); // create 1d distance map FBO
189 // setup matrices
190 glMatrixMode(GL_MODELVIEW);
191 glLoadIdentity();
193 loadSmFont();
194 loadAllMonsterGraphics();
198 // ////////////////////////////////////////////////////////////////////////// //
199 // should be called when OpenGL is initialized
200 void loadMap (string mapname) {
201 if (map !is null) map.clear();
202 map = new LevelMap(mapname);
204 ugInit(map.width*8, map.height*8);
206 map.oglBuildMega();
207 mapTilesChanged = 0;
209 if (fboLevel !is null) fboLevel.clear();
210 if (fboLevelLight !is null) fboLevelLight.clear();
211 if (fboOrigBack !is null) fboOrigBack.clear();
213 fboLevel = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // final level render will be here
214 fboLevelLight = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level lights will be rendered here
215 fboOrigBack = new FBO(map.width*8, map.height*8, Texture.Option.Nearest, Texture.Option.Depth); // background+foreground
217 shadToPolar.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8-1, map.height*8-1); });
218 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
219 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
221 glActiveTexture(GL_TEXTURE0+0);
222 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
223 orthoCamera(vlWidth, vlHeight);
225 Actor.resetStorage();
226 loadMapMonsters();
228 dotInit();
230 // save first snapshot
231 prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
232 prevFrameActorOfs[] = uint.max; // just for fun
233 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
234 mapViewPosX[0] = mapViewPosX[1];
235 mapViewPosY[0] = mapViewPosY[1];
237 levelLoaded = true;
239 { import core.memory : GC; GC.collect(); }
243 // ////////////////////////////////////////////////////////////////////////// //
244 //FIXME: optimize!
245 __gshared uint mapTilesChanged = 0;
248 //WARNING! this can be called only from DACS, so we don't have to sync it!
249 public void mapDirty (uint layermask) { mapTilesChanged |= layermask; }
252 void rebuildMapMegaTextures () {
253 //fbo.replaceTexture
254 //mapTilesChanged = false;
255 //map.clearMegaTextures();
256 map.oglBuildMega(mapTilesChanged);
257 mapTilesChanged = 0;
261 // ////////////////////////////////////////////////////////////////////////// //
262 // messages
263 struct Message {
264 enum Phase { FadeIn, Stay, FadeOut }
265 Phase phase;
266 int alpha;
267 int pauseMsecs;
268 MonoTime removeTime;
269 char[256] text;
270 usize textlen;
273 private import core.sync.mutex : Mutex;
275 __gshared Message[128] messages;
276 __gshared uint messagesUsed = 0;
278 //__gshared Mutex messageLock;
279 //shared static this () { messageLock = new Mutex(); }
282 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
283 //messageLock.lock();
284 //scope(exit) messageLock.unlock();
285 if (msgtext.length == 0) return;
286 conwriteln(msgtext);
287 if (pauseMsecs <= 50) return;
288 if (messagesUsed == messages.length) {
289 // remove top message
290 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
291 messages.ptr[0].alpha = 255;
292 --messagesUsed;
294 // quick replace
295 if (!noreplace && messagesUsed == 1) {
296 switch (messages.ptr[0].phase) {
297 case Message.Phase.FadeIn:
298 messages.ptr[0].phase = Message.Phase.FadeOut;
299 break;
300 case Message.Phase.Stay:
301 messages.ptr[0].phase = Message.Phase.FadeOut;
302 messages.ptr[0].alpha = 255;
303 break;
304 default:
307 auto msg = messages.ptr+messagesUsed;
308 ++messagesUsed;
309 msg.phase = Message.Phase.FadeIn;
310 msg.alpha = 0;
311 msg.pauseMsecs = pauseMsecs;
312 // copy text
313 if (msgtext.length > msg.text.length) {
314 msg.text = msgtext[0..msg.text.length];
315 msg.textlen = msg.text.length;
316 } else {
317 msg.text[0..msgtext.length] = msgtext[];
318 msg.textlen = msgtext.length;
323 void doMessages (MonoTime curtime) {
324 //messageLock.lock();
325 //scope(exit) messageLock.unlock();
327 if (messagesUsed == 0) return;
328 glEnable(GL_BLEND);
329 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
331 Message* msg;
333 again:
334 msg = messages.ptr;
335 final switch (msg.phase) {
336 case Message.Phase.FadeIn:
337 if ((msg.alpha += 10) >= 255) {
338 msg.phase = Message.Phase.Stay;
339 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
340 goto case; // to stay
342 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
343 break;
344 case Message.Phase.Stay:
345 if (msg.removeTime <= curtime) {
346 msg.alpha = 255;
347 msg.phase = Message.Phase.FadeOut;
348 goto case; // to fade
350 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
351 break;
352 case Message.Phase.FadeOut:
353 if ((msg.alpha -= 10) <= 0) {
354 if (--messagesUsed == 0) return;
355 // remove this message
356 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
357 goto again;
359 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
360 break;
363 smDrawText(10, 10, msg.text[0..msg.textlen]);
367 // ////////////////////////////////////////////////////////////////////////// //
368 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
370 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
371 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
372 mixin(Actor.FieldGetMixin!("x", int));
373 mixin(Actor.FieldGetMixin!("y", int));
374 mixin(Actor.FieldGetMixin!("flags", uint));
375 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
376 mixin(Actor.FieldGetMixin!("zAnimidx", int));
377 mixin(Actor.FieldGetMixin!("dir", uint));
378 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
379 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
380 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
382 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
383 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
384 mixin(Actor.FieldGetPtrMixin!("x", int));
385 mixin(Actor.FieldGetPtrMixin!("y", int));
386 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
387 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
388 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
389 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
390 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
391 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
392 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
395 // ////////////////////////////////////////////////////////////////////////// //
396 __gshared int vportX0, vportY0, vportX1, vportY1;
399 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
400 if (lightRadius < 2) return;
401 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
402 int lightSize = lightRadius*2;
403 // is this light visible?
404 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*8 || lightY-lightRadius >= map.height*8) return;
406 // out of viewport -- do nothing
407 if (lightX+lightRadius < vportX0 || lightY+lightRadius < vportY0) return;
408 if (lightX-lightRadius > vportX1 || lightY-lightRadius > vportY1) return;
410 if (lightX >= 0 && lightY >= 0 && lightX < map.width*8 && lightY < map.height*8 &&
411 map.teximgs[map.LightMask].imageData.colors.ptr[lightY*(map.width*8)+lightX].a > 190) return;
413 //glUseProgram(0);
414 glDisable(GL_BLEND);
416 // draw shadow casters to fboOccludersId, light should be in the center
417 version(old_light) {
418 fboOccluders[lightRadius].exec({
419 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
420 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
421 glClear(GL_COLOR_BUFFER_BIT);
422 orthoCamera(lightSize, lightSize);
423 drawAtXY(map.texgl.ptr[map.LightMask], lightRadius-lightX, lightRadius-lightY);
426 // common color for all the following
427 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
429 // build 1d distance map to fboShadowMapId
430 fboDistMap[lightRadius].exec({
431 shadToPolar.exec((Shader shad) {
432 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
433 shad["lightPos"] = SVec2F(lightX, lightY);
434 // no need to clear it, shader will take care of that
435 orthoCamera(lightSize, 1);
436 version(old_light) {
437 drawAtXY(fboOccluders[lightRadius].tex.tid, 0, 0, lightSize, 1);
438 } else {
439 // it doesn't matter what we will draw here, so just draw filled rect
440 glRectf(0, 0, lightSize, 1);
445 // build light texture for blending
446 fboOccluders[lightRadius].exec({
447 // no need to clear it, shader will take care of that
448 shadBlur.exec((Shader shad) {
449 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
450 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
451 shad["lightPos"] = SVec2F(lightX, lightY);
452 orthoCamera(lightSize, lightSize);
453 drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
457 // blend light texture
458 fboLevelLight.exec({
459 glEnable(GL_BLEND);
460 //glDisable(GL_BLEND);
461 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
462 orthoCamera(map.width*8, map.height*8);
463 drawAtXY(fboOccluders[lightRadius].tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
464 // and blend it again, with the shader that will touch only occluders
465 shadBlurOcc.exec((Shader shad) {
466 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
467 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
468 shad["lightPos"] = SVec2F(lightX, lightY);
469 drawAtXY(fboOccluders[lightRadius].tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
475 // ////////////////////////////////////////////////////////////////////////// //
476 __gshared int testLightX = vlWidth/2, testLightY = vlHeight/2;
477 __gshared bool testLightMoved = false;
478 //__gshared int mapOfsX, mapOfsY;
479 //__gshared bool movement = false;
480 __gshared float iLiquidTime = 0.0;
481 //__gshared bool altMove = false;
484 void renderScene (MonoTime curtime) {
485 //enum BackIntens = 0.05f;
486 enum BackIntens = 0.0f;
488 gloStackClear();
489 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
490 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
493 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
494 int curfp = cast(int)((curtime-lastthink).total!"msecs");
495 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
499 int mofsx, mofsy;
501 bool camCenter = true;
502 if (/*altMove || movement ||*/ scale == 1) {
504 mofsx = mapOfsX;
505 mofsy = mapOfsY;
507 vportX0 = 0;
508 vportY0 = 0;
509 vportX1 = map.width*8;
510 vportY1 = map.height*8;
511 camCenter = false;
512 } else {
513 if (frameInterpolation) {
514 import core.stdc.math : roundf;
515 mofsx = cast(int)(mapViewPosX[0]+roundf((mapViewPosX[1]-mapViewPosX[0])*atob));
516 mofsy = cast(int)(mapViewPosY[0]+roundf((mapViewPosY[1]-mapViewPosY[0])*atob));
517 } else {
518 mofsx = mapViewPosX[1];
519 mofsy = mapViewPosY[1];
521 vportX0 = mofsx/scale;
522 vportY0 = mofsy/scale;
523 vportX1 = vportX0+vlWidth/scale;
524 vportY1 = vportY0+vlHeight/scale;
527 if (mapTilesChanged != 0) rebuildMapMegaTextures();
529 dotDraw(atob);
531 // build background layer
532 fboOrigBack.exec({
533 //glDisable(GL_BLEND);
534 //glClearDepth(1.0f);
535 //glDepthFunc(GL_LESS);
536 //glDepthFunc(GL_NEVER);
537 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
538 glClear(GL_COLOR_BUFFER_BIT/*|GL_DEPTH_BUFFER_BIT*/);
539 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
540 orthoCamera(map.width*8, map.height*8);
542 glEnable(GL_BLEND);
543 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
544 // draw sky
546 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
547 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2, map.MapSize*8, map.MapSize*8);
548 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
549 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*8, map.MapSize*8);
551 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*8, map.MapSize*8);
552 // draw background
553 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
554 // draw distorted liquid areas
555 shadLiquidDistort.exec((Shader shad) {
556 shad["iDistortTime"] = iLiquidTime;
557 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
559 // monsters, items; we'll do linear interpolation here
560 glColor3f(1.0f, 1.0f, 1.0f);
561 //glEnable(GL_DEPTH_TEST);
562 attachedLightCount = 0;
564 // who cares about memory?!
565 // draw order: players, items, monsters, other
566 static struct DrawInfo {
567 ActorDef adef;
568 ActorId aid;
569 int actorX, actorY;
570 @disable this (this); // no copies
572 enum { Players, Items, Monsters, Other }
573 __gshared DrawInfo[65536][4] drawlists;
574 __gshared uint[4] dlpos;
575 DrawInfo camchickdi;
577 dlpos[] = 0;
578 ActorId camchick;
580 Actor.forEach((ActorId me) {
581 //me.fprop_0drawlistpos = 0;
582 if (auto adef = findActorDef(me)) {
583 uint dlnum = Other;
584 switch (adef.classtype.get) {
585 case "monster": dlnum = (adef.classname.get != "Player" ? Monsters : Players); break;
586 case "item": dlnum = Items; break;
587 default: dlnum = Other; break;
589 int actorX, actorY; // current actor position
591 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
592 if (frameInterpolation && ofs < uint.max-1 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
593 import core.stdc.math : roundf;
594 auto xptr = prevFrameActorsData.ptr+ofs;
595 int ox = xptr.fgetp_x;
596 int nx = me.fget_x;
597 int oy = xptr.fgetp_y;
598 int ny = me.fget_y;
599 actorX = cast(int)(ox+roundf((nx-ox)*atob));
600 actorY = cast(int)(oy+roundf((ny-oy)*atob));
601 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
602 } else {
603 actorX = me.fget_x;
604 actorY = me.fget_y;
607 if (!camchick.valid && me.flags!uint&AF_CAMERACHICK) {
608 camchick = me;
609 camchickdi.adef = adef;
610 camchickdi.aid = me;
611 camchickdi.actorX = actorX;
612 camchickdi.actorY = actorY;
614 // draw sprite
615 if ((me.fget_flags&AF_NODRAW) == 0) {
616 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
617 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
618 auto dl = drawlists.ptr[dlnum].ptr+dlpos.ptr[dlnum];
619 ++dlpos.ptr[dlnum];
620 dl.adef = adef;
621 dl.aid = me;
622 dl.actorX = actorX;
623 dl.actorY = actorY;
625 if (auto isp = adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
626 drawAtXY(isp.tex, actorX-isp.vga.sx, actorY-isp.vga.sy, adef.zz);
627 } else {
628 //conwriteln("no animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
632 // process attached lights
633 if ((me.fget_flags&AF_NOLIGHT) == 0) {
634 uint alr = me.fget_attLightRGBX;
635 if ((alr&0xff) >= 4) {
636 // yep, add it
637 auto li = attachedLights.ptr+attachedLightCount;
638 ++attachedLightCount;
639 li.x = actorX+me.fget_attLightXOfs;
640 li.y = actorY+me.fget_attLightYOfs;
641 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
642 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
643 li.uncolored = true;
644 } else {
645 li.g = ((alr>>16)&0xff)/255.0f;
646 li.b = ((alr>>8)&0xff)/255.0f;
647 li.uncolored = false;
649 li.radius = (alr&0xff);
650 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
653 } else {
654 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
657 // draw actor lists
658 foreach_reverse (uint dlnum; 0..drawlists.length) {
659 auto dl = drawlists.ptr[dlnum].ptr;
660 if (dlnum == Players) dl += dlpos.ptr[dlnum]-1;
661 foreach (uint idx; 0..dlpos.ptr[dlnum]) {
662 auto me = dl.aid;
663 if (auto isp = dl.adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
664 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
665 isp.drawAtXY(dl.actorX, dl.actorY);
667 if (dlnum != Players) ++dl; else --dl;
670 if (camCenter && camchick.valid) {
671 int tiltHeight = /*getMapViewHeight()*/(vlHeight/scale)/4;
672 int vy = camchick.looky!int;
673 if (vy < -tiltHeight) vy = -tiltHeight; else if (vy > tiltHeight) vy = tiltHeight;
674 int swdt = vlWidth/scale;
675 int shgt = vlHeight/scale;
676 int x = camchickdi.actorX-swdt/2;
677 int y = (camchickdi.actorY+vy)-shgt/2;
678 if (x < 0) x = 0; else if (x >= map.width*8-swdt) x = map.width*8-swdt-1;
679 if (y < 0) y = 0; else if (y >= map.height*8-shgt) y = map.height*8-shgt-1;
680 mofsx = x*2;
681 mofsy = y*2;
682 vportX0 = mofsx/scale;
683 vportY0 = mofsy/scale;
684 vportX1 = vportX0+vlWidth/scale;
685 vportY1 = vportY0+vlHeight/scale;
687 //glDisable(GL_DEPTH_TEST);
688 // draw dots
689 drawAtXY(texParts, 0, 0);
690 // do liquid coloring
691 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
692 // foreground -- hide secrets, draw lifts and such
693 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
697 if (doLighting) {
698 // clear light layer
699 fboLevelLight.exec({
700 glDisable(GL_BLEND);
701 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
702 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
703 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
704 glClear(GL_COLOR_BUFFER_BIT);
707 // texture 1 is background
708 glActiveTexture(GL_TEXTURE0+1);
709 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
710 // texture 2 is occluders
711 glActiveTexture(GL_TEXTURE0+2);
712 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
713 // done texture assign
714 glActiveTexture(GL_TEXTURE0+0);
716 enum LYOfs = 1;
718 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
719 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
720 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
721 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
722 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
723 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
724 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
725 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
726 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
727 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
729 renderLight(24*8+4, (24+18)*8-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
731 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
733 // attached lights
734 foreach (ref li; attachedLights[0..attachedLightCount]) {
735 if (li.uncolored) {
736 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
737 } else {
738 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
743 if (testLightMoved) {
744 testLightX = testLightX/scale+mofsx/scale;
745 testLightY = testLightY/scale+mofsy/scale;
746 testLightMoved = false;
748 foreach (immutable _; 0..1) {
749 renderLight(testLightX, testLightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
753 glActiveTexture(GL_TEXTURE0+1);
754 glBindTexture(GL_TEXTURE_2D, 0);
755 glActiveTexture(GL_TEXTURE0+2);
756 glBindTexture(GL_TEXTURE_2D, 0);
757 glActiveTexture(GL_TEXTURE0+0);
760 // draw scaled level
762 shadScanlines.exec((Shader shad) {
763 shad["scanlines"] = scanlines;
764 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
765 glClear(GL_COLOR_BUFFER_BIT);
766 orthoCamera(vlWidth, vlHeight);
767 //orthoCamera(map.width*8*scale, map.height*8*scale);
768 //glMatrixMode(GL_MODELVIEW);
769 //glLoadIdentity();
770 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
771 // somehow, FBO objects are mirrored; wtf?!
772 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
773 //glLoadIdentity();
778 fboLevelLight.exec({
779 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
784 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
785 glDisable(GL_BLEND);
788 fboOrigBack.exec({
789 //auto img = smfont.ptr[0x39];
790 auto img = fftest;
791 if (img !is null) {
792 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
793 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
800 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
801 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
802 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
803 glDrawBuffers(1, buffers.ptr);
807 orthoCamera(vlWidth, vlHeight);
808 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
809 //mofsx &= ~1;
810 //mofsy &= ~1;
811 drawAtXY(tex, -mofsx, -mofsy, map.width*8*scale, map.height*8*scale, mirrorY:true);
813 doMessages(curtime);
817 // ////////////////////////////////////////////////////////////////////////// //
818 // returns time slept
819 int sleepAtMaxMsecs (int msecs) {
820 if (msecs > 0) {
821 import core.sys.posix.signal : timespec;
822 import core.sys.posix.time : nanosleep;
823 timespec ts = void, tpassed = void;
824 ts.tv_sec = 0;
825 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
826 nanosleep(&ts, &tpassed);
827 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
828 } else {
829 return 0;
834 // ////////////////////////////////////////////////////////////////////////// //
835 // rendering thread
836 shared int diedie = 0;
838 enum D2DFrameTime = 55; // milliseconds
839 enum MinFrameTime = 1000/60; // ~60 FPS
841 public void renderThread (Tid starterTid) {
842 send(starterTid, 42);
843 try {
844 MonoTime curtime = MonoTime.currTime;
846 lastthink = curtime; // for interpolator
847 nextthink = curtime+dur!"msecs"(D2DFrameTime);
848 MonoTime nextvframe = curtime;
850 enum MaxFPSFrames = 16;
851 float frtimes = 0.0f;
852 int framenum = 0;
853 int prevFPS = -1;
854 int hushFrames = 6; // ignore first `hushFrames` frames overtime
855 MonoTime prevFrameStartTime = curtime;
857 bool vframeWasLost = false;
859 void receiveMessages () {
860 for (;;) {
861 import core.time : Duration;
862 //conwriteln("rendering thread: waiting for messages...");
863 auto got = receiveTimeout(
864 Duration.zero, // don't wait
865 (TMsgMessage msg) {
866 addMessage(msg.text[0..msg.textlen], msg.pauseMsecs, msg.noreplace);
868 (TMsgLoadLevel msg) {
869 if (levelLoaded) {
870 conwriteln("ERROR: can't load new levels yet");
871 return;
873 auto mn = msg.mapfile[0..msg.textlen].idup;
874 if (mn.length == 0) {
875 conwriteln("ERROR: can't load empty level!");
877 conwriteln("loading map '", mn, "'");
878 loadMap(mn);
880 (TMsgIntOption msg) {
881 final switch (msg.type) with (TMsgIntOption.Type) {
882 case Scale:
883 if (msg.value >= 1 && msg.value <= 2) scale = msg.value;
884 break;
887 (TMsgBoolOption msg) {
888 final switch (msg.type) with (TMsgBoolOption.Type) {
889 case Interpolation:
890 if (msg.toggle) msg.value = !frameInterpolation;
891 if (frameInterpolation != msg.value) {
892 frameInterpolation = msg.value;
893 } else {
894 msg.showMessage = false;
896 break;
897 case Lighting:
898 if (msg.toggle) msg.value = !doLighting;
899 if (doLighting != msg.value) {
900 doLighting = msg.value;
901 } else {
902 msg.showMessage = false;
904 break;
905 case CheatNoDoors:
906 if (msg.toggle) msg.value = !cheatNoDoors;
907 if (cheatNoDoors != msg.value) {
908 cheatNoDoors = msg.value;
909 } else {
910 msg.showMessage = false;
912 break;
913 case CheatNoWallClip:
914 if (msg.toggle) msg.value = !cheatNoWallClip;
915 if (CheatNoWallClip != msg.value) {
916 cheatNoWallClip = msg.value;
917 } else {
918 msg.showMessage = false;
920 break;
922 if (msg.showMessage) {
923 char[128] mbuf;
924 uint msgpos;
925 void putStr(T) (T s) if (is(T : const(char)[])) {
926 foreach (char ch; s) {
927 if (msgpos >= mbuf.length) break;
928 mbuf.ptr[msgpos++] = ch;
931 putStr("Option \"");
932 { import std.conv : to; putStr(to!string(msg.type)); }
933 putStr("\": O");
934 if (msg.value) putStr("N"); else putStr("FF");
935 addMessage(mbuf[0..msgpos]);
938 (TMsgTestLightMove msg) {
939 testLightX = msg.x;
940 testLightY = msg.y;
941 testLightMoved = true;
943 (Variant v) {
944 conwriteln("WARNING: unknown thread message received and ignored");
947 if (!got) {
948 // no more messages
949 //conwriteln("rendering thread: no more messages");
950 break;
955 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
956 bool doThinkFrame () {
957 if (curtime >= nextthink) {
958 lastthink = curtime;
959 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
960 if (levelLoaded) {
961 // save snapshot and other data for interpolator
962 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
963 mapViewPosX[0] = mapViewPosX[1];
964 mapViewPosY[0] = mapViewPosY[1];
965 // process actors
966 doActorsThink();
967 dotThink();
969 // some timing
970 auto tm = MonoTime.currTime;
971 int thinkTime = cast(int)((tm-curtime).total!"msecs");
972 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
973 curtime = tm;
974 return true;
975 } else {
976 return false;
980 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
981 bool doVFrame () {
982 version(dont_use_vsync) {
983 // timer
984 enum doCheckTime = true;
985 } else {
986 // vsync
987 __gshared bool prevLost = false;
988 bool doCheckTime = vframeWasLost;
989 if (vframeWasLost) {
990 if (!prevLost) {
991 { import core.stdc.stdio; printf("frame was lost!\n"); }
993 prevLost = true;
994 } else {
995 prevLost = false;
998 if (doCheckTime) {
999 if (curtime < nextvframe) return false;
1000 version(dont_use_vsync) {
1001 if (curtime > nextvframe) {
1002 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
1003 if (overtime > 2500) {
1004 if (hushFrames) {
1005 --hushFrames;
1006 } else {
1007 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
1013 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
1014 bool ctset = false;
1016 sdwindow.mtLock();
1017 scope(exit) sdwindow.mtUnlock();
1018 ctset = sdwindow.setAsCurrentOpenGlContextNT;
1020 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1021 if (ctset) {
1022 // render scene
1023 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
1024 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1025 if (levelLoaded) {
1026 renderScene(curtime);
1027 } else {
1028 //renderLoading(curtime);
1030 sdwindow.mtLock();
1031 scope(exit) sdwindow.mtUnlock();
1032 sdwindow.swapOpenGlBuffers();
1033 glFinish();
1034 sdwindow.releaseCurrentOpenGlContext();
1035 vframeWasLost = false;
1036 } else {
1037 vframeWasLost = true;
1038 { import core.stdc.stdio; printf("xframe was lost!\n"); }
1040 curtime = MonoTime.currTime;
1041 return true;
1044 for (;;) {
1045 if (sdwindow.closed) break;
1046 if (atomicLoad(diedie) > 0) break;
1048 curtime = MonoTime.currTime;
1049 auto fstime = curtime;
1051 doThinkFrame(); // this will fix curtime if necessary
1052 if (doVFrame()) {
1053 if (!vframeWasLost) {
1054 // fps
1055 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
1056 prevFrameStartTime = curtime;
1057 frtimes += frameTime;
1058 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
1059 import std.string : format;
1060 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
1061 if (newFPS != prevFPS) {
1062 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
1063 prevFPS = newFPS;
1065 framenum = 0;
1066 frtimes = 0.0f;
1071 curtime = MonoTime.currTime;
1073 // now sleep until next "video" or "think" frame
1074 if (nextthink > curtime && nextvframe > curtime) {
1075 // let's decide
1076 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
1077 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
1078 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
1079 sleepAtMaxMsecs(sleepTime);
1080 //curtime = MonoTime.currTime;
1083 } catch (Exception e) {
1084 import core.stdc.stdio;
1085 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1086 for (;;) {
1087 if (sdwindow.closed) break;
1088 if (atomicLoad(diedie) > 0) break;
1089 sleepAtMaxMsecs(100);
1092 atomicStore(diedie, 2);
1096 // ////////////////////////////////////////////////////////////////////////// //
1097 __gshared Tid renderTid;
1098 shared bool renderThreadStarted = false;
1101 public void startRenderThread () {
1102 if (!cas(&renderThreadStarted, false, true)) {
1103 assert(0, "render thread already started!");
1105 renderTid = spawn(&renderThread, thisTid);
1106 setMaxMailboxSize(renderTid, 1024, OnCrowding.throwException); //FIXME
1107 // wait for "i'm ready" signal
1108 receive(
1109 (int ok) {
1110 if (ok != 42) assert(0, "wtf?!");
1113 conwriteln("rendering thread started");
1117 // ////////////////////////////////////////////////////////////////////////// //
1118 public void closeWindow () {
1119 if (atomicLoad(diedie) != 2) {
1120 atomicStore(diedie, 1);
1121 while (atomicLoad(diedie) != 2) {}
1123 if (!sdwindow.closed) {
1124 flushGui();
1125 sdwindow.close();
1130 // ////////////////////////////////////////////////////////////////////////// //
1131 // thread messages
1134 // ////////////////////////////////////////////////////////////////////////// //
1135 struct TMsgTestLightMove {
1136 int x, y;
1139 public void postTestLightMove (int x, int y) {
1140 if (!atomicLoad(renderThreadStarted)) return;
1141 auto msg = TMsgTestLightMove(x, y);
1142 send(renderTid, msg);
1146 // ////////////////////////////////////////////////////////////////////////// //
1147 struct TMsgMessage {
1148 char[256] text;
1149 uint textlen;
1150 int pauseMsecs;
1151 bool noreplace;
1154 public void postAddMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
1155 if (!atomicLoad(renderThreadStarted)) return;
1156 if (msgtext.length > TMsgMessage.text.length) msgtext = msgtext[0..TMsgMessage.text.length];
1157 TMsgMessage msg;
1158 msg.textlen = cast(uint)msgtext.length;
1159 if (msg.textlen) msg.text[0..msg.textlen] = msgtext[0..msg.textlen];
1160 msg.pauseMsecs = pauseMsecs;
1161 msg.noreplace = noreplace;
1162 send(renderTid, msg);
1166 // ////////////////////////////////////////////////////////////////////////// //
1167 struct TMsgLoadLevel {
1168 char[1024] mapfile;
1169 uint textlen;
1172 public void postLoadLevel (const(char)[] mapfile) {
1173 if (!atomicLoad(renderThreadStarted)) return;
1174 if (mapfile.length > TMsgLoadLevel.mapfile.length) mapfile = mapfile[0..TMsgLoadLevel.mapfile.length];
1175 TMsgLoadLevel msg;
1176 msg.textlen = cast(uint)mapfile.length;
1177 if (msg.textlen) msg.mapfile[0..msg.textlen] = mapfile[0..msg.textlen];
1178 send(renderTid, msg);
1182 // ////////////////////////////////////////////////////////////////////////// //
1183 struct TMsgIntOption {
1184 enum Type {
1185 Scale,
1187 Type type;
1188 int value;
1189 bool showMessage;
1193 struct TMsgBoolOption {
1194 enum Type {
1195 Interpolation,
1196 Lighting,
1197 CheatNoDoors,
1198 CheatNoWallClip,
1200 Type type;
1201 bool value;
1202 bool toggle;
1203 bool showMessage;
1207 bool strCaseEqu (const(char)[] s0, const(char)[] s1) {
1208 if (s0.length != s1.length) return false;
1209 foreach (immutable idx, char ch; s0) {
1210 if (ch >= 'A' && ch <= 'Z') ch += 32;
1211 char c1 = s1.ptr[idx];
1212 if (c1 >= 'A' && c1 <= 'Z') c1 += 32;
1213 if (ch != c1) return false;
1215 return true;
1219 public bool postToggleOption (const(char)[] name, bool showMessage=false) { pragma(inline, true); return postSetOption(name, true, showMessage:showMessage, toggle:true); }
1221 public bool postSetOption(T) (const(char)[] name, T value, bool showMessage=false, bool toggle=false) if ((is(T == int) || is(T == bool))) {
1222 if (!atomicLoad(renderThreadStarted)) return false;
1223 if (name.length == 0 || name.length > 127) return false;
1224 static if (is(T == int)) {
1225 TMsgIntOption msg;
1226 foreach (string oname; __traits(allMembers, TMsgIntOption.Type)) {
1227 if (strCaseEqu(oname, name)) {
1228 msg.type = __traits(getMember, TMsgIntOption.Type, oname);
1229 msg.value = value;
1230 msg.showMessage = showMessage;
1231 send(renderTid, msg);
1232 return true;
1235 } else static if (is(T == bool)) {
1236 TMsgBoolOption msg;
1237 foreach (string oname; __traits(allMembers, TMsgBoolOption.Type)) {
1238 if (strCaseEqu(oname, name)) {
1239 msg.type = __traits(getMember, TMsgBoolOption.Type, oname);
1240 msg.value = value;
1241 msg.toggle = toggle;
1242 msg.showMessage = showMessage;
1243 send(renderTid, msg);
1244 return true;
1247 } else {
1248 static assert(0, "invalid option type '"~T.stringof~"'");
1250 return false;