This commit is contained in:
2025-05-25 23:37:40 +03:00
commit 7f054e2904
79 changed files with 4850 additions and 0 deletions

63
engine/__build.c Normal file
View File

@@ -0,0 +1,63 @@
#include "god/c.h"
#include "god/ld.h"
#include "god/utils.h"
void engine_build(struct build_data b)
{
char* files[] = {
"engine/console.cpp",
"engine/filesystem.cpp",
"engine/server.cpp",
"engine/engine.cpp",
/* rendering */
"engine/vk_videolinux.cpp",
"engine/vk_video.cpp",
"engine/vk_brush.cpp",
/* entities */
"engine/baseentity.cpp",
"engine/level.cpp",
"engine/brush.cpp",
/* server */
"engine/sv_worldspawn.cpp",
"engine/sv_light.cpp",
/* client */
"engine/cl_worldspawn.cpp",
"engine/cl_light.cpp",
NULL,
};
char *rustFiles[] = {
"engine/rust/physics.rs"
};
struct project p = {
.b = &b,
.files = files,
.name = "engine",
};
struct project o = C_compile(p, (struct C_settings){
.generation_flags = C_GENERATION_FLAGS_PIC,
.compile_flags = C_COMPILE_FLAGS_WALL,
.include_dirs = include_dirs,
});
add_item(&o.files, tier1_lib);
char* libs[] = {
"c",
"vulkan",
"X11",
NULL,
};
char* dll = ld_link_project(o, (struct link_settings){
.type = LINK_TYPE_DYNAMIC,
.libs = libs,
});
mv("build/"GAME_NAME"/game/bin",dll);
}

22
engine/baseentity.cpp Normal file
View File

@@ -0,0 +1,22 @@
#include "baseentity.h"
CUtlSelfReferencingVector<CBaseEntity*> g_entities;
CUtlVector<CEntityRegistry*> g_RegisteredEntities;
CEntityRegistry::CEntityRegistry(const char *szName, const char *szClass, EntityRegistryFn pfn) :
m_szName(szName), m_szClass(szClass), m_pfn(pfn), m_pClientfn(0)
{
g_RegisteredEntities.AppendTail(this);
};
C_EntityRegistry::C_EntityRegistry( const char *szName, ClientEntityRegistryFn pfn )
{
for (auto &entity: g_RegisteredEntities)
{
if (!V_strcmp(entity->m_szClass, szName))
{
entity->m_pClientfn = pfn;
}
}
}

84
engine/brush.cpp Normal file
View File

@@ -0,0 +1,84 @@
#include "brush.h"
#include "rendering.h"
#include "tier0/platform.h"
#include "tier1/utlvector.h"
void CBrushEntity::Precache()
{
}
void CBrushEntity::Spawn()
{
};
void CBrushEntity::Destroy()
{
}
void CBrushEntity::Think( float fDelta )
{
};
void C_BrushEntity::Precache()
{
CBrushEntity* pBrushEntity = dynamic_cast<CBrushEntity*>(pEntity);
if (!pBrushEntity)
Plat_FatalErrorFunc("pEntity is not a CBrushEntity");
}
void C_BrushEntity::Spawn()
{
struct Vertex_t
{
float position[3];
float uv[2];
};
pAlbedo = ITextureManager::LoadTexture("gfx/bricks.png");
CBrushEntity* pBrushEntity = (CBrushEntity*)pEntity;
uint32_t numVertices = 15*pBrushEntity->m_mesh.GetSize();
vertexBuffer = IBrushRenderer::CreateVertexBuffer(numVertices*4);
Vertex_t *pTriangles = (Vertex_t*)vertexBuffer->Map();
uint32_t i = 0;
for (auto &triangle: pBrushEntity->m_mesh)
{
pTriangles[i].position[0] = triangle.location[0];
pTriangles[i].position[1] = triangle.location[1];
pTriangles[i].position[2] = triangle.location[2];
pTriangles[i].uv[0] = triangle.uv[0];
pTriangles[i].uv[1] = triangle.uv[1];
pTriangles[i+1].position[0] = triangle.location[3];
pTriangles[i+1].position[1] = triangle.location[4];
pTriangles[i+1].position[2] = triangle.location[5];
pTriangles[i+1].uv[0] = triangle.uv[2];
pTriangles[i+1].uv[1] = triangle.uv[3];
pTriangles[i+2].position[0] = triangle.location[6];
pTriangles[i+2].position[1] = triangle.location[7];
pTriangles[i+2].position[2] = triangle.location[8];
pTriangles[i+2].uv[0] = triangle.uv[4];
pTriangles[i+2].uv[1] = triangle.uv[5];
i+=3;
}
vertexBuffer->Unmap();
mesh = IBrushRenderer::CreateMesh();
mesh->SetVertexBuffer(vertexBuffer);
};
void C_BrushEntity::Destroy()
{
}
void C_BrushEntity::Think( float fDelta )
{
material.m.albedo = ITextureManager::GetTexture(pAlbedo);
IBrushRenderer::SetMaterial(&material);
mesh->Draw();
};

31
engine/cl_light.cpp Normal file
View File

@@ -0,0 +1,31 @@
#include "baseentity.h"
class C_Light: public C_BaseEntity
{
public:
virtual void Precache ( void ) override;
virtual void Spawn( void ) override;
virtual void Destroy( void ) override;
virtual void Think( float fDelta ) override;
};
void C_Light::Precache()
{
}
void C_Light::Spawn()
{
};
void C_Light::Destroy()
{
}
void C_Light::Think( float fDelta )
{
};
LINK_CLIENT_ENTITY(C_Light, CLight)

33
engine/cl_worldspawn.cpp Normal file
View File

@@ -0,0 +1,33 @@
#include "brush.h"
#include "rendering.h"
class C_WorldSpawn: public C_BrushEntity
{
public:
virtual void Precache ( void ) override;
virtual void Spawn( void ) override;
virtual void Destroy( void ) override;
virtual void Think( float fDelta ) override;
};
void C_WorldSpawn::Precache()
{
}
void C_WorldSpawn::Spawn()
{
C_BrushEntity::Spawn();
};
void C_WorldSpawn::Destroy()
{
C_BrushEntity::Destroy();
}
void C_WorldSpawn::Think( float fDelta )
{
C_BrushEntity::Think(fDelta);
};
LINK_CLIENT_ENTITY(C_WorldSpawn, CWorldSpawn)

132
engine/console.cpp Normal file
View File

@@ -0,0 +1,132 @@
#include "console.h"
#include "tier1/utlvector.h"
void IConsole::RegisterVar( ConVar *cvar )
{
}
void IConsole::UnRegisterVar( ConVar *cvar )
{
}
ConVar *IConsole::FindVar( const char *pName )
{
}
void IConsole::RegisterCommand( ConVar *cvar )
{
}
void IConsole::UnRegisterCommand( ConVar *cvar )
{
}
ConCommand *IConsole::FindCommand( const char *pName )
{
}
void IConsole::Execute( void )
{
}
void IConsole::AddCommand( const char *psz )
{
}
void IConsole::InsertCommand( const char *psz )
{
};
ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags )
: ConVar(pName, pDefaultValue, flags, 0)
{
}
ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags,
const char *pHelpString )
: ConVar(pName, pDefaultValue, flags, pHelpString, 0)
{
}
ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags,
const char *pHelpString, ConCommandFn callback )
{
m_szName = CUtlString(pName);
m_flags = flags;
m_szValue = pDefaultValue;
m_fValue = V_atof(pDefaultValue);
m_nValue = V_atoi(pDefaultValue);
IConsole::RegisterVar(this);
}
bool ConVar::IsFlagSet( int flag )
{
}
const char *ConVar::GetHelpText( void )
{
}
bool ConVar::IsRegistered( void )
{
}
const char *ConVar::GetName( void )
{
}
void ConVar::AddFlags( int flags )
{
}
bool ConVar::IsCommand( void )
{
}
void ConVar::InstallChangeCallback( ConCommandFn )
{
}
float ConVar::GetFloat( void )
{
}
int ConVar::GetInt( void )
{
return m_nValue;
}
bool ConVar::GetBool( void )
{
return m_nValue;
}
const char *ConVar::GetString( void )
{
}
void ConVar::SetValue( const char *szValue )
{
if (!szValue)
return;
m_szValue = szValue;
m_fValue = V_atof(szValue);
m_nValue = V_atoi(szValue);
}
void ConVar::SetValue( float fValue )
{
m_fValue = fValue;
m_nValue = fValue;
m_szValue = CUtlString("%f\n",fValue);
}
void ConVar::SetValue( int iValue )
{
m_fValue = iValue;
m_nValue = iValue;
m_szValue = CUtlString("%i\n",iValue);
}

