- moved some more files.

This commit is contained in:
Christoph Oelckers 2019-07-14 21:09:49 +02:00
commit 7346288bf5
34 changed files with 18 additions and 26 deletions

View file

@ -39,7 +39,6 @@
#include "v_video.h"
#include "r_defs.h"
#include "r_utility.h"
#include "r_renderer.h"
#include "doomstat.h"
#include "gi.h"
#include "g_level.h"

View file

@ -4,7 +4,7 @@
#include "r_defs.h"
#include "v_video.h"
#include "vectors.h"
#include "r_renderer.h"
#include "swrenderer/r_renderer.h"
#include "r_data/matrix.h"
#include "gl/renderer/gl_renderbuffers.h"
#include "hwrenderer/scene/hw_portal.h"

32
src/rendering/i_video.h Normal file
View file

@ -0,0 +1,32 @@
#ifndef __I_VIDEO_H__
#define __I_VIDEO_H__
class DFrameBuffer;
class IVideo
{
public:
virtual ~IVideo() {}
virtual DFrameBuffer *CreateFrameBuffer() = 0;
bool SetResolution();
virtual void DumpAdapters();
};
void I_InitGraphics();
void I_ShutdownGraphics();
extern IVideo *Video;
// Pause a bit.
// [RH] Despite the name, it apparently never waited for the VBL, even in
// the original DOS version (if the Heretic/Hexen source is any indicator).
void I_WaitVBL(int count);
#endif // __I_VIDEO_H__

148
src/rendering/r_sky.cpp Normal file
View file

@ -0,0 +1,148 @@
//-----------------------------------------------------------------------------
//
// Copyright 1993-1996 id Software
// Copyright 1994-1996 Raven Software
// Copyright 1999-2016 Randy Heit
// Copyright 2002-2016 Christoph Oelckers
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//-----------------------------------------------------------------------------
//
// DESCRIPTION:
// Sky rendering. The DOOM sky is a texture map like any
// wall, wrapping around. 1024 columns equal 360 degrees.
// The default sky map is 256 columns and repeats 4 times
// on a 320 screen.
//
//
//-----------------------------------------------------------------------------
// Needed for FRACUNIT.
#include "m_fixed.h"
#include "c_cvars.h"
#include "g_level.h"
#include "r_sky.h"
#include "r_utility.h"
#include "v_text.h"
#include "g_levellocals.h"
//
// sky mapping
//
FTextureID skyflatnum;
// [RH] Stretch sky texture if not taller than 128 pixels?
// Also now controls capped skies. 0 = normal, 1 = stretched, 2 = capped
CUSTOM_CVAR (Int, r_skymode, 2, CVAR_ARCHIVE|CVAR_NOINITCALL)
{
R_InitSkyMap ();
}
CVAR(Float, skyoffset, 0, 0) // for testing
//==========================================================================
//
// R_InitSkyMap
//
// Called whenever the view size changes.
//
//==========================================================================
void InitSkyMap(FLevelLocals *Level)
{
int skyheight;
FTexture *skytex1, *skytex2;
// Do not allow the null texture which has no bitmap and will crash.
if (Level->skytexture1.isNull())
{
Level->skytexture1 = TexMan.CheckForTexture("-noflat-", ETextureType::Any);
}
if (Level->skytexture2.isNull())
{
Level->skytexture2 = TexMan.CheckForTexture("-noflat-", ETextureType::Any);
}
skytex1 = TexMan.GetTexture(Level->skytexture1, false);
skytex2 = TexMan.GetTexture(Level->skytexture2, false);
if (skytex1 == nullptr)
return;
if ((Level->flags & LEVEL_DOUBLESKY) && skytex1->GetDisplayHeight() != skytex2->GetDisplayHeight())
{
Printf(TEXTCOLOR_BOLD "Both sky textures must be the same height." TEXTCOLOR_NORMAL "\n");
Level->flags &= ~LEVEL_DOUBLESKY;
Level->skytexture1 = Level->skytexture2;
}
// There are various combinations for sky rendering depending on how tall the sky is:
// h < 128: Unstretched and tiled, centered on horizon
// 128 <= h < 200: Can possibly be stretched. When unstretched, the baseline is
// 28 rows below the horizon so that the top of the texture
// aligns with the top of the screen when looking straight ahead.
// When stretched, it is scaled to 228 pixels with the baseline
// in the same location as an unstretched 128-tall sky, so the top
// of the texture aligns with the top of the screen when looking
// fully up.
// h == 200: Unstretched, baseline is on horizon, and top is at the top of
// the screen when looking fully up.
// h > 200: Unstretched, but the baseline is shifted down so that the top
// of the texture is at the top of the screen when looking fully up.
skyheight = skytex1->GetDisplayHeight();
if (skyheight >= 128 && skyheight < 200)
{
Level->skystretch = (r_skymode == 1
&& skyheight >= 128
&& Level->IsFreelookAllowed()
&& !(Level->flags & LEVEL_FORCETILEDSKY)) ? 1 : 0;
}
else Level->skystretch = false;
}
void R_InitSkyMap()
{
for(auto Level : AllLevels())
{
InitSkyMap(Level);
}
}
//==========================================================================
//
// R_UpdateSky
//
// Performs sky scrolling
//
//==========================================================================
void R_UpdateSky (uint64_t mstime)
{
double ms = (double)mstime * FRACUNIT;
for(auto Level : AllLevels())
{
// Scroll the sky
Level->sky1pos = ms * Level->skyspeed1;
Level->sky2pos = ms * Level->skyspeed2;
// The hardware renderer uses a different value range and clamps it to a single rotation
Level->hw_sky1pos = (float)(fmod((double(mstime) * Level->skyspeed1), 1024.) * (90. / 256.));
Level->hw_sky2pos = (float)(fmod((double(mstime) * Level->skyspeed2), 1024.) * (90. / 256.));
}
}

52
src/rendering/r_sky.h Normal file
View file

@ -0,0 +1,52 @@
//-----------------------------------------------------------------------------
//
// Copyright 1993-1996 id Software
// Copyright 1999-2016 Randy Heit
// Copyright 2002-2016 Christoph Oelckers
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//-----------------------------------------------------------------------------
//
// DESCRIPTION:
// Sky rendering.
//
//-----------------------------------------------------------------------------
#ifndef __R_SKY_H__
#define __R_SKY_H__
#include "textures/textures.h"
struct FLevelLocals;
extern FTextureID skyflatnum;
extern int freelookviewheight;
#define SKYSTRETCH_HEIGHT 228
// Called whenever the sky changes.
void InitSkyMap(FLevelLocals *Level);
void R_InitSkyMap();
void R_UpdateSky (uint64_t mstime);
// 57 world units roughly represent one sky texel for the glTranslate call.
enum
{
skyoffsetfactor = 57
};
#endif //__R_SKY_H__

1073
src/rendering/r_utility.cpp Normal file

File diff suppressed because it is too large Load diff

139
src/rendering/r_utility.h Normal file
View file

@ -0,0 +1,139 @@
#ifndef __R_UTIL_H
#define __R_UTIL_H
#include "r_state.h"
#include "vectors.h"
class FSerializer;
struct FViewWindow;
//
// Stuff from r_main.h that's needed outside the rendering code.
// Number of diminishing brightness levels.
// There a 0-31, i.e. 32 LUT in the COLORMAP lump.
#define NUMCOLORMAPS 32
struct FLevelLocals;
struct FRenderViewpoint
{
FRenderViewpoint();
player_t *player; // For which player is this viewpoint being renderered? (can be null for camera textures)
DVector3 Pos; // Camera position
DVector3 ActorPos; // Camera actor's position
DRotator Angles; // Camera angles
FRotator HWAngles; // Actual rotation angles for the hardware renderer
DVector2 ViewVector; // HWR only: direction the camera is facing.
AActor *ViewActor; // either the same as camera or nullptr
FLevelLocals *ViewLevel; // The level this viewpoint is on.
DVector3 Path[2]; // View path for portal calculations
double Cos; // cos(Angles.Yaw)
double Sin; // sin(Angles.Yaw)
double TanCos; // FocalTangent * cos(Angles.Yaw)
double TanSin; // FocalTangent * sin(Angles.Yaw)
AActor *camera; // camera actor
sector_t *sector; // [RH] keep track of sector viewing from
DAngle FieldOfView; // current field of view
double TicFrac; // fraction of tic for interpolation
uint32_t FrameTime; // current frame's time in tics.
int extralight; // extralight to be added to this viewpoint
bool showviewer; // show the camera actor?
void SetViewAngle(const FViewWindow &viewwindow);
};
extern FRenderViewpoint r_viewpoint;
//-----------------------------------
struct FViewWindow
{
double FocalTangent = 0.0;
int centerx = 0;
int centerxwide = 0;
int centery = 0;
float WidescreenRatio = 0.0f;
};
extern FViewWindow r_viewwindow;
//-----------------------------------
extern int setblocks;
extern bool r_NoInterpolate;
extern int validcount;
extern int dl_validcount; // For use with FSection. validcount is in use by the renderer and any quick section exclusion needs another variable.
extern angle_t LocalViewAngle; // [RH] Added to consoleplayer's angle
extern int LocalViewPitch; // [RH] Used directly instead of consoleplayer's pitch
extern bool LocalKeyboardTurner; // [RH] The local player used the keyboard to turn, so interpolate
extern unsigned int R_OldBlend;
const double r_Yaspect = 200.0; // Why did I make this a variable? It's never set anywhere.
//==========================================================================
//
// R_PointOnSide
//
// Traverse BSP (sub) tree, check point against partition plane.
// Returns side 0 (front/on) or 1 (back).
//
// [RH] inlined, stripped down, and made more precise
//
//==========================================================================
inline int R_PointOnSide (fixed_t x, fixed_t y, const node_t *node)
{
return DMulScale32 (y-node->y, node->dx, node->x-x, node->dy) > 0;
}
inline int R_PointOnSide(double x, double y, const node_t *node)
{
return DMulScale32(FLOAT2FIXED(y) - node->y, node->dx, node->x - FLOAT2FIXED(x), node->dy) > 0;
}
inline int R_PointOnSide(const DVector2 &pos, const node_t *node)
{
return DMulScale32(FLOAT2FIXED(pos.Y) - node->y, node->dx, node->x - FLOAT2FIXED(pos.X), node->dy) > 0;
}
// Used for interpolation waypoints.
struct DVector3a
{
DVector3 pos;
DAngle angle;
};
void R_ResetViewInterpolation ();
void R_RebuildViewInterpolation(player_t *player);
bool R_GetViewInterpolationStatus();
void R_ClearInterpolationPath();
void R_AddInterpolationPoint(const DVector3a &vec);
void R_SetViewSize (int blocks);
void R_SetFOV (FRenderViewpoint &viewpoint, DAngle fov);
void R_SetupFrame (FRenderViewpoint &viewpoint, FViewWindow &viewwindow, AActor * camera);
void R_SetViewAngle (FRenderViewpoint &viewpoint, const FViewWindow &viewwindow);
// Called by startup code.
void R_Init (void);
void R_ExecuteSetViewSize (FRenderViewpoint &viewpoint, FViewWindow &viewwindow);
// Called by M_Responder.
void R_SetViewSize (int blocks);
void R_SetWindow (FRenderViewpoint &viewpoint, FViewWindow &viewwindow, int windowSize, int fullWidth, int fullHeight, int stHeight, bool renderingToCanvas = false);
double R_GetGlobVis(const FViewWindow &viewwindow, double vis);
double R_ClampVisibility(double vis);
extern void R_FreePastViewers ();
extern void R_ClearPastViewer (AActor *actor);
#endif

