Adding new 3D engine by Ian Curtis. Old engine moved to Graphics/Legacy3D/.

This commit is contained in:
Bart Trzynadlowski 2016-03-21 04:10:14 +00:00
parent 9802bbbfd8
commit 34301e97e1
42 changed files with 8800 additions and 57 deletions

View file

@ -38,7 +38,7 @@ BITS = 64
# #
# Include console-based debugger in emulator ('yes' or 'no') # Include console-based debugger in emulator ('yes' or 'no')
# #
ENABLE_DEBUGGER = no ENABLE_DEBUGGER = yes
############################################################################### ###############################################################################
@ -47,6 +47,11 @@ ENABLE_DEBUGGER = no
# Edit these paths as necessary. # Edit these paths as necessary.
############################################################################### ###############################################################################
#
# Boost 1.55
#
BOOST_INCLUDEPATH = /mingw64/boost_1_55_0
# #
# SDL # SDL
# #
@ -90,11 +95,11 @@ OUTFILE = $(BIN_DIR)\Supermodel.exe
CC = gcc CC = gcc
CXX = g++ CXX = g++
LD = g++ LD = g++
COMPILER_FLAGS = -I$(SDL_INCLUDEPATH) -ISrc/ -ISrc/OSD/ -ISrc/OSD/SDL/ -ISrc/OSD/Windows/ -c -Wall -O3 -DSUPERMODEL_WIN32 -DGLEW_STATIC COMPILER_FLAGS = -I$(SDL_INCLUDEPATH) -ISrc/ -ISrc/OSD/ -ISrc/OSD/SDL/ -ISrc/OSD/Windows/ -c -Wall -DSUPERMODEL_WIN32 -DGLEW_STATIC -O3
CFLAGS = $(COMPILER_FLAGS) CFLAGS = $(COMPILER_FLAGS)
CPPFLAGS = $(COMPILER_FLAGS) CPPFLAGS = $(COMPILER_FLAGS) -I$(BOOST_INCLUDEPATH) -std=c++11
#LFLAGS = -s -o $(OUTFILE) $(OBJ) -L$(SDL_LIBPATH) -lmingw32 -lSDLmain -lSDL -lopengl32 -lglu32 -ldinput8 -ldxguid -lole32 -loleaut32 -lz -l:$(WINSDK_LIBPATH)/WbemUuid.lib #LFLAGS = -s -o $(OUTFILE) $(OBJ) -L$(SDL_LIBPATH) -lmingw32 -lSDLmain -lSDL -lopengl32 -lglu32 -ldinput8 -ldxguid -lole32 -loleaut32 -lz -l:$(WINSDK_LIBPATH)/WbemUuid.lib
LFLAGS = -s -o $(OUTFILE) $(OBJ) -L$(SDL_LIBPATH) -lmingw32 -lSDLmain -lSDL -lopengl32 -lglu32 -ldinput8 -ldxguid -lole32 -loleaut32 -lz -l:$(WINSDK_LIBPATH)/WbemUuid.lib LFLAGS = -o $(OUTFILE) $(OBJ) -L$(SDL_LIBPATH) -lmingw32 -lSDLmain -lSDL -lopengl32 -lglu32 -ldinput8 -ldxguid -lole32 -loleaut32 -lz -l:$(WINSDK_LIBPATH)/WbemUuid.lib -s
# #
# Build options... # Build options...
@ -115,7 +120,9 @@ endif
# #
OBJ = $(OBJ_DIR)/PPCDisasm.o $(OBJ_DIR)/Games.o $(OBJ_DIR)/Config.o $(OBJ_DIR)/INIFile.o $(OBJ_DIR)/BlockFile.o $(OBJ_DIR)/93C46.o \ OBJ = $(OBJ_DIR)/PPCDisasm.o $(OBJ_DIR)/Games.o $(OBJ_DIR)/Config.o $(OBJ_DIR)/INIFile.o $(OBJ_DIR)/BlockFile.o $(OBJ_DIR)/93C46.o \
$(OBJ_DIR)/ROMLoad.o $(OBJ_DIR)/unzip.o $(OBJ_DIR)/ioapi.o $(OBJ_DIR)/Error.o $(OBJ_DIR)/glew.o $(OBJ_DIR)/Shader.o \ $(OBJ_DIR)/ROMLoad.o $(OBJ_DIR)/unzip.o $(OBJ_DIR)/ioapi.o $(OBJ_DIR)/Error.o $(OBJ_DIR)/glew.o $(OBJ_DIR)/Shader.o \
$(OBJ_DIR)/Real3D.o $(OBJ_DIR)/Render3D.o $(OBJ_DIR)/Models.o $(OBJ_DIR)/TextureRefs.o $(OBJ_DIR)/Render2D.o $(OBJ_DIR)/TileGen.o \ $(OBJ_DIR)/Real3D.o $(OBJ_DIR)/Legacy3D.o $(OBJ_DIR)/Models.o $(OBJ_DIR)/TextureRefs.o \
$(OBJ_DIR)/New3D.o $(OBJ_DIR)/Mat4.o $(OBJ_DIR)/Model.o $(OBJ_DIR)/PolyHeader.o $(OBJ_DIR)/Texture.o $(OBJ_DIR)/TextureSheet.o $(OBJ_DIR)/VBO.o $(OBJ_DIR)/Vec.o $(OBJ_DIR)/R3DShader.o \
$(OBJ_DIR)/Render2D.o $(OBJ_DIR)/TileGen.o \
$(OBJ_DIR)/Model3.o $(OBJ_DIR)/ppc.o $(OBJ_DIR)/Main.o $(OBJ_DIR)/Audio.o $(OBJ_DIR)/Thread.o $(OBJ_DIR)/SoundBoard.o \ $(OBJ_DIR)/Model3.o $(OBJ_DIR)/ppc.o $(OBJ_DIR)/Main.o $(OBJ_DIR)/Audio.o $(OBJ_DIR)/Thread.o $(OBJ_DIR)/SoundBoard.o \
$(OBJ_DIR)/SCSP.o $(OBJ_DIR)/SCSPDSP.o $(OBJ_DIR)/68K.o $(OBJ_DIR)/m68kcpu.o $(OBJ_DIR)/m68kopnz.o $(OBJ_DIR)/m68kopdm.o \ $(OBJ_DIR)/SCSP.o $(OBJ_DIR)/SCSPDSP.o $(OBJ_DIR)/68K.o $(OBJ_DIR)/m68kcpu.o $(OBJ_DIR)/m68kopnz.o $(OBJ_DIR)/m68kopdm.o \
$(OBJ_DIR)/m68kopac.o $(OBJ_DIR)/m68kops.o $(OBJ_DIR)/DSB.o $(OBJ_DIR)/Z80.o \ $(OBJ_DIR)/m68kopac.o $(OBJ_DIR)/m68kops.o $(OBJ_DIR)/DSB.o $(OBJ_DIR)/Z80.o \
@ -143,6 +150,10 @@ endif
all: $(BIN_DIR) $(OBJ_DIR) $(OBJ) all: $(BIN_DIR) $(OBJ_DIR) $(OBJ)
$(LD) $(LFLAGS) $(LD) $(LFLAGS)
ppcd: $(BIN_DIR) $(OBJ_DIR)
$(CXX) Src/CPU/PowerPC/PPCDisasm.cpp $(CPPFLAGS) -DSTANDALONE -o $(OBJ_DIR)/ppcd.o
$(LD) -o $(BIN_DIR)/ppcd.exe -mconsole $(OBJ_DIR)/ppcd.o
$(BIN_DIR): $(BIN_DIR):
mkdir $(BIN_DIR) mkdir $(BIN_DIR)
@ -195,7 +206,13 @@ $(OBJ_DIR)/%.o: Src/%.cpp
$(OBJ_DIR)/%.o: Src/Model3/%.cpp $(OBJ_DIR)/%.o: Src/Model3/%.cpp
$(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o $(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o
$(OBJ_DIR)/%.o: Src/Graphics/%.cpp Src/Graphics/Shaders2D.h Src/Graphics/Shaders3D.h $(OBJ_DIR)/%.o: Src/Graphics/%.cpp Src/Graphics/Shaders2D.h
$(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o
$(OBJ_DIR)/%.o: Src/Graphics/Legacy3D/%.cpp Src/Graphics/Legacy3D/Shaders3D.h
$(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o
$(OBJ_DIR)/%.o: Src/Graphics/New3D/%.cpp Src/Graphics/New3D/%.h
$(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o $(CXX) $< $(CPPFLAGS) -o $(OBJ_DIR)/$(*F).o
$(OBJ_DIR)/%.o: Src/Sound/%.cpp $(OBJ_DIR)/%.o: Src/Sound/%.cpp

27
Src/Graphics/IRender3D.h Normal file
View file

@ -0,0 +1,27 @@
#ifndef INCLUDED_IRENDER3D_H
#define INCLUDED_IRENDER3D_H
#include <cstdint>
/*
* IRender3D:
*
* Interface (abstract base class) for Real3D rendering engine.
*/
class IRender3D
{
public:
virtual void RenderFrame(void) = 0;
virtual void BeginFrame(void) = 0;
virtual void EndFrame(void) = 0;
virtual void UploadTextures(unsigned x, unsigned y, unsigned width, unsigned height) = 0;
virtual void AttachMemory(const uint32_t *cullingRAMLoPtr, const uint32_t *cullingRAMHiPtr, const uint32_t *polyRAMPtr, const uint32_t *vromPtr, const uint16_t *textureRAMPtr) = 0;
virtual void SetStep(int stepID) = 0;
virtual bool Init(unsigned xOffset, unsigned yOffset, unsigned xRes, unsigned yRes, unsigned totalXRes, unsigned totalYRes) = 0;
virtual ~IRender3D()
{
}
};
#endif // INCLUDED_IRENDER3D_H

View file

@ -0,0 +1,67 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Error.cpp
*
* Error reporting for 3D renderer. There are some situations in which it is
* appropriate to inform the user of an error during rendering. However, these
* will frequently lead to an avalanche of error messages. Therefore, error
* messages are managed by this interface, ensuring that they are displayed not
* more than once per frame.
*
* Error functions can always be counted on to return FAIL, like ErrorLog().
*/
#include "Supermodel.h"
namespace Legacy3D {
// Error bit flags (must not conflict)
#define ERROR_LOCAL_VERTEX_OVERFLOW 0x1
#define ERROR_UNABLE_TO_CACHE_MODEL 0x2
// Overflow in the local vertex buffer, which holds one model
bool CLegacy3D::ErrorLocalVertexOverflow(void)
{
if ((errorMsgFlags&ERROR_LOCAL_VERTEX_OVERFLOW))
return FAIL;
errorMsgFlags |= ERROR_LOCAL_VERTEX_OVERFLOW;
return ErrorLog("Overflow in local vertex buffer!");
}
// Model could not be cached, even after dumping display list and re-caching
bool CLegacy3D::ErrorUnableToCacheModel(UINT32 modelAddr)
{
if ((errorMsgFlags&ERROR_UNABLE_TO_CACHE_MODEL))
return FAIL;
errorMsgFlags |= ERROR_UNABLE_TO_CACHE_MODEL;
return ErrorLog("Encountered a model that was too large to cache (at %08X)!", modelAddr);
}
// Call this every frame to clear the error flag, allowing errors to be printed
void CLegacy3D::ClearErrors(void)
{
errorMsgFlags = 0;
}
} // Legacy3D

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,485 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Legacy3D.h
*
* Header file defining the CLegacy3D class: Supermodel's original OpenGL
* Real3D graphics engine.
*/
#ifndef INCLUDED_LEGACY3D_H
#define INCLUDED_LEGACY3D_H
#include "Graphics/IRender3D.h"
#include "Pkgs/glew.h"
namespace Legacy3D {
/******************************************************************************
Internal Definitions and Data Structures
NOTE: These should probably be moved inside the Legacy3D namespace at some
point.
******************************************************************************/
// Model caches sort models by alpha (translucency) state
enum POLY_STATE
{
POLY_STATE_NORMAL = 0,
POLY_STATE_ALPHA
};
struct Vertex
{
GLfloat x,y,z; // vertex
GLfloat n[3]; // normal X, Y, Z
GLfloat u,v; // texture U, V coordinates (in texels, relative to selected texture)
};
struct Poly
{
Vertex Vert[4];
GLfloat n[3]; // polygon normal (used for backface culling)
POLY_STATE state; // alpha or normal?
unsigned numVerts; // triangle (3) or quad (4)
const UINT32 *header; // pointer to Real3D 7-word polygon header
};
/*
* VBORef:
*
* Reference to model polygons stored in a VBO. Each reference has two sets of
* vertices: normal and alpha. Copies of the model with different texture
* offsets applied are searchable via the linked list of texture offset states.
*/
struct VBORef
{
unsigned index[2]; // index of model polygons in VBO
unsigned numVerts[2]; // number of vertices
unsigned lutIdx; // LUT index associated with this model (for fast LUT clearing)
struct VBORef *nextTexOffset; // linked list of models with different texture offset states
UINT16 texOffset; // texture offset data for this model
CTextureRefs texRefs; // unique texture references contained in this model
/*
* Clear():
*
* Clears the VBORef by setting all fields to 0 and clearing the texture
* references.
*/
inline void Clear(void)
{
texRefs.Clear();
lutIdx = 0;
texOffset = 0;
nextTexOffset = NULL;
for (int i = 0; i < 2; i++)
{
index[i] = 0;
numVerts[i] = 0;
}
}
};
// Display list items: model instances and viewport settings
struct DisplayList
{
bool isViewport; // if true, this is a viewport node
union
{
// Viewport data
struct
{
GLfloat projectionMatrix[4*4]; // projection matrix
GLfloat lightingParams[6]; // lighting parameters (see RenderViewport() and vertex shader)
GLfloat spotEllipse[4]; // spotlight ellipse (see RenderViewport())
GLfloat spotRange[2]; // Z range
GLfloat spotColor[3]; // color
GLfloat fogParams[5]; // fog parameters (...)
GLint x, y; // viewport coordinates (scaled and in OpenGL format)
GLint width, height; // viewport dimensions (scaled for display surface size)
} Viewport;
// Model data
struct
{
GLfloat modelViewMatrix[4*4]; // model-view matrix
unsigned index; // index in VBO
unsigned numVerts; // number of vertices
GLint frontFace; // GL_CW (default), GL_CCW, or -GL_CW to indicate no culling
} Model;
} Data;
DisplayList *next; // next display list item with the same state (alpha or non-alpha)
};
/*
* ModelCache:
*
* A model cache tracks all models in a particular region (ie., VROM or polygon
* RAM). It contains a look-up table to quickly obtain VBO indices. Be careful
* when accessing the LUT, there are some special cases.
*
* If the model cache is marked dynamic, cached models may not necessarily be
* retained. Clearing the model cache is also much faster. The LUT entry for
* the last model cached will be valid, but because the LUT may not be
* cleared, one cannot assume a model exists because there is a LUT entry
* pointing to it. Always use NeedToCache() to determine whether caching is
* necessary before reading the LUT!
*/
struct ModelCache
{
// Cache type
bool dynamic;
// Vertex buffer object
unsigned vboMaxOffset; // size of VBO (in bytes)
unsigned vboCurOffset; // current offset in VBO (in bytes)
GLuint vboID; // OpenGL VBO handle
// Local vertex buffers (enough for a single model)
unsigned maxVertIdx; // size of each local vertex buffer (in vertices)
unsigned curVertIdx[2]; // current vertex index (in vertices)
GLfloat *verts[2];
// Array of cached models
unsigned maxModels; // maximum number of models
unsigned numModels; // current number stored
VBORef *Models;
/*
* Look-Up Table:
*
* Can be accessed directly with a LUT index to determine the model index.
* However, it should not be used to determine whether a model needs to be
* cached. Use NeedToCache() instead. A valid index, for example, may still
* have to be re-cached if the model cache is dynamic (polygon RAM).
*/
unsigned lutSize; // number of elements in LUT
INT16 *lut; // stores indices into Models[] or -1 if not yet cached
// Display list
unsigned maxListSize; // maximum number of display list items
unsigned listSize; // number of items in display list
DisplayList *List; // holds all display list items
DisplayList *ListHead[2]; // heads of linked lists for each state
DisplayList *ListTail[2]; // current tail node for each state
};
struct TexSheet
{
unsigned sheetNum;
unsigned mapNum;
unsigned xOffset;
unsigned yOffset;
/*
* Texture Format Buffer
*
* Records the format that a texture (at a given location within the
* texture sheet) is currently stored in. A negative value indicates the
* texture has not been accessed and converted yet and non-negative values
* correspond to the texture format bits in the polygon headers. They can
* be used to determine whether a texture needs to be updated.
*/
int texWidth[2048/32][2048/32];
int texHeight[2048/32][2048/32];
INT8 texFormat[2048/32][2048/32];
};
/******************************************************************************
CLegacy3D Classes
******************************************************************************/
/*
* CLegacy3DConfig:
*
* Settings used by CLegacy3D.
*/
class CLegacy3DConfig
{
public:
string vertexShaderFile; // path to vertex shader or "" to use internal shader
string fragmentShaderFile; // fragment shader
unsigned maxTexMaps; // maximum number of texture maps to use (1-9)
unsigned maxTexMapExtent; // maximum extent of texture maps (where num of tex sheets per map = extent ^ 2)
bool multiTexture; // if enabled and no external fragment shader, select internal shader w/ multiple texture sheet support
// Defaults
CLegacy3DConfig(void)
{
// strings will be clear to begin with
maxTexMaps = 9;
maxTexMapExtent = 4;
multiTexture = false;
}
};
/*
* CLegacy3D:
*
* 3D renderer. Lots of work to do here :)
*/
class CLegacy3D: public IRender3D
{
friend class CTextureRefs;
public:
/*
* RenderFrame(void):
*
* Renders the complete scene database. Must be called between BeginFrame() and
* EndFrame(). This function traverses the scene database and builds up display
* lists.
*/
void RenderFrame(void);
/*
* BeginFrame(void):
*
* Prepare to render a new frame. Must be called once per frame prior to
* drawing anything.
*/
void BeginFrame(void);
/*
* EndFrame(void):
*
* Signals the end of rendering for this frame. Must be called last during
* the frame.
*/
void EndFrame(void);
/*
* UploadTextures(x, y, width, height):
*
* Signals that a portion of texture RAM has been updated.
*
* Parameters:
* x X position within texture RAM.
* y Y position within texture RAM.
* width Width of texture data in texels.
* height Height.
*/
void UploadTextures(unsigned x, unsigned y, unsigned width, unsigned height);
/*
* AttachMemory(cullingRAMLoPtr, cullingRAMHiPtr, polyRAMPtr, vromPtr,
* textureRAMPtr):
*
* Attaches RAM and ROM areas. This must be done prior to any rendering
* otherwise the program may crash with an access violation.
*
* Parameters:
* cullingRAMLoPtr Pointer to low culling RAM (4 MB).
* cullingRAMHiPtr Pointer to high culling RAM (1 MB).
* polyRAMPtr Pointer to polygon RAM (4 MB).
* vromPtr Pointer to video ROM (64 MB).
* textureRAMPtr Pointer to texture RAM (8 MB).
*/
void AttachMemory(const UINT32 *cullingRAMLoPtr,
const UINT32 *cullingRAMHiPtr, const UINT32 *polyRAMPtr,
const UINT32 *vromPtr, const UINT16 *textureRAMPtr);
/*
* SetStep(stepID):
*
* Sets the Model 3 hardware stepping, which also determines the Real3D
* functionality. The default is Step 1.0. This should be called prior to
* any other emulation functions and after Init().
*
* Parameters:
* stepID 0x10 for Step 1.0, 0x15 for Step 1.5, 0x20 for Step 2.0,
* or 0x21 for Step 2.1. Anything else defaults to 1.0.
*/
void SetStep(int stepID);
/*
* Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes):
*
* One-time initialization of the context. Must be called before any other
* members (meaning it should be called even before being attached to any
* other objects that want to use it).
*
* External shader files are loaded according to configuration settings.
*
* Parameters:
* xOffset X offset of the viewable area within OpenGL display
* surface, in pixels.
* yOffset Y offset.
* xRes Horizontal resolution of the viewable area.
* yRes Vertical resolution.
* totalXRes Horizontal resolution of the complete display area.
* totalYRes Vertical resolution.
*
* Returns:
* OKAY is successful, otherwise FAILED if a non-recoverable error
* occurred. Any allocated memory will not be freed until the
* destructor is called. Prints own error messages.
*/
bool Init(unsigned xOffset, unsigned yOffset, unsigned xRes, unsigned yRes, unsigned totalXRes, unsigned totalYRes);
/*
* CLegacy3D(void):
* ~CLegacy3D(void):
*
* Constructor and destructor.
*/
CLegacy3D(void);
~CLegacy3D(void);
private:
/*
* Private Members
*/
// Real3D address translation
const UINT32 *TranslateCullingAddress(UINT32 addr);
const UINT32 *TranslateModelAddress(UINT32 addr);
// Model caching and display list management
void DrawDisplayList(ModelCache *Cache, POLY_STATE state);
bool AppendDisplayList(ModelCache *Cache, bool isViewport, const struct VBORef *Model);
void ClearDisplayList(ModelCache *Cache);
bool InsertPolygon(ModelCache *cache, const Poly *p);
void InsertVertex(ModelCache *cache, const Vertex *v, const Poly *p, float normFlip);
struct VBORef *BeginModel(ModelCache *cache);
void EndModel(ModelCache *cache, struct VBORef *Model, int lutIdx, UINT16 texOffset);
struct VBORef *CacheModel(ModelCache *cache, int lutIdx, UINT16 texOffset, const UINT32 *data);
struct VBORef *LookUpModel(ModelCache *cache, int lutIdx, UINT16 texOffset);
void ClearModelCache(ModelCache *cache);
bool CreateModelCache(ModelCache *cache, unsigned vboMaxVerts, unsigned localMaxVerts, unsigned maxNumModels, unsigned numLUTEntries, unsigned displayListSize, bool isDynamic);
void DestroyModelCache(ModelCache *cache);
// Texture management
void DecodeTexture(int format, int x, int y, int width, int height);
// Matrix stack
void MultMatrix(UINT32 matrixOffset);
void InitMatrixStack(UINT32 matrixBaseAddr);
// Scene database traversal
bool DrawModel(UINT32 modelAddr);
void DescendCullingNode(UINT32 addr);
void DescendPointerList(UINT32 addr);
void DescendNodePtr(UINT32 nodeAddr);
void RenderViewport(UINT32 addr, int pri);
// In-frame error reporting
bool ErrorLocalVertexOverflow(void);
bool ErrorUnableToCacheModel(UINT32 modelAddr);
void ClearErrors(void);
/*
* Data
*/
// Stepping
int step;
int offset; // offset to subtract for words 3 and higher of culling nodes
GLfloat vertexFactor; // fixed-point conversion factor for vertices
// Memory (passed from outside)
const UINT32 *cullingRAMLo; // 4 MB
const UINT32 *cullingRAMHi; // 1 MB
const UINT32 *polyRAM; // 4 MB
const UINT32 *vrom; // 64 MB
const UINT16 *textureRAM; // 8 MB
// Error reporting
unsigned errorMsgFlags; // tracks which errors have been printed this frame
// Real3D Base Matrix Pointer
const float *matrixBasePtr;
// Current viewport parameters (updated as viewports are traversed)
GLfloat lightingParams[6];
GLfloat fogParams[5];
GLfloat spotEllipse[4];
GLfloat spotRange[2];
GLfloat spotColor[3];
GLint viewportX, viewportY;
GLint viewportWidth, viewportHeight;
// Scene graph stack
int listDepth; // how many lists have we recursed into
int stackDepth; // for debugging and error handling purposes
// Texture offset (during scene graph processing)
GLfloat texOffsetXY[2]; // decoded X, Y offsets
UINT16 texOffset; // raw texture offset data as it appears in culling node
// Resolution and scaling factors (to support resolutions higher than 496x384) and offsets
GLfloat xRatio, yRatio;
unsigned xOffs, yOffs;
unsigned totalXRes, totalYRes;
// Texture details
static int defaultFmtToTexSheetNum[8]; // default mapping from Model3 texture format to texture sheet
unsigned numTexMaps; // total number of texture maps
GLuint texMapIDs[9]; // GL texture IDs of texture maps
unsigned numTexSheets; // total number of texture sheets
TexSheet *texSheets; // texture sheet objects
TexSheet *fmtToTexSheet[8]; // final mapping from Model3 texture format to texture sheet
// Shader programs and input data locations
GLuint shaderProgram; // shader program object
GLuint vertexShader; // vertex shader handle
GLuint fragmentShader; // fragment shader
GLint textureMapLoc; // location of "textureMap" uniform (if available)
GLint textureMapLocs[8]; // location of "textureMap[0-7]" uniforms (if available)
GLint modelViewMatrixLoc; // uniform
GLint projectionMatrixLoc; // uniform
GLint lightingLoc; // uniform
GLint mapSizeLoc; // uniform
GLint spotEllipseLoc; // uniform
GLint spotRangeLoc; // uniform
GLint spotColorLoc; // uniform
GLint subTextureLoc; // attribute
GLint texParamsLoc; // attribute
GLint texFormatLoc; // attribute
GLint texMapLoc; // attribute
GLint transLevelLoc; // attribute
GLint lightEnableLoc; // attribute
GLint shininessLoc; // attribute
GLint fogIntensityLoc; // attribute
// Model caching
ModelCache VROMCache; // VROM (static) models
ModelCache PolyCache; // polygon RAM (dynamic) models
/*
* Texture Decode Buffer
*
* Textures are decoded and copied from texture RAM into this temporary buffer
* before being uploaded. Dimensions are 512x512.
*/
GLfloat *textureBuffer; // RGBA8 format
};
} // Legacy3D
#endif // INCLUDED_LEGACY3D_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,2 @@
Shader source files go here. Completed versions of the shader files should be
copied into Src/Graphics/Shaders3D.h and Src/Graphics/Shaders2D.h.

View file

@ -0,0 +1,194 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Fragment.glsl
*
* Fragment shader for 3D rendering.
*/
#version 120
// Global uniforms
uniform sampler2D textureMap; // complete texture map, 2048x2048 texels
uniform vec4 spotEllipse; // spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)
uniform vec2 spotRange; // spotlight Z range: .x=start (viewspace coordinates), .y=limit
uniform vec3 spotColor; // spotlight RGB color
uniform vec3 lighting[2]; // lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)
uniform float mapSize; // texture map size (2048,4096,6144 etc)
// Inputs from vertex shader
varying vec4 fsSubTexture; // .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)
varying vec4 fsTexParams; // .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode
varying float fsTexFormat; // T1RGB5 contour texture (if > 0)
varying float fsTexMap; // texture map number
varying float fsTransLevel; // translucence level, 0.0 (transparent) to 1.0 (opaque)
varying vec3 fsLightIntensity; // lighting intensity
varying float fsSpecularTerm; // specular highlight
varying float fsFogFactor; // fog factor
varying float fsViewZ; // Z distance to fragment from viewpoint at origin
/*
* WrapTexelCoords():
*
* Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture
* sheet, taking into account wrapping behavior.
*
* Computing normalized OpenGL texture coordinates (0 to 1) within the
* Real3D texture sheet:
*
* If the texture is not mirrored, we simply have to clamp the
* coordinates to fit within the texture dimensions, add the texture
* X, Y position to select the appropriate one, and normalize by 2048
* (the dimensions of the Real3D texture sheet).
*
* = [(u,v)%(w,h)+(x,y)]/(2048,2048)
*
* If mirroring is enabled, textures are mirrored every odd multiple of
* the original texture. To detect whether we are in an odd multiple,
* simply divide the coordinate by the texture dimension and check
* whether the result is odd. Then, clamp the coordinates as before but
* subtract from the last texel to mirror them:
*
* = [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)
* where M is 1.0 if the texture must be mirrored.
*
* As an optimization, this function computes TWO texture coordinates
* simultaneously. The first is texCoord.xy, the second is in .zw. The other
* parameters must have .xy = .zw.
*/
vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)
{
vec4 clampedCoord, mirror, glTexCoord;
clampedCoord = mod(texCoord,texSize); // clamp coordinates to within texture size
mirror = mirrorEnable * mod(floor(texCoord/texSize),2.0); // whether this texel needs to be mirrored
glTexCoord = ( mirror*(texSize-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
return glTexCoord;
}
/*
* main():
*
* Fragment shader entry point.
*/
void main(void)
{
vec4 uv_top, uv_bot, c[4];
vec2 r;
vec4 fragColor;
vec2 ellipse;
vec3 lightIntensity;
float insideSpot;
int x;
// Get polygon color for untextured polygons (textured polygons will overwrite)
if (fsTexParams.x < 0.5)
fragColor = gl_Color;
else
// Textured polygons: set fragment color to texel value
{
/*
* Bilinear Filtering
*
* In order to get this working on ATI, the number of operations is
* reduced by putting everything into vec4s. uv_top holds the UV
* coordinates for the top two texels (.xy=left, .zw=right) and uv_bot
* is for the lower two.
*/
// Compute fractional blending factor, r, and lower left corner of texel 0
uv_bot.xy = gl_TexCoord[0].st-vec2(0.5,0.5); // move into the lower left blending texel
r = uv_bot.xy-floor(uv_bot.xy); // fractional part
uv_bot.xy = floor(uv_bot.xy); // integral part
// Compute texel coordinates
uv_bot.xy += vec2(0.5,0.5); // offset to center of pixel (should not be needed but it fixes a lot of glitches, esp. on Nvidia)
uv_bot.zw = uv_bot.xy + vec2(1.0,0.0); // compute coordinates of the other three neighbors
uv_top = uv_bot + vec4(0.0,1.0,0.0,1.0);
// Compute the properly wrapped texel coordinates
uv_top = WrapTexelCoords(uv_top,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
uv_bot = WrapTexelCoords(uv_bot,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
// Fetch the texels
c[0]=texture2D(textureMap,uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap,uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap,uv_top.xy); // top-left
c[3]=texture2D(textureMap,uv_top.zw); // top-right
// Interpolate texels and blend result with material color to determine final (unlit) fragment color
// fragColor = (c[0]*(1.0-r.s)*(1.0-r.t) + c[1]*r.s*(1.0-r.t) + c[2]*(1.0-r.s)*r.t + c[3]*r.s*r.t);
// Faster method:
c[0] += (c[1]-c[0])*r.s; // 2 alu
c[2] += (c[3]-c[2])*r.s; // 2 alu
fragColor = c[0]+(c[2]-c[0])*r.t; //2 alu
/*
* T1RGB5:
*
* The transparency bit determines whether to discard pixels (if set).
* What is unknown is how this bit behaves when interpolated. OpenGL
* processes it as an alpha value, so it might concievably be blended
* with neighbors. Here, an arbitrary threshold is chosen.
*
* To-do: blending could probably enabled and this would work even
* better with a hard threshold.
*
* Countour processing also seems to be enabled for RGBA4 textures.
* When the alpha value is 0.0 (or close), pixels are discarded
* entirely.
*/
if (fsTexParams.y > 0.5) // contour processing enabled
{
if (fragColor.a < 0.01) // discard anything with alpha == 0
discard;
}
// If contour texture and not discarded, force alpha to 1.0 because will later be modified by polygon translucency
if (fsTexFormat < 0.5) // contour (T1RGB5) texture
fragColor.a = 1.0;
}
// Compute spotlight and apply lighting
ellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;
insideSpot = dot(ellipse,ellipse);
if ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))
lightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;
else
lightIntensity = fsLightIntensity;
fragColor.rgb *= lightIntensity;
fragColor.rgb += vec3(fsSpecularTerm,fsSpecularTerm,fsSpecularTerm);
// Translucency (modulates existing alpha channel for RGBA4 texels)
fragColor.a *= fsTransLevel;
// Apply fog under the control of fog factor setting from polygon header
fragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor);
// Store final color
gl_FragColor = fragColor;
}

View file

@ -0,0 +1,42 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Fragment2D.glsl
*
* Fragment shader for 2D tilemap rendering.
*/
#version 120
// Global uniforms
uniform sampler2D textureMap; // 512x512 layer surface
/*
* main():
*
* Fragment shader entry point.
*/
void main(void)
{
gl_FragColor = texture2D(textureMap, gl_TexCoord[0].st);
}

View file

@ -0,0 +1,142 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Fragment_NoSpotlight.glsl
*
* Fragment shader for 3D rendering. Spotlight effect removed. Fixes fragment
* shader link errors on older ATI Radeon GPUs.
*
* To load external fragment shaders, use the -frag-shader=<file> option when
* starting Supermodel.
*/
#version 120
// Global uniforms
uniform sampler2D textureMap; // complete texture map, 2048x2048 texels
uniform vec4 spotEllipse; // spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)
uniform vec2 spotRange; // spotlight Z range: .x=start (viewspace coordinates), .y=limit
uniform vec3 spotColor; // spotlight RGB color
uniform float mapSize; // texture map size (2048,4096,6144 etc)
// Inputs from vertex shader
varying vec4 fsSubTexture; // .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)
varying vec4 fsTexParams; // .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode
varying float fsTexFormat; // .x=T1RGB5 contour texture (if > 0)
varying float fsTransLevel; // translucence level, 0.0 (transparent) to 1.0 (opaque)
varying vec3 fsLightIntensity; // lighting intensity
varying float fsFogFactor; // fog factor
varying float fsViewZ; // Z distance to fragment from viewpoint at origin
/*
* WrapTexelCoords():
*
* Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture
* sheet, taking into account wrapping behavior.
*
* Computing normalized OpenGL texture coordinates (0 to 1) within the
* Real3D texture sheet:
*
* If the texture is not mirrored, we simply have to clamp the
* coordinates to fit within the texture dimensions, add the texture
* X, Y position to select the appropriate one, and normalize by 2048
* (the dimensions of the Real3D texture sheet).
*
* = [(u,v)%(w,h)+(x,y)]/(2048,2048)
*
* If mirroring is enabled, textures are mirrored every odd multiple of
* the original texture. To detect whether we are in an odd multiple,
* simply divide the coordinate by the texture dimension and check
* whether the result is odd. Then, clamp the coordinates as before but
* subtract from the last texel to mirror them:
*
* = [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)
* where M is 1.0 if the texture must be mirrored.
*
* As an optimization, this function computes TWO texture coordinates
* simultaneously. The first is texCoord.xy, the second is in .zw. The other
* parameters must have .xy = .zw.
*/
vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)
{
vec4 clampedCoord, mirror, glTexCoord;
clampedCoord = mod(texCoord,texSize); // clamp coordinates to within texture size
mirror = mirrorEnable * mod(floor(texCoord/texSize),2.0); // whether this texel needs to be mirrored
glTexCoord = ( mirror*(texSize-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
/*
glTexCoord = ( mirror*(texSize-vec4(1.0,1.0,1.0,1.0)-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
*/
return glTexCoord;
}
/*
* main():
*
* Fragment shader entry point.
*/
void main(void)
{
vec4 uv_top, uv_bot, c[4];
vec2 r;
vec4 fragColor;
vec2 ellipse;
vec3 lightIntensity;
float insideSpot;
// Get polygon color for untextured polygons (textured polygons will overwrite)
if (fsTexParams.x < 0.5)
fragColor = gl_Color;
else
// Textured polygons: set fragment color to texel value
{
fragColor = texture2D(textureMap,(fsSubTexture.xy+fsSubTexture.zw/2.0)/mapSize);
//fragColor += texture2D(textureMap,(fsSubTexture.xy+fsSubTexture.zw)/mapSize);
}
// Compute spotlight and apply lighting
ellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;
insideSpot = dot(ellipse,ellipse);
if ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))
lightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;
else
lightIntensity = fsLightIntensity;
fragColor.rgb *= lightIntensity;
// Translucency (modulates existing alpha channel for RGBA4 texels)
fragColor.a *= fsTransLevel;
// Apply fog under the control of fog factor setting from polygon header
fragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor );
// Store final color
gl_FragColor = fragColor;
}

View file

@ -0,0 +1,239 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Fragment_MultiSheet.glsl
*
* Fragment shader for 3D rendering. Uses 8 texture sheets to decode the
* different possible formats.
*/
#version 120
// Global uniforms
uniform sampler2D textureMap0; // complete texture map (fmt 0), 2048x2048 texels
uniform sampler2D textureMap1; // complete texture map (fmt 1), 2048x2048 texels
uniform sampler2D textureMap2; // complete texture map (fmt 2), 2048x2048 texels
uniform sampler2D textureMap3; // complete texture map (fmt 3), 2048x2048 texels
uniform sampler2D textureMap4; // complete texture map (fmt 4), 2048x2048 texels
uniform sampler2D textureMap5; // complete texture map (fmt 5), 2048x2048 texels
uniform sampler2D textureMap6; // complete texture map (fmt 6), 2048x2048 texels
uniform sampler2D textureMap7; // complete texture map (fmt 7), 2048x2048 texels
uniform vec4 spotEllipse; // spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)
uniform vec2 spotRange; // spotlight Z range: .x=start (viewspace coordinates), .y=limit
uniform vec3 spotColor; // spotlight RGB color
uniform vec3 lighting[2]; // lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)
uniform float mapSize; // texture map size (2048,4096,6144 etc)
// Inputs from vertex shader
varying vec4 fsSubTexture; // .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)
varying vec4 fsTexParams; // .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode
varying float fsTexFormat; // T1RGB5 contour texture (if > 0)
varying float fsTexMap; // texture map number
varying float fsTransLevel; // translucence level, 0.0 (transparent) to 1.0 (opaque)
varying vec3 fsLightIntensity; // lighting intensity
varying float fsSpecularTerm; // specular highlight
varying float fsFogFactor; // fog factor
varying float fsViewZ; // Z distance to fragment from viewpoint at origin
/*
* WrapTexelCoords():
*
* Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture
* sheet, taking into account wrapping behavior.
*
* Computing normalized OpenGL texture coordinates (0 to 1) within the
* Real3D texture sheet:
*
* If the texture is not mirrored, we simply have to clamp the
* coordinates to fit within the texture dimensions, add the texture
* X, Y position to select the appropriate one, and normalize by 2048
* (the dimensions of the Real3D texture sheet).
*
* = [(u,v)%(w,h)+(x,y)]/(2048,2048)
*
* If mirroring is enabled, textures are mirrored every odd multiple of
* the original texture. To detect whether we are in an odd multiple,
* simply divide the coordinate by the texture dimension and check
* whether the result is odd. Then, clamp the coordinates as before but
* subtract from the last texel to mirror them:
*
* = [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)
* where M is 1.0 if the texture must be mirrored.
*
* As an optimization, this function computes TWO texture coordinates
* simultaneously. The first is texCoord.xy, the second is in .zw. The other
* parameters must have .xy = .zw.
*/
vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)
{
vec4 clampedCoord, mirror, glTexCoord;
clampedCoord = mod(texCoord,texSize); // clamp coordinates to within texture size
mirror = mirrorEnable * mod(floor(texCoord/texSize),2.0); // whether this texel needs to be mirrored
glTexCoord = ( mirror*(texSize-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
return glTexCoord;
}
/*
* main():
*
* Fragment shader entry point.
*/
void main(void)
{
vec4 uv_top, uv_bot, c[4];
vec2 r;
vec4 fragColor;
vec2 ellipse;
vec3 lightIntensity;
float insideSpot;
int x;
// Get polygon color for untextured polygons (textured polygons will overwrite)
if (fsTexParams.x < 0.5)
fragColor = gl_Color;
else
// Textured polygons: set fragment color to texel value
{
/*
* Bilinear Filtering
*
* In order to get this working on ATI, the number of operations is
* reduced by putting everything into vec4s. uv_top holds the UV
* coordinates for the top two texels (.xy=left, .zw=right) and uv_bot
* is for the lower two.
*/
// Compute fractional blending factor, r, and lower left corner of texel 0
uv_bot.xy = gl_TexCoord[0].st-vec2(0.5,0.5); // move into the lower left blending texel
r = uv_bot.xy-floor(uv_bot.xy); // fractional part
uv_bot.xy = floor(uv_bot.xy); // integral part
// Compute texel coordinates
uv_bot.xy += vec2(0.5,0.5); // offset to center of pixel (should not be needed but it fixes a lot of glitches, esp. on Nvidia)
uv_bot.zw = uv_bot.xy + vec2(1.0,0.0); // compute coordinates of the other three neighbors
uv_top = uv_bot + vec4(0.0,1.0,0.0,1.0);
// Compute the properly wrapped texel coordinates
uv_top = WrapTexelCoords(uv_top,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
uv_bot = WrapTexelCoords(uv_bot,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
// Fetch the texels from the given texture map
if (fsTexMap < 0.5f) {
c[0]=texture2D(textureMap0, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap0, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap0, uv_top.xy); // top-left
c[3]=texture2D(textureMap0, uv_top.zw); // top-right
} else if (fsTexMap < 1.5f) {
c[0]=texture2D(textureMap1, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap1, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap1, uv_top.xy); // top-left
c[3]=texture2D(textureMap1, uv_top.zw); // top-right
} else if (fsTexMap < 2.5f) {
c[0]=texture2D(textureMap2, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap2, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap2, uv_top.xy); // top-left
c[3]=texture2D(textureMap2, uv_top.zw); // top-right
} else if (fsTexMap < 3.5f) {
c[0]=texture2D(textureMap3, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap3, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap3, uv_top.xy); // top-left
c[3]=texture2D(textureMap3, uv_top.zw); // top-right
} else if (fsTexMap < 4.5f) {
c[0]=texture2D(textureMap4, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap4, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap4, uv_top.xy); // top-left
c[3]=texture2D(textureMap4, uv_top.zw); // top-right
} else if (fsTexMap < 5.5f) {
c[0]=texture2D(textureMap5, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap5, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap5, uv_top.xy); // top-left
c[3]=texture2D(textureMap5, uv_top.zw); // top-right
} else if (fsTexMap < 6.5f) {
c[0]=texture2D(textureMap6, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap6, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap6, uv_top.xy); // top-left
c[3]=texture2D(textureMap6, uv_top.zw); // top-right
} else {
c[0]=texture2D(textureMap7, uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap7, uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap7, uv_top.xy); // top-left
c[3]=texture2D(textureMap7, uv_top.zw); // top-right
}
// Interpolate texels and blend result with material color to determine final (unlit) fragment color
// fragColor = (c[0]*(1.0-r.s)*(1.0-r.t) + c[1]*r.s*(1.0-r.t) + c[2]*(1.0-r.s)*r.t + c[3]*r.s*r.t);
// Faster method:
c[0] += (c[1]-c[0])*r.s; // 2 alu
c[2] += (c[3]-c[2])*r.s; // 2 alu
fragColor = c[0]+(c[2]-c[0])*r.t; // 2 alu
/*
* T1RGB5:
*
* The transparency bit determines whether to discard pixels (if set).
* What is unknown is how this bit behaves when interpolated. OpenGL
* processes it as an alpha value, so it might concievably be blended
* with neighbors. Here, an arbitrary threshold is chosen.
*
* To-do: blending could probably enabled and this would work even
* better with a hard threshold.
*
* Countour processing also seems to be enabled for RGBA4 textures.
* When the alpha value is 0.0 (or close), pixels are discarded
* entirely.
*/
if (fsTexParams.y > 0.5) // contour processing enabled
{
if (fragColor.a < 0.01) // discard anything with alpha == 0
discard;
}
// If contour texture and not discarded, force alpha to 1.0 because will later be modified by polygon translucency
if (fsTexFormat < 0.5) // contour (T1RGB5) texture map
fragColor.a = 1.0;
}
// Compute spotlight and apply lighting
ellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;
insideSpot = dot(ellipse,ellipse);
if ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))
lightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;
else
lightIntensity = fsLightIntensity;
fragColor.rgb *= lightIntensity;
fragColor.rgb += vec3(fsSpecularTerm,fsSpecularTerm,fsSpecularTerm);
// Translucency (modulates existing alpha channel for RGBA4 texels)
fragColor.a *= fsTransLevel;
// Apply fog under the control of fog factor setting from polygon header
fragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor);
// Store final color
gl_FragColor = fragColor;
}

View file

@ -0,0 +1,202 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Fragment_NoSpotlight.glsl
*
* Fragment shader for 3D rendering. Spotlight effect removed. Fixes fragment
* shader link errors on older ATI Radeon GPUs.
*
* To load external fragment shaders, use the -frag-shader=<file> option when
* starting Supermodel.
*/
#version 120
// Global uniforms
uniform sampler2D textureMap; // complete texture map, 2048x2048 texels
uniform vec4 spotEllipse; // spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)
uniform vec2 spotRange; // spotlight Z range: .x=start (viewspace coordinates), .y=limit
uniform vec3 spotColor; // spotlight RGB color
uniform float mapSize; // texture map size (2048,4096,6144 etc)
// Inputs from vertex shader
varying vec4 fsSubTexture; // .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)
varying vec4 fsTexParams; // .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode
varying float fsTexFormat; // .x=T1RGB5 contour texture (if > 0)
varying float fsTransLevel; // translucence level, 0.0 (transparent) to 1.0 (opaque)
varying vec3 fsLightIntensity; // lighting intensity
varying float fsFogFactor; // fog factor
varying float fsViewZ; // Z distance to fragment from viewpoint at origin
/*
* WrapTexelCoords():
*
* Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture
* sheet, taking into account wrapping behavior.
*
* Computing normalized OpenGL texture coordinates (0 to 1) within the
* Real3D texture sheet:
*
* If the texture is not mirrored, we simply have to clamp the
* coordinates to fit within the texture dimensions, add the texture
* X, Y position to select the appropriate one, and normalize by 2048
* (the dimensions of the Real3D texture sheet).
*
* = [(u,v)%(w,h)+(x,y)]/(2048,2048)
*
* If mirroring is enabled, textures are mirrored every odd multiple of
* the original texture. To detect whether we are in an odd multiple,
* simply divide the coordinate by the texture dimension and check
* whether the result is odd. Then, clamp the coordinates as before but
* subtract from the last texel to mirror them:
*
* = [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)
* where M is 1.0 if the texture must be mirrored.
*
* As an optimization, this function computes TWO texture coordinates
* simultaneously. The first is texCoord.xy, the second is in .zw. The other
* parameters must have .xy = .zw.
*/
vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)
{
vec4 clampedCoord, mirror, glTexCoord;
clampedCoord = mod(texCoord,texSize); // clamp coordinates to within texture size
mirror = mirrorEnable * mod(floor(texCoord/texSize),2.0); // whether this texel needs to be mirrored
glTexCoord = ( mirror*(texSize-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
/*
glTexCoord = ( mirror*(texSize-vec4(1.0,1.0,1.0,1.0)-clampedCoord) +
(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +
texOffset
) / mapSize;
*/
return glTexCoord;
}
/*
* main():
*
* Fragment shader entry point.
*/
void main(void)
{
vec4 uv_top, uv_bot, c[4];
vec2 r;
vec4 fragColor;
vec2 ellipse;
vec3 lightIntensity;
float insideSpot;
// Get polygon color for untextured polygons (textured polygons will overwrite)
if (fsTexParams.x < 0.5)
fragColor = gl_Color;
else
// Textured polygons: set fragment color to texel value
{
/*
* Bilinear Filtering
*
* In order to get this working on ATI, the number of operations is
* reduced by putting everything into vec4s. uv_top holds the UV
* coordinates for the top two texels (.xy=left, .zw=right) and uv_bot
* is for the lower two.
*/
// Compute fractional blending factor, r, and lower left corner of texel 0
uv_bot.xy = gl_TexCoord[0].st-vec2(0.5,0.5); // move into the lower left blending texel
r = uv_bot.xy-floor(uv_bot.xy); // fractional part
uv_bot.xy = floor(uv_bot.xy); // integral part
// Compute texel coordinates
uv_bot.xy += vec2(0.5,0.5); // offset to center of pixel (should not be needed but it fixes a lot of glitches, esp. on Nvidia)
uv_bot.zw = uv_bot.xy + vec2(1.0,0.0); // compute coordinates of the other three neighbors
uv_top = uv_bot + vec4(0.0,1.0,0.0,1.0);
// Compute the properly wrapped texel coordinates
uv_top = WrapTexelCoords(uv_top,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
uv_bot = WrapTexelCoords(uv_bot,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));
// Fetch the texels
c[0]=texture2D(textureMap,uv_bot.xy); // bottom-left (base texel)
c[1]=texture2D(textureMap,uv_bot.zw); // bottom-right
c[2]=texture2D(textureMap,uv_top.xy); // top-left
c[3]=texture2D(textureMap,uv_top.zw); // top-right
// Interpolate texels and blend result with material color to determine final (unlit) fragment color
// fragColor = (c[0]*(1.0-r.s)*(1.0-r.t) + c[1]*r.s*(1.0-r.t) + c[2]*(1.0-r.s)*r.t + c[3]*r.s*r.t);
// Faster method:
c[0] += (c[1]-c[0])*r.s; // 2 alu
c[2] += (c[3]-c[2])*r.s; // 2 alu
fragColor = c[0]+(c[2]-c[0])*r.t; //2 alu
/*
* T1RGB5:
*
* The transparency bit determines whether to discard pixels (if set).
* What is unknown is how this bit behaves when interpolated. OpenGL
* processes it as an alpha value, so it might concievably be blended
* with neighbors. Here, an arbitrary threshold is chosen.
*
* To-do: blending could probably enabled and this would work even
* better with a hard threshold.
*
* Countour processing also seems to be enabled for RGBA4 textures.
* When the alpha value is 0.0 (or close), pixels are discarded
* entirely.
*/
if (fsTexParams.y > 0.5) // contour processing enabled
{
if (fragColor.a < 0.01) // discard anything with alpha == 0
discard;
}
// If contour texture and not discarded, force alpha to 1.0 because will later be modified by polygon translucency
if (fsTexFormat < 0.5) // contour (T1RGB5) texture map
fragColor.a = 1.0;
}
// Compute spotlight and apply lighting
/***
ellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;
insideSpot = dot(ellipse,ellipse);
if ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))
lightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;
else
lightIntensity = fsLightIntensity;
fragColor.rgb *= lightIntensity;
***/
fragColor.rgb *= fsLightIntensity;
// Translucency (modulates existing alpha channel for RGBA4 texels)
fragColor.a *= fsTransLevel;
// Apply fog under the control of fog factor setting from polygon header
fragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor );
// Store final color
gl_FragColor = fragColor;
}

View file

@ -0,0 +1,181 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Vertex.glsl
*
* Vertex shader for 3D rendering.
*/
#version 120
// Global uniforms
uniform mat4 modelViewMatrix; // model -> view space matrix
uniform mat4 projectionMatrix; // view space -> screen space matrix
uniform vec3 lighting[2]; // lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)
uniform vec4 spotEllipse; // spotlight ellipse position: .x=X position (normalized device coordinates), .y=Y position, .z=half-width, .w=half-height)
uniform vec2 spotRange; // spotlight Z range: .x=start (viewspace coordinates), .y=limit
uniform vec3 spotColor; // spotlight RGB color
// Custom vertex attributes
attribute vec4 subTexture; // .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)
attribute vec4 texParams; // .x=texture enable (if 1, else 0), .y=use transparency (if >=0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode
attribute float texFormat; // T1RGB5 contour texture (if > 0)
attribute float texMap; // texture map number
attribute float transLevel; // translucence level, 0.0 (transparent) to 1.0 (opaque). if less than 1.0, replace alpha value
attribute float lightEnable; // lighting enabled (1.0) or luminous (0.0), drawn at full intensity
attribute float shininess; // specular shininess (if >= 0.0) or disable specular lighting (negative)
attribute float fogIntensity; // fog intensity (1.0, full fog effect, 0.0, no fog)
// Custom outputs to fragment shader
varying vec4 fsSubTexture;
varying vec4 fsTexParams;
varying float fsTexFormat;
varying float fsTexMap;
varying float fsTransLevel;
varying vec3 fsLightIntensity; // total light intensity for this vertex
varying float fsSpecularTerm; // specular light term (additive)
varying float fsFogFactor; // fog factor
varying float fsViewZ;
// Gets the 3x3 matrix out of a 4x4 (because mat3(mat4matrix) does not work on ATI!)
mat3 GetLinearPart( mat4 m )
{
mat3 result;
result[0][0] = m[0][0];
result[0][1] = m[0][1];
result[0][2] = m[0][2];
result[1][0] = m[1][0];
result[1][1] = m[1][1];
result[1][2] = m[1][2];
result[2][0] = m[2][0];
result[2][1] = m[2][1];
result[2][2] = m[2][2];
return result;
}
void main(void)
{
vec3 viewVertex; // vertex coordinates in view space
vec3 viewNormal; // vertex normal in view space
vec3 sunVector; // sun lighting vector (as reflecting away from vertex)
float sunFactor; // sun light projection along vertex normal (0.0 to 1.0)
vec3 halfway;
float specFactor;
// Transform vertex
gl_Position = projectionMatrix * modelViewMatrix * gl_Vertex;
viewVertex = vec3(modelViewMatrix * gl_Vertex);
/*
* Modulation
*
* Polygon color serves as material color (modulating the light intensity)
* for textured polygons. The fragment shader will ignore (overwrite) the
* the color passed to it if the fragment is textured.
*
* Untextured fragments must be set to the polygon color and the light
* intensity is initialized to 1.0 here. Alpha must be set to 1.0 because
* the fragment shader multiplies it by the polygon translucency setting.
*
* TO-DO: Does OpenGL set alpha to 1.0 by default if no alpha is specified
* for the vertex? If so, we can remove that line from here.
*/
gl_FrontColor = gl_Color; // untextured polygons will use this
gl_FrontColor.a = 1.0;
fsLightIntensity = vec3(1.0,1.0,1.0);
if (texParams.x > 0.5) // textured
fsLightIntensity *= gl_Color.rgb;
/*
* Sun Light
*
* Parallel light source and ambient lighting are only applied for non-
* luminous polygons.
*/
fsSpecularTerm = 0.0;
if (lightEnable > 0.5) // not luminous
{
// Normal -> view space
viewNormal = normalize(GetLinearPart(modelViewMatrix)*gl_Normal);
// Real3D -> OpenGL view space convention (TO-DO: do this outside of shader)
sunVector = lighting[0]*vec3(1.0,-1.0,-1.0);
// Compute diffuse factor for sunlight
sunFactor = max(dot(sunVector,viewNormal),0.0);
// Total light intensity: sum of all components
fsLightIntensity *= (sunFactor*lighting[1].x+lighting[1].y);
/*
* Specular Lighting
*
* The specular term is treated similarly to the "separate specular
* color" functionality of OpenGL: it is added as a highlight in the
* fragment shader. This allows even black textures to be lit.
*
* TO-DO: Ambient intensity viewport parameter is known but what about
* the intensity of the specular term? Always applied with full
* intensity here but this is unlikely to be correct.
*/
if (shininess >= 0.0)
{
// Standard specular lighting equation
vec3 V = normalize(-viewVertex);
vec3 H = normalize(sunVector+V); // halfway vector
float s = max(10.0,64.0-shininess); // seems to look nice, but probably not correct
fsSpecularTerm = pow(max(dot(viewNormal,H),0.0),s);
if (sunFactor <= 0.0) fsSpecularTerm = 0.0;
// Faster approximation
//float temp = max(dot(viewNormal,H),0.0);
//float s = 64.0-shininess;
//fsSpecularTerm = temp/(s-temp*s+temp);
// Phong formula
//vec3 R = normalize(2.0*dot(sunVector,viewNormal)*viewNormal - sunVector);
//vec3 V = normalize(-viewVertex);
//float s = max(2.0,64.0-shininess);
//fsSpecularTerm = pow(max(dot(R,V),0.0),s);
}
}
// Fog
float z = length(viewVertex);
fsFogFactor = clamp(1.0-fogIntensity*(gl_Fog.start+z*gl_Fog.density), 0.0, 1.0);
// Pass viewspace Z coordinate (for spotlight)
fsViewZ = -viewVertex.z; // convert Z from GL->Real3D convention (want +Z to be further into screen)
// Pass remaining parameters to fragment shader
gl_TexCoord[0] = gl_MultiTexCoord0;
fsSubTexture = subTexture;
fsTexParams = texParams;
fsTransLevel = transLevel;
fsTexFormat = texFormat;
fsTexMap = texMap;
}

View file

@ -0,0 +1,34 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Vertex2D.glsl
*
* Vertex shader for 2D tilemap rendering.
*/
#version 120
void main(void)
{
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix*gl_Vertex;
}

View file

@ -0,0 +1,666 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* Shaders3D.h
*
* Header file containing the 3D vertex and fragment shaders.
*/
#ifndef INCLUDED_SHADERS3D_H
#define INCLUDED_SHADERS3D_H
namespace Legacy3D {
// Vertex shader
static const char vertexShaderSource[] =
{
"/**\n"
" ** Supermodel\n"
" ** A Sega Model 3 Arcade Emulator.\n"
" ** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson \n"
" **\n"
" ** This file is part of Supermodel.\n"
" **\n"
" ** Supermodel is free software: you can redistribute it and/or modify it under\n"
" ** the terms of the GNU General Public License as published by the Free \n"
" ** Software Foundation, either version 3 of the License, or (at your option)\n"
" ** any later version.\n"
" **\n"
" ** Supermodel is distributed in the hope that it will be useful, but WITHOUT\n"
" ** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n"
" ** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n"
" ** more details.\n"
" **\n"
" ** You should have received a copy of the GNU General Public License along\n"
" ** with Supermodel. If not, see <http://www.gnu.org/licenses/>.\n"
" **/\n"
" \n"
"/*\n"
" * Vertex.glsl\n"
" *\n"
" * Vertex shader for 3D rendering.\n"
" */\n"
" \n"
"#version 120\n"
"\n"
"// Global uniforms\n"
"uniform mat4\tmodelViewMatrix;\t// model -> view space matrix\n"
"uniform mat4\tprojectionMatrix;\t// view space -> screen space matrix\n"
"uniform vec3\tlighting[2];\t\t// lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)\n"
"uniform vec4\tspotEllipse;\t\t// spotlight ellipse position: .x=X position (normalized device coordinates), .y=Y position, .z=half-width, .w=half-height)\n"
"uniform vec2\tspotRange;\t\t\t// spotlight Z range: .x=start (viewspace coordinates), .y=limit\n"
"uniform vec3\tspotColor;\t\t\t// spotlight RGB color\n"
"\n"
"// Custom vertex attributes\n"
"attribute vec4\tsubTexture;\t\t// .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)\n"
"attribute vec4\ttexParams;\t\t// .x=texture enable (if 1, else 0), .y=use transparency (if >=0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode\n"
"attribute float\ttexFormat;\t\t// T1RGB5 contour texture (if > 0)\n"
"attribute float\ttexMap;\t\t// texture map number\n"
"attribute float\ttransLevel;\t\t// translucence level, 0.0 (transparent) to 1.0 (opaque). if less than 1.0, replace alpha value\n"
"attribute float\tlightEnable;\t// lighting enabled (1.0) or luminous (0.0), drawn at full intensity\n"
"attribute float\tshininess;\t\t// specular shininess (if >= 0.0) or disable specular lighting (negative)\n"
"attribute float\tfogIntensity;\t// fog intensity (1.0, full fog effect, 0.0, no fog) \n"
"\n"
"// Custom outputs to fragment shader\n"
"varying vec4\tfsSubTexture;\n"
"varying vec4\tfsTexParams;\n"
"varying float\tfsTexFormat;\n"
"varying float\tfsTexMap;\n"
"varying float\tfsTransLevel;\n"
"varying vec3\tfsLightIntensity;\t// total light intensity for this vertex\n"
"varying float\tfsSpecularTerm;\t\t// specular light term (additive)\n"
"varying float\tfsFogFactor;\t\t// fog factor\n"
"varying float\tfsViewZ;\n"
"\n"
"// Gets the 3x3 matrix out of a 4x4 (because mat3(mat4matrix) does not work on ATI!)\n"
"mat3 GetLinearPart( mat4 m )\n"
"{\n"
"\tmat3 result;\n"
"\t\n"
"\tresult[0][0] = m[0][0]; \n"
"\tresult[0][1] = m[0][1]; \n"
"\tresult[0][2] = m[0][2]; \n"
"\n"
"\tresult[1][0] = m[1][0]; \n"
"\tresult[1][1] = m[1][1]; \n"
"\tresult[1][2] = m[1][2]; \n"
"\t\n"
"\tresult[2][0] = m[2][0]; \n"
"\tresult[2][1] = m[2][1]; \n"
"\tresult[2][2] = m[2][2]; \n"
"\t\n"
"\treturn result;\n"
"}\n"
"\n"
"void main(void)\n"
"{\n"
"\tvec3\tviewVertex;\t\t// vertex coordinates in view space\n"
"\tvec3\tviewNormal;\t\t// vertex normal in view space\n"
"\tvec3\tsunVector;\t\t// sun lighting vector (as reflecting away from vertex)\n"
"\tfloat\tsunFactor;\t\t// sun light projection along vertex normal (0.0 to 1.0)\n"
"\tvec3\thalfway;\n"
"\tfloat\tspecFactor;\n"
"\t\n"
"\t// Transform vertex\n"
"\tgl_Position = projectionMatrix * modelViewMatrix * gl_Vertex;\n"
"\tviewVertex = vec3(modelViewMatrix * gl_Vertex);\t\n"
"\t\n"
"\t/*\n"
"\t * Modulation\n"
"\t *\n"
" \t * Polygon color serves as material color (modulating the light intensity)\n"
"\t * for textured polygons. The fragment shader will ignore (overwrite) the\n"
"\t * the color passed to it if the fragment is textured. \n"
"\t *\n"
"\t * Untextured fragments must be set to the polygon color and the light\n"
"\t * intensity is initialized to 1.0 here. Alpha must be set to 1.0 because\n"
"\t * the fragment shader multiplies it by the polygon translucency setting. \n"
"\t *\n"
"\t * TO-DO: Does OpenGL set alpha to 1.0 by default if no alpha is specified\n"
"\t * for the vertex? If so, we can remove that line from here.\n"
"\t */\n"
"\n"
"\tgl_FrontColor = gl_Color;\t// untextured polygons will use this\n"
"\tgl_FrontColor.a = 1.0;\t\n"
"\tfsLightIntensity = vec3(1.0,1.0,1.0);\n"
"\tif (texParams.x > 0.5)\t\t// textured\n"
"\t\tfsLightIntensity *= gl_Color.rgb;\n"
"\t\t\n"
"\t/*\n"
" \t * Sun Light\n"
"\t *\n"
"\t * Parallel light source and ambient lighting are only applied for non-\n"
"\t * luminous polygons.\n"
" \t */\n"
"\tfsSpecularTerm = 0.0;\n"
" \tif (lightEnable > 0.5)\t// not luminous\n"
"\t{\n"
"\t\t// Normal -> view space\n"
"\t\tviewNormal = normalize(GetLinearPart(modelViewMatrix)*gl_Normal);\n"
"\n"
"\t\t// Real3D -> OpenGL view space convention (TO-DO: do this outside of shader)\n"
"\t\tsunVector = lighting[0]*vec3(1.0,-1.0,-1.0);\n"
"\t\t\n"
"\t\t// Compute diffuse factor for sunlight\n"
"\t\tsunFactor = max(dot(sunVector,viewNormal),0.0);\n"
"\t\t\n"
"\t\t// Total light intensity: sum of all components\n"
"\t\tfsLightIntensity *= (sunFactor*lighting[1].x+lighting[1].y);\n"
"\t\t\n"
"\t\t/*\n"
"\t\t * Specular Lighting\n"
"\t\t *\n"
"\t\t * The specular term is treated similarly to the \"separate specular\n"
"\t\t * color\" functionality of OpenGL: it is added as a highlight in the\n"
"\t\t * fragment shader. This allows even black textures to be lit.\n"
"\t\t *\n"
"\t\t * TO-DO: Ambient intensity viewport parameter is known but what about\n"
"\t\t * the intensity of the specular term? Always applied with full \n"
"\t\t * intensity here but this is unlikely to be correct.\n"
"\t\t */\n"
" \t\tif (shininess >= 0.0)\n"
" \t\t{\n"
" \t\t\t// Standard specular lighting equation\n"
" \t\t\tvec3 V = normalize(-viewVertex);\n"
" \t\t\tvec3 H = normalize(sunVector+V);\t// halfway vector\n"
" \t\t\tfloat s = max(10.0,64.0-shininess);\t\t// seems to look nice, but probably not correct\n"
" \t\t\tfsSpecularTerm = pow(max(dot(viewNormal,H),0.0),s);\n"
" \t\t\tif (sunFactor <= 0.0) fsSpecularTerm = 0.0;\n"
" \t\t\t\n"
" \t\t\t// Faster approximation \t\t\t\n"
" \t\t\t//float temp = max(dot(viewNormal,H),0.0);\n"
" \t\t\t//float s = 64.0-shininess;\n"
" \t\t\t//fsSpecularTerm = temp/(s-temp*s+temp);\n"
" \t\t\t\n"
" \t\t\t// Phong formula\n"
" \t\t\t//vec3 R = normalize(2.0*dot(sunVector,viewNormal)*viewNormal - sunVector);\n"
" \t\t\t//vec3 V = normalize(-viewVertex);\n"
" \t\t\t//float s = max(2.0,64.0-shininess);\n"
" \t\t\t//fsSpecularTerm = pow(max(dot(R,V),0.0),s);\n"
" \t\t}\n"
"\t}\n"
"\t\n"
"\t// Fog\n"
"\tfloat z = length(viewVertex);\n"
"\tfsFogFactor = clamp(1.0-fogIntensity*(gl_Fog.start+z*gl_Fog.density), 0.0, 1.0);\n"
"\n"
"\t// Pass viewspace Z coordinate (for spotlight)\n"
"\tfsViewZ = -viewVertex.z;\t// convert Z from GL->Real3D convention (want +Z to be further into screen)\n"
"\n"
"\t// Pass remaining parameters to fragment shader\n"
"\tgl_TexCoord[0] = gl_MultiTexCoord0;\n"
"\tfsSubTexture = subTexture;\n"
"\tfsTexParams = texParams;\n"
"\tfsTransLevel = transLevel;\n"
"\tfsTexFormat = texFormat;\n"
"\tfsTexMap = texMap;\n"
"}\n"
};
// Fragment shader (single texture sheet)
static const char fragmentShaderSingleSheetSource[] =
{
"/**\n"
" ** Supermodel\n"
" ** A Sega Model 3 Arcade Emulator.\n"
" ** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson \n"
" **\n"
" ** This file is part of Supermodel.\n"
" **\n"
" ** Supermodel is free software: you can redistribute it and/or modify it under\n"
" ** the terms of the GNU General Public License as published by the Free \n"
" ** Software Foundation, either version 3 of the License, or (at your option)\n"
" ** any later version.\n"
" **\n"
" ** Supermodel is distributed in the hope that it will be useful, but WITHOUT\n"
" ** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n"
" ** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n"
" ** more details.\n"
" **\n"
" ** You should have received a copy of the GNU General Public License along\n"
" ** with Supermodel. If not, see <http://www.gnu.org/licenses/>.\n"
" **/\n"
" \n"
"/*\n"
" * Fragment.glsl\n"
" *\n"
" * Fragment shader for 3D rendering.\n"
" */\n"
"\n"
"#version 120\n"
"\n"
"// Global uniforms\n"
"uniform sampler2D\ttextureMap;\t\t// complete texture map, 2048x2048 texels\n"
"uniform vec4\t\tspotEllipse;\t\t// spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)\n"
"uniform vec2\t\tspotRange;\t\t// spotlight Z range: .x=start (viewspace coordinates), .y=limit\n"
"uniform vec3\t\tspotColor;\t\t// spotlight RGB color\n"
"uniform vec3\t\tlighting[2];\t\t// lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)\n"
"uniform float\t\tmapSize;\t\t// texture map size (2048,4096,6144 etc)\n"
"\n"
"// Inputs from vertex shader \n"
"varying vec4\t\tfsSubTexture;\t// .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)\n"
"varying vec4\t\tfsTexParams;\t// .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode\n"
"varying float\t\tfsTexFormat;\t// T1RGB5 contour texture (if > 0)\n"
"varying float\t\tfsTexMap;\t\t// texture map number\n"
"varying float\t\tfsTransLevel;\t// translucence level, 0.0 (transparent) to 1.0 (opaque)\n"
"varying vec3\t\tfsLightIntensity;\t// lighting intensity \n"
"varying float\t\tfsSpecularTerm;\t// specular highlight\n"
"varying float\t\tfsFogFactor;\t// fog factor\n"
"varying float\t\tfsViewZ;\t\t// Z distance to fragment from viewpoint at origin\n"
"\n"
"/*\n"
" * WrapTexelCoords():\n"
" *\n"
" * Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture\n"
" * sheet, taking into account wrapping behavior.\n"
" *\n"
" * Computing normalized OpenGL texture coordinates (0 to 1) within the \n"
" * Real3D texture sheet:\n"
" *\n"
" * If the texture is not mirrored, we simply have to clamp the\n"
" * coordinates to fit within the texture dimensions, add the texture\n"
" * X, Y position to select the appropriate one, and normalize by 2048\n"
" * (the dimensions of the Real3D texture sheet).\n"
" *\n"
" *\t\t= [(u,v)%(w,h)+(x,y)]/(2048,2048)\n"
" *\n"
" * If mirroring is enabled, textures are mirrored every odd multiple of\n"
" * the original texture. To detect whether we are in an odd multiple, \n"
" * simply divide the coordinate by the texture dimension and check \n"
" * whether the result is odd. Then, clamp the coordinates as before but\n"
" * subtract from the last texel to mirror them:\n"
" *\n"
" * \t\t= [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)\n"
" *\t\twhere M is 1.0 if the texture must be mirrored.\n"
" *\n"
" * As an optimization, this function computes TWO texture coordinates\n"
" * simultaneously. The first is texCoord.xy, the second is in .zw. The other\n"
" * parameters must have .xy = .zw.\n"
" */\n"
"vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)\n"
"{\n"
"\tvec4\tclampedCoord, mirror, glTexCoord;\n"
"\t\n"
"\tclampedCoord = mod(texCoord,texSize);\t\t\t\t\t\t// clamp coordinates to within texture size\n"
"\tmirror = mirrorEnable * mod(floor(texCoord/texSize),2.0);\t// whether this texel needs to be mirrored\n"
"\n"
"\tglTexCoord = (\tmirror*(texSize-clampedCoord) +\n"
"\t\t\t\t\t(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +\n"
"\t\t\t\t\ttexOffset\n"
"\t\t\t\t ) / mapSize;\n"
"\treturn glTexCoord;\n"
"}\n"
"\n"
"/*\n"
" * main():\n"
" *\n"
" * Fragment shader entry point.\n"
" */\n"
"\n"
"void main(void)\n"
"{\t\n"
"\tvec4\tuv_top, uv_bot, c[4];\n"
"\tvec2\tr;\n"
"\tvec4\tfragColor;\n"
"\tvec2\tellipse;\n"
"\tvec3\tlightIntensity;\n"
"\tfloat\tinsideSpot;\n"
"\tint\t\tx;\n"
"\t\n"
"\t// Get polygon color for untextured polygons (textured polygons will overwrite)\n"
"\tif (fsTexParams.x < 0.5)\n"
"\t\tfragColor = gl_Color;\t\t\n"
"\telse\n"
"\t// Textured polygons: set fragment color to texel value\n"
"\t{\t\t\t\n"
"\t\t/*\n"
"\t\t * Bilinear Filtering\n"
"\t\t *\n"
"\t\t * In order to get this working on ATI, the number of operations is\n"
"\t\t * reduced by putting everything into vec4s. uv_top holds the UV \n"
"\t\t * coordinates for the top two texels (.xy=left, .zw=right) and uv_bot\n"
"\t\t * is for the lower two.\n"
"\t\t */\n"
"\n"
"\t\t// Compute fractional blending factor, r, and lower left corner of texel 0\n"
"\t\tuv_bot.xy = gl_TexCoord[0].st-vec2(0.5,0.5);\t// move into the lower left blending texel \n"
"\t\tr = uv_bot.xy-floor(uv_bot.xy);\t\t\t\t\t// fractional part\n"
"\t\tuv_bot.xy = floor(uv_bot.xy);\t\t\t\t\t// integral part\n"
"\t\t\n"
"\t\t// Compute texel coordinates\n"
"\t\tuv_bot.xy += vec2(0.5,0.5);\t// offset to center of pixel (should not be needed but it fixes a lot of glitches, esp. on Nvidia)\n"
"\t\tuv_bot.zw = uv_bot.xy + vec2(1.0,0.0);\t\t\t// compute coordinates of the other three neighbors\n"
"\t\tuv_top = uv_bot + vec4(0.0,1.0,0.0,1.0);\n"
"\n"
"\t\t// Compute the properly wrapped texel coordinates\n"
"\t\tuv_top = WrapTexelCoords(uv_top,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));\n"
"\t\tuv_bot = WrapTexelCoords(uv_bot,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));\n"
"\n"
"\t\t// Fetch the texels\n"
"\t\tc[0]=texture2D(textureMap,uv_bot.xy);\t// bottom-left (base texel)\n"
"\t\tc[1]=texture2D(textureMap,uv_bot.zw);\t// bottom-right\n"
"\t\tc[2]=texture2D(textureMap,uv_top.xy);\t// top-left\n"
"\t\tc[3]=texture2D(textureMap,uv_top.zw);\t// top-right\t\t\n"
"\n"
"\t\t// Interpolate texels and blend result with material color to determine final (unlit) fragment color\n"
"\t\t// fragColor = (c[0]*(1.0-r.s)*(1.0-r.t) + c[1]*r.s*(1.0-r.t) + c[2]*(1.0-r.s)*r.t + c[3]*r.s*r.t);\n"
"\t\t// Faster method:\n"
"\t\tc[0] += (c[1]-c[0])*r.s;\t\t\t// 2 alu\n"
"\t\tc[2] += (c[3]-c[2])*r.s;\t\t\t// 2 alu\n"
"\t\tfragColor = c[0]+(c[2]-c[0])*r.t;\t//2 alu\n"
"\t\n"
"\t\t/*\n"
"\t\t * T1RGB5:\n"
"\t\t *\n"
"\t\t * The transparency bit determines whether to discard pixels (if set).\n"
"\t\t * What is unknown is how this bit behaves when interpolated. OpenGL\n"
"\t\t * processes it as an alpha value, so it might concievably be blended\n"
"\t\t * with neighbors. Here, an arbitrary threshold is chosen.\n"
"\t\t *\n"
"\t\t * To-do: blending could probably enabled and this would work even\n"
"\t\t * better with a hard threshold.\n"
"\t\t *\n"
"\t\t * Countour processing also seems to be enabled for RGBA4 textures.\n"
"\t\t * When the alpha value is 0.0 (or close), pixels are discarded \n"
"\t\t * entirely.\n"
"\t\t */\n"
"\t\tif (fsTexParams.y > 0.5)\t// contour processing enabled\n"
"\t\t{\n"
"\t\t\tif (fragColor.a < 0.01)\t// discard anything with alpha == 0\n"
"\t\t\t\tdiscard;\n"
"\t\t}\n"
"\t\t\n"
"\t\t// If contour texture and not discarded, force alpha to 1.0 because will later be modified by polygon translucency\n"
"\t\tif (fsTexFormat < 0.5)\t\t// contour (T1RGB5) texture\n"
"\t\t\tfragColor.a = 1.0;\n"
"\t}\n"
"\n"
"\t// Compute spotlight and apply lighting\n"
"\tellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;\n"
"\tinsideSpot = dot(ellipse,ellipse);\n"
"\tif ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))\n"
"\t\tlightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;\n"
"\telse\n"
"\t\tlightIntensity = fsLightIntensity;\n"
"\tfragColor.rgb *= lightIntensity;\n"
"\tfragColor.rgb += vec3(fsSpecularTerm,fsSpecularTerm,fsSpecularTerm);\n"
"\t\n"
"\t// Translucency (modulates existing alpha channel for RGBA4 texels)\n"
"\tfragColor.a *= fsTransLevel;\n"
"\n"
"\t// Apply fog under the control of fog factor setting from polygon header\n"
"\tfragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor);\n"
"\n"
"\t// Store final color\n"
"\tgl_FragColor = fragColor;\n"
"}\n"
};
// Fragment shader (8 texture sheets)
static const char fragmentShaderMultiSheetSource[] =
{
"/**\n"
" ** Supermodel\n"
" ** A Sega Model 3 Arcade Emulator.\n"
" ** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson \n"
" **\n"
" ** This file is part of Supermodel.\n"
" **\n"
" ** Supermodel is free software: you can redistribute it and/or modify it under\n"
" ** the terms of the GNU General Public License as published by the Free \n"
" ** Software Foundation, either version 3 of the License, or (at your option)\n"
" ** any later version.\n"
" **\n"
" ** Supermodel is distributed in the hope that it will be useful, but WITHOUT\n"
" ** ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n"
" ** FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n"
" ** more details.\n"
" **\n"
" ** You should have received a copy of the GNU General Public License along\n"
" ** with Supermodel. If not, see <http://www.gnu.org/licenses/>.\n"
" **/\n"
" \n"
"/*\n"
" * Fragment_MultiSheet.glsl\n"
" *\n"
" * Fragment shader for 3D rendering. Uses 8 texture sheets to decode the \n"
" * different possible formats.\n"
" */\n"
"\n"
"#version 120\n"
"\n"
"// Global uniforms\n"
"uniform sampler2D\ttextureMap0;\t\t// complete texture map (fmt 0), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap1;\t\t// complete texture map (fmt 1), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap2;\t\t// complete texture map (fmt 2), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap3;\t\t// complete texture map (fmt 3), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap4;\t\t// complete texture map (fmt 4), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap5;\t\t// complete texture map (fmt 5), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap6;\t\t// complete texture map (fmt 6), 2048x2048 texels\n"
"uniform sampler2D\ttextureMap7;\t\t// complete texture map (fmt 7), 2048x2048 texels\n"
"uniform vec4\t\tspotEllipse;\t\t// spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)\n"
"uniform vec2\t\tspotRange;\t\t\t// spotlight Z range: .x=start (viewspace coordinates), .y=limit\n"
"uniform vec3\t\tspotColor;\t\t\t// spotlight RGB color\n"
"uniform vec3\t\tlighting[2];\t\t// lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)\n"
"uniform float\t\tmapSize;\t\t// texture map size (2048,4096,6144 etc)\n"
"\n"
"// Inputs from vertex shader \n"
"varying vec4\t\tfsSubTexture;\t// .x=texture X, .y=texture Y, .z=texture width, .w=texture height (all in texels)\n"
"varying vec4\t\tfsTexParams;\t// .x=texture enable (if 1, else 0), .y=use transparency (if > 0), .z=U wrap mode (1=mirror, 0=repeat), .w=V wrap mode\n"
"varying float\t\tfsTexFormat;\t// T1RGB5 contour texture (if > 0)\n"
"varying float\t\tfsTexMap;\t// texture map number\n"
"varying float\t\tfsTransLevel;\t// translucence level, 0.0 (transparent) to 1.0 (opaque)\n"
"varying vec3\t\tfsLightIntensity;\t// lighting intensity \n"
"varying float\t\tfsSpecularTerm;\t// specular highlight\n"
"varying float\t\tfsFogFactor;\t// fog factor\n"
"varying float\t\tfsViewZ;\t\t// Z distance to fragment from viewpoint at origin\n"
"\n"
"/*\n"
" * WrapTexelCoords():\n"
" *\n"
" * Computes the normalized OpenGL S,T coordinates within the 2048x2048 texture\n"
" * sheet, taking into account wrapping behavior.\n"
" *\n"
" * Computing normalized OpenGL texture coordinates (0 to 1) within the \n"
" * Real3D texture sheet:\n"
" *\n"
" * If the texture is not mirrored, we simply have to clamp the\n"
" * coordinates to fit within the texture dimensions, add the texture\n"
" * X, Y position to select the appropriate one, and normalize by 2048\n"
" * (the dimensions of the Real3D texture sheet).\n"
" *\n"
" *\t\t= [(u,v)%(w,h)+(x,y)]/(2048,2048)\n"
" *\n"
" * If mirroring is enabled, textures are mirrored every odd multiple of\n"
" * the original texture. To detect whether we are in an odd multiple, \n"
" * simply divide the coordinate by the texture dimension and check \n"
" * whether the result is odd. Then, clamp the coordinates as before but\n"
" * subtract from the last texel to mirror them:\n"
" *\n"
" * \t\t= [M*((w-1,h-1)-(u,v)%(w,h)) + (1-M)*(u,v)%(w,h) + (x,y)]/(2048,2048)\n"
" *\t\twhere M is 1.0 if the texture must be mirrored.\n"
" *\n"
" * As an optimization, this function computes TWO texture coordinates\n"
" * simultaneously. The first is texCoord.xy, the second is in .zw. The other\n"
" * parameters must have .xy = .zw.\n"
" */\n"
"vec4 WrapTexelCoords(vec4 texCoord, vec4 texOffset, vec4 texSize, vec4 mirrorEnable)\n"
"{\n"
"\tvec4\tclampedCoord, mirror, glTexCoord;\n"
"\t\n"
"\tclampedCoord = mod(texCoord,texSize);\t\t\t\t\t\t// clamp coordinates to within texture size\n"
"\tmirror = mirrorEnable * mod(floor(texCoord/texSize),2.0);\t// whether this texel needs to be mirrored\n"
"\n"
"\tglTexCoord = (\tmirror*(texSize-clampedCoord) +\n"
"\t\t\t\t\t(vec4(1.0,1.0,1.0,1.0)-mirror)*clampedCoord +\n"
"\t\t\t\t\ttexOffset\n"
"\t\t\t\t ) / mapSize;\n"
"\treturn glTexCoord;\n"
"}\n"
"\n"
"/*\n"
" * main():\n"
" *\n"
" * Fragment shader entry point.\n"
" */\n"
"\n"
"void main(void)\n"
"{\t\n"
"\tvec4\tuv_top, uv_bot, c[4];\n"
"\tvec2\tr;\n"
"\tvec4\tfragColor;\n"
"\tvec2\tellipse;\n"
"\tvec3\tlightIntensity;\n"
"\tfloat\tinsideSpot;\n"
"\tint\t\tx;\n"
"\t\n"
"\t// Get polygon color for untextured polygons (textured polygons will overwrite)\n"
"\tif (fsTexParams.x < 0.5)\n"
"\t\tfragColor = gl_Color;\t\t\n"
"\telse\n"
"\t// Textured polygons: set fragment color to texel value\n"
"\t{\t\t\t\n"
"\t\t/*\n"
"\t\t * Bilinear Filtering\n"
"\t\t *\n"
"\t\t * In order to get this working on ATI, the number of operations is\n"
"\t\t * reduced by putting everything into vec4s. uv_top holds the UV \n"
"\t\t * coordinates for the top two texels (.xy=left, .zw=right) and uv_bot\n"
"\t\t * is for the lower two.\n"
"\t\t */\n"
"\n"
"\t\t// Compute fractional blending factor, r, and lower left corner of texel 0\n"
"\t\tuv_bot.xy = gl_TexCoord[0].st-vec2(0.5,0.5);\t// move into the lower left blending texel \n"
"\t\tr = uv_bot.xy-floor(uv_bot.xy);\t\t\t\t\t// fractional part\n"
"\t\tuv_bot.xy = floor(uv_bot.xy);\t\t\t\t\t// integral part\n"
"\t\t\n"
"\t\t// Compute texel coordinates\n"
"\t\tuv_bot.xy += vec2(0.5,0.5);\t// offset to center of pixel (should not be needed but it fixes a lot of glitches, esp. on Nvidia)\n"
"\t\tuv_bot.zw = uv_bot.xy + vec2(1.0,0.0);\t\t\t// compute coordinates of the other three neighbors\n"
"\t\tuv_top = uv_bot + vec4(0.0,1.0,0.0,1.0);\n"
"\n"
"\t\t// Compute the properly wrapped texel coordinates\n"
"\t\tuv_top = WrapTexelCoords(uv_top,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));\n"
"\t\tuv_bot = WrapTexelCoords(uv_bot,vec4(fsSubTexture.xy,fsSubTexture.xy),vec4(fsSubTexture.zw,fsSubTexture.zw), vec4(fsTexParams.zw,fsTexParams.zw));\n"
"\n"
"\t\t// Fetch the texels from the given texture map\n"
"\t\tif (fsTexMap < 0.5f)\t{\n"
"\t\t\tc[0]=texture2D(textureMap0, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap0, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap0, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap0, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 1.5f) {\n"
" c[0]=texture2D(textureMap1, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap1, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap1, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap1, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 2.5f) {\n"
" c[0]=texture2D(textureMap2, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap2, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap2, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap2, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 3.5f) {\n"
" c[0]=texture2D(textureMap3, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap3, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap3, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap3, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 4.5f) {\n"
" c[0]=texture2D(textureMap4, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap4, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap4, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap4, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 5.5f) {\n"
" c[0]=texture2D(textureMap5, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap5, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap5, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap5, uv_top.zw); // top-right\n"
"\t\t} else if (fsTexMap < 6.5f) {\n"
"\t\t\tc[0]=texture2D(textureMap6, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap6, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap6, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap6, uv_top.zw); // top-right\n"
"\t\t} else {\n"
" c[0]=texture2D(textureMap7, uv_bot.xy); // bottom-left (base texel)\n"
"\t\t\tc[1]=texture2D(textureMap7, uv_bot.zw); // bottom-right\n"
"\t\t\tc[2]=texture2D(textureMap7, uv_top.xy); // top-left\n"
"\t\t\tc[3]=texture2D(textureMap7, uv_top.zw); // top-right\n"
"\t\t} \n"
"\n"
"\t\t// Interpolate texels and blend result with material color to determine final (unlit) fragment color\n"
"\t\t// fragColor = (c[0]*(1.0-r.s)*(1.0-r.t) + c[1]*r.s*(1.0-r.t) + c[2]*(1.0-r.s)*r.t + c[3]*r.s*r.t);\n"
"\t\t// Faster method:\n"
"\t\tc[0] += (c[1]-c[0])*r.s;\t\t\t// 2 alu\n"
"\t\tc[2] += (c[3]-c[2])*r.s;\t\t\t// 2 alu\n"
"\t\tfragColor = c[0]+(c[2]-c[0])*r.t;\t// 2 alu\n"
"\t\n"
"\t\t/*\n"
"\t\t * T1RGB5:\n"
"\t\t *\n"
"\t\t * The transparency bit determines whether to discard pixels (if set).\n"
"\t\t * What is unknown is how this bit behaves when interpolated. OpenGL\n"
"\t\t * processes it as an alpha value, so it might concievably be blended\n"
"\t\t * with neighbors. Here, an arbitrary threshold is chosen.\n"
"\t\t *\n"
"\t\t * To-do: blending could probably enabled and this would work even\n"
"\t\t * better with a hard threshold.\n"
"\t\t *\n"
"\t\t * Countour processing also seems to be enabled for RGBA4 textures.\n"
"\t\t * When the alpha value is 0.0 (or close), pixels are discarded \n"
"\t\t * entirely.\n"
"\t\t */\n"
"\t\tif (fsTexParams.y > 0.5)\t// contour processing enabled\n"
"\t\t{\n"
"\t\t\tif (fragColor.a < 0.01)\t// discard anything with alpha == 0\n"
"\t\t\t\tdiscard;\n"
"\t\t}\n"
"\t\t\n"
"\t\t// If contour texture and not discarded, force alpha to 1.0 because will later be modified by polygon translucency\n"
"\t\tif (fsTexFormat < 0.5)\t\t// contour (T1RGB5) texture map\n"
"\t\t\tfragColor.a = 1.0;\n"
"\t}\n"
"\n"
"\t// Compute spotlight and apply lighting\n"
"\tellipse = (gl_FragCoord.xy-spotEllipse.xy)/spotEllipse.zw;\n"
"\tinsideSpot = dot(ellipse,ellipse);\n"
"\tif ((insideSpot <= 1.0) && (fsViewZ>=spotRange.x) && (fsViewZ<spotRange.y))\n"
"\t\tlightIntensity = fsLightIntensity+(1.0-insideSpot)*spotColor;\n"
"\telse\n"
"\t\tlightIntensity = fsLightIntensity;\n"
"\tfragColor.rgb *= lightIntensity;\n"
"\tfragColor.rgb += vec3(fsSpecularTerm,fsSpecularTerm,fsSpecularTerm);\n"
"\t\n"
"\t// Translucency (modulates existing alpha channel for RGBA4 texels)\n"
"\tfragColor.a *= fsTransLevel;\n"
"\n"
"\t// Apply fog under the control of fog factor setting from polygon header\n"
"\tfragColor.rgb = mix(gl_Fog.color.rgb, fragColor.rgb, fsFogFactor);\n"
"\n"
"\t// Store final color\n"
"\tgl_FragColor = fragColor;\n"
"}\n"
};
} // Legacy3D
#endif // INCLUDED_SHADERS3D_H

View file

@ -0,0 +1,333 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* CTextureRefs.cpp
*
* Class that tracks unique texture references, eg in a cached model.
*
* Texture references are stored internally as a 27-bit field (3 bits for format, 6 bits each for x, y, width & height) to save space.
*
* A pre-allocated array is used for storing up to TEXREFS_ARRAY_SIZE texture references. When that limit is exceeded, it switches
* to using a hashset to store the texture references, but this requires extra memory allocation.
*/
#include "Supermodel.h"
namespace Legacy3D {
CTextureRefs::CTextureRefs() : m_size(0), m_hashCapacity(0), m_hashEntries(NULL)
{
//
}
CTextureRefs::~CTextureRefs()
{
DeleteAllHashEntries();
}
unsigned CTextureRefs::GetSize() const
{
return m_size;
}
void CTextureRefs::Clear()
{
// Delete all hash entries
DeleteAllHashEntries();
m_size = 0;
m_hashCapacity = 0;
m_hashEntries = NULL;
}
bool CTextureRefs::ContainsRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height)
{
// Pack texture reference into bitfield
unsigned texRef = (fmt&7)<<24|(x&0x7E0)<<13|(y&0x7E0)<<7|(width&0x7E0)<<1|(height&0x7E0)>>5;
// Check if using array or hashset
if (m_size <= TEXREFS_ARRAY_SIZE)
{
// See if texture reference held in array
for (unsigned i = 0; i < m_size; i++)
{
if (texRef == m_array[i])
return true;
}
return false;
}
else
// See if texture reference held in hashset
return HashContains(texRef);
}
bool CTextureRefs::AddRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height)
{
// Pack texture reference into bitfield
unsigned texRef = (fmt&7)<<24|(x&0x7E0)<<13|(y&0x7E0)<<7|(width&0x7E0)<<1|(height&0x7E0)>>5;
// Check if using array or hashset
if (m_size <= TEXREFS_ARRAY_SIZE)
{
// See if already held in array, if so nothing to do
for (unsigned i = 0; i < m_size; i++)
{
if (texRef == m_array[i])
return true;
}
// If not, check if array is full
if (m_size == TEXREFS_ARRAY_SIZE)
{
// If so, set initial hashset capacity to 47 to initialize it
UpdateHashCapacity(47);
// Copy array into hashset
for (unsigned i = 0; i < TEXREFS_ARRAY_SIZE; i++)
AddToHash(m_array[i]);
// Add texture reference to hashset
AddToHash(texRef);
}
else
{
// Add texture reference to array
m_array[m_size] = texRef;
m_size++;
}
return true;
}
else
// Add texture reference to hashset
return AddToHash(texRef);
}
bool CTextureRefs::RemoveRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height)
{
// Pack texture reference into bitfield
unsigned texRef = (fmt&7)<<24|(x&0x7E0)<<13|(y&0x7E0)<<7|(width&0x7E0)<<1|(height&0x7E0)>>5;
// Check if using array or hashset
if (m_size <= TEXREFS_ARRAY_SIZE)
{
for (unsigned i = 0; i < m_size; i++)
{
if (texRef == m_array[i])
{
for (unsigned j = i + 1; j < m_size; j++)
m_array[j - 1] = m_array[j];
m_size--;
return true;
}
}
return false;
}
else
{
// Remove texture reference from hashset
bool removed = RemoveFromHash(texRef);
// See if should switch back to array
if (m_size == TEXREFS_ARRAY_SIZE)
{
// Loop through all hash entries and copy texture references into array
unsigned j = 0;
for (unsigned i = 0; i < m_hashCapacity; i++)
{
for (HashEntry *entry = m_hashEntries[i]; entry; entry = entry->nextEntry)
m_array[j++] = entry->texRef;
}
// Delete all hash entries
DeleteAllHashEntries();
}
return removed;
}
}
void CTextureRefs::DecodeAllTextures(CLegacy3D *Render3D)
{
// Check if using array or hashset
if (m_size <= TEXREFS_ARRAY_SIZE)
{
// Loop through elements in array and call CLegacy3D::DecodeTexture
for (unsigned i = 0; i < m_size; i++)
{
// Unpack texture reference from bitfield
unsigned texRef = m_array[i];
unsigned fmt = texRef>>24;
unsigned x = (texRef>>13)&0x7E0;
unsigned y = (texRef>>7)&0x7E0;
unsigned width = (texRef>>1)&0x7E0;
unsigned height = (texRef<<5)&0x7E0;
Render3D->DecodeTexture(fmt, x, y, width, height);
}
}
else
{
// Loop through all hash entriesa and call CLegacy3D::DecodeTexture
for (unsigned i = 0; i < m_hashCapacity; i++)
{
for (HashEntry *entry = m_hashEntries[i]; entry; entry = entry->nextEntry)
{
// Unpack texture reference from bitfield
unsigned texRef = entry->texRef;
unsigned fmt = texRef>>24;
unsigned x = (texRef>>13)&0x7E0;
unsigned y = (texRef>>7)&0x7E0;
unsigned width = (texRef>>1)&0x7E0;
unsigned height = (texRef<<5)&0x7E0;
Render3D->DecodeTexture(fmt, x, y, width, height);
}
}
}
}
bool CTextureRefs::UpdateHashCapacity(unsigned capacity)
{
unsigned oldCapacity = m_hashCapacity;
HashEntry **oldEntries = m_hashEntries;
// Update capacity and create new empty entries array
m_hashCapacity = capacity;
m_hashEntries = new(std::nothrow) HashEntry*[capacity];
if (!m_hashEntries)
return false;
memset(m_hashEntries, NULL, capacity * sizeof(HashEntry*));
if (oldEntries)
{
// Redistribute entries into new entries array
for (unsigned i = 0; i < oldCapacity; i++)
{
HashEntry *entry = oldEntries[i];
while (entry)
{
HashEntry *nextEntry = entry->nextEntry;
unsigned hash = entry->texRef % capacity;
entry->nextEntry = m_hashEntries[hash];
m_hashEntries[hash] = entry;
entry = nextEntry;
}
}
// Delete old entries array
delete[] oldEntries;
}
return true;
}
HashEntry *CTextureRefs::CreateHashEntry(unsigned texRef, bool &hashCapacityUpdated)
{
// Update size and increase hash capacity if required
m_size++;
hashCapacityUpdated = m_size >= m_hashCapacity;
if (hashCapacityUpdated)
{
if (m_hashCapacity < 89)
UpdateHashCapacity(89); // Capacity of 89 gives good sequence of mostly prime capacities (89, 179, 359, 719, 1439, 2879 etc)
else
UpdateHashCapacity(2 * m_hashCapacity + 1);
}
return new(std::nothrow) HashEntry(texRef);
}
void CTextureRefs::DeleteHashEntry(HashEntry *entry)
{
// Update size and delete hash entry
m_size--;
delete entry;
}
void CTextureRefs::DeleteAllHashEntries()
{
if (!m_hashEntries)
return;
// Delete all hash entries and their storage
for (unsigned i = 0; i < m_hashCapacity; i++)
{
HashEntry *entry = m_hashEntries[i];
if (entry)
delete entry;
}
delete[] m_hashEntries;
}
bool CTextureRefs::AddToHash(unsigned texRef)
{
// Convert texture reference to hash value
unsigned hash = texRef % m_hashCapacity;
// Loop through linked list for hash value and see if have texture reference already
HashEntry *headEntry = m_hashEntries[hash];
HashEntry *entry = headEntry;
while (entry && texRef != entry->texRef)
entry = entry->nextEntry;
// If found, nothing to do
if (entry)
return true;
// Otherwise, create new hash entry for texture reference
bool hashCapacityUpdated;
entry = CreateHashEntry(texRef, hashCapacityUpdated);
// If couldn't create entry (ie out of memory), let caller know
if (!entry)
return false;
if (hashCapacityUpdated)
{
// If hash capacity was increased recalculate hash value
hash = texRef % m_hashCapacity;
headEntry = m_hashEntries[hash];
}
// Store hash entry in linked list for hash value
entry->nextEntry = headEntry;
m_hashEntries[hash] = entry;
return true;
}
bool CTextureRefs::RemoveFromHash(unsigned texRef)
{
// Convert texture reference to hash value
unsigned hash = texRef % m_hashCapacity;
// Loop through linked list for hash value and see if have texture reference
HashEntry *entry = m_hashEntries[hash];
HashEntry *prevEntry = NULL;
while (entry && texRef != entry->texRef)
{
prevEntry = entry;
entry = entry->nextEntry;
}
// If not found, nothing to do
if (!entry)
return false;
// Otherwise, remove entry from linked list for hash value
if (prevEntry)
prevEntry->nextEntry = entry->nextEntry;
else
m_hashEntries[hash] = entry->nextEntry;
// Delete hash entry storage
DeleteHashEntry(entry);
return true;
}
bool CTextureRefs::HashContains(unsigned texRef) const
{
// Convert texture reference to hash value
unsigned hash = texRef % m_hashCapacity;
// Loop through linked list for hash value and see if have texture reference
HashEntry *entry = m_hashEntries[hash];
while (entry && texRef != entry->texRef)
entry = entry->nextEntry;
return !!entry;
}
} // Legacy3D