117
engine/engine.cpp Normal file
View File

@@ -0,0 +1,117 @@
#include "tier1/commandline.h"
#include "tier1/utlstring.h"
#include "tier0/lib.h"
#include "console.h"
#include "filesystem.h"
#include "rendering.h"
#include "engine.h"
#include "baseentity.h"
#include "server.h"
#ifdef __linux
#include "signal.h"
#endif
double fPrev = 0;
double fCurrent = 0;
//-----------------------------------------------------------------------------
// Purpose: Engine entry point
//-----------------------------------------------------------------------------
extern "C" void FunnyMain( int argc, char **argv ) {
ICommandLine::CreateCommandLine(argc, argv);
IEngine::Init();
for (;;)
{
fPrev = fCurrent;
fCurrent = Plat_GetTime();
IEngine::Frame(fCurrent-fPrev);
};
/* deinit is handled explicitly */
};
void IEngine_Signal(int sig)
{
printf("Trapped signal %i\n",sig);
switch (sig)
{
case SIGSEGV:
case SIGILL:
case SIGABRT:
printf("Consider running app with debugger attached\n");
Plat_Backtrace();
break;
default:
break;
};
IEngine::Shutdown();
_exit(0);
};
void IEngine::Init()
{
/* trap signals */
#ifdef __linux
signal(SIGHUP, IEngine_Signal);
signal(SIGINT, IEngine_Signal);
signal(SIGQUIT, IEngine_Signal);
signal(SIGILL, IEngine_Signal);
signal(SIGTRAP, IEngine_Signal);
signal(SIGIOT, IEngine_Signal);
signal(SIGBUS, IEngine_Signal);
signal(SIGFPE, IEngine_Signal);
signal(SIGSEGV, IEngine_Signal);
signal(SIGTERM, IEngine_Signal);
#endif
IFileSystem::InitFilesystem();
IVideo::Init();
IServer::LoadGame("funnygame");
};
void IEngine::Frame(float fDelta)
{
IServer::Think(fDelta);
IVideo::Frame(fDelta);
};
void IEngine::Shutdown()
{
};
void IIEngine::PrecacheModel( const char *psz )
{
}
void IIEngine::PrecacheSound( const char *psz )
{
}
CBaseEntity *IIEngine::SpawnEntity( const char *szName )
{
V_printf("%s\n", szName);
for (auto &entity: g_RegisteredEntities)
{
if (!V_strcmp(entity->m_szName, szName))
{
CBaseEntity *pEnt = entity->m_pfn();
pEnt->Spawn();
g_entities.AppendTail(pEnt);
if (entity->m_pClientfn)
{
pEnt->pClientEntity = entity->m_pClientfn();
pEnt->pClientEntity->Spawn();
pEnt->pClientEntity->pEntity = pEnt;
}
return pEnt;
}
}
return 0;
};
void IIEngine::DestroyEntity( CBaseEntity *pEntity )
{
};

210
engine/filesystem.cpp Normal file
View File

@@ -0,0 +1,210 @@
#include "tier0/platform.h"
#include "tier1/commandline.h"
#include "filesystem.h"
#include "unistd.h"
#include <cstdio>
#define BASEDIR "rtt"
#define GAMEDIR "funnygame"
struct PackHeader_t
{
char id[8];
unsigned long long offset;
unsigned long long size;
};
struct PackDirectory_t
{
char name[56];
unsigned long long offset;
unsigned long long size;
};
struct Pack_t
{
FILE* handle;
PackHeader_t header;
CUtlVector<PackDirectory_t> files;
};
struct FileDirectory_t
{
CUtlString path;
Pack_t pack;
};
CUtlString fs_basedir;
CUtlString fs_gamedir;
CUtlSelfReferencingVector<FileDirectory_t> fs_directories;
class CFileSystem: public IFileSystem
{
public:
static void AddDirectory( const char *psz );
static void AddFile( const char *psz );
};
void IFileSystem::InitFilesystem()
{
fs_basedir = ICommandLine::ParamValue("-basedir");
if ( fs_basedir == 0 )
fs_basedir=BASEDIR;
if ( fs_basedir.GetString()[0] == '-' )
fs_basedir=BASEDIR;
fs_gamedir = ICommandLine::ParamValue("-gamedir");
if ( fs_gamedir == 0 )
fs_gamedir=GAMEDIR;
if ( fs_gamedir.GetString()[0] == '-' )
fs_gamedir=GAMEDIR;
AddGameDirectory(fs_gamedir);
}
void CFileSystem::AddFile( const char *psz )
{
CUtlString extension = Plat_GetExtension(psz);
if (extension=="pak")
{
IFileSystem::LoadPackFile(psz);
};
}
void IFileSystem::AddGameDirectory( const char *psz )
{
FileDirectory_t dir = {};
dir.path = psz;
fs_directories.AppendTail(dir);
Plat_ListDirRecursive(psz, CFileSystem::AddFile, 0);
for (auto &dir: fs_directories)
{
V_printf("%s\n",(char*)dir.path);
};
};
bool IFileSystem::LoadPackFile( const char *szFilename )
{
Pack_t pack = {};
PackHeader_t header = {};
unsigned long long nNumFiles = 0;
PackDirectory_t *pDirs = NULL;
FILE* f = V_fopen(szFilename, "r");
if (!f)
Plat_FatalErrorFunc("Failed to open %s",szFilename);
V_fread(&header,1,sizeof(header),f);
// check for rttpacku
if (
header.id[0]!='r' || header.id[1] != 't' || header.id[2] != 't' || header.id[3]!='p' ||
header.id[4]!='a' || header.id[5] != 'c' || header.id[6] != 'k' || header.id[7]!='u'
)
{
Plat_FatalErrorFunc("%s is not a pack file",szFilename);
}
nNumFiles = header.size/sizeof(PackDirectory_t);
pDirs = (PackDirectory_t*)V_malloc(header.size);
V_fseek(f, header.offset, SEEK_SET);
V_fread(pDirs, sizeof(PackDirectory_t), nNumFiles, f);
pack.header = header;
pack.handle = f;
pack.files = CUtlVector<PackDirectory_t>(nNumFiles);
V_memcpy(pack.files.GetData(),pDirs, header.size);
for (auto &i: pack.files)
{
V_printf(" LOADED %s\n",i.name);
}
V_free(pDirs);
nNumFiles = header.size/sizeof(PackDirectory_t);
FileDirectory_t fd = {};
fd.path = szFilename;
fd.pack = pack;
fs_directories.AppendTail(fd);
return true;
}
void IFileSystem::CreatePath( const char *szPath )
{
}
FileHandle_t IFileSystem::Open( const char *szFilename, EFileOptions options )
{
if (options == IFILE_READ)
{
FILE *file = V_fopen(szFilename, "rb");
/* found in fs */
if ( file != NULL )
{
FileHandle_t filehandle = new FileHandle_s;
filehandle->file = file;
filehandle->nPtr = 0;
filehandle->options = IFILE_READ;
/* get size */
V_fseek(file, 0, SEEK_END);
filehandle->nSize = V_ftell(file);
V_fseek(file, 0, SEEK_SET);
return filehandle;
}
/* not found in fs, try to search in packs */
for ( auto &pak: fs_directories )
{
for ( auto &file: pak.pack.files )
{
if ( !strncmp(file.name, szFilename, 56) )
{
FileHandle_t filehandle = new FileHandle_s;
filehandle->file = 0;
filehandle->parent = pak.pack.handle;
filehandle->nSize = file.size;
filehandle->nOffset = file.offset;
filehandle->nPtr = 0;
filehandle->options = IFILE_READ;
return filehandle;
}
}
};
}
return 0;
}
void IFileSystem::Close( FileHandle_t file )
{
/* close only fs files */
if (file->file)
{
V_fclose(file->file);
}
delete file;
}
size_t IFileSystem::Size( FileHandle_t file )
{
return file->nSize;
}
size_t IFileSystem::Read( FileHandle_t file, void *pOutput, size_t nSize)
{
if (file->file)
{
size_t readsize = V_fread(pOutput, 1, nSize, file->file);
file->nPtr+=readsize;
return readsize;
}
size_t readsize = V_fseek(file->parent, file->nOffset, file->nPtr);
V_fread(pOutput, 1, nSize, file->parent);
return readsize;
}
size_t IFileSystem::ReadLine( FileHandle_t file, void *pOutput, size_t nSize)
{
}
size_t IFileSystem::Write( FileHandle_t file, void *pInput, size_t nSize)
{
}

