Removed old bgfx files

simple_math_single_header
Martin Felis 2018-03-01 13:16:42 +01:00
parent 2550bb5407
commit 2348929800
5 changed files with 0 additions and 2839 deletions

View File

@ -1,281 +0,0 @@
/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "shaderc.h"
#include <cstdio>
static long int fsize(FILE* _file)
{
long int pos = ftell(_file);
fseek(_file, 0L, SEEK_END);
long int size = ftell(_file);
fseek(_file, pos, SEEK_SET);
return size;
}
class Bin2cWriter : public bx::CrtFileWriter
{
public:
Bin2cWriter(const char* _name)
: m_name(_name)
{
}
virtual ~Bin2cWriter()
{
}
virtual int32_t close() BX_OVERRIDE
{
generate();
return bx::CrtFileWriter::close();
}
virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
{
const char* data = (const char*)_data;
m_buffer.insert(m_buffer.end(), data, data+_size);
return _size;
}
private:
void generate()
{
#define HEX_DUMP_WIDTH 16
#define HEX_DUMP_SPACE_WIDTH 96
#define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
const uint8_t* data = &m_buffer[0];
uint32_t size = (uint32_t)m_buffer.size();
outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
if (NULL != data)
{
char hex[HEX_DUMP_SPACE_WIDTH+1];
char ascii[HEX_DUMP_WIDTH+1];
uint32_t hexPos = 0;
uint32_t asciiPos = 0;
for (uint32_t ii = 0; ii < size; ++ii)
{
bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
hexPos += 6;
ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
asciiPos++;
if (HEX_DUMP_WIDTH == asciiPos)
{
ascii[asciiPos] = '\0';
outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
data += asciiPos;
hexPos = 0;
asciiPos = 0;
}
}
if (0 != asciiPos)
{
ascii[asciiPos] = '\0';
outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
}
}
outf("};\n");
#undef HEX_DUMP_WIDTH
#undef HEX_DUMP_SPACE_WIDTH
#undef HEX_DUMP_FORMAT
}
int32_t outf(const char* _format, ...)
{
va_list argList;
va_start(argList, _format);
char temp[2048];
char* out = temp;
int32_t max = sizeof(temp);
int32_t len = bx::vsnprintf(out, max, _format, argList);
if (len > max)
{
out = (char*)alloca(len);
len = bx::vsnprintf(out, len, _format, argList);
}
int32_t size = bx::CrtFileWriter::write(out, len);
va_end(argList);
return size;
}
std::string m_filePath;
std::string m_name;
typedef std::vector<uint8_t> Buffer;
Buffer m_buffer;
};
// c - compute
// d - domain
// f - fragment
// g - geometry
// h - hull
// v - vertex
//
// OpenGL #version Features Direct3D Features Shader Model
// 2.1 120 vf 9.0 vf 2.0
// 3.0 130
// 3.1 140
// 3.2 150 vgf
// 3.3 330 10.0 vgf 4.0
// 4.0 400 vhdgf
// 4.1 410
// 4.2 420 11.0 vhdgf+c 5.0
// 4.3 430 vhdgf+c
// 4.4 440
void help(const char* _error = NULL)
{
if (NULL != _error)
{
fprintf(stderr, "Error:\n%s\n\n", _error);
}
fprintf(stderr
, "shaderc, bgfx shader compiler tool\n"
"Copyright 2011-2015 Branimir Karadzic. All rights reserved.\n"
"License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
);
fprintf(stderr
, "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
"\n"
"Options:\n"
" -f <file path> Input file path.\n"
" -i <include path> Include path (for multiple paths use semicolon).\n"
" -o <file path> Output file path.\n"
" --bin2c <file path> Generate C header file.\n"
" --depends Generate makefile style depends file.\n"
" --platform <platform> Target platform.\n"
" android\n"
" asm.js\n"
" ios\n"
" linux\n"
" nacl\n"
" osx\n"
" windows\n"
" --preprocess Preprocess only.\n"
" --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
" --type <type> Shader type (vertex, fragment)\n"
" --varyingdef <file path> Path to varying.def.sc file.\n"
" --verbose Verbose.\n"
"\n"
"Options (DX9 and DX11 only):\n"
"\n"
" --debug Debug information.\n"
" --disasm Disassemble compiled shader.\n"
" -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
" -O <level> Optimization level (0, 1, 2, 3).\n"
" --Werror Treat warnings as errors.\n"
"\n"
"For additional information, see https://github.com/bkaradzic/bgfx\n"
);
}
int main(int _argc, const char* _argv[])
{
bx::CommandLine cmdLine(_argc, _argv);
if (cmdLine.hasArg('h', "help") )
{
help();
return EXIT_FAILURE;
}
const char* filePath = cmdLine.findOption('f');
if (NULL == filePath)
{
help("Shader file name must be specified.");
return EXIT_FAILURE;
}
const char* outFilePath = cmdLine.findOption('o');
if (NULL == outFilePath)
{
help("Output file name must be specified.");
return EXIT_FAILURE;
}
const char* bin2c = NULL;
if (cmdLine.hasArg("bin2c") )
{
bin2c = cmdLine.findOption("bin2c");
if (NULL == bin2c)
{
bin2c = bx::baseName(outFilePath);
uint32_t len = (uint32_t)strlen(bin2c);
char* temp = (char*)alloca(len+1);
for (char *out = temp; *bin2c != '\0';)
{
char ch = *bin2c++;
if (isalnum(ch) )
{
*out++ = ch;
}
else
{
*out++ = '_';
}
}
temp[len] = '\0';
bin2c = temp;
}
}
bx::CrtFileReader* reader = new bx::CrtFileReader;
if (0 != reader->open(filePath))
{
fprintf(stderr, "Unable to open input file '%s'.", filePath);
delete reader;
return EXIT_FAILURE;
}
bx::CrtFileWriter* writer = NULL;
if (NULL != bin2c)
{
writer = new Bin2cWriter(bin2c);
}
else
{
writer = new bx::CrtFileWriter;
}
if (0 != writer->open(outFilePath) )
{
fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
delete writer;
delete reader;
return EXIT_FAILURE;
}
int result = compileShader (cmdLine, reader, writer);
reader->close();
delete reader;
writer->close();
delete writer;
return result;
}