View file

@ -0,0 +1,200 @@
//
//---------------------------------------------------------------------------
//
// Copyright(C) 2017 Magnus Norddahl
// Copyright(C) 2018 Rachael Alexanderson
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//--------------------------------------------------------------------------
//
#include <math.h>
#include "c_dispatch.h"
#include "c_cvars.h"
#include "v_video.h"
#include "templates.h"
#define NUMSCALEMODES 6
extern bool setsizeneeded;
EXTERN_CVAR(Int, vid_aspect)
CUSTOM_CVAR(Int, vid_scale_customwidth, VID_MIN_WIDTH, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
if (self < VID_MIN_WIDTH)
self = VID_MIN_WIDTH;
setsizeneeded = true;
}
CUSTOM_CVAR(Int, vid_scale_customheight, VID_MIN_HEIGHT, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
if (self < VID_MIN_HEIGHT)
self = VID_MIN_HEIGHT;
setsizeneeded = true;
}
CVAR(Bool, vid_scale_customlinear, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CUSTOM_CVAR(Bool, vid_scale_customstretched, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
setsizeneeded = true;
}
namespace
{
struct v_ScaleTable
{
bool isValid;
bool isLinear;
uint32_t(*GetScaledWidth)(uint32_t Width);
uint32_t(*GetScaledHeight)(uint32_t Height);
bool isScaled43;
bool isCustom;
};
v_ScaleTable vScaleTable[NUMSCALEMODES] =
{
// isValid, isLinear, GetScaledWidth(), GetScaledHeight(), isScaled43, isCustom
{ true, false, [](uint32_t Width)->uint32_t { return Width; }, [](uint32_t Height)->uint32_t { return Height; }, false, false }, // 0 - Native
{ true, true, [](uint32_t Width)->uint32_t { return Width; }, [](uint32_t Height)->uint32_t { return Height; }, false, false }, // 1 - Native (Linear)
{ true, false, [](uint32_t Width)->uint32_t { return 640; }, [](uint32_t Height)->uint32_t { return 400; }, true, false }, // 2 - 640x400 (formerly 320x200)
{ true, true, [](uint32_t Width)->uint32_t { return 960; }, [](uint32_t Height)->uint32_t { return 600; }, true, false }, // 3 - 960x600 (formerly 640x400)
{ true, true, [](uint32_t Width)->uint32_t { return 1280; }, [](uint32_t Height)->uint32_t { return 800; }, true, false }, // 4 - 1280x800
{ true, true, [](uint32_t Width)->uint32_t { return vid_scale_customwidth; }, [](uint32_t Height)->uint32_t { return vid_scale_customheight; }, true, true }, // 5 - Custom
};
bool isOutOfBounds(int x)
{
return (x < 0 || x >= NUMSCALEMODES || vScaleTable[x].isValid == false);
}
}
void R_ShowCurrentScaling();
CUSTOM_CVAR(Float, vid_scalefactor, 1.0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
{
setsizeneeded = true;
if (self < 0.05 || self > 2.0)
self = 1.0;
if (self != 1.0)
R_ShowCurrentScaling();
}
CUSTOM_CVAR(Int, vid_scalemode, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
setsizeneeded = true;
if (isOutOfBounds(self))
self = 0;
}
CUSTOM_CVAR(Bool, vid_cropaspect, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
setsizeneeded = true;
}
bool ViewportLinearScale()
{
if (isOutOfBounds(vid_scalemode))
vid_scalemode = 0;
// hack - use custom scaling if in "custom" mode
if (vScaleTable[vid_scalemode].isCustom)
return vid_scale_customlinear;
// vid_scalefactor > 1 == forced linear scale
return (vid_scalefactor > 1.0) ? true : vScaleTable[vid_scalemode].isLinear;
}
int ViewportScaledWidth(int width, int height)
{
if (isOutOfBounds(vid_scalemode))
vid_scalemode = 0;
if (vid_cropaspect && height > 0)
width = ((float)width/height > ActiveRatio(width, height)) ? (int)(height * ActiveRatio(width, height)) : width;
return (int)MAX((int32_t)VID_MIN_WIDTH, (int32_t)(vid_scalefactor * vScaleTable[vid_scalemode].GetScaledWidth(width)));
}
int ViewportScaledHeight(int width, int height)
{
if (isOutOfBounds(vid_scalemode))
vid_scalemode = 0;
if (vid_cropaspect && height > 0)
height = ((float)width/height < ActiveRatio(width, height)) ? (int)(width / ActiveRatio(width, height)) : height;
return (int)MAX((int32_t)VID_MIN_HEIGHT, (int32_t)(vid_scalefactor * vScaleTable[vid_scalemode].GetScaledHeight(height)));
}
bool ViewportIsScaled43()
{
if (isOutOfBounds(vid_scalemode))
vid_scalemode = 0;
// hack - use custom scaling if in "custom" mode
if (vScaleTable[vid_scalemode].isCustom)
return vid_scale_customstretched;
return vScaleTable[vid_scalemode].isScaled43;
}
void R_ShowCurrentScaling()
{
int x1 = screen->GetClientWidth(), y1 = screen->GetClientHeight(), x2 = ViewportScaledWidth(x1, y1), y2 = ViewportScaledHeight(x1, y1);
Printf("Current vid_scalefactor: %f\n", (float)(vid_scalefactor));
Printf("Real resolution: %i x %i\nEmulated resolution: %i x %i\n", x1, y1, x2, y2);
}
CCMD (vid_showcurrentscaling)
{
R_ShowCurrentScaling();
}
CCMD (vid_scaletowidth)
{
if (argv.argc() > 1)
{
// the following enables the use of ViewportScaledWidth to get the proper dimensions in custom scale modes
vid_scalefactor = 1;
vid_scalefactor = (float)((double)atof(argv[1]) / ViewportScaledWidth(screen->GetClientWidth(), screen->GetClientHeight()));
}
}
CCMD (vid_scaletoheight)
{
if (argv.argc() > 1)
{
vid_scalefactor = 1;
vid_scalefactor = (float)((double)atof(argv[1]) / ViewportScaledHeight(screen->GetClientWidth(), screen->GetClientHeight()));
}
}
inline bool atob(char* I)
{
if (stricmp (I, "true") == 0 || stricmp (I, "1") == 0)
return true;
return false;
}
CCMD (vid_setscale)
{
if (argv.argc() > 2)
{
vid_scale_customwidth = atoi(argv[1]);
vid_scale_customheight = atoi(argv[2]);
if (argv.argc() > 3)
{
vid_scale_customlinear = atob(argv[3]);
if (argv.argc() > 4)
{
vid_scale_customstretched = atob(argv[4]);
}
}
vid_scalemode = 5;
vid_scalefactor = 1.0;
}
else
{
Printf("Usage: vid_setscale <x> <y> [bool linear] [bool long-pixel-shape]\nThis command will create a custom viewport scaling mode.\n");
}
}

View file

@ -0,0 +1,31 @@
//
//---------------------------------------------------------------------------
//
// Copyright(C) 2017 Magnus Norddahl
// Copyright(C) 2017 Rachael Alexanderson
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//--------------------------------------------------------------------------
//
#ifndef __VIDEOSCALE_H__
#define __VIDEOSCALE_H__
EXTERN_CVAR (Int, vid_scalemode)
bool ViewportLinearScale();
int ViewportScaledWidth(int width, int height);
int ViewportScaledHeight(int width, int height);
bool ViewportIsScaled43();
#endif //__VIDEOSCALE_H__

View file

@ -0,0 +1,45 @@
#ifndef __R_RENDERER_H
#define __R_RENDERER_H
#include <stdio.h>
struct FRenderer;
extern FRenderer *SWRenderer;
class FSerializer;
class FTexture;
class AActor;
class player_t;
struct sector_t;
class FCanvasTexture;
class FileWriter;
class DCanvas;
struct FLevelLocals;
struct FRenderer
{
virtual ~FRenderer() {}
// precache one texture
virtual void Precache(uint8_t *texhitlist, TMap<PClassActor*, bool> &actorhitlist) = 0;
// render 3D view
virtual void RenderView(player_t *player, DCanvas *target, void *videobuffer, int bufferpitch) = 0;
// renders view to a savegame picture
virtual void WriteSavePic(player_t *player, FileWriter *file, int width, int height) = 0;
// draws player sprites with hardware acceleration (only useful for software rendering)
virtual void DrawRemainingPlayerSprites() = 0;
// set up the colormap for a newly loaded level.
virtual void SetColormap(FLevelLocals *) = 0;
virtual void SetClearColor(int color) = 0;
virtual void Init() = 0;
};
#endif

View file

@ -54,7 +54,7 @@
#include "v_video.h"
#include "templates.h"
#include "r_utility.h"
#include "r_renderer.h"
#include "swrenderer/r_renderer.h"
#include "atterm.h"
#include <atomic>

View file

@ -1,7 +1,7 @@
#pragma once
#include "r_renderer.h"
#include "swrenderer/r_renderer.h"
#include "swrenderer/scene/r_scene.h"
struct FSoftwareRenderer : public FRenderer

View file

@ -27,7 +27,7 @@
#include "hwrenderer/textures/hw_ihwtexture.h"
#include "hwrenderer/textures/hw_material.h"
#include "r_renderer.h"
#include "swrenderer/r_renderer.h"
#include "r_swscene.h"
#include "w_wad.h"
#include "d_player.h"

View file

@ -0,0 +1,457 @@
/*
** The base framebuffer class
**
**---------------------------------------------------------------------------
** Copyright 1999-2016 Randy Heit
** Copyright 2005-2018 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <stdio.h>
#include "x86.h"
#include "actor.h"
#include "v_video.h"
#include "c_dispatch.h"
#include "sbar.h"
#include "hardware.h"
#include "r_utility.h"
#include "swrenderer/r_renderer.h"
#include "vm.h"
#include "r_videoscale.h"
#include "i_time.h"
#include "hwrenderer/scene/hw_portal.h"
#include "hwrenderer/utility/hw_clock.h"
#include "hwrenderer/data/flatvertices.h"
#include <chrono>
#include <thread>
CVAR(Bool, gl_scale_viewport, true, CVAR_ARCHIVE);
CVAR(Bool, vid_fps, false, 0)
CVAR(Int, vid_showpalette, 0, 0)
EXTERN_CVAR(Bool, ticker)
EXTERN_CVAR(Float, vid_brightness)
EXTERN_CVAR(Float, vid_contrast)
EXTERN_CVAR(Bool, vid_vsync)
EXTERN_CVAR(Int, vid_maxfps)
EXTERN_CVAR(Bool, cl_capfps)
EXTERN_CVAR(Int, screenblocks)
//==========================================================================
//
// DCanvas :: CalcGamma
//
//==========================================================================
void DFrameBuffer::CalcGamma (float gamma, uint8_t gammalookup[256])
{
// I found this formula on the web at
// <http://panda.mostang.com/sane/sane-gamma.html>,
// but that page no longer exits.
double invgamma = 1.f / gamma;
int i;
for (i = 0; i < 256; i++)
{
gammalookup[i] = (uint8_t)(255.0 * pow (i / 255.0, invgamma) + 0.5);
}
}
//==========================================================================
//
// DFrameBuffer Constructor
//
// A frame buffer canvas is the most common and represents the image that
// gets drawn to the screen.
//
//==========================================================================
DFrameBuffer::DFrameBuffer (int width, int height)
{
SetSize(width, height);
mPortalState = new FPortalSceneState;
}
DFrameBuffer::~DFrameBuffer()
{
delete mPortalState;
}
void DFrameBuffer::SetSize(int width, int height)
{
Width = ViewportScaledWidth(width, height);
Height = ViewportScaledHeight(width, height);
}
//==========================================================================
//
//
//
//==========================================================================
void V_DrawPaletteTester(int paletteno)
{
int blocksize = screen->GetHeight() / 50;
int t = paletteno;
int k = 0;
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < 16; ++j)
{
int palindex = (t > 1) ? translationtables[TRANSLATION_Standard][t - 2]->Remap[k] : k;
PalEntry pe = GPalette.BaseColors[palindex];
k++;
screen->Dim(pe, 1.f, j*blocksize, i*blocksize, blocksize, blocksize);
}
}
}
//==========================================================================
//
// DFrameBuffer :: DrawRateStuff
//
// Draws the fps counter, dot ticker, and palette debug.
//
//==========================================================================
void DFrameBuffer::DrawRateStuff ()
{
// Draws frame time and cumulative fps
if (vid_fps)
{
uint64_t ms = screen->FrameTime;
uint64_t howlong = ms - LastMS;
if ((signed)howlong >= 0)
{
char fpsbuff[40];
int chars;
int rate_x;
int textScale = active_con_scale();
chars = mysnprintf (fpsbuff, countof(fpsbuff), "%2llu ms (%3llu fps)", (unsigned long long)howlong, (unsigned long long)LastCount);
rate_x = Width / textScale - NewConsoleFont->StringWidth(&fpsbuff[0]);
Clear (rate_x * textScale, 0, Width, NewConsoleFont->GetHeight() * textScale, GPalette.BlackIndex, 0);
DrawText (NewConsoleFont, CR_WHITE, rate_x, 0, (char *)&fpsbuff[0],
DTA_VirtualWidth, screen->GetWidth() / textScale,
DTA_VirtualHeight, screen->GetHeight() / textScale,
DTA_KeepRatio, true, TAG_DONE);
uint32_t thisSec = (uint32_t)(ms/1000);
if (LastSec < thisSec)
{
LastCount = FrameCount / (thisSec - LastSec);
LastSec = thisSec;
FrameCount = 0;
}
FrameCount++;
}
LastMS = ms;
}
// draws little dots on the bottom of the screen
if (ticker)
{
int64_t t = I_GetTime();
int64_t tics = t - LastTic;
LastTic = t;
if (tics > 20) tics = 20;
int i;
for (i = 0; i < tics*2; i += 2) Clear(i, Height-1, i+1, Height, 255, 0);
for ( ; i < 20*2; i += 2) Clear(i, Height-1, i+1, Height, 0, 0);
}
// draws the palette for debugging
if (vid_showpalette)
{
V_DrawPaletteTester(vid_showpalette);
}
}
//==========================================================================
//
// Palette stuff.
//
//==========================================================================
void DFrameBuffer::Update()
{
CheckBench();
int initialWidth = GetClientWidth();
int initialHeight = GetClientHeight();
int clientWidth = ViewportScaledWidth(initialWidth, initialHeight);
int clientHeight = ViewportScaledHeight(initialWidth, initialHeight);
if (clientWidth < VID_MIN_WIDTH) clientWidth = VID_MIN_WIDTH;
if (clientHeight < VID_MIN_HEIGHT) clientHeight = VID_MIN_HEIGHT;
if (clientWidth > 0 && clientHeight > 0 && (GetWidth() != clientWidth || GetHeight() != clientHeight))
{
SetVirtualSize(clientWidth, clientHeight);
V_OutputResized(clientWidth, clientHeight);
mVertexData->OutputResized(clientWidth, clientHeight);
}
}
void DFrameBuffer::SetClearColor(int color)
{
PalEntry pe = GPalette.BaseColors[color];
mSceneClearColor[0] = pe.r / 255.f;
mSceneClearColor[1] = pe.g / 255.f;
mSceneClearColor[2] = pe.b / 255.f;
mSceneClearColor[3] = 1.f;
}
//==========================================================================
//
// DFrameBuffer :: SetVSync
//
// Turns vertical sync on and off, if supported.
//
//==========================================================================
void DFrameBuffer::SetVSync (bool vsync)
{
}
//==========================================================================
//
// DFrameBuffer :: WipeStartScreen
//
// Grabs a copy of the screen currently displayed to serve as the initial
// frame of a screen wipe. Also determines which screenwipe will be
// performed.
//
//==========================================================================
FTexture *DFrameBuffer::WipeStartScreen()
{
return nullptr;
}
//==========================================================================
//
// DFrameBuffer :: WipeEndScreen
//
// Grabs a copy of the most-recently drawn, but not yet displayed, screen
// to serve as the final frame of a screen wipe.
//
//==========================================================================
FTexture *DFrameBuffer::WipeEndScreen()
{
return nullptr;
}
//==========================================================================
//
// DFrameBuffer :: GetCaps
//
//==========================================================================
EXTERN_CVAR(Bool, r_drawvoxels)
uint32_t DFrameBuffer::GetCaps()
{
ActorRenderFeatureFlags FlagSet = 0;
if (V_IsPolyRenderer())
FlagSet |= RFF_POLYGONAL | RFF_TILTPITCH | RFF_SLOPE3DFLOORS;
else
{
FlagSet |= RFF_UNCLIPPEDTEX;
if (r_drawvoxels)
FlagSet |= RFF_VOXELS;
}
if (V_IsTrueColor())
FlagSet |= RFF_TRUECOLOR;
else
FlagSet |= RFF_COLORMAP;
return (uint32_t)FlagSet;
}
void DFrameBuffer::WriteSavePic(player_t *player, FileWriter *file, int width, int height)
{
SWRenderer->WriteSavePic(player, file, width, height);
}
//==========================================================================
//
// Calculates the viewport values needed for 2D and 3D operations
//
//==========================================================================
void DFrameBuffer::SetViewportRects(IntRect *bounds)
{
if (bounds)
{
mSceneViewport = *bounds;
mScreenViewport = *bounds;
mOutputLetterbox = *bounds;
return;
}
// Special handling so the view with a visible status bar displays properly
int height, width;
if (screenblocks >= 10)
{
height = GetHeight();
width = GetWidth();
}
else
{
height = (screenblocks*GetHeight() / 10) & ~7;
width = (screenblocks*GetWidth() / 10);
}
// Back buffer letterbox for the final output
int clientWidth = GetClientWidth();
int clientHeight = GetClientHeight();
if (clientWidth == 0 || clientHeight == 0)
{
// When window is minimized there may not be any client area.
// Pretend to the rest of the render code that we just have a very small window.
clientWidth = 160;
clientHeight = 120;
}
int screenWidth = GetWidth();
int screenHeight = GetHeight();
float scaleX, scaleY;
if (ViewportIsScaled43())
{
scaleX = MIN(clientWidth / (float)screenWidth, clientHeight / (screenHeight * 1.2f));
scaleY = scaleX * 1.2f;
}
else
{
scaleX = MIN(clientWidth / (float)screenWidth, clientHeight / (float)screenHeight);
scaleY = scaleX;
}
mOutputLetterbox.width = (int)round(screenWidth * scaleX);
mOutputLetterbox.height = (int)round(screenHeight * scaleY);
mOutputLetterbox.left = (clientWidth - mOutputLetterbox.width) / 2;
mOutputLetterbox.top = (clientHeight - mOutputLetterbox.height) / 2;
// The entire renderable area, including the 2D HUD
mScreenViewport.left = 0;
mScreenViewport.top = 0;
mScreenViewport.width = screenWidth;
mScreenViewport.height = screenHeight;
// Viewport for the 3D scene
mSceneViewport.left = viewwindowx;
mSceneViewport.top = screenHeight - (height + viewwindowy - ((height - viewheight) / 2));
mSceneViewport.width = viewwidth;
mSceneViewport.height = height;
// Scale viewports to fit letterbox
bool notScaled = ((mScreenViewport.width == ViewportScaledWidth(mScreenViewport.width, mScreenViewport.height)) &&
(mScreenViewport.width == ViewportScaledHeight(mScreenViewport.width, mScreenViewport.height)) &&
!ViewportIsScaled43());
if (gl_scale_viewport && !IsFullscreen() && notScaled)
{
mScreenViewport.width = mOutputLetterbox.width;
mScreenViewport.height = mOutputLetterbox.height;
mSceneViewport.left = (int)round(mSceneViewport.left * scaleX);
mSceneViewport.top = (int)round(mSceneViewport.top * scaleY);
mSceneViewport.width = (int)round(mSceneViewport.width * scaleX);
mSceneViewport.height = (int)round(mSceneViewport.height * scaleY);
}
}
//===========================================================================
//
// Calculates the OpenGL window coordinates for a zdoom screen position
//
//===========================================================================
int DFrameBuffer::ScreenToWindowX(int x)
{
return mScreenViewport.left + (int)round(x * mScreenViewport.width / (float)GetWidth());
}
int DFrameBuffer::ScreenToWindowY(int y)
{
return mScreenViewport.top + mScreenViewport.height - (int)round(y * mScreenViewport.height / (float)GetHeight());
}
void DFrameBuffer::ScaleCoordsFromWindow(int16_t &x, int16_t &y)
{
int letterboxX = mOutputLetterbox.left;
int letterboxY = mOutputLetterbox.top;
int letterboxWidth = mOutputLetterbox.width;
int letterboxHeight = mOutputLetterbox.height;
x = int16_t((x - letterboxX) * Width / letterboxWidth);
y = int16_t((y - letterboxY) * Height / letterboxHeight);
}
void DFrameBuffer::FPSLimit()
{
using namespace std::chrono;
using namespace std::this_thread;
if (vid_maxfps <= 0 || cl_capfps)
return;
uint64_t targetWakeTime = fpsLimitTime + 1'000'000 / vid_maxfps;
while (true)
{
fpsLimitTime = duration_cast<microseconds>(steady_clock::now().time_since_epoch()).count();
int64_t timeToWait = targetWakeTime - fpsLimitTime;
if (timeToWait > 1'000'000 || timeToWait <= 0)
{
break;
}
if (timeToWait <= 2'000)
{
// We are too close to the deadline. OS sleep is not precise enough to wake us before it elapses.
// Yield execution and check time again.
sleep_for(nanoseconds(0));
}
else
{
// Sleep, but try to wake before deadline.
sleep_for(microseconds(timeToWait - 2'000));
}
}
}

937
src/rendering/v_video.cpp Normal file
View file

@ -0,0 +1,937 @@
/*
** Video basics and init code.
**
**---------------------------------------------------------------------------
** Copyright 1999-2016 Randy Heit
** Copyright 2005-2016 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <stdio.h>
#include "i_system.h"
#include "c_cvars.h"
#include "x86.h"
#include "i_video.h"
#include "r_state.h"
#include "am_map.h"
#include "doomstat.h"
#include "c_console.h"
#include "hu_stuff.h"
#include "m_argv.h"
#include "v_video.h"
#include "v_text.h"
#include "sc_man.h"
#include "w_wad.h"
#include "c_dispatch.h"
#include "cmdlib.h"
#include "sbar.h"
#include "hardware.h"
#include "m_png.h"
#include "r_utility.h"
#include "swrenderer/r_renderer.h"
#include "menu/menu.h"
#include "vm.h"
#include "r_videoscale.h"
#include "i_time.h"
#include "version.h"
#include "g_levellocals.h"
#include "am_map.h"
#include "atterm.h"
EXTERN_CVAR(Int, menu_resolution_custom_width)
EXTERN_CVAR(Int, menu_resolution_custom_height)
CVAR(Int, win_x, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CVAR(Int, win_y, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CVAR(Int, win_w, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CVAR(Int, win_h, -1, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
CVAR(Bool, win_maximized, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
CUSTOM_CVAR(Int, vid_maxfps, 200, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
{
if (vid_maxfps < TICRATE && vid_maxfps != 0)
{
vid_maxfps = TICRATE;
}
else if (vid_maxfps > 1000)
{
vid_maxfps = 1000;
}
}
CUSTOM_CVAR(Int, vid_rendermode, 4, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
{
if (self < 0 || self > 4)
{
self = 4;
}
if (usergame)
{
// [SP] Update pitch limits to the netgame/gamesim.
players[consoleplayer].SendPitchLimits();
}
screen->SetTextureFilterMode();
// No further checks needed. All this changes now is which scene drawer the render backend calls.
}
CUSTOM_CVAR(Int, vid_enablevulkan, 0, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
{
// [SP] This may seem pointless - but I don't want to implement live switching just
// yet - I'm pretty sure it's going to require a lot of reinits and destructions to
// do it right without memory leaks
Printf("Changing the video backend requires a restart for " GAMENAME ".\n");
}
CVAR(Int, vid_renderer, 1, 0) // for some stupid mods which threw caution out of the window...
EXTERN_CVAR(Bool, r_blendmethod)
int active_con_scale();
FRenderer *SWRenderer;
#define DBGBREAK assert(0)
class DDummyFrameBuffer : public DFrameBuffer
{
typedef DFrameBuffer Super;
public:
DDummyFrameBuffer (int width, int height)
: DFrameBuffer (0, 0)
{
SetVirtualSize(width, height);
}
// These methods should never be called.
void Update() { DBGBREAK; }
bool IsFullscreen() { DBGBREAK; return 0; }
int GetClientWidth() { DBGBREAK; return 0; }
int GetClientHeight() { DBGBREAK; return 0; }
void InitializeState() override {}
float Gamma;
};
int DisplayWidth, DisplayHeight;
FFont *SmallFont, *SmallFont2, *BigFont, *BigUpper, *ConFont, *IntermissionFont, *NewConsoleFont, *NewSmallFont, *CurrentConsoleFont, *OriginalSmallFont, *AlternativeSmallFont, *OriginalBigFont;
uint32_t Col2RGB8[65][256];
uint32_t *Col2RGB8_LessPrecision[65];
uint32_t Col2RGB8_Inverse[65][256];
ColorTable32k RGB32k;
ColorTable256k RGB256k;
static uint32_t Col2RGB8_2[63][256];
// [RH] The framebuffer is no longer a mere byte array.
// There's also only one, not four.
DFrameBuffer *screen;
CVAR (Int, vid_defwidth, 640, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
CVAR (Int, vid_defheight, 480, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
CVAR (Bool, ticker, false, 0)
CUSTOM_CVAR (Bool, vid_vsync, false, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
{
if (screen != NULL)
{
screen->SetVSync (*self);
}
}
// [RH] Set true when vid_setmode command has been executed
bool setmodeneeded = false;
//==========================================================================
//
// DCanvas Constructor
//
//==========================================================================
DCanvas::DCanvas (int _width, int _height, bool _bgra)
{
// Init member vars
Width = _width;
Height = _height;
Bgra = _bgra;
Resize(_width, _height);
}
//==========================================================================
//
// DCanvas Destructor
//
//==========================================================================
DCanvas::~DCanvas ()
{
}
//==========================================================================
//
//
//
//==========================================================================
void DCanvas::Resize(int width, int height)
{
Width = width;
Height = height;
// Making the pitch a power of 2 is very bad for performance
// Try to maximize the number of cache lines that can be filled
// for each column drawing operation by making the pitch slightly
// longer than the width. The values used here are all based on
// empirical evidence.
if (width <= 640)
{
// For low resolutions, just keep the pitch the same as the width.
// Some speedup can be seen using the technique below, but the speedup
// is so marginal that I don't consider it worthwhile.
Pitch = width;
}
else
{
// If we couldn't figure out the CPU's L1 cache line size, assume
// it's 32 bytes wide.
if (CPU.DataL1LineSize == 0)
{
CPU.DataL1LineSize = 32;
}
// The Athlon and P3 have very different caches, apparently.
// I am going to generalize the Athlon's performance to all AMD
// processors and the P3's to all non-AMD processors. I don't know
// how smart that is, but I don't have a vast plethora of
// processors to test with.
if (CPU.bIsAMD)
{
Pitch = width + CPU.DataL1LineSize;
}
else
{
Pitch = width + MAX(0, CPU.DataL1LineSize - 8);
}
}
int bytes_per_pixel = Bgra ? 4 : 1;
Pixels.Resize(Pitch * height * bytes_per_pixel);
memset (Pixels.Data(), 0, Pixels.Size());
}
//==========================================================================
//
// V_GetColorFromString
//
// Passed a string of the form "#RGB", "#RRGGBB", "R G B", or "RR GG BB",
// returns a number representing that color. If palette is non-NULL, the
// index of the best match in the palette is returned, otherwise the
// RRGGBB value is returned directly.
//
//==========================================================================
int V_GetColorFromString (const uint32_t *palette, const char *cstr, FScriptPosition *sc)
{
int c[3], i, p;
char val[3];
val[2] = '\0';
// Check for HTML-style #RRGGBB or #RGB color string
if (cstr[0] == '#')
{
size_t len = strlen (cstr);
if (len == 7)
{
// Extract each eight-bit component into c[].
for (i = 0; i < 3; ++i)
{
val[0] = cstr[1 + i*2];
val[1] = cstr[2 + i*2];
c[i] = ParseHex (val, sc);
}
}
else if (len == 4)
{
// Extract each four-bit component into c[], expanding to eight bits.
for (i = 0; i < 3; ++i)
{
val[1] = val[0] = cstr[1 + i];
c[i] = ParseHex (val, sc);
}
}
else
{
// Bad HTML-style; pretend it's black.
c[2] = c[1] = c[0] = 0;
}
}
else
{
if (strlen(cstr) == 6)
{
char *p;
int color = strtol(cstr, &p, 16);
if (*p == 0)
{
// RRGGBB string
c[0] = (color & 0xff0000) >> 16;
c[1] = (color & 0xff00) >> 8;
c[2] = (color & 0xff);
}
else goto normal;
}
else
{
normal:
// Treat it as a space-delimited hexadecimal string
for (i = 0; i < 3; ++i)
{
// Skip leading whitespace
while (*cstr <= ' ' && *cstr != '\0')
{
cstr++;
}
// Extract a component and convert it to eight-bit
for (p = 0; *cstr > ' '; ++p, ++cstr)
{
if (p < 2)
{
val[p] = *cstr;
}
}
if (p == 0)
{
c[i] = 0;
}
else
{
if (p == 1)
{
val[1] = val[0];
}
c[i] = ParseHex (val, sc);
}
}
}
}
if (palette)
return ColorMatcher.Pick (c[0], c[1], c[2]);
else
return MAKERGB(c[0], c[1], c[2]);
}
//==========================================================================
//
// V_GetColorStringByName
//
// Searches for the given color name in x11r6rgb.txt and returns an
// HTML-ish "#RRGGBB" string for it if found or the empty string if not.
//
//==========================================================================
FString V_GetColorStringByName (const char *name, FScriptPosition *sc)
{
FMemLump rgbNames;
char *rgbEnd;
char *rgb, *endp;
int rgblump;
int c[3], step;
size_t namelen;
if (Wads.GetNumLumps()==0) return FString();
rgblump = Wads.CheckNumForName ("X11R6RGB");
if (rgblump == -1)
{
if (!sc) Printf ("X11R6RGB lump not found\n");
else sc->Message(MSG_WARNING, "X11R6RGB lump not found");
return FString();
}
rgbNames = Wads.ReadLump (rgblump);
rgb = (char *)rgbNames.GetMem();
rgbEnd = rgb + Wads.LumpLength (rgblump);
step = 0;
namelen = strlen (name);
while (rgb < rgbEnd)
{
// Skip white space
if (*rgb <= ' ')
{
do
{
rgb++;
} while (rgb < rgbEnd && *rgb <= ' ');
}
else if (step == 0 && *rgb == '!')
{ // skip comment lines
do
{
rgb++;
} while (rgb < rgbEnd && *rgb != '\n');
}
else if (step < 3)
{ // collect RGB values
c[step++] = strtoul (rgb, &endp, 10);
if (endp == rgb)
{
break;
}
rgb = endp;
}
else
{ // Check color name
endp = rgb;
// Find the end of the line
while (endp < rgbEnd && *endp != '\n')
endp++;
// Back up over any whitespace
while (endp > rgb && *endp <= ' ')
endp--;
if (endp == rgb)
{
break;
}
size_t checklen = ++endp - rgb;
if (checklen == namelen && strnicmp (rgb, name, checklen) == 0)
{
FString descr;
descr.Format ("#%02x%02x%02x", c[0], c[1], c[2]);
return descr;
}
rgb = endp;
step = 0;
}
}
if (rgb < rgbEnd)
{
if (!sc) Printf ("X11R6RGB lump is corrupt\n");
else sc->Message(MSG_WARNING, "X11R6RGB lump is corrupt");
}
return FString();
}
//==========================================================================
//
// V_GetColor
//
// Works like V_GetColorFromString(), but also understands X11 color names.
//
//==========================================================================
int V_GetColor (const uint32_t *palette, const char *str, FScriptPosition *sc)
{
FString string = V_GetColorStringByName (str, sc);
int res;
if (!string.IsEmpty())
{
res = V_GetColorFromString (palette, string, sc);
}
else
{
res = V_GetColorFromString (palette, str, sc);
}
return res;
}
int V_GetColor(const uint32_t *palette, FScanner &sc)
{
FScriptPosition scc = sc;
return V_GetColor(palette, sc.String, &scc);
}
//==========================================================================
//
// BuildTransTable
//
// Build the tables necessary for blending
//
//==========================================================================
static void BuildTransTable (const PalEntry *palette)
{
int r, g, b;
// create the RGB555 lookup table
for (r = 0; r < 32; r++)
for (g = 0; g < 32; g++)
for (b = 0; b < 32; b++)
RGB32k.RGB[r][g][b] = ColorMatcher.Pick ((r<<3)|(r>>2), (g<<3)|(g>>2), (b<<3)|(b>>2));
// create the RGB666 lookup table
for (r = 0; r < 64; r++)
for (g = 0; g < 64; g++)
for (b = 0; b < 64; b++)
RGB256k.RGB[r][g][b] = ColorMatcher.Pick ((r<<2)|(r>>4), (g<<2)|(g>>4), (b<<2)|(b>>4));
int x, y;
// create the swizzled palette
for (x = 0; x < 65; x++)
for (y = 0; y < 256; y++)
Col2RGB8[x][y] = (((palette[y].r*x)>>4)<<20) |
((palette[y].g*x)>>4) |
(((palette[y].b*x)>>4)<<10);
// create the swizzled palette with the lsb of red and blue forced to 0
// (for green, a 1 is okay since it never gets added into)
for (x = 1; x < 64; x++)
{
Col2RGB8_LessPrecision[x] = Col2RGB8_2[x-1];
for (y = 0; y < 256; y++)
{
Col2RGB8_2[x-1][y] = Col2RGB8[x][y] & 0x3feffbff;
}
}
Col2RGB8_LessPrecision[0] = Col2RGB8[0];
Col2RGB8_LessPrecision[64] = Col2RGB8[64];
// create the inverse swizzled palette
for (x = 0; x < 65; x++)
for (y = 0; y < 256; y++)
{
Col2RGB8_Inverse[x][y] = (((((255-palette[y].r)*x)>>4)<<20) |
(((255-palette[y].g)*x)>>4) |
((((255-palette[y].b)*x)>>4)<<10)) & 0x3feffbff;
}
}
CCMD(clean)
{
Printf ("CleanXfac: %d\nCleanYfac: %d\n", CleanXfac, CleanYfac);
}
void V_UpdateModeSize (int width, int height)
{
// This calculates the menu scale.
// The optimal scale will always be to fit a virtual 640 pixel wide display onto the screen.
// Exceptions are made for a few ranges where the available virtual width is > 480.
// This reference size is being used so that on 800x450 (small 16:9) a scale of 2 gets used.
CleanXfac = std::max(std::min(screen->GetWidth() / 400, screen->GetHeight() / 240), 1);
if (CleanXfac >= 4) CleanXfac--; // Otherwise we do not have enough space for the episode/skill menus in some languages.
CleanYfac = CleanXfac;
CleanWidth = screen->GetWidth() / CleanXfac;
CleanHeight = screen->GetHeight() / CleanYfac;
int w = screen->GetWidth();
int factor;
if (w < 640) factor = 1;
else if (w >= 1024 && w < 1280) factor = 2;
else if (w >= 1600 && w < 1920) factor = 3;
else factor = w / 640;
if (w < 1360) factor = 1;
else if (w < 1920) factor = 2;
else factor = int(factor * 0.7);
CleanYfac_1 = CleanXfac_1 = factor;// MAX(1, int(factor * 0.7));
CleanWidth_1 = width / CleanXfac_1;
CleanHeight_1 = height / CleanYfac_1;
DisplayWidth = width;
DisplayHeight = height;
R_OldBlend = ~0;
}
void V_OutputResized (int width, int height)
{
V_UpdateModeSize(width, height);
setsizeneeded = true;
if (StatusBar != NULL)
{
StatusBar->CallScreenSizeChanged();
}
C_NewModeAdjust();
// Reload crosshair if transitioned to a different size
ST_LoadCrosshair(true);
if (primaryLevel && primaryLevel->automap)
primaryLevel->automap->NewResolution();
}
void V_CalcCleanFacs (int designwidth, int designheight, int realwidth, int realheight, int *cleanx, int *cleany, int *_cx1, int *_cx2)
{
if (designheight < 240 && realheight >= 480) designheight = 240;
*cleanx = *cleany = std::min(realwidth / designwidth, realheight / designheight);
}
bool IVideo::SetResolution ()
{
DFrameBuffer *buff = CreateFrameBuffer();
if (buff == NULL) // this cannot really happen
{
return false;
}
screen = buff;
screen->InitializeState();
screen->SetGamma();
V_UpdateModeSize(screen->GetWidth(), screen->GetHeight());
return true;
}
//
// V_Init
//
void V_Init (bool restart)
{
const char *i;
int width, height, bits;
atterm (V_Shutdown);
// [RH] Initialize palette management
InitPalette ();
if (!restart)
{
width = height = bits = 0;
if ( (i = Args->CheckValue ("-width")) )
width = atoi (i);
if ( (i = Args->CheckValue ("-height")) )
height = atoi (i);
if (width == 0)
{
if (height == 0)
{
width = vid_defwidth;
height = vid_defheight;
}
else
{
width = (height * 8) / 6;
}
}
else if (height == 0)
{
height = (width * 6) / 8;
}
// Remember the passed arguments for the next time the game starts up windowed.
vid_defwidth = width;
vid_defheight = height;
screen = new DDummyFrameBuffer (width, height);
}
// Update screen palette when restarting
else
{
screen->UpdatePalette();
}
BuildTransTable (GPalette.BaseColors);
}
void V_Init2()
{
float gamma = static_cast<DDummyFrameBuffer *>(screen)->Gamma;
{
DFrameBuffer *s = screen;
screen = NULL;
delete s;
}
UCVarValue val;
val.Bool = !!Args->CheckParm("-devparm");
ticker.SetGenericRepDefault(val, CVAR_Bool);
I_InitGraphics();
Video->SetResolution(); // this only fails via exceptions.
Printf ("Resolution: %d x %d\n", SCREENWIDTH, SCREENHEIGHT);
// init these for the scaling menu
menu_resolution_custom_width = SCREENWIDTH;
menu_resolution_custom_height = SCREENHEIGHT;
screen->SetGamma ();
FBaseCVar::ResetColors ();
C_NewModeAdjust();
setsizeneeded = true;
}
void V_Shutdown()
{
if (screen)
{
DFrameBuffer *s = screen;
screen = NULL;
delete s;
}
V_ClearFonts();
}
CUSTOM_CVAR (Int, vid_aspect, 0, CVAR_GLOBALCONFIG|CVAR_ARCHIVE)
{
setsizeneeded = true;
if (StatusBar != NULL)
{
StatusBar->CallScreenSizeChanged();
}
}
// Helper for ActiveRatio and CheckRatio. Returns the forced ratio type, or -1 if none.
int ActiveFakeRatio(int width, int height)
{
int fakeratio = -1;
if ((vid_aspect >= 1) && (vid_aspect <= 6))
{
// [SP] User wants to force aspect ratio; let them.
fakeratio = int(vid_aspect);
if (fakeratio == 3)
{
fakeratio = 0;
}
else if (fakeratio == 5)
{
fakeratio = 3;
}
}
else if (vid_aspect == 0 && ViewportIsScaled43())
{
fakeratio = 0;
}
return fakeratio;
}
// Active screen ratio based on cvars and size
float ActiveRatio(int width, int height, float *trueratio)
{
static float forcedRatioTypes[] =
{
4 / 3.0f,
16 / 9.0f,
16 / 10.0f,
17 / 10.0f,
5 / 4.0f,
17 / 10.0f,
21 / 9.0f
};
float ratio = width / (float)height;
int fakeratio = ActiveFakeRatio(width, height);
if (trueratio)
*trueratio = ratio;
return (fakeratio != -1) ? forcedRatioTypes[fakeratio] : ratio;
}
DEFINE_ACTION_FUNCTION(_Screen, GetAspectRatio)
{
ACTION_RETURN_FLOAT(ActiveRatio(screen->GetWidth(), screen->GetHeight(), nullptr));
}
// Tries to guess the physical dimensions of the screen based on the
// screen's pixel dimensions. Can return:
// 0: 4:3
// 1: 16:9
// 2: 16:10
// 3: 17:10
// 4: 5:4
// 5: 17:10 (redundant, never returned)
// 6: 21:9
int CheckRatio (int width, int height, int *trueratio)
{
float aspect = width / (float)height;
static std::pair<float, int> ratioTypes[] =
{
{ 21 / 9.0f , 6 },
{ 16 / 9.0f , 1 },
{ 17 / 10.0f , 3 },
{ 16 / 10.0f , 2 },
{ 4 / 3.0f , 0 },
{ 5 / 4.0f , 4 },
{ 0.0f, 0 }
};
int ratio = ratioTypes[0].second;
float distance = fabs(ratioTypes[0].first - aspect);
for (int i = 1; ratioTypes[i].first != 0.0f; i++)
{
float d = fabs(ratioTypes[i].first - aspect);
if (d < distance)
{
ratio = ratioTypes[i].second;
distance = d;
}
}
int fakeratio = ActiveFakeRatio(width, height);
if (fakeratio == -1)
fakeratio = ratio;
if (trueratio)
*trueratio = ratio;
return fakeratio;
}
int AspectBaseWidth(float aspect)
{
return (int)round(240.0f * aspect * 3.0f);
}
int AspectBaseHeight(float aspect)
{
if (!AspectTallerThanWide(aspect))
return (int)round(200.0f * (320.0f / (AspectBaseWidth(aspect) / 3.0f)) * 3.0f);
else
return (int)round((200.0f * (4.0f / 3.0f)) / aspect * 3.0f);
}
double AspectPspriteOffset(float aspect)
{
if (!AspectTallerThanWide(aspect))
return 0.0;
else
return ((4.0 / 3.0) / aspect - 1.0) * 97.5;
}
int AspectMultiplier(float aspect)
{
if (!AspectTallerThanWide(aspect))
return (int)round(320.0f / (AspectBaseWidth(aspect) / 3.0f) * 48.0f);
else
return (int)round(200.0f / (AspectBaseHeight(aspect) / 3.0f) * 48.0f);
}
bool AspectTallerThanWide(float aspect)
{
return aspect < 1.333f;
}
void ScaleWithAspect (int &w, int &h, int Width, int Height)
{
int resRatio = CheckRatio (Width, Height);
int screenRatio;
CheckRatio (w, h, &screenRatio);
if (resRatio == screenRatio)
return;
double yratio;
switch(resRatio)
{
case 0: yratio = 4./3.; break;
case 1: yratio = 16./9.; break;
case 2: yratio = 16./10.; break;
case 3: yratio = 17./10.; break;
case 4: yratio = 5./4.; break;
case 6: yratio = 21./9.; break;
default: return;
}
double y = w/yratio;
if (y > h)
w = static_cast<int>(h * yratio);
else
h = static_cast<int>(y);
}
CCMD(vid_setsize)
{
if (argv.argc() < 3)
{
Printf("Usage: vid_setsize width height\n");
}
else
{
screen->SetWindowSize((int)strtol(argv[1], nullptr, 0), (int)strtol(argv[2], nullptr, 0));
V_OutputResized(screen->GetClientWidth(), screen->GetClientHeight());
}
}
void IVideo::DumpAdapters ()
{
Printf("Multi-monitor support unavailable.\n");
}
CUSTOM_CVAR(Bool, fullscreen, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
{
setmodeneeded = true;
}
CUSTOM_CVAR(Bool, vid_hdr, false, CVAR_ARCHIVE | CVAR_GLOBALCONFIG | CVAR_NOINITCALL)
{
Printf("This won't take effect until " GAMENAME " is restarted.\n");
}
CCMD(vid_listadapters)
{
if (Video != NULL)
Video->DumpAdapters();
}
bool vid_hdr_active = false;
DEFINE_GLOBAL(SmallFont)
DEFINE_GLOBAL(SmallFont2)
DEFINE_GLOBAL(BigFont)
DEFINE_GLOBAL(ConFont)
DEFINE_GLOBAL(NewConsoleFont)
DEFINE_GLOBAL(NewSmallFont)
DEFINE_GLOBAL(AlternativeSmallFont)
DEFINE_GLOBAL(OriginalSmallFont)
DEFINE_GLOBAL(OriginalBigFont)
DEFINE_GLOBAL(IntermissionFont)
DEFINE_GLOBAL(CleanXfac)
DEFINE_GLOBAL(CleanYfac)
DEFINE_GLOBAL(CleanWidth)
DEFINE_GLOBAL(CleanHeight)
DEFINE_GLOBAL(CleanXfac_1)
DEFINE_GLOBAL(CleanYfac_1)
DEFINE_GLOBAL(CleanWidth_1)
DEFINE_GLOBAL(CleanHeight_1)
DEFINE_GLOBAL(generic_ui)

678
src/rendering/v_video.h Normal file
View file

@ -0,0 +1,678 @@
/*
** v_video.h
**
**---------------------------------------------------------------------------
** Copyright 1998-2008 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#ifndef __V_VIDEO_H__
#define __V_VIDEO_H__
#include <functional>
#include "doomtype.h"
#include "vectors.h"
#include "doomdef.h"
#include "dobject.h"
#include "r_data/renderstyle.h"
#include "c_cvars.h"
#include "r_data/v_colortables.h"
#include "v_2ddrawer.h"
#include "hwrenderer/dynlights/hw_shadowmap.h"
static const int VID_MIN_WIDTH = 640;
static const int VID_MIN_HEIGHT = 400;
struct sector_t;
class FTexture;
struct FPortalSceneState;
class FSkyVertexBuffer;
class IIndexBuffer;
class IVertexBuffer;
class IDataBuffer;
class FFlatVertexBuffer;
class HWViewpointBuffer;
class FLightBuffer;
struct HWDrawInfo;
enum EHWCaps
{
// [BB] Added texture compression flags.
RFL_TEXTURE_COMPRESSION = 1,
RFL_TEXTURE_COMPRESSION_S3TC = 2,
RFL_SHADER_STORAGE_BUFFER = 4,
RFL_BUFFER_STORAGE = 8,
RFL_NO_CLIP_PLANES = 32,
RFL_INVALIDATE_BUFFER = 64,
RFL_DEBUG = 128,
};
struct IntRect
{
int left, top;
int width, height;
void Offset(int xofs, int yofs)
{
left += xofs;
top += yofs;
}
void AddToRect(int x, int y)
{
if (x < left)
left = x;
if (x > left + width)
width = x - left;
if (y < top)
top = y;
if (y > top + height)
height = y - top;
}
};
extern int CleanWidth, CleanHeight, CleanXfac, CleanYfac;
extern int CleanWidth_1, CleanHeight_1, CleanXfac_1, CleanYfac_1;
extern int DisplayWidth, DisplayHeight;
void V_UpdateModeSize (int width, int height);
void V_OutputResized (int width, int height);
void V_CalcCleanFacs (int designwidth, int designheight, int realwidth, int realheight, int *cleanx, int *cleany, int *cx1=NULL, int *cx2=NULL);
EXTERN_CVAR(Int, vid_rendermode)
EXTERN_CVAR(Bool, fullscreen)
EXTERN_CVAR(Int, win_x)
EXTERN_CVAR(Int, win_y)
EXTERN_CVAR(Int, win_w)
EXTERN_CVAR(Int, win_h)
EXTERN_CVAR(Bool, win_maximized)
inline bool V_IsHardwareRenderer()
{
return vid_rendermode == 4;
}
inline bool V_IsSoftwareRenderer()
{
return vid_rendermode < 2;
}
inline bool V_IsPolyRenderer()
{
return vid_rendermode == 2 || vid_rendermode == 3;
}
inline bool V_IsTrueColor()
{
return vid_rendermode == 1 || vid_rendermode == 3 || vid_rendermode == 4;
}
class FTexture;
struct FColormap;
class FileWriter;
enum FTextureFormat : uint32_t;
class FModelRenderer;
struct SamplerUniform;
// TagItem definitions for DrawTexture. As far as I know, tag lists
// originated on the Amiga.
//
// Think of TagItems as an array of the following structure:
//
// struct TagItem {
// uint32_t ti_Tag;
// uint32_t ti_Data;
// };
#define TAG_DONE (0) /* Used to indicate the end of the Tag list */
#define TAG_END (0) /* Ditto */
/* list pointed to in ti_Data */
#define TAG_USER ((uint32_t)(1u<<30))
enum
{
DTA_Base = TAG_USER + 5000,
DTA_DestWidth, // width of area to draw to
DTA_DestHeight, // height of area to draw to
DTA_Alpha, // alpha value for translucency
DTA_FillColor, // color to stencil onto the destination
DTA_TranslationIndex, // translation table to recolor the source
DTA_AlphaChannel, // bool: the source is an alpha channel; used with DTA_FillColor
DTA_Clean, // bool: scale texture size and position by CleanXfac and CleanYfac
DTA_320x200, // bool: scale texture size and position to fit on a virtual 320x200 screen
DTA_Bottom320x200, // bool: same as DTA_320x200 but centers virtual screen on bottom for 1280x1024 targets
DTA_CleanNoMove, // bool: like DTA_Clean but does not reposition output position
DTA_CleanNoMove_1, // bool: like DTA_CleanNoMove, but uses Clean[XY]fac_1 instead
DTA_FlipX, // bool: flip image horizontally //FIXME: Does not work with DTA_Window(Left|Right)
DTA_ShadowColor, // color of shadow
DTA_ShadowAlpha, // alpha of shadow
DTA_Shadow, // set shadow color and alphas to defaults
DTA_VirtualWidth, // pretend the canvas is this wide
DTA_VirtualHeight, // pretend the canvas is this tall
DTA_TopOffset, // override texture's top offset
DTA_LeftOffset, // override texture's left offset
DTA_CenterOffset, // bool: override texture's left and top offsets and set them for the texture's middle
DTA_CenterBottomOffset,// bool: override texture's left and top offsets and set them for the texture's bottom middle
DTA_WindowLeft, // don't draw anything left of this column (on source, not dest)
DTA_WindowRight, // don't draw anything at or to the right of this column (on source, not dest)
DTA_ClipTop, // don't draw anything above this row (on dest, not source)
DTA_ClipBottom, // don't draw anything at or below this row (on dest, not source)
DTA_ClipLeft, // don't draw anything to the left of this column (on dest, not source)
DTA_ClipRight, // don't draw anything at or to the right of this column (on dest, not source)
DTA_Masked, // true(default)=use masks from texture, false=ignore masks
DTA_HUDRules, // use fullscreen HUD rules to position and size textures
DTA_HUDRulesC, // only used internally for marking HUD_HorizCenter
DTA_KeepRatio, // doesn't adjust screen size for DTA_Virtual* if the aspect ratio is not 4:3
DTA_RenderStyle, // same as render style for actors
DTA_ColorOverlay, // uint32_t: ARGB to overlay on top of image; limited to black for software
DTA_BilinearFilter, // bool: apply bilinear filtering to the image
DTA_SpecialColormap,// pointer to FSpecialColormapParameters
DTA_Desaturate, // explicit desaturation factor (does not do anything in Legacy OpenGL)
DTA_Fullscreen, // Draw image fullscreen (same as DTA_VirtualWidth/Height with graphics size.)
// floating point duplicates of some of the above:
DTA_DestWidthF,
DTA_DestHeightF,
DTA_TopOffsetF,
DTA_LeftOffsetF,
DTA_VirtualWidthF,
DTA_VirtualHeightF,
DTA_WindowLeftF,
DTA_WindowRightF,
// For DrawText calls:
DTA_TextLen, // stop after this many characters, even if \0 not hit
DTA_CellX, // horizontal size of character cell
DTA_CellY, // vertical size of character cell
// New additions.
DTA_Color,
DTA_FlipY, // bool: flip image vertically
DTA_SrcX, // specify a source rectangle (this supersedes the poorly implemented DTA_WindowLeft/Right
DTA_SrcY,
DTA_SrcWidth,
DTA_SrcHeight,
DTA_LegacyRenderStyle, // takes an old-style STYLE_* constant instead of an FRenderStyle
DTA_Burn, // activates the burn shader for this element
DTA_Spacing, // Strings only: Additional spacing between characters
DTA_Monospace, // Fonts only: Use a fixed distance between characters.
};
enum EMonospacing : int
{
Off = 0,
CellLeft = 1,
CellCenter = 2,
CellRight = 3
};
enum
{
HUD_Normal,
HUD_HorizCenter
};
class FFont;
struct FRemapTable;
class player_t;
typedef uint32_t angle_t;
struct DrawParms
{
double x, y;
double texwidth;
double texheight;
double destwidth;
double destheight;
double virtWidth;
double virtHeight;
double windowleft;
double windowright;
int cleanmode;
int dclip;
int uclip;
int lclip;
int rclip;
double top;
double left;
float Alpha;
PalEntry fillcolor;
FRemapTable *remap;
PalEntry colorOverlay;
PalEntry color;
INTBOOL alphaChannel;
INTBOOL flipX;
INTBOOL flipY;
//float shadowAlpha;
int shadowColor;
INTBOOL keepratio;
INTBOOL masked;
INTBOOL bilinear;
FRenderStyle style;
struct FSpecialColormap *specialcolormap;
int desaturate;
int scalex, scaley;
int cellx, celly;
int monospace;
int spacing;
int maxstrlen;
bool fortext;
bool virtBottom;
double srcx, srcy;
double srcwidth, srcheight;
bool burn;
};
struct Va_List
{
va_list list;
};
struct VMVa_List
{
VMValue *args;
int curindex;
int numargs;
const uint8_t *reginfo;
};
//
// VIDEO
//
//
class DCanvas
{
public:
DCanvas (int width, int height, bool bgra);
~DCanvas ();
void Resize(int width, int height);
// Member variable access
inline uint8_t *GetPixels () const { return Pixels.Data(); }
inline int GetWidth () const { return Width; }
inline int GetHeight () const { return Height; }
inline int GetPitch () const { return Pitch; }
inline bool IsBgra() const { return Bgra; }
protected:
TArray<uint8_t> Pixels;
int Width;
int Height;
int Pitch;
bool Bgra;
};
class FUniquePalette;
class IHardwareTexture;
class FTexture;
class DFrameBuffer
{
protected:
void DrawTextureV(FTexture *img, double x, double y, uint32_t tag, va_list tags) = delete;
void DrawTextureParms(FTexture *img, DrawParms &parms);
template<class T>
bool ParseDrawTextureTags(FTexture *img, double x, double y, uint32_t tag, T& tags, DrawParms *parms, bool fortext) const;
template<class T>
void DrawTextCommon(FFont *font, int normalcolor, double x, double y, const T *string, DrawParms &parms);
F2DDrawer m2DDrawer;
private:
int Width = 0;
int Height = 0;
protected:
int clipleft = 0, cliptop = 0, clipwidth = -1, clipheight = -1;
public:
// Hardware render state that needs to be exposed to the API independent part of the renderer. For ease of access this is stored in the base class.
int hwcaps = 0; // Capability flags
float glslversion = 0; // This is here so that the differences between old OpenGL and new OpenGL/Vulkan can be handled by platform independent code.
int instack[2] = { 0,0 }; // this is globally maintained state for portal recursion avoidance.
int stencilValue = 0; // Global stencil test value
unsigned int uniformblockalignment = 256; // Hardware dependent uniform buffer alignment.
unsigned int maxuniformblock = 65536;
const char *vendorstring; // We have to account for some issues with particular vendors.
FPortalSceneState *mPortalState; // global portal state.
FSkyVertexBuffer *mSkyData = nullptr; // the sky vertex buffer
FFlatVertexBuffer *mVertexData = nullptr; // Global vertex data
HWViewpointBuffer *mViewpoints = nullptr; // Viewpoint render data.
FLightBuffer *mLights = nullptr; // Dynamic lights
IShadowMap mShadowMap;
IntRect mScreenViewport;
IntRect mSceneViewport;
IntRect mOutputLetterbox;
float mSceneClearColor[4];
public:
DFrameBuffer (int width=1, int height=1);
virtual ~DFrameBuffer();
virtual void InitializeState() = 0; // For stuff that needs 'screen' set.
virtual bool IsVulkan() { return false; }
void SetSize(int width, int height);
void SetVirtualSize(int width, int height)
{
Width = width;
Height = height;
}
inline int GetWidth() const { return Width; }
inline int GetHeight() const { return Height; }
FVector2 SceneScale() const
{
return { mSceneViewport.width / (float)mScreenViewport.width, mSceneViewport.height / (float)mScreenViewport.height };
}
FVector2 SceneOffset() const
{
return { mSceneViewport.left / (float)mScreenViewport.width, mSceneViewport.top / (float)mScreenViewport.height };
}
// Make the surface visible.
virtual void Update ();
// Stores the palette with flash blended in into 256 dwords
// Mark the palette as changed. It will be updated on the next Update().
virtual void UpdatePalette() {}
virtual void SetGamma() {}
// Returns true if running fullscreen.
virtual bool IsFullscreen () = 0;
virtual void ToggleFullscreen(bool yes) {}
// Changes the vsync setting, if supported by the device.
virtual void SetVSync (bool vsync);
// Delete any resources that need to be deleted after restarting with a different IWAD
virtual void CleanForRestart() {}
virtual void SetTextureFilterMode() {}
virtual IHardwareTexture *CreateHardwareTexture() { return nullptr; }
virtual void PrecacheMaterial(FMaterial *mat, int translation) {}
virtual FModelRenderer *CreateModelRenderer(int mli) { return nullptr; }
virtual void TextureFilterChanged() {}
virtual void BeginFrame() {}
virtual void SetWindowSize(int w, int h) {}
virtual void StartPrecaching() {}
virtual int GetClientWidth() = 0;
virtual int GetClientHeight() = 0;
virtual void BlurScene(float amount) {}
// Interface to hardware rendering resources
virtual IVertexBuffer *CreateVertexBuffer() { return nullptr; }
virtual IIndexBuffer *CreateIndexBuffer() { return nullptr; }
virtual IDataBuffer *CreateDataBuffer(int bindingpoint, bool ssbo, bool needsresize) { return nullptr; }
bool BuffersArePersistent() { return !!(hwcaps & RFL_BUFFER_STORAGE); }
// Begin/End 2D drawing operations.
void Begin2D() { isIn2D = true; }
void End2D() { isIn2D = false; }
void End2DAndUpdate()
{
DrawRateStuff();
End2D();
Update();
}
// Returns true if Begin2D has been called and 2D drawing is now active
bool HasBegun2D() { return isIn2D; }
// This is overridable in case Vulkan does it differently.
virtual bool RenderTextureIsFlipped() const
{
return true;
}
// Report a game restart
void SetClearColor(int color);
virtual uint32_t GetCaps();
virtual void WriteSavePic(player_t *player, FileWriter *file, int width, int height);
virtual sector_t *RenderView(player_t *player) { return nullptr; }
// Screen wiping
virtual FTexture *WipeStartScreen();
virtual FTexture *WipeEndScreen();
virtual void PostProcessScene(int fixedcm, const std::function<void()> &afterBloomDrawEndScene2D) { if (afterBloomDrawEndScene2D) afterBloomDrawEndScene2D(); }
void ScaleCoordsFromWindow(int16_t &x, int16_t &y);
uint64_t GetLastFPS() const { return LastCount; }
// 2D Texture drawing
void ClearClipRect() { clipleft = cliptop = 0; clipwidth = clipheight = -1; }
void SetClipRect(int x, int y, int w, int h);
void GetClipRect(int *x, int *y, int *w, int *h);
virtual void Draw2D() {}
void Clear2D() { m2DDrawer.Clear(); }
// Dim part of the canvas
void Dim(PalEntry color, float amount, int x1, int y1, int w, int h, FRenderStyle *style = nullptr);
void DoDim(PalEntry color, float amount, int x1, int y1, int w, int h, FRenderStyle *style = nullptr);
FVector4 CalcBlend(sector_t * viewsector, PalEntry *modulateColor);
void DrawBlend(sector_t * viewsector);
// Fill an area with a texture
void FlatFill(int left, int top, int right, int bottom, FTexture *src, bool local_origin = false);
// Fill a simple polygon with a texture
void FillSimplePoly(FTexture *tex, FVector2 *points, int npoints,
double originx, double originy, double scalex, double scaley, DAngle rotation,
const FColormap &colormap, PalEntry flatcolor, int lightlevel, int bottomclip, uint32_t *indices, size_t indexcount);
// Set an area to a specified color
void Clear(int left, int top, int right, int bottom, int palcolor, uint32_t color);
// Draws a line
void DrawLine(int x0, int y0, int x1, int y1, int palColor, uint32_t realcolor, uint8_t alpha = 255);
// Draws a line with thickness
void DrawThickLine(int x0, int y0, int x1, int y1, double thickness, uint32_t realcolor, uint8_t alpha = 255);
// Draws a single pixel
void DrawPixel(int x, int y, int palcolor, uint32_t rgbcolor);
bool SetTextureParms(DrawParms *parms, FTexture *img, double x, double y) const;
void DrawTexture(FTexture *img, double x, double y, int tags, ...);
void DrawTexture(FTexture *img, double x, double y, VMVa_List &);
void DrawShape(FTexture *img, DShape2D *shape, int tags, ...);
void DrawShape(FTexture *img, DShape2D *shape, VMVa_List &);
void FillBorder(FTexture *img); // Fills the border around a 4:3 part of the screen on non-4:3 displays
void VirtualToRealCoords(double &x, double &y, double &w, double &h, double vwidth, double vheight, bool vbottom = false, bool handleaspect = true) const;
// Code that uses these (i.e. SBARINFO) should probably be evaluated for using doubles all around instead.
void VirtualToRealCoordsInt(int &x, int &y, int &w, int &h, int vwidth, int vheight, bool vbottom = false, bool handleaspect = true) const;
// Text drawing functions -----------------------------------------------
#ifdef DrawText
#undef DrawText // See WinUser.h for the definition of DrawText as a macro
#endif
// 2D Text drawing
void DrawText(FFont *font, int normalcolor, double x, double y, const char *string, int tag_first, ...);
void DrawText(FFont *font, int normalcolor, double x, double y, const char *string, VMVa_List &args);
void DrawChar(FFont *font, int normalcolor, double x, double y, int character, int tag_first, ...);
void DrawChar(FFont *font, int normalcolor, double x, double y, int character, VMVa_List &args);
void DrawText(FFont *font, int normalcolor, double x, double y, const char32_t *string, int tag_first, ...);
void DrawFrame(int left, int top, int width, int height);
void DrawBorder(FTextureID, int x1, int y1, int x2, int y2);
// Calculate gamma table
void CalcGamma(float gamma, uint8_t gammalookup[256]);
virtual void SetViewportRects(IntRect *bounds);
int ScreenToWindowX(int x);
int ScreenToWindowY(int y);
void FPSLimit();
// Retrieves a buffer containing image data for a screenshot.
// Hint: Pitch can be negative for upside-down images, in which case buffer
// points to the last row in the buffer, which will be the first row output.
virtual TArray<uint8_t> GetScreenshotBuffer(int &pitch, ESSType &color_type, float &gamma) { return TArray<uint8_t>(); }
static float GetZNear() { return 5.f; }
static float GetZFar() { return 65536.f; }
// The original size of the framebuffer as selected in the video menu.
uint64_t FrameTime = 0;
protected:
void DrawRateStuff ();
private:
uint64_t fpsLimitTime = 0;
uint64_t LastMS = 0, LastSec = 0, FrameCount = 0, LastCount = 0, LastTic = 0;
bool isIn2D = false;
};
// This is the screen updated by I_FinishUpdate.
extern DFrameBuffer *screen;
#define SCREENWIDTH (screen->GetWidth ())
#define SCREENHEIGHT (screen->GetHeight ())
#define SCREENPITCH (screen->GetPitch ())
EXTERN_CVAR (Float, Gamma)
// Allocates buffer screens, call before R_Init.
void V_Init (bool restart);
// Initializes graphics mode for the first time.
void V_Init2 ();
void V_Shutdown ();
class FScanner;
struct FScriptPosition;
// Returns the closest color to the one desired. String
// should be of the form "rr gg bb".
int V_GetColorFromString (const uint32_t *palette, const char *colorstring, FScriptPosition *sc = nullptr);
// Scans through the X11R6RGB lump for a matching color
// and returns a color string suitable for V_GetColorFromString.
FString V_GetColorStringByName (const char *name, FScriptPosition *sc = nullptr);
// Tries to get color by name, then by string
int V_GetColor (const uint32_t *palette, const char *str, FScriptPosition *sc = nullptr);
int V_GetColor(const uint32_t *palette, FScanner &sc);
int CheckRatio (int width, int height, int *trueratio=NULL);
static inline int CheckRatio (double width, double height) { return CheckRatio(int(width), int(height)); }
inline bool IsRatioWidescreen(int ratio) { return (ratio & 3) != 0; }
float ActiveRatio (int width, int height, float *trueratio = NULL);
static inline double ActiveRatio (double width, double height) { return ActiveRatio(int(width), int(height)); }
int AspectBaseWidth(float aspect);
int AspectBaseHeight(float aspect);
double AspectPspriteOffset(float aspect);
int AspectMultiplier(float aspect);
bool AspectTallerThanWide(float aspect);
void ScaleWithAspect(int &w, int &h, int Width, int Height);
int GetUIScale(int altval);
int GetConScale(int altval);
EXTERN_CVAR(Int, uiscale);
EXTERN_CVAR(Int, con_scaletext);
EXTERN_CVAR(Int, con_scale);
inline int active_con_scaletext(bool newconfont = false)
{
return newconfont? GetConScale(con_scaletext) : GetUIScale(con_scaletext);
}
inline int active_con_scale()
{
return GetConScale(con_scale);
}
class ScaleOverrider
{
int savedxfac, savedyfac, savedwidth, savedheight;
public:
// This is to allow certain elements to use an optimal fullscreen scale which for the menu would be too large.
// The old code contained far too much mess to compensate for the menus which negatively affected everything else.
// However, for compatibility reasons the currently used variables cannot be changed so they have to be overridden temporarily.
// This class provides a safe interface for this because it ensures that the values get restored afterward.
// Currently, the intermission and the level summary screen use this.
ScaleOverrider()
{
savedxfac = CleanXfac;
savedyfac = CleanYfac;
savedwidth = CleanWidth;
savedheight = CleanHeight;
V_CalcCleanFacs(320, 200, screen->GetWidth(), screen->GetHeight(), &CleanXfac, &CleanYfac);
CleanWidth = screen->GetWidth() / CleanXfac;
CleanHeight = screen->GetHeight() / CleanYfac;
}
~ScaleOverrider()
{
CleanXfac = savedxfac;
CleanYfac = savedyfac;
CleanWidth = savedwidth;
CleanHeight = savedheight;
}
};
#endif // __V_VIDEO_H__