View file

@ -0,0 +1,168 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* CTextureRefs.h
*
* Class that tracks unique texture references, eg in a cached model.
*/
#ifndef INCLUDED_TEXTUREREFS_H
#define INCLUDED_TEXTUREREFS_H
namespace Legacy3D {
#define TEXREFS_ARRAY_SIZE 12
// Hash entry that holds a texture reference in the hashset
struct HashEntry
{
const unsigned texRef; // Texture reference as a bitfield
HashEntry *nextEntry; // Next entry with the same hash
HashEntry(unsigned theTexRef) : texRef(theTexRef), nextEntry(NULL) { }
};
class CLegacy3D;
class CTextureRefs
{
public:
/*
* CTextureRefs():
*
* Constructor.
*/
CTextureRefs();
/*
* ~CTextureRefs():
*
* Destructor.
*/
~CTextureRefs();
/*
* GetSize():
*
* Returns number of unique texture references held.
*/
unsigned GetSize() const;
/*
* Clear():
*
* Removes all texture references.
*/
void Clear();
/*
* ContainsRef(fmt, x, y, width, height):
*
* Returns true if holds the given texture reference.
*/
bool ContainsRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height);
/*
* AddRef(fmt, x, y, width, height):
*
* Adds the given texture reference. Returns false if it was not possible to add the reference (ie out of memory).
*/
bool AddRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height);
/*
* RemoveRef(fmt, x, y, width, height):
*
* Removes the given texture reference. Return true if the reference was found.
*/
bool RemoveRef(unsigned fmt, unsigned x, unsigned y, unsigned width, unsigned height);
/*
* RemoveRef(fmt, x, y, width, height):
*
* Decodes all texture references held, calling CLegacy3D::DecodeTexture for each one.
*/
void DecodeAllTextures(CLegacy3D *Render3D);
private:
// Number of texture references held.
unsigned m_size;
// Pre-allocated array used to hold first TEXREFS_ARRAY_SIZE texture references.
unsigned m_array[TEXREFS_ARRAY_SIZE];
// Dynamically allocated hashset used to hold texture references when there are more than TEXREFS_ARRAY_SIZE.
unsigned m_hashCapacity;
HashEntry **m_hashEntries;
/*
* UpdateHashCapacity(hashCapacity)
*
* Increases capacity of the hashset to given size.
*/
bool UpdateHashCapacity(unsigned hashCapacity);
/*
* CreateHashEntry(texRef, hashCapacityUpdated)
*
* Creates and returns a new hash entry, updating the capacity if required (hashCapacityUpdated is set to true).
*/
HashEntry *CreateHashEntry(unsigned texRef, bool &hashCapacityUpdated);
/*
* DeleteHashEntry(entry)
*
* Deletes the given hash entry and its storage.
*/
void DeleteHashEntry(HashEntry *entry);
/*
* DeleteAllHashEntries()
*
* Deletes all hash entries and their storage.
*/
void DeleteAllHashEntries();
/*
* AddToHash(texRef)
*
* Adds the given texture reference (as a bitfield) to the hashset.
*/
bool AddToHash(unsigned texRef);
/*
* RemoveFromHash(texRef)
*
* Removes the given texture reference (as a bitfield) from the hashset.
*/
bool RemoveFromHash(unsigned texRef);
/*
* HashContains(texRef)
*
* Returns true if given texture reference (as a bitfield) is held in the hashset.
*/
bool HashContains(unsigned texRef) const;
};
} // Legacy3D
#endif // INCLUDED_TEXTUREREFS_H

