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 xmain_d2d
is aliced
;
45 // ////////////////////////////////////////////////////////////////////////// //
50 // ////////////////////////////////////////////////////////////////////////// //
51 public __gshared
bool cheatNoDoors
= false;
54 // ////////////////////////////////////////////////////////////////////////// //
55 __gshared SimpleWindow sdwindow
;
58 public enum vlWidth
= 800;
59 public enum vlHeight
= 800;
60 public __gshared
int scale
= 1;
63 // ////////////////////////////////////////////////////////////////////////// //
64 __gshared
bool scanlines
= false;
65 __gshared
bool doLighting
= true;
68 // ////////////////////////////////////////////////////////////////////////// //
70 __gshared
ubyte[] prevFrameActorsData
;
71 __gshared
uint[65536] prevFrameActorOfs
; // uint.max-1: dead; uint.max: last
72 __gshared MonoTime lastthink
= MonoTime
.zero
; // for interpolator
73 __gshared MonoTime nextthink
= MonoTime
.zero
;
74 __gshared
bool frameInterpolation
= true;
77 __gshared
int[2] mapViewPosX
, mapViewPosY
; // [0]: previous frame -- for interpolator
80 // this should be screen center
81 public void setMapViewPos (int x
, int y
) {
87 int swdt
= vlWidth
/scale
;
88 int shgt
= vlHeight
/scale
;
91 if (x
< 0) x
= 0; else if (x
>= map
.width
*8-swdt
) x
= map
.width
*8-swdt
-1;
92 if (y
< 0) y
= 0; else if (y
>= map
.height
*8-shgt
) y
= map
.height
*8-shgt
-1;
93 mapViewPosX
[1] = x
*scale
;
94 mapViewPosY
[1] = y
*scale
;
98 // ////////////////////////////////////////////////////////////////////////// //
100 struct AttachedLightInfo
{
107 __gshared AttachedLightInfo
[65536] attachedLights
;
108 __gshared
uint attachedLightCount
= 0;
111 // ////////////////////////////////////////////////////////////////////////// //
112 enum MaxLightRadius
= 512;
115 // ////////////////////////////////////////////////////////////////////////// //
117 __gshared FBO
[MaxLightRadius
+1] fboOccluders
, fboShadowMap
;
118 __gshared Shader shadToPolar
, shadBlur
, shadBlurOcc
;
120 __gshared FBO fboLevel
, fboLevelLight
, fboOrigBack
;
121 __gshared Shader shadScanlines
;
122 __gshared Shader shadLiquidDistort
;
125 // ////////////////////////////////////////////////////////////////////////// //
127 glEnable(GL_TEXTURE_2D
);
128 glDisable(GL_LIGHTING
);
129 glDisable(GL_DITHER
);
131 glDisable(GL_DEPTH_TEST
);
134 shadScanlines
= new Shader("scanlines", loadTextFile("data/shaders/srscanlines.frag"));
136 shadLiquidDistort
= new Shader("liquid_distort", loadTextFile("data/shaders/srliquid_distort.frag"));
137 shadLiquidDistort
.exec((Shader shad
) { shad
["tex0"] = 0; });
140 shadToPolar
= new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar.frag"));
141 shadBlur
= new Shader("light_blur", loadTextFile("data/shaders/srlight_blur.frag"));
142 shadBlur
.exec((Shader shad
) {
147 shadBlurOcc
= new Shader("light_blur_occ", loadTextFile("data/shaders/srlight_blur_occ.frag"));
148 shadBlurOcc
.exec((Shader shad
) {
154 foreach (int sz
; 2..MaxLightRadius
+1) {
155 fboOccluders
[sz
] = new FBO(sz
*2, sz
*2, Texture
.Option
.Clamp
, Texture
.Option
.Linear
); // create occluders FBO
156 fboShadowMap
[sz
] = new FBO(sz
*2, 1, Texture
.Option
.Clamp
); // create 1d shadowmap FBO
160 glMatrixMode(GL_MODELVIEW
);
164 mapTilesChanged
= false;
166 fboLevel
= new FBO(map
.width
*8, map
.height
*8, Texture
.Option
.Nearest
); // final level render will be here
167 fboLevelLight
= new FBO(map
.width
*8, map
.height
*8, Texture
.Option
.Nearest
); // level lights will be rendered here
168 //fboForeground = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level foreground
169 fboOrigBack
= new FBO(map
.width
*8, map
.height
*8, Texture
.Option
.Nearest
); // background+foreground
171 shadBlur
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*8, map
.height
*8); });
172 shadBlurOcc
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*8, map
.height
*8); });
174 glActiveTexture(GL_TEXTURE0
+0);
175 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
176 orthoCamera(vlWidth
, vlHeight
);
180 Actor
.resetStorage();
183 // save first snapshot
184 prevFrameActorsData
= new ubyte[](Actor
.actorSize
*65536); // ~15-20 megabytes
185 prevFrameActorOfs
[] = uint.max
; // just for fun
186 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
187 mapViewPosX
[0] = mapViewPosX
[1];
188 mapViewPosY
[0] = mapViewPosY
[1];
190 { import core
.memory
: GC
; GC
.collect(); }
194 // ////////////////////////////////////////////////////////////////////////// //
196 __gshared
bool mapTilesChanged
= false;
199 public void mapDirty () { mapTilesChanged
= true; }
201 void rebuildMapMegaTextures () {
203 mapTilesChanged
= false;
204 map
.clearMegaTextures();
209 // ////////////////////////////////////////////////////////////////////////// //
210 void renderLight() (int lightX
, int lightY
, in auto ref SVec4F lcol
, int lightRadius
) {
211 if (lightRadius
< 2) return;
212 if (lightRadius
> MaxLightRadius
) lightRadius
= MaxLightRadius
;
213 int lightSize
= lightRadius
*2;
214 // is this light visible?
215 if (lightX
<= -lightRadius || lightY
<= -lightRadius || lightX
-lightRadius
>= map
.width
*8 || lightY
-lightRadius
>= map
.height
*8) return;
217 // draw shadow casters to fboOccludersId, light should be in the center
220 fboOccluders
[lightRadius
].exec({
221 //glDisable(GL_BLEND);
222 glColor3f(0.0f, 0.0f, 0.0f);
223 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
224 glClear(GL_COLOR_BUFFER_BIT
);
225 orthoCamera(lightSize
, lightSize
);
226 drawAtXY(map
.texgl
.ptr
[map
.LightMask
], lightRadius
-lightX
, lightRadius
-lightY
);
229 // build 1d shadow map to fboShadowMapId
230 fboShadowMap
[lightRadius
].exec({
231 shadToPolar
.exec((Shader shad
) {
232 //glDisable(GL_BLEND);
233 glColor3f(0.0f, 0.0f, 0.0f);
234 shad
["lightTexSize"] = SVec2F(lightSize
, lightSize
);
235 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
236 glClear(GL_COLOR_BUFFER_BIT
);
237 orthoCamera(lightSize
, 1);
238 drawAtXY(fboOccluders
[lightRadius
].tex
.tid
, 0, 0, lightSize
, 1);
242 // build light texture for blending
243 fboOccluders
[lightRadius
].exec({
244 // no need to clear it, shader will take care of that
245 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
246 //glClear(GL_COLOR_BUFFER_BIT);
247 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
248 //glDisable(GL_BLEND);
249 shadBlur
.exec((Shader shad
) {
250 shad
["lightTexSize"] = SVec2F(lightSize
, lightSize
);
251 shad
["lightColor"] = SVec4F(lcol
.x
, lcol
.y
, lcol
.z
, lcol
.w
);
252 shad
["lightPos"] = SVec2F(lightX
, lightY
);
253 orthoCamera(lightSize
, lightSize
);
254 drawAtXY(fboShadowMap
[lightRadius
].tex
.tid
, 0, 0, lightSize
, lightSize
);
258 // blend light texture
261 glBlendFunc(GL_SRC_ALPHA
, GL_ONE
);
262 orthoCamera(map
.width
*8, map
.height
*8);
263 drawAtXY(fboOccluders
[lightRadius
].tex
, lightX
-lightRadius
, lightY
-lightRadius
, mirrorY
:true);
264 // and blend it again, somewhat bigger, with the shader that will touch only occluders
266 shadBlurOcc
.exec((Shader shad
) {
267 shad
["lightTexSize"] = SVec2F(lightSize
, lightSize
);
268 shad
["lightColor"] = SVec4F(lcol
.x
, lcol
.y
, lcol
.z
, lcol
.w
);
269 shad
["lightPos"] = SVec2F(lightX
, lightY
);
270 drawAtXY(fboOccluders
[lightRadius
].tex
.tid
, lightX
-lightRadius
-szmore
, lightY
-lightRadius
-szmore
, lightSize
+szmore
*2, lightSize
+szmore
*2, mirrorY
:true);
276 // ////////////////////////////////////////////////////////////////////////// //
279 enum Phase
{ FadeIn
, Stay
, FadeOut
}
288 private import core
.sync
.mutex
: Mutex
;
290 __gshared Message
[128] messages
;
291 __gshared
uint messagesUsed
= 0;
292 __gshared Mutex messageLock
;
294 shared static this () { messageLock
= new Mutex(); }
297 void addMessage (const(char)[] msgtext
, int pauseMsecs
=3000, bool noreplace
=false) {
299 scope(exit
) messageLock
.unlock();
300 if (msgtext
.length
== 0) return;
302 if (pauseMsecs
<= 50) return;
303 if (messagesUsed
== messages
.length
) {
304 // remove top message
305 foreach (immutable cidx
; 1..messagesUsed
) messages
.ptr
[cidx
-1] = messages
.ptr
[cidx
];
306 messages
.ptr
[0].alpha
= 255;
310 if (!noreplace
&& messagesUsed
== 1) {
311 switch (messages
.ptr
[0].phase
) {
312 case Message
.Phase
.FadeIn
:
313 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
315 case Message
.Phase
.Stay
:
316 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
317 messages
.ptr
[0].alpha
= 255;
322 auto msg
= messages
.ptr
+messagesUsed
;
324 msg
.phase
= Message
.Phase
.FadeIn
;
326 msg
.pauseMsecs
= pauseMsecs
;
328 if (msgtext
.length
> msg
.text
.length
) {
329 msg
.text
= msgtext
[0..msg
.text
.length
];
330 msg
.textlen
= msg
.text
.length
;
332 msg
.text
[0..msgtext
.length
] = msgtext
[];
333 msg
.textlen
= msgtext
.length
;
338 void doMessages (MonoTime curtime
) {
340 scope(exit
) messageLock
.unlock();
342 if (messagesUsed
== 0) return;
344 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
350 final switch (msg
.phase
) {
351 case Message
.Phase
.FadeIn
:
352 if ((msg
.alpha
+= 10) >= 255) {
353 msg
.phase
= Message
.Phase
.Stay
;
354 msg
.removeTime
= curtime
+dur
!"msecs"(msg
.pauseMsecs
);
355 goto case; // to stay
357 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
359 case Message
.Phase
.Stay
:
360 if (msg
.removeTime
<= curtime
) {
362 msg
.phase
= Message
.Phase
.FadeOut
;
363 goto case; // to fade
365 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
367 case Message
.Phase
.FadeOut
:
368 if ((msg
.alpha
-= 10) <= 0) {
369 if (--messagesUsed
== 0) return;
370 // remove this message
371 foreach (immutable cidx
; 1..messagesUsed
+1) messages
.ptr
[cidx
-1] = messages
.ptr
[cidx
];
374 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
378 smDrawText(10, 10, msg
.text
[0..msg
.textlen
]);
382 // ////////////////////////////////////////////////////////////////////////// //
383 mixin(Actor
.FieldGetMixin
!("classtype", StrId
)); // fget_classtype
384 mixin(Actor
.FieldGetMixin
!("classname", StrId
)); // fget_classname
385 mixin(Actor
.FieldGetMixin
!("x", int));
386 mixin(Actor
.FieldGetMixin
!("y", int));
387 mixin(Actor
.FieldGetMixin
!("flags", uint));
388 mixin(Actor
.FieldGetMixin
!("zAnimstate", StrId
));
389 mixin(Actor
.FieldGetMixin
!("zAnimidx", int));
390 mixin(Actor
.FieldGetMixin
!("dir", uint));
391 mixin(Actor
.FieldGetMixin
!("attLightXOfs", int));
392 mixin(Actor
.FieldGetMixin
!("attLightYOfs", int));
393 mixin(Actor
.FieldGetMixin
!("attLightRGBX", uint));
395 mixin(Actor
.FieldGetPtrMixin
!("classtype", StrId
)); // fget_classtype
396 mixin(Actor
.FieldGetPtrMixin
!("classname", StrId
)); // fget_classname
397 mixin(Actor
.FieldGetPtrMixin
!("x", int));
398 mixin(Actor
.FieldGetPtrMixin
!("y", int));
399 mixin(Actor
.FieldGetPtrMixin
!("flags", uint));
400 mixin(Actor
.FieldGetPtrMixin
!("zAnimstate", StrId
));
401 mixin(Actor
.FieldGetPtrMixin
!("zAnimidx", int));
402 mixin(Actor
.FieldGetPtrMixin
!("dir", uint));
403 mixin(Actor
.FieldGetPtrMixin
!("attLightXOfs", int));
404 mixin(Actor
.FieldGetPtrMixin
!("attLightYOfs", int));
405 mixin(Actor
.FieldGetPtrMixin
!("attLightRGBX", uint));
408 // ////////////////////////////////////////////////////////////////////////// //
409 __gshared
int lightX
= vlWidth
/2, lightY
= vlHeight
/2;
410 __gshared
int mapOfsX
, mapOfsY
;
411 __gshared
bool movement
= false;
412 __gshared
float iLiquidTime
= 0.0;
413 __gshared
bool altMove
= false;
416 void renderScene (MonoTime curtime
) {
417 //enum BackIntens = 0.05f;
418 enum BackIntens
= 0.0f;
420 float atob
= (curtime
> lastthink ?
cast(float)((curtime
-lastthink
).total
!"msecs")/cast(float)((nextthink
-lastthink
).total
!"msecs") : 1.0f);
421 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
424 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
425 int curfp = cast(int)((curtime-lastthink).total!"msecs");
426 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
432 if (mapTilesChanged
) rebuildMapMegaTextures();
434 // build background layer
436 //glDisable(GL_BLEND);
437 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
438 glClear(GL_COLOR_BUFFER_BIT
);
439 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
440 orthoCamera(map
.width
*8, map
.height
*8);
442 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
445 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
446 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2, map.MapSize*8, map.MapSize*8);
447 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
448 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*8, map.MapSize*8);
450 drawAtXY(map
.skytexgl
.tid
, 0, 0, map
.MapSize
*8, map
.MapSize
*8);
452 drawAtXY(map
.texgl
.ptr
[map
.Back
], 0, 0);
453 // draw distorted liquid areas
454 shadLiquidDistort
.exec((Shader shad
) {
455 shad
["iDistortTime"] = iLiquidTime
;
456 drawAtXY(map
.texgl
.ptr
[map
.AllLiquids
], 0, 0);
458 // monsters, items; we'll do linear interpolation here
459 // we need this for saved frame anyway, so let's play dirty and speed up the things
460 glColor3f(1.0f, 1.0f, 1.0f);
461 attachedLightCount
= 0;
462 Actor
.forEach((ActorId me
) {
463 if (auto adef
= findActorDef(me
)) {
464 int actorX
, actorY
; // current actor position
466 auto ofs
= prevFrameActorOfs
.ptr
[me
.id
&0xffff];
467 if (frameInterpolation
&& ofs
< uint.max
-1 && Actor
.isSameSavedActor(me
.id
, prevFrameActorsData
.ptr
, ofs
)) {
468 import core
.stdc
.math
: roundf
;
469 auto xptr
= prevFrameActorsData
.ptr
+ofs
;
470 int ox
= xptr
.fgetp_x
;
472 int oy
= xptr
.fgetp_y
;
474 actorX
= cast(int)(ox
+roundf((nx
-ox
)*atob
));
475 actorY
= cast(int)(oy
+roundf((ny
-oy
)*atob
));
476 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
483 if ((me
.fget_flags
&AF_NODRAW
) == 0) {
484 if (auto isp
= adef
.animSpr(me
.fget_zAnimstate
, me
.fget_dir
, me
.fget_zAnimidx
)) {
485 drawAtXY(isp
.tex
, actorX
-isp
.vga
.sx
, actorY
-isp
.vga
.sy
);
487 //conwriteln("no animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
490 // process attached lights
491 if ((me
.fget_flags
&AF_NOLIGHT
) == 0) {
492 uint alr
= me
.fget_attLightRGBX
;
493 if ((alr
&0xff) >= 4) {
495 auto li
= attachedLights
.ptr
+attachedLightCount
;
496 ++attachedLightCount
;
497 li
.x
= actorX
+me
.fget_attLightXOfs
;
498 li
.y
= actorY
+me
.fget_attLightYOfs
;
499 li
.r
= ((alr
>>24)&0xff)/255.0f; // red or intensity
500 if ((alr
&0x00_ff_ff
_00U) == 0x00_00_01_00U) {
503 li
.g
= ((alr
>>16)&0xff)/255.0f;
504 li
.b
= ((alr
>>8)&0xff)/255.0f;
505 li
.uncolored
= false;
507 li
.radius
= (alr
&0xff);
508 if (li
.radius
> MaxLightRadius
) li
.radius
= MaxLightRadius
;
512 conwriteln("not found actor ", me
.id
, " (", me
.classtype
!string
, ":", me
.classname
!string
, ")");
515 // do liquid coloring
516 drawAtXY(map
.texgl
.ptr
[map
.LiquidMask
], 0, 0);
517 // foreground -- hide secrets, draw lifts and such
518 drawAtXY(map
.texgl
.ptr
[map
.Front
], 0, 0);
526 glClearColor(BackIntens
, BackIntens
, BackIntens
, 1.0f);
527 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
528 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
529 glClear(GL_COLOR_BUFFER_BIT
);
532 // texture 1 is background
533 glActiveTexture(GL_TEXTURE0
+1);
534 glBindTexture(GL_TEXTURE_2D
, fboOrigBack
.tex
.tid
);
535 // texture 2 is occluders
536 glActiveTexture(GL_TEXTURE0
+2);
537 glBindTexture(GL_TEXTURE_2D
, map
.texgl
.ptr
[map
.LightMask
].tid
);
538 // done texture assign
539 glActiveTexture(GL_TEXTURE0
+0);
543 renderLight( 27, 391-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
544 renderLight(542, 424-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
545 renderLight(377, 368-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
546 renderLight(147, 288-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
547 renderLight( 71, 200-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
548 renderLight(249, 200-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
549 renderLight(426, 200-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
550 renderLight(624, 200-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
551 renderLight(549, 298-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
552 renderLight( 74, 304-0+LYOfs
, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
554 renderLight(24*8+4, (24+18)*8-2+LYOfs
, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
557 foreach (ref li
; attachedLights
[0..attachedLightCount
]) {
559 renderLight(li
.x
, li
.y
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
), li
.radius
);
561 renderLight(li
.x
, li
.y
, SVec4F(li
.r
, li
.g
, li
.b
, 1.0f), li
.radius
);
565 foreach (immutable _
; 0..1) {
566 renderLight(lightX
, lightY
, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
569 glActiveTexture(GL_TEXTURE0
+1);
570 glBindTexture(GL_TEXTURE_2D
, 0);
571 glActiveTexture(GL_TEXTURE0
+2);
572 glBindTexture(GL_TEXTURE_2D
, 0);
573 glActiveTexture(GL_TEXTURE0
+0);
578 shadScanlines.exec((Shader shad) {
579 shad["scanlines"] = scanlines;
580 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
581 glClear(GL_COLOR_BUFFER_BIT);
582 orthoCamera(vlWidth, vlHeight);
583 //orthoCamera(map.width*8*scale, map.height*8*scale);
584 //glMatrixMode(GL_MODELVIEW);
586 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
587 // somehow, FBO objects are mirrored; wtf?!
588 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
595 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
600 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
605 //auto img = smfont.ptr[0x39];
608 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
609 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
616 if (altMove || movement || scale
== 1) {
620 if (frameInterpolation
) {
621 import core
.stdc
.math
: roundf
;
622 mofsx
= cast(int)(mapViewPosX
[0]+roundf((mapViewPosX
[1]-mapViewPosX
[0])*atob
));
623 mofsy
= cast(int)(mapViewPosY
[0]+roundf((mapViewPosY
[1]-mapViewPosY
[0])*atob
));
625 mofsx
= mapViewPosX
[1];
626 mofsy
= mapViewPosY
[1];
630 orthoCamera(vlWidth
, vlHeight
);
631 auto tex
= (doLighting ? fboLevelLight
.tex
.tid
: fboOrigBack
.tex
.tid
);
632 drawAtXY(tex
, -mofsx
, -mofsy
, map
.width
*8*scale
, map
.height
*8*scale
, mirrorY
:true);
638 // ////////////////////////////////////////////////////////////////////////// //
639 // returns time slept
640 int sleepAtMaxMsecs (int msecs
) {
642 import core
.sys
.posix
.signal
: timespec
;
643 import core
.sys
.posix
.time
: nanosleep
;
644 timespec ts
= void, tpassed
= void;
646 ts
.tv_nsec
= msecs
*1000*1000+(500*1000); // milli to nano
647 nanosleep(&ts
, &tpassed
);
648 return (ts
.tv_nsec
-tpassed
.tv_nsec
)/(1000*1000);
655 // ////////////////////////////////////////////////////////////////////////// //
657 shared int diedie
= 0;
659 enum D2DFrameTime
= 55; // milliseconds
660 enum MinFrameTime
= 1000/60; // ~60 FPS
662 void renderThread () {
664 version(use_vsync
) {} else MonoTime ltt
= MonoTime
.currTime
;
666 MonoTime curtime
= MonoTime
.currTime
;
668 lastthink
= curtime
; // for interpolator
669 nextthink
= curtime
+dur
!"msecs"(D2DFrameTime
);
670 MonoTime nextvframe
= curtime
;
672 enum MaxFPSFrames
= 16;
673 float frtimes
= 0.0f;
676 int hushFrames
= 6; // ignore first `hushFrames` frames overtime
677 MonoTime prevFrameStartTime
= curtime
;
679 bool vframeWasLost
= false;
681 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
682 bool doThinkFrame () {
683 if (curtime
>= nextthink
) {
685 while (nextthink
<= curtime
) nextthink
+= dur
!"msecs"(D2DFrameTime
);
686 // save snapshot and other datafor interpolator
687 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
688 mapViewPosX
[0] = mapViewPosX
[1];
689 mapViewPosY
[0] = mapViewPosY
[1];
693 auto tm
= MonoTime
.currTime
;
694 int thinkTime
= cast(int)((tm
-curtime
).total
!"msecs");
695 if (thinkTime
> 9) { import core
.stdc
.stdio
; printf("spent on thinking: %d msecs\n", thinkTime
); }
703 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
706 __gshared
bool prevLost
= false;
707 bool doCheckTime
= vframeWasLost
;
710 { import core
.stdc
.stdio
; printf("frame was lost!\n"); }
717 enum doCheckTime
= true;
720 if (curtime
< nextvframe
) return false;
721 version(use_vsync
) {} else {
722 if (curtime
> nextvframe
) {
723 auto overtime
= cast(int)((curtime
-nextvframe
).total
!"msecs");
724 if (overtime
> 2500) {
728 { import core
.stdc
.stdio
; printf(" spent whole %d msecs\n", overtime
); }
734 while (nextvframe
<= curtime
) nextvframe
+= dur
!"msecs"(MinFrameTime
);
738 scope(exit
) sdwindow
.mtUnlock();
739 ctset
= sdwindow
.setAsCurrentOpenGlContextNT
;
741 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
744 iLiquidTime
= cast(float)((curtime
-MonoTime
.zero
).total
!"msecs"%10000000)/18.0f*0.04f;
745 renderScene(curtime
);
747 scope(exit
) sdwindow
.mtUnlock();
748 sdwindow
.swapOpenGlBuffers();
750 sdwindow
.releaseCurrentOpenGlContext();
751 vframeWasLost
= false;
753 vframeWasLost
= true;
754 { import core
.stdc
.stdio
; printf("xframe was lost!\n"); }
756 curtime
= MonoTime
.currTime
;
761 if (sdwindow
.closed
) break;
762 if (atomicLoad(diedie
) > 0) break;
764 curtime
= MonoTime
.currTime
;
765 auto fstime
= curtime
;
767 doThinkFrame(); // this will fix curtime if necessary
769 if (!vframeWasLost
) {
771 auto frameTime
= cast(float)(curtime
-prevFrameStartTime
).total
!"msecs"/1000.0f;
772 prevFrameStartTime
= curtime
;
773 frtimes
+= frameTime
;
774 if (++framenum
>= MaxFPSFrames || frtimes
>= 3.0f) {
775 import std
.string
: format
;
776 int newFPS
= cast(int)(cast(float)MaxFPSFrames
/frtimes
+0.5);
777 if (newFPS
!= prevFPS
) {
778 sdwindow
.title
= "%s / FPS:%s".format("D2D", newFPS
);
787 curtime
= MonoTime
.currTime
;
789 // now sleep until next "video" or "think" frame
790 if (nextthink
> curtime
&& nextvframe
> curtime
) {
792 immutable nextVideoFrameSleep
= cast(int)((nextvframe
-curtime
).total
!"msecs");
793 immutable nextThinkFrameSleep
= cast(int)((nextthink
-curtime
).total
!"msecs");
794 immutable sleepTime
= (nextVideoFrameSleep
< nextThinkFrameSleep ? nextVideoFrameSleep
: nextThinkFrameSleep
);
795 sleepAtMaxMsecs(sleepTime
);
796 //curtime = MonoTime.currTime;
799 } catch (Exception e
) {
800 import core
.stdc
.stdio
;
801 fprintf(stderr
, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
803 if (sdwindow
.closed
) break;
804 if (atomicLoad(diedie
) > 0) break;
805 //{ import core.stdc.stdio; printf(" spent only %d msecs\n", cast(int)((time-ltt).total!"msecs")); }
806 sleepAtMaxMsecs(100);
809 atomicStore(diedie
, 2);
813 // ////////////////////////////////////////////////////////////////////////// //
814 void closeWindow () {
815 if (atomicLoad(diedie
) != 2) {
816 atomicStore(diedie
, 1);
817 while (atomicLoad(diedie
) != 2) {}
819 if (!sdwindow
.closed
) {
826 // ////////////////////////////////////////////////////////////////////////// //
827 __gshared Thread renderTid
;
830 void main (string
[] args
) {
831 FuncPool
.dumpCode
= false;
832 FuncPool
.dumpCodeSize
= false;
833 dacsDumpSemantic
= false;
835 //version(rdmd) { dacsOptimize = 0; }
836 bool compileOnly
= false;
838 for (usize idx
= 1; idx
< args
.length
; ++idx
) {
840 if (args
[idx
] == "--dump-code") FuncPool
.dumpCode
= true;
841 else if (args
[idx
] == "--dump-code-size") FuncPool
.dumpCodeSize
= true;
842 else if (args
[idx
] == "--dump-semantic") dacsDumpSemantic
= true;
843 else if (args
[idx
] == "--dump-all") { FuncPool
.dumpCode
= true; FuncPool
.dumpCodeSize
= true; dacsDumpSemantic
= true; }
844 else if (args
[idx
] == "--compile") compileOnly
= true;
845 else if (args
[idx
] == "--compile-only") compileOnly
= true;
846 else if (args
[idx
] == "--messages") ++dacsMessages
;
847 else if (args
[idx
] == "--no-copro") dacsOptimizeNoCoPro
= true;
848 else if (args
[idx
] == "--no-deadass") dacsOptimizeNoDeadAss
= true;
849 else if (args
[idx
] == "--no-purekill") dacsOptimizeNoPureKill
= true;
850 else if (args
[idx
].length
> 2 && args
[idx
][0..2] == "-O") {
851 import std
.conv
: to
;
852 ubyte olevel
= to
!ubyte(args
[idx
][2..$]);
853 dacsOptimize
= olevel
;
857 foreach (immutable c
; idx
+1..args
.length
) args
.ptr
[c
-1] = args
.ptr
[c
];
863 static void setDP () {
867 import std
.file
: thisExePath
;
868 import std
.path
: dirName
;
869 setDataPath(thisExePath
.dirName
);
871 addPK3(getDataPath
~"base.pk3"); loadWadScripts();
872 //addWad("/home/ketmar/k8prj/doom2d-tl/data/doom2d.wad"); loadWadScripts();
873 //addWad("/home/ketmar/k8prj/doom2d-tl/data/meat.wad"); loadWadScripts();
874 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm.wad"); loadWadScripts();
875 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm1.wad"); loadWadScripts();
876 //addWad("/home/ketmar/k8prj/doom2d-tl/data/superdm.wad"); loadWadScripts();
877 //addWad("/home/ketmar/k8prj/doom2d-tl/data/zadoomka.wad"); loadWadScripts();
878 scriptLoadingComplete();
883 if (compileOnly
) return;
889 setOpenGLContextVersion(3, 2); // up to GLSL 150
890 //openGLContextCompatible = false;
892 map
= new LevelMap("maps/map01.d2m");
893 ugInit(map
.width
*8, map
.height
*8);
899 map
.getThingPos(1/*ThingId.Player1*/, &mapOfsX
, &mapOfsY
);
902 mapOfsX = (mapOfsX*2)-vlWidth/2;
903 if (mapOfsX+vlWidth > map.width*16) mapOfsX = map.width*16-vlWidth;
904 if (mapOfsX < 0) mapOfsX = 0;
905 mapOfsY = (mapOfsY*2)-vlHeight/2;
906 if (mapOfsY+vlHeight > map.height*16) mapOfsY = map.height*16-vlHeight;
907 if (mapOfsY < 0) mapOfsY = 0;
909 setMapViewPos(mapOfsX
, mapOfsY
);
910 mapOfsX
= mapViewPosX
[1];
911 mapOfsY
= mapViewPosY
[1];
913 sdwindow
= new SimpleWindow(vlWidth
, vlHeight
, "D2D", OpenGlOptions
.yes
, Resizablity
.fixedSize
);
915 sdwindow
.visibleForTheFirstTime
= delegate () {
916 sdwindow
.setAsCurrentOpenGlContext(); // make this window active
917 glbindLoadFunctions();
920 import core.stdc.stdio;
921 printf("GL version: %s\n", glGetString(GL_VERSION));
923 glGetIntegerv(GL_MAJOR_VERSION, &h);
924 glGetIntegerv(GL_MINOR_VERSION, &l);
925 printf("version: %d.%d\n", h, l);
926 printf("shader version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
928 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &svcount);
930 printf("%d shader versions supported:\n", svcount);
931 foreach (GLuint n; 0..svcount) printf(" %d: %s\n", n, glGetStringi(GL_SHADING_LANGUAGE_VERSION, n));
935 glGetIntegerv(GL_NUM_EXTENSIONS, &ecount);
937 printf("%d extensions supported:\n", ecount);
938 foreach (GLuint n; 0..ecount) printf(" %d: %s\n", n, glGetStringi(GL_EXTENSIONS, n));
943 // check if we have sufficient shader version here
947 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS
, &svcount
);
949 foreach (GLuint n
; 0..svcount
) {
950 import core
.stdc
.string
: strncmp
;
951 auto v
= glGetStringi(GL_SHADING_LANGUAGE_VERSION
, n
);
952 if (v
is null) continue;
953 if (strncmp(v
, "120", 3) != 0) continue;
954 if (v
[3] > ' ') continue;
959 if (!found
) assert(0, "can't find OpenGL GLSL 120");
961 auto adr
= glGetProcAddress("glTexParameterf");
962 if (adr
is null) assert(0);
966 sdwindow
.vsync
= true;
968 sdwindow
.vsync
= false;
970 //sdwindow.useGLFinish = false;
972 //sdwindow.redrawOpenGlScene();
973 if (!sdwindow
.releaseCurrentOpenGlContext()) { import core
.stdc
.stdio
; printf("can't release OpenGL context(1)\n"); }
975 renderTid
= new Thread(&renderThread
);
980 //sdwindow.redrawOpenGlScene = delegate () { renderScene(); };
982 enum MSecsPerFrame
= 1000/30; /* 30 is FPS */
984 uint[8] frameTimes
= 1000;
985 enum { Left
, Right
, Up
, Down
}
986 bool[4] pressed
= false;
988 sdwindow
.eventLoop(MSecsPerFrame
,
990 if (sdwindow
.closed
) return;
991 if (pressed
[Left
]) mapOfsX
-= 8;
992 if (pressed
[Right
]) mapOfsX
+= 8;
993 if (pressed
[Up
]) mapOfsY
-= 8;
994 if (pressed
[Down
]) mapOfsY
+= 8;
995 import std
.math
: cos
, sin
;
996 __gshared
float itime
= 0.0;
999 mapOfsX
= cast(int)(800.0/2.0+cos(itime
)*220.0);
1000 mapOfsY
= cast(int)(800.0/2.0+120.0+sin(itime
)*160.0);
1002 if (scale
== 1) mapOfsX
= mapOfsY
= 0;
1003 //sdwindow.redrawOpenGlSceneNow();
1005 delegate (KeyEvent event
) {
1006 if (sdwindow
.closed
) return;
1007 if (event
.pressed
&& event
.key
== Key
.Escape
) { closeWindow(); return; }
1008 switch (event
.key
) {
1009 case Key
.X
: if (event
.pressed
) altMove
= !altMove
; break;
1010 case Key
.Left
: if (altMove
) pressed
[Left
] = event
.pressed
; break;
1011 case Key
.Right
: if (altMove
) pressed
[Right
] = event
.pressed
; break;
1012 case Key
.Up
: if (altMove
) pressed
[Up
] = event
.pressed
; break;
1013 case Key
.Down
: if (altMove
) pressed
[Down
] = event
.pressed
; break;
1017 switch (event
.key
) {
1018 case Key
.Left
: case Key
.Pad4
: plrKeyUpDown(0, PLK_LEFT
, event
.pressed
); break;
1019 case Key
.Right
: case Key
.Pad6
: plrKeyUpDown(0, PLK_RIGHT
, event
.pressed
); break;
1020 case Key
.Up
: case Key
.Pad8
: plrKeyUpDown(0, PLK_UP
, event
.pressed
); break;
1021 case Key
.Down
: case Key
.Pad2
: plrKeyUpDown(0, PLK_DOWN
, event
.pressed
); break;
1022 case Key
.Alt
: plrKeyUpDown(0, PLK_JUMP
, event
.pressed
); break;
1023 case Key
.Ctrl
: plrKeyUpDown(0, PLK_FIRE
, event
.pressed
); break;
1024 case Key
.Shift
: plrKeyUpDown(0, PLK_USE
, event
.pressed
); break;
1029 delegate (MouseEvent event
) {
1030 lightX
= event
.x
/scale
;
1031 lightY
= event
.y
/scale
;
1032 lightX
+= mapOfsX
/scale
;
1033 lightY
+= mapOfsY
/scale
;
1035 delegate (dchar ch
) {
1036 if (ch
== 'q') { closeWindow(); return; }
1037 if (ch
== 's') scanlines
= !scanlines
;
1038 if (ch
== '1') scale
= 1;
1039 if (ch
== '2') scale
= 2;
1040 if (ch
== 'D') cheatNoDoors
= !cheatNoDoors
;
1042 frameInterpolation
= !frameInterpolation
;
1043 if (frameInterpolation
) addMessage("Interpolation: ON"); else addMessage("Interpolation: OFF");
1046 doLighting
= !doLighting
;
1047 if (doLighting
) addMessage("Lighting: ON"); else addMessage("Lighting: OFF");
1049 if (ch
== ' ') movement
= !movement
;
1052 } catch (Exception e
) {
1053 import std
.stdio
: stderr
;
1054 stderr
.writeln("FUUUUUUUUUUUU\n", e
.toString
);