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;
27 import std
.concurrency
;
50 // ////////////////////////////////////////////////////////////////////////// //
55 // ////////////////////////////////////////////////////////////////////////// //
56 public __gshared
bool cheatNoDoors
= false;
57 public __gshared
bool cheatNoWallClip
= false;
60 // ////////////////////////////////////////////////////////////////////////// //
61 public __gshared SimpleWindow sdwindow
;
64 public enum vlWidth
= 800;
65 public enum vlHeight
= 800;
66 __gshared
int scale
= 2;
68 public int getScale () nothrow @trusted @nogc { pragma(inline
, true); return scale
; }
71 // ////////////////////////////////////////////////////////////////////////// //
72 __gshared
bool levelLoaded
= false;
75 // ////////////////////////////////////////////////////////////////////////// //
76 __gshared
bool scanlines
= false;
77 __gshared
bool doLighting
= true;
78 __gshared
bool gamePaused
= false;
79 __gshared
bool rConsoleVisible
= false;
80 __gshared
int rConsoleHeight
= 16*3;
81 shared bool editMode
= false;
82 shared bool vquitRequested
= false;
84 public @property bool inEditMode () nothrow @trusted @nogc { import core
.atomic
; return atomicLoad(editMode
); }
85 @property void inEditMode (bool v
) nothrow @trusted @nogc { import core
.atomic
; atomicStore(editMode
, v
); }
87 public @property bool quitRequested () nothrow @trusted @nogc { import core
.atomic
; return atomicLoad(vquitRequested
); }
88 public @property bool conVisible () nothrow @trusted @nogc { return rConsoleVisible
; }
91 // ////////////////////////////////////////////////////////////////////////// //
92 __gshared
char[] concmdbuf
;
93 __gshared
uint concmdbufpos
;
94 private import core
.sync
.mutex
: Mutex
;
95 shared static this () { concmdbuf
.length
= 65536; }
97 __gshared
char[4096] concli
= 0;
98 __gshared
uint conclilen
= 0;
100 __gshared
char[4096][128] concmdhistory
= void;
101 __gshared
int conhisidx
= -1;
102 shared static this () { foreach (ref hb
; concmdhistory
) hb
[] = 0; }
104 __gshared
int conskiplines
= 0;
107 const(char)[] conhisAt (int idx
) {
108 if (idx
< 0 || idx
>= concmdhistory
.length
) return null;
109 const(char)[] res
= concmdhistory
.ptr
[idx
][];
111 while (pos
< res
.length
&& res
.ptr
[pos
]) ++pos
;
116 int conhisFind (const(char)[] cmd
) {
117 while (cmd
.length
&& cmd
[$-1] <= 32) cmd
= cmd
[0..$-1];
118 if (cmd
.length
> concmdhistory
.ptr
[0].length
) cmd
= cmd
[0..concmdhistory
.ptr
[0].length
];
119 if (cmd
.length
== 0) return -1;
120 foreach (int idx
; 0..cast(int)concmdhistory
.length
) {
121 auto c
= conhisAt(idx
);
122 while (c
.length
> 0 && c
[$-1] <= 32) c
= c
[0..$-1];
123 if (c
== cmd
) return idx
;
129 void conhisAdd (const(char)[] cmd
) {
130 while (cmd
.length
&& cmd
[$-1] <= 32) cmd
= cmd
[0..$-1];
131 if (cmd
.length
> concmdhistory
.ptr
[0].length
) cmd
= cmd
[0..concmdhistory
.ptr
[0].length
];
132 if (cmd
.length
== 0) return;
133 auto idx
= conhisFind(cmd
);
136 foreach (immutable c
; idx
+1..concmdhistory
.length
) concmdhistory
.ptr
[c
-1][] = concmdhistory
.ptr
[c
][];
139 foreach (immutable c
; 1..concmdhistory
.length
; reverse
) concmdhistory
.ptr
[c
][] = concmdhistory
.ptr
[c
-1][];
140 concmdhistory
.ptr
[0][] = 0;
141 concmdhistory
.ptr
[0][0..cmd
.length
] = cmd
[];
145 void concmdAdd (const(char)[] s
) {
147 if (concmdbuf
.length
-concmdbufpos
< s
.length
+1) {
148 concmdbuf
.assumeSafeAppend
.length
+= s
.length
-(concmdbuf
.length
-concmdbufpos
)+512;
150 if (concmdbufpos
> 0 && concmdbuf
[concmdbufpos
-1] != '\n') concmdbuf
.ptr
[concmdbufpos
++] = '\n';
151 concmdbuf
[concmdbufpos
..concmdbufpos
+s
.length
] = s
[];
152 concmdbufpos
+= s
.length
;
157 void concmdDoAll () {
158 if (concmdbufpos
== 0) return;
159 scope(exit
) concmdbufpos
= 0;
160 auto ebuf
= concmdbufpos
;
161 const(char)[] s
= concmdbuf
[0..concmdbufpos
];
164 auto cmd
= conGetCommand(s
);
165 if (cmd
is null) break;
168 } catch (Exception e
) {
169 conwriteln("***ERROR: ", e
.msg
);
172 if (concmdbufpos
<= ebuf
) break;
173 s
= concmdbuf
[ebuf
..concmdbufpos
];
179 void concliChar (char ch
) {
180 __gshared
int prevWasEmptyAndTab
= 0;
183 scope(exit
) cbufUnlock();
188 if (conclilen
== 0) {
189 if (++prevWasEmptyAndTab
< 2) return;
191 prevWasEmptyAndTab
= 0;
194 string minPfx
= null;
195 // find longest command
196 foreach (auto name
; conByCommand
) {
197 if (name
.length
>= conclilen
&& name
.length
> minPfx
.length
&& name
[0..conclilen
] == concli
[0..conclilen
]) minPfx
= name
;
199 //conwriteln("longest command: [", minPfx, "]");
200 // find longest prefix
201 foreach (auto name
; conByCommand
) {
202 if (name
.length
< conclilen
) continue;
203 if (name
[0..conclilen
] != concli
[0..conclilen
]) continue;
205 while (pos
< name
.length
&& pos
< minPfx
.length
&& minPfx
.ptr
[pos
] == name
.ptr
[pos
]) ++pos
;
206 if (pos
< minPfx
.length
) minPfx
= minPfx
[0..pos
];
208 if (minPfx
.length
> concli
.length
) minPfx
= minPfx
[0..concli
.length
];
209 //conwriteln("longest prefix : [", minPfx, "]");
210 if (minPfx
.length
>= conclilen
) {
212 bool doRet
= (minPfx
.length
> conclilen
);
214 concli
[0..minPfx
.length
] = minPfx
[];
215 conclilen
= cast(uint)minPfx
.length
;
216 if (conclilen
< concli
.length
&& conHasCommand(minPfx
)) {
217 concli
.ptr
[conclilen
++] = ' ';
223 // nope, print all available commands
224 bool needDelimiter
= true;
225 foreach (auto name
; conByCommand
) {
227 if (name
.length
< conclilen
) continue;
228 if (name
[0..conclilen
] != concli
[0..conclilen
]) continue;
230 if (needDelimiter
) { conwriteln("----------------"); needDelimiter
= false; }
235 // process other keys
236 prevWasEmptyAndTab
= 0;
239 if (conclilen
> 0) { conLastChange
= 0; --conclilen
; }
244 if (conskiplines
) { conskiplines
= 0; conLastChange
= 0; }
248 conhisAdd(concli
[0..conclilen
]);
249 concmdAdd(concli
[0..conclilen
]);
256 if (conclilen
> 0) { conLastChange
= 0; conclilen
= 0; }
262 auto cmd
= conhisAt(conhisidx
);
263 if (cmd
.length
== 0) {
266 concli
[0..cmd
.length
] = cmd
[];
267 conclilen
= cast(uint)cmd
.length
;
275 auto cmd
= conhisAt(conhisidx
);
276 if (cmd
.length
== 0 && conhisidx
< -1) {
279 concli
[0..cmd
.length
] = cmd
[];
280 conclilen
= cast(uint)cmd
.length
;
287 int lnx
= (rConsoleHeight
-4)/conCharHeight
-2;
288 if (lnx
< 1) lnx
= 1;
295 if (conskiplines
> 0) {
296 int lnx
= (rConsoleHeight
-4)/conCharHeight
-2;
297 if (lnx
< 1) lnx
= 1;
298 if ((conskiplines
-= lnx
) < 0) conskiplines
= 0;
304 if (ch
< ' ' || ch
> 127) return;
305 if (conclilen
>= concli
.length
) return;
306 concli
.ptr
[conclilen
++] = ch
;
311 // ////////////////////////////////////////////////////////////////////////// //
312 shared static this () {
313 conRegVar
!doLighting("r_lighting", "dynamic lighting");
314 conRegVar
!gamePaused("g_pause", "pause game");
315 conRegVar
!rConsoleVisible("r_console", "console visibility");
316 conRegVar
!rConsoleHeight(16*3, vlHeight
, "r_conheight");
317 rConsoleHeight
= vlHeight
-vlHeight
/3;
318 rConsoleHeight
= vlHeight
/2;
319 conRegVar
!frameInterpolation("r_interpolation", "interpolate camera and sprite movement");
320 conRegVar
!scale(1, 2, "r_scale");
322 cheatNoDoors
= !cheatNoDoors
;
323 if (cheatNoDoors
) conwriteln("player ignores doors"); else conwriteln("player respects doors");
324 })("nodoorclip", "ignore doors");
326 cheatNoWallClip
= !cheatNoWallClip
;
327 if (cheatNoWallClip
) conwriteln("player ignores walls"); else conwriteln("player respects walls");
328 })("nowallclip", "ignore walls");
331 atomicStore(vquitRequested
, true);
332 })("quit", "quit game");
333 conRegFunc
!((const(char)[] msg
, int pauseMsecs
=3000, bool noreplace
=false) {
335 auto s
= buf
.conFormatStr(msg
);
336 if (s
.length
) postAddMessage(s
, pauseMsecs
, noreplace
);
337 })("hudmsg", "show hud message; hudmsg msg [pausemsecs [noreplace]]");
341 // ////////////////////////////////////////////////////////////////////////// //
343 __gshared
ubyte[] prevFrameActorsData
;
344 __gshared
uint[65536] prevFrameActorOfs
; // uint.max-1: dead; uint.max: last
345 __gshared MonoTime lastthink
= MonoTime
.zero
; // for interpolator
346 __gshared MonoTime nextthink
= MonoTime
.zero
;
347 __gshared
bool frameInterpolation
= true;
350 // ////////////////////////////////////////////////////////////////////////// //
352 struct AttachedLightInfo
{
359 int w
, h
; // for ambient lights
365 __gshared AttachedLightInfo
[65536] attachedLights
;
366 __gshared
uint attachedLightCount
= 0;
369 // ////////////////////////////////////////////////////////////////////////// //
370 enum MaxLightRadius
= 255;
373 // ////////////////////////////////////////////////////////////////////////// //
375 __gshared FBO
[MaxLightRadius
+1] fboDistMap
;
376 __gshared FBO fboOccluders
;
377 __gshared Shader shadToPolar
, shadBlur
, shadBlurOcc
, shadAmbient
;
378 __gshared TrueColorImage editorImg
;
379 __gshared FBO fboEditor
;
380 __gshared FBO fboConsole
;
381 __gshared Texture texSigil
;
383 __gshared FBO fboLevel
, fboLevelLight
, fboOrigBack
, fboLMaskSmall
;
384 __gshared Shader shadScanlines
;
385 __gshared Shader shadLiquidDistort
;
388 // ////////////////////////////////////////////////////////////////////////// //
390 public void initOpenGL () {
393 glEnable(GL_TEXTURE_2D
);
394 glDisable(GL_LIGHTING
);
395 glDisable(GL_DITHER
);
397 glDisable(GL_DEPTH_TEST
);
400 shadScanlines
= new Shader("scanlines", loadTextFile("shaders/srscanlines.frag"));
402 shadLiquidDistort
= new Shader("liquid_distort", loadTextFile("shaders/srliquid_distort.frag"));
403 shadLiquidDistort
.exec((Shader shad
) {
404 shad
["texLqMap"] = 0;
408 shadToPolar
= new Shader("light_trace", loadTextFile("shaders/srlight_trace.frag"));
409 shadToPolar
.exec((Shader shad
) {
411 shad
["texOccFull"] = 2;
412 shad
["texOccSmall"] = 3;
415 shadBlur
= new Shader("light_blur", loadTextFile("shaders/srlight_blur.frag"));
416 shadBlur
.exec((Shader shad
) {
420 shad
["texOccSmall"] = 3;
423 shadBlurOcc
= new Shader("light_blur_occ", loadTextFile("shaders/srlight_blur_occ.frag"));
424 shadBlurOcc
.exec((Shader shad
) {
428 shad
["texOccSmall"] = 3;
431 shadAmbient
= new Shader("light_ambient", loadTextFile("shaders/srlight_ambient.frag"));
432 shadAmbient
.exec((Shader shad
) {
435 shad
["texOccSmall"] = 3;
438 fboOccluders
= new FBO(MaxLightRadius
*2, MaxLightRadius
*2, Texture
.Option
.Clamp
, Texture
.Option
.Linear
);
440 foreach (int sz
; 2..MaxLightRadius
+1) {
441 fboDistMap
[sz
] = new FBO(sz
*2, 1, Texture
.Option
.Clamp
, Texture
.Option
.Linear
); // create 1d distance map FBO
444 editorImg
= new TrueColorImage(vlWidth
, vlHeight
);
445 editorImg
.imageData
.colors
[] = Color(0, 0, 0, 0);
446 fboEditor
= new FBO(vlWidth
, vlHeight
, Texture
.Option
.Nearest
);
448 texSigil
= new Texture("console/sigil_of_baphomet.png", Texture
.Option
.Nearest
);
449 fboConsole
= new FBO(vlWidth
, vlHeight
, Texture
.Option
.Nearest
);
453 glMatrixMode(GL_MODELVIEW
);
458 loadAllMonsterGraphics();
462 // ////////////////////////////////////////////////////////////////////////// //
463 __gshared
ulong conLastChange
= 0;
465 void renderConsoleFBO () {
467 if (conLastChange
== cbufLastChange
) return;
469 scope(exit
) cbufUnlock();
471 conLastChange
= cbufLastChange
;
472 //foreach (auto s; conbufLinesRev) stdout.writeln(s, "|");
473 int skipLines
= conskiplines
;
474 fboConsole
.exec((FBO me
) {
476 orthoCamera(me
.width
, me
.height
);
478 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
479 glClear(GL_COLOR_BUFFER_BIT
);
482 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
483 glRectf(0, 0, me.width-1, me.height-1);
487 glBlendFunc(GL_SRC_ALPHA
, GL_ONE
);
489 glColor4f(1.0f, 1.0f, 1.0f, 0.2f);
490 drawAtXY(texSigil
, (me
.width
-texSigil
.width
)/2, (vlHeight
-rConsoleHeight
)/2+(me
.height
-texSigil
.height
)/2);
492 int y
= me
.height
-conCharHeight
-2;
495 scope(exit
) glPopMatrix();
496 glTranslatef(XOfs
, y
, 0);
497 int w
= conCharWidth('>');
498 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
500 uint spos
= conclilen
;
502 char ch
= concli
.ptr
[spos
-1];
503 if (w
+conCharWidth(ch
) > me
.width
-XOfs
*2-12) break;
504 w
+= conCharWidth(ch
);
507 glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
508 foreach (char ch
; concli
[spos
..conclilen
]) conDrawChar(ch
);
511 glColor4f(1.0f, 0.5f, 0.0f, 1.0f);
512 glRectf(0, 0, 12, 16);
516 glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
518 scope(exit
) glPopMatrix();
519 glTranslatef(XOfs
, y
, 0);
521 void putLine(T
) (auto ref T line
, usize pos
=0) {
522 if (y
+conCharHeight
<= 0) return;
525 while (sp
< line
.length
) {
526 char ch
= line
[sp
++];
527 int cw
= conCharWidth(ch
);
528 if ((w
+= cw
) > me
.width
-XOfs
) { w
-= cw
; --sp
; break; }
530 if (sp
< line
.length
) putLine(line
, sp
); // recursive put tail
532 if (skipLines
-- <= 0) {
533 while (pos
< sp
) conDrawChar(line
[pos
++]);
537 glTranslatef(XOfs
, y
, 0);
541 foreach (auto line
; conbufLinesRev
) {
543 if (y
+conCharHeight
<= 0) break;
549 // ////////////////////////////////////////////////////////////////////////// //
550 // should be called when OpenGL is initialized
551 void loadMap (string mapname
) {
552 mapscripts
.runUnloading(); // "map unloading" script
555 if (map
!is null) map
.clear();
556 map
= new LevelMap(mapname
);
557 curmapname
= mapname
;
559 ugInit(map
.width
*TileSize
, map
.height
*TileSize
);
564 if (fboLevel
!is null) fboLevel
.clear();
565 if (fboLevelLight
!is null) fboLevelLight
.clear();
566 if (fboOrigBack
!is null) fboOrigBack
.clear();
567 if (fboLMaskSmall
!is null) fboLMaskSmall
.clear();
569 fboLevel
= new FBO(map
.width
*TileSize
, map
.height
*TileSize
, Texture
.Option
.Nearest
); // final level render will be here
570 fboLevelLight
= new FBO(map
.width
*TileSize
, map
.height
*TileSize
, Texture
.Option
.Nearest
); // level lights will be rendered here
571 fboOrigBack
= new FBO(map
.width
*TileSize
, map
.height
*TileSize
, Texture
.Option
.Nearest
/*, Texture.Option.Depth*/); // background+foreground
572 fboLMaskSmall
= new FBO(map
.width
, map
.height
, Texture
.Option
.Nearest
); // small lightmask
574 shadToPolar
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*TileSize
-1, map
.height
*TileSize
-1); });
575 shadBlur
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*TileSize
, map
.height
*TileSize
); });
576 shadBlurOcc
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*TileSize
, map
.height
*TileSize
); });
577 shadAmbient
.exec((Shader shad
) { shad
["mapPixSize"] = SVec2F(map
.width
*TileSize
, map
.height
*TileSize
); });
579 glActiveTexture(GL_TEXTURE0
+0);
580 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
581 orthoCamera(vlWidth
, vlHeight
);
583 Actor
.resetStorage();
586 mapscripts
.runInit();
589 mapscripts
.runLoaded();
591 // save first snapshot
592 if (prevFrameActorsData
.length
== 0) prevFrameActorsData
= new ubyte[](Actor
.actorSize
*65536); // ~15-20 megabytes
593 prevFrameActorOfs
[] = uint.max
; // just for fun
594 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
598 { import core
.memory
: GC
; GC
.collect(); }
602 // ////////////////////////////////////////////////////////////////////////// //
604 __gshared
uint mapTilesChanged
= 0;
607 //WARNING! this can be called only from DACS, so we don't have to sync it!
608 public void mapDirty (uint layermask
) { mapTilesChanged |
= layermask
; }
611 void rebuildMapMegaTextures () {
613 //mapTilesChanged = false;
614 //map.clearMegaTextures();
615 map
.oglBuildMega(mapTilesChanged
);
617 dotsAwake(); // let dormant dots fall
621 // ////////////////////////////////////////////////////////////////////////// //
624 enum Phase
{ FadeIn
, Stay
, FadeOut
}
633 //private import core.sync.mutex : Mutex;
635 __gshared Message
[128] messages
;
636 __gshared
uint messagesUsed
= 0;
638 //__gshared Mutex messageLock;
639 //shared static this () { messageLock = new Mutex(); }
642 void addMessage (const(char)[] msgtext
, int pauseMsecs
=3000, bool noreplace
=false) {
643 //messageLock.lock();
644 //scope(exit) messageLock.unlock();
645 if (msgtext
.length
== 0) return;
647 if (pauseMsecs
<= 50) return;
648 if (messagesUsed
== messages
.length
) {
649 // remove top message
650 foreach (immutable cidx
; 1..messagesUsed
) messages
.ptr
[cidx
-1] = messages
.ptr
[cidx
];
651 messages
.ptr
[0].alpha
= 255;
655 if (!noreplace
&& messagesUsed
== 1) {
656 switch (messages
.ptr
[0].phase
) {
657 case Message
.Phase
.FadeIn
:
658 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
660 case Message
.Phase
.Stay
:
661 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
662 messages
.ptr
[0].alpha
= 255;
667 auto msg
= messages
.ptr
+messagesUsed
;
669 msg
.phase
= Message
.Phase
.FadeIn
;
671 msg
.pauseMsecs
= pauseMsecs
;
673 if (msgtext
.length
> msg
.text
.length
) {
674 msg
.text
= msgtext
[0..msg
.text
.length
];
675 msg
.textlen
= msg
.text
.length
;
677 msg
.text
[0..msgtext
.length
] = msgtext
[];
678 msg
.textlen
= msgtext
.length
;
683 void doMessages (MonoTime curtime
) {
684 //messageLock.lock();
685 //scope(exit) messageLock.unlock();
687 if (messagesUsed
== 0) return;
689 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
695 final switch (msg
.phase
) {
696 case Message
.Phase
.FadeIn
:
697 if ((msg
.alpha
+= 10) >= 255) {
698 msg
.phase
= Message
.Phase
.Stay
;
699 msg
.removeTime
= curtime
+dur
!"msecs"(msg
.pauseMsecs
);
700 goto case; // to stay
702 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
704 case Message
.Phase
.Stay
:
705 if (msg
.removeTime
<= curtime
) {
707 msg
.phase
= Message
.Phase
.FadeOut
;
708 goto case; // to fade
710 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
712 case Message
.Phase
.FadeOut
:
713 if ((msg
.alpha
-= 10) <= 0) {
714 if (--messagesUsed
== 0) return;
715 // remove this message
716 foreach (immutable cidx
; 1..messagesUsed
+1) messages
.ptr
[cidx
-1] = messages
.ptr
[cidx
];
719 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
723 smDrawText(10, 10, msg
.text
[0..msg
.textlen
]);
727 // ////////////////////////////////////////////////////////////////////////// //
728 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
730 mixin(Actor
.FieldGetMixin
!("classtype", StrId
)); // fget_classtype
731 mixin(Actor
.FieldGetMixin
!("classname", StrId
)); // fget_classname
732 mixin(Actor
.FieldGetMixin
!("x", int));
733 mixin(Actor
.FieldGetMixin
!("y", int));
734 mixin(Actor
.FieldGetMixin
!("s", int));
735 mixin(Actor
.FieldGetMixin
!("radius", int));
736 mixin(Actor
.FieldGetMixin
!("height", int));
737 mixin(Actor
.FieldGetMixin
!("flags", uint));
738 mixin(Actor
.FieldGetMixin
!("zAnimstate", StrId
));
739 mixin(Actor
.FieldGetMixin
!("zAnimidx", int));
740 mixin(Actor
.FieldGetMixin
!("dir", uint));
741 mixin(Actor
.FieldGetMixin
!("attLightXOfs", int));
742 mixin(Actor
.FieldGetMixin
!("attLightYOfs", int));
743 mixin(Actor
.FieldGetMixin
!("attLightRGBX", uint));
745 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
746 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
747 mixin(Actor
.FieldGetPtrMixin
!("x", int));
748 mixin(Actor
.FieldGetPtrMixin
!("y", int));
749 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
750 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
751 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
752 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
753 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
754 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
755 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
758 // ////////////////////////////////////////////////////////////////////////// //
759 __gshared
int vportX0
, vportY0
, vportX1
, vportY1
;
762 // ////////////////////////////////////////////////////////////////////////// //
763 void renderLightAmbient() (int lightX
, int lightY
, int lightW
, int lightH
, in auto ref SVec4F lcol
) {
764 //conwriteln("!!!000: (", lightX, ",", lightY, ")-(", lightW, ",", lightH, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
765 if (lightW
< 1 || lightH
< 1) return;
766 int lightX1
= lightX
+lightW
-1;
767 int lightY1
= lightY
+lightH
-1;
768 // clip light to viewport
769 if (lightX
< vportX0
) lightX
= vportX0
;
770 if (lightY
< vportY0
) lightY
= vportY0
;
771 if (lightX1
> vportX1
) lightX1
= vportX1
;
772 if (lightY1
> vportY1
) lightY1
= vportY1
;
773 // is this light visible?
774 //conwriteln("!!!001: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
775 if (lightX1
< lightX || lightY1
< lightY || lightX
> vportX1 || lightY
> vportY1 || lightX1
< vportX0 || lightY1
< vportY0
) return;
776 //conwriteln("!!!002: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
781 glBlendFunc(GL_SRC_ALPHA
, GL_ONE
);
782 //glDisable(GL_BLEND);
783 orthoCamera(map
.width
*TileSize
, map
.height
*TileSize
);
784 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
785 shadAmbient
.exec((Shader shad
) {
786 shad
["lightColor"] = SVec4F(lcol
.x
, lcol
.y
, lcol
.z
, lcol
.w
);
787 //shad["lightPos"] = SVec2F(lightX, lightY);
788 glRectf(lightX
, lightY
, lightX1
, lightY1
);
794 // ////////////////////////////////////////////////////////////////////////// //
795 void renderLight() (int lightX
, int lightY
, in auto ref SVec4F lcol
, int lightRadius
) {
796 if (lightRadius
< 2) return;
797 if (lightRadius
> MaxLightRadius
) lightRadius
= MaxLightRadius
;
798 int lightSize
= lightRadius
*2;
799 // is this light visible?
800 if (lightX
<= -lightRadius || lightY
<= -lightRadius || lightX
-lightRadius
>= map
.width
*TileSize || lightY
-lightRadius
>= map
.height
*TileSize
) return;
802 // out of viewport -- do nothing
803 if (lightX
+lightRadius
< vportX0 || lightY
+lightRadius
< vportY0
) return;
804 if (lightX
-lightRadius
> vportX1 || lightY
-lightRadius
> vportY1
) return;
806 if (lightX
>= 0 && lightY
>= 0 && lightX
< map
.width
*TileSize
&& lightY
< map
.height
*TileSize
&&
807 map
.teximgs
[map
.LightMask
].imageData
.colors
.ptr
[lightY
*(map
.width
*TileSize
)+lightX
].a
> 190) return;
809 // common color for all the following
811 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
813 // build 1d distance map to fboShadowMapId
814 fboDistMap
.ptr
[lightRadius
].exec({
815 // no need to clear it, shader will take care of that
816 shadToPolar
.exec((Shader shad
) {
817 shad
["lightTexSize"] = SVec2F(lightSize
, lightSize
);
818 shad
["lightPos"] = SVec2F(lightX
, lightY
);
819 orthoCamera(lightSize
, 1);
820 // it doesn't matter what we will draw here, so just draw filled rect
821 glRectf(0, 0, lightSize
, 1);
825 // build light texture for blending
827 // no need to clear it, shader will take care of that
829 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
830 //glClear(GL_COLOR_BUFFER_BIT);
831 shadBlur
.exec((Shader shad
) {
832 shad
["lightTexSize"] = SVec2F(lightSize
, MaxLightRadius
*2); // x: size of distmap; y: size of this texture
833 shad
["lightColor"] = SVec4F(lcol
.x
, lcol
.y
, lcol
.z
, lcol
.w
);
834 shad
["lightPos"] = SVec2F(lightX
-lightRadius
, lightY
-lightRadius
);
835 orthoCamera(fboOccluders
.tex
.width
, fboOccluders
.tex
.height
);
836 //drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
837 bindTexture(fboDistMap
.ptr
[lightRadius
].tex
.tid
);
839 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, 0); // top-left
840 glTexCoord2f(1.0f, 0.0f); glVertex2i(lightSize
, 0); // top-right
841 glTexCoord2f(1.0f, 1.0f); glVertex2i(lightSize
, lightSize
); // bottom-right
842 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, lightSize
); // bottom-left
847 // blend light texture
850 //glDisable(GL_BLEND);
851 glBlendFunc(GL_SRC_ALPHA
, GL_ONE
);
852 orthoCamera(fboLevelLight
.tex
.width
, fboLevelLight
.tex
.height
);
853 //drawAtXY(fboOccluders.tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
854 float occe
= 1.0f*lightSize
/(MaxLightRadius
*2);
855 float occs
= 1.0f-occe
;
856 int x0
= lightX
-lightRadius
+0;
857 int y1
= lightY
-lightRadius
+0;
858 int x1
= lightX
+lightRadius
-1+1;
859 int y0
= lightY
+lightRadius
-1+1;
860 bindTexture(fboOccluders
.tex
.tid
);
863 glTexCoord2f(0.0f, 0.0f); glVertex2i(x0, y0); // top-left
864 glTexCoord2f(occe, 0.0f); glVertex2i(x1, y0); // top-right
865 glTexCoord2f(occe, occe); glVertex2i(x1, y1); // bottom-right
866 glTexCoord2f(0.0f, occe); glVertex2i(x0, y1); // bottom-left
868 glTexCoord2f(0.0f, occs
); glVertex2i(x0
, y0
); // top-left
869 glTexCoord2f(occe
, occs
); glVertex2i(x1
, y0
); // top-right
870 glTexCoord2f(occe
, 1.0f); glVertex2i(x1
, y1
); // bottom-right
871 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0
, y1
); // bottom-left
875 glRectf(x0, y0, x1, y1);
877 // and blend it again, with the shader that will touch only occluders
878 shadBlurOcc
.exec((Shader shad
) {
879 //shad["lightTexSize"] = SVec2F(lightSize, lightSize);
880 shad
["lightTexSize"] = SVec2F(lightSize
, fboOccluders
.tex
.height
);
881 shad
["lightColor"] = SVec4F(lcol
.x
, lcol
.y
, lcol
.z
, lcol
.w
);
882 shad
["lightPos"] = SVec2F(lightX
, lightY
);
883 //shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
884 bindTexture(fboOccluders
.tex
.tid
);
886 glTexCoord2f(0.0f, occs
); glVertex2i(x0
, y0
); // top-left
887 glTexCoord2f(occe
, occs
); glVertex2i(x1
, y0
); // top-right
888 glTexCoord2f(occe
, 1.0f); glVertex2i(x1
, y1
); // bottom-right
889 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0
, y1
); // bottom-left
891 //drawAtXY(fboOccluders.tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
897 // ////////////////////////////////////////////////////////////////////////// //
898 __gshared
int testLightX
= vlWidth
/2, testLightY
= vlHeight
/2;
899 __gshared
bool testLightMoved
= false;
900 //__gshared int mapOfsX, mapOfsY;
901 //__gshared bool movement = false;
902 __gshared
float iLiquidTime
= 0.0;
903 //__gshared bool altMove = false;
906 void renderScene (MonoTime curtime
) {
907 //enum BackIntens = 0.05f;
908 enum BackIntens
= 0.0f;
911 float atob
= (curtime
> lastthink ?
cast(float)((curtime
-lastthink
).total
!"msecs")/cast(float)((nextthink
-lastthink
).total
!"msecs") : 1.0f);
912 if (gamePaused || inEditMode
) atob
= 1.0f;
913 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
916 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
917 int curfp = cast(int)((curtime-lastthink).total!"msecs");
918 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
922 int mofsx
, mofsy
; // camera offset, will be set in background layer builder
924 if (mapTilesChanged
!= 0) rebuildMapMegaTextures();
926 // build background layer
928 //glDisable(GL_BLEND);
929 //glClearDepth(1.0f);
930 //glDepthFunc(GL_LESS);
931 //glDepthFunc(GL_NEVER);
932 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
933 glClear(GL_COLOR_BUFFER_BIT
/*|GL_DEPTH_BUFFER_BIT*/);
934 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
935 orthoCamera(map
.width
*TileSize
, map
.height
*TileSize
);
938 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
941 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
942 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
943 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
944 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
946 drawAtXY(map
.skytexgl
.tid
, 0, 0, map
.MapSize
*TileSize
, map
.MapSize
*TileSize
);
948 drawAtXY(map
.texgl
.ptr
[map
.Back
], 0, 0);
949 // draw distorted liquid areas
950 shadLiquidDistort
.exec((Shader shad
) {
951 shad
["iDistortTime"] = iLiquidTime
;
952 drawAtXY(map
.texgl
.ptr
[map
.AllLiquids
], 0, 0);
954 // monsters, items; we'll do linear interpolation here
955 glColor3f(1.0f, 1.0f, 1.0f);
956 //glEnable(GL_DEPTH_TEST);
957 attachedLightCount
= 0;
959 // who cares about memory?!
960 // draw order: players, items, monsters, other
961 static struct DrawInfo
{
965 @disable this (this); // no copies
967 enum { Pixels
, Players
, Items
, Monsters
, Other
}
968 __gshared DrawInfo
[65536][4] drawlists
;
969 __gshared
uint[4] dlpos
;
974 Actor
.forEach((ActorId me
) {
975 //me.fprop_0drawlistpos = 0;
976 if (auto adef
= findActorDef(me
)) {
978 switch (adef
.classtype
.get
) {
979 case "monster": dlnum
= (adef
.classname
.get
!= "Player" ? Monsters
: Players
); break;
980 case "item": dlnum
= Items
; break;
981 default: dlnum
= Other
; break;
983 if (me
.fget_flags
&AF_PIXEL
) dlnum
= Pixels
;
984 int actorX
, actorY
; // current actor position
986 auto ofs
= prevFrameActorOfs
.ptr
[me
.id
&0xffff];
987 if (frameInterpolation
&& ofs
< uint.max
-1 && (me
.fget_flags
&AF_TELEPORT
) == 0 && Actor
.isSameSavedActor(me
.id
, prevFrameActorsData
.ptr
, ofs
)) {
988 import core
.stdc
.math
: roundf
;
989 auto xptr
= prevFrameActorsData
.ptr
+ofs
;
990 int ox
= xptr
.fgetp_x
;
992 int oy
= xptr
.fgetp_y
;
994 actorX
= cast(int)(ox
+roundf((nx
-ox
)*atob
));
995 actorY
= cast(int)(oy
+roundf((ny
-oy
)*atob
));
996 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
1002 if (me
.id
== cameraChick
.id
) {
1003 camchickdi
.adef
= adef
;
1004 camchickdi
.aid
= me
;
1005 camchickdi
.actorX
= actorX
;
1006 camchickdi
.actorY
= actorY
;
1009 if ((me
.fget_flags
&AF_NODRAW
) == 0) {
1010 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
1011 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
1012 auto dl = drawlists
.ptr
[dlnum
].ptr
+dlpos
.ptr
[dlnum
];
1019 // process attached lights
1020 if ((me
.fget_flags
&AF_NOLIGHT
) == 0) {
1021 uint alr
= me
.fget_attLightRGBX
;
1022 bool isambient
= (me
.fget_classtype
.get
== "light" && me
.fget_classname
.get
== "Ambient");
1023 if ((alr
&0xff) >= 4 ||
(isambient
&& me
.fget_radius
>= 1 && me
.fget_height
>= 1)) {
1024 //if (isambient) conwriteln("isambient: ", isambient, "; x=", me.fget_x, "; y=", me.fget_y, "; w=", me.fget_radius, "; h=", me.fget_height);
1026 auto li
= attachedLights
.ptr
+attachedLightCount
;
1027 ++attachedLightCount
;
1028 li
.type
= (!isambient ? AttachedLightInfo
.Type
.Point
: AttachedLightInfo
.Type
.Ambient
);
1029 li
.x
= actorX
+me
.fget_attLightXOfs
;
1030 li
.y
= actorY
+me
.fget_attLightYOfs
;
1031 li
.r
= ((alr
>>24)&0xff)/255.0f; // red or intensity
1032 if ((alr
&0x00_ff_ff
_00U) == 0x00_00_01_00U) {
1033 li
.uncolored
= true;
1035 li
.g
= ((alr
>>16)&0xff)/255.0f;
1036 li
.b
= ((alr
>>8)&0xff)/255.0f;
1037 li
.uncolored
= false;
1039 li
.radius
= (alr
&0xff);
1040 if (li
.radius
> MaxLightRadius
) li
.radius
= MaxLightRadius
;
1042 li
.w
= me
.fget_radius
;
1043 li
.h
= me
.fget_height
;
1048 conwriteln("not found actor ", me
.id
, " (", me
.classtype
!string
, ":", me
.classname
!string
, ")");
1053 foreach_reverse (uint dlnum
; 0..drawlists
.length
) {
1054 if (dlnum
== Pixels
) continue;
1055 auto dl = drawlists
.ptr
[dlnum
].ptr
;
1056 if (dlnum
== Players
) dl += dlpos
.ptr
[dlnum
]-1;
1057 foreach (uint idx
; 0..dlpos
.ptr
[dlnum
]) {
1059 if (auto isp
= dl.adef
.animSpr(me
.fget_zAnimstate
, me
.fget_dir
, me
.fget_zAnimidx
)) {
1060 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
1061 isp
.drawAtXY(dl.actorX
, dl.actorY
);
1063 if (dlnum
!= Players
) ++dl; else --dl;
1067 if (dlpos
[Pixels
]) {
1069 bool pointsStarted
= false;
1070 Color lastColor
= Color(0, 0, 0, 0);
1071 auto dl = drawlists
.ptr
[Pixels
].ptr
;
1072 foreach (uint idx
; 0..dlpos
.ptr
[Pixels
]) {
1075 if (s
< 0 || s
> 255) continue; //FIXME
1076 Color clr
= d2dpal
.ptr
[s
&0xff];
1077 if (clr
.a
== 0) continue;
1078 if (clr
!= lastColor
) {
1079 if (pointsStarted
) glEnd();
1080 glColor4f(clr
.r
/255.0f, clr
.g
/255.0f, clr
.b
/255.0f, clr
.a
/255.0f);
1082 pointsStarted
= false;
1084 if (!pointsStarted
) {
1086 pointsStarted
= true;
1088 glVertex2i(dl.actorX
, dl.actorY
);
1091 if (pointsStarted
) {
1093 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1098 if (/*altMove || movement ||*/ scale
== 1 ||
!cameraChick
.valid
) {
1103 vportX1
= map
.width
*TileSize
;
1104 vportY1
= map
.height
*TileSize
;
1106 int tiltHeight
= /*getMapViewHeight()*/(vlHeight
/scale
)/4;
1107 int vy
= cameraChick
.looky
!int;
1108 if (vy
< -tiltHeight
) vy
= -tiltHeight
; else if (vy
> tiltHeight
) vy
= tiltHeight
;
1109 int swdt
= vlWidth
/scale
;
1110 int shgt
= vlHeight
/scale
;
1111 int x
= camchickdi
.actorX
-swdt
/2;
1112 int y
= (camchickdi
.actorY
+vy
)-shgt
/2;
1113 if (x
< 0) x
= 0; else if (x
>= map
.width
*TileSize
-swdt
) x
= map
.width
*TileSize
-swdt
-1;
1114 if (y
< 0) y
= 0; else if (y
>= map
.height
*TileSize
-shgt
) y
= map
.height
*TileSize
-shgt
-1;
1117 vportX0
= mofsx
/scale
;
1118 vportY0
= mofsy
/scale
;
1119 vportX1
= vportX0
+vlWidth
/scale
;
1120 vportY1
= vportY0
+vlHeight
/scale
;
1123 //glDisable(GL_DEPTH_TEST);
1126 // do liquid coloring
1127 drawAtXY(map
.texgl
.ptr
[map
.LiquidMask
], 0, 0);
1128 // foreground -- hide secrets, draw lifts and such
1129 drawAtXY(map
.texgl
.ptr
[map
.Front
], 0, 0);
1137 glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
1138 glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
1139 if (cameraChick.valid) {
1141 glVertex2i(camchickdi.actorX, camchickdi.actorY-70);
1143 //glRectf(camchickdi.actorX, camchickdi.actorY-70, camchickdi.actorX+4, camchickdi.actorY-70+4);
1145 //glRectf(0, 0, 300, 300);
1146 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1153 glDisable(GL_BLEND
);
1154 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1156 // make smaller occluder texture, so we can trace faster
1157 //assert(fboLMaskSmall.tex.width == map.width);
1158 //assert(fboLMaskSmall.tex.height == map.height);
1159 fboLMaskSmall
.exec({
1160 orthoCamera(map
.width
, map
.height
);
1161 drawAtXY(map
.texgl
.ptr
[map
.LightMask
].tid
, 0, 0, map
.width
, map
.height
, mirrorY
:true);
1164 // clear light layer
1165 fboLevelLight
.exec({
1166 glClearColor(BackIntens
, BackIntens
, BackIntens
, 1.0f);
1167 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
1168 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
1169 glClear(GL_COLOR_BUFFER_BIT
);
1172 // texture 1 is background
1173 glActiveTexture(GL_TEXTURE0
+1);
1174 glBindTexture(GL_TEXTURE_2D
, fboOrigBack
.tex
.tid
);
1175 // texture 2 is occluders
1176 glActiveTexture(GL_TEXTURE0
+2);
1177 glBindTexture(GL_TEXTURE_2D
, map
.texgl
.ptr
[map
.LightMask
].tid
);
1178 // texture 3 is small occluder map
1179 glActiveTexture(GL_TEXTURE0
+3);
1180 glBindTexture(GL_TEXTURE_2D
, fboLMaskSmall
.tex
.tid
);
1181 // done texture assign
1182 glActiveTexture(GL_TEXTURE0
+0);
1187 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1188 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1189 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1190 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1191 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1192 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1193 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1194 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1195 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1196 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1198 renderLight(24*TileSize+4, (24+18)*TileSize-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
1200 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1205 foreach (ref li
; attachedLights
[0..attachedLightCount
]) {
1206 if (li
.type
== AttachedLightInfo
.Type
.Ambient
) {
1207 //conwriteln("ambient: x=", li.x, "; y=", li.y, "; w=", li.w, "; h=", li.h);
1210 renderLightAmbient(li
.x
, li
.y
, li
.w
, li
.h
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
));
1212 renderLightAmbient(li
.x
, li
.y
, li
.w
, li
.h
, SVec4F(li
.r
, li
.g
, li
.b
, 1.0f));
1214 } else if (li
.type
== AttachedLightInfo
.Type
.Point
) {
1217 renderLight(li
.x
, li
.y
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
), li
.radius
);
1219 renderLight(li
.x
, li
.y
, SVec4F(li
.r
, li
.g
, li
.b
, 1.0f), li
.radius
);
1226 if (testLightMoved
) {
1227 testLightX
= testLightX
/scale
+mofsx
/scale
;
1228 testLightY
= testLightY
/scale
+mofsy
/scale
;
1229 testLightMoved
= false;
1231 foreach (immutable _
; 0..1) {
1232 renderLight(testLightX
, testLightY
, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
1236 glActiveTexture(GL_TEXTURE0
+1);
1237 glBindTexture(GL_TEXTURE_2D
, 0);
1238 glActiveTexture(GL_TEXTURE0
+2);
1239 glBindTexture(GL_TEXTURE_2D
, 0);
1240 glActiveTexture(GL_TEXTURE0
+3);
1241 glBindTexture(GL_TEXTURE_2D
, 0);
1242 glActiveTexture(GL_TEXTURE0
+0);
1245 // draw scaled level
1247 shadScanlines.exec((Shader shad) {
1248 shad["scanlines"] = scanlines;
1249 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1250 glClear(GL_COLOR_BUFFER_BIT);
1251 orthoCamera(vlWidth, vlHeight);
1252 //orthoCamera(map.width*TileSize*scale, map.height*TileSize*scale);
1253 //glMatrixMode(GL_MODELVIEW);
1255 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
1256 // somehow, FBO objects are mirrored; wtf?!
1257 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1263 fboLevelLight.exec({
1264 smDrawText(map.width*TileSize/2, map.height*TileSize/2, "Testing...");
1269 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
1271 glDisable(GL_BLEND
);
1275 //auto img = smfont.ptr[0x39];
1278 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
1279 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
1286 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
1287 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1288 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1289 glDrawBuffers(1, buffers.ptr);
1294 orthoCamera(vlWidth
, vlHeight
);
1295 auto tex
= (doLighting ? fboLevelLight
.tex
.tid
: fboOrigBack
.tex
.tid
);
1296 drawAtXY(tex
, -mofsx
, -mofsy
, map
.width
*TileSize
*scale
, map
.height
*TileSize
*scale
, mirrorY
:true);
1299 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1300 //orthoCamera(map.width*TileSize, map.height*TileSize);
1302 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
1303 hudScripts
.runDraw();
1306 //drawAtXY(map.texgl.ptr[map.LightMask].tid, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1307 //drawAtXY(fboLMaskSmall.tex.tid, 0, 0, map.width*TileSize, map.height*TileSize);
1311 //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1312 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
1313 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1314 editorUpdateImage();
1315 fboEditor
.tex
.setFromImage(editorImg
);
1316 drawAtXY(fboEditor
.tex
, 0, 0);
1317 glDisable(GL_BLEND
);
1320 doMessages(curtime
);
1322 if (rConsoleVisible
) {
1324 orthoCamera(vlWidth
, vlHeight
);
1326 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
1327 glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
1328 drawAtXY(fboConsole
.tex
, 0, rConsoleHeight
-vlHeight
, mirrorY
:true);
1333 // ////////////////////////////////////////////////////////////////////////// //
1334 // returns time slept
1335 int sleepAtMaxMsecs (int msecs
) {
1337 import core
.sys
.posix
.signal
: timespec
;
1338 import core
.sys
.posix
.time
: nanosleep
;
1339 timespec ts
= void, tpassed
= void;
1341 ts
.tv_nsec
= msecs
*1000*1000+(500*1000); // milli to nano
1342 nanosleep(&ts
, &tpassed
);
1343 return (ts
.tv_nsec
-tpassed
.tv_nsec
)/(1000*1000);
1350 // ////////////////////////////////////////////////////////////////////////// //
1351 mixin(import("editor.d"));
1354 // ////////////////////////////////////////////////////////////////////////// //
1356 shared int diedie
= 0;
1358 enum D2DFrameTime
= 55; // milliseconds
1359 enum MinFrameTime
= 1000/60; // ~60 FPS
1361 public void renderThread (Tid starterTid
) {
1362 enum BoolOptVarMsgMixin(string varname
) =
1363 "if (msg.toggle) msg.value = !"~varname
~";\n"~
1364 "if ("~varname
~" != msg.value) "~varname
~" = msg.value; else msg.showMessage = false;\n";
1366 send(starterTid
, 42);
1368 MonoTime curtime
= MonoTime
.currTime
;
1370 lastthink
= curtime
; // for interpolator
1371 nextthink
= curtime
+dur
!"msecs"(D2DFrameTime
);
1372 MonoTime nextvframe
= curtime
;
1374 enum MaxFPSFrames
= 16;
1375 float frtimes
= 0.0f;
1378 int hushFrames
= 6; // ignore first `hushFrames` frames overtime
1379 MonoTime prevFrameStartTime
= curtime
;
1381 bool vframeWasLost
= false;
1383 void resetFrameTimers () {
1384 MonoTime curtime
= MonoTime
.currTime
;
1385 lastthink
= curtime
; // for interpolator
1386 nextthink
= curtime
+dur
!"msecs"(D2DFrameTime
);
1387 nextvframe
= curtime
;
1390 void loadNewLevel (string name
) {
1393 conwriteln("ERROR: can't load new levels yet");
1397 if (name
.length
== 0) {
1398 conwriteln("ERROR: can't load empty level!");
1400 conwriteln("loading map '", name
, "'");
1406 string mn
= genNextMapName(0);
1408 nextmapname
= null; // clear "exit" flag
1411 conwriteln("can't skip level");
1413 })("skiplevel", "skip current level");
1416 inEditMode
= !inEditMode
;
1417 if (inEditMode
) sdwindow
.hideCursor(); else sdwindow
.showCursor();
1418 })("ed_toggle", "toggle editor");
1423 sdwindow
.showCursor();
1425 })("ed_exit", "exit from editor");
1427 conRegFunc
!((string mapname
) {
1428 nextmapname
= null; // clear "exit" flag
1429 loadNewLevel(mapname
);
1430 })("map", "load map");
1432 void receiveMessages () {
1434 import core
.time
: Duration
;
1435 //conwriteln("rendering thread: waiting for messages...");
1436 auto got
= receiveTimeout(
1437 Duration
.zero
, // don't wait
1439 addMessage(msg
.text
[0..msg
.textlen
], msg
.pauseMsecs
, msg
.noreplace
);
1441 (TMsgTestLightMove msg
) {
1444 testLightMoved
= true;
1446 (TMsgMouseEvent msg
) { editorMouseEvent(msg
); },
1447 (TMsgKeyEvent msg
) { editorKeyEvent(msg
); },
1448 (TMsgChar msg
) { concliChar(msg
.ch
); },
1450 conwriteln("WARNING: unknown thread message received and ignored");
1455 //conwriteln("rendering thread: no more messages");
1459 if (nextmapname
.length
) {
1460 string mn
= nextmapname
;
1461 nextmapname
= null; // clear "exit" flag
1466 void processConsoleCommands () {
1468 scope(exit
) cbufUnlock();
1472 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1473 bool doThinkFrame () {
1474 if (curtime
>= nextthink
) {
1475 lastthink
= curtime
;
1476 while (nextthink
<= curtime
) nextthink
+= dur
!"msecs"(D2DFrameTime
);
1478 // save snapshot and other data for interpolator
1479 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
1480 if (!gamePaused
&& !inEditMode
) {
1487 auto tm
= MonoTime
.currTime
;
1488 int thinkTime
= cast(int)((tm
-curtime
).total
!"msecs");
1489 if (thinkTime
> 9) { import core
.stdc
.stdio
; printf("spent on thinking: %d msecs\n", thinkTime
); }
1497 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1499 version(dont_use_vsync
) {
1501 enum doCheckTime
= true;
1504 __gshared
bool prevLost
= false;
1505 bool doCheckTime
= vframeWasLost
;
1506 if (vframeWasLost
) {
1508 { import core
.stdc
.stdio
; printf("frame was lost!\n"); }
1516 if (curtime
< nextvframe
) return false;
1517 version(dont_use_vsync
) {
1518 if (curtime
> nextvframe
) {
1519 auto overtime
= cast(int)((curtime
-nextvframe
).total
!"msecs");
1520 if (overtime
> 2500) {
1524 { import core
.stdc
.stdio
; printf(" spent whole %d msecs\n", overtime
); }
1530 while (nextvframe
<= curtime
) nextvframe
+= dur
!"msecs"(MinFrameTime
);
1534 scope(exit
) sdwindow
.mtUnlock();
1535 ctset
= sdwindow
.setAsCurrentOpenGlContextNT
;
1537 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1540 iLiquidTime
= cast(float)((curtime
-MonoTime
.zero
).total
!"msecs"%10000000)/18.0f*0.04f;
1541 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1542 processConsoleCommands();
1544 renderScene(curtime
);
1546 //renderLoading(curtime);
1549 scope(exit
) sdwindow
.mtUnlock();
1550 sdwindow
.swapOpenGlBuffers();
1552 sdwindow
.releaseCurrentOpenGlContext();
1553 vframeWasLost
= false;
1555 vframeWasLost
= true;
1556 { import core
.stdc
.stdio
; printf("xframe was lost!\n"); }
1558 curtime
= MonoTime
.currTime
;
1563 if (sdwindow
.closed
) break;
1564 if (atomicLoad(diedie
) > 0) break;
1566 curtime
= MonoTime
.currTime
;
1567 auto fstime
= curtime
;
1569 doThinkFrame(); // this will fix curtime if necessary
1571 if (!vframeWasLost
) {
1573 auto frameTime
= cast(float)(curtime
-prevFrameStartTime
).total
!"msecs"/1000.0f;
1574 prevFrameStartTime
= curtime
;
1575 frtimes
+= frameTime
;
1576 if (++framenum
>= MaxFPSFrames || frtimes
>= 3.0f) {
1577 import std
.string
: format
;
1578 int newFPS
= cast(int)(cast(float)MaxFPSFrames
/frtimes
+0.5);
1579 if (newFPS
!= prevFPS
) {
1580 sdwindow
.title
= "%s / FPS:%s".format("D2D", newFPS
);
1589 curtime
= MonoTime
.currTime
;
1591 // now sleep until next "video" or "think" frame
1592 if (nextthink
> curtime
&& nextvframe
> curtime
) {
1594 immutable nextVideoFrameSleep
= cast(int)((nextvframe
-curtime
).total
!"msecs");
1595 immutable nextThinkFrameSleep
= cast(int)((nextthink
-curtime
).total
!"msecs");
1596 immutable sleepTime
= (nextVideoFrameSleep
< nextThinkFrameSleep ? nextVideoFrameSleep
: nextThinkFrameSleep
);
1597 sleepAtMaxMsecs(sleepTime
);
1598 //curtime = MonoTime.currTime;
1601 } catch (Throwable e
) {
1602 // here, we are dead and fucked (the exact order doesn't matter)
1603 import core
.stdc
.stdlib
: abort
;
1604 import core
.stdc
.stdio
: fprintf
, stderr
;
1605 import core
.memory
: GC
;
1606 GC
.disable(); // yeah
1607 thread_suspendAll(); // stop right here, you criminal scum!
1608 auto s
= e
.toString();
1609 fprintf(stderr
, "\n=== FATAL ===\n%.*s\n", cast(uint)s
.length
, s
.ptr
);
1610 abort(); // die, you bitch!
1612 import core.stdc.stdio;
1613 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1614 import std.stdio : stderr;
1617 if (sdwindow.closed) break;
1618 if (atomicLoad(diedie) > 0) break;
1619 sleepAtMaxMsecs(100);
1623 atomicStore(diedie
, 2);
1627 // ////////////////////////////////////////////////////////////////////////// //
1628 __gshared Tid renderTid
;
1629 shared bool renderThreadStarted
= false;
1632 public void startRenderThread () {
1633 if (!cas(&renderThreadStarted
, false, true)) {
1634 assert(0, "render thread already started!");
1636 renderTid
= spawn(&renderThread
, thisTid
);
1637 setMaxMailboxSize(renderTid
, 1024, OnCrowding
.throwException
); //FIXME
1638 // wait for "i'm ready" signal
1641 if (ok
!= 42) assert(0, "wtf?!");
1644 conwriteln("rendering thread started");
1648 // ////////////////////////////////////////////////////////////////////////// //
1649 public void closeWindow () {
1650 if (atomicLoad(diedie
) != 2) {
1651 atomicStore(diedie
, 1);
1652 while (atomicLoad(diedie
) != 2) {}
1654 if (!sdwindow
.closed
) {
1661 // ////////////////////////////////////////////////////////////////////////// //
1665 // ////////////////////////////////////////////////////////////////////////// //
1666 struct TMsgMouseEvent
{
1667 MouseEventType type
;
1670 MouseButton button
; /// See $(LREF MouseButton)
1671 int modifierState
; /// See $(LREF ModifierState)
1674 public void postMouseEvent() (in auto ref MouseEvent evt
) {
1675 if (!atomicLoad(renderThreadStarted
)) return;
1677 msg
.type
= evt
.type
;
1682 msg
.button
= evt
.button
;
1683 msg
.modifierState
= evt
.modifierState
;
1684 send(renderTid
, msg
);
1688 // ////////////////////////////////////////////////////////////////////////// //
1689 struct TMsgKeyEvent
{
1697 public void postKeyEvent() (in auto ref KeyEvent evt
) {
1698 if (!atomicLoad(renderThreadStarted
)) return;
1701 msg
.pressed
= evt
.pressed
;
1702 msg
.character
= evt
.character
;
1703 msg
.modifierState
= evt
.modifierState
;
1704 send(renderTid
, msg
);
1708 // ////////////////////////////////////////////////////////////////////////// //
1709 struct TMsgTestLightMove
{
1713 public void postTestLightMove (int x
, int y
) {
1714 if (!atomicLoad(renderThreadStarted
)) return;
1715 auto msg
= TMsgTestLightMove(x
, y
);
1716 send(renderTid
, msg
);
1720 // ////////////////////////////////////////////////////////////////////////// //
1721 struct TMsgMessage
{
1728 public void postAddMessage (const(char)[] msgtext
, int pauseMsecs
=3000, bool noreplace
=false) {
1729 if (!atomicLoad(renderThreadStarted
)) return;
1730 if (msgtext
.length
> TMsgMessage
.text
.length
) msgtext
= msgtext
[0..TMsgMessage
.text
.length
];
1732 msg
.textlen
= cast(uint)msgtext
.length
;
1733 if (msg
.textlen
) msg
.text
[0..msg
.textlen
] = msgtext
[0..msg
.textlen
];
1734 msg
.pauseMsecs
= pauseMsecs
;
1735 msg
.noreplace
= noreplace
;
1736 send(renderTid
, msg
);
1740 // ////////////////////////////////////////////////////////////////////////// //
1745 public void postChar (char ch
) {
1746 if (!atomicLoad(renderThreadStarted
)) return;
1749 send(renderTid
, msg
);
1753 // ////////////////////////////////////////////////////////////////////////// //
1754 public void concmd (const(char)[] cmd
) {
1755 //if (!atomicLoad(renderThreadStarted)) return;
1757 scope(exit
) cbufUnlock();