View File

@ -1,119 +0,0 @@
/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#ifndef SHADERC_H_HEADER_GUARD
#define SHADERC_H_HEADER_GUARD
#include <bx/macros.h>
#ifndef SHADERC_CONFIG_HLSL
# define SHADERC_CONFIG_HLSL BX_PLATFORM_WINDOWS
#endif // SHADERC_CONFIG_HLSL
extern bool g_verbose;
#include <alloca.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_map>
#include <bx/bx.h>
#include <bx/debug.h>
#include <bx/commandline.h>
#include <bx/endian.h>
#include <bx/uint32_t.h>
#include <bx/readerwriter.h>
#include <bx/string.h>
#include <bx/hash.h>
#include <bx/crtimpl.h>
#include "../../src/vertexdecl.h"
class LineReader
{
public:
LineReader(const char* _str)
: m_str(_str)
, m_pos(0)
, m_size((uint32_t)strlen(_str))
{
}
std::string getLine()
{
const char* str = &m_str[m_pos];
skipLine();
const char* eol = &m_str[m_pos];
std::string tmp;
tmp.assign(str, eol - str);
return tmp;
}
bool isEof() const
{
return m_str[m_pos] == '\0';
}
void skipLine()
{
const char* str = &m_str[m_pos];
const char* nl = bx::strnl(str);
m_pos += (uint32_t)(nl - str);
}
const char* m_str;
uint32_t m_pos;
uint32_t m_size;
};
struct UniformType
{
enum Enum
{
Int1,
End,
Vec4,
Mat3,
Mat4,
Count
};
};
#define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10)
#define BGFX_UNIFORM_SAMPLERBIT UINT8_C(0x20)
const char* getUniformTypeName(UniformType::Enum _enum);
UniformType::Enum nameToUniformTypeEnum(const char* _name);
struct Uniform
{
std::string name;
UniformType::Enum type;
uint8_t num;
uint16_t regIndex;
uint16_t regCount;
};
typedef std::vector<Uniform> UniformArray;
void printCode(const char* _code, int32_t _line = 0, int32_t _start = 0, int32_t _end = INT32_MAX);
void strreplace(char* _str, const char* _find, const char* _replace);
int32_t writef(bx::WriterI* _writer, const char* _format, ...);
void writeFile(const char* _filePath, const void* _data, int32_t _size);
bool compileHLSLShader(bx::CommandLine& _cmdLine, uint32_t _d3d, const std::string& _code, bx::WriterI* _writer, bool firstPass = true);
bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer);
int compileShader(bx::CommandLine& _cmdLine, bx::ReaderSeekerI* _reader, bx::WriterI* _writer);
#endif // SHADERC_H_HEADER_GUARD

