message system
[dd2d.git] / xmain_d2d.d
blob603d59f5fc9b9c489340c23bfc8ea02b1e3369bd
1 module xmain_d2d is aliced;
3 private:
4 import core.atomic;
5 import core.thread;
6 import core.time;
8 import iv.glbinds;
9 import glutils;
10 import console;
11 import wadarc;
13 import iv.stream;
15 import d2dmap;
16 import d2dadefs;
17 //import d2dactors;
18 import d2dgfx;
19 import d2dfont;
20 import dacs;
22 // `map` is there
23 import dengapi;
26 // ////////////////////////////////////////////////////////////////////////// //
27 import arsd.color;
28 import arsd.png;
31 // ////////////////////////////////////////////////////////////////////////// //
32 __gshared SimpleWindow sdwindow;
35 public enum vlWidth = 800;
36 public enum vlHeight = 800;
37 __gshared int scale = 1;
38 __gshared bool scanlines = false;
41 // ////////////////////////////////////////////////////////////////////////// //
42 // interpolation
43 __gshared ubyte[] prevFrameActorsData;
44 __gshared uint[65536] prevFrameActorOfs; // uint.max-1: dead; uint.max: last
45 __gshared MonoTime lastthink = MonoTime.zero; // for interpolator
46 __gshared MonoTime nextthink = MonoTime.zero;
47 __gshared bool frameInterpolation = true;
48 __gshared bool doLighting = true;
51 // ////////////////////////////////////////////////////////////////////////// //
52 enum MaxLightRadius = 512;
55 // ////////////////////////////////////////////////////////////////////////// //
56 // for light
57 __gshared FBO[MaxLightRadius+1] fboOccluders, fboShadowMap;
58 __gshared Shader shadToPolar, shadBlur, shadBlurOcc;
60 __gshared FBO fboLevel, fboLevelLight, fboOrigBack;
61 __gshared Shader shadScanlines;
62 __gshared Shader shadLiquidDistort;
65 // ////////////////////////////////////////////////////////////////////////// //
66 void initOpenGL () {
67 glEnable(GL_TEXTURE_2D);
68 glDisable(GL_LIGHTING);
69 glDisable(GL_DITHER);
70 glDisable(GL_BLEND);
71 glDisable(GL_DEPTH_TEST);
73 // create shaders
74 shadScanlines = new Shader("scanlines", loadTextFile("data/shaders/srscanlines.frag"));
76 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("data/shaders/srliquid_distort.frag"));
77 shadLiquidDistort.exec((Shader shad) { shad["tex0"] = 0; });
79 // lights
80 shadToPolar = new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar.frag"));
81 shadBlur = new Shader("light_blur", loadTextFile("data/shaders/srlight_blur.frag"));
82 shadBlur.exec((Shader shad) {
83 shad["tex0"] = 0;
84 shad["tex1"] = 1;
85 shad["tex2"] = 2;
86 });
87 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("data/shaders/srlight_blur_occ.frag"));
88 shadBlurOcc.exec((Shader shad) {
89 shad["tex0"] = 0;
90 shad["tex1"] = 1;
91 shad["tex2"] = 2;
92 });
93 //TODO: this sux!
94 foreach (int sz; 2..MaxLightRadius+1) {
95 fboOccluders[sz] = new FBO(sz*2, sz*2, Texture.Option.Clamp, Texture.Option.Linear); // create occluders FBO
96 fboShadowMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp); // create 1d shadowmap FBO
99 // setup matrices
100 glMatrixMode(GL_MODELVIEW);
101 glLoadIdentity();
103 map.oglBuildMega();
105 fboLevel = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // final level render will be here
106 fboLevelLight = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level lights will be rendered here
107 //fboForeground = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level foreground
108 fboOrigBack = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // background+foreground
110 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
111 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
113 glActiveTexture(GL_TEXTURE0+0);
114 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
115 orthoCamera(vlWidth, vlHeight);
117 loadSmFont();
119 Actor.resetStorage();
120 loadMapMonsters();
122 // save first snapshot
123 prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
124 prevFrameActorOfs[] = uint.max; // just for fun
125 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
127 { import core.memory : GC; GC.collect(); }
131 // ////////////////////////////////////////////////////////////////////////// //
132 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
133 if (lightRadius < 2) return;
134 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
135 int lightSize = lightRadius*2;
136 // is this light visible?
137 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*8 || lightY-lightRadius >= map.height*8) return;
139 // draw shadow casters to fboOccludersId, light should be in the center
140 glUseProgram(0);
141 glDisable(GL_BLEND);
142 fboOccluders[lightRadius].exec({
143 //glDisable(GL_BLEND);
144 glColor3f(0.0f, 0.0f, 0.0f);
145 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
146 glClear(GL_COLOR_BUFFER_BIT);
147 orthoCamera(lightSize, lightSize);
148 drawAtXY(map.texgl.ptr[map.LightMask], lightRadius-lightX, lightRadius-lightY);
151 // build 1d shadow map to fboShadowMapId
152 fboShadowMap[lightRadius].exec({
153 shadToPolar.exec((Shader shad) {
154 //glDisable(GL_BLEND);
155 glColor3f(0.0f, 0.0f, 0.0f);
156 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
157 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
158 glClear(GL_COLOR_BUFFER_BIT);
159 orthoCamera(lightSize, 1);
160 drawAtXY(fboOccluders[lightRadius].tex.tid, 0, 0, lightSize, 1);
164 // build light texture for blending
165 fboOccluders[lightRadius].exec({
166 // no need to clear it, shader will take care of that
167 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
168 //glClear(GL_COLOR_BUFFER_BIT);
169 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
170 //glDisable(GL_BLEND);
171 shadBlur.exec((Shader shad) {
172 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
173 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
174 shad["lightPos"] = SVec2F(lightX, lightY);
175 orthoCamera(lightSize, lightSize);
176 drawAtXY(fboShadowMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
180 // blend light texture
181 fboLevelLight.exec({
182 glEnable(GL_BLEND);
183 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
184 orthoCamera(map.width*8, map.height*8);
185 drawAtXY(fboOccluders[lightRadius].tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
186 // and blend it again, somewhat bigger, with the shader that will touch only occluders
187 enum szmore = 0;
188 shadBlurOcc.exec((Shader shad) {
189 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
190 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
191 shad["lightPos"] = SVec2F(lightX, lightY);
192 drawAtXY(fboOccluders[lightRadius].tex.tid, lightX-lightRadius-szmore, lightY-lightRadius-szmore, lightSize+szmore*2, lightSize+szmore*2, mirrorY:true);
198 // ////////////////////////////////////////////////////////////////////////// //
199 // messages
200 struct Message {
201 enum Phase { FadeIn, Stay, FadeOut }
202 Phase phase;
203 int alpha;
204 int pauseMsecs;
205 MonoTime removeTime;
206 char[256] text;
207 const(char)[] txt;
210 private import core.sync.mutex : Mutex;
212 __gshared Message[128] messages;
213 __gshared uint messagesUsed = 0;
214 __gshared Mutex messageLock;
216 shared static this () { messageLock = new Mutex(); }
219 void addMessage (const(char)[] msgtext, int pauseMsecs=3000) {
220 messageLock.lock();
221 scope(exit) messageLock.unlock();
222 if (msgtext.length == 0) return;
223 if (pauseMsecs <= 50) return;
224 if (messagesUsed == messages.length) {
225 // remove top message
226 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
227 messages.ptr[0].alpha = 255;
228 --messagesUsed;
230 auto msg = messages.ptr+messagesUsed;
231 msg.phase = Message.Phase.FadeIn;
232 msg.alpha = 0;
233 msg.pauseMsecs = pauseMsecs;
234 // copy text
235 if (msgtext.length > msg.text.length) {
236 msg.text = msgtext[0..msg.text.length];
237 msg.txt = msg.text[0..$];
238 } else {
239 msg.text[0..msgtext.length] = msgtext[0..$];
240 msg.txt = msg.text[0..msgtext.length];
242 ++messagesUsed;
246 void doMessages (MonoTime curtime) {
247 messageLock.lock();
248 scope(exit) messageLock.unlock();
250 if (messagesUsed == 0) return;
251 glEnable(GL_BLEND);
252 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
254 Message* msg;
256 again:
257 msg = messages.ptr;
258 final switch (msg.phase) {
259 case Message.Phase.FadeIn:
260 if ((msg.alpha += 10) >= 255) {
261 msg.phase = Message.Phase.Stay;
262 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
263 goto case; // to stay
265 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
266 break;
267 case Message.Phase.Stay:
268 if (msg.removeTime <= curtime) {
269 msg.alpha = 255;
270 msg.phase = Message.Phase.FadeOut;
271 goto case; // to fade
273 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
274 break;
275 case Message.Phase.FadeOut:
276 if ((msg.alpha -= 10) <= 0) {
277 if (--messagesUsed == 0) return;
278 // remove this message
279 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
280 goto again;
282 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
283 break;
286 //glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
287 smDrawText(10, 10, msg.txt);
291 // ////////////////////////////////////////////////////////////////////////// //
292 __gshared int lightX = vlWidth/2, lightY = vlHeight/2;
293 __gshared int mapOfsX, mapOfsY;
294 __gshared bool movement = false;
295 __gshared float iLiquidTime = 0.0;
298 void renderScene (MonoTime curtime) {
299 //enum BackIntens = 0.05f;
300 enum BackIntens = 0.0f;
302 float atob = cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs");
303 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
306 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
307 int curfp = cast(int)((curtime-lastthink).total!"msecs");
308 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
312 glUseProgram(0);
314 // build background layer
315 fboOrigBack.exec({
316 //glDisable(GL_BLEND);
317 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
318 glClear(GL_COLOR_BUFFER_BIT);
319 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
320 orthoCamera(map.width*8, map.height*8);
321 glEnable(GL_BLEND);
322 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
323 // draw sky
325 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
326 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2, map.MapSize*8, map.MapSize*8);
327 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
328 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*8, map.MapSize*8);
330 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*8, map.MapSize*8);
331 // draw background
332 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
333 // draw distorted liquid areas
334 shadLiquidDistort.exec((Shader shad) {
335 shad["iDistortTime"] = iLiquidTime;
336 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
338 // monsters, items; we'll do linear interpolation here
339 // we need this for saved frame anyway, so let's play dirty and speed up the things
340 uint fxofs = Actor.fields["x"].ofs;
341 uint fyofs = Actor.fields["y"].ofs;
342 uint fzAnimstateofs = Actor.fields["zAnimstate"].ofs;
343 uint fdirofs = Actor.fields["dir"].ofs;
344 uint fzAnimidxofs = Actor.fields["zAnimidx"].ofs;
345 uint fclasstypeofs = Actor.fields["classtype"].ofs;
346 uint fclassnameofs = Actor.fields["classname"].ofs;
347 glColor3f(1.0f, 1.0f, 1.0f);
348 Actor.forEach((ActorId me) {
349 // `act` is always valid here
350 auto aptr = me.data.ptr;
351 auto ctstr = StrId(*cast(uint*)(aptr+fclasstypeofs));
352 auto cnstr = StrId(*cast(uint*)(aptr+fclassnameofs));
353 if (auto adef = findActorDef(ctstr, cnstr)) {
354 ctstr = StrId(*cast(uint*)(aptr+fzAnimstateofs));
355 if (auto isp = adef.animSpr(ctstr, *cast(uint*)(aptr+fdirofs), *cast(int*)(aptr+fzAnimidxofs))) {
356 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
357 if (frameInterpolation && ofs < uint.max-1) {
358 import core.stdc.math : roundf;
359 auto xptr = prevFrameActorsData.ptr+ofs;
360 int ox = *cast(int*)(xptr+fxofs);
361 int nx = *cast(int*)(aptr+fxofs);
362 int oy = *cast(int*)(xptr+fyofs);
363 int ny = *cast(int*)(aptr+fyofs);
364 int x = cast(int)(ox+roundf((nx-ox)*atob));
365 int y = cast(int)(oy+roundf((ny-oy)*atob));
366 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
367 drawAtXY(isp.tex, x-isp.vga.sx, y-isp.vga.sy);
368 } else {
369 int nx = *cast(int*)(aptr+fxofs)-isp.vga.sx;
370 int ny = *cast(int*)(aptr+fyofs)-isp.vga.sy;
371 //conwriteln("actor ", me.id, "; nx=", nx, "; ny=", ny);
372 drawAtXY(isp.tex, nx, ny);
374 } else {
375 conwriteln("no animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
377 } else {
378 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
381 if (auto adef = findActorDef(me.classtype!StrId, me.classname!StrId)) {
382 if (auto isp = adef.animSpr(me.zAnimstate!StrId, me.dir!uint, me.zAnimidx!int)) {
383 int y = me.y!int-isp.vga.sy;
384 drawAtXY(isp.tex, me.x!int-isp.vga.sx, y);
385 //conwriteln("found animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")", " (", adef.fullname, ")");
386 } else {
387 conwriteln("no animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
389 } else {
390 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
394 // do liquid coloring
395 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
396 // foreground -- hide secrets, draw lifts and such
397 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
399 glDisable(GL_BLEND);
400 if (auto img = fftest) {
401 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
402 drawAtXY(img.tex, 50-img.sx, 50-img.sy);
408 if (doLighting) {
409 // clear light layer
410 fboLevelLight.exec({
411 glDisable(GL_BLEND);
412 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
413 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
414 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
415 glClear(GL_COLOR_BUFFER_BIT);
418 // texture 1 is background
419 glActiveTexture(GL_TEXTURE0+1);
420 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
421 // texture 2 is occluders
422 glActiveTexture(GL_TEXTURE0+2);
423 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
424 // done texture assign
425 glActiveTexture(GL_TEXTURE0+0);
427 enum LYOfs = 1;
429 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 100);
430 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 100);
431 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 32);
432 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 64);
433 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 128);
434 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 128);
435 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 128);
436 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 128);
437 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 64);
438 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 0.0f), 32);
440 renderLight(24*8+4, (24+18)*8-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
442 foreach (immutable _; 0..1) {
443 renderLight(lightX, lightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
446 glActiveTexture(GL_TEXTURE0+1);
447 glBindTexture(GL_TEXTURE_2D, 0);
448 glActiveTexture(GL_TEXTURE0+2);
449 glBindTexture(GL_TEXTURE_2D, 0);
450 glActiveTexture(GL_TEXTURE0+0);
453 // draw scaled level
455 shadScanlines.exec((Shader shad) {
456 shad["scanlines"] = scanlines;
457 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
458 glClear(GL_COLOR_BUFFER_BIT);
459 orthoCamera(vlWidth, vlHeight);
460 //orthoCamera(map.width*8*scale, map.height*8*scale);
461 //glMatrixMode(GL_MODELVIEW);
462 //glLoadIdentity();
463 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
464 // somehow, FBO objects are mirrored; wtf?!
465 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
466 //glLoadIdentity();
471 fboLevelLight.exec({
472 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
477 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
478 glDisable(GL_BLEND);
481 fboOrigBack.exec({
482 //auto img = smfont.ptr[0x39];
483 auto img = fftest;
484 if (img !is null) {
485 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
486 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
491 orthoCamera(vlWidth, vlHeight);
492 if (doLighting) {
493 drawAtXY(fboLevelLight.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
494 } else {
495 drawAtXY(fboOrigBack.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
498 doMessages(curtime);
502 // ////////////////////////////////////////////////////////////////////////// //
503 // rendering thread
504 shared int diedie = 0;
506 enum D2DFrameTime = 55; // milliseconds
508 void renderThread () {
509 try {
510 MonoTime prevFrameStartTime = MonoTime.currTime;
511 version(use_vsync) {} else MonoTime ltt = MonoTime.currTime;
512 MonoTime lasttime = MonoTime.currTime;
513 nextthink = MonoTime.currTime;
514 lastthink = nextthink; // for interpolator
515 nextthink += dur!"msecs"(D2DFrameTime);
516 MonoTime fstime, fetime;
517 enum MaxFPSFrames = 16;
518 float frtimes = 0.0f;
519 int framenum = 0;
520 int prevFPS = -1;
521 int hushFrames = 6; // ignore first `hushFrames` frames overtime
522 for (;;) {
523 if (sdwindow.closed) break;
524 if (atomicLoad(diedie) > 0) break;
526 fstime = MonoTime.currTime;
528 // "D2D frames"
529 if (nextthink <= fstime) {
530 lastthink = fstime;
531 nextthink = fstime;
532 nextthink += dur!"msecs"(D2DFrameTime);
533 // save snapshot for interpolator
534 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
535 // process actors
536 doActorsThink();
537 // some timing
538 int thinkTime = cast(int)((MonoTime.currTime-fstime).total!"msecs");
539 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
542 bool ctset;
544 sdwindow.mtLock();
545 scope(exit) sdwindow.mtUnlock();
546 ctset = sdwindow.setAsCurrentOpenGlContextNT;
548 if (!ctset) {
549 { import core.stdc.stdio; printf(" FUUUU\n"); }
550 //glXMakeCurrent(sdwindow.display, 0, null);
551 import core.sys.posix.signal : timespec;
552 import core.sys.posix.time : nanosleep;
553 timespec ts = void;
554 ts.tv_sec = 0;
555 ts.tv_nsec = 16*1000*1000; // milli to nano
556 nanosleep(&ts, null); // idc how much time was passed
557 continue;
558 } else {
559 // render scene
560 iLiquidTime = cast(float)((fstime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
561 renderScene(fstime);
562 sdwindow.mtLock();
563 scope(exit) sdwindow.mtUnlock();
564 sdwindow.swapOpenGlBuffers();
565 glFinish();
566 sdwindow.releaseCurrentOpenGlContext();
569 fetime = MonoTime.currTime;
570 // wait for 16 ms if we still have some time
571 version(use_vsync) {
572 } else {
573 // max 60 FPS; capped by vsync
574 //{ import core.stdc.stdio; printf(" spent only %d msecs\n", cast(int)((fetime-fstime).total!"msecs")); }
575 if ((fetime-fstime).total!"msecs" < 16) {
576 //{ import core.stdc.stdio; printf(" spent only %d msecs\n", cast(int)((fetime-fstime).total!"msecs")); }
577 import core.sys.posix.signal : timespec;
578 import core.sys.posix.time : nanosleep;
579 timespec ts = void;
580 ts.tv_sec = 0;
581 ts.tv_nsec = (16-cast(int)((fetime-fstime).total!"msecs"))*1000*1000; // milli to nano
582 nanosleep(&ts, null); // idc how much time was passed
583 fetime = MonoTime.currTime;
584 } else {
585 if (hushFrames) {
586 --hushFrames;
587 } else {
588 { import core.stdc.stdio; printf(" spent whole %d msecs\n", cast(int)((fetime-fstime).total!"msecs")); }
594 auto frameTime = cast(float)(fetime-prevFrameStartTime).total!"msecs"/1000.0f;
595 prevFrameStartTime = fetime;
596 frtimes += frameTime;
597 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
598 import std.string : format;
599 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
600 if (newFPS != prevFPS) {
601 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
602 prevFPS = newFPS;
604 framenum = 0;
605 frtimes = 0.0f;
609 } catch (Exception e) {
610 import core.stdc.stdio;
611 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
612 for (;;) {
613 if (sdwindow.closed) break;
614 if (atomicLoad(diedie) > 0) break;
615 //{ import core.stdc.stdio; printf(" spent only %d msecs\n", cast(int)((time-ltt).total!"msecs")); }
616 import core.sys.posix.signal : timespec;
617 import core.sys.posix.time : nanosleep;
618 timespec ts = void;
619 ts.tv_sec = 0;
620 ts.tv_nsec = 100*1000*1000; // milli to nano
621 nanosleep(&ts, null); // idc how much time was passed
624 atomicStore(diedie, 2);
628 // ////////////////////////////////////////////////////////////////////////// //
629 void closeWindow () {
630 if (atomicLoad(diedie) != 2) {
631 atomicStore(diedie, 1);
632 while (atomicLoad(diedie) != 2) {}
634 if (!sdwindow.closed) {
635 flushGui();
636 sdwindow.close();
641 // ////////////////////////////////////////////////////////////////////////// //
642 __gshared Thread renderTid;
645 void main (string[] args) {
646 FuncPool.dumpCode = false;
647 FuncPool.dumpCodeSize = false;
648 dacsDumpSemantic = false;
649 dacsOptimize = 9;
650 version(rdmd) { dacsOptimize = 0; }
651 bool compileOnly = false;
653 for (usize idx = 1; idx < args.length; ++idx) {
654 bool remove = true;
655 if (args[idx] == "--dump-code") FuncPool.dumpCode = true;
656 else if (args[idx] == "--dump-code-size") FuncPool.dumpCodeSize = true;
657 else if (args[idx] == "--dump-semantic") dacsDumpSemantic = true;
658 else if (args[idx] == "--dump-all") { FuncPool.dumpCode = true; FuncPool.dumpCodeSize = true; dacsDumpSemantic = true; }
659 else if (args[idx] == "--compile") compileOnly = true;
660 else if (args[idx] == "--compile-only") compileOnly = true;
661 else if (args[idx] == "--messages") ++dacsMessages;
662 else if (args[idx] == "--no-copro") dacsOptimizeNoCoPro = true;
663 else if (args[idx] == "--no-deadass") dacsOptimizeNoDeadAss = true;
664 else if (args[idx] == "--no-purekill") dacsOptimizeNoPureKill = true;
665 else if (args[idx].length > 2 && args[idx][0..2] == "-O") {
666 import std.conv : to;
667 ubyte olevel = to!ubyte(args[idx][2..$]);
668 dacsOptimize = olevel;
670 else remove = false;
671 if (remove) {
672 foreach (immutable c; idx+1..args.length) args.ptr[c-1] = args.ptr[c];
673 args.length -= 1;
674 --idx; //hack
678 static void setDP () {
679 version(rdmd) {
680 setDataPath("data");
681 } else {
682 import std.file : thisExePath;
683 import std.path : dirName;
684 setDataPath(thisExePath.dirName);
686 addPK3(getDataPath~"base.pk3"); loadWadScripts();
687 //addWad("/home/ketmar/k8prj/doom2d-tl/data/doom2d.wad"); loadWadScripts();
688 //addWad("/home/ketmar/k8prj/doom2d-tl/data/meat.wad"); loadWadScripts();
689 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm.wad"); loadWadScripts();
690 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm1.wad"); loadWadScripts();
691 //addWad("/home/ketmar/k8prj/doom2d-tl/data/superdm.wad"); loadWadScripts();
692 //addWad("/home/ketmar/k8prj/doom2d-tl/data/zadoomka.wad"); loadWadScripts();
693 scriptLoadingComplete();
696 setDP();
698 if (compileOnly) return;
700 try {
701 registerAPI();
702 loadPalette();
704 setOpenGLContextVersion(3, 2); // up to GLSL 150
705 //openGLContextCompatible = false;
707 map = new LevelMap("maps/map01.d2m");
709 //mapOfsX = 8*26;
710 //mapOfsY = 8*56;
711 map.getThingPos(1/*ThingId.Player1*/, &mapOfsX, &mapOfsY);
712 // fix viewport
713 mapOfsX = (mapOfsX*2)-vlWidth/2;
714 if (mapOfsX+vlWidth > map.width*16) mapOfsX = map.width*16-vlWidth;
715 if (mapOfsX < 0) mapOfsX = 0;
716 mapOfsY = (mapOfsY*2)-vlHeight/2;
717 if (mapOfsY+vlHeight > map.height*16) mapOfsY = map.height*16-vlHeight;
718 if (mapOfsY < 0) mapOfsY = 0;
719 scale = 2;
721 sdwindow = new SimpleWindow(vlWidth, vlHeight, "D2D", OpenGlOptions.yes, Resizablity.fixedSize);
723 sdwindow.visibleForTheFirstTime = delegate () {
724 sdwindow.setAsCurrentOpenGlContext(); // make this window active
725 glbindLoadFunctions();
728 import core.stdc.stdio;
729 printf("GL version: %s\n", glGetString(GL_VERSION));
730 GLint l, h;
731 glGetIntegerv(GL_MAJOR_VERSION, &h);
732 glGetIntegerv(GL_MINOR_VERSION, &l);
733 printf("version: %d.%d\n", h, l);
734 printf("shader version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
735 GLint svcount;
736 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &svcount);
737 if (svcount > 0) {
738 printf("%d shader versions supported:\n", svcount);
739 foreach (GLuint n; 0..svcount) printf(" %d: %s\n", n, glGetStringi(GL_SHADING_LANGUAGE_VERSION, n));
742 GLint ecount;
743 glGetIntegerv(GL_NUM_EXTENSIONS, &ecount);
744 if (ecount > 0) {
745 printf("%d extensions supported:\n", ecount);
746 foreach (GLuint n; 0..ecount) printf(" %d: %s\n", n, glGetStringi(GL_EXTENSIONS, n));
751 // check if we have sufficient shader version here
753 bool found = false;
754 GLint svcount;
755 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &svcount);
756 if (svcount > 0) {
757 foreach (GLuint n; 0..svcount) {
758 import core.stdc.string : strncmp;
759 auto v = glGetStringi(GL_SHADING_LANGUAGE_VERSION, n);
760 if (v is null) continue;
761 if (strncmp(v, "120", 3) != 0) continue;
762 if (v[3] > ' ') continue;
763 found = true;
764 break;
767 if (!found) assert(0, "can't find OpenGL GLSL 120");
769 auto adr = glGetProcAddress("glTexParameterf");
770 if (adr is null) assert(0);
773 sdwindow.vsync = false;
774 //sdwindow.useGLFinish = false;
775 initOpenGL();
776 //sdwindow.redrawOpenGlScene();
777 if (!sdwindow.releaseCurrentOpenGlContext()) { import core.stdc.stdio; printf("can't release OpenGL context(1)\n"); }
778 if (!renderTid) {
779 renderTid = new Thread(&renderThread);
780 renderTid.start();
784 //sdwindow.redrawOpenGlScene = delegate () { renderScene(); };
786 enum MSecsPerFrame = 1000/30; /* 30 is FPS */
788 uint[8] frameTimes = 1000;
789 enum { Left, Right, Up, Down }
790 bool[4] pressed = false;
791 bool altMove = false;
793 sdwindow.eventLoop(MSecsPerFrame,
794 delegate () {
795 if (sdwindow.closed) return;
796 if (pressed[Left]) mapOfsX -= 8;
797 if (pressed[Right]) mapOfsX += 8;
798 if (pressed[Up]) mapOfsY -= 8;
799 if (pressed[Down]) mapOfsY += 8;
800 import std.math : cos, sin;
801 __gshared float itime = 0.0;
802 itime += 0.02;
803 if (movement) {
804 mapOfsX = cast(int)(800.0/2.0+cos(itime)*220.0);
805 mapOfsY = cast(int)(800.0/2.0+120.0+sin(itime)*160.0);
807 if (scale == 1) mapOfsX = mapOfsY = 0;
808 //sdwindow.redrawOpenGlSceneNow();
810 delegate (KeyEvent event) {
811 if (sdwindow.closed) return;
812 if (event.pressed && event.key == Key.Escape) { closeWindow(); return; }
813 switch (event.key) {
814 case Key.X: if (event.pressed) altMove = !altMove; break;
815 case Key.Left: if (altMove) pressed[Left] = event.pressed; break;
816 case Key.Right: if (altMove) pressed[Right] = event.pressed; break;
817 case Key.Up: if (altMove) pressed[Up] = event.pressed; break;
818 case Key.Down: if (altMove) pressed[Down] = event.pressed; break;
819 default:
821 if (!altMove) {
822 switch (event.key) {
823 case Key.Left: case Key.Pad4: plrKeyUpDown(0, PLK_LEFT, event.pressed); break;
824 case Key.Right: case Key.Pad6: plrKeyUpDown(0, PLK_RIGHT, event.pressed); break;
825 case Key.Up: case Key.Pad8: plrKeyUpDown(0, PLK_UP, event.pressed); break;
826 case Key.Down: case Key.Pad2: plrKeyUpDown(0, PLK_DOWN, event.pressed); break;
827 case Key.Alt: plrKeyUpDown(0, PLK_JUMP, event.pressed); break;
828 case Key.Ctrl: plrKeyUpDown(0, PLK_FIRE, event.pressed); break;
829 case Key.Shift: plrKeyUpDown(0, PLK_USE, event.pressed); break;
830 default:
834 delegate (MouseEvent event) {
835 lightX = event.x/scale;
836 lightY = event.y/scale;
837 lightX += mapOfsX/scale;
838 lightY += mapOfsY/scale;
840 delegate (dchar ch) {
841 if (ch == 'q') { closeWindow(); return; }
842 if (ch == 's') scanlines = !scanlines;
843 if (ch == '1') scale = 1;
844 if (ch == '2') scale = 2;
845 if (ch == 'i') {
846 frameInterpolation = !frameInterpolation;
847 if (frameInterpolation) addMessage("Interpolation: ON"); else addMessage("Interpolation: OFF");
849 if (ch == 'l') doLighting = !doLighting;
850 if (ch == ' ') movement = !movement;
853 } catch (Exception e) {
854 import std.stdio : stderr;
855 stderr.writeln("FUUUUUUUUUUUU\n", e.toString);
857 closeWindow();
858 flushGui();