353
Src/Graphics/New3D/Mat4.cpp Normal file
View file

@ -0,0 +1,353 @@
#include "Mat4.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <utility>
#ifndef M_PI
#define M_PI 3.14159265359
#endif
namespace New3D {
Mat4::Mat4()
{
LoadIdentity();
}
void Mat4::LoadIdentity()
{
float *m = currentMatrix;
m[0] = 1; m[4] = 0; m[8 ] = 0; m[12] = 0;
m[1] = 0; m[5] = 1; m[9 ] = 0; m[13] = 0;
m[2] = 0; m[6] = 0; m[10] = 1; m[14] = 0;
m[3] = 0; m[7] = 0; m[11] = 0; m[15] = 1;
}
void Mat4::MultiMatrices(const float a[16], const float b[16], float r[16]) {
#define A(row,col) a[(col<<2)+row]
#define B(row,col) b[(col<<2)+row]
#define P(row,col) r[(col<<2)+row]
int i;
for (i = 0; i < 4; i++) {
const float ai0 = A(i, 0), ai1 = A(i, 1), ai2 = A(i, 2), ai3 = A(i, 3);
P(i, 0) = ai0 * B(0, 0) + ai1 * B(1, 0) + ai2 * B(2, 0) + ai3 * B(3, 0);
P(i, 1) = ai0 * B(0, 1) + ai1 * B(1, 1) + ai2 * B(2, 1) + ai3 * B(3, 1);
P(i, 2) = ai0 * B(0, 2) + ai1 * B(1, 2) + ai2 * B(2, 2) + ai3 * B(3, 2);
P(i, 3) = ai0 * B(0, 3) + ai1 * B(1, 3) + ai2 * B(2, 3) + ai3 * B(3, 3);
}
#undef A
#undef B
#undef p
}
void Mat4::Copy(const float in[16], float out[16]) {
for (int i = 0; i<16; i++) {
out[i] = in[i];
}
}
void Mat4::Translate(float x, float y, float z) {
//=============
float m[16];
float cur[16];
//=============
Mat4::Copy(currentMatrix, cur);
m[0] = 1;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = 1;
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = 1;
m[11] = 0;
m[12] = x;
m[13] = y;
m[14] = z;
m[15] = 1;
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::Scale(float x, float y, float z) {
//=============
float m[16];
float cur[16];
//=============
Mat4::Copy(currentMatrix, cur);
m[0] = x;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = y;
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = z;
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::Rotate(float angle, float x, float y, float z) {
//============
float c;
float s;
float m[16];
float cur[16];
//===========
Mat4::Copy(currentMatrix, cur);
// normalise vector first
{
//========
float len;
//========
len = sqrt(x * x + y * y + z * z);
x /= len;
y /= len;
z /= len;
}
c = cos(angle*3.14159265f / 180.0f);
s = sin(angle*3.14159265f / 180.0f);
m[0] = (x*x) * (1 - c) + c;
m[1] = (y*x) * (1 - c) + (z*s);
m[2] = (x*z) * (1 - c) - (y*s);
m[3] = 0;
m[4] = (x*y) * (1 - c) - (z*s);
m[5] = (y*y) * (1 - c) + c;
m[6] = (y*z) * (1 - c) + (x*s);
m[7] = 0;
m[8] = (x*z) * (1 - c) + (y*s);
m[9] = (y*z) * (1 - c) - (x*s);
m[10] = (z*z) * (1 - c) + c;
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::Frustum(float left, float right, float bottom, float top, float nearVal, float farVal) {
//=====================
float m[16];
float cur[16];
float x, y, a, b, c, d;
//=====================
Mat4::Copy(currentMatrix, cur);
x = (2.0F*nearVal) / (right - left);
y = (2.0F*nearVal) / (top - bottom);
a = (right + left) / (right - left);
b = (top + bottom) / (top - bottom);
c = -(farVal + nearVal) / (farVal - nearVal);
d = -(2.0F*farVal*nearVal) / (farVal - nearVal);
m[0] = x;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = y;
m[6] = 0;
m[7] = 0;
m[8] = a;
m[9] = b;
m[10] = c;
m[11] = -1;
m[12] = 0;
m[13] = 0;
m[14] = d;
m[15] = 0;
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::Perspective(float fovy, float aspect, float zNear, float zFar)
{
//=========
float ymax;
float xmax;
//=========
ymax = zNear * tanf(fovy * (float)M_PI / 360.0f);
xmax = ymax * aspect;
Frustum(-xmax, xmax, -ymax, ymax, zNear, zFar);
}
void Mat4::Ortho(float left, float right, float bottom, float top, float nearVal, float farVal)
{
//================
float m[16];
float cur[16];
float tx, ty, tz;
//================
Mat4::Copy(currentMatrix, cur);
tx = -(right + left) / (right - left);
ty = -(top + bottom) / (top - bottom);
tz = -(farVal + nearVal) / (farVal - nearVal);
m[0] = 2/(right-left);
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = 2/(top-bottom);
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = -2/(farVal-nearVal);
m[11] = 0;
m[12] = tx;
m[13] = ty;
m[14] = tz;
m[15] = 1;
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::Transpose(float m[16]) {
std::swap(m[1], m[4]);
std::swap(m[2], m[8]);
std::swap(m[3], m[12]);
std::swap(m[6], m[9]);
std::swap(m[7], m[13]);
std::swap(m[11], m[14]);
}
void Mat4::MultMatrix(const float *m)
{
if (!m) {
return;
}
//============
float cur[16];
//============
Mat4::Copy(currentMatrix, cur);
Mat4::MultiMatrices(cur, m, currentMatrix);
}
void Mat4::LoadMatrix(const float *m)
{
if (!m) {
return;
}
Mat4::Copy(m, currentMatrix);
}
void Mat4::LoadTransposeMatrix(const float *m)
{
if (!m) {
return;
}
//=============
float copy[16];
//=============
Mat4::Copy(m, copy);
Mat4::Transpose(copy);
Mat4::LoadMatrix(copy);
}
void Mat4::MultTransposeMatrix(const float *m)
{
if (!m) {
return;
}
//=============
float copy[16];
//=============
Mat4::Copy(m, copy);
Mat4::Transpose(copy);
Mat4::MultMatrix(copy);
}
void Mat4::PushMatrix()
{
//==============
Mat4Container m;
//==============
if (m_vMat4.size() > 128) {
return; // check for overflow
}
Mat4::Copy(currentMatrix, m.mat);
m_vMat4.push_back(m);
}
void Mat4::PopMatrix()
{
if (m_vMat4.empty()) {
return; // check for underflow
}
Mat4::Copy(m_vMat4.back().mat, currentMatrix);
m_vMat4.pop_back();
}
// flush the matrix stack
void Mat4::Release()
{
m_vMat4.clear();
}
} // New3D

48
Src/Graphics/New3D/Mat4.h Normal file
View file

@ -0,0 +1,48 @@
#ifndef _MAT4_H_
#define _MAT4_H_
#include <vector>
namespace New3D {
class Mat4
{
public:
Mat4();
void LoadIdentity ();
void Translate (float x, float y, float z);
void Rotate (float angle, float x, float y, float z);
void Scale (float x, float y, float z);
void Frustum (float left, float right, float bottom, float top, float nearVal, float farVal);
void Ortho (float left, float right, float bottom, float top, float nearVal, float farVal);
void Perspective (float fovy, float aspect, float zNear, float zFar);
void MultMatrix (const float *m);
void LoadMatrix (const float *m);
void LoadTransposeMatrix (const float *m);
void MultTransposeMatrix (const float *m);
void PushMatrix ();
void PopMatrix ();
void Release ();
operator const float* () { return currentMatrix; }
float currentMatrix[16];
private:
void MultiMatrices (const float a[16], const float b[16], float r[16]);
void Copy (const float in[16], float out[16]);
void Transpose (float m[16]);
struct Mat4Container {
float mat[16]; // we must wrap the matrix inside a struct otherwise vector doesn't work
};
std::vector<Mat4Container> m_vMat4;
};
} // New3D
#endif

View file

@ -0,0 +1,60 @@
#include "Model.h"
namespace New3D {
NodeAttributes::NodeAttributes()
{
currentTexOffsetX = 0;
currentTexOffsetY = 0;
currentTexOffset = 0;
}
bool NodeAttributes::Push()
{
//=============
NodeAttribs na;
//=============
// check for overflow
if (m_vecAttribs.size() >= 128) {
return false;
}
na.texOffset = currentTexOffset;
na.texOffsetX = currentTexOffsetX;
na.texOffsetY = currentTexOffsetY;
m_vecAttribs.push_back(na);
return true;
}
bool NodeAttributes::Pop()
{
if (m_vecAttribs.empty()) {
return false; // check for underflow
}
currentTexOffset = m_vecAttribs.back().texOffset;
currentTexOffsetX = m_vecAttribs.back().texOffsetX;
currentTexOffsetY = m_vecAttribs.back().texOffsetY;
m_vecAttribs.pop_back();
return true;
}
bool NodeAttributes::StackLimit()
{
return m_vecAttribs.size() >= 1024;
}
void NodeAttributes::Reset()
{
currentTexOffset = 0;
currentTexOffsetX = 0;
currentTexOffsetY = 0;
m_vecAttribs.clear();
}
} // New3D

127
Src/Graphics/New3D/Model.h Normal file
View file

@ -0,0 +1,127 @@
#ifndef _MODEL_H_
#define _MODEL_H_
#include "types.h"
#include <vector>
#include <unordered_map>
#include <map>
#include <memory>
#include "Texture.h"
#include "Mat4.h"
namespace New3D {
struct Vertex
{
float pos[3];
float normal[3];
float texcoords[2];
UINT8 color[4]; //rgba
};
struct Poly // our polys are always 3 triangles, unlike the real h/w
{
Vertex p1;
Vertex p2;
Vertex p3;
};
struct R3DPoly
{
Vertex v[4]; // just easier to have them as an array
float faceNormal[3]; // we need this to help work out poly winding, i assume the h/w uses this instead of calculating normals itself
int number = 4;
};
struct Mesh
{
std::shared_ptr<Texture> texture;
// attributes
bool doubleSided = false;
bool textured = false;
bool polyAlpha = false; // specified in the rgba colour
bool textureAlpha = false; // use alpha in texture
bool alphaTest = false; // discard fragment based on alpha (ogl does this with fixed function)
bool lighting = false;
bool testBit = false;
bool clockWise = true; // we need to check if the matrix will change the winding
float fogIntensity = 1.0f;
// texture
bool mirrorU = false;
bool mirrorV = false;
// opengl resources
int vboOffset = 0; // this will be calculated later
int triangleCount = 0;
};
struct SortingMesh : public Mesh // This struct temporarily holds the model data, before it gets copied to the main buffer
{
std::vector<Poly> polys;
};
struct Model
{
std::vector<Mesh> meshes;
//matrices
float modelMat[16];
// misc
int lutIdx = 0;
};
struct Viewport
{
Mat4 projectionMatrix; // projection matrix
float lightingParams[6]; // lighting parameters (see RenderViewport() and vertex shader)
float spotEllipse[4]; // spotlight ellipse (see RenderViewport())
float spotRange[2]; // Z range
float spotColor[3]; // color
float fogParams[5]; // fog parameters (...)
int x, y; // viewport coordinates (scaled and in OpenGL format)
int width, height; // viewport dimensions (scaled for display surface size)
int priority;
};
class NodeAttributes
{
public:
NodeAttributes();
bool Push();
bool Pop();
bool StackLimit();
void Reset();
int currentTexOffsetX;
int currentTexOffsetY;
int currentTexOffset; // raw value
private:
struct NodeAttribs
{
int texOffsetX;
int texOffsetY;
int texOffset;
};
std::vector<NodeAttribs> m_vecAttribs;
};
struct Node
{
Viewport viewport;
std::vector<Model> models;
};
} // New3D
#endif

1020
Src/Graphics/New3D/New3D.cpp Normal file

File diff suppressed because it is too large Load diff

216
Src/Graphics/New3D/New3D.h Normal file
View file

@ -0,0 +1,216 @@
/**
** Supermodel
** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson
**
** This file is part of Supermodel.
**
** Supermodel 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.
**
** Supermodel 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 Supermodel. If not, see <http://www.gnu.org/licenses/>.
**/
/*
* New3D.h
*
* Header file defining the CNew3D class: OpenGL Real3D graphics engine.
*/
#ifndef INCLUDED_NEW3D_H
#define INCLUDED_NEW3D_H
#include "Pkgs/glew.h"
#include "Types.h"
#include "TextureSheet.h"
#include "Graphics/IRender3D.h"
#include "Model.h"
#include "Mat4.h"
#include "R3DShader.h"
#include "VBO.h"
namespace New3D {
class CNew3D : public IRender3D
{
public:
/*
* RenderFrame(void):
*
* Renders the complete scene database. Must be called between BeginFrame() and
* EndFrame(). This function traverses the scene database and builds up display
* lists.
*/
void RenderFrame(void);
/*
* BeginFrame(void):
*
* Prepare to render a new frame. Must be called once per frame prior to
* drawing anything.
*/
void BeginFrame(void);
/*
* EndFrame(void):
*
* Signals the end of rendering for this frame. Must be called last during
* the frame.
*/
void EndFrame(void);
/*
* UploadTextures(x, y, width, height):
*
* Signals that a portion of texture RAM has been updated.
*
* Parameters:
* x X position within texture RAM.
* y Y position within texture RAM.
* width Width of texture data in texels.
* height Height.
*/
void UploadTextures(unsigned x, unsigned y, unsigned width, unsigned height);
/*
* AttachMemory(cullingRAMLoPtr, cullingRAMHiPtr, polyRAMPtr, vromPtr,
* textureRAMPtr):
*
* Attaches RAM and ROM areas. This must be done prior to any rendering
* otherwise the program may crash with an access violation.
*
* Parameters:
* cullingRAMLoPtr Pointer to low culling RAM (4 MB).
* cullingRAMHiPtr Pointer to high culling RAM (1 MB).
* polyRAMPtr Pointer to polygon RAM (4 MB).
* vromPtr Pointer to video ROM (64 MB).
* textureRAMPtr Pointer to texture RAM (8 MB).
*/
void AttachMemory(const UINT32 *cullingRAMLoPtr,
const UINT32 *cullingRAMHiPtr, const UINT32 *polyRAMPtr,
const UINT32 *vromPtr, const UINT16 *textureRAMPtr);
/*
* SetStep(stepID):
*
* Sets the Model 3 hardware stepping, which also determines the Real3D
* functionality. The default is Step 1.0. This should be called prior to
* any other emulation functions and after Init().
*
* Parameters:
* stepID 0x10 for Step 1.0, 0x15 for Step 1.5, 0x20 for Step 2.0,
* or 0x21 for Step 2.1. Anything else defaults to 1.0.
*/
void SetStep(int stepID);
/*
* Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes):
*
* One-time initialization of the context. Must be called before any other
* members (meaning it should be called even before being attached to any
* other objects that want to use it).
*
* External shader files are loaded according to configuration settings.
*
* Parameters:
* xOffset X offset of the viewable area within OpenGL display
* surface, in pixels.
* yOffset Y offset.
* xRes Horizontal resolution of the viewable area.
* yRes Vertical resolution.
* totalXRes Horizontal resolution of the complete display area.
* totalYRes Vertical resolution.
*
* Returns:
* OKAY is successful, otherwise FAILED if a non-recoverable error
* occurred. Any allocated memory will not be freed until the
* destructor is called. Prints own error messages.
*/
bool Init(unsigned xOffset, unsigned yOffset, unsigned xRes, unsigned yRes, unsigned totalXRes, unsigned totalYRes);
/*
* CRender3D(void):
* ~CRender3D(void):
*
* Constructor and destructor.
*/
CNew3D(void);
~CNew3D(void);
private:
/*
* Private Members
*/
// Real3D address translation
const UINT32 *TranslateCullingAddress(UINT32 addr);
const UINT32 *TranslateModelAddress(UINT32 addr);
// Matrix stack
void MultMatrix(UINT32 matrixOffset, Mat4& mat);
void InitMatrixStack(UINT32 matrixBaseAddr, Mat4& mat);
// Scene database traversal
bool DrawModel(UINT32 modelAddr);
void DescendCullingNode(UINT32 addr);
void DescendPointerList(UINT32 addr);
void DescendNodePtr(UINT32 nodeAddr);
void RenderViewport(UINT32 addr, int pri);
// building the scene
void CacheModel(Model *m, const UINT32 *data);
void CopyVertexData(R3DPoly& r3dPoly, std::vector<Poly>& polyArray);
enum class AlphaType{ none, poly, texture };
void RenderScene(int priority, bool alpha);
bool ClockWiseWinding(); // calculate winding with current matrix
/*
* Data
*/
// Stepping
int m_step;
int m_offset; // offset to subtract for words 3 and higher of culling nodes
float m_vertexFactor; // fixed-point conversion factor for vertices
// Memory (passed from outside)
const UINT32 *m_cullingRAMLo; // 4 MB
const UINT32 *m_cullingRAMHi; // 1 MB
const UINT32 *m_polyRAM; // 4 MB
const UINT32 *m_vrom; // 64 MB
const UINT16 *m_textureRAM; // 8 MB
// Resolution and scaling factors (to support resolutions higher than 496x384) and offsets
float m_xRatio, m_yRatio;
unsigned m_xOffs, m_yOffs;
unsigned m_totalXRes, m_totalYRes;
// Real3D Base Matrix Pointer
const float *m_matrixBasePtr;
TextureSheet m_texSheet;
NodeAttributes m_nodeAttribs;
Mat4 m_modelMat; // current modelview matrix
int m_listDepth;
std::vector<Node> m_nodes; // build the scene
std::vector<Poly> m_polyBuffer; // we actually hold the vertex data here, one buffer to send to opengl, instead of 2000+ small ones.
VBO m_vboDynamic; // dynamic data from poly ram, rom polys can go in a different buffer
R3DShader m_r3dShader;
int m_currentVPPriority;
};
} // New3D
#endif // INCLUDED_NEW3D_H

View file

@ -0,0 +1,2 @@
namespace New3D {
} // New3D

View file

@ -0,0 +1,2 @@
namespace New3D {
} // New3D

View file

@ -0,0 +1,320 @@
#include "Supermodel.h"
#include "PolyHeader.h"
namespace New3D {
PolyHeader::PolyHeader()
{
header = NULL;
}
PolyHeader::PolyHeader(UINT32* h)
{
header = h;
}
void PolyHeader::operator = (const UINT32* h)
{
header = (UINT32*)h;
}
UINT32* PolyHeader::StartOfData()
{
return header + 7; // 7 is size of header in bytes, data immediately follows
}
bool PolyHeader::NextPoly()
{
if (LastPoly()) {
return false;
}
header += 7 + (NumVerts() - NumSharedVerts()) * 4;
return true;
}
int PolyHeader::NumPolysTotal()
{
UINT32* start = header; // save start address
int count = 1;
while (NextPoly()) {
count++;
}
header = start; // restore start address
return count;
}
int PolyHeader::NumTrianglesTotal()
{
if (header[6] == 0) {
return 0; // no poly data
}
UINT32* start = header; // save start address
int count = (NumVerts() == 4) ? 2 : 1;
while (NextPoly()) {
count += (NumVerts() == 4) ? 2 : 1;
}
header = start; // restore start address
return count;
}
//
// header 0
//
bool PolyHeader::Specular()
{
return (header[0] & 0x800000000) > 0;
}
int PolyHeader::PolyNumber()
{
return (header[0] & 0x000FFFC00) >> 10; // not all programs pass this, instead they are set to 0
}
bool PolyHeader::Disabled()
{
if ((header[0] & 0x100) && (header[0] & 0x200)) { // assuming these two bits mean z and colour writes are disabled
return true;
}
return false;
}
int PolyHeader::NumVerts()
{
return (header[0] & 0x40) ? 4 : 3;
}
int PolyHeader::NumSharedVerts()
{
int num = 0;
for (int i = 0; i < 4; i++) {
if (SharedVertex(i)) {
num++;
}
}
return num;
}
bool PolyHeader::SharedVertex(int vertex)
{
UINT32 mask = 1 << vertex;
return (header[0] & mask) > 0;
}
//
// header 1
//
void PolyHeader::FaceNormal(float n[3])
{
n[0] = (float)(((INT32)header[1]) >> 8) * (1.0f / 4194304.0f);
n[1] = (float)(((INT32)header[2]) >> 8) * (1.0f / 4194304.0f);
n[2] = (float)(((INT32)header[3]) >> 8) * (1.0f / 4194304.0f);
}
float PolyHeader::UVScale()
{
return (header[1] & 0x40) ? 1.0f : (1.0f / 8.0f);
}
bool PolyHeader::DoubleSided()
{
return (header[1] & 0x10) ? true : false;
}
bool PolyHeader::LastPoly()
{
if ((header[1] & 4) > 0 || header[6] == 0) {
return true;
}
return false;
}
bool PolyHeader::PolyColor()
{
return (header[1] & 2) > 0;
}
//
// header 2
//
bool PolyHeader::TexUMirror()
{
return (header[2] & 2) > 0;
}
bool PolyHeader::TexVMirror()
{
return (header[2] & 1) > 0;
}
//
// header 3
int PolyHeader::TexWidth()
{
return 32 << ((header[3] >> 3) & 7);
}
int PolyHeader::TexHeight()
{
return 32 << ((header[3] >> 0) & 7);
}
//
// header 4
//
void PolyHeader::Color(UINT8& r, UINT8& g, UINT8& b)
{
r = (header[4] >> 24);
g = (header[4] >> 16) & 0xFF;
b = (header[4] >> 8) & 0xFF;
}
int PolyHeader::Page()
{
return (header[4] & 0x40) >> 6;
}
//
// header 5
//
int PolyHeader::X(int textureXOffset)
{
//====
int x;
//====
x = (32 * (((header[4] & 0x1F) << 1) | ((header[5] >> 7) & 1))) + textureXOffset;
x &= 2047;
return x;
}
int PolyHeader::Y(int textureYOffset)
{
//=======
int y;
int page;
//=======
if (Page()) {
page = 1024;
}
else {
page = 0;
}
y = (32 * (header[5] & 0x1F) + page) + textureYOffset; // if we hit 2nd page add 1024 to y coordinate
y &= 2047;
return y;
}
//
// header 6
//
int PolyHeader::TexFormat()
{
return (header[6] >> 7) & 7;
}
bool PolyHeader::TexEnabled()
{
return (header[6] & 0x04000000) > 0;
}
bool PolyHeader::LightEnabled()
{
return !(header[6] & 0x00010000);
}
bool PolyHeader::AlphaTest()
{
return (header[6] & 0x80000000) > 0;
}
UINT8 PolyHeader::Transparency()
{
return (UINT8)(((header[6] >> 18) & 0x1F) * 255.f / 0x1F);
}
bool PolyHeader::FixedShading()
{
return (header[6] & 0x2000000) > 0;
}
UINT8 PolyHeader::ShadeValue()
{
return (UINT8)(((header[6] >> 26) & 0x1F) * (255.f / 0x1F));
}
bool PolyHeader::PolyAlpha()
{
return (header[6] & 0x00800000) == 0;
}
bool PolyHeader::TextureAlpha()
{
return (header[6] & 0x1);
}
bool PolyHeader::StencilPoly()
{
return (header[6] & 1000000) > 0;
}
bool PolyHeader::Luminous()
{
return (header[6] & 0x00010000) > 0;
}
float PolyHeader::LightModifier()
{
return (float)((header[6] >> 11) & 0x1F) * (1.0f / 31.0f);
}
//
// misc
//
UINT64 PolyHeader::Hash(int textureXOffset, int textureYOffset)
{
UINT64 hash = 0;
hash |= (header[2] & 3); // bits 0-1 uv mirror bits
hash |= ((header[3] >> 0) & 7) << 2; // bits 2-4 tex height
hash |= ((header[3] >> 3) & 7) << 5; // bits 5-7 tex width
hash |= X(textureXOffset) << 8; // bits 8-17 x offset
hash |= Y(textureYOffset) << 18; // bits 18-27 y offset
hash |= TexFormat() << 28; // bits 28-30 tex format
hash |= (UINT64)TexEnabled() << 31; // bits 31 textures enabled
hash |= (UINT64)LightEnabled() << 32; // bits 32 light enabled
hash |= (UINT64)DoubleSided() << 33; // bits 33 double sided
hash |= (UINT64)AlphaTest() << 34; // bits 34 contour processing
hash |= (UINT64)PolyAlpha() << 35; // bits 35 poly alpha processing
hash |= (UINT64)TextureAlpha() << 36; // bits 35 poly alpha processing
//to do add the rest of the states
return hash;
}
} // New3D

View file

@ -0,0 +1,139 @@
#ifndef _POLY_HEADER_H_
#define _POLY_HEADER_H_
namespace New3D {
/*
Polygon Data
0x00:
x------- -------- -------- -------- Specular enable
-xxxxx-- -------- -------- -------- ?
------xx xxxxxxxx xxxxxx-- -------- Polygon number (not always present)
-------- -------- ------xx -------- Possibly disable z and colour writing
-------- -------- -------- -x------ 0 = Triangle, 1 = Quad
-------- -------- -------- ----x--- Vertex 3 shared from previous polygon
-------- -------- -------- -----x-- Vertex 2 shared from previous polygon
-------- -------- -------- ------x- Vertex 1 shared from previous polygon
-------- -------- -------- -------x Vertex 0 shared from previous polygon
-------- -------- -------- x-xx---- ?
0x01:
xxxxxxxx xxxxxxxx xxxxxxxx-------- Polygon normal X coordinate(2.22 fixed point)
-------- -------- -------- -x------ UV scale (0 = 13.3, 1 = 16.0)
-------- -------- -------- ---x---- 1 = Double-sided polygon
-------- -------- -------- -----x-- If set, this is the last polygon
-------- -------- -------- ------x- Poly color, 1 = RGB, 0 = color table
-------- -------- -------- x-x-x--x ?
0x02:
xxxxxxxx xxxxxxxx xxxxxxxx -------- Polygon normal Y coordinate(2.22 fixed point)
-------- -------- -------- ------x- Texture U mirror enable
-------- -------- -------- -------x Texture V mirror enable
-------- -------- -------- xxxxxx-- H/W also supports texture clamp/mirror, so guessing some of these bits must be that
0x03:
xxxxxxxx xxxxxxxx xxxxxxxx -------- Polygon normal Z coordinate(2.22 fixed point)
-------- -------- -------- --xxx--- Texture width(in 8 - pixel tiles)
-------- -------- -------- ---- - xxx Texture height(in 8 - pixel tiles)
0x04:
xxxxxxxx xxxxxxxx xxxxxxxx -------- Color(RGB888)
-------- -------- -------- -x------ Texture page
-------- -------- -------- ---xxxxx Upper 5 bits of texture U coordinate
-------- -------- -------- x------- ?
-------- -------- -------- --x----- ?
0x05 :
xxxxxxxx xxxxxxxx xxxxxxxx -------- Specular color ?
-------- -------- -------- x------- Low bit of texture U coordinate
-------- -------- -------- ---xxxxx Low 5 bits of texture V coordinate
-------- -------- -------- -xx----- ?
0x06:
x------- -------- -------- -------- Alpha testing / contour
-xxxxx-- -------- -------- -------- Fixed shading ?
------x- -------- -------- -------- Enable fixed shading ?
-------x -------- -------- -------- Possible stencil
-------- x------- -------- -------- 1 = disable transparency ?
-------- -xxxxx-- -------- -------- Polygon translucency(0 = fully transparent)
-------- -------x -------- -------- 1 = disable lighting
-------- -------- xxxxx--- -------- Polygon light modifier(Amount that a luminous polygon will burn through fog. Valid range is 0.0 to 1.0. 0.0 is completely fogged; 1.0 has no fog.)
-------- -------- -----x-- -------- Texture enable
-------- -------- ------xx x------- Texture format
-------- -------- -------- -------x Alpha enable ?
-------- ------x - ------- -------- Never seen set ?
-------- -------- -------- -----xx- Always set ?
-------- -------- -------- -xxxx--- ?
*/
class PolyHeader
{
public:
PolyHeader();
PolyHeader(UINT32* h);
void operator =(const UINT32* h);
UINT32* StartOfData();
bool NextPoly();
int NumPolysTotal(); // could be quads or triangles
int NumTrianglesTotal();
//header 0
bool Specular();
int PolyNumber();
bool Disabled(); // z & colour disabled
int NumVerts();
int NumSharedVerts();
bool SharedVertex(int vertex);
//header 1
void FaceNormal(float n[3]);
float UVScale();
bool DoubleSided();
bool LastPoly();
bool PolyColor(); // if false uses LUT from ram
//header 2
bool TexUMirror();
bool TexVMirror();
// header 3
int TexWidth();
int TexHeight();
//header 4
void Color(UINT8& r, UINT8& g, UINT8& b);
int Page();
// header 5
int X(int textureXOffset);
int Y(int textureYOffset);
//header 6
int TexFormat();
bool TexEnabled();
bool LightEnabled();
bool AlphaTest();
UINT8 Transparency(); // 0-255
bool FixedShading();
UINT8 ShadeValue();
bool PolyAlpha();
bool TextureAlpha();
bool StencilPoly();
bool Luminous();
float LightModifier();
// misc
UINT64 Hash(int textureXOffset, int textureYOffset); // make a unique hash for sorting by state
//=============
UINT32* header;
//=============
};
} // New3D
#endif

View file

@ -0,0 +1,263 @@
#include "R3DShader.h"
#include "Graphics/Shader.h"
namespace New3D {
static char *vertexShaderBasic =
// uniforms
"uniform float fogIntensity;\n"
"uniform float fogDensity;\n"
"uniform float fogStart;\n"
//outputs to fragment shader
"varying float fsFogFactor;\n"
"varying float fsSpecularTerm;\n" // specular light term (additive)
"varying float fsViewZ;\n"
"varying vec3 fsViewNormal;\n" // per vertex normal vector
"void main(void)\n"
"{\n"
"vec3 viewVertex;\n"
"viewVertex = vec3(gl_ModelViewMatrix * gl_Vertex);\n"
"fsViewNormal = normalize(gl_NormalMatrix*gl_Normal);\n"
"float z = length(viewVertex);\n"
"fsFogFactor = clamp(1.0 - fogIntensity*(fogStart + z*fogDensity), 0.0, 1.0);\n"
"fsViewZ = -viewVertex.z;\n" // convert Z from GL->Real3D convention (want +Z to be further into screen)
"gl_FrontColor = gl_Color;\n"
"gl_TexCoord[0] = gl_MultiTexCoord0;\n"
"gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
"}\n";
static char *fragmentShaderBasic =
"uniform sampler2D tex;\n"
"uniform int textureEnabled;\n"
"uniform int alphaTest;\n"
"uniform int textureAlpha;\n"
"uniform vec3 fogColour;\n"
"uniform vec4 spotEllipse;\n" // spotlight ellipse position: .x=X position (screen coordinates), .y=Y position, .z=half-width, .w=half-height)
"uniform vec2 spotRange;\n" // spotlight Z range: .x=start (viewspace coordinates), .y=limit
"uniform vec3 spotColor;\n" // spotlight RGB color
"uniform vec3 lighting[2];\n" // lighting state (lighting[0] = sun direction, lighting[1].x,y = diffuse, ambient intensities from 0-1.0)
"uniform int lightEnable;\n" // lighting enabled (1.0) or luminous (0.0), drawn at full intensity
"uniform float shininess;\n" // specular shininess (if >= 0.0) or disable specular lighting (negative)
//interpolated inputs from vertex shader
"varying float fsFogFactor;\n"
"varying float fsSpecularTerm;\n" // specular light term (additive)
"varying float fsViewZ;\n"
"varying vec3 fsViewNormal;\n" // per vertex normal vector
"void main()\n"
"{\n"
"vec4 texData;\n"
"vec4 colData;\n"
"vec4 finalData;\n"
"texData = vec4(1.0, 1.0, 1.0, 1.0);\n"
"if(textureEnabled==1) {\n"
"texData = texture2D( tex, gl_TexCoord[0].st);\n"
"if (alphaTest==1) {\n" // does it make any sense to do this later?
"if (texData.a < (8.0/16.0)) {\n"
"discard;\n"
"}\n"
"}\n"
"if (textureAlpha == 0) {\n"
"texData.a = 1.0;\n"
"}\n"
"}\n"
"colData = gl_Color;\n"
"finalData = texData * colData;\n"
"if (finalData.a < (1.0/16.0)) {\n" // basically chuck out any totally transparent pixels value = 1/16 the smallest transparency level h/w supports
"discard;\n"
"}\n"
"vec3 lightIntensity;\n"
"if (lightEnable==1)\n"
"{\n"
"vec3 sunVector;\n" // sun lighting vector (as reflecting away from vertex)
"float sunFactor;\n" // sun light projection along vertex normal (0.0 to 1.0)
// Real3D -> OpenGL view space convention (TO-DO: do this outside of shader)
"sunVector = lighting[0] * vec3(1.0, -1.0, -1.0);\n"
// Compute diffuse factor for sunlight
"sunFactor = max(dot(sunVector, fsViewNormal), 0.0);\n"
// Total light intensity: sum of all components
"lightIntensity = vec3(sunFactor*lighting[1].x + lighting[1].y);\n"
"lightIntensity = clamp(lightIntensity,0.0,1.0);\n"
"}\n"
"else {\n"
"lightIntensity = vec3(1.0,1.0,1.0);\n"
"}\n"
"finalData.rgb *= lightIntensity;\n"
/*
"vec2 ellipse;\n"
"vec3 lightIntensity;\n"
"float insideSpot;\n"
// Compute spotlight and apply lighting
"ellipse = (gl_FragCoord.xy - spotEllipse.xy) / spotEllipse.zw;\n"
"insideSpot = dot(ellipse, ellipse);\n"
"if ((insideSpot <= 1.0) && (fsViewZ >= spotRange.x) && (fsViewZ<spotRange.y)) {\n"
"lightIntensity = fsLightIntensity + (1.0 - insideSpot)*spotColor;\n"
"}\n"
"else {\n"
"lightIntensity = fsLightIntensity;\n"
"}\n"
"finalData.rgb *= lightIntensity;\n"
"finalData.rgb += vec3(fsSpecularTerm, fsSpecularTerm, fsSpecularTerm);\n"
*/
"finalData.rgb = mix(fogColour, finalData.rgb, fsFogFactor);\n"
"gl_FragColor = finalData;\n"
"}\n";
R3DShader::R3DShader()
{
m_shaderProgram = 0;
m_vertexShader = 0;
m_fragmentShader = 0;
Start(); // reset attributes
}
void R3DShader::Start()
{
m_textured = false;
m_textureAlpha = false; // use alpha in texture
m_alphaTest = false; // discard fragment based on alpha (ogl does this with fixed function)
m_doubleSided = false;
m_dirty = true; // dirty means all the above are dirty, ie first run
}
bool R3DShader::LoadShader(const char* vertexShader, const char* fragmentShader)
{
const char* vShader;
const char* fShader;
bool success;
if (vertexShader) {
vShader = vertexShader;
}
else {
vShader = vertexShaderBasic;
}
if (fragmentShader) {
fShader = fragmentShader;
}
else {
fShader = fragmentShaderBasic;
}
success = LoadShaderProgram(&m_shaderProgram, &m_vertexShader, &m_fragmentShader, nullptr, nullptr, vShader, fShader);
m_locTexture = glGetUniformLocation(m_shaderProgram, "tex");
m_locTextureEnabled = glGetUniformLocation(m_shaderProgram, "textureEnabled");
m_locTextureAlpha = glGetUniformLocation(m_shaderProgram, "textureAlpha");
m_locAlphaTest = glGetUniformLocation(m_shaderProgram, "alphaTest");
m_locFogIntensity = glGetUniformLocation(m_shaderProgram, "fogIntensity");
m_locFogDensity = glGetUniformLocation(m_shaderProgram, "fogDensity");
m_locFogStart = glGetUniformLocation(m_shaderProgram, "fogStart");
m_locFogColour = glGetUniformLocation(m_shaderProgram, "fogColour");
m_locLighting = glGetUniformLocation(m_shaderProgram, "lighting");
m_locLightEnable = glGetUniformLocation(m_shaderProgram, "lightEnable");
m_locShininess = glGetUniformLocation(m_shaderProgram, "shininess");
m_locSpotEllipse = glGetUniformLocation(m_shaderProgram, "spotEllipse");
m_locSpotRange = glGetUniformLocation(m_shaderProgram, "spotRange");
m_locSpotColor = glGetUniformLocation(m_shaderProgram, "spotColor");
return success;
}
void R3DShader::SetShader(bool enable)
{
if (enable) {
glUseProgram(m_shaderProgram);
Start();
}
else {
glUseProgram(0);
}
}
void R3DShader::SetMeshUniforms(const Mesh* m)
{
if (m == nullptr) {
return; // sanity check
}
if (m_dirty) {
glUniform1i(m_locTexture, 0);
}
if (m_dirty || m->textured != m_textured) {
glUniform1i(m_locTextureEnabled, m->textured);
m_textured = m->textured;
}
if (m_dirty || m->alphaTest != m_alphaTest) {
glUniform1i(m_locAlphaTest, m->alphaTest);
m_alphaTest = m->alphaTest;
}
if (m_dirty || m->textureAlpha != m_textureAlpha) {
glUniform1i(m_locTextureAlpha, m->textureAlpha);
m_textureAlpha = m->textureAlpha;
}
if (m_dirty || m->fogIntensity != m_fogIntensity) {
glUniform1f(m_locFogIntensity, m->fogIntensity);
m_fogIntensity = m->fogIntensity;
}
glUniform1i(m_locLightEnable, m->lighting);
glUniform1f(m_locShininess, 1);
// technically not uniforms
if (m_dirty || m->doubleSided != m_doubleSided) {
m_doubleSided = m->doubleSided;
if (m_doubleSided) {
glDisable(GL_CULL_FACE);
}
else {
glEnable(GL_CULL_FACE);
}
}
m_dirty = false;
}
void R3DShader::SetViewportUniforms(const Viewport *vp)
{
//didn't bother caching these, they don't get frequently called anyway
glUniform1f(m_locFogDensity, vp->fogParams[3]);
glUniform1f(m_locFogStart, vp->fogParams[4]);
glUniform3fv(m_locFogColour, 1, vp->fogParams);
glUniform3fv(m_locLighting, 2, vp->lightingParams);
glUniform4fv(m_locSpotEllipse, 1, vp->spotEllipse);
glUniform2fv(m_locSpotRange, 1, vp->spotRange);
glUniform3fv(m_locSpotColor, 1, vp->spotColor);
}
} // New3D

View file

@ -0,0 +1,57 @@
#ifndef _R3DSHADER_H_
#define _R3DSHADER_H_
#include "Pkgs/glew.h"
#include "Model.h"
namespace New3D {
class R3DShader
{
public:
R3DShader();
bool LoadShader(const char* vertexShader = nullptr, const char* fragmentShader = nullptr);
void SetMeshUniforms(const Mesh* m);
void SetViewportUniforms(const Viewport *vp);
void Start();
void SetShader(bool enable = true);
private:
GLuint m_shaderProgram;
GLuint m_vertexShader;
GLuint m_fragmentShader;
// mesh uniform data
GLint m_locTexture;
GLint m_locTextureEnabled;
GLint m_locTextureAlpha;
GLint m_locAlphaTest;
bool m_textured;
bool m_textureAlpha; // use alpha in texture
bool m_alphaTest; // discard fragment based on alpha (ogl does this with fixed function)
float m_fogIntensity;
bool m_doubleSided;
bool m_dirty;
// viewport uniform data
GLint m_locFogIntensity;
GLint m_locFogDensity;
GLint m_locFogStart;
GLint m_locFogColour;
// lighting
GLint m_locLighting;
GLint m_locLightEnable;
GLint m_locShininess;
GLint m_locSpotEllipse;
GLint m_locSpotRange;
GLint m_locSpotColor;
};
} // New3D
#endif

View file

@ -0,0 +1,264 @@
#include "Texture.h"
#include <stdio.h>
#include <math.h>
namespace New3D {
Texture::Texture()
{
Reset();
}
Texture::~Texture()
{
DeleteTexture(); // make sure to have valid context before destroying
}
void Texture::DeleteTexture()
{
if (m_textureID) {
glDeleteTextures(1, &m_textureID);
printf("-----> deleting %i %i %i %i %i\n", m_format, m_x, m_y, m_width, m_height);
Reset();
}
}
void Texture::Reset()
{
m_x = 0;
m_y = 0;
m_width = 0;
m_height = 0;
m_format = 0;
m_textureID = 0;
m_mirrorU = false;
m_mirrorV = false;
}
void Texture::BindTexture()
{
glBindTexture(GL_TEXTURE_2D, m_textureID);
}
void Texture::GetCoordinates(UINT16 uIn, UINT16 vIn, float uvScale, float& uOut, float& vOut)
{
uOut = ((uIn*uvScale)+0.0f) / m_width;
vOut = ((vIn*uvScale)+0.0f) / m_height;
}
void Texture::SetWrapMode(bool mirrorU, bool mirrorV)
{
if (mirrorU != m_mirrorU) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mirrorU ? GL_MIRRORED_REPEAT : GL_REPEAT);
m_mirrorU = mirrorU;
}
if (mirrorV != m_mirrorV) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mirrorV ? GL_MIRRORED_REPEAT : GL_REPEAT);
m_mirrorV = mirrorV;
}
}
UINT32 Texture::UploadTexture(const UINT16* src, UINT8* scratch, int format, bool mirrorU, bool mirrorV, int x, int y, int width, int height)
{
int xi, yi, i;
GLubyte texel;
GLubyte c, a;
if (!src || !scratch) {
return 0; // sanity checking
}
DeleteTexture(); // free any existing texture
i = 0;
switch (format)
{
default: // Debug texture, use TEXTURE_DEBUG mask
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
scratch[i++] = 255; // R
scratch[i++] = 0; // G
scratch[i++] = 0; // B
scratch[i++] = 255; // A
}
}
break;
case 0: // T1RGB5 <- correct
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
scratch[i++] = (GLubyte)(((src[yi * 2048 + xi] >> 10) & 0x1F) * 255.f / 0x1F); // R
scratch[i++] = (GLubyte)(((src[yi * 2048 + xi] >> 5) & 0x1F) * 255.f / 0x1F); // G
scratch[i++] = (GLubyte)(((src[yi * 2048 + xi] >> 0) & 0x1F) * 255.f / 0x1F); // B
scratch[i++] = ((src[yi * 2048 + xi] & 0x8000) ? 0 : 255); // T
}
}
break;
case 1: // Interleaved A4L4 (low byte)
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
// Interpret as A4L4
texel = src[yi * 2048 + xi] & 0xFF;
c = (texel & 0xF) * 17;
a = (texel >> 4) * 17;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = a;
}
}
break;
case 2: // luminance alpha texture <- this one is correct
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
texel = src[yi * 2048 + xi] & 0xFF;
c = ((texel >> 4) & 0xF) * 17;
a = (texel & 0xF) * 17;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = a;
}
}
break;
case 3: // Interleaved A4L4 (high byte)
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
texel = src[yi * 2048 + xi] >> 8;
c = (texel & 0xF) * 17;
a = (texel >> 4) * 17;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = a;
}
}
break;
case 4: // 8-bit, L4A4
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
texel = src[yi * 2048 + xi] & 0xFF;
c = ((texel >> 4) & 0xF) * 17; // seems to work better in Lost World (raptor shadows)
a = (texel & 0xF) * 17;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = c;
scratch[i++] = a;
}
}
break;
case 5: // 8-bit grayscale
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
// Interpret as 8-bit grayscale
texel = src[yi * 2048 + xi] & 0xFF;
scratch[i++] = texel;
scratch[i++] = texel;
scratch[i++] = texel;
scratch[i++] = 255;
}
}
break;
case 6: // 8-bit grayscale <-- this one is correct
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
texel = src[yi * 2048 + xi] >> 8;
scratch[i++] = texel;
scratch[i++] = texel;
scratch[i++] = texel;
scratch[i++] = 255;
}
}
break;
case 7: // RGBA4
for (yi = y; yi < (y + height); yi++)
{
for (xi = x; xi < (x + width); xi++)
{
scratch[i++] = ((src[yi * 2048 + xi] >> 12) & 0xF) * 17;// R
scratch[i++] = ((src[yi * 2048 + xi] >> 8) & 0xF) * 17; // G
scratch[i++] = ((src[yi * 2048 + xi] >> 4) & 0xF) * 17; // B
scratch[i++] = ((src[yi * 2048 + xi] >> 0) & 0xF) * 17; // A
}
}
break;
}
//remove debug mask
format &= 7;
GLfloat maxAnistrophy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnistrophy);
if (maxAnistrophy > 8) {
maxAnistrophy = 8.0f; //anymore than 8 can get expensive for little gain
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // rgba is always 4 byte aligned
glActiveTexture(GL_TEXTURE0); // activate correct texture unit
glGenTextures(1, &m_textureID);
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mirrorU ? GL_MIRRORED_REPEAT : GL_REPEAT); //todo this in shaders?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mirrorV ? GL_MIRRORED_REPEAT : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnistrophy);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scratch);
// assuming successful we can copy details
m_x = x;
m_y = y;
m_width = width;
m_height = height;
m_format = format;
m_mirrorU = mirrorU;
m_mirrorV = mirrorV;
printf("create format %i x: %i y: %i width: %i height: %i\n", format, x, y, width, height);
return m_textureID;
}
void Texture::GetDetails(int& x, int&y, int& width, int& height, int& format)
{
x = m_x;
y = m_y;
width = m_width;
height = m_height;
format = m_format;
}
} // New3D