File diff suppressed because it is too large Load Diff

View File

@ -1,212 +0,0 @@
/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "shaderc.h"
#include "glsl-optimizer/src/glsl/glsl_optimizer.h"
bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer)
{
char ch = tolower(_cmdLine.findOption('\0', "type")[0]);
const glslopt_shader_type type = ch == 'f'
? kGlslOptShaderFragment
: (ch == 'c' ? kGlslOptShaderCompute : kGlslOptShaderVertex);
glslopt_target target = kGlslTargetOpenGL;
switch (_gles)
{
case BX_MAKEFOURCC('M', 'T', 'L', 0):
target = kGlslTargetMetal;
break;
case 2:
target = kGlslTargetOpenGLES20;
break;
case 3:
target = kGlslTargetOpenGLES30;
break;
default:
target = kGlslTargetOpenGL;
break;
}
glslopt_ctx* ctx = glslopt_initialize(target);
glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
if (!glslopt_get_status(shader) )
{
const char* log = glslopt_get_log(shader);
int32_t source = 0;
int32_t line = 0;
int32_t column = 0;
int32_t start = 0;
int32_t end = INT32_MAX;
if (3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
&& 0 != line)
{
start = bx::uint32_imax(1, line-10);
end = start + 20;
}
printCode(_code.c_str(), line, start, end);
fprintf(stderr, "Error: %s\n", log);
glslopt_cleanup(ctx);
return false;
}
const char* optimizedShader = glslopt_get_output(shader);
// Trim all directives.
while ('#' == *optimizedShader)
{
optimizedShader = bx::strnl(optimizedShader);
}
if (0 != _gles)
{
char* code = const_cast<char*>(optimizedShader);
strreplace(code, "gl_FragDepthEXT", "gl_FragDepth");
strreplace(code, "texture2DLodEXT", "texture2DLod");
strreplace(code, "texture2DProjLodEXT", "texture2DProjLod");
strreplace(code, "textureCubeLodEXT", "textureCubeLod");
strreplace(code, "texture2DGradEXT", "texture2DGrad");
strreplace(code, "texture2DProjGradEXT", "texture2DProjGrad");
strreplace(code, "textureCubeGradEXT", "textureCubeGrad");
strreplace(code, "shadow2DEXT", "shadow2D");
strreplace(code, "shadow2DProjEXT", "shadow2DProj");
}
UniformArray uniforms;
{
const char* parse = optimizedShader;
while (NULL != parse
&& *parse != '\0')
{
parse = bx::strws(parse);
const char* eol = strchr(parse, ';');
if (NULL != eol)
{
const char* qualifier = parse;
parse = bx::strws(bx::strword(parse) );
if (0 == strncmp(qualifier, "attribute", 9)
|| 0 == strncmp(qualifier, "varying", 7) )
{
// skip attributes and varyings.
parse = eol + 1;
continue;
}
if (0 != strncmp(qualifier, "uniform", 7) )
{
// end if there is no uniform keyword.
parse = NULL;
continue;
}
const char* precision = NULL;
const char* typen = parse;
if (0 == strncmp(typen, "lowp", 4)
|| 0 == strncmp(typen, "mediump", 7)
|| 0 == strncmp(typen, "highp", 5) )
{
precision = typen;
typen = parse = bx::strws(bx::strword(parse) );
}
BX_UNUSED(precision);
char uniformType[256];
parse = bx::strword(parse);
if (0 == strncmp(typen, "sampler", 7) )
{
strcpy(uniformType, "int");
}
else
{
bx::strlcpy(uniformType, typen, parse-typen+1);
}
const char* name = parse = bx::strws(parse);
char uniformName[256];
uint8_t num = 1;
const char* array = bx::strnstr(name, "[", eol-parse);
if (NULL != array)
{
bx::strlcpy(uniformName, name, array-name+1);
char arraySize[32];
const char* end = bx::strnstr(array, "]", eol-array);
bx::strlcpy(arraySize, array+1, end-array);
num = atoi(arraySize);
}
else
{
bx::strlcpy(uniformName, name, eol-name+1);
}
Uniform un;
un.type = nameToUniformTypeEnum(uniformType);
if (UniformType::Count != un.type)
{
BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);
un.name = uniformName;
un.num = num;
un.regIndex = 0;
un.regCount = num;
uniforms.push_back(un);
}
parse = eol + 1;
}
}
}
uint16_t count = (uint16_t)uniforms.size();
bx::write(_writer, count);
for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
{
const Uniform& un = *it;
uint8_t nameSize = (uint8_t)un.name.size();
bx::write(_writer, nameSize);
bx::write(_writer, un.name.c_str(), nameSize);
uint8_t uniformType = un.type;
bx::write(_writer, uniformType);
bx::write(_writer, un.num);
bx::write(_writer, un.regIndex);
bx::write(_writer, un.regCount);
BX_TRACE("%s, %s, %d, %d, %d"
, un.name.c_str()
, getUniformTypeName(un.type)
, un.num
, un.regIndex
, un.regCount
);
}
uint32_t shaderSize = (uint32_t)strlen(optimizedShader);
bx::write(_writer, shaderSize);
bx::write(_writer, optimizedShader, shaderSize);
uint8_t nul = 0;
bx::write(_writer, nul);
glslopt_cleanup(ctx);
return true;
}

