Initial sources

This commit is contained in:
2025-02-28 04:43:17 +03:00
commit d9437c8619
34 changed files with 18207 additions and 0 deletions

208
engine/engine.dsp Normal file
View File

@@ -0,0 +1,208 @@
# Microsoft Developer Studio Project File - Name="engine" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Application" 0x0101
CFG=engine - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "engine.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "engine.mak" CFG="engine - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "engine - Win32 Release" (based on "Win32 (x86) Application")
!MESSAGE "engine - Win32 Debug" (based on "Win32 (x86) Application")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "engine - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /I "./ ../sdk" /I "./" /I "../sdk" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x419 /d "NDEBUG"
# ADD RSC /l 0x419 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib opengl32.lib /nologo /subsystem:windows /machine:I386
!ELSEIF "$(CFG)" == "engine - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "./" /I "../sdk" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /FR /YX /FD /GZ /c
# SUBTRACT CPP /X
# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x419 /d "_DEBUG"
# ADD RSC /l 0x419 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib opengl32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
!ENDIF
# Begin Target
# Name "engine - Win32 Release"
# Name "engine - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\filesystem\file.cpp
# End Source File
# Begin Source File
SOURCE=.\filesystem\filemanager.cpp
# End Source File
# Begin Source File
SOURCE=.\render\gl_shared.cpp
# End Source File
# Begin Source File
SOURCE=.\render\indexbuffer.cpp
# End Source File
# Begin Source File
SOURCE=.\input\inputsystem.cpp
# End Source File
# Begin Source File
SOURCE=.\utils\logger.cpp
# End Source File
# Begin Source File
SOURCE=.\main.cpp
# End Source File
# Begin Source File
SOURCE=.\utils\maths.cpp
# End Source File
# Begin Source File
SOURCE=.\render\render.cpp
# End Source File
# Begin Source File
SOURCE=.\render\render_shared.cpp
# End Source File
# Begin Source File
SOURCE=.\render\renderdevice.cpp
# End Source File
# Begin Source File
SOURCE=.\filesystem\stream.cpp
# End Source File
# Begin Source File
SOURCE=.\render\vertexbuffer.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\filesystem\file.h
# End Source File
# Begin Source File
SOURCE=.\filesystem\filecommon.h
# End Source File
# Begin Source File
SOURCE=.\filesystem\filemanager.h
# End Source File
# Begin Source File
SOURCE=.\render\gl_shared.h
# End Source File
# Begin Source File
SOURCE=.\render\indexbuffer.h
# End Source File
# Begin Source File
SOURCE=.\input\inputsystem.h
# End Source File
# Begin Source File
SOURCE=.\utils\logger.h
# End Source File
# Begin Source File
SOURCE=.\utils\maths.h
# End Source File
# Begin Source File
SOURCE=.\render\render.h
# End Source File
# Begin Source File
SOURCE=.\render\render_shared.h
# End Source File
# Begin Source File
SOURCE=.\render\renderdevice.h
# End Source File
# Begin Source File
SOURCE=.\filesystem\stream.h
# End Source File
# Begin Source File
SOURCE=.\render\vertexbuffer.h
# End Source File
# End Group
# Begin Group "Resource Files"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# End Target
# End Project

29
engine/engine.dsw Normal file
View File

@@ -0,0 +1,29 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "engine"=.\engine.dsp - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -0,0 +1,57 @@
#include <assert.h>
#include "filesystem/file.h"
static const char* s_stdioOpeningMode[] = { "rb", "wb" };
static int s_stdioSeekDir[] = { SEEK_SET, SEEK_CUR, SEEK_END };
File::File(const char* path, FileAccess access)
{
m_filehandle = fopen(path, s_stdioOpeningMode[(int)access]);
assert(m_filehandle && "Unable to open file");
}
File::~File()
{
if (m_filehandle)
{
fclose(m_filehandle);
m_filehandle = NULL;
}
}
void File::Seek(SeekDir seekdir, long offset)
{
fseek(m_filehandle, offset, s_stdioSeekDir[(int)seekdir]);
}
size_t File::Tell()
{
return (size_t)ftell(m_filehandle);
}
bool File::Eof()
{
return !!feof(m_filehandle);
}
size_t File::Read(void* buffer, size_t size)
{
return fread(buffer, 1, size, m_filehandle);
}
size_t File::Write(void const* buffer, size_t size)
{
return fwrite(buffer, size, 1, m_filehandle);
}
void File::ReadStringBuffer(char* buffer, size_t bufferSize)
{
Seek(Seek_End, 0);
size_t length = Tell();
Seek(Seek_Begin, 0);
assert(length <= bufferSize);
Read(buffer, length);
buffer[length] = '\0';
}

28
engine/filesystem/file.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef FILE_H
#define FILE_H
#include "filesystem/filecommon.h"
class File
{
public:
File(const char* path, FileAccess access);
~File();
FILE* GetHandle() { return m_filehandle; }
void Seek(SeekDir seekdir, long offset);
size_t Tell();
bool Eof();
size_t Read(void* buffer, size_t size);
size_t Write(void const* buffer, size_t size);
// helpers
void ReadStringBuffer(char* buffer, size_t bufferSize);
private:
FILE* m_filehandle;
};
#endif

View File

@@ -0,0 +1,21 @@
#ifndef FILECOMMON_H
#define FILECOMMON_H
#include <stdio.h>
static const int kMaxPathLength = 260;
enum FileAccess
{
FileAccess_Read,
FileAccess_Write
};
enum SeekDir
{
Seek_Begin,
Seek_Current,
Seek_End
};
#endif // !FILECOMMON_H

View File