View file

@ -0,0 +1,42 @@
#ifndef _TEXTURE_H_
#define _TEXTURE_H_
#include "Types.h"
#include "Pkgs/glew.h" //arg
namespace New3D {
#define TEXTURE_DEBUG 0x8
#define TEXTURE_DEBUG_MASK 0x7
class Texture
{
public:
Texture();
~Texture();
UINT32 UploadTexture (const UINT16* src, UINT8* scratch, int format, bool mirrorU, bool mirrorV, int x, int y, int width, int height);
void DeleteTexture ();
void BindTexture ();
void GetCoordinates (UINT16 uIn, UINT16 vIn, float uvScale, float& uOut, float& vOut);
void GetDetails (int& x, int&y, int& width, int& height, int& format);
void SetWrapMode (bool mirrorU, bool mirrorV);
private:
void Reset();
int m_x;
int m_y;
int m_width;
int m_height;
int m_format;
bool m_mirrorU;
bool m_mirrorV;
GLuint m_textureID;
};
} // New3D
#endif

View file

@ -0,0 +1,104 @@
#include "TextureSheet.h"
namespace New3D {
TextureSheet::TextureSheet()
{
m_temp.resize(512 * 512 * 4); // temporay buffer for textures
}
int TextureSheet::ToIndex(int x, int y)
{
return (y * 2048) + x;
}
std::shared_ptr<Texture> TextureSheet::BindTexture(const UINT16* src, int format, bool mirrorU, bool mirrorV, int x, int y, int width, int height)
{
//========
int index;
//========
x &= 2047;
y &= 2047;
if ((x + width) > 2048 || (y + height) > 2048) {
return 0;
}
if (width > 512 || height > 512) {
return 0;
}
index = ToIndex(x, y);
if (m_texMap[format&TEXTURE_DEBUG_MASK].count(index) == 0) {
//no textures at this position or format so add it to the map
std::shared_ptr<Texture> t(new Texture());
m_texMap[format&TEXTURE_DEBUG_MASK].insert(std::pair<int, std::shared_ptr<Texture>>(index, t));
t->UploadTexture(src, m_temp.data(), format, mirrorU, mirrorV, x, y, width, height);
return t;
}
else {
//scan for duplicates
//only texture width/height and wrap modes can change here. Since key is based on x/y pos, and each map is a separate format
auto range = m_texMap[format&TEXTURE_DEBUG_MASK].equal_range(index);
for (auto it = range.first; it != range.second; ++it) {
int x2, y2, width2, height2, format2;
it->second->GetDetails(x2, y2, width2, height2, format2);
if (width == width2 && height == height2) {
return it->second;
}
}
std::shared_ptr<Texture> t(new Texture());
m_texMap[format&TEXTURE_DEBUG_MASK].insert(std::pair<int, std::shared_ptr<Texture>>(index, t));
t->UploadTexture(src, m_temp.data(), format, mirrorU, mirrorV, x, y, width, height);
return t;
}
}
void TextureSheet::Release()
{
for (int i = 0; i < 8; i++) {
m_texMap[i].clear();
}
}
void TextureSheet::Invalidate(int x, int y, int width, int height)
{
//==========
int count;
int sWidth; // sample width
int sHeight; // sample height
//==========
// since the smallest sized texture is 32x32 pixels?
// we can invalidate 32x32 tiles over the width/height of the area
sWidth = width / 32;
sHeight = height / 32;
count = sWidth * sHeight;
for (int i = 0; i < count; i++) {
int index = ToIndex(x + ((i%sWidth) * 32), y + ((i / sWidth) * 32));
for (int j = 0; j<8; j++) {
if (m_texMap[j].count(index) > 0) {
m_texMap[j].erase(index);
}
}
}
}
} // New3D

