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;
28 import std
.concurrency
;
52 // ////////////////////////////////////////////////////////////////////////// //
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 // ////////////////////////////////////////////////////////////////////////// //
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
) {
101 int swdt
= vlWidth
/scale
;
102 int shgt
= vlHeight
/scale
;
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 // ////////////////////////////////////////////////////////////////////////// //
114 struct AttachedLightInfo
{
121 __gshared AttachedLightInfo
[65536] attachedLights
;
122 __gshared
uint attachedLightCount
= 0;
125 // ////////////////////////////////////////////////////////////////////////// //
126 enum MaxLightRadius
= 512;
129 // ////////////////////////////////////////////////////////////////////////// //
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 // ////////////////////////////////////////////////////////////////////////// //
141 public void initOpenGL () {
144 glEnable(GL_TEXTURE_2D
);
145 glDisable(GL_LIGHTING
);
146 glDisable(GL_DITHER
);
148 glDisable(GL_DEPTH_TEST
);
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;
160 shadToPolar
= new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar.frag"));
162 shadToPolar
= new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar_new.frag"));
164 shadToPolar
.exec((Shader shad
) {
166 shad
["texOccFull"] = 2;
169 shadBlur
= new Shader("light_blur", loadTextFile("data/shaders/srlight_blur.frag"));
170 shadBlur
.exec((Shader shad
) {
176 shadBlurOcc
= new Shader("light_blur_occ", loadTextFile("data/shaders/srlight_blur_occ.frag"));
177 shadBlurOcc
.exec((Shader shad
) {
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
190 glMatrixMode(GL_MODELVIEW
);
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);
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();
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];
239 { import core
.memory
: GC
; GC
.collect(); }
243 // ////////////////////////////////////////////////////////////////////////// //
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 () {
254 //mapTilesChanged = false;
255 //map.clearMegaTextures();
256 map
.oglBuildMega(mapTilesChanged
);
261 // ////////////////////////////////////////////////////////////////////////// //
264 enum Phase
{ FadeIn
, Stay
, FadeOut
}
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;
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;
295 if (!noreplace
&& messagesUsed
== 1) {
296 switch (messages
.ptr
[0].phase
) {
297 case Message
.Phase
.FadeIn
:
298 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
300 case Message
.Phase
.Stay
:
301 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
302 messages
.ptr
[0].alpha
= 255;
307 auto msg
= messages
.ptr
+messagesUsed
;
309 msg
.phase
= Message
.Phase
.FadeIn
;
311 msg
.pauseMsecs
= pauseMsecs
;
313 if (msgtext
.length
> msg
.text
.length
) {
314 msg
.text
= msgtext
[0..msg
.text
.length
];
315 msg
.textlen
= msg
.text
.length
;
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;
329 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
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);
344 case Message
.Phase
.Stay
:
345 if (msg
.removeTime
<= curtime
) {
347 msg
.phase
= Message
.Phase
.FadeOut
;
348 goto case; // to fade
350 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
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
];
359 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
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;
416 // draw shadow casters to fboOccludersId, light should be in the center
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);
437 drawAtXY(fboOccluders
[lightRadius
].tex
.tid
, 0, 0, lightSize
, 1);
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
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;
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); }
501 bool camCenter
= true;
502 if (/*altMove || movement ||*/ scale
== 1) {
509 vportX1
= map
.width
*8;
510 vportY1
= map
.height
*8;
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
));
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();
531 // build background layer
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);
543 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
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);
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
{
570 @disable this (this); // no copies
572 enum { Players
, Items
, Monsters
, Other
}
573 __gshared DrawInfo
[65536][4] drawlists
;
574 __gshared
uint[4] dlpos
;
580 Actor
.forEach((ActorId me
) {
581 //me.fprop_0drawlistpos = 0;
582 if (auto adef
= findActorDef(me
)) {
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
;
597 int oy
= xptr
.fgetp_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, ")");
607 if (!camchick
.valid
&& me
.flags
!uint&AF_CAMERACHICK
) {
609 camchickdi
.adef
= adef
;
611 camchickdi
.actorX
= actorX
;
612 camchickdi
.actorY
= actorY
;
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
];
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);
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) {
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) {
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
;
654 conwriteln("not found actor ", me
.id
, " (", me
.classtype
!string
, ":", me
.classname
!string
, ")");
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
]) {
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;
682 vportX0
= mofsx
/scale
;
683 vportY0
= mofsy
/scale
;
684 vportX1
= vportX0
+vlWidth
/scale
;
685 vportY1
= vportY0
+vlHeight
/scale
;
687 //glDisable(GL_DEPTH_TEST);
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);
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);
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);
734 foreach (ref li
; attachedLights
[0..attachedLightCount
]) {
736 renderLight(li
.x
, li
.y
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
), li
.radius
);
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);
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);
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);
779 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
784 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
789 //auto img = smfont.ptr[0x39];
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
);
811 drawAtXY(tex
, -mofsx
, -mofsy
, map
.width
*8*scale
, map
.height
*8*scale
, mirrorY
:true);
817 // ////////////////////////////////////////////////////////////////////////// //
818 // returns time slept
819 int sleepAtMaxMsecs (int msecs
) {
821 import core
.sys
.posix
.signal
: timespec
;
822 import core
.sys
.posix
.time
: nanosleep
;
823 timespec ts
= void, tpassed
= void;
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);
834 // ////////////////////////////////////////////////////////////////////////// //
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);
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;
854 int hushFrames
= 6; // ignore first `hushFrames` frames overtime
855 MonoTime prevFrameStartTime
= curtime
;
857 bool vframeWasLost
= false;
859 void receiveMessages () {
861 import core
.time
: Duration
;
862 //conwriteln("rendering thread: waiting for messages...");
863 auto got
= receiveTimeout(
864 Duration
.zero
, // don't wait
866 addMessage(msg
.text
[0..msg
.textlen
], msg
.pauseMsecs
, msg
.noreplace
);
868 (TMsgLoadLevel msg
) {
870 conwriteln("ERROR: can't load new levels yet");
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
, "'");
880 (TMsgIntOption msg
) {
881 final switch (msg
.type
) with (TMsgIntOption
.Type
) {
883 if (msg
.value
>= 1 && msg
.value
<= 2) scale
= msg
.value
;
887 (TMsgBoolOption msg
) {
888 final switch (msg
.type
) with (TMsgBoolOption
.Type
) {
890 if (msg
.toggle
) msg
.value
= !frameInterpolation
;
891 if (frameInterpolation
!= msg
.value
) {
892 frameInterpolation
= msg
.value
;
894 msg
.showMessage
= false;
898 if (msg
.toggle
) msg
.value
= !doLighting
;
899 if (doLighting
!= msg
.value
) {
900 doLighting
= msg
.value
;
902 msg
.showMessage
= false;
906 if (msg
.toggle
) msg
.value
= !cheatNoDoors
;
907 if (cheatNoDoors
!= msg
.value
) {
908 cheatNoDoors
= msg
.value
;
910 msg
.showMessage
= false;
913 case CheatNoWallClip
:
914 if (msg
.toggle
) msg
.value
= !cheatNoWallClip
;
915 if (CheatNoWallClip
!= msg
.value
) {
916 cheatNoWallClip
= msg
.value
;
918 msg
.showMessage
= false;
922 if (msg
.showMessage
) {
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
;
932 { import std
.conv
: to
; putStr(to
!string(msg
.type
)); }
934 if (msg
.value
) putStr("N"); else putStr("FF");
935 addMessage(mbuf
[0..msgpos
]);
938 (TMsgTestLightMove msg
) {
941 testLightMoved
= true;
944 conwriteln("WARNING: unknown thread message received and ignored");
949 //conwriteln("rendering thread: no more messages");
955 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
956 bool doThinkFrame () {
957 if (curtime
>= nextthink
) {
959 while (nextthink
<= curtime
) nextthink
+= dur
!"msecs"(D2DFrameTime
);
961 // save snapshot and other data for interpolator
962 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
963 mapViewPosX
[0] = mapViewPosX
[1];
964 mapViewPosY
[0] = mapViewPosY
[1];
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
); }
980 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
982 version(dont_use_vsync
) {
984 enum doCheckTime
= true;
987 __gshared
bool prevLost
= false;
988 bool doCheckTime
= vframeWasLost
;
991 { import core
.stdc
.stdio
; printf("frame was lost!\n"); }
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) {
1007 { import core
.stdc
.stdio
; printf(" spent whole %d msecs\n", overtime
); }
1013 while (nextvframe
<= curtime
) nextvframe
+= dur
!"msecs"(MinFrameTime
);
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
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
1026 renderScene(curtime
);
1028 //renderLoading(curtime);
1031 scope(exit
) sdwindow
.mtUnlock();
1032 sdwindow
.swapOpenGlBuffers();
1034 sdwindow
.releaseCurrentOpenGlContext();
1035 vframeWasLost
= false;
1037 vframeWasLost
= true;
1038 { import core
.stdc
.stdio
; printf("xframe was lost!\n"); }
1040 curtime
= MonoTime
.currTime
;
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
1053 if (!vframeWasLost
) {
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
);
1071 curtime
= MonoTime
.currTime
;
1073 // now sleep until next "video" or "think" frame
1074 if (nextthink
> curtime
&& nextvframe
> curtime
) {
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");
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
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
) {
1130 // ////////////////////////////////////////////////////////////////////////// //
1134 // ////////////////////////////////////////////////////////////////////////// //
1135 struct TMsgTestLightMove
{
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
{
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
];
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
{
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
];
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
{
1193 struct TMsgBoolOption
{
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;
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)) {
1226 foreach (string oname
; __traits(allMembers
, TMsgIntOption
.Type
)) {
1227 if (strCaseEqu(oname
, name
)) {
1228 msg
.type
= __traits(getMember
, TMsgIntOption
.Type
, oname
);
1230 msg
.showMessage
= showMessage
;
1231 send(renderTid
, msg
);
1235 } else static if (is(T
== bool)) {
1237 foreach (string oname
; __traits(allMembers
, TMsgBoolOption
.Type
)) {
1238 if (strCaseEqu(oname
, name
)) {
1239 msg
.type
= __traits(getMember
, TMsgBoolOption
.Type
, oname
);
1241 msg
.toggle
= toggle
;
1242 msg
.showMessage
= showMessage
;
1243 send(renderTid
, msg
);
1248 static assert(0, "invalid option type '"~T
.stringof
~"'");