@@ -0,0 +1,316 @@
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <assert.h>
#include "filesystem/stream.h"
#include "filesystem/filemanager.h"
void RecursiveSearch(const std::string& path, std::vector<std::string>& files);
void osResolvePath(char* path);
FileManager* g_fileManager;
FileManager::FileManager()
{
static char currentDirectory[kMaxPathLength];
GetCurrentDirectoryA(kMaxPathLength, currentDirectory);
strcat(currentDirectory, "/");
osResolvePath(currentDirectory);
m_defaultPath = currentDirectory;
}
FileManager::~FileManager()
{
}
void FileManager::SetDefaultPath(const char* path)
{
m_defaultPath = path;
}
bool FileManager::FileExist(const char* filename)
{
#if defined(WIN32) || defined(_WIN32)
char pathBuffer[kMaxPathLength];
if (!strstr(filename, m_defaultPath))
sprintf(pathBuffer, "%s%s", m_defaultPath, filename);
else
strcpy(pathBuffer, filename);
osResolvePath(pathBuffer);
DWORD dwAttrib = GetFileAttributes(pathBuffer);
return (dwAttrib != 0xffffffff && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
#else
FILE* file;
if ((file = fopen(filename, "r")) != NULL)
{
fclose(file);
return true;
}
else
return false;
#endif
}
File* FileManager::OpenFile(const char* path, FileAccess access)
{
char pathBuffer[kMaxPathLength];
if (!strstr(path, m_defaultPath))
sprintf(pathBuffer, "%s%s", m_defaultPath, path);
else
strcpy(pathBuffer, path);
osResolvePath(pathBuffer);
return new File(pathBuffer, access);
}
void FileManager::CloseFile(File*& file)
{
if (file)
{
delete file;
file = NULL;
}
}
StreamBase* FileManager::OpenStream(const char* fname, FileAccess access)
{
char pathBuffer[kMaxPathLength];
if (!strstr(fname, m_defaultPath))
sprintf(pathBuffer, "%s%s", m_defaultPath, fname);
else
strcpy(pathBuffer, fname);
osResolvePath(pathBuffer);
if (!g_fileManager->FileExist( pathBuffer ))
return NULL;
File* file = new File(pathBuffer, access);
return CreateFileStream(file);
}
#if _WIN32
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <time.h>
void GetFileListFromFolder(const char* path, const char* findingPattern, std::vector<std::string>& filesList)
{
struct _finddata_t c_file;
long hFile;
char pathfind[kMaxPathLength];
sprintf(pathfind, "%s/%s", path, findingPattern);
osResolvePath(pathfind);
if ((hFile = _findfirst(pathfind, &c_file)) != -1L) {
do {
char buffer[kMaxPathLength];
sprintf(buffer, "%s/%s", path, c_file.name);
filesList.push_back(buffer);
} while (_findnext(hFile, &c_file) == 0);
_findclose(hFile);
}
}
void osResolvePath(char* path)
{
assert(path);
size_t length = strlen(path);
for (int i = 0; i < (int)length; i++) {
if (path[i] == '/')
path[i] = '\\';
}
}
bool osDirectoryIsExist(const char* path)
{
DWORD ftyp = GetFileAttributesA(path);
if (ftyp == 0xffffffff)
return false;
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true;
return false;
}
void osCreateDirectory(const char* path)
{
CreateDirectoryA(path, NULL);
}
void RecursiveSearch(const std::string& path, std::vector<std::string>& files)
{
struct _finddata_t c_file;
long hFile;
std::string bufferPath;
bufferPath += path;
bufferPath += "/";
bufferPath += "*.*";
if ((hFile = _findfirst(bufferPath.c_str(), &c_file)) != -1L)
{
do {
if (strcmp(c_file.name, ".") == 0 ||
strcmp(c_file.name, "..") == 0 ||
strcmp(c_file.name, ".git") == 0 ||
strcmp(c_file.name, ".gitignore") == 0 ||
strcmp(c_file.name, ".gitignore") == 0 ||
strcmp(c_file.name, ".vs") == 0)
continue;
if (c_file.attrib & _A_SUBDIR)
{
std::string nextPath;
nextPath += path;
nextPath += "/";
nextPath += c_file.name;
RecursiveSearch(nextPath, files);
}
else
{
std::string filepath;
filepath += path;
filepath += "/";
filepath += c_file.name;
files.push_back(filepath);
}
} while (_findnext(hFile, &c_file) == 0);
_findclose(hFile);
}
}
#else
#include <dirent.h>
bool match(const char* pattern, const char* str, int p = 0, int c = 0)
{
if (pattern[p] == '\0')
{
return str[c] == '\0';
}
else if (pattern[p] == '*')
{
for (; str[c] != '\0'; c++)
{
if (match(pattern, str, p + 1, c))
return true;
}
return match(pattern, str, p + 1, c);
}
else if (pattern[p] != '?' && pattern[p] != str[c])
{
return false;
}
else
{
return match(pattern, str, p + 1, c + 1);
}
}
void GetFileListFromFolder(const char* path, const char* findingPattern, std::vector<std::string>& filesList)
{
DIR* dir;
dirent* ent;
if ((dir = opendir(path)) != NULL)
{
while ((ent = readdir(dir)) != NULL)
{
if (match(findingPattern, ent->d_name))
{
char buffer[kMaxPathLength];
snprintf(buffer, kMaxPathLength, "%s/%s", path, ent->d_name);
filesList.push_back(buffer);
}
}
closedir(dir);
}
}
#endif
namespace fs
{
std::string getFileExtension(const std::string& filename)
{
size_t whereIsDot = filename.find_last_of('.');
if (whereIsDot != std::string::npos) {
return filename.substr(whereIsDot);
}
return std::string();
}
std::string getFilePath(const std::string& filename)
{
size_t lastindex = filename.find_last_of("/");
if (lastindex == std::string::npos) {
lastindex = filename.find_last_of("\\");
}
if (lastindex != std::string::npos) {
return filename.substr(0, lastindex);
}
return std::string();
}
std::string getFileNameWithoutExtension(const std::string& filename)
{
size_t lastindex = filename.find_last_of(".");
if (lastindex != std::string::npos) {
return filename.substr(0, lastindex);
}
return filename;
}
std::string getFilenameWithoutPath(const std::string& filename)
{
size_t whereIsSlash = filename.find_last_of('/');
if (whereIsSlash == std::string::npos) {
whereIsSlash = filename.find_last_of('\\');
}
if (whereIsSlash == std::string::npos) {
return filename;
}
std::string string = filename.substr(whereIsSlash + 1);
return string;
}
std::string getFilenameWithoutPathAndExtension(const std::string& filename)
{
size_t whereIsDot = filename.find_last_of('.');
size_t whereIsSlash = filename.find_last_of('/');
if (whereIsSlash == std::string::npos) {
whereIsSlash = filename.find_last_of('\\');
}
if (whereIsDot == std::string::npos && whereIsSlash == std::string::npos) {
return filename;
}
std::string string = filename.substr(whereIsSlash + 1);
whereIsDot = string.find_last_of('.');
string = string.substr(0, whereIsDot);
return string;
}
}

View File

@@ -0,0 +1,51 @@
#ifndef FILEMANAGER_H
#define FILEMANAGER_H
#include <string>
#include <vector>
#include "filesystem/file.h"
class StreamBase;
class FileManager
{
public:
FileManager();
~FileManager();
void SetDefaultPath(const char* path);
const char* GetDefaultPath() { return m_defaultPath; }
bool FileExist(const char* filename);
File* OpenFile(const char* path, FileAccess access);
void CloseFile(File*& file);
StreamBase* OpenStream(const char* fname, FileAccess access);
private:
const char* m_defaultPath;
};
extern FileManager* g_fileManager;
void GetFileListFromFolder(const char* path, const char* findingPattern, std::vector<std::string>& filesList);
void osResolvePath(char* path);
bool osDirectoryIsExist(const char* path);
void osCreateDirectory(const char* path);
// Filename helper
namespace fs
{
std::string getFileExtension(const std::string& filename);
std::string getFilePath(const std::string& filename);
std::string getFileNameWithoutExtension(const std::string& filename);
std::string getFilenameWithoutPath(const std::string& filename);
std::string getFilenameWithoutPathAndExtension(const std::string& filename);
};
#endif // !FILEMANAGER_H

View File

@@ -0,0 +1,61 @@
#include <assert.h>
#include "filesystem/stream.h"
#include "filesystem/filemanager.h"
class FileStream : public StreamBase
{
public:
FileStream(File* file);
~FileStream();
size_t Read(void* buffer, size_t size);
size_t Write(void* buffer, size_t size);
void Seek(SeekDir way, long offset);
size_t Tell();
bool Eof();
private:
File* m_file;
};
FileStream::FileStream(File* file)
{
assert(file && "Cannot open file stream with nullptr file handle.");
m_file = file;
}
FileStream::~FileStream()
{
if (m_file)
g_fileManager->CloseFile(m_file);
}
size_t FileStream::Read(void* buffer, size_t size)
{
return m_file->Read(buffer, size);
}
size_t FileStream::Write(void* buffer, size_t size)
{
return m_file->Write(buffer, size);
}
void FileStream::Seek(SeekDir way, long offset)
{
m_file->Seek(way, offset);
}
size_t FileStream::Tell()
{
return m_file->Tell();
}
bool FileStream::Eof()
{
return m_file->Eof();;
}
StreamBase* CreateFileStream(File* file)
{
return new FileStream(file);
}

View File

@@ -0,0 +1,21 @@
#ifndef STREAM_H
#define STREAM_H
#include "filesystem/filecommon.h"
class StreamBase
{
public:
virtual ~StreamBase() {}
virtual size_t Read(void* buffer, size_t size) = 0;
virtual size_t Write(void* buffer, size_t size) = 0;
virtual void Seek(SeekDir way, long offset) = 0;
virtual size_t Tell() = 0;
virtual bool Eof() = 0;
};
class File;
StreamBase* CreateFileStream(File* file);
#endif // !STREAM_H

View File

@@ -0,0 +1,181 @@
#include <assert.h>
#include <memory.h>
#include "utils/maths.h"
#include "input/inputsystem.h"
const int kMaxKeyboardKeys = 460;
const int kMaxMouseButtons = mouseButton_LastNamed + 1; //5;
const float kKeyThreshold = 0.2f;
IInputSystem* g_inputSystem = NULL;
class InputSystem : public IInputSystem
{
public:
InputSystem();
~InputSystem();
void Init();
void Shutdown();
void Update();
size_t GetMaxScancode() const;
size_t GetMaxMouseButton() const;
char TranslateScancode(scanCode_t scancode) const;
void OnKeyDown(scanCode_t scancode);
void OnKeyUp(scanCode_t scancode);
void OnMouseKeyDown(mouseButton_t mousebutton);
void OnMouseKeyUp(mouseButton_t mousebutton);
void OnMouseMove(int x, int y);
void OnMouseWheel(int x, int y);
bool IsKeyPressed(scanCode_t scancode) const;
bool IsMouseButtonPressed(mouseButton_t mousebutton) const;
void GetMousePosition(int* x, int* y) const;
void GetMouseWheelPosition(int* x, int* y) const;
const char* ActionToString(Action action) const;
void BindKey(Action action, scanCode_t scancode);
bool IsActionActive(Action action) const;
void UnBindKey(Action action);
void UnBindAll();
private:
bool m_keyboardKeys[kMaxKeyboardKeys];
bool m_mouseButtons[kMaxMouseButtons];
Point2 m_mousePosition;
};
InputSystem::InputSystem()
{
memset( m_keyboardKeys, 0, sizeof( m_keyboardKeys ) );
memset( m_mouseButtons, 0, sizeof( m_mouseButtons ) );
memset( &m_mousePosition, 0, sizeof( m_mousePosition ) );
}
InputSystem::~InputSystem()
{
}
void InputSystem::Init()
{
// Nothing to do
}
void InputSystem::Shutdown()
{
// Nothing to do
}
void InputSystem::Update()
{
// TODO: Reset all pressed keys ...
}
size_t InputSystem::GetMaxScancode() const
{
return kMaxKeyboardKeys;
}
size_t InputSystem::GetMaxMouseButton() const
{
return kMaxMouseButtons;
}
char InputSystem::TranslateScancode(scanCode_t scancode) const
{
assert(0 && "Not implemented");
return 0;
}
void InputSystem::OnKeyDown(scanCode_t scancode)
{
assert(scancode <= kMaxKeyboardKeys);
m_keyboardKeys[scancode] = true;
}
void InputSystem::OnKeyUp(scanCode_t scancode)
{
assert(scancode <= kMaxKeyboardKeys);
m_keyboardKeys[scancode] = false;
}
void InputSystem::OnMouseKeyDown(mouseButton_t mousebutton)
{
assert(mousebutton <= kMaxMouseButtons);
m_mouseButtons[mousebutton] = true;
}
void InputSystem::OnMouseKeyUp(mouseButton_t mousebutton)
{
assert(mousebutton <= kMaxMouseButtons);
m_mouseButtons[mousebutton] = false;
}
void InputSystem::OnMouseMove(int x, int y)
{
m_mousePosition.x = (int)x;
m_mousePosition.y = (int)y;
}
void InputSystem::OnMouseWheel(int x, int y)
{
}
bool InputSystem::IsKeyPressed(scanCode_t scancode) const
{
assert(scancode <= KEY_MAX);
return m_keyboardKeys[scancode];
}
bool InputSystem::IsMouseButtonPressed(mouseButton_t mousebutton) const
{
assert(mousebutton <= kMaxMouseButtons);
return m_mouseButtons[mousebutton];
}
void InputSystem::GetMousePosition(int* x, int* y) const
{
if (x) *x = m_mousePosition.x;
if (y) *y = m_mousePosition.y;
}
void InputSystem::GetMouseWheelPosition(int* x, int* y) const
{
}
const char* InputSystem::ActionToString(Action action) const
{
return NULL;
}
void InputSystem::BindKey(Action action, scanCode_t scancode)
{
}
bool InputSystem::IsActionActive(Action action) const
{
return false;
}
void InputSystem::UnBindKey(Action action)
{
}
void InputSystem::UnBindAll()
{
}
IInputSystem* CreateInputSystem(void* wndHandle)
{
return new InputSystem();
}
void DestroyInputSystem(IInputSystem* pInstance)
{
InputSystem* pInput = (InputSystem*)pInstance;
delete pInput;
}

197
engine/input/inputsystem.h Normal file
View File

@@ -0,0 +1,197 @@
#ifndef INPUT_SYSTEM_H
#define INPUT_SYSTEM_H
#include <stddef.h>
enum KeyboardKeys
{
KEY_UNKNOWN = 0,
KEY_SPACE = 32,
KEY_APOSTROPHE = 39, /* ' */
KEY_COMMA = 44, /* , */
KEY_MINUS = 45, /* - */
KEY_PERIOD = 46, /* . */
KEY_SLASH = 47, /* / */
KEY_0 = 48,
KEY_1 = 49,
KEY_2 = 50,
KEY_3 = 51,
KEY_4 = 52,
KEY_5 = 53,
KEY_6 = 54,
KEY_7 = 55,
KEY_8 = 56,
KEY_9 = 57,
KEY_SEMICOLON = 59, /* ; */
KEY_EQUAL = 61, /* = */
KEY_A = 65,
KEY_B = 66,
KEY_C = 67,
KEY_D = 68,
KEY_E = 69,
KEY_F = 70,
KEY_G = 71,
KEY_H = 72,
KEY_I = 73,
KEY_J = 74,
KEY_K = 75,
KEY_L = 76,
KEY_M = 77,
KEY_N = 78,
KEY_O = 79,
KEY_P = 80,
KEY_Q = 81,
KEY_R = 82,
KEY_S = 83,
KEY_T = 84,
KEY_U = 85,
KEY_V = 86,
KEY_W = 87,
KEY_X = 88,
KEY_Y = 89,
KEY_Z = 90,
KEY_LEFT_BRACKET = 91, /* [ */
KEY_BACKSLASH = 92, /* \ */
KEY_RIGHT_BRACKET = 93, /* ] */
KEY_GRAVE_ACCENT = 96, /* ` */
KEY_WORLD_1 = 161, /* non-US #1 */
KEY_WORLD_2 = 162, /* non-US #2 */
KEY_ESCAPE = 256,
KEY_ENTER = 257,
KEY_TAB = 258,
KEY_BACKSPACE = 259,
KEY_INSERT = 260,
KEY_DELETE = 261,
KEY_RIGHT = 262,
KEY_LEFT = 263,
KEY_DOWN = 264,
KEY_UP = 265,
KEY_PAGE_UP = 266,
KEY_PAGE_DOWN = 267,
KEY_HOME = 268,
KEY_END = 269,
KEY_CAPS_LOCK = 280,
KEY_SCROLL_LOCK = 281,
KEY_NUM_LOCK = 282,
KEY_PRINT_SCREEN = 283,
KEY_PAUSE = 284,
KEY_F1 = 290,
KEY_F2 = 291,
KEY_F3 = 292,
KEY_F4 = 293,
KEY_F5 = 294,
KEY_F6 = 295,
KEY_F7 = 296,
KEY_F8 = 297,
KEY_F9 = 298,
KEY_F10 = 299,
KEY_F11 = 300,
KEY_F12 = 301,
KEY_F13 = 302,
KEY_F14 = 303,
KEY_F15 = 304,
KEY_F16 = 305,
KEY_F17 = 306,
KEY_F18 = 307,
KEY_F19 = 308,
KEY_F20 = 309,
KEY_F21 = 310,
KEY_F22 = 311,
KEY_F23 = 312,
KEY_F24 = 313,
KEY_F25 = 314,
KEY_KP_0 = 320,
KEY_KP_1 = 321,
KEY_KP_2 = 322,
KEY_KP_3 = 323,
KEY_KP_4 = 324,
KEY_KP_5 = 325,
KEY_KP_6 = 326,
KEY_KP_7 = 327,
KEY_KP_8 = 328,
KEY_KP_9 = 329,
KEY_KP_DECIMAL = 330,
KEY_KP_DIVIDE = 331,
KEY_KP_MULTIPLY = 332,
KEY_KP_SUBTRACT = 333,
KEY_KP_ADD = 334,
KEY_KP_ENTER = 335,
KEY_KP_EQUAL = 336,
KEY_LEFT_SHIFT = 340,
KEY_LEFT_CONTROL = 341,
KEY_LEFT_ALT = 342,
KEY_LEFT_SUPER = 343,
KEY_RIGHT_SHIFT = 344,
KEY_RIGHT_CONTROL = 345,
KEY_RIGHT_ALT = 346,
KEY_RIGHT_SUPER = 347,
KEY_MENU = 348,
KEY_MAX
};
typedef KeyboardKeys scanCode_t;
typedef byte mouseButton_t;
enum mouseButton_
{
mouseButton_Left = 1,
mouseButton_Middle ,
mouseButton_Right ,
mouseButton_LastNamed = mouseButton_Right
};
#define GetNamelessMouseButtonIndex(buttonNum) mouseButton_t(mouseButton_LastNamed + buttonNum)
enum Action_
{
Action_Forward,
Action_Backward,
Action_Left,
Action_Right,
Action_Fire,
Action_Use,
Action_Max
};
typedef uint Action;
class IInputSystem
{
public:
virtual ~IInputSystem() {}
virtual void Init() = 0;
virtual void Shutdown() = 0;
virtual void Update() = 0;
virtual size_t GetMaxScancode () const = 0;
virtual size_t GetMaxMouseButton() const = 0;
virtual char TranslateScancode(scanCode_t scancode) const = 0;
virtual void OnKeyDown (scanCode_t scancode) = 0;
virtual void OnKeyUp (scanCode_t scancode) = 0;
virtual void OnMouseKeyDown (mouseButton_t mousebutton) = 0;
virtual void OnMouseKeyUp (mouseButton_t mousebutton) = 0;
virtual void OnMouseMove (int x, int y) = 0;
virtual void OnMouseWheel (int x, int y) = 0;
virtual bool IsKeyPressed (scanCode_t scancode) const = 0;
virtual bool IsMouseButtonPressed (mouseButton_t mousebutton) const = 0;
virtual void GetMousePosition (int* x, int* y) const = 0;
virtual void GetMouseWheelPosition (int* x, int* y) const = 0;
virtual const char* ActionToString (Action action) const = 0;
virtual void BindKey (Action action, scanCode_t scancode) = 0;
virtual bool IsActionActive (Action action) const = 0;
virtual void UnBindKey (Action action) = 0;
virtual void UnBindAll () = 0;
};
extern IInputSystem* g_inputSystem;
IInputSystem* CreateInputSystem(void* wndHandle);
void DestroyInputSystem(IInputSystem* pInstance);
#endif // !INPUT_SYSTEM_H

33
engine/main.cpp Normal file
View File

@@ -0,0 +1,33 @@
// Windows Entry Point
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include "filesystem/filemanager.h"
#include "render/render.h"
int WINAPI WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int iCmdShow)
{
// Initialize file manager
g_fileManager = new FileManager();
// Start renderer
R_Init();
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
R_Present();
}
R_Shutdown();
delete g_fileManager; g_fileManager = NULL;
return 0;
}