View file

@ -0,0 +1,38 @@
#ifndef _TEXTURE_SHEET_H_
#define _TEXTURE_SHEET_H_
#include "Types.h"
#include <unordered_map>
#include <vector>
#include <memory>
#include "Texture.h"
namespace New3D {
#define REAL_SHEET_WIDTH 2048
#define REAL_SHEET_HEIGHT 2048
class TextureSheet
{
public:
TextureSheet();
std::shared_ptr<Texture> BindTexture (const UINT16* src, int format, bool mirrorU, bool mirrorV, int x, int y, int width, int height);
void Invalidate (int x, int y, int width, int height); // release parts of the memory
void Release (); // release all texture objects and memory
private:
int ToIndex(int x, int y);
std::unordered_multimap<int, std::shared_ptr<Texture>> m_texMap[8];
// the key for the above maps is the x/y position in the 2048x2048 texture
// array of 8 planes for each texture type
std::vector<UINT8> m_temp;
};
} // New3D
#endif

View file

@ -0,0 +1,46 @@
#include "VBO.h"
namespace New3D {
VBO::VBO()
{
m_id = 0;
m_target = 0;
}
void VBO::Create(GLenum target, GLenum usage, GLsizeiptr size, const void* data)
{
glGenBuffers(1, &m_id); // create a vbo
glBindBuffer(target, m_id); // activate vbo id to use
glBufferData(target, size, data, usage); // upload data to video card
m_target = target;
Bind(false); // unbind
}
void VBO::BufferSubData(GLintptr offset, GLsizeiptr size, const GLvoid* data)
{
glBufferSubData(m_target, offset, size, data);
}
void VBO::Destroy()
{
if (m_id) {
glDeleteBuffers(1, &m_id);
m_id = 0;
m_target = 0;
}
}
void VBO::Bind(bool enable)
{
if (enable) {
glBindBuffer(m_target, m_id);
}
else {
glBindBuffer(m_target, 0);
}
}
} // New3D