90
engine/level.cpp Normal file
View File

@@ -0,0 +1,90 @@
#include "level.h"
#include "baseentity.h"
#include "brush.h"
#include "engine.h"
#include "filesystem.h"
#include "tier1/utlbuffer.h"
#include "tier1/utlstring.h"
struct MapHeader_t
{
char id[8];
uint32_t nEntities;
};
struct EntityHeader_t
{
uint32_t nTriangles;
uint32_t nProperties;
};
void ILevel::LoadLevel( const char *szLevelName )
{
FileHandle_t handle = IFileSystem::Open(CUtlString("%s.fmap",szLevelName), IFILE_READ);
CUtlBuffer<char> mapdata(IFileSystem::Size(handle));
IFileSystem::Read(handle, mapdata.GetMemory(), mapdata.GetSize());
IFileSystem::Close(handle);
MapHeader_t* pHeader = (MapHeader_t*)mapdata.GetMemory();
char *pData = (char*)mapdata.GetMemory()+sizeof(MapHeader_t);
for ( uint32_t i = 0; i < pHeader->nEntities; i++ )
{
CUtlBuffer<char> szEntityType(V_strlen(pData)+1);
V_strcpy(szEntityType, pData);
pData+=szEntityType.GetSize();
EntityHeader_t* pEntityHeader = (EntityHeader_t*)pData;
pData+=sizeof(EntityHeader_t);
CBaseEntity *pEntity = NULL;
for (auto &entity: g_RegisteredEntities)
{
if (!V_strcmp(entity->m_szName, (char*)szEntityType.GetMemory()))
{
CBaseEntity *pEnt = entity->m_pfn();
g_entities.AppendTail(pEnt);
if (entity->m_pClientfn)
{
pEnt->pClientEntity = entity->m_pClientfn();
pEnt->pClientEntity->pEntity = pEnt;
}
pEntity = pEnt;
break;
}
}
for ( uint32_t j = 0; j<pEntityHeader->nProperties; j++ )
{
CUtlBuffer<char> szParamName(V_strlen(pData)+1);
V_strcpy(szParamName, pData);
pData+=szParamName.GetSize();
CUtlBuffer<char> szParamValue(V_strlen(pData)+1);
V_strcpy(szParamValue, pData);
pData+=szParamValue.GetSize();
};
CBrushEntity *pBrush = dynamic_cast<CBrushEntity*>(pEntity);
if (!pBrush)
{
pEntity->Spawn();
if (pEntity->pClientEntity)
pEntity->pClientEntity->Spawn();
continue;
}
pBrush->m_mesh = CUtlVector<Triangle_t>(0);
V_printf("%i\n",pBrush->m_mesh.GetSize());
for ( uint32_t j = 0; j<pEntityHeader->nTriangles; j++ )
{
Triangle_t triangle = {};
V_memcpy(triangle.location, pData, 4*9);
pData+=4*9;
V_memcpy(triangle.uv, pData, 4*6);
pData+=4*6;
CUtlBuffer<char> szTextureName(V_strlen(pData)+1);
V_strcpy(szTextureName, pData);
pData+=szTextureName.GetSize();
pBrush->m_mesh.AppendTail(triangle);
};
pBrush->Spawn();
if (pBrush->pClientEntity)
pBrush->pClientEntity->Spawn();
};
};

38
engine/server.cpp Normal file
View File

@@ -0,0 +1,38 @@
#include "server.h"
#include "tier1/utlstring.h"
#include "baseentity.h"
#include "console.h"
void *g_serverdll;
void IServer::LoadGame( const char *psz )
{
g_serverdll = Plat_LoadLibrary(CUtlString("%s/bin/libserver.so", psz));
void (*GameLoadfn)() = (void(*)())Plat_GetProc(g_serverdll, "IGame_Load");
if (!GameLoadfn)
Plat_FatalErrorFunc("IGame_Load not found in libserver.so\n");
GameLoadfn();
};
ConVar g_tickrate("tickrate","64",FCVAR_PROTECTED);
float g_fAccumulator = 0;
void IServer::Think( float fDelta )
{
g_fAccumulator += fDelta;
float fTickrate = 1.0/g_tickrate.GetInt();
/* tickrate */
while(g_fAccumulator>=fTickrate)
{
for (auto &entity: g_entities)
{
entity->Think(fTickrate);
g_fAccumulator-=fTickrate;
}
}
for (auto &entity: g_entities)
{
if (entity->pClientEntity)
entity->pClientEntity->Think(fDelta);
}
};

31
engine/sv_light.cpp Normal file
View File

@@ -0,0 +1,31 @@
#include "baseentity.h"
class CLight: public CBaseEntity
{
public:
virtual void Precache ( void ) override;
virtual void Spawn( void ) override;
virtual void Destroy( void ) override;
virtual void Think( float fDelta ) override;
};
void CLight::Precache()
{
}
void CLight::Spawn()
{
};
void CLight::Destroy()
{
}
void CLight::Think( float fDelta )
{
};
DECLARE_ENTITY(light, CLight)

32
engine/sv_worldspawn.cpp Normal file
View File

@@ -0,0 +1,32 @@
#include "brush.h"
class CWorldSpawn: public CBrushEntity
{
public:
virtual void Precache ( void ) override;
virtual void Spawn( void ) override;
virtual void Destroy( void ) override;
virtual void Think( float fDelta ) override;
};
void CWorldSpawn::Precache()
{
}
void CWorldSpawn::Spawn()
{
};
void CWorldSpawn::Destroy()
{
}
void CWorldSpawn::Think( float fDelta )
{
};
DECLARE_ENTITY(worldspawn, CWorldSpawn)

406
engine/vk_brush.cpp Normal file
View File