137
engine/render/gl_shared.cpp Normal file
View File

@@ -0,0 +1,137 @@
#include "utils/logger.h"
#include "render/gl_shared.h"
#include "render/render_shared.h"
const char *GL_ErrorString( int err )
{
switch( err )
{
case GL_STACK_OVERFLOW:
return "GL_STACK_OVERFLOW";
case GL_STACK_UNDERFLOW:
return "GL_STACK_UNDERFLOW";
case GL_INVALID_ENUM:
return "GL_INVALID_ENUM";
case GL_INVALID_VALUE:
return "GL_INVALID_VALUE";
case GL_INVALID_OPERATION:
return "GL_INVALID_OPERATION";
case GL_OUT_OF_MEMORY:
return "GL_OUT_OF_MEMORY";
default:
return "UNKNOWN ERROR";
}
}
void GL_CheckError()
{
GLenum err;
if ( (err = glGetError()) != GL_NO_ERROR )
Msg( "OpenGL Error: %s", GL_ErrorString( err ) );// Msg("OpenGL Error: %s [%s]\n", GL_ErrorString(err), GL_TargetToString(tex->target));
}
void GL_CheckErrorEx( const char* filename, int line )
{
GLenum err;
if ( (err = glGetError()) != GL_NO_ERROR )
Msg( "OpenGL Error: %s at %s:%i", GL_ErrorString( err ), filename, line );// Msg("OpenGL Error: %s [%s]\n", GL_ErrorString(err), GL_TargetToString(tex->target));
}
void GL_CheckErrorFunction(const char* expression, const char* filename, int line)
{
GLenum err;
if ( (err = glGetError()) != GL_NO_ERROR )
Msg( "OpenGL Error: %s (%s) at %s:%i", expression, GL_ErrorString( err ), filename, line );// Msg("OpenGL Error: %s [%s]\n", GL_ErrorString(err), GL_TargetToString(tex->target));
}
uint GetGLBlendFactor(BlendFactor factor)
{
switch (factor)
{
case BF_ZERO:
return GL_ZERO;
case BF_ONE:
return GL_ONE;
case BF_SRC_COLOR:
return GL_SRC_COLOR;
case BF_ONE_MINUS_SRC_COLOR:
return GL_ONE_MINUS_SRC_COLOR;
case BF_DST_COLOR:
return GL_DST_COLOR;
case BF_ONE_MINUS_DST_COLOR:
return GL_ONE_MINUS_DST_COLOR;
case BF_SRC_ALPHA:
return GL_SRC_ALPHA;
case BF_ONE_MINUS_SRC_ALPHA:
return GL_ONE_MINUS_SRC_ALPHA;
case BF_DST_ALPHA:
return GL_DST_ALPHA;
case BF_ONE_MINUS_DST_ALPHA:
return GL_ONE_MINUS_DST_ALPHA;
case BF_CONSTANT_COLOR:
return GL_CONSTANT_COLOR;
case BF_ONE_MINUS_CONSTANT_COLOR:
return GL_ONE_MINUS_CONSTANT_COLOR;
case BF_CONSTANT_ALPHA:
return GL_CONSTANT_ALPHA;
case BF_ONE_MINUS_CONSTANT_ALPHA:
return GL_ONE_MINUS_CONSTANT_ALPHA;
default:
break;
}
return 0;
}
#define LOAD_GL_FUNC(functype, funcname) \
{ \
funcname = (functype)wglGetProcAddress(#funcname); \
if (funcname == NULL) \
LogMsg("Failed to load %s", #funcname); \
}
void GL_Load()
{
// OpenGL 1.5
LOAD_GL_FUNC(PFNGLGENQUERIESPROC, glGenQueries);
LOAD_GL_FUNC(PFNGLDELETEQUERIESPROC, glDeleteQueries);
LOAD_GL_FUNC(PFNGLISQUERYPROC, glIsQuery);
LOAD_GL_FUNC(PFNGLBEGINQUERYPROC, glBeginQuery);
LOAD_GL_FUNC(PFNGLENDQUERYPROC, glEndQuery);
LOAD_GL_FUNC(PFNGLGETQUERYIVPROC, glGetQueryiv);
LOAD_GL_FUNC(PFNGLGETQUERYOBJECTIVPROC, glGetQueryObjectiv);
LOAD_GL_FUNC(PFNGLGETQUERYOBJECTUIVPROC, glGetQueryObjectuiv);
LOAD_GL_FUNC(PFNGLBINDBUFFERPROC, glBindBuffer);
LOAD_GL_FUNC(PFNGLDELETEBUFFERSPROC, glDeleteBuffers);
LOAD_GL_FUNC(PFNGLGENBUFFERSPROC, glGenBuffers);
LOAD_GL_FUNC(PFNGLISBUFFERPROC, glIsBuffer);
LOAD_GL_FUNC(PFNGLBUFFERDATAPROC, glBufferData);
LOAD_GL_FUNC(PFNGLBUFFERSUBDATAPROC, glBufferSubData);
LOAD_GL_FUNC(PFNGLGETBUFFERSUBDATAPROC, glGetBufferSubData);
LOAD_GL_FUNC(PFNGLMAPBUFFERPROC, glMapBuffer);
LOAD_GL_FUNC(PFNGLUNMAPBUFFERPROC, glUnmapBuffer);
LOAD_GL_FUNC(PFNGLGETBUFFERPARAMETERIVPROC, glGetBufferParameteriv);
LOAD_GL_FUNC(PFNGLGETBUFFERPOINTERVPROC, glGetBufferPointerv);
}
PFNGLGENQUERIESPROC glGenQueries = NULL;
PFNGLDELETEQUERIESPROC glDeleteQueries = NULL;
PFNGLISQUERYPROC glIsQuery = NULL;
PFNGLBEGINQUERYPROC glBeginQuery = NULL;
PFNGLENDQUERYPROC glEndQuery = NULL;
PFNGLGETQUERYIVPROC glGetQueryiv = NULL;
PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv = NULL;
PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv = NULL;
PFNGLBINDBUFFERPROC glBindBuffer = NULL;
PFNGLDELETEBUFFERSPROC glDeleteBuffers = NULL;
PFNGLGENBUFFERSPROC glGenBuffers = NULL;
PFNGLISBUFFERPROC glIsBuffer = NULL;
PFNGLBUFFERDATAPROC glBufferData = NULL;
PFNGLBUFFERSUBDATAPROC glBufferSubData = NULL;
PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData = NULL;
PFNGLMAPBUFFERPROC glMapBuffer = NULL;
PFNGLUNMAPBUFFERPROC glUnmapBuffer = NULL;
PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv = NULL;
PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv = NULL;

44
engine/render/gl_shared.h Normal file
View File

@@ -0,0 +1,44 @@
#ifndef GL_SHARED_H
#define GL_SHARED_H
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <gl/gl.h>
#include <gl/glext.h>
void GL_Load();
void GL_CheckError();
void GL_CheckErrorEx(const char* filename, int line);
void GL_CheckErrorFunction(const char* expression, const char* filename, int line);
#define GL_CHECK_ERROR() \
GL_CheckErrorEx(__FILE__, __LINE__)
#define GL_CHECK_FUNC_ERROR(expr) \
expr; \
GL_CheckErrorFunction(#expr, __FILE__, __LINE__)
// OpenGL 1.5 Functional
extern PFNGLGENQUERIESPROC glGenQueries;
extern PFNGLDELETEQUERIESPROC glDeleteQueries;
extern PFNGLISQUERYPROC glIsQuery;
extern PFNGLBEGINQUERYPROC glBeginQuery;
extern PFNGLENDQUERYPROC glEndQuery;
extern PFNGLGETQUERYIVPROC glGetQueryiv;
extern PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv;
extern PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv;
extern PFNGLBINDBUFFERPROC glBindBuffer;
extern PFNGLDELETEBUFFERSPROC glDeleteBuffers;
extern PFNGLGENBUFFERSPROC glGenBuffers;
extern PFNGLISBUFFERPROC glIsBuffer;
extern PFNGLBUFFERDATAPROC glBufferData;
extern PFNGLBUFFERSUBDATAPROC glBufferSubData;
extern PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData;
extern PFNGLMAPBUFFERPROC glMapBuffer;
extern PFNGLUNMAPBUFFERPROC glUnmapBuffer;
extern PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv;
extern PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv;
#endif // !GL_SHARED_H

View File

@@ -0,0 +1,56 @@
#include "render/indexbuffer.h"
#include "render/gl_shared.h"
IndexBuffer::IndexBuffer(void* data, size_t size, bool isStream /*= false*/)
{
glGenBuffers(1, &m_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, isStream ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//if (isStream) {
// Logger::msg("created dynamic index stream ...");
//}
}
IndexBuffer::~IndexBuffer()
{
glDeleteBuffers(1, &m_buffer);
}
void IndexBuffer::Bind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
}
void* IndexBuffer::MapBuffer(BufferAccess access)
{
GLenum accessGl = 0;
switch (access)
{
case BA_READ_ONLY:
accessGl = GL_READ_ONLY;
break;
case BA_WRITE_ONLY:
accessGl = GL_WRITE_ONLY;
break;
case BA_READ_WRITE:
accessGl = GL_READ_WRITE;
break;
}
Bind();
void* ptr = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, accessGl);
GL_CHECK_ERROR();
return ptr;
}
void IndexBuffer::UnmapBuffer()
{
Bind();
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
}

View File

@@ -0,0 +1,26 @@
#ifndef INDEXOBJECT_H
#define INDEXOBJECT_H
#include "render/render_shared.h"
#include "render/gl_shared.h"
class RenderDevice;
class IndexBuffer
{
friend class RenderDevice;
public:
~IndexBuffer();
void* MapBuffer(BufferAccess access);
void UnmapBuffer();
void Bind();
private:
IndexBuffer(void* data, size_t size, bool isStream = false);
GLuint m_buffer;
};
#endif // !INDEXOBJECT_H

133
engine/render/render.cpp Normal file
View File

@@ -0,0 +1,133 @@
#include "render/render.h"
#include "render/renderdevice.h"
#include "render/gl_shared.h"
#include "utils/logger.h"
#define RENDER_CLASS_NAME "RenderClassName"
#define RENDER_WINDOW_NAME "UNEASE Alpha"
HWND hWnd = NULL;
HDC hDC = NULL;
HGLRC hRC = NULL;
LRESULT CALLBACK WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
case WM_KEYDOWN:
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
//input->OnKeyAction((int)wParam, true);
return 0;
case WM_KEYUP:
//input->OnKeyAction((int)wParam, false);
return 0;
default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
}
void R_CreateWindow(int width, int height)
{
static bool wndclassRegistered = false;
if (wndclassRegistered == false)
{
WNDCLASS wc;
/* register window class */
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(0);
wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = RENDER_CLASS_NAME;
RegisterClass (&wc);
wndclassRegistered=true;
}
/* create main window */
hWnd = CreateWindow (
RENDER_CLASS_NAME, RENDER_WINDOW_NAME,
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
0, 0, width, height,
NULL, NULL, GetModuleHandle(0), NULL);
LogMsg("Created window %ix%i", width, height);
// create opengl context
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
hDC = GetDC (hWnd);
/* set the pixel format for the DC */
ZeroMemory (&pfd, sizeof (pfd));
pfd.nSize = sizeof (pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat (hDC, &pfd);
SetPixelFormat (hDC, iFormat, &pfd);
LogMsg("SetPixelFormat successful");
/* create and enable the render context (RC) */
hRC = wglCreateContext( hDC );
LogMsg("wglCreateContext successful");
wglMakeCurrent( hDC, hRC );
}
void R_Init()
{
LogMsg("--- R_Init ---");
// Create window
R_CreateWindow(1024, 768);
// Load OpenGL
GL_Load();
// Create render device
g_renderDevice = new RenderDevice();
}
void R_Shutdown()
{
if (g_renderDevice != NULL)
{
delete g_renderDevice;
g_renderDevice = NULL;
}
}
void R_Present()
{
SwapBuffers(hDC);
}

11
engine/render/render.h Normal file
View File

@@ -0,0 +1,11 @@
#ifndef RENDER_H
#define RENDER_H
#include "render/render_shared.h"
void R_Init();
void R_Shutdown();
void R_Present();
#endif

View File

@@ -0,0 +1,3 @@
#include "render/render_shared.h"
#include "render/gl_shared.h"

View File

@@ -0,0 +1,89 @@
// Shared header for render stuff
#ifndef RENDER_SHARED_H
#define RENDER_SHARED_H
#include "utils/maths.h"
enum BufferAccess
{
BA_READ_ONLY,
BA_WRITE_ONLY,
BA_READ_WRITE
};
// texture format
enum PixelFormat
{
PF_UNKNOWN,
PF_R8G8B8,
PF_R8G8B8A8,
PF_R8G8B8F,
PF_R8G8B8A8F,
// Depth formats
PF_DEPTH32F
};
// Blending functions
enum BlendFactor
{
BF_ZERO,
BF_ONE,
BF_SRC_COLOR,
BF_ONE_MINUS_SRC_COLOR,
BF_DST_COLOR,
BF_ONE_MINUS_DST_COLOR,
BF_SRC_ALPHA,
BF_ONE_MINUS_SRC_ALPHA,
BF_DST_ALPHA,
BF_ONE_MINUS_DST_ALPHA,
BF_CONSTANT_COLOR,
BF_ONE_MINUS_CONSTANT_COLOR,
BF_CONSTANT_ALPHA,
BF_ONE_MINUS_CONSTANT_ALPHA
};
enum TextureSurfaceType
{
TST_COLOR = 1 << 0,
TST_DEPTH = 1 << 1,
TST_STENCIL = 1 << 2,
};
enum PrimitiveType
{
PT_POINTS,
PT_LINES,
PT_TRIANGLES
};
// Base structure for render view (view and projection matrices, viewport settings)
struct View
{
int x, y;
int width, height;
float fov;
};
// Global instance of render view
extern View g_renderView;
// pixel format convertion
uint GetGLPF(PixelFormat pf);
uint GetGLInternalPF(PixelFormat pf);
uint GetGLTypePF(PixelFormat pf);
// Blending factor convertion
uint GetGLBlendFactor(BlendFactor factor);
// Stretched picture vertex
//struct StretchedVertex
//{
// Vec3 position;
// Vec2 texcoord;
//};
//#define MAX_STRETCH_VX 12 * sizeof(StretchedVertex)
#endif

View File

@@ -0,0 +1,192 @@
#include <assert.h>
#include <stdio.h>
// OpenGL
#include "render/gl_shared.h"
// VERTEX AND INDEX OBJECTS
#include "render/vertexbuffer.h"
#include "render/indexbuffer.h"
//#include "render/rendertarget.h"
#include "render/renderdevice.h"
RenderDevice* g_renderDevice = NULL;
RenderDevice::RenderDevice()
{
m_activeVB = NULL;
m_activeIB = NULL;
m_blending = false;
m_activeReadRT = NULL;
m_activeWriteRT = NULL;
}
RenderDevice::~RenderDevice()
{
}
VertexBuffer* RenderDevice::CreateVertexBuffer(void* data, size_t size, bool isStream)
{
return new VertexBuffer(data, size, isStream);
}
IndexBuffer* RenderDevice::CreateIndexBuffer(void* data, size_t size, bool isStream)
{
return new IndexBuffer(data, size, isStream);
}
void RenderDevice::SetVerticesBuffer(VertexBuffer* buffer)
{
if (buffer) {
if (m_activeVB != buffer) {
m_activeVB = buffer;
m_activeVB->Bind();
}
} else { // unbind buffer
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void RenderDevice::SetIndicesBuffer(IndexBuffer* buffer)
{
if (buffer) {
if (m_activeIB != buffer) {
m_activeIB = buffer;
m_activeIB->Bind();
}
} else { // unbind buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
void RenderDevice::SetDepthTest(bool enable)
{
enable ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST);
}
void RenderDevice::SetDepthWrite(bool enable)
{
glDepthMask(enable ? GL_TRUE : GL_FALSE);
}
//void RenderDevice::setVertexFormat(VertexFormat* format)
//{
// assert(format);
//
// if (format->count() == 0) {
// Core::error("RenderDevice::setVertexFormat: failed to set empty vertex format");
// }
//
// size_t appliedOffset = 0;
// for (VertexAttribute* it = format->begin(); it != format->end(); ++it) {
//
// GLenum data_type = get_gl_vertex_attribute_type(it->m_type);
// GLuint data_size = GLuint(get_vertex_attribute_size(it->m_type));
//
// if (appliedOffset > 0)
// glVertexAttribPointer(
// GLuint(it->m_offset),
// GLint(it->m_size),
// data_type,
// GL_FALSE,
// GLsizei(format->size() * data_size),
// (void*)(appliedOffset * sizeof(float))
// );
// else
// glVertexAttribPointer(
// GLuint(it->m_offset),
// GLint(it->m_size),
// data_type,
// GL_FALSE,
// GLsizei(format->size() * data_size),
// (void*)0
// );
//
// glEnableVertexAttribArray(GLuint(it->m_offset));
//
// appliedOffset += it->m_size;
// }
//}
void RenderDevice::SetBlending(bool value)
{
if (m_blending != value) {
m_blending = value;
value ? glEnable(GL_BLEND) : glDisable(GL_BLEND);
}
}
void RenderDevice::SetBlendingFunction(BlendFactor srcFactor, BlendFactor destFactor)
{
// Switch state if one of two blending factors was changed
if (srcFactor != m_srcBlendFactor || destFactor != m_destBlendFactor)
{
m_srcBlendFactor = srcFactor;
m_destBlendFactor = destFactor;
// push to gl state
glBlendFunc(GetGLBlendFactor(srcFactor), GetGLBlendFactor(destFactor));
}
}
void RenderDevice::SetReadRenderTarget(RenderTarget* renderTarget)
{
if (renderTarget) {
if (m_activeReadRT != renderTarget) {
m_activeReadRT = renderTarget;
//glBindFramebuffer(GL_READ_FRAMEBUFFER, renderTarget->m_framebuffer);
}
}
else { // set default rt
// glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
}
void RenderDevice::SetWriteRenderTarget(RenderTarget* renderTarget)
{
if (renderTarget) {
if (m_activeWriteRT != renderTarget) {
m_activeWriteRT = renderTarget;
//glBindFramebuffer(GL_DRAW_FRAMEBUFFER, renderTarget->m_framebuffer);
}
}
else { // set default rt
//glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
}
void RenderDevice::SetViewport(int x, int y, int w, int h)
{
glViewport(x, y, w, h);
}
void RenderDevice::BlitRenderTarget(int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, TextureSurfaceType surfaceType)
{
GLbitfield mask = 0;
if (surfaceType & TST_COLOR)
mask |= GL_COLOR_BUFFER_BIT;
if (surfaceType & TST_DEPTH)
mask |= GL_DEPTH_BUFFER_BIT;
if (surfaceType & TST_STENCIL)
mask |= GL_STENCIL_BUFFER_BIT;
//glBlitFramebuffer(srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, mask, GL_LINEAR);
}
static GLenum g_glPrimitiveMode[PT_TRIANGLES + 1] = {
GL_POINTS,
GL_LINES,
GL_TRIANGLES
};
void RenderDevice::DrawArrays(PrimitiveType primType, uint startOf, size_t verticesCount)
{
glDrawArrays(g_glPrimitiveMode[primType], startOf, GLsizei(verticesCount));
}
void RenderDevice::DrawElements(PrimitiveType primType, size_t elementsCount, bool is16bitIndices)
{
glDrawElements(g_glPrimitiveMode[primType], GLsizei(elementsCount), is16bitIndices ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, NULL);
}

View File

@@ -0,0 +1,59 @@
#ifndef RENDERDEVICE_H
#define RENDERDEVICE_H
#include "render/render_shared.h"
class VertexBuffer;
class IndexBuffer;
class VertexFormat;
class RenderTarget;
class RenderDevice
{
public:
RenderDevice();
~RenderDevice();
VertexBuffer* CreateVertexBuffer(void* data, size_t size, bool isStream = false);
IndexBuffer* CreateIndexBuffer(void* data, size_t size, bool isStream = false);
void SetVerticesBuffer(VertexBuffer* buffer);
void SetIndicesBuffer(IndexBuffer* buffer);
void SetDepthTest(bool enable);
void SetDepthWrite(bool enable);
//void setVertexFormat(VertexFormat* format);
void SetBlending(bool value);
void SetBlendingFunction(BlendFactor srcFactor, BlendFactor destFactor);
void SetReadRenderTarget(RenderTarget* renderTarget);
void SetWriteRenderTarget(RenderTarget* renderTarget);
void SetViewport(int x, int y, int w, int h);
// glBlitFramebuffer
void BlitRenderTarget(int srcX, int srcY, int srcWidth, int srcHeight,
int destX, int destY, int destWidth, int destHeight,
TextureSurfaceType surfaceType);
// drawing
void DrawArrays(PrimitiveType primType, uint startOf, size_t verticesCount);
void DrawElements(PrimitiveType primType, size_t elementsCount, bool is16bitIndices);
private:
VertexBuffer* m_activeVB;
IndexBuffer* m_activeIB;
RenderTarget* m_activeReadRT;
RenderTarget* m_activeWriteRT;
bool m_blending;
BlendFactor m_srcBlendFactor;
BlendFactor m_destBlendFactor;
};
extern RenderDevice* g_renderDevice;
#endif // !RENDERDEVICE_H

View File

@@ -0,0 +1,63 @@
#include <assert.h>
#include "render/rendertarget.h"
#include "render/texturesmanager.h"
#include "render/texture2d.h"
#include "glad/glad.h"
void RenderTarget::setDefaultFramebuffer()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
RenderTarget::RenderTarget()
{
m_framebuffer = -1;
}
RenderTarget::~RenderTarget()
{
m_framebuffer = -1;
}
void RenderTarget::create(const char* name /*= nullptr*/)
{
assert(g_texturesManager);
////////////////////////
// Create FBO
// generate frame buffer
glGenFramebuffers(1, &m_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
}
void RenderTarget::destroy()
{
GLint drawFboId;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &drawFboId);
if (drawFboId == (GLint)m_framebuffer)
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &m_framebuffer);
}
void RenderTarget::finialize()
{
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
assert(0 && "RenderTarget::finialize: failed to finialize framebuffer. Framebuffer is not complete");
}
}
void RenderTarget::attachColorTexture(int slot, Texture2D* texture)
{
assert(texture && "Failed to assing nullptr texture");
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + slot, GL_TEXTURE_2D, texture->GetHandle(), 0);
}
void RenderTarget::attachDepthTexture(Texture2D* texture)
{
assert(texture && "Failed to assing nullptr texture");
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture->GetHandle(), 0);
}

View File

@@ -0,0 +1,33 @@
#ifndef RENDERTARGET_H
#define RENDERTARGET_H
#include <stdint.h>
class Texture2D;
class RenderDevice;
class RenderTarget
{
friend class RenderDevice;
public:
// #TODO: Little hack
static void setDefaultFramebuffer();
public:
RenderTarget();
~RenderTarget();
void create(const char* name = nullptr);
void destroy();
void finialize();
void attachColorTexture(int slot, Texture2D* texture);
void attachDepthTexture(Texture2D* texture);
private:
uint32_t m_framebuffer;
};
#endif

View File

@@ -0,0 +1,58 @@
#include "render/vertexbuffer.h"
#include "render/gl_shared.h"
VertexBuffer::VertexBuffer(void* data, size_t size, bool isStream /*= false*/)
{
glGenBuffers(1, &m_buffer);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
glBufferData(GL_ARRAY_BUFFER, size, data, isStream ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
VertexBuffer::~VertexBuffer()
{
glDeleteBuffers(1, &m_buffer);
}
void VertexBuffer::Bind()
{
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
}
void* VertexBuffer::MapBuffer(BufferAccess access)
{
GLenum accessGl = 0;
switch (access)
{
case BA_READ_ONLY:
accessGl = GL_READ_ONLY;
break;
case BA_WRITE_ONLY:
accessGl = GL_WRITE_ONLY;
break;
case BA_READ_WRITE:
accessGl = GL_READ_WRITE;
break;
}
Bind();
void* ptr = glMapBuffer(GL_ARRAY_BUFFER, accessGl);
GL_CHECK_ERROR();
return ptr;
}
void VertexBuffer::UnmapBuffer()
{
Bind();
glUnmapBuffer(GL_ARRAY_BUFFER);
}
void VertexBuffer::UpdateBuffer(void* data, size_t size)
{
glBufferData(GL_ARRAY_BUFFER, size, data, GL_DYNAMIC_DRAW);
GL_CHECK_ERROR();
}

View File

@@ -0,0 +1,28 @@
#ifndef VERTEXOBJECT_H
#define VERTEXOBJECT_H
#include "render/render_shared.h"
#include "render/gl_shared.h"
class RenderDevice;
class VertexBuffer
{
friend class RenderDevice;
public:
~VertexBuffer();
void Bind();
void* MapBuffer(BufferAccess access);
void UnmapBuffer();
void UpdateBuffer(void* data, size_t size);
private:
VertexBuffer(void* data, size_t size, bool isStream = false);
GLuint m_buffer;
};
#endif // !VERTEXOBJECT_H

96
engine/utils/logger.cpp Normal file
View File

@@ -0,0 +1,96 @@
#include <assert.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <memory.h>
#include <time.h>
#include <Windows.h>
#include "utils/logger.h"
static FILE* s_logFileHandle = NULL;
static DWORD s_logOpenTime = 0;
void logWriteMsg(const char* msg)
{
DWORD dwCurrentTime = GetTickCount() - s_logOpenTime;
static char buffer[1024];
int len = sprintf(buffer, "%02lu:%02lu.%02lu: %s",
dwCurrentTime / 60000, dwCurrentTime / 1000 % 60, dwCurrentTime % 1000 / 10, msg);
if (s_logFileHandle)
{
fwrite(buffer, sizeof(char), len, s_logFileHandle);
fflush(s_logFileHandle);
}
}
static bool s_Initialized = false;
void Logger::Init()
{
s_logFileHandle = fopen("output.txt", "w");
assert(s_logFileHandle);
s_logOpenTime = GetTickCount();
s_Initialized = true;
}
void Logger::Shutdown()
{
if (s_logFileHandle)
{
fclose(s_logFileHandle);
s_logFileHandle = NULL;
}
}
void Logger::LogPrint(const char* msg, ...)
{
static char buffer[2048 * 2];
if (s_Initialized == false)
Logger::Init();
va_list args;
va_start(args, msg);
vsprintf(buffer, msg, args);
va_end(args);
strcat(buffer, "\n");
OutputDebugStringA(buffer);
// write to console
fwrite(buffer, sizeof(char), strlen(buffer), stdout);
logWriteMsg(buffer);
}
void Logger::Error(const char* msg, ...)
{
static char buffer[2048 * 2];
va_list args;
va_start(args, msg);
vsprintf(buffer, msg, args);
va_end(args);
strcat(buffer, "\n");
OutputDebugStringA(buffer);
// write to console
fwrite(buffer, sizeof(char), strlen(buffer), stdout);
logWriteMsg(buffer);
MessageBoxA(NULL, buffer, "Engine Error", MB_OK | MB_ICONERROR);
// if (IsDebuggerPresent())
// DebugBreak();
//else
exit(-1);
}

16
engine/utils/logger.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef LOGGER_H
#define LOGGER_H
class Logger
{
public:
static void Init();
static void Shutdown();
static void LogPrint(const char* msg, ...);
static void Error(const char* msg, ...);
};
#define Msg Logger::LogPrint
#define LogMsg Logger::LogPrint
#endif // !LOGGER_H

2
engine/utils/maths.cpp Normal file
View File

@@ -0,0 +1,2 @@
#include <utils/maths.h>

28
engine/utils/maths.h Normal file
View File

@@ -0,0 +1,28 @@
#ifndef MATHS_H
#define MATHS_H
#include <math.h>
#include <memory.h>
#include <limits.h>
// Type definition
typedef unsigned char uchar;
typedef uchar byte;
typedef short int16;
typedef unsigned short uint16;
typedef unsigned int uint;
// Define M_PI
#ifndef M_PI
#define M_PI 3.14159265358979323846 // pi
#endif // !M_PI
#pragma warning( disable : 4244 )
struct Point2
{
int x;
int y;
};
#endif // !MATHS_H