25
Src/Graphics/New3D/VBO.h Normal file
View file

@ -0,0 +1,25 @@
#ifndef _VBO_H_
#define _VBO_H_
#include "Pkgs/glew.h"
namespace New3D {
class VBO
{
public:
VBO();
void Create (GLenum target, GLenum usage, GLsizeiptr size, const void* data=nullptr);
void BufferSubData (GLintptr offset, GLsizeiptr size, const GLvoid* data);
void Destroy ();
void Bind (bool enable);
private:
GLuint m_id;
GLenum m_target;
};
} // New3D
#endif

237
Src/Graphics/New3D/Vec.cpp Normal file
View file

@ -0,0 +1,237 @@
#include <windows.h>
#include "Vec.h"
#include <Math.h>
namespace New3D {
static float fastSqrt(float number) {
long i;
float x, y;
const float f = 1.5F;
x = number * 0.5F;
y = number;
i = * ( long * ) &y;
i = 0x5f375a86 - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( f - ( x * y * y ) );
y = y * ( f - ( x * y * y ) );
return number * y;
}
static float fastInvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating value
i = 0x5f375a86- (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits back to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return x;
}
void V3::subtract(const Vec3 a, const Vec3 b, Vec3 out) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
}
void V3::subtract(Vec3 a, const Vec3 b) {
a[0] -= b[0];
a[1] -= b[1];
a[2] -= b[2];
}
void V3::add(const Vec3 a, const Vec3 b, Vec3 out) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
}
void V3::add(Vec3 a, const Vec3 b) {
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
}
void V3::divide(Vec3 a, float number) {
multiply(a,1/number);
}
void V3::multiply(Vec3 a, float number) {
a[0] *= number;
a[1] *= number;
a[2] *= number;
}
void V3::multiply(Vec3 a, const Vec3 b) {
a[0] *= b[0];
a[1] *= b[1];
a[2] *= b[2];
}
void V3::multiply(const Vec3 a, const Vec3 b, Vec3 out) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
}
void V3::crossProduct(const Vec3 v1, const Vec3 v2, Vec3 cross) {
cross[0] = v1[1]*v2[2] - v1[2]*v2[1];
cross[1] = v1[2]*v2[0] - v1[0]*v2[2];
cross[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
float V3::dotProduct(const Vec3 v1, const Vec3 v2) {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
}
void V3::copy(const Vec3 in, Vec3 out) {
out[0] = in[0];
out[1] = in[1];
out[2] = in[2];
}
void V3::inverse(Vec3 v) {
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
float V3::length(const Vec3 v) {
//===========
float length;
//===========
length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
length = sqrt(length);
return length;
}
void V3::normalise(Vec3 v) {
//========
float len;
//========
len = v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
len = fastInvSqrt(len);
multiply(v,len);
}
void V3::multiplyAdd(const Vec3 a, float scale, const Vec3 b, Vec3 out) {
out[0] = a[0] + scale*b[0];
out[1] = a[1] + scale*b[1];
out[2] = a[2] + scale*b[2];
}
void V3::reset(Vec3 v) {
v[0] = 0;
v[1] = 0;
v[2] = 0;
}
void V3::set(Vec3 v, float value) {
v[0] = value;
v[1] = value;
v[2] = value;
}
void V3::set(Vec3 v, float x, float y, float z) {
v[0] = x;
v[1] = y;
v[2] = z;
}
void V3::reflect(const Vec3 a, const Vec3 b, Vec3 out) {
//===========
float temp;
Vec3 v;
//===========
//Vect2 = Vect1 - 2 * WallN * (WallN DOT Vect1)
V3::copy(a,v);
temp = V3::dotProduct(a,b) * 2;
V3::multiply(v,temp);
V3::subtract(b,v,out);
}
void V3::createNormal(const Vec3 a, const Vec3 b, const Vec3 c, Vec3 outNormal) {
//======
Vec3 v1;
Vec3 v2;
//======
V3::subtract (a,b,v1);
V3::subtract (c,b,v2);
V3::crossProduct(v1,v2,outNormal);
}
void V3::_max(Vec3 a, const Vec3 compare) {
if(a[0] < compare[0]) a[0] = compare[0];
if(a[1] < compare[1]) a[1] = compare[1];
if(a[2] < compare[2]) a[2] = compare[2];
}
void V3::_min(Vec3 a, const Vec3 compare) {
if(a[0] > compare[0]) a[0] = compare[0];
if(a[1] > compare[1]) a[1] = compare[1];
if(a[2] > compare[2]) a[2] = compare[2];
}
bool V3::cmp(const Vec3 a, float b) {
if(a[0]!=b) return false;
if(a[1]!=b) return false;
if(a[2]!=b) return false;
return true;
}
bool V3::cmp(const Vec3 a, const Vec3 b) {
if(a[0]!=b[0]) return false;
if(a[1]!=b[1]) return false;
if(a[2]!=b[2]) return false;
return true;
}
void V3::clamp(Vec3 a, float _min, float _max) {
if(a[0] < _min) a[0] = _min;
if(a[0] > _max) a[0] = _max;
if(a[1] < _min) a[1] = _min;
if(a[1] > _max) a[1] = _max;
if(a[2] < _min) a[2] = _min;
if(a[2] > _max) a[2] = _max;
}
} // New3D

37
Src/Graphics/New3D/Vec.h Normal file
View file

@ -0,0 +1,37 @@
#ifndef VEC_H
#define VEC_H
namespace New3D {
namespace V3
{
typedef float Vec3[3];
void subtract (const Vec3 a, const Vec3 b, Vec3 out);
void subtract (Vec3 a, const Vec3 b);
void add (const Vec3 a, const Vec3 b, Vec3 out);
void add (Vec3 a, const Vec3 b);
void divide (Vec3 a, float number);
void multiply (Vec3 a, float number);
void multiply (Vec3 a, const Vec3 b);
void multiply (const Vec3 a, const Vec3 b, Vec3 out);
void crossProduct (const Vec3 v1, const Vec3 v2, Vec3 cross);
float dotProduct (const Vec3 v1, const Vec3 v2);
void copy (const Vec3 in, Vec3 out);
void inverse (Vec3 v);
float length (const Vec3 v);
void normalise (Vec3 v);
void multiplyAdd (const Vec3 a, float scale, const Vec3 b, Vec3 out);
void reset (Vec3 v);
void set (Vec3 v, float value);
void set (Vec3 v, float x, float y, float z);
void reflect (const Vec3 a, const Vec3 b, Vec3 out);
void createNormal (const Vec3 a, const Vec3 b, const Vec3 c, Vec3 outNormal); // assume a,b,c are wound clockwise
void _max (Vec3 a, const Vec3 compare);
void _min (Vec3 a, const Vec3 compare);
bool cmp (const Vec3 a, float b);
bool cmp (const Vec3 a, const Vec3 b);
void clamp (Vec3 a, float _min, float _max);
}
} // New3D
#endif

View file

@ -710,7 +710,7 @@ void CRender2D::BeginFrame(void)
// Top layers // Top layers
void CRender2D::EndFrame(void) void CRender2D::EndFrame(void)
{ {
// Display top surface // Display top surface
Setup2D(false, false); Setup2D(false, false);
glEnable(GL_BLEND); glEnable(GL_BLEND);

View file

@ -107,6 +107,7 @@ void CReal3D::LoadState(CBlockFile *SaveState)
} }
SaveState->Read(memoryPool, MEM_POOL_SIZE_RW); SaveState->Read(memoryPool, MEM_POOL_SIZE_RW);
// If multi-threaded, update read-only snapshots too // If multi-threaded, update read-only snapshots too
if (g_Config.gpuMultiThreaded) if (g_Config.gpuMultiThreaded)
UpdateSnapshots(true); UpdateSnapshots(true);
@ -706,7 +707,6 @@ void CReal3D::UploadTexture(UINT32 header, UINT16 *texData)
unsigned x, y, page, width, height, bytesPerTexel, unsigned x, y, page, width, height, bytesPerTexel,
mipYPos, mipWidth, mipHeight, mipNum, mipX, mipY; mipYPos, mipWidth, mipHeight, mipNum, mipX, mipY;
// Position: texture RAM is arranged as 2 2048x1024 texel sheets // Position: texture RAM is arranged as 2 2048x1024 texel sheets
x = 32*(header&0x3F); x = 32*(header&0x3F);
y = 32*((header>>7)&0x1F); y = 32*((header>>7)&0x1F);
@ -855,7 +855,7 @@ void CReal3D::WriteTexturePort(unsigned reg, UINT32 data)
case 0x8: // VROM texture length (also used to trigger uploads) case 0x8: // VROM texture length (also used to trigger uploads)
case 0x14: case 0x14:
UploadTexture(vromTextureHeader,(UINT16 *)&vrom[vromTextureAddr&0xFFFFFF]); UploadTexture(vromTextureHeader,(UINT16 *)&vrom[vromTextureAddr&0xFFFFFF]);
//printf("texture upload: addr=%08X\n", vromTextureAddr); //printf("texture upload: addr=%08X\n", vromTextureAddr);
break; break;
default: default:
DebugLog("Real3D texture port write: %X=%08X\n", reg, data); DebugLog("Real3D texture port write: %X=%08X\n", reg, data);
@ -969,7 +969,7 @@ void CReal3D::Reset(void)
Configuration, Initialization, and Shutdown Configuration, Initialization, and Shutdown
******************************************************************************/ ******************************************************************************/
void CReal3D::AttachRenderer(CRender3D *Render3DPtr) void CReal3D::AttachRenderer(IRender3D *Render3DPtr)
{ {
Render3D = Render3DPtr; Render3D = Render3DPtr;

View file

@ -319,7 +319,7 @@ public:
void Reset(void); void Reset(void);
/* /*
* AttachRenderer(render2DPtr): * AttachRenderer(render3DPtr):
* *
* Attaches a 3D renderer for the Real3D to use. This function will * Attaches a 3D renderer for the Real3D to use. This function will
* immediately pass along the information that a CRender3D object needs to * immediately pass along the information that a CRender3D object needs to
@ -328,7 +328,7 @@ public:
* Parameters: * Parameters:
* Render3DPtr Pointer to a 3D renderer object. * Render3DPtr Pointer to a 3D renderer object.
*/ */
void AttachRenderer(CRender3D *Render3DPtr); void AttachRenderer(IRender3D *Render3DPtr);
/* /*
* SetStep(stepID): * SetStep(stepID):
@ -388,7 +388,7 @@ private:
UINT32 UpdateSnapshot(bool copyWhole, UINT8 *src, UINT8 *dst, unsigned size, UINT8 *dirty); UINT32 UpdateSnapshot(bool copyWhole, UINT8 *src, UINT8 *dst, unsigned size, UINT8 *dirty);
// Renderer attached to the Real3D // Renderer attached to the Real3D
CRender3D *Render3D; IRender3D *Render3D;
// Data passed from Model 3 object // Data passed from Model 3 object
const UINT32 *vrom; // Video ROM const UINT32 *vrom; // Video ROM

View file

@ -1,7 +1,7 @@
/** /**
** Supermodel ** Supermodel
** A Sega Model 3 Arcade Emulator. ** A Sega Model 3 Arcade Emulator.
** Copyright 2011-2012 Bart Trzynadlowski, Nik Henson ** Copyright 2011-2016 Bart Trzynadlowski, Nik Henson
** **
** This file is part of Supermodel. ** This file is part of Supermodel.
** **
@ -28,6 +28,7 @@
* ------------------------- * -------------------------
* - Add UI keys for balance setting? * - Add UI keys for balance setting?
* - 5.1 audio support? * - 5.1 audio support?
* - Stretch video option
* *
* Compile-Time Options * Compile-Time Options
* -------------------- * --------------------
@ -216,10 +217,10 @@ static bool CreateGLScreen(const char *caption, unsigned *xOffsetPtr, unsigned *
return ErrorLog("Unable to initialize SDL video subsystem: %s\n", SDL_GetError()); return ErrorLog("Unable to initialize SDL video subsystem: %s\n", SDL_GetError());
// Important GL attributes // Important GL attributes
SDL_GL_SetAttribute(SDL_GL_RED_SIZE,5); // need at least RGB555 for Model 3 textures SDL_GL_SetAttribute(SDL_GL_RED_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,5); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
// Set vsync // Set vsync
@ -350,6 +351,87 @@ static void PrintGLInfo(bool createScreen, bool infoLog, bool printExtensions)
else printf("\n"); else printf("\n");
} }
static void PrintBAT(unsigned regu, unsigned regl)
{
#ifdef DEBUG
UINT32 batu = ppc_read_spr(regu);
UINT32 batl = ppc_read_spr(regl);
UINT32 bepi = batu >> (31 - 14);
UINT32 bl = (batu >> (31 - 29)) & 0x7ff;
bool vs = batu & 2;
bool vp = batu & 1;
UINT32 brpn = batl >> (31 - 14);
UINT32 wimg = (batl >> (31 - 28)) & 0xf;
UINT32 pp = batl & 3;
UINT32 size = (bl + 1) * 128 * 1024;
UINT32 ea_base = bepi << (31 - 14);
UINT32 ea_limit = ea_base + size - 1;
UINT32 pa_base = brpn << (31 - 14);
UINT32 pa_limit = pa_base + size - 1;
printf("%08X-%08X -> %08X-%08X ", ea_base, ea_limit, pa_base, pa_limit);
printf("%c%c%c%c ", (wimg&8)?'W':'-', (wimg&4)?'I':'-', (wimg&2)?'M':'-', (wimg&1)?'G':'-');
printf("PP=");
if (pp == 0)
printf("NA");
else if (pp == 2)
printf("RW");
else
printf("RO");
printf(" Vs=%d Vp=%d", vs, vp);
#endif
}
static void DumpPPCRegisters(CBus *bus)
{
#ifdef DEBUG
for (int i = 0; i < 32; i += 4)
printf("R%d=%08X\tR%d=%08X\tR%d=%08X\tR%d=%08X\n",
i + 0, ppc_get_gpr(i + 0),
i + 1, ppc_get_gpr(i + 1),
i + 2, ppc_get_gpr(i + 2),
i + 3, ppc_get_gpr(i + 3));
printf("PC =%08X\n", ppc_get_pc());
printf("LR =%08X\n", ppc_get_lr());
printf("DBAT0U=%08X\tIBAT0U=%08X\n", ppc_read_spr(SPR603E_DBAT0U), ppc_read_spr(SPR603E_IBAT0U));
printf("DBAT0L=%08X\tIBAT0L=%08X\n", ppc_read_spr(SPR603E_DBAT0L), ppc_read_spr(SPR603E_IBAT0L));
printf("DBAT1U=%08X\tIBAT1U=%08X\n", ppc_read_spr(SPR603E_DBAT1U), ppc_read_spr(SPR603E_IBAT1U));
printf("DBAT1L=%08X\tIBAT1L=%08X\n", ppc_read_spr(SPR603E_DBAT1L), ppc_read_spr(SPR603E_IBAT1L));
printf("DBAT2U=%08X\tIBAT2U=%08X\n", ppc_read_spr(SPR603E_DBAT2U), ppc_read_spr(SPR603E_IBAT2U));
printf("DBAT2L=%08X\tIBAT2L=%08X\n", ppc_read_spr(SPR603E_DBAT2L), ppc_read_spr(SPR603E_IBAT2L));
printf("DBAT3U=%08X\tIBAT3U=%08X\n", ppc_read_spr(SPR603E_DBAT3U), ppc_read_spr(SPR603E_IBAT3U));
printf("DBAT3L=%08X\tIBAT3L=%08X\n", ppc_read_spr(SPR603E_DBAT3L), ppc_read_spr(SPR603E_IBAT3L));
for (int i = 0; i < 10; i++)
printf("SR%d =%08X VSID=%06X\n", i, ppc_read_sr(i), ppc_read_sr(i) & 0x00ffffff);
for (int i = 10; i < 16; i++)
printf("SR%d=%08X VSID=%06X\n", i, ppc_read_sr(i), ppc_read_sr(i) & 0x00ffffff);
printf("SDR1=%08X\n", ppc_read_spr(SPR603E_SDR1));
printf("\n");
printf("DBAT0: "); PrintBAT(SPR603E_DBAT0U, SPR603E_DBAT0L); printf("\n");
printf("DBAT1: "); PrintBAT(SPR603E_DBAT1U, SPR603E_DBAT1L); printf("\n");
printf("DBAT2: "); PrintBAT(SPR603E_DBAT2U, SPR603E_DBAT2L); printf("\n");
printf("DBAT3: "); PrintBAT(SPR603E_DBAT3U, SPR603E_DBAT3L); printf("\n");
printf("IBAT0: "); PrintBAT(SPR603E_IBAT0U, SPR603E_IBAT0L); printf("\n");
printf("IBAT1: "); PrintBAT(SPR603E_IBAT1U, SPR603E_IBAT1L); printf("\n");
printf("IBAT2: "); PrintBAT(SPR603E_IBAT2U, SPR603E_IBAT2L); printf("\n");
printf("IBAT3: "); PrintBAT(SPR603E_IBAT3U, SPR603E_IBAT3L); printf("\n");
printf("\n");
/*
printf("First PTEG:\n");
UINT32 ptab = ppc_read_spr(SPR603E_SDR1) & 0xffff0000;
for (int i = 0; i < 65536/8; i++)
{
UINT64 pte = bus->Read64(ptab + i*8);
UINT32 vsid = (pte >> (32 + (31 - 24))) & 0x00ffffff;
UINT32 rpn = pte & 0xfffff000;
int wimg = (pte >> 3) & 0xf;
bool v = pte & 0x8000000000000000ULL;
printf(" %d: %016llX V=%d VSID=%06X RPN=%08X WIMG=%c%c%c%c\n", i, pte, v, vsid, rpn, (wimg&8)?'W':'-', (wimg&4)?'I':'-', (wimg&2)?'M':'-', (wimg&1)?'G':'-');
}
*/
#endif
}
/****************************************************************************** /******************************************************************************
Configuration Configuration
@ -433,6 +515,7 @@ static void ApplySettings(CINIFile *INI, const char *section)
#endif // SUPERMODEL_WIN32 #endif // SUPERMODEL_WIN32
// OSD // OSD
INI->Get(section, "New3DEngine", g_Config.new3DEngine);
INI->Get(section, "XResolution", g_Config.xRes); INI->Get(section, "XResolution", g_Config.xRes);
INI->Get(section, "YResolution", g_Config.yRes); INI->Get(section, "YResolution", g_Config.yRes);
INI->Get(section, "FullScreen", g_Config.fullScreen); INI->Get(section, "FullScreen", g_Config.fullScreen);
@ -479,6 +562,7 @@ static void LogConfig(void)
InfoLog("Program settings:"); InfoLog("Program settings:");
// COSDConfig // COSDConfig
InfoLog("\tNew3DEngine = %d", g_Config.new3DEngine);
InfoLog("\tXResolution = %d", g_Config.xRes); InfoLog("\tXResolution = %d", g_Config.xRes);
InfoLog("\tYResolution = %d", g_Config.yRes); InfoLog("\tYResolution = %d", g_Config.yRes);
InfoLog("\tFullScreen = %d", g_Config.fullScreen); InfoLog("\tFullScreen = %d", g_Config.fullScreen);
@ -528,7 +612,7 @@ static void LogConfig(void)
InfoLog("\tForceFeedback = %d", g_Config.forceFeedback); InfoLog("\tForceFeedback = %d", g_Config.forceFeedback);
#endif #endif
// CRender3DConfig // CLegacy3DConfig
InfoLog("\tVertexShader = %s", g_Config.vertexShaderFile.c_str()); InfoLog("\tVertexShader = %s", g_Config.vertexShaderFile.c_str());
InfoLog("\tFragmentShader = %s", g_Config.fragmentShaderFile.c_str()); InfoLog("\tFragmentShader = %s", g_Config.fragmentShaderFile.c_str());
@ -800,8 +884,8 @@ int Supermodel(const char *zipFile, CInputs *Inputs, COutputs *Outputs, CINIFile
CModel3 *Model3 = new CModel3(); CModel3 *Model3 = new CModel3();
#endif // SUPERMODEL_DEBUGGER #endif // SUPERMODEL_DEBUGGER
char baseTitleStr[128], titleStr[128]; char baseTitleStr[128], titleStr[128];
CRender2D *Render2D = new CRender2D(); CRender2D *Render2D;
CRender3D *Render3D = new CRender3D(); IRender3D *Render3D;
unsigned prevFPSTicks, currentFPSTicks, currentTicks, targetTicks, startTicks; unsigned prevFPSTicks, currentFPSTicks, currentTicks, targetTicks, startTicks;
unsigned fpsFramesElapsed, framesElapsed; unsigned fpsFramesElapsed, framesElapsed;
bool gameHasLightguns = false; bool gameHasLightguns = false;
@ -852,7 +936,9 @@ int Supermodel(const char *zipFile, CInputs *Inputs, COutputs *Outputs, CINIFile
if (Outputs != NULL) if (Outputs != NULL)
Model3->AttachOutputs(Outputs); Model3->AttachOutputs(Outputs);
// Initialize the renderer // Initialize the renderers
Render2D = new CRender2D();
Render3D = g_Config.new3DEngine ? ((IRender3D *) new New3D::CNew3D()) : ((IRender3D *) new Legacy3D::CLegacy3D());
if (OKAY != Render2D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes)) if (OKAY != Render2D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes))
goto QuitError; goto QuitError;
if (OKAY != Render3D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes)) if (OKAY != Render3D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes))
@ -985,7 +1071,7 @@ int Supermodel(const char *zipFile, CInputs *Inputs, COutputs *Outputs, CINIFile
// Recreate renderers and attach to the emulator // Recreate renderers and attach to the emulator
Render2D = new CRender2D(); Render2D = new CRender2D();
Render3D = new CRender3D(); Render3D = g_Config.new3DEngine ? ((IRender3D *) new New3D::CNew3D()) : ((IRender3D *) new Legacy3D::CLegacy3D());
if (OKAY != Render2D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes)) if (OKAY != Render2D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes))
goto QuitError; goto QuitError;
if (OKAY != Render3D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes)) if (OKAY != Render3D->Init(xOffset, yOffset, xRes, yRes, totalXRes, totalYRes))
@ -1204,33 +1290,6 @@ int Supermodel(const char *zipFile, CInputs *Inputs, COutputs *Outputs, CINIFile
delete Render2D; delete Render2D;
delete Render3D; delete Render3D;
// Dump PowerPC registers
#ifdef DEBUG
for (int i = 0; i < 32; i += 4)
printf("R%d=%08X\tR%d=%08X\tR%d=%08X\tR%d=%08X\n",
i + 0, ppc_get_gpr(i + 0),
i + 1, ppc_get_gpr(i + 1),
i + 2, ppc_get_gpr(i + 2),
i + 3, ppc_get_gpr(i + 3));
printf("PC =%08X\n", ppc_get_pc());
printf("LR =%08X\n", ppc_get_lr());
/*
printf("DBAT0U=%08X\tIBAT0U=%08X\n", ppc_read_spr(SPR603E_DBAT0U), ppc_read_spr(SPR603E_IBAT0U));
printf("DBAT0L=%08X\tIBAT0L=%08X\n", ppc_read_spr(SPR603E_DBAT0L), ppc_read_spr(SPR603E_IBAT0L));
printf("DBAT1U=%08X\tIBAT1U=%08X\n", ppc_read_spr(SPR603E_DBAT1U), ppc_read_spr(SPR603E_IBAT1U));
printf("DBAT1L=%08X\tIBAT1L=%08X\n", ppc_read_spr(SPR603E_DBAT1L), ppc_read_spr(SPR603E_IBAT1L));
printf("DBAT2U=%08X\tIBAT2U=%08X\n", ppc_read_spr(SPR603E_DBAT2U), ppc_read_spr(SPR603E_IBAT2U));
printf("DBAT2L=%08X\tIBAT2L=%08X\n", ppc_read_spr(SPR603E_DBAT2L), ppc_read_spr(SPR603E_IBAT2L));
printf("DBAT3U=%08X\tIBAT3U=%08X\n", ppc_read_spr(SPR603E_DBAT3U), ppc_read_spr(SPR603E_IBAT3U));
printf("DBAT3L=%08X\tIBAT3L=%08X\n", ppc_read_spr(SPR603E_DBAT3L), ppc_read_spr(SPR603E_IBAT3L));
for (int i = 0; i < 10; i++)
printf("SR%d =%08X\n", i, ppc_read_sr(i));
for (int i = 10; i < 16; i++)
printf("SR%d=%08X\n", i, ppc_read_sr(i));
printf("SDR1=%08X\n", ppc_read_spr(SPR603E_SDR1));
*/
#endif
return 0; return 0;
// Quit with an error // Quit with an error
@ -1316,7 +1375,7 @@ static int DisassembleCROM(const char *zipFile, UINT32 addr, unsigned n)
static void Title(void) static void Title(void)
{ {
puts("Supermodel: A Sega Model 3 Arcade Emulator (Version "SUPERMODEL_VERSION")"); puts("Supermodel: A Sega Model 3 Arcade Emulator (Version "SUPERMODEL_VERSION")");
puts("Copyright (C) 2011-2012 by Bart Trzynadlowski and Nik Henson\n"); puts("Copyright 2011-2016 by Bart Trzynadlowski and Nik Henson\n");
} }
// Print usage information // Print usage information
@ -1326,7 +1385,7 @@ static void Help(void)
puts("ROM set must be a valid ZIP file containing a single game."); puts("ROM set must be a valid ZIP file containing a single game.");
puts(""); puts("");
puts("General Options:"); puts("General Options:");
puts(" -?, -h Print this help text"); puts(" -?, -h, -help, --help Print this help text");
puts(" -print-games List supported games and quit"); puts(" -print-games List supported games and quit");
puts(""); puts("");
puts("Core Options:"); puts("Core Options:");
@ -1346,8 +1405,10 @@ static void Help(void)
puts(" -show-fps Display frame rate in window title bar"); puts(" -show-fps Display frame rate in window title bar");
puts(" -crosshairs=<n> Crosshairs configuration for gun games:"); puts(" -crosshairs=<n> Crosshairs configuration for gun games:");
puts(" 0=none [Default], 1=P1 only, 2=P2 only, 3=P1 & P2"); puts(" 0=none [Default], 1=P1 only, 2=P2 only, 3=P1 & P2");
puts(" -vert-shader=<file> Load 3D vertex shader from external file"); puts(" -legacy3d Legacy 3D engine [Default]");
puts(" -frag-shader=<file> Load 3D fragment shader from external file"); puts(" -new3d New 3D engine by Ian Curtis");
puts(" -vert-shader=<file> Load vertex shader from file (legacy 3D engine)");
puts(" -frag-shader=<file> Load fragment shader from file (legacy 3D engine)");
puts(" -print-gl-info Print OpenGL driver information and quit"); puts(" -print-gl-info Print OpenGL driver information and quit");
puts(""); puts("");
puts("Audio Options:"); puts("Audio Options:");
@ -1371,7 +1432,7 @@ static void Help(void)
puts(""); puts("");
#ifdef SUPERMODEL_DEBUGGER #ifdef SUPERMODEL_DEBUGGER
puts("Debug Options:"); puts("Debug Options:");
puts(" -disable-debugger Completely disable debugger functionality"); puts(" -disable-debugger Completely disable debugger functionality");
puts(" -enter-debugger Enter debugger at start of emulation"); puts(" -enter-debugger Enter debugger at start of emulation");
puts(" -dis=<addr>[,n] Disassemble PowerPC code from CROM"); puts(" -dis=<addr>[,n] Disassemble PowerPC code from CROM");
puts(""); puts("");
@ -1449,7 +1510,17 @@ int main(int argc, char **argv)
CmdLine.SetDefaultSectionName("Global"); // command line settings are global-level CmdLine.SetDefaultSectionName("Global"); // command line settings are global-level
for (i = 1; i < argc; i++) for (i = 1; i < argc; i++)
{ {
if (!strcmp(argv[i],"-h") || !strcmp(argv[i],"-?")) if (!strcmp(argv[i],"-new3d"))
{
n = 1;
CmdLine.Set("Global", "New3DEngine", n);
}
else if (!strcmp(argv[i],"-legacy3d"))
{
n = 0;
CmdLine.Set("Global", "New3DEngine", n);
}
else if (!strcmp(argv[i],"-h") || !strcmp(argv[i],"-?") || !strcmp(argv[i],"-help") || !strcmp(argv[i],"--help"))
{ {
Help(); Help();
return 0; return 0;

View file

@ -1,7 +1,7 @@
/** /**
** Supermodel ** Supermodel
** A Sega Model 3 Arcade Emulator. ** A Sega Model 3 Arcade Emulator.
** Copyright 2011 Bart Trzynadlowski, Nik Henson ** Copyright 2011-2016 Bart Trzynadlowski, Nik Henson
** **
** This file is part of Supermodel. ** This file is part of Supermodel.
** **
@ -43,6 +43,7 @@ using namespace std;
class COSDConfig class COSDConfig
{ {
public: public:
bool new3DEngine; // New 3D engine
unsigned xRes, yRes; // X and Y resolution, in pixels unsigned xRes, yRes; // X and Y resolution, in pixels
bool fullScreen; // Full screen mode (if true) bool fullScreen; // Full screen mode (if true)
bool wideScreen; // Wide screen hack bool wideScreen; // Wide screen hack
@ -135,6 +136,7 @@ public:
// Defaults // Defaults
COSDConfig(void) COSDConfig(void)
{ {
new3DEngine = false;
xRes = 496; xRes = 496;
yRes = 384; yRes = 384;
fullScreen = false; fullScreen = false;