@@ -0,0 +1,406 @@
#include "filesystem.h"
#include "rendering.h"
#include "tier1/utlvector.h"
#include "vk_helper.h"
#include "vulkan/vulkan_core.h"
extern VkSampler g_invalidTextureSampler;
abstract_class CBrush: public IBrush
{
public:
void SetPosition( vec3 position ) override;
void SetRotationEuler( vec3 angle ) override;
void SetRotationQuat( vec4 quaternion) override;
void SetMatrix( mat3 matrix ) override;
void SetScale( vec3 scale ) override;
void SetVertexBuffer( IVertexBuffer *pBuffer ) override;
void SetIndexBuffer( IIndexBuffer *pBuffer ) override;
void Draw() override;
IMaterial *m_pMaterial = NULL;
CVertexBuffer *m_pVertexBuffer = NULL;
CIndexBuffer *m_pIndexBuffer = NULL;
};
void CBrush::SetPosition( vec3 position )
{
}
void CBrush::SetRotationEuler( vec3 angle )
{
}
void CBrush::SetRotationQuat( vec4 quaternion)
{
}
void CBrush::SetMatrix( mat3 matrix )
{
}
void CBrush::SetScale( vec3 scale )
{
}
void CBrush::SetVertexBuffer( IVertexBuffer *pBuffer )
{
m_pVertexBuffer = (CVertexBuffer*)pBuffer;
}
void CBrush::SetIndexBuffer( IIndexBuffer *pBuffer )
{
m_pIndexBuffer = (CIndexBuffer*)pBuffer;
}
CUtlVector<CBrush> g_drawnMeshes;
IMaterial *g_pDefaultMaterial;
IMaterial *g_pCurrentMaterial;
void CBrush::Draw()
{
g_drawnMeshes.AppendTail(*this);
}
abstract_class CMaterial: public IMaterial
{
};
extern CUtlVector<ITexture*> g_textures;
vk_tripipeline_t g_brushPipeline = {};
vk_image2d_t meshdepth;
vk_image2d_t meshcolor;
extern bool g_bConfigNotify;
VkDescriptorPool g_brushDescriptorPool;
VkDescriptorSet g_brushDescriptorSet;
vk_buffer_t g_brushProjection;
struct MeshProjection {
mat4 projection;
} *g_brushProject;
VkSampler g_brushSampler;
void IBrushRenderer::Init()
{
CUtlVector<vk_shader_t> shaders(2);
for (auto &shader: shaders)
{
shader.m_shaderModule = NULL;
}
shaders[0].Create("gfx/brush_vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaders[1].Create("gfx/brush_frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
CUtlVector<VkDescriptorSetLayoutBinding> bindings(2);
bindings[0] = {};
bindings[0].binding = 0;
bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
bindings[0].descriptorCount = 1;
bindings[1] = {};
bindings[1].binding = 1;
bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
bindings[1].descriptorCount = 1024;
g_brushPipeline.Create(shaders, bindings, 4);
shaders[1].Destroy();
shaders[0].Destroy();
meshdepth.Create(1280, 720, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
meshcolor.Create(1280, 720, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
CUtlVector<VkDescriptorPoolSize> pools;
for (auto &binding: bindings)
{
VkDescriptorPoolSize dps = {};
dps.type = binding.descriptorType;
dps.descriptorCount = binding.descriptorCount;
pools.AppendTail(dps);
}
VkDescriptorPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = pools.GetSize();
poolInfo.pPoolSizes = pools.GetData();
poolInfo.maxSets = 1;
vkCreateDescriptorPool(g_vkDevice, &poolInfo, NULL, &g_brushDescriptorPool);
VkDescriptorSetAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = g_brushDescriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &g_brushPipeline.m_descriptorSetLayout;
vkAllocateDescriptorSets(g_vkDevice, &allocInfo, &g_brushDescriptorSet);
g_brushProjection.Create(64, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
g_brushProject = (MeshProjection*)g_brushProjection.Map(0, 64);
VkPhysicalDeviceProperties properties{};
vkGetPhysicalDeviceProperties(g_vkPhysicalDevice, &properties);
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0f;
vkCreateSampler(g_vkDevice, &samplerInfo, nullptr, &g_brushSampler);
}
void IBrushRenderer::Frame( float fDelta )
{
glm_mat4_identity(g_brushProject->projection);
glm_perspective(glm_rad(90),(float)g_nWindowWidth/g_nWindowHeight, 0.01, 100, g_brushProject->projection);
glm_rotate(g_brushProject->projection, glm_rad(90), (vec4){1,0,0,0});
glm_scale(g_brushProject->projection, (vec4){1,-1,1,1});
if (g_bConfigNotify)
{
meshdepth.Destroy();
meshdepth.Create(g_nWindowWidth, g_nWindowHeight, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
}
CUtlVector<VkWriteDescriptorSet> writes(2);
for (auto &write: writes)
{
write = {};
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = g_brushDescriptorSet;
write.dstArrayElement = 0;
}
VkDescriptorBufferInfo bufferInfo = {};
bufferInfo.buffer = g_brushProjection.m_buffer;
bufferInfo.offset = 0;
bufferInfo.range = g_brushProjection.m_nSize;
writes[0].dstBinding = 0;
writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
writes[0].descriptorCount = 1;
writes[0].pBufferInfo = &bufferInfo;
CUtlVector<VkDescriptorImageInfo> textures;
textures.Reserve(g_textures.GetSize());
for (ITexture *t: g_textures)
{
CTexture *texture = (CTexture*)t;
VkDescriptorImageInfo image = {};
image.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
image.imageView = texture->image.m_imageView;
image.sampler = g_brushSampler;
textures.AppendTail(image);
};
textures[0].sampler = g_invalidTextureSampler;
writes[1].dstBinding = 1;
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writes[1].descriptorCount = textures.GetSize();
writes[1].pImageInfo = textures.GetData();
vkUpdateDescriptorSets(g_vkDevice, writes.GetSize(), writes.GetData(), 0, NULL);
VkImageMemoryBarrier barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = 0,
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.image = g_swapchainImage,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}
};
vkCmdPipelineBarrier(g_vkCommandBuffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 0, NULL, 0, NULL, 1, &barrier);
VkRenderingAttachmentInfo colorAttachment = {
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = g_swapchainImageView,
.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = {.color = {0.0f, 0.0f, 0.0f, 1.0f}}
};
VkRenderingAttachmentInfo depthAttachment = {
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = meshdepth.m_imageView,
.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = {.depthStencil = {.depth = 1}},
};
VkRenderingInfo renderInfo = {
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = {{0, 0}, {g_nWindowWidth, g_nWindowHeight}},
.layerCount = 1,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAttachment,
.pDepthAttachment = &depthAttachment,
};
vkCmdBeginRendering(g_vkCommandBuffer, &renderInfo);
vkCmdSetRasterizerDiscardEnable(g_vkCommandBuffer, VK_FALSE);
vkCmdSetDepthBiasEnable(g_vkCommandBuffer, VK_FALSE);
_vkCmdSetPolygonModeEXT(g_vkCommandBuffer, VK_POLYGON_MODE_FILL);
vkCmdSetCullMode(g_vkCommandBuffer, VK_CULL_MODE_BACK_BIT);
vkCmdSetFrontFace(g_vkCommandBuffer, VK_FRONT_FACE_COUNTER_CLOCKWISE);
vkCmdSetDepthTestEnable(g_vkCommandBuffer, VK_TRUE);
vkCmdSetDepthWriteEnable(g_vkCommandBuffer, VK_TRUE);
vkCmdSetDepthCompareOp(g_vkCommandBuffer, VK_COMPARE_OP_LESS);
vkCmdSetStencilTestEnable(g_vkCommandBuffer, VK_FALSE);
_vkCmdSetRasterizationSamplesEXT(g_vkCommandBuffer, VK_SAMPLE_COUNT_1_BIT);
VkSampleMask sampleMask = 0xFFFFFFFF;
_vkCmdSetSampleMaskEXT(g_vkCommandBuffer, VK_SAMPLE_COUNT_1_BIT, &sampleMask);
_vkCmdSetAlphaToCoverageEnableEXT(g_vkCommandBuffer, VK_FALSE);
VkViewport viewport = {0, 0, (float)g_nWindowWidth, (float)g_nWindowHeight, 0.0f, 1.0f};
VkRect2D scissor = {{0, 0}, {g_nWindowWidth, g_nWindowHeight}};
vkCmdSetViewportWithCount(g_vkCommandBuffer, 1, &viewport);
vkCmdSetScissorWithCount(g_vkCommandBuffer, 1, &scissor);
vkCmdSetPrimitiveTopology(g_vkCommandBuffer, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
vkCmdSetPrimitiveRestartEnable(g_vkCommandBuffer, VK_FALSE);
VkVertexInputBindingDescription2EXT binding = {
.sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT,
.binding = 0,
.stride = 20,
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
.divisor = 1,
};
VkVertexInputAttributeDescription2EXT attributes[2] = {
{
VK_STRUCTURE_TYPE_VERTEX_INPUT_ATTRIBUTE_DESCRIPTION_2_EXT,
NULL,
0, 0,
VK_FORMAT_R32G32B32_SFLOAT,
0
},
{
VK_STRUCTURE_TYPE_VERTEX_INPUT_ATTRIBUTE_DESCRIPTION_2_EXT,
NULL,
1, 0,
VK_FORMAT_R32G32_SFLOAT,
12
}
};
_vkCmdSetVertexInputEXT(g_vkCommandBuffer, 1, &binding, 2, attributes);
VkBool32 blendEnable = VK_FALSE;
VkColorBlendEquationEXT blendEquation = {
VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD
};
VkColorComponentFlags writeMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
_vkCmdSetColorBlendEnableEXT(g_vkCommandBuffer, 0, 1, &blendEnable);
_vkCmdSetColorBlendEquationEXT(g_vkCommandBuffer, 0, 1, &blendEquation);
_vkCmdSetColorWriteMaskEXT(g_vkCommandBuffer, 0, 1, &writeMask);
vkCmdBindPipeline(g_vkCommandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_brushPipeline.m_pipeline);
vkCmdBindDescriptorSets(g_vkCommandBuffer,VK_PIPELINE_BIND_POINT_GRAPHICS, g_brushPipeline.m_layout, 0, 1, &g_brushDescriptorSet, 0, NULL);
for (auto &mesh: g_drawnMeshes)
{
VkDeviceSize offset = 0;
uint32_t textureID = 0;
if (g_pCurrentMaterial == 0)
textureID = 0;
else
textureID = ((CMaterial*)g_pCurrentMaterial)->m.albedo;
vkCmdPushConstants(g_vkCommandBuffer, g_brushPipeline.m_layout, VK_SHADER_STAGE_ALL, 0, 4, &textureID);
vkCmdBindVertexBuffers(g_vkCommandBuffer, 0, 1, &mesh.m_pVertexBuffer->m_buffer.m_buffer, &offset);
if (mesh.m_pIndexBuffer)
{
vkCmdBindIndexBuffer(
g_vkCommandBuffer,
mesh.m_pIndexBuffer->m_buffer.m_buffer,
0,
VK_INDEX_TYPE_UINT32
);
vkCmdDrawIndexed(g_vkCommandBuffer, mesh.m_pIndexBuffer->m_buffer.m_nSize/4, 1, 0, 0, 0);
}
else
{
vkCmdDraw(g_vkCommandBuffer, mesh.m_pVertexBuffer->m_buffer.m_nSize/12,1,0,0);
}
}
vkCmdEndRendering(g_vkCommandBuffer);
barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.image = g_swapchainImage,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}
};
vkCmdPipelineBarrier(g_vkCommandBuffer,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &barrier);
g_drawnMeshes = CUtlVector<CBrush>();
}
IVertexBuffer *IBrushRenderer::CreateVertexBuffer( uint32_t uSize )
{
CVertexBuffer *pBuffer = new CVertexBuffer();
pBuffer->m_buffer.Create(uSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
return pBuffer;
}
IIndexBuffer *IBrushRenderer::CreateIndexBuffer( uint32_t uSize )
{
CIndexBuffer *pBuffer = new CIndexBuffer();
pBuffer->m_buffer.Create(uSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
return pBuffer;
}
IBrush *IBrushRenderer::CreateMesh()
{
CBrush *mesh = new CBrush;
return mesh;
}
void IBrushRenderer::Destroy( IBrush *pModel )
{
}
IMaterial *IBrushRenderer::LoadMaterial( const char *szMaterial )
{
FileHandle_t file = IFileSystem::Open(szMaterial, IFILE_READ);
CMaterial *pMaterial = new CMaterial;
if (!file)
{
return g_pDefaultMaterial;
}
IFileSystem::Close(file);
}
void IBrushRenderer::SetMaterial( IMaterial *pMaterial )
{
g_pCurrentMaterial = pMaterial;
}

View File

@@ -0,0 +1,9 @@
VK_DEVICE_FUNCTION(vkCmdSetPolygonModeEXT);
VK_DEVICE_FUNCTION(vkCmdSetRasterizationSamplesEXT);
VK_DEVICE_FUNCTION(vkCmdSetVertexInputEXT);
VK_DEVICE_FUNCTION(vkCmdSetSampleMaskEXT);
VK_DEVICE_FUNCTION(vkCmdSetAlphaToCoverageEnableEXT);
VK_DEVICE_FUNCTION(vkCmdSetViewportWithCount);
VK_DEVICE_FUNCTION(vkCmdSetColorBlendEnableEXT);
VK_DEVICE_FUNCTION(vkCmdSetColorBlendEquationEXT);
VK_DEVICE_FUNCTION(vkCmdSetColorWriteMaskEXT);

72
engine/vk_helper.h Normal file
View File

@@ -0,0 +1,72 @@
#include "filesystem.h"
#include "rendering.h"
#include "tier0/platform.h"
#include "tier1/utlvector.h"
#include "console.h"
#include "tier1/commandline.h"
#include "X11/X.h"
#include "X11/Xlib.h"
#include "vulkan/vulkan.h"
#include "vulkan/vulkan_core.h"
#include "vulkan/vulkan_xlib.h"
#define VULKAN_RENDERING_IMPL
#include "vk_video.h"
#define VK_DEVICE_FUNCTION(name) extern PFN_##name _##name
#include "vk_external_functions.cpp"
#undef VK_DEVICE_FUNCTION
#include "cglm/affine.h"
#include "cglm/cglm.h"
extern Display* g_xdisplay;
extern int g_xscreen;
extern Window g_xroot;
extern Window g_xwin;
extern VkInstance g_vkInstance;
extern VkPhysicalDevice g_vkPhysicalDevice;
extern VkDevice g_vkDevice;
extern uint32_t g_drawfamily;
extern VkQueue g_drawQueue;
extern uint32_t g_presentfamily;
extern VkQueue g_presentQueue;
extern VmaAllocator g_allocator;
extern VkSurfaceKHR g_surface;
extern VkSwapchainKHR g_swapchain;
extern VkCommandPool g_vkCommandPool;
extern VkCommandBuffer g_vkCommandBuffer;
extern VkImageView g_swapchainImageView;
extern VkImage g_swapchainImage;
extern uint32_t g_nWindowWidth;
extern uint32_t g_nWindowHeight;
class CVertexBuffer: public IVertexBuffer
{
public:
void *Map() override;
void Unmap() override;
vk_buffer_t m_buffer;
void *m_pAllocated = NULL;
};
class CIndexBuffer: public IIndexBuffer
{
public:
void *Map() override;
void Unmap() override;
vk_buffer_t m_buffer;
void *m_pAllocated;
};
class CTexture: public ITexture
{
public:
vk_image2d_t image;
};

474
engine/vk_video.cpp Normal file
View File

@@ -0,0 +1,474 @@
#include "filesystem.h"
#include "rendering.h"
#include "tier0/lib.h"
#include "tier1/utlvector.h"
#include "vk_helper.h"
#include "tier0/platform.h"
#include "vulkan/vulkan_core.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
VkSampler g_invalidTextureSampler;
void IVulkan::Init()
{
char invalidTexture[1024] = {};
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
int index = i * 16 + j;
if ((i + j) % 2 == 0) {
invalidTexture[index*4] = 255;
}
}
}
ITextureManager::LoadTexture(invalidTexture, 16, 16, 4);
VkPhysicalDeviceProperties properties{};
vkGetPhysicalDeviceProperties(g_vkPhysicalDevice, &properties);
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_FALSE;
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = 0.0f;
vkCreateSampler(g_vkDevice, &samplerInfo, nullptr, &g_invalidTextureSampler);
IBrushRenderer::Init();
};
void IVulkan::Frame()
{
IBrushRenderer::Frame(0);
};
void vk_shader_t::Create( const char *szPath, VkShaderStageFlagBits shaderStage )
{
FileHandle_t shader = IFileSystem::Open(szPath, IFILE_READ);
if (!shader)
Plat_FatalErrorFunc("Failed to open shader %s\n", szPath);
CUtlBuffer<uint8_t> buffer(IFileSystem::Size(shader));
IFileSystem::Read(shader, buffer.GetMemory(), buffer.GetSize());
Create(buffer, shaderStage);
IFileSystem::Close(shader);
}
void vk_shader_t::Create( CUtlBuffer<uint8_t> &spirv, VkShaderStageFlagBits shaderStage )
{
if (m_shaderModule != NULL)
Plat_FatalErrorFunc("Shader already exists");
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = spirv.GetSize();
createInfo.pCode = (uint32_t*)spirv.GetMemory();
vkCreateShaderModule(g_vkDevice, &createInfo, NULL, &m_shaderModule);
m_stageCreateInfo = {};
m_stageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
m_stageCreateInfo.module = m_shaderModule;
m_stageCreateInfo.stage = shaderStage;
m_stageCreateInfo.pName = "main";
}
void vk_shader_t::Destroy( void )
{
if (m_shaderModule == NULL)
Plat_FatalErrorFunc("Shader doesn't exist");
vkDestroyShaderModule(g_vkDevice, m_shaderModule, NULL);
}
void vk_tripipeline_t::Create(
CUtlVector<vk_shader_t> &shaders,
CUtlVector<VkDescriptorSetLayoutBinding> &bindings,
uint32_t pushConstantSize
)
{
VkPushConstantRange pushConstantRange = {};
pushConstantRange.stageFlags = VK_SHADER_STAGE_ALL;
pushConstantRange.offset = 0;
pushConstantRange.size = pushConstantSize;
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {};
descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptorSetLayoutCreateInfo.bindingCount = bindings.GetSize();
descriptorSetLayoutCreateInfo.pBindings = bindings.GetData();
vkCreateDescriptorSetLayout(g_vkDevice, &descriptorSetLayoutCreateInfo, NULL, &m_descriptorSetLayout);
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {};
pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutCreateInfo.setLayoutCount = 1;
pipelineLayoutCreateInfo.pSetLayouts = &m_descriptorSetLayout;
if (pushConstantSize != 0)
{
pipelineLayoutCreateInfo.pushConstantRangeCount = 1;
pipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange;
}
vkCreatePipelineLayout(g_vkDevice, &pipelineLayoutCreateInfo, NULL, &m_layout);
VkDynamicState dynamicStates[] = {
/* pVertexInputState */
VK_DYNAMIC_STATE_VERTEX_INPUT_EXT,
/* pInputAssemblyState */
VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE,
VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY,
/* pTessellationState */
VK_DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT,
/* pViewportState */
VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT,
VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT,
/* pRasterizationState */
VK_DYNAMIC_STATE_DEPTH_CLAMP_ENABLE_EXT,
VK_DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE,
VK_DYNAMIC_STATE_POLYGON_MODE_EXT,
VK_DYNAMIC_STATE_CULL_MODE,
VK_DYNAMIC_STATE_FRONT_FACE,
VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE,
VK_DYNAMIC_STATE_DEPTH_BIAS,
VK_DYNAMIC_STATE_LINE_WIDTH,
/* pMultisampleState */
VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT,
VK_DYNAMIC_STATE_SAMPLE_MASK_EXT,
VK_DYNAMIC_STATE_ALPHA_TO_COVERAGE_ENABLE_EXT,
/* pDepthStencilState */
VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE,
VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE,
VK_DYNAMIC_STATE_DEPTH_COMPARE_OP,
VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE,
VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE,
VK_DYNAMIC_STATE_STENCIL_OP,
VK_DYNAMIC_STATE_DEPTH_BOUNDS,
/* pColorBlendState */
VK_DYNAMIC_STATE_LOGIC_OP_ENABLE_EXT,
VK_DYNAMIC_STATE_LOGIC_OP_EXT,
VK_DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT,
VK_DYNAMIC_STATE_COLOR_BLEND_EQUATION_EXT,
VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT,
VK_DYNAMIC_STATE_BLEND_CONSTANTS,
};
VkPipelineDynamicStateCreateInfo pipelineDynamicStateCreateInfo = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
.dynamicStateCount = sizeof(dynamicStates)/sizeof(VkDynamicState),
.pDynamicStates = dynamicStates,
};
VkPipelineInputAssemblyStateCreateInfo piasci = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
.primitiveRestartEnable = VK_TRUE,
};
VkPipelineRenderingCreateInfo prci = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
.pNext = NULL,
.colorAttachmentCount = 1,
.pColorAttachmentFormats = (VkFormat[]){ VK_FORMAT_B8G8R8A8_UNORM }, // <-- replace with your actual format
.depthAttachmentFormat = VK_FORMAT_D32_SFLOAT,
};
VkGraphicsPipelineCreateInfo graphicsPipelineCreateInfo = {};
graphicsPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
graphicsPipelineCreateInfo.pInputAssemblyState = &piasci;
graphicsPipelineCreateInfo.layout = m_layout;
graphicsPipelineCreateInfo.pDynamicState = &pipelineDynamicStateCreateInfo;
graphicsPipelineCreateInfo.stageCount = shaders.GetSize();
CUtlVector<VkPipelineShaderStageCreateInfo> stages(graphicsPipelineCreateInfo.stageCount);
uint32_t i = 0;
for (auto &shader: shaders)
{
stages[i] = shader.m_stageCreateInfo;
i++;
}
graphicsPipelineCreateInfo.pStages = stages.GetData();
graphicsPipelineCreateInfo.pNext = &prci;
vkCreateGraphicsPipelines(g_vkDevice, NULL, 1, &graphicsPipelineCreateInfo, NULL, &m_pipeline);
}
void vk_tripipeline_t::Destroy()
{
}
void vk_buffer_t::Create(size_t size, VkBufferUsageFlags usage)
{
VkBufferCreateInfo bufferCreateInfo = {};
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.usage = usage;
bufferCreateInfo.size = size;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
VMA_ALLOCATION_CREATE_MAPPED_BIT;
m_nSize = size;
vmaCreateBuffer(g_allocator, &bufferCreateInfo, &allocInfo, &m_buffer, &m_memory, NULL);
}
void vk_buffer_t::Destroy()
{
}
void *vk_buffer_t::Map(size_t offset, size_t size)
{
void *pData;
vmaMapMemory(g_allocator, m_memory, &pData);
return pData;
}
void vk_buffer_t::Unmap()
{
vmaUnmapMemory(g_allocator, m_memory);
}
void vk_buffer_t::CopyTo(struct vk_image2d_t *image)
{
}
void vk_buffer_t::CopyTo(struct vk_buffer_t *buffer)
{
}
void vk_image2d_t::Create(size_t x, size_t y, VkFormat format, VkImageUsageFlags usage)
{
VkImageCreateInfo imageInfo={};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = x > 1 ? x : 1;
imageInfo.extent.height = y > 1 ? y : 1;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.usage = usage;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.format=format;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
VmaAllocationCreateInfo alloc = {};
alloc.usage=VMA_MEMORY_USAGE_AUTO;
vmaCreateImage(g_allocator, &imageInfo,&alloc, &m_image, &m_memory,0);
m_X=imageInfo.extent.width;
m_Y=imageInfo.extent.width;
m_format=format;
VkImageView imageView = 0;
VkImageViewCreateInfo imageViewCreateInfo={};
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = format;
imageViewCreateInfo.image = m_image;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
if (format == VK_FORMAT_D32_SFLOAT) {
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
}
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
vkCreateImageView(g_vkDevice, &imageViewCreateInfo, 0, &m_imageView);
}
void vk_image2d_t::Destroy()
{
vkDestroyImageView(g_vkDevice, m_imageView, NULL);
vmaDestroyImage(g_allocator, m_image, NULL);
}
void CopyTo(struct vk_image2d_t *image);
void CopyTo(struct vk_buffer_t *buffer);
void *CVertexBuffer::Map()
{
if (!m_pAllocated)
m_pAllocated = m_buffer.Map(0, m_buffer.m_nSize);
return m_pAllocated;
};
void CVertexBuffer::Unmap()
{
if (!m_pAllocated)
return;
m_buffer.Unmap();
m_pAllocated = 0;
};
void *CIndexBuffer::Map()
{
if (!m_pAllocated)
m_pAllocated = m_buffer.Map(0, m_buffer.m_nSize);
return m_pAllocated;
};
void CIndexBuffer::Unmap()
{
if (!m_pAllocated)
return;
m_buffer.Unmap();
m_pAllocated = 0;
};
CUtlVector<ITexture*> g_textures;
CUtlVector<ITexture*> g_newtextures;
uint32_t ITextureManager::GetTexture(ITexture *pTexture)
{
uint32_t i = 0;
for (ITexture *texture: g_textures)
{
if (texture == pTexture)
return i;
i++;
};
return 0;
}
ITexture *ITextureManager::LoadTexture( void *pData, uint32_t X, uint32_t Y, uint32_t numChannels )
{
CTexture *pTexture = new CTexture;
*pTexture = {};
VkDeviceSize imageSize = X*Y*4;
vk_buffer_t gpu_buffer = {};
gpu_buffer.Create(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
void *gpu_buffer_map = gpu_buffer.Map(0, 0);
V_memcpy(gpu_buffer_map, pData, imageSize);
gpu_buffer.Unmap();
pTexture->image = {};
pTexture->image.Create(X, Y, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
VkCommandPool commandPool;
VkCommandBuffer commandBuffer;
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = g_drawfamily;
poolInfo.flags = 0;
vkCreateCommandPool(g_vkDevice, &poolInfo, NULL, &commandPool);
VkCommandBufferAllocateInfo cmdAllocInfo{};
cmdAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmdAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmdAllocInfo.commandPool = commandPool;
cmdAllocInfo.commandBufferCount = 1;
vkAllocateCommandBuffers(g_vkDevice, &cmdAllocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = pTexture->image.m_image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(
commandBuffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0,
0, NULL,
0, NULL,
1, &barrier
);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = {0, 0, 0};
region.imageExtent = {(uint32_t)X, (uint32_t)Y, 1};
vkCmdCopyBufferToImage(
commandBuffer,
gpu_buffer.m_buffer,
pTexture->image.m_image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
&region
);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(
commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, NULL,
0, NULL,
1, &barrier
);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(g_drawQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(g_drawQueue);
vkFreeCommandBuffers(g_vkDevice, commandPool, 1, &commandBuffer);
vkDestroyCommandPool(g_vkDevice, commandPool, NULL);
g_newtextures.AppendTail(pTexture);
g_textures.AppendTail(pTexture);
return pTexture;
};
ITexture *ITextureManager::LoadTexture( const char *szName )
{
for (ITexture *texture: g_textures)
{
if (!texture->szName)
continue;
if (!V_strcmp(texture->szName, szName))
return texture;
};
FileHandle_t file = IFileSystem::Open(szName, IFILE_READ);
if (!file)
Plat_FatalErrorFunc("Failed to load %s\n", szName);
CUtlBuffer<stbi_uc> buffer(IFileSystem::Size(file));
IFileSystem::Read(file, buffer.GetMemory(), buffer.GetSize());
int nImageX;
int nImageY;
int nImageChannels;
stbi_uc *pixels = stbi_load_from_memory((stbi_uc*)buffer.GetMemory(), buffer.GetSize(), &nImageX, &nImageY, &nImageChannels, STBI_rgb_alpha);
ITexture *pTexture = ITextureManager::LoadTexture(pixels, nImageX, nImageY, 4);
pTexture->szName = szName;
return pTexture;
};

449
engine/vk_videolinux.cpp Normal file
View File

@@ -0,0 +1,449 @@
#include "rendering.h"
#include "tier1/utlvector.h"
#include "console.h"
#include "tier1/commandline.h"
#include "X11/X.h"
#include "X11/Xlib.h"
#include "vulkan/vulkan.h"
#include "vulkan/vulkan_core.h"
#include "vulkan/vulkan_xlib.h"
#define VULKAN_RENDERING_IMPL
#include "vk_video.h"
#define VMA_VULKAN_VERSION 1004000
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
Display* g_xdisplay;
int g_xscreen;
Window g_xroot;
Window g_xwin;
VkInstance g_vkInstance = NULL;
VkPhysicalDevice g_vkPhysicalDevice = NULL;
VkDevice g_vkDevice = NULL;
uint32_t g_drawfamily = 0;
VkQueue g_drawQueue;
uint32_t g_presentfamily = 0;
VkQueue g_presentQueue;
VmaAllocator g_allocator = NULL;
VkSurfaceKHR g_surface;
VkSwapchainKHR g_swapchain;
ConVar vulkan_gpu("vk_gpu", "0", FCVAR_ARCHIVE);
VkCommandPool g_vkCommandPool;
/* more efficient */
CUtlVector<VkCommandBuffer> g_commandBuffers;
VkCommandBuffer g_vkCommandBuffer;
CUtlVector<vk_framedata_t> g_frameData;
CUtlVector<VkImage> g_swapchainImages;
CUtlVector<VkImageView> g_swapchainImageViews;
VkImageView g_swapchainImageView;
VkImage g_swapchainImage;
uint32_t g_nNumSwapchainImages = 0;
void IVideo_SwapchainInit()
{
/* swapchain */
VkXlibSurfaceCreateInfoKHR surfaceCreateInfo = {};
surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
surfaceCreateInfo.dpy = g_xdisplay;
surfaceCreateInfo.window = g_xwin;
vkCreateXlibSurfaceKHR(g_vkInstance, &surfaceCreateInfo, NULL, &g_surface);
VkSurfaceCapabilitiesKHR surfaceCapatibilities = {};
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_vkPhysicalDevice, g_surface, &surfaceCapatibilities);
const VkFormat preferedSurfaceFormats[] = {
VK_FORMAT_R8G8B8A8_UNORM,
VK_FORMAT_B8G8R8A8_UNORM,
};
uint32_t numSurfaceFormats = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR(g_vkPhysicalDevice, g_surface, &numSurfaceFormats, NULL);
CUtlVector<VkSurfaceFormatKHR> surfaceFormats(numSurfaceFormats);
vkGetPhysicalDeviceSurfaceFormatsKHR(g_vkPhysicalDevice, g_surface, &numSurfaceFormats, surfaceFormats.GetData());
VkSurfaceFormatKHR selectedFormat = surfaceFormats[0];
for (auto &format: surfaceFormats)
{
for (int i = 0; i < sizeof(preferedSurfaceFormats)/sizeof(VkFormat); i++)
{
selectedFormat = surfaceFormats[i];
}
}
uint32_t numSurfacePresentModes = 0;
vkGetPhysicalDeviceSurfacePresentModesKHR(g_vkPhysicalDevice, g_surface, &numSurfacePresentModes, NULL);
CUtlVector<VkPresentModeKHR> surfacePresentModes(numSurfacePresentModes);
vkGetPhysicalDeviceSurfacePresentModesKHR(g_vkPhysicalDevice, g_surface, &numSurfacePresentModes, surfacePresentModes.GetData());
VkSwapchainCreateInfoKHR swapchainCreateInfo = {};
swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainCreateInfo.surface = g_surface;
swapchainCreateInfo.imageFormat = selectedFormat.format;
swapchainCreateInfo.imageColorSpace = selectedFormat.colorSpace;
swapchainCreateInfo.presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchainCreateInfo.preTransform = surfaceCapatibilities.currentTransform;
swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchainCreateInfo.imageArrayLayers = 1;
swapchainCreateInfo.imageExtent = surfaceCapatibilities.minImageExtent;
swapchainCreateInfo.minImageCount = surfaceCapatibilities.minImageCount;
vkCreateSwapchainKHR(g_vkDevice, &swapchainCreateInfo, NULL, &g_swapchain);
vkGetSwapchainImagesKHR(g_vkDevice, g_swapchain, &g_nNumSwapchainImages, NULL);
g_swapchainImages = CUtlVector<VkImage>(g_nNumSwapchainImages);
g_swapchainImageViews = CUtlVector<VkImageView>(g_nNumSwapchainImages);
g_commandBuffers = CUtlVector<VkCommandBuffer>(g_nNumSwapchainImages);
g_frameData = CUtlVector<vk_framedata_t>(g_nNumSwapchainImages);
vkGetSwapchainImagesKHR(g_vkDevice, g_swapchain, &g_nNumSwapchainImages, g_swapchainImages.GetData());
for (int i = 0; i < g_nNumSwapchainImages; i++)
{
VkImageViewCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = g_swapchainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = selectedFormat.format;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
vkCreateImageView(g_vkDevice, &createInfo, NULL, &g_swapchainImageViews[i]);
}
/* command buffers */
VkCommandPoolCreateInfo commandPoolCreateInfo = {};
commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
commandPoolCreateInfo.queueFamilyIndex = g_drawfamily;
commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
vkCreateCommandPool(g_vkDevice, &commandPoolCreateInfo, NULL, &g_vkCommandPool);
VkCommandBufferAllocateInfo commandBufferAllocInfo = {};
commandBufferAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocInfo.commandPool = g_vkCommandPool;
commandBufferAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocInfo.commandBufferCount = g_nNumSwapchainImages;
vkAllocateCommandBuffers(g_vkDevice, &commandBufferAllocInfo, g_commandBuffers.GetData());
/* sync */
VkFenceCreateInfo fenceCreateInfo = {};
fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
VkSemaphoreCreateInfo semaphoreCreateInfo = {};
semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
for (int i = 0; i < g_nNumSwapchainImages; i++)
{
vkCreateFence(g_vkDevice,&fenceCreateInfo, NULL, &g_frameData[i].fence);
vkCreateSemaphore(g_vkDevice, &semaphoreCreateInfo, NULL, &g_frameData[i].draw);
vkCreateSemaphore(g_vkDevice, &semaphoreCreateInfo, NULL, &g_frameData[i].present);
}
};
void IVideo_SwapchainDestroy()
{
vkDestroySwapchainKHR(g_vkDevice, g_swapchain, NULL);
vkDestroySurfaceKHR(g_vkInstance, g_surface, NULL);
for (int i = 0; i < g_nNumSwapchainImages; i++)
{
vkDestroyImageView(g_vkDevice, g_swapchainImageViews[i], NULL);
vkDestroySemaphore(g_vkDevice, g_frameData[i].draw, NULL);
vkDestroySemaphore(g_vkDevice, g_frameData[i].present, NULL);
vkDestroyFence(g_vkDevice, g_frameData[i].fence, NULL);
}
};
#define VK_DEVICE_FUNCTION(name) PFN_##name _##name
#include "vk_external_functions.cpp"
#undef VK_DEVICE_FUNCTION
void IVideo::Init()
{
g_xdisplay = XOpenDisplay(NULL);
g_xscreen = DefaultScreen(g_xdisplay);
g_xroot = RootWindow(g_xdisplay, g_xscreen);
g_xwin = XCreateSimpleWindow(g_xdisplay, g_xroot, 0, 0, 1280, 720, 0, 0, 0);
XSelectInput(g_xdisplay, g_xwin, StructureNotifyMask);
vulkan_gpu.SetValue(ICommandLine::ParamValue("-gpu"));
VkResult r = VK_SUCCESS;
uint32_t i = 0;
/* Instance */
VkApplicationInfo applicationInfo = {};
applicationInfo.apiVersion = VK_API_VERSION_1_4;
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &applicationInfo;
const char *szEnabledExtensions[] = {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
};
instanceCreateInfo.enabledExtensionCount = 2;
instanceCreateInfo.ppEnabledExtensionNames = szEnabledExtensions;
r = vkCreateInstance(&instanceCreateInfo, NULL, &g_vkInstance);
if ( r != VK_SUCCESS )
Plat_FatalErrorFunc("Failed to create VkInstance!");
/* Physical Devices */
uint32_t nNumPhysicalDevices = 0;
vkEnumeratePhysicalDevices(g_vkInstance, &nNumPhysicalDevices, NULL);
if ( nNumPhysicalDevices == 0 )
Plat_FatalErrorFunc("No GPU drivers available!");
CUtlVector<VkPhysicalDevice> PhysicalDevices(nNumPhysicalDevices);
vkEnumeratePhysicalDevices(g_vkInstance, &nNumPhysicalDevices, PhysicalDevices.GetData());
/* enumerate them for the user */
for (auto &device: PhysicalDevices)
{
VkPhysicalDeviceProperties Properties = {};
vkGetPhysicalDeviceProperties(device, &Properties);
V_printf("GPU%i available: %s\n", i, Properties.deviceName);
i++;
}
/* select one in vk_gpu */
g_vkPhysicalDevice = PhysicalDevices[vulkan_gpu.GetInt()];
/* queue family */
uint32_t nNumQueueFamilies = 0;
vkGetPhysicalDeviceQueueFamilyProperties(g_vkPhysicalDevice, &nNumQueueFamilies, NULL);
CUtlVector<VkQueueFamilyProperties> queueFamilyProperties(nNumQueueFamilies);
vkGetPhysicalDeviceQueueFamilyProperties(g_vkPhysicalDevice, &nNumQueueFamilies, queueFamilyProperties.GetData());
i = 0;
for (auto &family: queueFamilyProperties)
{
if (family.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
g_drawfamily = i;
g_presentfamily = i;
}
i++;
}
/* create device */
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = g_drawfamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT pdvidsfe = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_INPUT_DYNAMIC_STATE_FEATURES_EXT,
.vertexInputDynamicState = VK_TRUE,
};
VkPhysicalDeviceExtendedDynamicState3FeaturesEXT pdeds3fe = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_3_FEATURES_EXT,
.pNext = &pdvidsfe,
.extendedDynamicState3DepthClampEnable = VK_TRUE,
.extendedDynamicState3PolygonMode = VK_TRUE,
.extendedDynamicState3RasterizationSamples = VK_TRUE,
.extendedDynamicState3SampleMask = VK_TRUE,
.extendedDynamicState3AlphaToCoverageEnable = VK_TRUE,
.extendedDynamicState3LogicOpEnable = VK_TRUE,
.extendedDynamicState3ColorBlendEnable = VK_TRUE,
.extendedDynamicState3ColorBlendEquation = VK_TRUE,
.extendedDynamicState3ColorWriteMask = VK_TRUE,
};
VkPhysicalDeviceExtendedDynamicState2FeaturesEXT pdeds2fe = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT,
.pNext = &pdeds3fe,
.extendedDynamicState2LogicOp = VK_TRUE,
.extendedDynamicState2PatchControlPoints = VK_TRUE,
};
VkPhysicalDeviceVulkan13Features pdv13f = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
.pNext = &pdeds2fe,
.dynamicRendering = VK_TRUE,
};
VkPhysicalDeviceVulkan12Features pdv12f = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
.pNext = &pdv13f,
.runtimeDescriptorArray = VK_TRUE,
.bufferDeviceAddress = VK_TRUE,
};
VkPhysicalDeviceVulkan11Features pdv11f = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
.pNext = &pdv12f,
};
const char *szEnabledGPUExtensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
VK_EXT_VERTEX_INPUT_DYNAMIC_STATE_EXTENSION_NAME,
VK_EXT_EXTENDED_DYNAMIC_STATE_3_EXTENSION_NAME,
};
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.enabledExtensionCount = sizeof(szEnabledGPUExtensions)/(sizeof(const char*));
deviceCreateInfo.ppEnabledExtensionNames = szEnabledGPUExtensions;
deviceCreateInfo.pNext = &pdv11f;
r = vkCreateDevice(g_vkPhysicalDevice, &deviceCreateInfo, NULL, &g_vkDevice);
if ( r != VK_SUCCESS )
Plat_FatalErrorFunc("Failed to create VkDevice!");
vkGetDeviceQueue(g_vkDevice, g_drawfamily, 0, &g_drawQueue);
vkGetDeviceQueue(g_vkDevice, g_presentfamily, 0, &g_presentQueue);
VmaVulkanFunctions vulkanFunctions = {};
vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;
VmaAllocatorCreateInfo allocatorCreateInfo = {};
allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT;
allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_4;
allocatorCreateInfo.physicalDevice = g_vkPhysicalDevice;
allocatorCreateInfo.device = g_vkDevice;
allocatorCreateInfo.instance = g_vkInstance;
vmaCreateAllocator(&allocatorCreateInfo, &g_allocator);
#define VK_DEVICE_FUNCTION(name) _##name = (PFN_##name)vkGetDeviceProcAddr(g_vkDevice, #name)
#include "vk_external_functions.cpp"
#undef VK_DEVICE_FUNCTION
IVideo_SwapchainInit();
XMapWindow(g_xdisplay, g_xwin);
XFlush(g_xdisplay);
IVulkan::Init();
}
char g_bConfigNotify = 0;
uint32_t g_nWindowWidth = 1280;
uint32_t g_nWindowHeight = 720;
void IVideo_HandleX11()
{
XEvent event;
while(XPending(g_xdisplay))
{
XNextEvent(g_xdisplay, &event);
switch (event.type)
{
case KeyPress:
case KeyRelease:
break;
case MotionNotify:
break;
case ButtonPress:
break;
case ButtonRelease:
break;
case CreateNotify:
break;
case ConfigureNotify:
g_nWindowWidth = event.xconfigure.width;
g_nWindowHeight = event.xconfigure.height;
g_bConfigNotify = 2;
break;
}
}
};
void IVideo::Frame( float fDelta )
{
static uint32_t s_frameID = 0;
IVideo_HandleX11();
vk_framedata_t frame = g_frameData[s_frameID];
vkDeviceWaitIdle(g_vkDevice);
vkWaitForFences(g_vkDevice, 1, &frame.fence, VK_TRUE, UINT64_MAX);
uint32_t imageIndex = 0;
VkResult r = vkAcquireNextImageKHR(g_vkDevice, g_swapchain, UINT64_MAX, frame.draw, VK_NULL_HANDLE, &imageIndex);
if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR || g_bConfigNotify == 2)
{
g_bConfigNotify=1;
vkDeviceWaitIdle(g_vkDevice);
IVideo_SwapchainDestroy();
IVideo_SwapchainInit();
return;
}
vk_framedata_t frameindex = g_frameData[imageIndex];
vkResetFences(g_vkDevice, 1, &frame.fence);
g_vkCommandBuffer = g_commandBuffers[s_frameID];
g_swapchainImageView = g_swapchainImageViews[imageIndex];
g_swapchainImage = g_swapchainImages[imageIndex];
vkResetCommandBuffer(g_vkCommandBuffer, 0);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(g_vkCommandBuffer, &beginInfo);
IVulkan::Frame();
vkEndCommandBuffer(g_vkCommandBuffer);
VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &frame.draw;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &g_vkCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &frameindex.present;
vkQueueSubmit(g_drawQueue, 1, &submitInfo, frame.fence);
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &frameindex.present;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &g_swapchain;
presentInfo.pImageIndices = &imageIndex;
r = vkQueuePresentKHR(g_presentQueue, &presentInfo);
if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR)
{
vkDeviceWaitIdle(g_vkDevice);
IVideo_SwapchainDestroy();
IVideo_SwapchainInit();
return;
}
g_bConfigNotify = 0;
s_frameID=(s_frameID+1)%g_nNumSwapchainImages;
};