View File

@ -1,683 +0,0 @@
/*
* Copyright 2011-2015 Branimir Karadzic. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "shaderc.h"
#if SHADERC_CONFIG_HLSL
#define INITGUID
#include <d3dcompiler.h>
#include <d3d11shader.h>
#ifndef D3D_SVF_USED
# define D3D_SVF_USED 2
#endif // D3D_SVF_USED
struct CTHeader
{
uint32_t Size;
uint32_t Creator;
uint32_t Version;
uint32_t Constants;
uint32_t ConstantInfo;
uint32_t Flags;
uint32_t Target;
};
struct CTInfo
{
uint32_t Name;
uint16_t RegisterSet;
uint16_t RegisterIndex;
uint16_t RegisterCount;
uint16_t Reserved;
uint32_t TypeInfo;
uint32_t DefaultValue;
};
struct CTType
{
uint16_t Class;
uint16_t Type;
uint16_t Rows;
uint16_t Columns;
uint16_t Elements;
uint16_t StructMembers;
uint32_t StructMemberInfo;
};
struct RemapInputSemantic
{
bgfx::Attrib::Enum m_attr;
const char* m_name;
uint8_t m_index;
};
static const RemapInputSemantic s_remapInputSemantic[bgfx::Attrib::Count+1] =
{
{ bgfx::Attrib::Position, "POSITION", 0 },
{ bgfx::Attrib::Normal, "NORMAL", 0 },
{ bgfx::Attrib::Tangent, "TANGENT", 0 },
{ bgfx::Attrib::Bitangent, "BITANGENT", 0 },
{ bgfx::Attrib::Color0, "COLOR", 0 },
{ bgfx::Attrib::Color1, "COLOR", 1 },
{ bgfx::Attrib::Indices, "BLENDINDICES", 0 },
{ bgfx::Attrib::Weight, "BLENDWEIGHT", 0 },
{ bgfx::Attrib::TexCoord0, "TEXCOORD", 0 },
{ bgfx::Attrib::TexCoord1, "TEXCOORD", 1 },
{ bgfx::Attrib::TexCoord2, "TEXCOORD", 2 },
{ bgfx::Attrib::TexCoord3, "TEXCOORD", 3 },
{ bgfx::Attrib::TexCoord4, "TEXCOORD", 4 },
{ bgfx::Attrib::TexCoord5, "TEXCOORD", 5 },
{ bgfx::Attrib::TexCoord6, "TEXCOORD", 6 },
{ bgfx::Attrib::TexCoord7, "TEXCOORD", 7 },
{ bgfx::Attrib::Count, "", 0 },
};
const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
{
for (uint32_t ii = 0; ii < bgfx::Attrib::Count; ++ii)
{
const RemapInputSemantic& ris = s_remapInputSemantic[ii];
if (0 == strcmp(ris.m_name, _name)
&& ris.m_index == _index)
{
return ris;
}
}
return s_remapInputSemantic[bgfx::Attrib::Count];
}
struct UniformRemap
{
UniformType::Enum id;
D3D_SHADER_VARIABLE_CLASS paramClass;
D3D_SHADER_VARIABLE_TYPE paramType;
uint8_t columns;
uint8_t rows;
};
static const UniformRemap s_uniformRemap[] =
{
{ UniformType::Int1, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
{ UniformType::Vec4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
{ UniformType::Mat3, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
{ UniformType::Mat4, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
{ UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER, 0, 0 },
{ UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER2D, 0, 0 },
{ UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER3D, 0, 0 },
{ UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLERCUBE, 0, 0 },
};
UniformType::Enum findUniformType(const D3D11_SHADER_TYPE_DESC& constDesc)
{
for (uint32_t ii = 0; ii < BX_COUNTOF(s_uniformRemap); ++ii)
{
const UniformRemap& remap = s_uniformRemap[ii];
if (remap.paramClass == constDesc.Class
&& remap.paramType == constDesc.Type)
{
if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
{
return remap.id;
}
if (remap.columns == constDesc.Columns
&& remap.rows == constDesc.Rows)
{
return remap.id;
}
}
}
return UniformType::Count;
}
static uint32_t s_optimizationLevelDx11[4] =
{
D3DCOMPILE_OPTIMIZATION_LEVEL0,
D3DCOMPILE_OPTIMIZATION_LEVEL1,
D3DCOMPILE_OPTIMIZATION_LEVEL2,
D3DCOMPILE_OPTIMIZATION_LEVEL3,
};
typedef std::vector<std::string> UniformNameList;
static bool isSampler(D3D_SHADER_VARIABLE_TYPE _svt)
{
switch (_svt)
{
case D3D_SVT_SAMPLER:
case D3D_SVT_SAMPLER1D:
case D3D_SVT_SAMPLER2D:
case D3D_SVT_SAMPLER3D:
case D3D_SVT_SAMPLERCUBE:
return true;
default:
break;
}
return false;
}
bool getReflectionDataDx9(ID3DBlob* _code, UniformArray& _uniforms)
{
// see reference for magic values: https://msdn.microsoft.com/en-us/library/ff552891(VS.85).aspx
const uint32_t D3DSIO_COMMENT = 0x0000FFFE;
const uint32_t D3DSIO_END = 0x0000FFFF;
const uint32_t D3DSI_OPCODE_MASK = 0x0000FFFF;
const uint32_t D3DSI_COMMENTSIZE_MASK = 0x7FFF0000;
const uint32_t CTAB_CONSTANT = MAKEFOURCC('C','T','A','B');
// parse the shader blob for the constant table
const size_t codeSize = _code->GetBufferSize();
const uint32_t* ptr = (const uint32_t*)_code->GetBufferPointer();
const uint32_t* end = (const uint32_t*)( (const uint8_t*)ptr + codeSize);
const CTHeader* header = NULL;
ptr++; // first byte is shader type / version; skip it since we already know
while (ptr < end && *ptr != D3DSIO_END)
{
uint32_t cur = *ptr++;
if ( (cur & D3DSI_OPCODE_MASK) != D3DSIO_COMMENT)
{
continue;
}
// try to find CTAB comment block
uint32_t commentSize = (cur & D3DSI_COMMENTSIZE_MASK) >> 16;
uint32_t fourcc = *ptr;
if (fourcc == CTAB_CONSTANT)
{
// found the constant table data
header = (const CTHeader*)(ptr + 1);
uint32_t tableSize = (commentSize - 1) * 4;
if (tableSize < sizeof(CTHeader) || header->Size != sizeof(CTHeader) )
{
fprintf(stderr, "Error: Invalid constant table data\n");
return false;
}
break;
}
// this is a different kind of comment section, so skip over it
ptr += commentSize - 1;
}
if (!header)
{
fprintf(stderr, "Error: Could not find constant table data\n");
return false;
}
const uint8_t* headerBytePtr = (const uint8_t*)header;
const char* creator = (const char*)(headerBytePtr + header->Creator);
BX_TRACE("Creator: %s 0x%08x", creator, header->Version);
BX_TRACE("Num constants: %d", header->Constants);
BX_TRACE("# cl ty RxC S By Name");
const CTInfo* ctInfoArray = (const CTInfo*)(headerBytePtr + header->ConstantInfo);
for (uint32_t ii = 0; ii < header->Constants; ++ii)
{
const CTInfo& ctInfo = ctInfoArray[ii];
const CTType& ctType = *(const CTType*)(headerBytePtr + ctInfo.TypeInfo);
const char* name = (const char*)(headerBytePtr + ctInfo.Name);
BX_TRACE("%3d %2d %2d [%dx%d] %d %s[%d] c%d (%d)"
, ii
, ctType.Class
, ctType.Type
, ctType.Rows
, ctType.Columns
, ctType.StructMembers
, name
, ctType.Elements
, ctInfo.RegisterIndex
, ctInfo.RegisterCount
);
D3D11_SHADER_TYPE_DESC desc;
desc.Class = (D3D_SHADER_VARIABLE_CLASS)ctType.Class;
desc.Type = (D3D_SHADER_VARIABLE_TYPE)ctType.Type;
desc.Rows = ctType.Rows;
desc.Columns = ctType.Columns;
UniformType::Enum type = findUniformType(desc);
if (UniformType::Count != type)
{
Uniform un;
un.name = '$' == name[0] ? name + 1 : name;
un.type = isSampler(desc.Type)
? UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | type)
: type
;
un.num = (uint8_t)ctType.Elements;
un.regIndex = ctInfo.RegisterIndex;
un.regCount = ctInfo.RegisterCount;
_uniforms.push_back(un);
}
}
return true;
}
bool getReflectionDataDx11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms)
{
ID3D11ShaderReflection* reflect = NULL;
HRESULT hr = D3DReflect(_code->GetBufferPointer()
, _code->GetBufferSize()
, IID_ID3D11ShaderReflection
, (void**)&reflect
);
if (FAILED(hr) )
{
fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr);
return false;
}
D3D11_SHADER_DESC desc;
hr = reflect->GetDesc(&desc);
if (FAILED(hr) )
{
fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
return false;
}
BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
BX_TRACE("Input:");
if (_vshader) // Only care about input semantic on vertex shaders
{
for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
{
D3D11_SIGNATURE_PARAMETER_DESC spd;
reflect->GetInputParameterDesc(ii, &spd);
BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
, ii
, spd.SemanticName
, spd.SemanticIndex
, spd.SystemValueType
, spd.ComponentType
, spd.Mask
, spd.Register
);
const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
if (ris.m_attr != bgfx::Attrib::Count)
{
_attrs[_numAttrs] = bgfx::attribToId(ris.m_attr);
++_numAttrs;
}
}
}
BX_TRACE("Output:");
for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
{
D3D11_SIGNATURE_PARAMETER_DESC spd;
reflect->GetOutputParameterDesc(ii, &spd);
BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
}
for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii)
{
ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
D3D11_SHADER_BUFFER_DESC bufferDesc;
hr = cbuffer->GetDesc(&bufferDesc);
_size = (uint16_t)bufferDesc.Size;
if (SUCCEEDED(hr) )
{
BX_TRACE("%s, %d, vars %d, size %d"
, bufferDesc.Name
, bufferDesc.Type
, bufferDesc.Variables
, bufferDesc.Size
);
for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
{
ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
ID3D11ShaderReflectionType* type = var->GetType();
D3D11_SHADER_VARIABLE_DESC varDesc;
hr = var->GetDesc(&varDesc);
if (SUCCEEDED(hr) )
{
D3D11_SHADER_TYPE_DESC constDesc;
hr = type->GetDesc(&constDesc);
if (SUCCEEDED(hr) )
{
UniformType::Enum uniformType = findUniformType(constDesc);
if (UniformType::Count != uniformType
&& 0 != (varDesc.uFlags & D3D_SVF_USED) )
{
Uniform un;
un.name = varDesc.Name;
un.type = uniformType;
un.num = constDesc.Elements;
un.regIndex = varDesc.StartOffset;
un.regCount = BX_ALIGN_16(varDesc.Size) / 16;
_uniforms.push_back(un);
BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)"
, varDesc.Name
, varDesc.StartOffset
, varDesc.Size
, varDesc.uFlags
, uniformType
);
}
else
{
if (0 == (varDesc.uFlags & D3D_SVF_USED) )
{
unusedUniforms.push_back(varDesc.Name);
}
BX_TRACE("\t%s, unknown type", varDesc.Name);
}
}
}
}
}
}
BX_TRACE("Bound:");
for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
{
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
if (SUCCEEDED(hr) )
{
if (D3D_SIT_SAMPLER == bindDesc.Type)
{
BX_TRACE("\t%s, %d, %d, %d"
, bindDesc.Name
, bindDesc.Type
, bindDesc.BindPoint
, bindDesc.BindCount
);
const char * end = strstr(bindDesc.Name, "Sampler");
if (NULL != end)
{
Uniform un;
un.name.assign(bindDesc.Name, (end - bindDesc.Name) );
un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | UniformType::Int1);
un.num = 1;
un.regIndex = bindDesc.BindPoint;
un.regCount = bindDesc.BindCount;
_uniforms.push_back(un);
}
}
}
}
if (NULL != reflect)
{
reflect->Release();
}
return true;
}
bool compileHLSLShader(bx::CommandLine& _cmdLine, uint32_t _d3d, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
{
BX_TRACE("DX11");
const char* profile = _cmdLine.findOption('p', "profile");
if (NULL == profile)
{
fprintf(stderr, "Shader profile must be specified.\n");
return false;
}
bool debug = _cmdLine.hasArg('\0', "debug");
uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
flags |= debug ? D3DCOMPILE_DEBUG : 0;
flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
bool werror = _cmdLine.hasArg('\0', "Werror");
if (werror)
{
flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
}
uint32_t optimization = 3;
if (_cmdLine.hasArg(optimization, 'O') )
{
optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
flags |= s_optimizationLevelDx11[optimization];
}
else
{
flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
}
BX_TRACE("Profile: %s", profile);
BX_TRACE("Flags: 0x%08x", flags);
ID3DBlob* code;
ID3DBlob* errorMsg;
// Output preprocessed shader so that HLSL can be debugged via GPA
// or PIX. Compiling through memory won't embed preprocessed shader
// file path.
std::string hlslfp;
if (debug)
{
hlslfp = _cmdLine.findOption('o');
hlslfp += ".hlsl";
writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
}
HRESULT hr = D3DCompile(_code.c_str()
, _code.size()
, hlslfp.c_str()
, NULL
, NULL
, "main"
, profile
, flags
, 0
, &code
, &errorMsg
);
if (FAILED(hr)
|| (werror && NULL != errorMsg) )
{
const char* log = (char*)errorMsg->GetBufferPointer();
int32_t line = 0;
int32_t column = 0;
int32_t start = 0;
int32_t end = INT32_MAX;
if (2 == sscanf(log, "(%u,%u):", &line, &column)
&& 0 != line)
{
start = bx::uint32_imax(1, line-10);
end = start + 20;
}
printCode(_code.c_str(), line, start, end);
fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
errorMsg->Release();
return false;
}
UniformArray uniforms;
uint8_t numAttrs = 0;
uint16_t attrs[bgfx::Attrib::Count];
uint16_t size = 0;
if (_d3d == 9)
{
if (!getReflectionDataDx9(code, uniforms) )
{
return false;
}
}
else
{
UniformNameList unusedUniforms;
if (!getReflectionDataDx11(code, profile[0] == 'v', uniforms, numAttrs, attrs, size, unusedUniforms) )
{
return false;
}
if (_firstPass
&& unusedUniforms.size() > 0)
{
const size_t strLength = strlen("uniform");
// first time through, we just find unused uniforms and get rid of them
std::string output;
LineReader reader(_code.c_str() );
while (!reader.isEof() )
{
std::string line = reader.getLine();
for (UniformNameList::iterator it = unusedUniforms.begin(), itEnd = unusedUniforms.end(); it != itEnd; ++it)
{
size_t index = line.find("uniform ");
if (index == std::string::npos)
{
continue;
}
// matching lines like: uniform u_name;
// we want to replace "uniform" with "static" so that it's no longer
// included in the uniform blob that the application must upload
// we can't just remove them, because unused functions might still reference
// them and cause a compile error when they're gone
if (!!bx::findIdentifierMatch(line.c_str(), it->c_str() ) )
{
line = line.replace(index, strLength, "static");
unusedUniforms.erase(it);
break;
}
}
output += line;
}
// recompile with the unused uniforms converted to statics
return compileHLSLShader(_cmdLine, _d3d, output.c_str(), _writer, false);
}
}
uint16_t count = (uint16_t)uniforms.size();
bx::write(_writer, count);
uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
{
const Uniform& un = *it;
uint8_t nameSize = (uint8_t)un.name.size();
bx::write(_writer, nameSize);
bx::write(_writer, un.name.c_str(), nameSize);
uint8_t type = un.type|fragmentBit;
bx::write(_writer, type);
bx::write(_writer, un.num);
bx::write(_writer, un.regIndex);
bx::write(_writer, un.regCount);
BX_TRACE("%s, %s, %d, %d, %d"
, un.name.c_str()
, getUniformTypeName(un.type)
, un.num
, un.regIndex
, un.regCount
);
}
{
ID3DBlob* stripped;
hr = D3DStripShader(code->GetBufferPointer()
, code->GetBufferSize()
, D3DCOMPILER_STRIP_REFLECTION_DATA
| D3DCOMPILER_STRIP_TEST_BLOBS
, &stripped
);
if (SUCCEEDED(hr) )
{
code->Release();
code = stripped;
}
}
uint16_t shaderSize = (uint16_t)code->GetBufferSize();
bx::write(_writer, shaderSize);
bx::write(_writer, code->GetBufferPointer(), shaderSize);
uint8_t nul = 0;
bx::write(_writer, nul);
if (_d3d > 9)
{
bx::write(_writer, numAttrs);
bx::write(_writer, attrs, numAttrs*sizeof(uint16_t) );
bx::write(_writer, size);
}
if (_cmdLine.hasArg('\0', "disasm") )
{
ID3DBlob* disasm;
D3DDisassemble(code->GetBufferPointer()
, code->GetBufferSize()
, 0
, NULL
, &disasm
);
if (NULL != disasm)
{
std::string disasmfp = _cmdLine.findOption('o');
disasmfp += ".disasm";
writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
disasm->Release();
}
}
if (NULL != errorMsg)
{
errorMsg->Release();
}
code->Release();
return true;
}
#else
bool compileHLSLShader(bx::CommandLine& _cmdLine, uint32_t _d3d, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
{
BX_UNUSED(_cmdLine, _d3d, _code, _writer, _firstPass);
fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
return false;
}
#endif // SHADERC_CONFIG_HLSL