LCOV - code coverage report
Current view: top level - engine/render - rendergl.cpp (source / functions) Coverage Total Hit
Test: Libprimis Test Coverage Lines: 1.5 % 990 15
Test Date: 2025-11-03 06:43:22 Functions: 8.4 % 83 7

            Line data    Source code
       1              : /* rendergl.cpp: core opengl rendering stuff
       2              :  *
       3              :  * rendergl.cpp handles the main rendering functions, which render the scene
       4              :  * using OpenGL features aliased in this file. This file also handles the
       5              :  * position of the camera and the projection frustum handling.
       6              :  *
       7              :  * While this file does not handle light and texture rendering, it does handle
       8              :  * the simple world depth fog in libprimis.
       9              :  */
      10              : #include "../libprimis-headers/cube.h"
      11              : #include "../../shared/geomexts.h"
      12              : #include "../../shared/glemu.h"
      13              : #include "../../shared/glexts.h"
      14              : 
      15              : #include <format>
      16              : 
      17              : #include "aa.h"
      18              : #include "grass.h"
      19              : #include "hdr.h"
      20              : #include "hud.h"
      21              : #include "octarender.h"
      22              : #include "postfx.h"
      23              : #include "radiancehints.h"
      24              : #include "rendergl.h"
      25              : #include "renderlights.h"
      26              : #include "rendermodel.h"
      27              : #include "renderparticles.h"
      28              : #include "rendersky.h"
      29              : #include "rendertimers.h"
      30              : #include "renderva.h"
      31              : #include "renderwindow.h"
      32              : #include "shader.h"
      33              : #include "shaderparam.h"
      34              : #include "texture.h"
      35              : #include "water.h"
      36              : 
      37              : #include "world/material.h"
      38              : #include "world/octaedit.h"
      39              : #include "world/octaworld.h"
      40              : #include "world/raycube.h"
      41              : #include "world/world.h"
      42              : 
      43              : #include "interface/console.h"
      44              : #include "interface/control.h"
      45              : #include "interface/input.h"
      46              : #include "interface/menus.h"
      47              : #include "interface/ui.h"
      48              : 
      49              : bool hasFBMSBS = false,
      50              :      hasTQ     = false,
      51              :      hasDBT    = false,
      52              :      hasEGPU4  = false,
      53              :      hasES3    = false,
      54              :      hasCI     = false;
      55              : 
      56              : //used in iengine
      57              : VAR(outline, 0, 0, 1); //vertex/edge highlighting in edit mode
      58              : 
      59              : //read-only info for gl debugging
      60              : static VAR(glversion, 1, 0, 0);
      61              : VAR(glslversion, 1, 0, 0);
      62              : 
      63              : // GL_EXT_framebuffer_blit
      64              : PFNGLBLITFRAMEBUFFERPROC         glBlitFramebuffer_         = nullptr;
      65              : 
      66              : // GL_EXT_framebuffer_multisample
      67              : PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glRenderbufferStorageMultisample_ = nullptr;
      68              : 
      69              : // GL_ARB_texture_multisample
      70              : PFNGLTEXIMAGE2DMULTISAMPLEPROC glTexImage2DMultisample_ = nullptr;
      71              : 
      72              : // OpenGL 1.3
      73              : #ifdef WIN32
      74              : PFNGLACTIVETEXTUREPROC    glActiveTexture_    = nullptr;
      75              : 
      76              : PFNGLBLENDEQUATIONEXTPROC glBlendEquation_ = nullptr;
      77              : PFNGLBLENDCOLOREXTPROC    glBlendColor_    = nullptr;
      78              : 
      79              : PFNGLTEXIMAGE3DPROC        glTexImage3D_        = nullptr;
      80              : PFNGLTEXSUBIMAGE3DPROC     glTexSubImage3D_     = nullptr;
      81              : PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D_ = nullptr;
      82              : 
      83              : PFNGLCOMPRESSEDTEXIMAGE3DPROC    glCompressedTexImage3D_    = nullptr;
      84              : PFNGLCOMPRESSEDTEXIMAGE2DPROC    glCompressedTexImage2D_    = nullptr;
      85              : PFNGLCOMPRESSEDTEXIMAGE1DPROC    glCompressedTexImage1D_    = nullptr;
      86              : PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D_ = nullptr;
      87              : PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D_ = nullptr;
      88              : PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glCompressedTexSubImage1D_ = nullptr;
      89              : PFNGLGETCOMPRESSEDTEXIMAGEPROC   glGetCompressedTexImage_   = nullptr;
      90              : 
      91              : PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements_ = nullptr;
      92              : #endif
      93              : 
      94              : // GL_EXT_depth_bounds_test
      95              : PFNGLDEPTHBOUNDSEXTPROC glDepthBounds_ = nullptr;
      96              : 
      97              : // GL_ARB_copy_image
      98              : PFNGLCOPYIMAGESUBDATAPROC glCopyImageSubData_ = nullptr;
      99              : 
     100            0 : void masktiles(uint *tiles, float sx1, float sy1, float sx2, float sy2)
     101              : {
     102              :     int tx1, ty1, tx2, ty2;
     103            0 :     calctilebounds(sx1, sy1, sx2, sy2, tx1, ty1, tx2, ty2);
     104            0 :     for(int ty = ty1; ty < ty2; ty++)
     105              :     {
     106            0 :         tiles[ty] |= ((1<<(tx2-tx1))-1)<<tx1;
     107              :     }
     108            0 : }
     109              : 
     110            0 : static void *getprocaddress(const char *name)
     111              : {
     112            0 :     return SDL_GL_GetProcAddress(name);
     113              : }
     114              : 
     115              : static VAR(glerr, 0, 0, 1);
     116              : 
     117              : /**
     118              :  * @brief Prints out a GL error to the command line.
     119              :  *
     120              :  * Used by glerror(). This function is a helper to allow glerror() to print out
     121              :  * the location and file where a GL error occured.
     122              :  *
     123              :  * @param a filename to use to help locate where the error is
     124              :  * @param line the line of code in the file
     125              :  * @param error the GL error code to print out
     126              :  */
     127            0 : static void glerror(const char *file, int line, GLenum error)
     128              : {
     129            0 :     const char *desc = "unknown";
     130            0 :     switch(error)
     131              :     {
     132            0 :         case GL_NO_ERROR:
     133              :         {
     134            0 :             desc = "no error";
     135            0 :             break;
     136              :         }
     137            0 :         case GL_INVALID_ENUM:
     138              :         {
     139            0 :             desc = "invalid enum";
     140            0 :             break;
     141              :         }
     142            0 :         case GL_INVALID_VALUE:
     143              :         {
     144            0 :             desc = "invalid value";
     145            0 :             break;
     146              :         }
     147            0 :         case GL_INVALID_OPERATION:
     148              :         {
     149            0 :             desc = "invalid operation";
     150            0 :             break;
     151              :         }
     152            0 :         case GL_STACK_OVERFLOW:
     153              :         {
     154            0 :             desc = "stack overflow";
     155            0 :             break;
     156              :         }
     157            0 :         case GL_STACK_UNDERFLOW:
     158              :         {
     159            0 :             desc = "stack underflow";
     160            0 :             break;
     161              :         }
     162            0 :         case GL_OUT_OF_MEMORY:
     163              :         {
     164            0 :             desc = "out of memory";
     165            0 :             break;
     166              :         }
     167              :     }
     168            0 :     std::printf("GL error: %s:%d: %s (%x)\n", file, line, desc, error);
     169            0 : }
     170              : 
     171            0 : void glerror()
     172              : {
     173            0 :     if(glerr)
     174              :     {
     175            0 :         GLenum error = glGetError();
     176            0 :         if(error != GL_NO_ERROR)
     177              :         {
     178            0 :             glerror(__FILE__, __LINE__, error);
     179              :         }
     180              :     }
     181            0 : }
     182              : 
     183              : VAR(intel_texalpha_bug, 0, 0, 1); //used in rendergl.h
     184              : VAR(mesa_swap_bug, 0, 0, 1); //used in rendergl.h
     185              : VAR(usetexgather, 1, 0, 0); //used in rendergl.h
     186              : static VAR(maxdrawbufs, 1, 0, 0);
     187              : VAR(maxdualdrawbufs, 1, 0, 0); //used in rendergl.h
     188              : 
     189              : static VAR(debugexts, 0, 0, 1);
     190              : 
     191              : static std::unordered_set<std::string> glexts;
     192              : 
     193            0 : static void parseglexts()
     194              : {
     195            0 :     GLint numexts = 0;
     196            0 :     glGetIntegerv(GL_NUM_EXTENSIONS, &numexts);
     197            0 :     for(int i = 0; i < numexts; ++i)
     198              :     {
     199              :         //cast from uchar * to char *
     200            0 :         const char *ext = reinterpret_cast<const char *>(glGetStringi(GL_EXTENSIONS, i));
     201            0 :         glexts.insert(ext);
     202              :     }
     203            0 : }
     204              : 
     205            1 : static bool hasext(const char *ext)
     206              : {
     207            3 :     return glexts.find(ext)!=glexts.end();
     208              : }
     209              : 
     210            0 : static bool checkdepthtexstencilrb()
     211              : {
     212            0 :     uint w = 256,
     213            0 :          h = 256;
     214            0 :     GLuint fbo = 0;
     215            0 :     glGenFramebuffers(1, &fbo);
     216            0 :     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
     217              : 
     218            0 :     GLuint depthtex = 0;
     219            0 :     glGenTextures(1, &depthtex);
     220            0 :     createtexture(depthtex, w, h, nullptr, 3, 0, GL_DEPTH_COMPONENT24, GL_TEXTURE_RECTANGLE);
     221            0 :     glBindTexture(GL_TEXTURE_RECTANGLE, 0);
     222            0 :     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_RECTANGLE, depthtex, 0);
     223              : 
     224            0 :     GLuint stencilrb = 0;
     225            0 :     glGenRenderbuffers(1, &stencilrb);
     226            0 :     glBindRenderbuffer(GL_RENDERBUFFER, stencilrb);
     227            0 :     glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, w, h);
     228            0 :     glBindRenderbuffer(GL_RENDERBUFFER, 0);
     229            0 :     glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, stencilrb);
     230              : 
     231            0 :     bool supported = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
     232              : 
     233            0 :     glBindFramebuffer(GL_FRAMEBUFFER, 0);
     234            0 :     glDeleteFramebuffers(1, &fbo);
     235            0 :     glDeleteTextures(1, &depthtex);
     236            0 :     glDeleteRenderbuffers(1, &stencilrb);
     237              : 
     238            0 :     return supported;
     239              : }
     240              : 
     241            0 : void gl_checkextensions()
     242              : {
     243            0 :     bool mesa   = false,
     244            0 :          intel  = false,
     245            0 :          amd    = false,
     246            0 :          nvidia = false;
     247            0 :     const char *vendor   = reinterpret_cast<const char *>(glGetString(GL_VENDOR)),
     248            0 :                *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)),
     249            0 :                *version  = reinterpret_cast<const char *>(glGetString(GL_VERSION));
     250            0 :     conoutf(Console_Init, "Renderer: %s (%s)", renderer, vendor);
     251            0 :     conoutf(Console_Init, "Driver: %s", version);
     252              : 
     253            0 :     if(!renderer || !vendor || !version)
     254              :     {
     255            0 :         fatal("Could not get rendering context information!");
     256              :     }
     257            0 :     if(std::strstr(renderer, "Mesa") || std::strstr(version, "Mesa"))
     258              :     {
     259            0 :         mesa = true;
     260            0 :         if(std::strstr(renderer, "Intel"))
     261              :         {
     262            0 :             intel = true;
     263              :         }
     264              :     }
     265            0 :     else if(std::strstr(vendor, "NVIDIA"))
     266              :     {
     267            0 :         nvidia = true;
     268              :     }
     269            0 :     else if(std::strstr(vendor, "ATI") || std::strstr(vendor, "Advanced Micro Devices"))
     270              :     {
     271            0 :         amd = true;
     272              :     }
     273            0 :     else if(std::strstr(vendor, "Intel"))
     274              :     {
     275            0 :         intel = true;
     276              :     }
     277              : 
     278              :     uint glmajorversion, glminorversion;
     279            0 :     if(std::sscanf(version, " %u.%u", &glmajorversion, &glminorversion) != 2)
     280              :     {
     281            0 :         glversion = 100; //__really__ legacy systems (which won't run anyways)
     282              :     }
     283              :     else
     284              :     {
     285            0 :         glversion = glmajorversion*100 + glminorversion*10;
     286              :     }
     287            0 :     if(glversion < 400)
     288              :     {
     289            0 :         fatal("OpenGL 4.0 or greater is required!");
     290              :     }
     291              : 
     292            0 :     const char *glslstr = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION));
     293            0 :     conoutf(Console_Init, "GLSL: %s", glslstr ? glslstr : "unknown");
     294              : 
     295              :     uint glslmajorversion, glslminorversion;
     296            0 :     if(glslstr && std::sscanf(glslstr, " %u.%u", &glslmajorversion, &glslminorversion) == 2)
     297              :     {
     298            0 :         glslversion = glslmajorversion*100 + glslminorversion;
     299              :     }
     300            0 :     if(glslversion < 400)
     301              :     {
     302            0 :         fatal("GLSL 4.00 or greater is required!");
     303              :     }
     304            0 :     parseglexts();
     305            0 :     GLint texsize = 0,
     306            0 :           texunits = 0,
     307            0 :           vtexunits = 0,
     308            0 :           cubetexsize = 0,
     309            0 :           drawbufs = 0;
     310            0 :     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texsize);
     311            0 :     hwtexsize = texsize;
     312            0 :     if(hwtexsize < 4096)
     313              :     {
     314            0 :         fatal("Large texture support is required!");
     315              :     }
     316            0 :     glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texunits);
     317            0 :     hwtexunits = texunits;
     318            0 :     if(hwtexunits < 16)
     319              :     {
     320            0 :         fatal("Hardware does not support at least 16 texture units.");
     321              :     }
     322            0 :     glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vtexunits);
     323            0 :     hwvtexunits = vtexunits;
     324            0 :     if(hwvtexunits < 16)
     325              :     {
     326            0 :         fatal("Hardware does not support at least 16 vertex texture units.");
     327              :     }
     328            0 :     glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &cubetexsize);
     329            0 :     hwcubetexsize = cubetexsize;
     330            0 :     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &drawbufs);
     331            0 :     maxdrawbufs = drawbufs;
     332            0 :     if(maxdrawbufs < 4)
     333              :     {
     334            0 :         fatal("Hardware does not support at least 4 draw buffers.");
     335              :     }
     336              :     //OpenGL 3.0
     337              : 
     338            0 :     if(hasext("GL_EXT_gpu_shader4"))
     339              :     {
     340            0 :         hasEGPU4 = true;
     341            0 :         if(debugexts)
     342              :         {
     343            0 :             conoutf(Console_Init, "Using GL_EXT_gpu_shader4 extension.");
     344              :         }
     345              :     }
     346            0 :     glRenderbufferStorageMultisample_ = reinterpret_cast<PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC>(getprocaddress("glRenderbufferStorageMultisample"));
     347              : 
     348              :     //OpenGL 3.2
     349            0 :     glTexImage2DMultisample_ = reinterpret_cast<PFNGLTEXIMAGE2DMULTISAMPLEPROC>(getprocaddress("glTexImage2DMultisample"));
     350            0 :     if(hasext("GL_EXT_framebuffer_multisample_blit_scaled"))
     351              :     {
     352            0 :         hasFBMSBS = true;
     353            0 :         if(debugexts)
     354              :         {
     355            0 :             conoutf(Console_Init, "Using GL_EXT_framebuffer_multisample_blit_scaled extension.");
     356              :         }
     357              :     }
     358              :     //OpenGL 3.3
     359            0 :     if(hasext("GL_EXT_texture_filter_anisotropic"))
     360              :     {
     361            0 :         GLint val = 0;
     362            0 :         glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val);
     363            0 :         hwmaxaniso = val;
     364            0 :         if(debugexts)
     365              :         {
     366            0 :             conoutf(Console_Init, "Using GL_EXT_texture_filter_anisotropic extension.");
     367              :         }
     368              :     }
     369              :     else
     370              :     {
     371            0 :         fatal("Anisotropic filtering support is required!");
     372              :     }
     373            0 :     if(hasext("GL_EXT_depth_bounds_test"))
     374              :     {
     375            0 :         glDepthBounds_ = reinterpret_cast<PFNGLDEPTHBOUNDSEXTPROC>(getprocaddress("glDepthBoundsEXT"));
     376            0 :         hasDBT = true;
     377            0 :         if(debugexts)
     378              :         {
     379            0 :             conoutf(Console_Init, "Using GL_EXT_depth_bounds_test extension.");
     380              :         }
     381              :     }
     382            0 :     GLint dualbufs = 0;
     383            0 :     glGetIntegerv(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS, &dualbufs);
     384            0 :     maxdualdrawbufs = dualbufs;
     385            0 :     usetexgather = !intel && !nvidia ? 2 : 1;
     386              :     //OpenGL 4.x
     387            0 :     if(glversion >= 430 || hasext("GL_ARB_ES3_compatibility"))
     388              :     {
     389            0 :         hasES3 = true;
     390            0 :         if(glversion < 430 && debugexts)
     391              :         {
     392            0 :             conoutf(Console_Init, "Using GL_ARB_ES3_compatibility extension.");
     393              :         }
     394              :     }
     395              : 
     396            0 :     if(glversion >= 430 || hasext("GL_ARB_copy_image"))
     397              :     {
     398            0 :         glCopyImageSubData_ = reinterpret_cast<PFNGLCOPYIMAGESUBDATAPROC>(getprocaddress("glCopyImageSubData"));
     399              : 
     400            0 :         hasCI = true;
     401            0 :         if(glversion < 430 && debugexts)
     402              :         {
     403            0 :             conoutf(Console_Init, "Using GL_ARB_copy_image extension.");
     404              :         }
     405              :     }
     406            0 :     else if(hasext("GL_NV_copy_image"))
     407              :     {
     408            0 :         glCopyImageSubData_ = reinterpret_cast<PFNGLCOPYIMAGESUBDATAPROC>(getprocaddress("glCopyImageSubDataNV"));
     409              : 
     410            0 :         hasCI = true;
     411            0 :         if(debugexts)
     412              :         {
     413            0 :             conoutf(Console_Init, "Using GL_NV_copy_image extension.");
     414              :         }
     415              :     }
     416              : 
     417            0 :     if(amd)
     418              :     {
     419            0 :         msaalineardepth = glineardepth = 1; // reading back from depth-stencil still buggy on newer cards, and requires stencil for MSAA
     420              :     }
     421            0 :     else if(nvidia) //no errata on nvidia cards (yet)
     422              :     {
     423              :     }
     424            0 :     else if(intel)
     425              :     {
     426            0 :         smgather = 1; // native shadow filter is slow
     427            0 :         if(mesa)
     428              :         {
     429            0 :             batchsunlight = 0; // causes massive slowdown in linux driver
     430            0 :             msaalineardepth = 1; // MSAA depth texture access is buggy and resolves are slow
     431              :         }
     432              :         else
     433              :         {
     434              :             // causes massive slowdown in windows driver if reading depth-stencil texture
     435            0 :             if(checkdepthtexstencilrb())
     436              :             {
     437            0 :                 gdepthstencil = 1;
     438            0 :                 gstencil = 1;
     439              :             }
     440              :             // sampling alpha by itself from a texture generates garbage on Intel drivers on Windows
     441            0 :             intel_texalpha_bug = 1;
     442              :         }
     443              :     }
     444            0 :     if(mesa)
     445              :     {
     446            0 :         mesa_swap_bug = 1;
     447              :     }
     448            0 :     tqaaresolvegather = 1;
     449            0 : }
     450              : 
     451              : /**
     452              :  * @brief checks for existence of glext
     453              :  *
     454              :  * returns to console 1 if hashtable glexts contains glext (with the name passed)
     455              :  * and returns 0 otherwise
     456              :  *
     457              :  * glexts is a global variable
     458              :  *
     459              :  * @param ext the ext to check for
     460              :  */
     461            1 : static void glext(const char *ext)
     462              : {
     463            1 :     intret(hasext(ext) ? 1 : 0);
     464            1 : }
     465              : 
     466              : 
     467            0 : void gl_resize()
     468              : {
     469            0 :     gl_setupframe();
     470            0 :     glViewport(0, 0, hudw(), hudh());
     471            0 : }
     472              : 
     473            0 : void gl_init()
     474              : {
     475            0 :     glerror();
     476              : 
     477            0 :     glClearColor(0, 0, 0, 0);
     478            0 :     glClearDepth(1);
     479            0 :     glClearStencil(0);
     480            0 :     glDepthFunc(GL_LESS);
     481            0 :     glDisable(GL_DEPTH_TEST);
     482            0 :     glDisable(GL_STENCIL_TEST);
     483            0 :     glStencilFunc(GL_ALWAYS, 0, ~0);
     484            0 :     glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
     485              : 
     486            0 :     glEnable(GL_LINE_SMOOTH);
     487              :     //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
     488              : 
     489            0 :     glFrontFace(GL_CW);
     490            0 :     glCullFace(GL_BACK);
     491            0 :     glDisable(GL_CULL_FACE);
     492              : 
     493            0 :     gle::setup();
     494            0 :     setupshaders();
     495              : 
     496            0 :     glerror();
     497              : 
     498            0 :     gl_resize();
     499            0 : }
     500              : 
     501              : VAR(wireframe, 0, 0, 1); //used in rendergl.h
     502              : 
     503              : vec worldpos; //used in iengine
     504              : 
     505              : //these three cam() functions replace global variables that previously tracked their respective transforms of cammatrix
     506            0 : vec camdir()
     507              : {
     508            0 :     vec out;
     509            0 :     cammatrix.transposedtransformnormal(vec(viewmatrix.b), out);
     510            0 :     return out;
     511              : }
     512              : 
     513            0 : vec camright()
     514              : {
     515            0 :     vec out;
     516            0 :     cammatrix.transposedtransformnormal(vec(viewmatrix.a).neg(), out);
     517            0 :     return out;
     518              : }
     519              : 
     520            0 : vec camup()
     521              : {
     522            0 :     vec out;
     523            0 :     cammatrix.transposedtransformnormal(vec(viewmatrix.c), out);
     524            0 :     return out;
     525              : }
     526              : 
     527            0 : static void setcammatrix()
     528              : {
     529              :     // move from RH to Z-up LH quake style worldspace
     530            0 :     cammatrix = viewmatrix;
     531            0 :     cammatrix.rotate_around_y(camera1->roll/RAD);
     532            0 :     cammatrix.rotate_around_x(camera1->pitch/-RAD);
     533            0 :     cammatrix.rotate_around_z(camera1->yaw/-RAD);
     534            0 :     cammatrix.translate(vec(camera1->o).neg());
     535              : 
     536            0 :     if(!drawtex)
     537              :     {
     538            0 :         if(raycubepos(camera1->o, camdir(), worldpos, 0, Ray_ClipMat|Ray_SkipFirst) == -1)
     539              :         {
     540            0 :             worldpos = camdir().mul(2*rootworld.mapsize()).add(camera1->o); // if nothing is hit, just far away in the view direction
     541              :         }
     542              :     }
     543            0 : }
     544              : 
     545            0 : void setcamprojmatrix(bool init = true, bool flush = false)
     546              : {
     547            0 :     if(init)
     548              :     {
     549            0 :         setcammatrix();
     550              :     }
     551            0 :     jitteraa();
     552            0 :     camprojmatrix.muld(projmatrix, cammatrix);
     553            0 :     GLOBALPARAM(camprojmatrix, camprojmatrix);
     554            0 :     GLOBALPARAM(lineardepthscale, projmatrix.lineardepthscale()); //(invprojmatrix.c.z, invprojmatrix.d.z));
     555            0 :     if(flush && Shader::lastshader)
     556              :     {
     557            0 :         Shader::lastshader->flushparams();
     558              :     }
     559            0 : }
     560              : 
     561              : matrix4 hudmatrix;
     562              : static std::array<matrix4, 64> hudmatrixstack;
     563              : 
     564              : int hudmatrixpos = 0;
     565              : 
     566            0 : void resethudmatrix()
     567              : {
     568            0 :     hudmatrixpos = 0;
     569            0 :     GLOBALPARAM(hudmatrix, hudmatrix);
     570            0 : }
     571              : 
     572            0 : void pushhudmatrix()
     573              : {
     574            0 :     if(hudmatrixpos >= 0 && hudmatrixpos < static_cast<int>(sizeof(hudmatrixstack)/sizeof(hudmatrixstack[0])))
     575              :     {
     576            0 :         hudmatrixstack[hudmatrixpos] = hudmatrix;
     577              :     }
     578            0 :     ++hudmatrixpos;
     579            0 : }
     580              : 
     581            0 : void flushhudmatrix(bool flushparams)
     582              : {
     583            0 :     GLOBALPARAM(hudmatrix, hudmatrix);
     584            0 :     if(flushparams && Shader::lastshader)
     585              :     {
     586            0 :         Shader::lastshader->flushparams();
     587              :     }
     588            0 : }
     589              : 
     590            0 : void pophudmatrix(bool flush, bool flushparams)
     591              : {
     592            0 :     --hudmatrixpos;
     593            0 :     if(hudmatrixpos >= 0 && hudmatrixpos < static_cast<int>(sizeof(hudmatrixstack)/sizeof(hudmatrixstack[0])))
     594              :     {
     595            0 :         hudmatrix = hudmatrixstack[hudmatrixpos];
     596            0 :         if(flush)
     597              :         {
     598            0 :             flushhudmatrix(flushparams);
     599              :         }
     600              :     }
     601            0 : }
     602              : 
     603            0 : void pushhudscale(float scale)
     604              : {
     605            0 :     pushhudmatrix();
     606            0 :     hudmatrix.scale(scale, scale, 1);
     607            0 :     flushhudmatrix();
     608            0 : }
     609              : 
     610            0 : void pushhudtranslate(float tx, float ty, float sx, float sy)
     611              : {
     612            0 :     if(!sy)
     613              :     {
     614            0 :         sy = sx;
     615              :     }
     616            0 :     pushhudmatrix();
     617            0 :     hudmatrix.translate(tx, ty, 0);
     618            0 :     if(sy)
     619              :     {
     620            0 :         hudmatrix.scale(sx, sy, 1);
     621              :     }
     622            0 :     flushhudmatrix();
     623            0 : }
     624              : 
     625              : float curfov, aspect, fovy;
     626              : static float curavatarfov;
     627              : int farplane;
     628              : static VARP(zoominvel, 0, 40, 500);
     629              : static VARP(zoomoutvel, 0, 50, 500);
     630              : static VARP(zoomfov, 10, 42, 90);
     631              : static VARP(fov, 10, 100, 150);
     632              : static VAR(avatarzoomfov, 1, 1, 1);
     633              : static VAR(avatarfov, 10, 40, 100);
     634              : static FVAR(avatardepth, 0, 0.7f, 1);
     635              : FVARNP(aspect, forceaspect, 0, 0, 1e3f);
     636              : 
     637              : static float zoomprogress = 0;
     638              : VAR(zoom, -1, 0, 1);
     639              : 
     640              : //used in iengine
     641            0 : void disablezoom()
     642              : {
     643            0 :     zoom = 0;
     644            0 :     zoomprogress = 0;
     645            0 : }
     646              : 
     647              : //used in iengine
     648            0 : void computezoom()
     649              : {
     650            0 :     if(!zoom)
     651              :     {
     652            0 :         zoomprogress = 0;
     653            0 :         curfov = fov;
     654            0 :         curavatarfov = avatarfov;
     655            0 :         return;
     656              :     }
     657            0 :     if(zoom > 0)
     658              :     {
     659            0 :         zoomprogress = zoominvel ? std::min(zoomprogress + static_cast<float>(elapsedtime) / zoominvel, 1.0f) : 1;
     660              :     }
     661              :     else
     662              :     {
     663            0 :         zoomprogress = zoomoutvel ? std::max(zoomprogress - static_cast<float>(elapsedtime) / zoomoutvel, 0.0f) : 0;
     664            0 :         if(zoomprogress <= 0)
     665              :         {
     666            0 :             zoom = 0;
     667              :         }
     668              :     }
     669            0 :     curfov = zoomfov*zoomprogress + fov*(1 - zoomprogress);
     670            0 :     curavatarfov = avatarzoomfov*zoomprogress + avatarfov*(1 - zoomprogress);
     671              : }
     672              : 
     673              : static FVARP(zoomsens, 1e-4f, 4.5f, 1e4f);
     674              : static FVARP(zoomaccel, 0, 0, 1000);
     675              : static VARP(zoomautosens, 0, 1, 1);
     676              : static FVARP(sensitivity, 0.01f, 3, 100.f);
     677              : static FVARP(sensitivityscale, 1e-4f, 100, 1e4f);
     678              : /* Sensitivity scales:
     679              :  * 100: Quake/Source (TF2, Q3, Apex, L4D)
     680              :  * 333: COD, Destiny, Overwatch, ~BL2/3
     681              :  * 400: Cube/RE
     682              :  */
     683              : static VARP(invmouse, 0, 0, 1); //toggles inverting the mouse
     684              : static FVARP(mouseaccel, 0, 0, 1000);
     685              : 
     686              : physent *camera1 = nullptr;
     687              : //used in iengine.h
     688              : bool detachedcamera = false;
     689              : 
     690              : //used in iengine.h
     691            0 : bool isthirdperson()
     692              : {
     693            0 :     return player!=camera1 || detachedcamera;
     694              : }
     695              : 
     696            0 : void fixcamerarange()
     697              : {
     698            0 :     constexpr float maxpitch = 90.0f;
     699            0 :     if(camera1->pitch>maxpitch)
     700              :     {
     701            0 :         camera1->pitch = maxpitch;
     702              :     }
     703            0 :     if(camera1->pitch<-maxpitch)
     704              :     {
     705            0 :         camera1->pitch = -maxpitch;
     706              :     }
     707            0 :     while(camera1->yaw<0.0f)
     708              :     {
     709            0 :         camera1->yaw += 360.0f;
     710              :     }
     711            0 :     while(camera1->yaw>=360.0f)
     712              :     {
     713            0 :         camera1->yaw -= 360.0f;
     714              :     }
     715            0 : }
     716              : 
     717            0 : void modifyorient(float yaw, float pitch)
     718              : {
     719            0 :     camera1->yaw += yaw;
     720            0 :     camera1->pitch += pitch;
     721            0 :     fixcamerarange();
     722            0 :     if(camera1!=player && !detachedcamera)
     723              :     {
     724            0 :         player->yaw = camera1->yaw;
     725            0 :         player->pitch = camera1->pitch;
     726              :     }
     727            0 : }
     728              : 
     729            0 : void mousemove(int dx, int dy)
     730              : {
     731            0 :     float cursens  = sensitivity,
     732            0 :           curaccel = mouseaccel;
     733            0 :     if(zoom)
     734              :     {
     735            0 :         if(zoomautosens)
     736              :         {
     737            0 :             cursens  = static_cast<float>(sensitivity*zoomfov)/fov;
     738            0 :             curaccel = static_cast<float>(mouseaccel*zoomfov)/fov;
     739              :         }
     740              :         else
     741              :         {
     742            0 :             cursens = zoomsens;
     743            0 :             curaccel = zoomaccel;
     744              :         }
     745              :     }
     746            0 :     if(curaccel && curtime && (dx || dy))
     747              :     {
     748            0 :         cursens += curaccel * sqrtf(dx*dx + dy*dy)/curtime;
     749              :     }
     750            0 :     cursens /= (sensitivityscale/4); //hard factor of 4 for 40 dots/deg like Quake/Source/etc.
     751            0 :     modifyorient(dx*cursens, dy*cursens*(invmouse ? 1 : -1));
     752            0 : }
     753              : 
     754              : matrix4 cammatrix, projmatrix, camprojmatrix;
     755              : 
     756              : FVAR(nearplane, 0.01f, 0.54f, 2.0f); //used in rendergl
     757              : 
     758            0 : vec calcavatarpos(const vec &pos, float dist)
     759              : {
     760            0 :     vec eyepos;
     761            0 :     cammatrix.transform(pos, eyepos);
     762            0 :     GLdouble ydist = nearplane * std::tan(curavatarfov/(2*RAD)),
     763            0 :              xdist = ydist * aspect;
     764            0 :     vec4<float> scrpos;
     765            0 :     scrpos.x = eyepos.x*nearplane/xdist;
     766            0 :     scrpos.y = eyepos.y*nearplane/ydist;
     767            0 :     scrpos.z = (eyepos.z*(farplane + nearplane) - 2*nearplane*farplane) / (farplane - nearplane);
     768            0 :     scrpos.w = -eyepos.z;
     769              : 
     770            0 :     vec worldpos = camprojmatrix.inverse().perspectivetransform(scrpos);
     771            0 :     vec dir = vec(worldpos).sub(camera1->o).rescale(dist);
     772            0 :     return dir.add(camera1->o);
     773              : }
     774              : 
     775            0 : void renderavatar(void (*hudfxn)())
     776              : {
     777            0 :     if(isthirdperson())
     778              :     {
     779            0 :         return;
     780              :     }
     781            0 :     matrix4 oldprojmatrix = nojittermatrix;
     782            0 :     projmatrix.perspective(curavatarfov, aspect, nearplane, farplane);
     783            0 :     projmatrix.scalez(avatardepth);
     784            0 :     setcamprojmatrix(false);
     785              : 
     786            0 :     enableavatarmask();
     787            0 :     hudfxn();
     788            0 :     disableavatarmask();
     789              : 
     790            0 :     projmatrix = oldprojmatrix;
     791            0 :     setcamprojmatrix(false);
     792              : }
     793              : 
     794              : static FVAR(polygonoffsetfactor, -1e4f, -3.0f, 1e4f);
     795              : static FVAR(polygonoffsetunits, -1e4f, -3.0f, 1e4f);
     796              : static FVAR(depthoffset, -1e4f, 0.01f, 1e4f);
     797              : 
     798              : static matrix4 nooffsetmatrix;
     799              : 
     800              : //used in rendergl.h
     801            0 : void enablepolygonoffset(GLenum type)
     802              : {
     803            0 :     if(!depthoffset)
     804              :     {
     805            0 :         glPolygonOffset(polygonoffsetfactor, polygonoffsetunits);
     806            0 :         glEnable(type);
     807            0 :         return;
     808              :     }
     809              : 
     810            0 :     projmatrix = nojittermatrix;
     811            0 :     nooffsetmatrix = projmatrix;
     812            0 :     projmatrix.d.z += depthoffset * projmatrix.c.z;
     813            0 :     setcamprojmatrix(false, true);
     814              : }
     815              : 
     816              : //used in rendergl.h
     817            0 : void disablepolygonoffset(GLenum type)
     818              : {
     819            0 :     if(!depthoffset)
     820              :     {
     821            0 :         glDisable(type);
     822            0 :         return;
     823              :     }
     824              : 
     825            0 :     projmatrix = nooffsetmatrix;
     826            0 :     setcamprojmatrix(false, true);
     827              : }
     828              : 
     829              : //used in renderlights
     830            0 : bool calcspherescissor(const vec &center, float size, float &sx1, float &sy1, float &sx2, float &sy2, float &sz1, float &sz2)
     831              : {
     832              :     //dim must be 0..2
     833              :     //dir should be +/- 1
     834            0 :     auto checkplane = [] (int dim, const float &dc, int dir, float focaldist, float &low, float &high, const float &cz, const float &drt, const vec &e) -> void
     835              :     {
     836            0 :         float nzc = (cz*cz + 1) / (cz + dir*drt) - cz,
     837            0 :               pz = dc/(nzc*e[dim] - e.z);
     838            0 :         if(pz > 0)
     839              :         {
     840            0 :             float c = (focaldist)*nzc,
     841            0 :                   pc = pz*nzc;
     842            0 :             if(pc < e[dim])
     843              :             {
     844            0 :                 low = c;
     845              :             }
     846            0 :             else if(pc > e[dim])
     847              :             {
     848            0 :                 high = c;
     849              :             }
     850              :         }
     851            0 :     };
     852              : 
     853            0 :     vec e;
     854            0 :     cammatrix.transform(center, e);
     855            0 :     if(e.z > 2*size)
     856              :     {
     857            0 :         sx1 = sy1 = sz1 =  1;
     858            0 :         sx2 = sy2 = sz2 = -1;
     859            0 :         return false;
     860              :     }
     861            0 :     if(drawtex == Draw_TexMinimap)
     862              :     {
     863            0 :         vec dir(size, size, size);
     864            0 :         if(projmatrix.a.x < 0)
     865              :         {
     866            0 :             dir.x = -dir.x;
     867              :         }
     868            0 :         if(projmatrix.b.y < 0)
     869              :         {
     870            0 :             dir.y = -dir.y;
     871              :         }
     872            0 :         if(projmatrix.c.z < 0)
     873              :         {
     874            0 :             dir.z = -dir.z;
     875              :         }
     876            0 :         sx1 = std::max(projmatrix.a.x*(e.x - dir.x) + projmatrix.d.x, -1.0f);
     877            0 :         sx2 = std::min(projmatrix.a.x*(e.x + dir.x) + projmatrix.d.x, 1.0f);
     878            0 :         sy1 = std::max(projmatrix.b.y*(e.y - dir.y) + projmatrix.d.y, -1.0f);
     879            0 :         sy2 = std::min(projmatrix.b.y*(e.y + dir.y) + projmatrix.d.y, 1.0f);
     880            0 :         sz1 = std::max(projmatrix.c.z*(e.z - dir.z) + projmatrix.d.z, -1.0f);
     881            0 :         sz2 = std::min(projmatrix.c.z*(e.z + dir.z) + projmatrix.d.z, 1.0f);
     882            0 :         return sx1 < sx2 && sy1 < sy2 && sz1 < sz2;
     883              :     }
     884            0 :     float zzrr = e.z*e.z - size*size,
     885            0 :           dx = e.x*e.x + zzrr,
     886            0 :           dy = e.y*e.y + zzrr,
     887            0 :           focaldist = 1.0f/std::tan(fovy*0.5f/RAD);
     888            0 :     sx1 = sy1 = -1;
     889            0 :     sx2 = sy2 = 1;
     890            0 :     if(dx > 0)
     891              :     {
     892            0 :         float cz  = e.x/e.z,
     893            0 :               drt = sqrtf(dx)/size;
     894            0 :         checkplane(0, dx, -1, focaldist/aspect, sx1, sx2, cz, drt, e);
     895            0 :         checkplane(0, dx,  1, focaldist/aspect, sx1, sx2, cz, drt, e);
     896              :     }
     897            0 :     if(dy > 0)
     898              :     {
     899            0 :         float cz  = e.y/e.z,
     900            0 :               drt = sqrtf(dy)/size;
     901            0 :         checkplane(1, dy, -1, focaldist, sy1, sy2, cz, drt, e);
     902            0 :         checkplane(1, dy,  1, focaldist, sy1, sy2, cz, drt, e);
     903              :     }
     904            0 :     float z1 = std::min(e.z + size, -1e-3f - nearplane),
     905            0 :           z2 = std::min(e.z - size, -1e-3f - nearplane);
     906            0 :     sz1 = (z1*projmatrix.c.z + projmatrix.d.z) / (z1*projmatrix.c.w + projmatrix.d.w);
     907            0 :     sz2 = (z2*projmatrix.c.z + projmatrix.d.z) / (z2*projmatrix.c.w + projmatrix.d.w);
     908            0 :     return sx1 < sx2 && sy1 < sy2 && sz1 < sz2;
     909              : }
     910              : 
     911              : //used in rendergl.h
     912            0 : bool calcbbscissor(const ivec &bbmin, const ivec &bbmax, float &sx1, float &sy1, float &sx2, float &sy2)
     913              : {
     914            0 :     auto addxyscissor = [&] (const vec4<float> &p)
     915              :     {
     916            0 :         if(p.z >= -p.w)
     917              :         {
     918            0 :             float x = p.x / p.w,
     919            0 :                   y = p.y / p.w;
     920            0 :             sx1 = std::min(sx1, x);
     921            0 :             sy1 = std::min(sy1, y);
     922            0 :             sx2 = std::max(sx2, x);
     923            0 :             sy2 = std::max(sy2, y);
     924              :         }
     925            0 :     };
     926              : 
     927            0 :     std::array<vec4<float>, 8> v;
     928            0 :     sx1 = sy1 = 1;
     929            0 :     sx2 = sy2 = -1;
     930            0 :     camprojmatrix.transform(vec(bbmin.x, bbmin.y, bbmin.z), v[0]);
     931            0 :     addxyscissor(v[0]);
     932            0 :     camprojmatrix.transform(vec(bbmax.x, bbmin.y, bbmin.z), v[1]);
     933            0 :     addxyscissor(v[1]);
     934            0 :     camprojmatrix.transform(vec(bbmin.x, bbmax.y, bbmin.z), v[2]);
     935            0 :     addxyscissor(v[2]);
     936            0 :     camprojmatrix.transform(vec(bbmax.x, bbmax.y, bbmin.z), v[3]);
     937            0 :     addxyscissor(v[3]);
     938            0 :     camprojmatrix.transform(vec(bbmin.x, bbmin.y, bbmax.z), v[4]);
     939            0 :     addxyscissor(v[4]);
     940            0 :     camprojmatrix.transform(vec(bbmax.x, bbmin.y, bbmax.z), v[5]);
     941            0 :     addxyscissor(v[5]);
     942            0 :     camprojmatrix.transform(vec(bbmin.x, bbmax.y, bbmax.z), v[6]);
     943            0 :     addxyscissor(v[6]);
     944            0 :     camprojmatrix.transform(vec(bbmax.x, bbmax.y, bbmax.z), v[7]);
     945            0 :     addxyscissor(v[7]);
     946            0 :     if(sx1 > sx2 || sy1 > sy2)
     947              :     {
     948            0 :         return false;
     949              :     }
     950            0 :     for(int i = 0; i < 8; ++i)
     951              :     {
     952            0 :         const vec4<float> &p = v[i];
     953            0 :         if(p.z >= -p.w)
     954              :         {
     955            0 :             continue;
     956              :         }
     957            0 :         for(int j = 0; j < 3; ++j)
     958              :         {
     959            0 :             const vec4<float> &o = v[i^(1<<j)];
     960            0 :             if(o.z <= -o.w)
     961              :             {
     962            0 :                 continue;
     963              :             }
     964              : 
     965            0 :             float t = (p.z + p.w)/(p.z + p.w - o.z - o.w),
     966            0 :                   w = p.w + t*(o.w - p.w),
     967            0 :                   x = (p.x + t*(o.x - p.x))/w,
     968            0 :                   y = (p.y + t*(o.y - p.y))/w;
     969            0 :             sx1 = std::min(sx1, x);
     970            0 :             sy1 = std::min(sy1, y);
     971            0 :             sx2 = std::max(sx2, x);
     972            0 :             sy2 = std::max(sy2, y);
     973              :         }
     974              :     }
     975              : 
     976              : 
     977            0 :     sx1 = std::max(sx1, -1.0f);
     978            0 :     sy1 = std::max(sy1, -1.0f);
     979            0 :     sx2 = std::min(sx2, 1.0f);
     980            0 :     sy2 = std::min(sy2, 1.0f);
     981            0 :     return true;
     982              : }
     983              : 
     984              : //used in renderlights
     985            0 : bool calcspotscissor(const vec &origin, float radius, const vec &dir, int spot, const vec &spotx, const vec &spoty, float &sx1, float &sy1, float &sx2, float &sy2, float &sz1, float &sz2)
     986              : {
     987            0 :     static auto addxyzscissor = [] (const vec4<float> &p, float &sx1, float &sy1, float &sx2, float &sy2, float &sz1, float &sz2) -> void
     988              :     {
     989            0 :         if(p.z >= -p.w)
     990              :         {
     991            0 :             float x = p.x / p.w,
     992            0 :                   y = p.y / p.w,
     993            0 :                   z = p.z / p.w;
     994            0 :             sx1 = std::min(sx1, x);
     995            0 :             sy1 = std::min(sy1, y);
     996            0 :             sz1 = std::min(sz1, z);
     997            0 :             sx2 = std::max(sx2, x);
     998            0 :             sy2 = std::max(sy2, y);
     999            0 :             sz2 = std::max(sz2, z);
    1000              :         }
    1001            0 :     };
    1002            0 :     float spotscale = radius * tan360(spot);
    1003            0 :     vec up     = vec(spotx).mul(spotscale),
    1004            0 :         right  = vec(spoty).mul(spotscale),
    1005            0 :         center = vec(dir).mul(radius).add(origin);
    1006            0 :     std::array<vec4<float>, 5> v;
    1007            0 :     sx1 = sy1 = sz1 = 1;
    1008            0 :     sx2 = sy2 = sz2 = -1;
    1009            0 :     camprojmatrix.transform(vec(center).sub(right).sub(up), v[0]);
    1010            0 :     addxyzscissor(v[0], sx1, sy1, sx2, sy2, sz1, sz2);
    1011            0 :     camprojmatrix.transform(vec(center).add(right).sub(up), v[1]);
    1012            0 :     addxyzscissor(v[1], sx1, sy1, sx2, sy2, sz1, sz2);
    1013            0 :     camprojmatrix.transform(vec(center).sub(right).add(up), v[2]);
    1014            0 :     addxyzscissor(v[2], sx1, sy1, sx2, sy2, sz1, sz2);
    1015            0 :     camprojmatrix.transform(vec(center).add(right).add(up), v[3]);
    1016            0 :     addxyzscissor(v[3], sx1, sy1, sx2, sy2, sz1, sz2);
    1017            0 :     camprojmatrix.transform(origin, v[4]);
    1018            0 :     addxyzscissor(v[4], sx1, sy1, sx2, sy2, sz1, sz2);
    1019              : 
    1020            0 :     static auto interpxyzscissor = [] (const vec4<float> &p, const vec4<float> &o, float &sx1, float &sy1, float &sx2, float &sy2, float &sz1) -> void
    1021              :     {
    1022            0 :         float t = (p.z + p.w)/(p.z + p.w - o.z - o.w),
    1023            0 :               w = p.w + t*(o.w - p.w),
    1024            0 :               x = (p.x + t*(o.x - p.x))/w,
    1025            0 :               y = (p.y + t*(o.y - p.y))/w;
    1026            0 :         sx1 = std::min(sx1, x);
    1027            0 :         sy1 = std::min(sy1, y);
    1028            0 :         sz1 = std::min(sz1, -1.0f);
    1029            0 :         sx2 = std::max(sx2, x);
    1030            0 :         sy2 = std::max(sy2, y);
    1031            0 :     };
    1032              : 
    1033            0 :     if(sx1 > sx2 || sy1 > sy2 || sz1 > sz2)
    1034              :     {
    1035            0 :         return false;
    1036              :     }
    1037            0 :     for(int i = 0; i < 4; ++i)
    1038              :     {
    1039            0 :         const vec4<float> &p = v[i];
    1040            0 :         if(p.z >= -p.w)
    1041              :         {
    1042            0 :             continue;
    1043              :         }
    1044            0 :         for(int j = 0; j < 2; ++j)
    1045              :         {
    1046            0 :             const vec4<float> &o = v[i^(1<<j)];
    1047            0 :             if(o.z <= -o.w)
    1048              :             {
    1049            0 :                 continue;
    1050              :             }
    1051              : 
    1052            0 :             interpxyzscissor(p, o, sx1, sy1, sx2, sy2, sz1);
    1053              :         }
    1054            0 :         if(v[4].z > -v[4].w)
    1055              :         {
    1056            0 :             interpxyzscissor(p, v[4], sx1, sy1, sx2, sy2, sz1);
    1057              :         }
    1058              :     }
    1059            0 :     if(v[4].z < -v[4].w)
    1060              :     {
    1061            0 :         for(int j = 0; j < 4; ++j)
    1062              :         {
    1063            0 :             const vec4<float> &o = v[j];
    1064            0 :             if(o.z <= -o.w)
    1065              :             {
    1066            0 :                 continue;
    1067              :             }
    1068            0 :             interpxyzscissor(v[4], o, sx1, sy1, sx2, sy2, sz1);
    1069              :         }
    1070              :     }
    1071              : 
    1072            0 :     sx1 = std::max(sx1, -1.0f);
    1073            0 :     sy1 = std::max(sy1, -1.0f);
    1074            0 :     sz1 = std::max(sz1, -1.0f);
    1075            0 :     sx2 = std::min(sx2,  1.0f);
    1076            0 :     sy2 = std::min(sy2,  1.0f);
    1077            0 :     sz2 = std::min(sz2,  1.0f);
    1078            0 :     return true;
    1079              : }
    1080              : 
    1081              : static GLuint screenquadvbo = 0;
    1082              : 
    1083            0 : static void setupscreenquad()
    1084              : {
    1085            0 :     if(!screenquadvbo)
    1086              :     {
    1087            0 :         glGenBuffers(1, &screenquadvbo);
    1088            0 :         gle::bindvbo(screenquadvbo);
    1089            0 :         vec2 verts[4] = { vec2(1, -1), vec2(-1, -1), vec2(1, 1), vec2(-1, 1) };
    1090            0 :         glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
    1091            0 :         gle::clearvbo();
    1092              :     }
    1093            0 : }
    1094              : 
    1095            0 : static void cleanupscreenquad()
    1096              : {
    1097            0 :     if(screenquadvbo)
    1098              :     {
    1099            0 :         glDeleteBuffers(1, &screenquadvbo);
    1100            0 :         screenquadvbo = 0;
    1101              :     }
    1102            0 : }
    1103              : 
    1104            0 : void screenquad()
    1105              : {
    1106            0 :     setupscreenquad();
    1107            0 :     gle::bindvbo(screenquadvbo);
    1108            0 :     gle::enablevertex();
    1109            0 :     gle::vertexpointer(sizeof(vec2), nullptr, GL_FLOAT, 2);
    1110            0 :     glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    1111            0 :     gle::disablevertex();
    1112            0 :     gle::clearvbo();
    1113            0 : }
    1114              : 
    1115              : //sets screentexcoord0,screentexcoord1 in glsl
    1116            0 : static void setscreentexcoord(int i, float w, float h, float x = 0, float y = 0)
    1117              : {
    1118              :     static std::array<LocalShaderParam, 2> screentexcoord =
    1119              :     {
    1120              :         LocalShaderParam("screentexcoord0"),
    1121              :         LocalShaderParam("screentexcoord1")
    1122            0 :     };
    1123            0 :     screentexcoord[i].setf(w*0.5f, h*0.5f, x + w*0.5f, y + std::fabs(h)*0.5f);
    1124            0 : }
    1125              : 
    1126            0 : void screenquad(float sw, float sh)
    1127              : {
    1128            0 :     setscreentexcoord(0, sw, sh);
    1129            0 :     screenquad();
    1130            0 : }
    1131              : 
    1132            0 : void screenquad(float sw, float sh, float sw2, float sh2)
    1133              : {
    1134            0 :     setscreentexcoord(0, sw, sh);
    1135            0 :     setscreentexcoord(1, sw2, sh2);
    1136            0 :     screenquad();
    1137            0 : }
    1138              : 
    1139            0 : void screenquadoffset(float x, float y, float w, float h)
    1140              : {
    1141            0 :     setscreentexcoord(0, w, h, x, y);
    1142            0 :     screenquad();
    1143            0 : }
    1144              : 
    1145              : // creates a hud quad for hudquad, debugquad
    1146            0 : static void createhudquad(float x1, float y1, float x2, float y2, float sx1, float sy1, float sx2, float sy2) {
    1147            0 :     gle::defvertex(2);
    1148            0 :     gle::deftexcoord0();
    1149            0 :     gle::begin(GL_TRIANGLE_STRIP);
    1150            0 :     gle::attribf(x2, y1); gle::attribf(sx2, sy1);
    1151            0 :     gle::attribf(x1, y1); gle::attribf(sx1, sy1);
    1152            0 :     gle::attribf(x2, y2); gle::attribf(sx2, sy2);
    1153            0 :     gle::attribf(x1, y2); gle::attribf(sx1, sy2);
    1154            0 :     gle::end();
    1155            0 : }
    1156              : 
    1157            0 : void hudquad(float x, float y, float w, float h, float tx, float ty, float tw, float th)
    1158              : {
    1159            0 :     createhudquad(x, y, x+w, y+h, tx, ty, tx+tw, ty+th);
    1160            0 : }
    1161              : 
    1162            0 : void debugquad(float x, float y, float w, float h, float tx, float ty, float tw, float th)
    1163              : {
    1164            0 :     createhudquad(x, y, x+w, y+h, tx, ty+th, tx+tw, ty);
    1165            0 : }
    1166              : 
    1167              : //used in iengine
    1168              : VARR(fog, 16, 4000, 1000024);
    1169            0 : static CVARR(fogcolor, 0x8099B3);
    1170              : static VAR(fogoverlay, 0, 1, 1);
    1171              : 
    1172            0 : static float findsurface(int fogmat, const vec &v, int &abovemat)
    1173              : {
    1174            0 :     fogmat &= MatFlag_Volume;
    1175            0 :     ivec o(v), co;
    1176              :     int csize;
    1177              :     do
    1178              :     {
    1179            0 :         const cube &c = rootworld.lookupcube(o, 0, co, csize);
    1180            0 :         int mat = c.material&MatFlag_Volume;
    1181            0 :         if(mat != fogmat)
    1182              :         {
    1183            0 :             abovemat = IS_LIQUID(mat) ? c.material : +Mat_Air;
    1184            0 :             return o.z;
    1185              :         }
    1186            0 :         o.z = co.z + csize;
    1187            0 :     } while(o.z < rootworld.mapsize());
    1188            0 :     abovemat = Mat_Air;
    1189            0 :     return rootworld.mapsize();
    1190              : }
    1191              : 
    1192            0 : static void blendfog(int fogmat, float below, float blend, float logblend, float &start, float &end, vec &fogc)
    1193              : {
    1194            0 :     switch(fogmat&MatFlag_Volume)
    1195              :     {
    1196            0 :         case Mat_Water:
    1197              :         {
    1198            0 :             const bvec &wcol = getwatercolor(fogmat),
    1199            0 :                        &wdeepcol = getwaterdeepcolor(fogmat);
    1200            0 :             int wfog = getwaterfog(fogmat),
    1201            0 :                 wdeep = getwaterdeep(fogmat);
    1202            0 :             float deepfade = std::clamp(below/std::max(wdeep, wfog), 0.0f, 1.0f);
    1203            0 :             vec color;
    1204            0 :             color.lerp(wcol.tocolor(), wdeepcol.tocolor(), deepfade);
    1205            0 :             fogc.add(vec(color).mul(blend));
    1206            0 :             end += logblend*std::min(fog, std::max(wfog*2, 16));
    1207            0 :             break;
    1208              :         }
    1209            0 :         default:
    1210              :         {
    1211            0 :             fogc.add(fogcolor.tocolor().mul(blend));
    1212            0 :             start += logblend*(fog+64)/8;
    1213            0 :             end += logblend*fog;
    1214            0 :             break;
    1215              :         }
    1216              :     }
    1217            0 : }
    1218              : 
    1219              : static vec curfogcolor(0, 0, 0);
    1220              : 
    1221            0 : void setfogcolor(const vec &v)
    1222              : {
    1223            0 :     GLOBALPARAM(fogcolor, v);
    1224            0 : }
    1225              : 
    1226            0 : void zerofogcolor()
    1227              : {
    1228            0 :     setfogcolor(vec(0, 0, 0));
    1229            0 : }
    1230              : 
    1231            0 : void resetfogcolor()
    1232              : {
    1233            0 :     setfogcolor(curfogcolor);
    1234            0 : }
    1235              : 
    1236              : static FVAR(fogintensity, 0, 0.15f, 1);
    1237              : 
    1238            0 : float calcfogdensity(float dist)
    1239              : {
    1240            0 :     return std::log(fogintensity)/(M_LN2*dist);
    1241              : }
    1242              : 
    1243              : static FVAR(fogcullintensity, 0, 1e-3f, 1);
    1244              : 
    1245            0 : float calcfogcull()
    1246              : {
    1247            0 :     return std::log(fogcullintensity) / (M_LN2*calcfogdensity(fog - (fog+64)/8));
    1248              : }
    1249              : 
    1250            0 : static void setfog(int fogmat, float below = 0, float blend = 1, int abovemat = Mat_Air)
    1251              : {
    1252            0 :     float start = 0,
    1253            0 :           end = 0,
    1254            0 :           logscale = 256,
    1255            0 :           logblend = std::log(1 + (logscale - 1)*blend) / std::log(logscale);
    1256              : 
    1257            0 :     curfogcolor = vec(0, 0, 0);
    1258            0 :     blendfog(fogmat, below, blend, logblend, start, end, curfogcolor);
    1259            0 :     if(blend < 1)
    1260              :     {
    1261            0 :         blendfog(abovemat, 0, 1-blend, 1-logblend, start, end, curfogcolor);
    1262              :     }
    1263            0 :     curfogcolor.mul(ldrscale);
    1264            0 :     GLOBALPARAM(fogcolor, curfogcolor);
    1265            0 :     float fogdensity = calcfogdensity(end-start);
    1266            0 :     GLOBALPARAMF(fogdensity, fogdensity, 1/std::exp(M_LN2*start*fogdensity));
    1267            0 : }
    1268              : 
    1269            0 : static void blendfogoverlay(int fogmat, float below, float blend, vec &overlay)
    1270              : {
    1271            0 :     switch(fogmat&MatFlag_Volume)
    1272              :     {
    1273            0 :         case Mat_Water:
    1274              :         {
    1275            0 :             const bvec &wcol = getwatercolor(fogmat),
    1276            0 :                        &wdeepcol = getwaterdeepcolor(fogmat);
    1277            0 :             const int wfog = getwaterfog(fogmat),
    1278            0 :                       wdeep = getwaterdeep(fogmat);
    1279            0 :             const float deepfade = std::clamp(below/std::max(wdeep, wfog), 0.0f, 1.0f);
    1280            0 :             vec color = vec(wcol.r(), wcol.g(), wcol.b()).lerp(vec(wdeepcol.r(), wdeepcol.g(), wdeepcol.b()), deepfade);
    1281            0 :             overlay.add(color.div(std::min(32.0f + std::max(color.r(), std::max(color.g(), color.b()))*7.0f/8.0f, 255.0f)).max(0.4f).mul(blend));
    1282            0 :             break;
    1283              :         }
    1284            0 :         default:
    1285              :         {
    1286            0 :             overlay.add(blend);
    1287            0 :             break;
    1288              :         }
    1289              :     }
    1290            0 : }
    1291              : 
    1292            0 : void drawfogoverlay(int fogmat, float fogbelow, float fogblend, int abovemat)
    1293              : {
    1294            0 :     SETSHADER(fogoverlay);
    1295              : 
    1296            0 :     glEnable(GL_BLEND);
    1297            0 :     glBlendFunc(GL_ZERO, GL_SRC_COLOR);
    1298            0 :     vec overlay(0, 0, 0);
    1299            0 :     blendfogoverlay(fogmat, fogbelow, fogblend, overlay);
    1300            0 :     blendfogoverlay(abovemat, 0, 1-fogblend, overlay);
    1301              : 
    1302            0 :     gle::color(overlay);
    1303            0 :     screenquad();
    1304              : 
    1305            0 :     glDisable(GL_BLEND);
    1306            0 : }
    1307              : 
    1308              : int drawtex = 0;
    1309              : 
    1310              : /* =========================== minimap functionality ======================== */
    1311              : 
    1312              : static GLuint minimaptex = 0;
    1313              : vec minimapcenter(0, 0, 0),
    1314              :     minimapradius(0, 0, 0),
    1315              :     minimapscale(0, 0, 0);
    1316              : 
    1317            0 : float calcfrustumboundsphere(float nearplane, float farplane,  const vec &pos, const vec &view, vec &center)
    1318              : {
    1319            0 :     if(drawtex == Draw_TexMinimap)
    1320              :     {
    1321            0 :         center = minimapcenter;
    1322            0 :         return minimapradius.magnitude();
    1323              :     }
    1324              : 
    1325            0 :     float width = std::tan(fov/(2.0f*RAD)),
    1326            0 :           height = width / aspect,
    1327            0 :           cdist = ((nearplane + farplane)/2)*(1 + width*width + height*height);
    1328            0 :     if(cdist <= farplane)
    1329              :     {
    1330            0 :         center = vec(view).mul(cdist).add(pos);
    1331            0 :         return vec(width*nearplane, height*nearplane, cdist-nearplane).magnitude();
    1332              :     }
    1333              :     else
    1334              :     {
    1335            0 :         center = vec(view).mul(farplane).add(pos);
    1336            0 :         return vec(width*farplane, height*farplane, 0).magnitude();
    1337              :     }
    1338              : }
    1339              : 
    1340            0 : void clearminimap()
    1341              : {
    1342            0 :     if(minimaptex)
    1343              :     {
    1344            0 :         glDeleteTextures(1, &minimaptex);
    1345            0 :         minimaptex = 0;
    1346              :     }
    1347            0 : }
    1348              : 
    1349              : static VARR(minimapheight, 0, 0, 2<<16); //height above bottom of map to render at
    1350            0 : static CVARR(minimapcolor, 0);
    1351              : static VARR(minimapclip, 0, 0, 1);
    1352              : static VARP(minimapsize, 7, 10, 12);      //2^n size of the minimap texture (along edge)
    1353              : static VARP(showminimap, 0, 1, 1);
    1354            0 : static CVARP(nominimapcolor, 0x101010);  //color for the part of the minimap that isn't the map texture
    1355              : 
    1356              : //used in iengine
    1357            0 : void bindminimap()
    1358              : {
    1359            0 :     glBindTexture(GL_TEXTURE_2D, minimaptex);
    1360            0 : }
    1361              : 
    1362            0 : static void clipminimap(ivec &bbmin, ivec &bbmax, const std::array<cube, 8> &c, const ivec &co = ivec(0, 0, 0), int size = rootworld.mapsize()>>1)
    1363              : {
    1364            0 :     for(int i = 0; i < 8; ++i)
    1365              :     {
    1366            0 :         ivec o(i, co, size);
    1367            0 :         if(c[i].children)
    1368              :         {
    1369            0 :             clipminimap(bbmin, bbmax, *(c[i].children), o, size>>1);
    1370              :         }
    1371            0 :         else if(!(c[i].issolid()) && (c[i].material&MatFlag_Clip)!=Mat_Clip)
    1372              :         {
    1373            0 :             for(int k = 0; k < 3; ++k)
    1374              :             {
    1375            0 :                 bbmin[k] = std::min(bbmin[k], o[k]);
    1376              :             }
    1377            0 :             for(int k = 0; k < 3; ++k)
    1378              :             {
    1379            0 :                 bbmax[k] = std::max(bbmax[k], o[k] + size);
    1380              :             }
    1381              :         }
    1382              :     }
    1383            0 : }
    1384              : 
    1385              : //used in iengine
    1386            0 : void drawminimap(int yaw, int pitch, vec loc, const cubeworld& world, int scalefactor)
    1387              : {
    1388            0 :     if(!showminimap)
    1389              :     {
    1390            0 :         if(!minimaptex)
    1391              :         {
    1392            0 :             glGenTextures(1, &minimaptex);
    1393              :         }
    1394              :         std::array<uchar, 3> v;
    1395            0 :         v[0] = nominimapcolor.r();
    1396            0 :         v[1] = nominimapcolor.g();
    1397            0 :         v[2] = nominimapcolor.b();
    1398            0 :         createtexture(minimaptex, 1, 1, v.data(), 3, 0, GL_RGB, GL_TEXTURE_2D);
    1399            0 :         return;
    1400              :     }
    1401              : 
    1402            0 :     glerror();
    1403              : 
    1404            0 :     drawtex = Draw_TexMinimap;
    1405              : 
    1406            0 :     glerror();
    1407            0 :     gl_setupframe(true);
    1408              : 
    1409            0 :     int size = 1<<minimapsize,
    1410            0 :         sizelimit = std::min(hwtexsize, std::min(gw, gh));
    1411            0 :     while(size > sizelimit)
    1412              :     {
    1413            0 :         size = size - 128;
    1414              :     }
    1415            0 :     if(!minimaptex)
    1416              :     {
    1417            0 :         glGenTextures(1, &minimaptex);
    1418              :     }
    1419            0 :     ivec bbmin(rootworld.mapsize(), rootworld.mapsize(), rootworld.mapsize()),
    1420            0 :          bbmax(0, 0, 0);
    1421            0 :     for(uint i = 0; i < valist.size(); i++)
    1422              :     {
    1423            0 :         const vtxarray *va = valist[i];
    1424            0 :         for(int k = 0; k < 3; ++k)
    1425              :         {
    1426            0 :             if(va->geommin[k]>va->geommax[k])
    1427              :             {
    1428            0 :                 continue;
    1429              :             }
    1430            0 :             bbmin[k] = std::min(bbmin[k], va->geommin[k]);
    1431            0 :             bbmax[k] = std::max(bbmax[k], va->geommax[k]);
    1432              :         }
    1433              :     }
    1434            0 :     if(minimapclip)
    1435              :     {
    1436            0 :         ivec clipmin(rootworld.mapsize(), rootworld.mapsize(), rootworld.mapsize()),
    1437            0 :              clipmax(0, 0, 0);
    1438            0 :         clipminimap(clipmin, clipmax, *world.worldroot);
    1439            0 :         for(int k = 0; k < 2; ++k)
    1440              :         {
    1441            0 :             bbmin[k] = std::max(bbmin[k], clipmin[k]);
    1442              :         }
    1443            0 :         for(int k = 0; k < 2; ++k)
    1444              :         {
    1445            0 :             bbmax[k] = std::min(bbmax[k], clipmax[k]);
    1446              :         }
    1447              :     }
    1448              : 
    1449            0 :     minimapradius = vec(bbmax).sub(vec(bbmin)).div(scalefactor);
    1450            0 :     minimapcenter = loc;
    1451            0 :     minimapradius.x = minimapradius.y = std::max(minimapradius.x, minimapradius.y);
    1452            0 :     minimapscale = vec((0.5f - 1.0f/size)/minimapradius.x, (0.5f - 1.0f/size)/minimapradius.y, 1.0f);
    1453              : 
    1454            0 :     physent *oldcamera = camera1;
    1455            0 :     physent cmcamera = *player;
    1456            0 :     cmcamera.reset();
    1457            0 :     cmcamera.type = physent::PhysEnt_Camera;
    1458            0 :     cmcamera.o = loc;
    1459            0 :     cmcamera.yaw = yaw;
    1460            0 :     cmcamera.pitch = pitch;
    1461            0 :     cmcamera.roll = 0;
    1462            0 :     camera1 = &cmcamera;
    1463              : 
    1464            0 :     float oldldrscale = ldrscale;
    1465            0 :     int oldfarplane = farplane,
    1466            0 :         oldvieww    = vieww,
    1467            0 :         oldviewh    = viewh;
    1468            0 :     farplane = rootworld.mapsize()*2;
    1469            0 :     vieww = viewh = size;
    1470              : 
    1471            0 :     float zscale = std::max(static_cast<float>(minimapheight), minimapcenter.z + minimapradius.z + 1) + 1;
    1472              : 
    1473            0 :     projmatrix.ortho(-minimapradius.x, minimapradius.x, -minimapradius.y, minimapradius.y, 0, 2*zscale);
    1474            0 :     setcamprojmatrix();
    1475              : 
    1476            0 :     glEnable(GL_CULL_FACE);
    1477            0 :     glEnable(GL_DEPTH_TEST);
    1478              : 
    1479            0 :     xtravertsva = xtraverts = glde = gbatches = vtris = vverts = 0;
    1480            0 :     occlusionengine.flipqueries();
    1481              : 
    1482            0 :     ldrscale = 1;
    1483              : 
    1484            0 :     view.visiblecubes(false);
    1485            0 :     gbuf.rendergbuffer();
    1486            0 :     gbuf.rendershadowatlas();
    1487              : 
    1488            0 :     gbuf.shademinimap(minimapcolor.tocolor().mul(ldrscale));
    1489              : 
    1490            0 :     if(minimapheight > 0 && minimapheight < minimapcenter.z + minimapradius.z)
    1491              :     {
    1492            0 :         camera1->o.z = minimapcenter.z + minimapradius.z + 1;
    1493            0 :         projmatrix.ortho(-minimapradius.x, minimapradius.x, -minimapradius.y, minimapradius.y, -zscale, zscale);
    1494            0 :         setcamprojmatrix();
    1495            0 :         gbuf.rendergbuffer(false);
    1496            0 :         gbuf.shademinimap();
    1497              :     }
    1498              : 
    1499            0 :     glDisable(GL_DEPTH_TEST);
    1500            0 :     glDisable(GL_CULL_FACE);
    1501              : 
    1502            0 :     farplane = oldfarplane;
    1503            0 :     vieww = oldvieww;
    1504            0 :     viewh = oldviewh;
    1505            0 :     ldrscale = oldldrscale;
    1506              : 
    1507            0 :     camera1 = oldcamera;
    1508            0 :     drawtex = 0;
    1509              : 
    1510            0 :     createtexture(minimaptex, size, size, nullptr, 3, 1, GL_RGB5, GL_TEXTURE_2D);
    1511            0 :     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    1512            0 :     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    1513            0 :     GLfloat border[4] = { minimapcolor.x/255.0f, minimapcolor.y/255.0f, minimapcolor.z/255.0f, 1.0f };
    1514            0 :     glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
    1515            0 :     glBindTexture(GL_TEXTURE_2D, 0);
    1516              : 
    1517            0 :     GLuint fbo = 0;
    1518            0 :     glGenFramebuffers(1, &fbo);
    1519            0 :     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    1520            0 :     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, minimaptex, 0);
    1521            0 :     copyhdr(size, size, fbo);
    1522            0 :     glBindFramebuffer(GL_FRAMEBUFFER, 0);
    1523            0 :     glDeleteFramebuffers(1, &fbo);
    1524              : 
    1525            0 :     glViewport(0, 0, hudw(), hudh());
    1526              : }
    1527              : 
    1528              : static VAR(modelpreviewfov, 10, 20, 100);    //y axis field of view
    1529              : static VAR(modelpreviewpitch, -90, -15, 90); //pitch above model to render
    1530              : 
    1531              : /* ======================== model preview windows =========================== */
    1532              : 
    1533              : 
    1534            0 : void ModelPreview::start(int xcoord, int ycoord, int width, int height, bool bg, bool usescissor)
    1535              : {
    1536            0 :     x = xcoord;
    1537            0 :     y = ycoord;
    1538            0 :     w = width;
    1539            0 :     h = height;
    1540            0 :     background = bg;
    1541            0 :     scissor = usescissor;
    1542              : 
    1543            0 :     gbuf.setupgbuffer();
    1544              : 
    1545            0 :     useshaderbyname("modelpreview");
    1546              : 
    1547            0 :     drawtex = Draw_TexModelPreview;
    1548              : 
    1549            0 :     oldcamera = camera1;
    1550            0 :     camera = *camera1;
    1551            0 :     camera.reset();
    1552            0 :     camera.type = physent::PhysEnt_Camera;
    1553            0 :     camera.o = vec(0, 0, 0);
    1554            0 :     camera.yaw = 0;
    1555            0 :     camera.pitch = modelpreviewpitch;
    1556            0 :     camera.roll = 0;
    1557            0 :     camera1 = &camera;
    1558              : 
    1559            0 :     oldaspect = aspect;
    1560            0 :     oldfovy = fovy;
    1561            0 :     oldfov = curfov;
    1562            0 :     oldldrscale = ldrscale;
    1563            0 :     oldfarplane = farplane;
    1564            0 :     oldvieww = vieww;
    1565            0 :     oldviewh = viewh;
    1566            0 :     oldprojmatrix = projmatrix;
    1567              : 
    1568            0 :     aspect = w/static_cast<float>(h);
    1569            0 :     fovy = modelpreviewfov;
    1570            0 :     curfov = 2*std::atan2(std::tan(fovy/(2*RAD)), 1/aspect)*RAD;
    1571            0 :     farplane = 1024;
    1572            0 :     vieww = std::min(gw, w);
    1573            0 :     viewh = std::min(gh, h);
    1574            0 :     ldrscale = 1;
    1575              : 
    1576            0 :     projmatrix.perspective(fovy, aspect, nearplane, farplane);
    1577            0 :     setcamprojmatrix();
    1578              : 
    1579            0 :     glEnable(GL_CULL_FACE);
    1580            0 :     glEnable(GL_DEPTH_TEST);
    1581            0 : }
    1582              : 
    1583            0 : void ModelPreview::end()
    1584              : {
    1585            0 :     gbuf.rendermodelbatches();
    1586              : 
    1587            0 :     glDisable(GL_DEPTH_TEST);
    1588            0 :     glDisable(GL_CULL_FACE);
    1589              : 
    1590            0 :     gbuf.shademodelpreview(x, y, w, h, background, scissor);
    1591              : 
    1592            0 :     aspect = oldaspect;
    1593            0 :     fovy = oldfovy;
    1594            0 :     curfov = oldfov;
    1595            0 :     farplane = oldfarplane;
    1596            0 :     vieww = oldvieww;
    1597            0 :     viewh = oldviewh;
    1598            0 :     ldrscale = oldldrscale;
    1599              : 
    1600            0 :     camera1 = oldcamera;
    1601            0 :     drawtex = 0;
    1602              : 
    1603            0 :     projmatrix = oldprojmatrix;
    1604            0 :     setcamprojmatrix();
    1605            0 : }
    1606              : 
    1607            0 : vec calcmodelpreviewpos(const vec &radius, float &yaw)
    1608              : {
    1609            0 :     yaw = std::fmod(lastmillis/10000.0f*360.0f, 360.0f);
    1610            0 :     float dist = std::max(radius.magnitude2()/aspect, radius.magnitude())/std::sin(fovy/(2*RAD));
    1611            0 :     return vec(0, dist, 0).rotate_around_x(camera1->pitch/RAD);
    1612              : }
    1613              : 
    1614              : int xtraverts, xtravertsva;
    1615              : 
    1616              : /* ============================= core rendering ============================= */
    1617              : 
    1618              : //main scene rendering function
    1619            0 : void gl_drawview(void (*gamefxn)(), void(*hudfxn)(), void(*editfxn)())
    1620              : {
    1621            0 :     GLuint scalefbo = gbuf.shouldscale();
    1622            0 :     if(scalefbo)
    1623              :     {
    1624            0 :         vieww = gw;
    1625            0 :         viewh = gh;
    1626              :     }
    1627            0 :     float fogmargin = 1 + wateramplitude + nearplane;
    1628            0 :     int fogmat = rootworld.lookupmaterial(vec(camera1->o.x, camera1->o.y, camera1->o.z - fogmargin))&(MatFlag_Volume|MatFlag_Index),
    1629            0 :         abovemat = Mat_Air;
    1630            0 :     float fogbelow = 0;
    1631            0 :     if(IS_LIQUID(fogmat&MatFlag_Volume)) //if in the water
    1632              :     {
    1633            0 :         float z = findsurface(fogmat, vec(camera1->o.x, camera1->o.y, camera1->o.z - fogmargin), abovemat) - wateroffset;
    1634            0 :         if(camera1->o.z < z + fogmargin)
    1635              :         {
    1636            0 :             fogbelow = z - camera1->o.z;
    1637              :         }
    1638              :         else
    1639              :         {
    1640            0 :             fogmat = abovemat;
    1641              :         }
    1642              :     }
    1643              :     else
    1644              :     {
    1645            0 :         fogmat = Mat_Air; //use air fog
    1646              :     }
    1647            0 :     setfog(abovemat);
    1648              :     //setfog(fogmat, fogbelow, 1, abovemat);
    1649              : 
    1650            0 :     farplane = rootworld.mapsize()*2;
    1651              :     //set the camera location
    1652            0 :     projmatrix.perspective(fovy, aspect, nearplane, farplane);
    1653            0 :     setcamprojmatrix();
    1654              : 
    1655            0 :     glEnable(GL_CULL_FACE);
    1656            0 :     glEnable(GL_DEPTH_TEST);
    1657              : 
    1658            0 :     ldrscale = 0.5f;
    1659              :     //do occlusion culling
    1660            0 :     view.visiblecubes();
    1661              :     //set to wireframe if applicable
    1662            0 :     if(wireframe && editmode)
    1663              :     {
    1664            0 :         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    1665              :     }
    1666              :     //construct g-buffer (build basic scene)
    1667            0 :     gbuf.rendergbuffer(true, gamefxn);
    1668            0 :     if(wireframe && editmode) //done with wireframe mode now
    1669              :     {
    1670            0 :         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    1671              :     }
    1672            0 :     else if(limitsky() && editmode)
    1673              :     {
    1674            0 :         renderexplicitsky(true);
    1675              :     }
    1676              : 
    1677              :     //ambient obscurance (ambient occlusion) on geometry & models only
    1678            0 :     gbuf.renderao();
    1679            0 :     glerror();
    1680              : 
    1681              :     // render avatar after AO to avoid weird contact shadows
    1682            0 :     renderavatar(hudfxn);
    1683            0 :     glerror();
    1684              : 
    1685              :     // render grass after AO to avoid disturbing shimmering patterns
    1686            0 :     generategrass();
    1687            0 :     rendergrass();
    1688            0 :     glerror();
    1689              : 
    1690            0 :     glFlush();
    1691              :     //global illumination
    1692            0 :     gbuf.renderradiancehints();
    1693            0 :     glerror();
    1694              :     //lighting
    1695            0 :     gbuf.rendershadowatlas();
    1696            0 :     glerror();
    1697              :     //shading
    1698            0 :     shadegbuffer();
    1699            0 :     glerror();
    1700              : 
    1701              :     //fog
    1702            0 :     if(fogmat)
    1703              :     {
    1704            0 :         setfog(fogmat, fogbelow, 1, abovemat);
    1705              : 
    1706            0 :         gbuf.renderwaterfog(fogmat, fogbelow);
    1707              : 
    1708            0 :         setfog(fogmat, fogbelow, std::clamp(fogbelow, 0.0f, 1.0f), abovemat);
    1709              :     }
    1710              : 
    1711              :     //alpha
    1712            0 :     gbuf.rendertransparent();
    1713            0 :     glerror();
    1714              : 
    1715            0 :     if(fogmat)
    1716              :     {
    1717            0 :         setfog(fogmat, fogbelow, 1, abovemat);
    1718              :     }
    1719              : 
    1720              :     //volumetric lights
    1721            0 :     gbuf.rendervolumetric();
    1722            0 :     glerror();
    1723              : 
    1724            0 :     if(editmode)
    1725              :     {
    1726            0 :         if(!wireframe && outline)
    1727              :         {
    1728            0 :             renderoutline(); //edit mode geometry outline
    1729              :         }
    1730            0 :         glerror();
    1731            0 :         rendereditmaterials();
    1732            0 :         glerror();
    1733            0 :         gbuf.renderparticles();
    1734            0 :         glerror();
    1735            0 :         if(showhud)
    1736              :         {
    1737            0 :             glDepthMask(GL_FALSE);
    1738            0 :             editfxn(); //edit cursor, passed as pointer
    1739            0 :             glDepthMask(GL_TRUE);
    1740              :         }
    1741              :     }
    1742              : 
    1743              :     //we're done with depth/geometry stuff so we don't need this functionality
    1744            0 :     glDisable(GL_CULL_FACE);
    1745            0 :     glDisable(GL_DEPTH_TEST);
    1746              : 
    1747            0 :     if(fogoverlay && fogmat != Mat_Air)
    1748              :     {
    1749            0 :         drawfogoverlay(fogmat, fogbelow, std::clamp(fogbelow, 0.0f, 1.0f), abovemat);
    1750              :     }
    1751              :     //antialiasing
    1752            0 :     doaa(setuppostfx(gbuf, vieww, viewh, scalefbo), gbuf);
    1753              :     //postfx
    1754            0 :     renderpostfx(scalefbo);
    1755            0 :     if(scalefbo)
    1756              :     {
    1757            0 :         gbuf.doscale();
    1758              :     }
    1759            0 : }
    1760              : 
    1761            0 : int renderw()
    1762              : {
    1763            0 :     return std::min(scr_w, screenw);
    1764              : }
    1765              : 
    1766            0 : int renderh()
    1767              : {
    1768            0 :     return std::min(scr_h, screenh);
    1769              : }
    1770              : 
    1771            0 : int hudw()
    1772              : {
    1773            0 :     return screenw;
    1774              : }
    1775              : 
    1776            0 : int hudh()
    1777              : {
    1778            0 :     return screenh;
    1779              : }
    1780              : 
    1781            0 : void gl_setupframe(bool force)
    1782              : {
    1783            0 :     if(!force)
    1784              :     {
    1785            0 :         return;
    1786              :     }
    1787            0 :     setuplights(gbuf);
    1788              : }
    1789              : 
    1790            0 : void gl_drawframe(int crosshairindex, void (*gamefxn)(), void (*hudfxn)(), void (*editfxn)(), void (*hud2d)())
    1791              : {
    1792            0 :     synctimers();
    1793            0 :     xtravertsva = xtraverts = glde = gbatches = vtris = vverts = 0;
    1794            0 :     occlusionengine.flipqueries();
    1795            0 :     aspect = forceaspect ? forceaspect : hudw()/static_cast<float>(hudh());
    1796            0 :     fovy = 2*std::atan2(std::tan(curfov/(2*RAD)), aspect)*RAD;
    1797            0 :     vieww = hudw();
    1798            0 :     viewh = hudh();
    1799            0 :     if(mainmenu)
    1800              :     {
    1801            0 :         gl_drawmainmenu();
    1802              :     }
    1803              :     else
    1804              :     {
    1805            0 :         gl_drawview(gamefxn, hudfxn, editfxn);
    1806              :     }
    1807            0 :     UI::render();
    1808            0 :     gl_drawhud(crosshairindex, hud2d);
    1809            0 : }
    1810              : 
    1811            0 : void cleanupgl()
    1812              : {
    1813            0 :     clearminimap();
    1814            0 :     cleanuptimers();
    1815            0 :     cleanupscreenquad();
    1816            0 :     gle::cleanup();
    1817            0 : }
    1818              : 
    1819            1 : void initrenderglcmds()
    1820              : {
    1821            1 :     addcommand("glext", reinterpret_cast<identfun>(glext), "s", Id_Command);
    1822            2 :     addcommand("getcamyaw", reinterpret_cast<identfun>(+[](){floatret(camera1 ? camera1->yaw : 0);}), "", Id_Command);
    1823            2 :     addcommand("getcampitch", reinterpret_cast<identfun>(+[](){floatret(camera1 ? camera1->pitch : 0);}), "", Id_Command);
    1824            2 :     addcommand("getcamroll", reinterpret_cast<identfun>(+[](){floatret(camera1 ? camera1->roll : 0);}), "", Id_Command);
    1825            1 :     addcommand("getcampos", reinterpret_cast<identfun>(+[]()
    1826              :     {
    1827            1 :         if(!camera1)
    1828              :         {
    1829            1 :             result("no camera");
    1830              :         }
    1831              :         else
    1832              :         {
    1833            0 :             std::string pos = std::format("{} {} {}",floatstr(camera1->o.x), floatstr(camera1->o.y), floatstr(camera1->o.z));
    1834            0 :             result(pos.c_str());
    1835            0 :         }
    1836            2 :     }), "", Id_Command);
    1837            1 : }
        

Generated by: LCOV version 2.0-1