hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23edbb26a26cff4b9109f3ae75199b84dbcf42f3 | 9,280 | cpp | C++ | Matrix.cpp | JSebastianZ/RayTracer | e720bd00811d01d28fab8ad9e295623c7a9bc284 | [
"MIT"
] | null | null | null | Matrix.cpp | JSebastianZ/RayTracer | e720bd00811d01d28fab8ad9e295623c7a9bc284 | [
"MIT"
] | 1 | 2020-06-17T05:08:30.000Z | 2020-06-17T05:08:30.000Z | Matrix.cpp | JSebastianZ/RayTracer | e720bd00811d01d28fab8ad9e295623c7a9bc284 | [
"MIT"
] | null | null | null | #include "Matrix.h"
using namespace rt;
// Matrix dimension parameters.
int m_rows{ 0 };
int m_columns{ 0 };
int size{ 0 };
// A matrix is implemented as a two dimensional array of real numbers.
void Matrix::create_matrix(int rows, int columns) {
this->matrix = new real * [rows]();
for (int i = 0; i < rows; ++i)
matrix[i] = new real[columns]();
};
// Default constructor is an identity matrix of size 4.
Matrix::Matrix() { identity(4); };
// Construct an square matrix with specified size.
Matrix::Matrix(int size) : m_rows{ size }, m_columns{ size }, size{ size } {
create_matrix(m_rows, m_columns);
};
// Construct matrix with specified dimensions.
Matrix::Matrix(int rows, int columns) : m_rows{ rows }, m_columns{ columns }{
create_matrix(m_rows, m_columns);
};
// Returns the value stored at position 'xy' in the matrix.
real Matrix::valueAt(int x, int y) {
return matrix[x][y];
};
// Evaluates if two matrices are identical.
bool Matrix::identical_matrix(const Matrix& a, const Matrix& b) {
if (a.m_rows != b.m_rows || a.m_columns != b.m_columns)
return false;
for (int i = 0; i < a.m_rows; i++) {
for (int j = 0; j < a.m_columns; j++) {
if (a.matrix[i][j] != b.matrix[i][j]) {
return false;
}
}
}
return true;
};
// Creates an identity matrix of the specified size.
Matrix Matrix::identity(int size) {
Matrix m{ size };
for (int i = 0; i < m.size; i++)
for (int j = 0; j < m.size; j++)
if (i == j) m.matrix[i][j] = 1; else m.matrix[i][j] = 0;
return m;
};
// Multiplies two matrices - AxB - and returns the resulting matrix.
Matrix Matrix::multiplyMatrices(const Matrix& a, const Matrix& b) {
Matrix c{ a.size };
real x = 0;
for (int i = 0; i < a.m_rows; i++) {
for (int j = 0; j < b.m_columns; j++) {
for (int f = 0; f < b.m_rows; f++) {
x += a.matrix[i][f] * b.matrix[f][j];
}
c.matrix[i][j] = x;
x = 0;
}
}
return c;
};
// Multiplies a matrix by a Point.
Point Matrix::multiply_point(const Matrix& a,const Point& b) {
Point t;
t.m_x = a.matrix[0][0] * b.m_x + a.matrix[0][1] * b.m_y + a.matrix[0][2] * b.m_z + a.matrix[0][3] * b.m_w;
t.m_y = a.matrix[1][0] * b.m_x + a.matrix[1][1] * b.m_y + a.matrix[1][2] * b.m_z + a.matrix[1][3] * b.m_w;
t.m_z = a.matrix[2][0] * b.m_x + a.matrix[2][1] * b.m_y + a.matrix[2][2] * b.m_z + a.matrix[2][3] * b.m_w;
t.m_w = 1;
return t;
};
// Multiplies a matrix by a Vector.
Vector Matrix::multiply_vector(const Matrix& a,const Vector& b) {
Vector t;
t.m_x = a.matrix[0][0] * b.m_x + a.matrix[0][1] * b.m_y + a.matrix[0][2] * b.m_z + a.matrix[0][3] * b.m_w;
t.m_y = a.matrix[1][0] * b.m_x + a.matrix[1][1] * b.m_y + a.matrix[1][2] * b.m_z + a.matrix[1][3] * b.m_w;
t.m_z = a.matrix[2][0] * b.m_x + a.matrix[2][1] * b.m_y + a.matrix[2][2] * b.m_z + a.matrix[2][3] * b.m_w;
t.m_w = 0;
return t;
};
// Multiplies a matrix by an identity matrix, and returns the resulting matrix.
Matrix Matrix::multiplyIdentity(const Matrix& a) {
Matrix m{ a.size };
m = identity(m.size);
return multiplyMatrices(a, m);
};
// Returns the transpose of matrix A.
Matrix Matrix::transpose(Matrix a) {
Matrix t(a.size);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
t.matrix[i][j] = a.matrix[j][i];
return t;
};
// Returns the submatrix XY of matrix M.
Matrix Matrix::submatrix(const Matrix& m, int x, int y) {
Matrix sm{ m.size - 1 };
int row = 0;
int col = 0;
for (int i = 0; i < sm.size; i++, ++row) {
if (i == x) ++row;
for (int j = 0; j < sm.size; j++, ++col) {
if (j == y) ++col;
sm.matrix[i][j] = m.matrix[row][col];
}
col = 0;
}
return sm;
};
// Returns the determinant of matrix M.
real Matrix::determinant(const Matrix& m) {
real deter{ 0 };
real minor{ 0 };
Matrix matrix{ m.size };
for (int i = 0; i < matrix.size; i++) {
for (int j = 0; j < matrix.size; j++) {
matrix.matrix[i][j] = m.matrix[i][j];
}
}
if (matrix.size == 2) {
deter = matrix.matrix[0][0] * matrix.matrix[1][1] - matrix.matrix[0][1] * matrix.matrix[1][0];
return deter;
}
for (int i = 0; i < matrix.size; i++) {
Matrix x = submatrix(matrix, 0, i);
if (i % 2 == 0) minor += matrix.matrix[0][i] * determinant(x);
else minor += (-1 * matrix.matrix[0][i] * determinant(x));
}
deter = minor;
return deter;
};
// Returns the Cofactor Matrix of matrix M.
Matrix Matrix::cofactorMatrix(const Matrix& m) {
real minor{ 0 };
Matrix matrix{ m.size };
Matrix cm{ m.size };
for (int i = 0; i < matrix.size; i++) {
for (int j = 0; j < matrix.size; j++) {
matrix.matrix[i][j] = m.matrix[i][j];
}
}
if (matrix.size == 2) {
minor = matrix.matrix[0][0] * matrix.matrix[1][1] - matrix.matrix[0][1] * matrix.matrix[1][0];
return minor;
}
for (int i = 0; i < matrix.size; i++) {
for (int j = 0; j < matrix.size; j++) {
Matrix x = submatrix(matrix, i, j);
if ((i + j) % 2 == 0) minor = determinant(x);
else minor = (-1 * determinant(x));
cm.matrix[i][j] = minor;
}
}
return cm;
};
// Returns the Inverse matrix of matrix A.
Matrix Matrix::inverse(const Matrix& a) {
real d{ determinant(a) };
Matrix cofactor{ cofactorMatrix(a) };
Matrix t{ transpose(cofactor) };
Matrix inverse{ a.size };
for (int i = 0; i < a.size; i++) {
for (int j = 0; j < a.size; j++) {
inverse.matrix[i][j] = t.matrix[i][j] / d;
}
}
return inverse;
};
// Returns the Translation matrix to point P.
Matrix Matrix::translation_matrix_p(const Point& p) {
Matrix t{ identity(4) };
t.matrix[0][3] = p.m_x;
t.matrix[1][3] = p.m_y;
t.matrix[2][3] = p.m_z;
t.matrix[3][3] = p.m_w;
return t;
};
// Returns the Translation matrix to vector V.
Matrix Matrix::translation_matrix_v(const Vector& v) {
Matrix t{ 4 };
t = identity(4);
t.matrix[0][3] = v.m_x;
t.matrix[1][3] = v.m_y;
t.matrix[2][3] = v.m_z;
t.matrix[3][3] = v.m_w;
return t;
};
// Returns an identity matrix scaled by point P xyz values.
Matrix Matrix::scaling_matrix_p(const Point& p) {
Matrix s{ 4 };
s = identity(4);
s.matrix[0][0] = p.m_x;
s.matrix[1][1] = p.m_y;
s.matrix[2][2] = p.m_z;
s.matrix[3][3] = p.m_w;
return s;
};
// Returns an identity matrix scaled by vector V xyz values.
Matrix Matrix::scaling_matrix_v(const Vector& v) {
Matrix s{ 4 };
s = identity(4);
s.matrix[0][0] = v.m_x;
s.matrix[1][1] = v.m_y;
s.matrix[2][2] = v.m_z;
s.matrix[3][3] = v.m_w;
return s;
};
// Returns an identity matrix rotated around the X axis by D degrees.
Matrix Matrix::rotation_matrix_x(const real& d) {
Matrix r{ identity(4) };
r.matrix[1][1] = cos(d);
r.matrix[1][2] = (-1 * sin(d));
r.matrix[2][1] = sin(d);
r.matrix[2][2] = cos(d);
return r;
};
// Returns an identity matrix rotated around the Y axis by D degrees.
Matrix Matrix::rotation_matrix_y(const real& d) {
Matrix r{ identity(4) };
r.matrix[0][0] = cos(d);
r.matrix[0][2] = sin(d);
r.matrix[2][0] = (-1 * sin(d));
r.matrix[2][2] = cos(d);
return r;
};
// Returns an identity matrix rotated around the Z axis by D degrees.
Matrix Matrix::rotation_matrix_z(const real& d) {
Matrix r{ 4 };
r = identity(4);
r.matrix[0][0] = cos(d);
r.matrix[0][1] = (-1 * sin(d));
r.matrix[1][0] = sin(d);
r.matrix[1][1] = cos(d);
return r;
};
// Returns an identity matrix sheared according to the specified values.
Matrix Matrix::shearing_matrix(const real& xy, const real& xz, const real& yx,
const real& yz, const real& zx, const real& zy)
{
Matrix s{ 4 };
s = identity(4);
s.matrix[0][1] = xy;
s.matrix[0][2] = xz;
s.matrix[1][0] = yx;
s.matrix[1][2] = yz;
s.matrix[2][0] = zx;
s.matrix[2][1] = zy;
return s;
};
// Returns a transformation matrix that orients the 3D scene relative to the viewer.
Matrix Matrix::view_transform(Point& from, Point& to, const Vector& up) {
Vector forward(Point::subPoints(to, from));
Vector upn = Vector::normalize(up);
Vector left = Vector::crossProduct(forward, upn);
Vector true_up = Vector::crossProduct(left, forward);
true_up = Vector::normalize(true_up);
forward = Vector::normalize(forward);
left = Vector::normalize(left);
Matrix orientation = Matrix(4);
orientation.matrix[0][0] = left.m_x;
orientation.matrix[0][1] = left.m_y;
orientation.matrix[0][2] = left.m_z;
orientation.matrix[0][3] = 0;
orientation.matrix[1][0] = true_up.m_x;
orientation.matrix[1][1] = true_up.m_y;
orientation.matrix[1][2] = true_up.m_z;
orientation.matrix[1][3] = 0;
orientation.matrix[2][0] = -forward.m_x;
orientation.matrix[2][1] = -forward.m_y;
orientation.matrix[2][2] = -forward.m_z;
orientation.matrix[2][3] = 0;
orientation.matrix[3][0] = 0;
orientation.matrix[3][1] = 0;
orientation.matrix[3][2] = 0;
orientation.matrix[3][3] = 1;
Matrix translation = Matrix::translation_matrix_p(Point::scalarMultiplication(from, -1));
return Matrix::multiplyMatrices(orientation, translation);
}; | 30.326797 | 108 | 0.586207 | [
"vector",
"3d"
] |
23eee6dea3863513b31fdebb434b4977bac6a6d4 | 455 | cpp | C++ | opt/sloop_2.cpp | aki-ph-chem/rot_const | 7f05e252d15e4b30bfd9ec0627a239154f7fb468 | [
"MIT"
] | null | null | null | opt/sloop_2.cpp | aki-ph-chem/rot_const | 7f05e252d15e4b30bfd9ec0627a239154f7fb468 | [
"MIT"
] | null | null | null | opt/sloop_2.cpp | aki-ph-chem/rot_const | 7f05e252d15e4b30bfd9ec0627a239154f7fb468 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include"sloop_2.h"
void sloop::set(double sign_h,double x_0,double h_0){
h = h_0;
h = sign_h*h;
x_now = x_0 + h;
}
void sloop::forward(){
//h = 2*h;
x_now = x_now + h;
}
void sloop::Memo(std::vector<std::vector<double>>& Result,
std::vector<double>& Res_set ){
Res_set[0] = x_now;
Res_set[1] = f;
Res_set[2] = dx_f;
Result.push_back(Res_set);
} | 16.25 | 59 | 0.564835 | [
"vector"
] |
23f42337e28e6a748b0a27e4613c2f2e5167c9f7 | 448 | cpp | C++ | Streams/InputUntilFail/main.cpp | ilyayunkin/CppSandbox | b03fd84462faa16b6c3ca03c1639fcbe0be361cf | [
"MIT"
] | null | null | null | Streams/InputUntilFail/main.cpp | ilyayunkin/CppSandbox | b03fd84462faa16b6c3ca03c1639fcbe0be361cf | [
"MIT"
] | null | null | null | Streams/InputUntilFail/main.cpp | ilyayunkin/CppSandbox | b03fd84462faa16b6c3ca03c1639fcbe0be361cf | [
"MIT"
] | null | null | null | #include <QCoreApplication>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::vector<double> v;
double value;
cout << "Input values:";
while(cin >> value){
v.push_back(value);
}
auto average = accumulate(v.begin(), v.end(), 0.) / v.size();
cout << "Average value is: " << average;
return a.exec();
}
| 21.333333 | 65 | 0.611607 | [
"vector"
] |
6712402a21e53f4a50bf560fcc797fd8035bd8ff | 1,258 | cpp | C++ | Cpp/ConnectedComponents.cpp | akshat-6397/hacktoberfest2021-easy | 4e71ab3cfc5e5514d81ca3eaacd8c6e2483cb703 | [
"MIT"
] | 15 | 2021-10-05T08:12:12.000Z | 2021-10-20T07:54:23.000Z | Cpp/ConnectedComponents.cpp | akshat-6397/hacktoberfest2021-easy | 4e71ab3cfc5e5514d81ca3eaacd8c6e2483cb703 | [
"MIT"
] | 18 | 2021-10-05T08:09:12.000Z | 2021-10-20T07:47:43.000Z | Cpp/ConnectedComponents.cpp | akshat-6397/hacktoberfest2021-easy | 4e71ab3cfc5e5514d81ca3eaacd8c6e2483cb703 | [
"MIT"
] | 54 | 2021-10-05T07:49:59.000Z | 2021-12-07T17:18:07.000Z | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
#define f(n) for (int i = 0; i < n; i++)
#define inf 1e18
#define mid(l, r) (l + (r - l) / 2)
typedef vector<int> vi;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef unordered_map<int, int> ump;
//#define w(x) int x; cin>>x; while(x--)
const int N = 1e5 + 5;
bool vis[N];
vi g[N];
void dfs(int vertex)
{
/* take action on vertex after entering it*/
vis[vertex] = true;
for (auto child : g[vertex])
{
if (vis[child])
continue;
// take action on child before entering the child node
dfs(child);
// take action on child after exiting the child node
}
// take action on vertex before exiting the vertex
}
int32_t main()
{
// Number of DFS calls = number of connected components
int n, e;
cin >> n >> e;
for (int i = 0; i < e; i++)
{
int u, v;
cin >> u >> v;
g[u].pb(v);
g[v].pb(u);
}
int count = 0;
for (int i = 1; i <= n; i++)
{
if (vis[i])
continue;
dfs(i);
count++;
}
cout << "Number of connected components in the Forest = " << count << endl;
return 0;
}
| 22.464286 | 79 | 0.544515 | [
"vector"
] |
671cfaa4073bc8066a019ddd96ac053f4a07c103 | 7,070 | cpp | C++ | main.cpp | vlee489/AC21009-Coursework-2 | 2b32dbc5405408fc5a7173cd43490ec21c388555 | [
"MIT"
] | null | null | null | main.cpp | vlee489/AC21009-Coursework-2 | 2b32dbc5405408fc5a7173cd43490ec21c388555 | [
"MIT"
] | null | null | null | main.cpp | vlee489/AC21009-Coursework-2 | 2b32dbc5405408fc5a7173cd43490ec21c388555 | [
"MIT"
] | null | null | null | // Imports the header file for this individual source file
#include "main.hpp"
// Imports error codes
#include "error.hpp"
// Imports game of life
#include "gameOfLife.hpp"
// Imports methods which allows the user to set their own generation
#include "generation.hpp"
// Imports methods to handle user input and output
#include "inputOutput.hpp"
// Imports Langton's Ant
#include "LangtonsAnt.hpp"
// Imports methods to generate rules and convert numbers to binary and decimal
#include "rule.hpp"
// Imports table class to handle storage of data
#include "table.hpp"
// Used for sleeping
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Main Function
int main() {
clearScreen();
// Keeps running
while (true) {
// Initialises objects that are not already initialised
initObjects(false);
// Displays the main menu and processes user input
menuInt(displayMenu, processMenu);
}
return 0;
}
// Initialises global objects for each external class
// But only does so, if it is yet uninitialised or the erase flag is turned on
void initObjects(bool erase) {
if (fullTable == nullptr || erase) {
fullTable = new Table();
}
if (ruleObj == nullptr || erase) {
ruleObj = new Rule();
}
if (generationObj == nullptr || erase) {
generationObj = new Generation();
}
}
// Displays the main menu
void displayMenu() {
cout << "Cellular Automaton Program" << endl;
cout << "Module Code: AC210009" << endl;
cout << "Authors: Max Kelly, Vincent Lee and Ramsay Sewell" << endl;
cout << "Assignment 2";
cout << endl;
cout << endl;
cout << "1. Create your own cellular automaton" << endl;
cout << "2. Load a cellular automaton from a file" << endl;
cout << "3. Save a cellular automaton to a file" << endl;
cout << "4. Conway's Game of Life" << endl;
cout << "5. Langton's Ant" << endl;
cout << "0. Exit" << endl;
cout << "Choose an option from the list: ";
}
// Processes the user's chosen operation
bool processMenu(int choice) {
switch (choice) {
case 1:
// Lets the user create and setup their own cellular automaton
createAutomaton();
break;
case 2:
// Allows the user to load a previously saved cellular automaton
loadAutomaton();
break;
case 3:
// Allows the user to save their cellular automaton to an external file
saveAutomaton();
break;
case 4:
// Runs a simulation of Conway's Game of Life
gameOfLife();
break;
case 5:
LangtonsAnt();
break;
case 0:
// Exits the program
exit(0);
default:
// Runs if the user's input is invalid
return false;
}
// Runs if the user's input is valid
return true;
}
// Lets the user create and setup their own cellular automaton
void createAutomaton() {
// Initialises all objects, clearing previous data
initObjects(true);
clearScreen();
// Gets the rule number from the user
int rule =
promptIntRange("Please enter the desired rule you want to use", 0, 255);
// Gets the number of generations from the user
int generations =
promptIntRange("Please enter the desired generations you want", 0, 100);
// Allows the user to set a first generation
generationObj->firstGenerator();
// Extracts the first generation the user's set from the generation object
vector<bool>* firstGen = generationObj->returnGen();
// checkValidity: Checks if the operation returns an error code, if it does,
// it prints it to the screen and stops the program
// Initialises the table with the appropriate first generation and size
checkValidity(fullTable->initTable(*firstGen, generations));
// Sets the rule we are using in the rule object
checkValidity(ruleObj->setRule(rule));
// Gets the width of the array in the table object
int arrayWidth = fullTable->getArrayWidth();
// Counts through each row except the first which already has a first
// generation
for (int row = 1; row < generations; row++) {
// Counts through each column
for (int col = 0; col < arrayWidth; col++) {
// Stores the neighbourhood of the current field
bool* neighbourhood = fullTable->getNeighbourhood(col, row);
// Calculates the value of the current field based on the neighbourhood
bool cell = ruleObj->generateCell(neighbourhood);
// Stores the value in the table
checkValidity(fullTable->setVal(col, row, cell));
// Deletes the neighbourhood we extracted
delete neighbourhood;
}
}
cout << endl;
// Displays the finished table to the user
checkValidity(fullTable->printTable());
}
// Allows the user to load a previously saved cellular automaton
void loadAutomaton() {
// Initialises all objects, clearing previous data
initObjects(true);
clearScreen();
// Asks the user what file we should load and loads it
promptStr("What is the path of the file you'd like to load?", processLoad);
}
// Processes loading a table from a file
bool processLoad(string filename) {
// Loads the table from the file and displays an error if this is unsuccessful
checkValidity(fullTable->loadTable(filename));
cout << "Loading file successful" << endl << endl;
// Prints the loaded table to the screen if the table has been initialised
checkValidity(fullTable->printTable());
return true;
}
// Allows the user to save their cellular automaton to an external file
void saveAutomaton() {
clearScreen();
// Asks the user what file we should load and loads it
promptStr("Where would you like to save?", processSave);
}
// Processes saving the table to a file
bool processSave(string filename) {
// Saves the table to the file and displays an error if this is unsuccessful
checkValidity(fullTable->saveTable(filename));
cout << "Saving file successful" << endl << endl;
return true;
}
// Runs a simulation of Conway's Game of Life
void gameOfLife() {
// Gets the width from the user
int width =
promptIntRange("Please enter the desired width of the grid", 15, 101);
// Gets the height from the user
int height =
promptIntRange("Please enter the desired height of the grid", 15, 101);
// Sets up Game of Life to be used with user's values
checkValidity(setupGameOfLife(width, height));
while (true) {
// If Escape is held, then exits game of life
checkValidity(runGameOfLife());
// Refreshes every half second
usleep(500000);
}
}
// Runs a simulation of Langton's ant
void LangtonsAnt() {
// Gets the width from the user
int width =
promptIntRange("Please enter the desired width of the grid", 10, 101);
// Gets the height from the user
int height =
promptIntRange("Please enter the desired height of the grid", 10, 101);
// Sets up Langton's ant to be used with user's values
checkValidity(setupLangtonsAnt(width, height));
// Keeps running
while (true) {
// Runs the langton's ant simulation
checkValidity(runLangtonsAnt());
// Refreshes every quarter second
usleep(250000);
}
}
| 31.846847 | 80 | 0.691655 | [
"object",
"vector"
] |
6725287b0650f3c50ada7bce1a02df7b651ebca6 | 629 | cpp | C++ | 155-min-stack/155-min-stack.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | 1 | 2022-02-27T09:01:07.000Z | 2022-02-27T09:01:07.000Z | 155-min-stack/155-min-stack.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | 155-min-stack/155-min-stack.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | class MinStack {
public:
stack<int> st1;
stack<int> st2;
MinStack() {
}
void push(int val) {
st1.push(val);
if(st2.empty() || val<=getMin())
st2.push(val);
}
void pop() {
if(st1.top()==getMin()) st2.pop();
st1.pop();
}
int top() {
return st1.top();
}
int getMin() {
return st2.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/ | 17.472222 | 64 | 0.473768 | [
"object"
] |
67317b5b4312ef5789b98789ab16105b1a285f8a | 5,717 | cpp | C++ | src/windraw/graphics/canvas.cpp | kosinw/windraw | 84958dc2225bc026e80a74e1767065b1264bb4f9 | [
"MIT"
] | null | null | null | src/windraw/graphics/canvas.cpp | kosinw/windraw | 84958dc2225bc026e80a74e1767065b1264bb4f9 | [
"MIT"
] | 8 | 2018-06-23T02:43:10.000Z | 2018-06-29T06:10:00.000Z | src/windraw/graphics/canvas.cpp | kosinw/windraw | 84958dc2225bc026e80a74e1767065b1264bb4f9 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Kosi Nwabueze
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include <Windows.h>
#include <d2d1.h>
#include <windraw/graphics/canvas.hpp>
#include <windraw/graphics/shapes.hpp>
#include <windraw/util/color.hpp>
namespace
{
template <class Interface>
inline void SafeRelease(
Interface **ppInterfaceToRelease)
{
if (*ppInterfaceToRelease != nullptr)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = nullptr;
}
}
}
namespace wd
{
Canvas::Canvas(WindowHandle handle, Size2 dimensions)
: m_windowHandle(handle)
, m_renderTarget(nullptr)
, m_dimensions(dimensions)
, m_factory(nullptr)
{
HRESULT hr = S_OK;
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_factory);
if (!SUCCEEDED(hr))
{
// TODO: Add error logging here
}
}
Canvas::~Canvas()
{
SafeRelease(&m_renderTarget);
SafeRelease(&m_factory);
if (!m_solidBrushes.empty())
{
for (auto brush : m_solidBrushes)
{
SafeRelease(&brush.second);
}
m_solidBrushes.clear();
}
}
void Canvas::clear(ColorF color)
{
D2D1_COLOR_F d2dcolor = D2D1::ColorF(color.r, color.g, color.b);
m_renderTarget->Clear(d2dcolor);
}
void Canvas::beginDraw()
{
if (!m_renderTarget)
{
HRESULT hr;
auto renderProps = D2D1::RenderTargetProperties();
auto size = D2D1::SizeU(static_cast<unsigned>(m_dimensions.width), static_cast<unsigned>(m_dimensions.height));
auto hwndRenderProps = D2D1::HwndRenderTargetProperties(m_windowHandle, size);
hr = m_factory->CreateHwndRenderTarget(
renderProps,
hwndRenderProps,
&m_renderTarget);
// For some odd reason it doesn't map pixels 1 : 1 unless this is sets
m_renderTarget->SetDpi(96.0f, 96.0f);
if (!SUCCEEDED(hr))
{
// TODO: Add error logging here
return;
}
}
m_renderTarget->BeginDraw();
m_renderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
}
void Canvas::endDraw()
{
HRESULT hr = m_renderTarget->EndDraw();
if (hr == D2DERR_RECREATE_TARGET)
{
SafeRelease(&m_renderTarget);
m_renderTarget = nullptr;
if (!m_solidBrushes.empty())
{
for (auto brush : m_solidBrushes)
{
SafeRelease(&brush.second);
}
m_solidBrushes.clear();
}
}
}
void Canvas::draw(const EllipseShape &shape)
{
ID2D1SolidColorBrush *brush;
if (m_solidBrushes.count(shape.color))
{
brush = m_solidBrushes[shape.color];
}
else
{
D2D1_COLOR_F color = D2D1::ColorF(shape.color.r, shape.color.g, shape.color.b);
m_renderTarget->CreateSolidColorBrush(
color,
&brush);
m_solidBrushes[shape.color] = brush;
}
Vector2f position = shape.position;
float radius = shape.radius;
D2D1_ELLIPSE ellipse = D2D1::Ellipse(
D2D1::Point2F(position.x, position.y),
radius,
radius);
if (shape.filled)
{
m_renderTarget->FillEllipse(ellipse, brush);
}
else
{
m_renderTarget->DrawEllipse(ellipse, brush);
}
}
void Canvas::draw(const RectShape &shape)
{
ID2D1SolidColorBrush *brush;
if (m_solidBrushes.count(shape.color))
{
brush = m_solidBrushes[shape.color];
}
else
{
D2D1_COLOR_F color = D2D1::ColorF(shape.color.r, shape.color.g, shape.color.b);
m_renderTarget->CreateSolidColorBrush(
color,
&brush);
m_solidBrushes[shape.color] = brush;
}
Size4 dimensions = shape.dimensions;
D2D1_RECT_F rect = D2D1::RectF(
dimensions.x,
dimensions.y,
dimensions.x + dimensions.width,
dimensions.y + dimensions.height);
if (shape.filled)
{
m_renderTarget->FillRectangle(rect, brush);
}
else
{
m_renderTarget->DrawRectangle(rect, brush);
}
}
void Canvas::draw(const LineShape& shape)
{
ID2D1SolidColorBrush *brush;
if (m_solidBrushes.count(shape.color))
{
brush = m_solidBrushes[shape.color];
}
else
{
D2D1_COLOR_F color = D2D1::ColorF(shape.color.r, shape.color.g, shape.color.b);
m_renderTarget->CreateSolidColorBrush(
color,
&brush);
m_solidBrushes[shape.color] = brush;
}
D2D1_POINT_2F pointA = D2D1::Point2F(shape.start.x, shape.start.y);
D2D1_POINT_2F pointB = D2D1::Point2F(shape.end.x, shape.end.y);
m_renderTarget->DrawLine(pointA, pointB, brush);
}
void Canvas::resizeRenderTarget(const Size2 &newSize)
{
m_dimensions = newSize;
if (m_renderTarget)
{
m_renderTarget->Resize(D2D1::SizeU(static_cast<unsigned>(newSize.width), static_cast<unsigned>(newSize.height)));
}
}
} // namespace wd | 24.431624 | 134 | 0.542767 | [
"shape"
] |
673b59b8fd64259d1452926a2ffcae77178d08d6 | 4,060 | hpp | C++ | include/Aether/types/ImageData.hpp | 3096/Aether | bc547ec192d8a973a63a97eda2994b3c2bdfeef7 | [
"MIT"
] | 9 | 2020-05-06T20:23:22.000Z | 2022-01-19T10:37:46.000Z | include/Aether/types/ImageData.hpp | 3096/Aether | bc547ec192d8a973a63a97eda2994b3c2bdfeef7 | [
"MIT"
] | 11 | 2020-03-22T03:40:50.000Z | 2020-06-09T00:53:13.000Z | include/Aether/types/ImageData.hpp | 3096/Aether | bc547ec192d8a973a63a97eda2994b3c2bdfeef7 | [
"MIT"
] | 6 | 2020-05-03T06:59:36.000Z | 2020-07-15T04:21:59.000Z | #ifndef AETHER_IMAGEDATA_HPP
#define AETHER_IMAGEDATA_HPP
#include "Aether/types/Colour.hpp"
#include <cstddef>
#include <cstdint>
#include <vector>
namespace Aether {
/**
* @brief Represents an object containing the raw pixel data for an image/texture
* as an array, along with required metadata such as width and height.
*
* @note Only RGB and RGBA (i.e. 3 or 4 channels) are supported.
*/
class ImageData {
private:
std::vector<Colour> pixels_; /** @brief Vector of pixels from top-left to bottom-right */
size_t width_; /** @brief Width of image in pixels */
size_t height_; /** @brief Height of image in pixels */
uint8_t channels_; /** @brief The number of channels in the image (usually 3 or 4) */
public:
/**
* @brief Constructs a new (invalid) ImageData object.
*/
ImageData();
/**
* @brief Constructs a new ImageData object from the given raw bytes.
*
* @param data Vector of bytes containing pixels in RGB(A) format.
* @param width Width of image in pixels
* @param height Height of image in pixels
* @param channels Number of channels forming the image.
*/
ImageData(const std::vector<uint8_t> & data, const size_t width, const size_t height, const uint8_t channels);
/**
* @brief Constructs a new ImageData object from the given raw bytes.
*
* @param pixels Vector of pixels.
* @param width Width of image in pixels
* @param height Height of image in pixels
* @param channels Number of channels forming the image.
*/
ImageData(const std::vector<Colour> & pixels, const size_t width, const size_t height, const uint8_t channels);
/**
* @brief Returns whether the associated image is considered 'valid' (i.e. has some pixel data).
*
* @return true if the stored image and metadata are valid values, false wtherwise.
*/
bool valid() const;
/**
* @brief Returns the width of the stored image in pixels.
*
* @return Width of the stored image in pixels.
*/
size_t width() const;
/**
* @brief Returns the height of the stored image in pixels.
*
* @return Height of the stored image in pixels.
*/
size_t height() const;
/**
* @brief Returns the number of channels used within the stored image.
* This will usually return 3 (RGB) or 4 (RGBA).
*
* @return Number of channels used in the stored image.
*/
uint8_t channels() const;
/**
* @brief Returns a pointer to the colour of a pixel at the given coordinate.
*
* @param x x-coordinate of pixel
* @param y y-coordinate of pixel
* @return Pointer to pixel colour, or nullptr if outside of image
*/
Colour * colourAt(const size_t x, const size_t y) const;
/**
* @brief Returns the stored image as a vector of bytes (i.e. one byte per channel).
* e.g. For an RGB image: [r0, g0, b0, r1, g1, b1, etc...]
*
* @return Vector of image pixels in raw byte format.
*/
std::vector<uint8_t> toByteVector() const;
/**
* @brief Returns the stored image as a vector of colours.
*
* @return Vector of image pixels.
*/
std::vector<Colour> toColourVector() const;
};
};
#endif
| 38.666667 | 124 | 0.520443 | [
"object",
"vector"
] |
673e65d369d8d89f79351c57241aa090956aa700 | 1,165 | cpp | C++ | LeetCode/cpp/684.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/cpp/684.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/cpp/684.cpp | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution {
vector<int> disjoint;
public:
vector<int> findRedundantConnection(vector<vector<int>> &edges) {
vector<int> ret(2, 0);
unordered_map<int, int> rank;
disjoint = vector<int>(1001, 0);
for (int i = 0; i < edges.size(); ++i) {
auto e = edges[i];
if (disjoint[e[0]] == 0) {
disjoint[e[0]] = e[0];
rank.insert(pair<int, int>(e[0], 0));
}
if (disjoint[e[1]] == 0) {
disjoint[e[1]] = e[1];
rank.insert(pair<int, int>(e[1], 0));
}
int a = UnionFind(e[0]);
int b = UnionFind(e[1]);
if (a == b) {
ret[0] = e[0];
ret[1] = e[1];
}
if (rank[a] > rank[b])
disjoint[b] = a;
else {
disjoint[a] = b;
if (rank[a] == rank[b])
++rank[a];
}
}
return ret;
}
int UnionFind(int &k) {
if (disjoint[k] != k)
disjoint[k] = UnionFind(disjoint[k]);
return disjoint[k];
}
}; | 29.125 | 69 | 0.387124 | [
"vector"
] |
6745e7e673793abb227b45d9e7f7f0b35eb5a36c | 4,495 | cpp | C++ | engine/core/graphics/common/spritesheet.cpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 47 | 2020-09-14T04:11:09.000Z | 2022-01-21T03:15:35.000Z | engine/core/graphics/common/spritesheet.cpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 19 | 2020-09-30T19:04:19.000Z | 2021-12-21T03:41:22.000Z | engine/core/graphics/common/spritesheet.cpp | warnwar/KestrelEngine | 985d1664b71aad62dd51721e0f81d5937d8ae9d4 | [
"MIT"
] | 3 | 2020-09-30T19:00:09.000Z | 2021-03-08T08:41:02.000Z | // Copyright (c) 2020 Tom Hancocks
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "core/graphics/common/spritesheet.hpp"
// MARK: - Sprite Construction
graphics::spritesheet::sprite::sprite(const double& x, const double& y, const double& width, const double& height)
: m_frame(x, y, width, height)
{
}
graphics::spritesheet::sprite::sprite(const math::point& origin, const math::size& size)
: m_frame(origin, size)
{
}
graphics::spritesheet::sprite::sprite(const math::rect& frame)
: m_frame(frame)
{
}
// MARK: - Sprite Accessor
auto graphics::spritesheet::sprite::frame() const -> math::rect
{
return m_frame;
}
auto graphics::spritesheet::sprite::point() const -> math::point
{
return m_frame.origin;
}
auto graphics::spritesheet::sprite::size() const -> math::size
{
return m_frame.size;
}
// MARK: - Spritesheet Construction
graphics::spritesheet::spritesheet(std::shared_ptr<graphics::texture> tex, const double& sprite_width, const double& sprite_height)
: m_backing_texture(std::move(tex)), m_sprite_base_size(sprite_width, sprite_height)
{
layout_sprites();
}
graphics::spritesheet::spritesheet(std::shared_ptr<graphics::texture> tex, const math::size& sprite_size)
: m_backing_texture(std::move(tex)), m_sprite_base_size(sprite_size)
{
layout_sprites();
}
// MARK: - Spritesheet Accessors
auto graphics::spritesheet::texture() const -> std::shared_ptr<graphics::texture>
{
return m_backing_texture;
}
auto graphics::spritesheet::sprite_count() const -> int
{
return m_sprites.size();
}
auto graphics::spritesheet::at(const int& n) const -> spritesheet::sprite
{
return m_sprites.at(n);
}
auto graphics::spritesheet::sprite_size() const -> math::size
{
return m_sprite_base_size;
}
// MARK: - Spritesheet Layout
auto graphics::spritesheet::layout_sprites() -> void
{
// Each sprite is providing the UV texture mapping information that will be used for drawing
// the appropriate portion of a texture.
auto sprite_uv_width = m_sprite_base_size.width / m_backing_texture->size().width;
auto sprite_uv_height = m_sprite_base_size.height / m_backing_texture->size().height;
// Determine the number of sprites in the grid.
auto count_x = static_cast<int>(m_backing_texture->size().width / m_sprite_base_size.width);
auto count_y = static_cast<int>(m_backing_texture->size().height / m_sprite_base_size.height);
for (auto y = 0; y < count_y; ++y) {
for (auto x = 0; x < count_x; ++x) {
spritesheet::sprite sprite(x * sprite_uv_width, y * sprite_uv_height, sprite_uv_width, sprite_uv_height);
m_sprites.emplace_back(sprite);
}
}
}
auto graphics::spritesheet::layout_sprites(const math::size &sprite_size) -> void
{
m_sprite_base_size = sprite_size;
m_sprites.clear();
layout_sprites();
}
auto graphics::spritesheet::layout_sprites(const std::vector<math::rect> &sprite_frames) -> void
{
m_sprites.clear();
m_sprite_base_size = sprite_frames.front().size;
auto width = m_backing_texture->size().width;
auto height = m_backing_texture->size().height;
for (const auto& frame : sprite_frames) {
auto x = frame.get_x();
auto y = frame.get_y();
auto w = frame.get_width();
auto h = frame.get_height();
y = height - y - h;
m_sprites.emplace_back(spritesheet::sprite(x / width, y / height, w / width, h / height));
}
}
| 31.65493 | 131 | 0.712792 | [
"vector"
] |
6746120f5b7597c8a391428b2f77ffbceef321b6 | 46,653 | cpp | C++ | homework2/solve.cpp | charleslucas/cs510 | 9515c1f236093db3287a018e4bfcf215b40bb67a | [
"MIT"
] | null | null | null | homework2/solve.cpp | charleslucas/cs510 | 9515c1f236093db3287a018e4bfcf215b40bb67a | [
"MIT"
] | null | null | null | homework2/solve.cpp | charleslucas/cs510 | 9515c1f236093db3287a018e4bfcf215b40bb67a | [
"MIT"
] | null | null | null | #include "maze.h"
#include "path.h"
#include<queue>
#include<vector>
#include<list>
#include<tuple>
#include<utility>
#include<iostream>
#include<climits>
#include<sstream>
#include<map>
#include<iomanip>
#include<algorithm>
using namespace std;
path solve_left(Maze& m, int rows, int cols);
path solve_dfs(Maze& m, int rows, int cols);
path solve_bfs(Maze& m, int rows, int cols);
path solve_bfs_custom(Maze& m, int rows, int cols, point start, point end);
path solve_dijkstra(Maze& m, int rows, int cols);
path solve_dijkstra_custom(Maze& m, int rows, int cols, point start, point end, int &path);
path solve_tour(Maze& m, int rows, int cols);
/**
* BitmapException denotes an exception from reading in a bitmap.
*/
class SolveException : public std::exception
{
// the message to print out
std::string _message;
// position in the bitmap file (in bytes) where the error occured.
uint32_t _tree_level;
public:
SolveException() = delete;
SolveException(const std::string& message, uint32_t tree_level);
SolveException(std::string&& message, uint32_t tree_level);
/**
* prints out the exception in the form:
*
* "Error in solver at position 0xposition :
* message"
*/
void print_exception();
};
/**
* SolveException denotes an exception from a maze solver.
*/
SolveException::SolveException(const std::string& message, uint32_t tree_level) {
_message = message;
_tree_level = tree_level;
}
SolveException::SolveException(std::string&& message, uint32_t tree_level) {
_message = message;
_tree_level = tree_level;
}
void SolveException::print_exception() {
std::cout << "Solver Exception: " << _message << " - tree level " << _tree_level << std::endl;
}
// Nodes for an exit mapping tree
struct nodeinfo {
point parent;
point next;
int exits[4]; // The exits from our current point (0=up, 1=left, 2=down, 3=right) - 0 = no exit, 1 = exit, -1 = backtracked from there
};
// All the exit data and costs for a point
struct exitinfo {
point exits[4]; // The exits from our current point (0=up, 1=left, 2=down, 3=right)
int ccost; // The *cumulative* cost for this node
int exit_ccosts[4]; // The *cumulative* costs for each exit (costs to the node in that direction plus all costs to this point)
};
// An array of corner IDs
struct corner_set {
int corners[4];
};
// The comparison function to be used with the priority queue in the tour path fitness selection
// Should sort the lowest cost (second) value to the top
struct solution_cmp {
bool operator()(const pair<corner_set,int> &a, const pair<corner_set,int> &b) {
return a.second > b.second;
};
};
int main(int argc, char** argv)
{
if(argc != 4)
{
cerr << "usage:\n"
<< "./maze option rows cols\n"
<< " options:\n"
<< " -left: always-look-left search\n"
<< " -dfs: depth first search (backtracking)\n"
<< " -bfs: breadth first search\n"
<< " -dij: dijkstra's algorithm\n"
<< " -tour: all corners tour\n"
<< " -basic: run dfs, bfs, and dij\n"
<< " -advanced: run dfs, bfs, dij and tour" << endl;
return 0;
}
string opt(argv[1]);
int rows, cols;
stringstream s;
s << argv[2] << " " << argv[3];
s >> rows >> cols;
// construct a new random maze;
Maze m(rows, cols);
// print the initial maze out
cout << "Initial maze" << endl;
m.print_maze(cout, opt == "-dij" || opt == "-tour");
if(opt == "-left")
{
cout << "\nSolving left" << endl;
path p = solve_left(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
}
if(opt == "-dfs")
{
cout << "\nSolving dfs" << endl;
path p = solve_dfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
}
if(opt == "-bfs")
{
cout << "\nSolving bfs" << endl;
path p = solve_bfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
}
if(opt == "-dij")
{
cout << "\nSolving dijkstra" << endl;
path p = solve_dijkstra(m, rows, cols);
m.print_maze_with_path(cout, p, true, false);
}
if(opt == "-tour")
{
cout << "\nSolving all corners tour" << endl;
path p = solve_tour(m, rows, cols);
m.print_maze_with_path(cout, p, true, true);
}
if(opt == "-basic")
{
cout << "\nSolving dfs" << endl;
path p = solve_dfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
cout << "\nSolving bfs" << endl;
p = solve_bfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
cout << "\nSolving dijkstra" << endl;
p = solve_dijkstra(m, rows, cols);
m.print_maze_with_path(cout, p, true, false);
}
if(opt == "-advanced")
{
cout << "\nSolving dfs" << endl;
path p = solve_dfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
cout << "\nSolving bfs" << endl;
p = solve_bfs(m, rows, cols);
m.print_maze_with_path(cout, p, false, false);
cout << "\nSolving dijkstra" << endl;
p = solve_dijkstra(m, rows, cols);
m.print_maze_with_path(cout, p, true, false);
cout << "\nSolving all corners tour" << endl;
p = solve_tour(m, rows, cols);
m.print_maze_with_path(cout, p, true, true);
}
}
/*
* A brute-force maze solving solution - follow the left wall, no matter how long it takes
* and allowing doubling-back on yourself.
* Construct a list of all the points in order that we traverse through them - duplicates are fine.
*/
path solve_left(Maze& m, int rows, int cols)
{
int forward = 2; // Save the direction we're pointing. We don't know at start, but we know we're at 0,0
int current_row = 0;
int current_col = 0;
int next_row = 0;
int next_col = 0;
list<point> pointlist;
point next_point;
// Push point 0,0 onto the list
next_point = make_pair(next_row,next_col);
pointlist.push_back(next_point);
// Calculate our path points and push them onto the list
while(next_row < m.rows()-1 || next_col < m.columns()-1) {
int relative_left = (forward+1)%4;
int relative_back = (forward+2)%4;
int relative_right = (forward+3)%4;
current_row = next_row;
current_col = next_col;
if(m.can_go(relative_left, current_row, current_col)) { // Can we go left?
forward = relative_left; // Turn to face left
}
else if(m.can_go(forward, current_row, current_col)) { // Can we go forward?
}
else if(m.can_go(relative_right, current_row, current_col)) { // Can we go right?
forward = relative_right; // Turn to face right
}
else {
forward = relative_back; // Turn around
}
// Choose our next point based on which way we are facing
if (forward == UP) {
next_row = current_row - 1;
}
else if (forward == LEFT) {
next_col = current_col - 1;
}
else if (forward == DOWN) {
next_row = current_row + 1;
}
else if (forward == RIGHT) {
next_col = current_col + 1;
}
else {
std::cout << "FAIL - bad direction value.";
}
next_point = make_pair(next_row,next_col);
pointlist.push_back(next_point);
}
return pointlist;
}
/*
* Implement a depth-first (backtracking) algorithm
* Find any solution to the maze - duplicate points are not allowed.
*/
path solve_dfs(Maze& m, int rows, int cols)
{
list<point> pointlist; // The list of points to return to the solution checker
map <point,nodeinfo> node_map; // Create a map-based list of each room, parent/child and exits
point previous_point;
point current_point;
point next_point;
bool end_found;
// Set our root node as 0,0
next_point = make_pair(0,0); // Row, Column
current_point = make_pair(-1,-1); // So our first previous_point will be -1,-1
// Calculate our path points and push them onto the list
while(current_point.first < m.rows()-1 || current_point.second < m.columns()-1) {
bool can_go_up = false;
bool can_go_left = false;
bool can_go_down = false;
bool can_go_right = false;
bool backtrack = false;
nodeinfo current_nodeinfo;
previous_point = current_point; // May be the parent, or the node we just backtracked from
current_point = next_point; // Move focus to the point selected by the previous loop iteration
// If the current node already exists in the map, then we know we are backtracking
if (node_map.count(current_point)) {
// Restore the nodeinfo for this node from the map
current_nodeinfo = node_map.at(current_point);
node_map.erase(current_point); // Remove our current point from the map, we will edit the nodeinfo and put it back later
// Figure out which direction we backtracked from, set that direction to -1 (Row/Column = Y/X)
if (previous_point.first == current_point.first-1 && previous_point.second == current_point.second ) {
current_nodeinfo.exits[UP] = -1;
}
else if (previous_point.first == current_point.first && previous_point.second == current_point.second-1) {
current_nodeinfo.exits[LEFT] = -1;
}
else if (previous_point.first == current_point.first+1 && previous_point.second == current_point.second ) {
current_nodeinfo.exits[DOWN] = -1;
}
else if (previous_point.first == current_point.first && previous_point.second == current_point.second+1) {
current_nodeinfo.exits[RIGHT] = -1;
}
}
else {
// Store the last node as our current parent, except if we're at root then store -1,-1
if (current_point.first == 0 && current_point.second == 0) {
current_nodeinfo.parent = make_pair(-1,-1); // Row, Column (Y,X)
}
else {
current_nodeinfo.parent = previous_point;
}
can_go_up = m.can_go_up (current_point.first, current_point.second);
can_go_left = m.can_go_left (current_point.first, current_point.second);
can_go_down = m.can_go_down (current_point.first, current_point.second);
can_go_right = m.can_go_right(current_point.first, current_point.second);
if (can_go_up) {
point up_from_here = make_pair(current_point.first-1, current_point.second);
// Check if we came from UP, or if we have seen that point before. If so, mark it with a -1
if (((previous_point.first == up_from_here.first) && (previous_point.second == up_from_here.second)) ||
(node_map.count(up_from_here) == 1 )) {
current_nodeinfo.exits[UP] = -1;
}
else {
current_nodeinfo.exits[UP] = 1;
}
}
else {
current_nodeinfo.exits[UP] = 0;
}
if (can_go_left) {
point left_from_here = make_pair(current_point.first, current_point.second-1);
// Check if we came from the LEFT, or if we have seen that point before. If so, mark it with a -1
if (((previous_point.first == left_from_here.first) && (previous_point.second == left_from_here.second)) ||
(node_map.count(left_from_here) == 1 )) {
current_nodeinfo.exits[LEFT] = -1;
}
else {
current_nodeinfo.exits[LEFT] = 1;
}
}
else {
current_nodeinfo.exits[LEFT] = 0;
}
if (can_go_down) {
point down_from_here = make_pair(current_point.first+1, current_point.second);
// Check if we came from DOWN, or if we have seen that point before. If so, mark it with a -1
if (((previous_point.first == down_from_here.first) && (previous_point.second == down_from_here.second)) ||
(node_map.count(down_from_here) == 1 )) {
current_nodeinfo.exits[DOWN] = -1;
}
else {
current_nodeinfo.exits[DOWN] = 1;
}
}
else {
current_nodeinfo.exits[DOWN] = 0;
}
if (can_go_right) {
point right_from_here = make_pair(current_point.first, current_point.second+1);
// Check if we came from the RIGHT, or if we have seen that point before. If so, mark it with a -1
if (((previous_point.first == right_from_here.first) && (previous_point.second == right_from_here.second)) ||
(node_map.count(right_from_here) == 1 )) {
current_nodeinfo.exits[RIGHT] = -1;
}
else {
current_nodeinfo.exits[RIGHT] = 1;
}
}
else {
current_nodeinfo.exits[RIGHT] = 0;
}
}
// Iterate over the valid exits and choose the next one in order
// If there aren't any valid exits left, backtrack
if (current_nodeinfo.exits[DOWN] == 1) {
next_point = make_pair(current_point.first + 1, current_point.second );
}
else if (current_nodeinfo.exits[LEFT] == 1) {
next_point = make_pair(current_point.first , current_point.second - 1);
}
else if (current_nodeinfo.exits[UP] == 1) {
next_point = make_pair(current_point.first - 1, current_point.second );
}
else if (current_nodeinfo.exits[RIGHT] == 1) {
next_point = make_pair(current_point.first , current_point.second + 1);
}
else {
// If there are no valid exits then either we are at the end or we need to backtrack
if (current_point.first == m.rows()-1 && current_point.second == m.columns()-1) {
next_point = make_pair(-1,-1);
}
else {
backtrack = true;
next_point = current_nodeinfo.parent;
}
}
// If we have to backtrack, pop our node off the list, set the parent as our next node
if (backtrack) {
#ifdef DEBUG
#endif
point popped = pointlist.back();
pointlist.pop_back();
}
else {
// Otherwise, push our current node onto the list and map
// Store our predicted next point in the current point's nodeinfo
pointlist.push_back(current_point);
current_nodeinfo.next = next_point;
node_map.insert(pair<point,nodeinfo>(current_point, current_nodeinfo));
}
}
return pointlist;
}
/*
* Implement a breadth-first algorithm
* Construct a list of just the points that make up the shortest distance to the end - duplicates are not allowed.
*/
path solve_bfs(Maze& m, int rows, int cols)
{
// Pass-through function to call the bfs routine with the default top-left start and bottom-right end points.
return(solve_bfs_custom(m, rows, cols, make_pair(0,0), make_pair(m.rows()-1, m.columns()-1)));
}
/*
* Implement a breadth-first algorithm
* Construct a list of just the points that make up the shortest distance from a given start point to the given
* end point - duplicate points in the path are not allowed.
*/
path solve_bfs_custom(Maze& m, int rows, int cols, point start, point end)
{
list<point> pointlist; // The resulting point list we will return to the checker
map <point,exitinfo> exit_map; // Create a map-based tree structure of each room and it's exits
map <point,point> parent_map; // Create a map-based tree structure of each room and it's parent
list <point> current_row; // the nodes in the current row of our tree
list <point> next_row; // the nodes in the next row of our tree
int tree_level = 0; // Current tree level
bool found_path = 0; // Set this when we reach the end square
point current_point = start; // first=row, second=col, start at our given coordinate
exitinfo current_exitinfo;
point current_parent; // For tracking the parent chain while constructing our final list
current_row.push_back(current_point); // Insert our first point into the first tree row
parent_map.insert(pair<point,point>(current_point, make_pair(-1,-1))); // Use -1,-1 to denote that our root node has no parent
// Discover the exits for each point in each possible path until we find the end
while(found_path == false) {
// Iterate over all the points in the current tree row, find their exits
for (std::list<point>::iterator it = current_row.begin(); it != current_row.end(); it++) {
point it_point = *it;
current_point = make_pair(it_point.first, it_point.second);
point current_parent = parent_map.at(current_point);
bool can_go_up = m.can_go_up(current_point.first, current_point.second);
bool can_go_left = m.can_go_left(current_point.first, current_point.second);
bool can_go_down = m.can_go_down(current_point.first, current_point.second);
bool can_go_right = m.can_go_right(current_point.first, current_point.second);
// Determine all the exits from our current point
if(can_go_up) { // Can we go up?
point up_point = make_pair(current_point.first-1, current_point.second);
current_exitinfo.exits[0] = up_point; // Store the x,y for the point to up
if ((up_point != current_parent) && (exit_map.count(up_point) == 0)) {
next_row.push_back(up_point); // Insert the exit point into the next tree row
parent_map.insert(pair<point,point>(up_point, current_point)); // Insert our current node into the parent tree map
}
}
if(can_go_left) { // Can we go left?
point left_point = make_pair(current_point.first, current_point.second-1);
current_exitinfo.exits[1] = left_point; // Store the x,y for the point to the left
if ((left_point != current_parent) && (exit_map.count(left_point) == 0)) {
next_row.push_back(left_point); // Insert the exit point into the next tree row
parent_map.insert(pair<point,point>(left_point, current_point)); // Insert our current node into the parent tree map
}
}
if(can_go_down) { // Can we go down?
point down_point = make_pair(current_point.first+1, current_point.second);
current_exitinfo.exits[2] = down_point; // Store the x,y for the point to down
if ((down_point != current_parent) && (exit_map.count(down_point) == 0)) {
next_row.push_back(down_point); // Insert the exit point into the next tree row
parent_map.insert(pair<point,point>(down_point, current_point)); // Insert our current node into the parent tree map
}
}
if(can_go_right) { // Can we go right?
point right_point = make_pair(current_point.first, current_point.second+1);
current_exitinfo.exits[3] = right_point; // Store the x,y for the point to the right
if ((right_point != current_parent) && (exit_map.count(right_point) == 0)) {
next_row.push_back(right_point); // Insert the exit point into the next tree row
parent_map.insert(pair<point,point>(right_point, current_point)); // Insert our current node into the parent tree map
}
}
exit_map.insert(pair<point,exitinfo>(current_point, current_exitinfo)); // Insert our current node into the tree map
// If we found the end of the maze, exit the while loop after the current row
// If we happen to find multiple solutions this row, they will all be of equal length
if (current_point == end) {
found_path = true;
}
}
current_row = next_row;
next_row.clear();
tree_level++;
// Safety check - we shouldn't have more tree levels than squares in the maze
if (tree_level >= (m.rows() * m.columns())) {
std::cout << "Runaway while loop - tree level > max number of maze squares" << std::endl;
throw(SolveException("Exceeded maximum number of tree levels", tree_level));
}
}
// If we are here, then we have found the end of the maze
current_point = end; // Start with the point at the end of the maze
pointlist.push_front(current_point); // Add that point to the list
current_parent = parent_map.at(current_point); // Get that node's parent
// Iterate backwards over our solution list until we hit -1/-1, the parent of 0,0
while (current_parent.first != -1 && current_parent.second != -1) {
current_point = current_parent; // Move backwards through the solution path
pointlist.push_front(current_point); // Add each point of the solution to the list
current_parent = parent_map.at(current_point); // Get the parent for each node
}
return pointlist;
}
/*
* Implement a breadth-first algorithm weighted by cost
* Construct a list of just the points that make up the lowest-cost distance to the end - duplicates are not allowed.
*/
path solve_dijkstra(Maze& m, int rows, int cols)
{
int path_cost;
// Pass-through function to call the bfs routine with the default top-left start and bottom-right end points.
return(solve_dijkstra_custom(m, rows, cols, make_pair(0,0), make_pair(m.rows()-1, m.columns()-1), path_cost));
}
/*
* Implement a breadth-first algorithm weighted by cost
* Construct a list of just the points that make up the lowest-cost distance from a given start point to the given
* end point - duplicate points in the path are not allowed.
*/
path solve_dijkstra_custom(Maze& m, int rows, int cols, point start, point end, int& path_cost)
{
list<point> pointlist; // The resulting point list we will return to the checker
map <point,exitinfo> exit_map; // Create a map-based tree structure of each room and it's exits
map <point,point> parent_map; // Create a map-based tree structure of each room and it's parent
list <point> current_frontier; // the nodes in the current frontier of our tree
list <point> next_frontier; // the nodes in the next row of our tree
int frontier_level = 0; // How many frontier levels we have iterated through
bool found_path = false; // Set this when we reach the end square
point current_point = start; // first=row, second=col
exitinfo current_exitinfo;
point current_parent; // For tracking the parent chain while constructing our final list
current_frontier.push_back(current_point); // Insert our first point into the first frontier
parent_map.insert(pair<point,point>(current_point, make_pair(-1,-1))); // Use -1,-1 to denote that our root node has no parent
// Discover the lowest-cost exits for each point in each possible path until we find the end of the maze
while(found_path == false && current_frontier.size() != 0) {
int lowest_ccost = 0; // The lowest cumulative movement cost we've found so far
int it_lowest_ccost = 9 * m.rows() * m.columns(); // Lowest cumulative movement cost we've found for each iteration (set to the max possible cost)
// Iterate over the current frontier row, fill out all the data for new nodes and figure out the lowest ccost for this frontier
for (std::list<point>::iterator it = current_frontier.begin(); it != current_frontier.end(); it++) {
exitinfo current_exitinfo;
exitinfo parent_exitinfo;
point it_point = *it;
current_point = make_pair(it_point.first, it_point.second);
// Get the known info for the current point's parent (unless we're the root node)
if (current_point == start) {
current_parent = make_pair(-1,-1);
}
else {
current_parent = parent_map.at(current_point);
parent_exitinfo = exit_map.at(current_parent);
}
// If this point already exists in our map
if (exit_map.count(current_point) > 0) {
//#ifdef DEBUG
//std::cout << " Current_point " << current_point.first << "/" << current_point.second << " already exists" << std::endl;
//#endif
current_exitinfo = exit_map.at(current_point); // Get our known exit info for the current point
// Iterate over our known valid exits for this node to find the lowest cumulative cost
for (int i = 0; i < 4; i++) {
if (current_exitinfo.exits[i].first > -1 && current_exitinfo.exits[i].second > -1 &&
it_lowest_ccost > current_exitinfo.exit_ccosts[i]) {
it_lowest_ccost = current_exitinfo.exit_ccosts[i];
}
}
}
else { // Create a new node
//#ifdef DEBUG
//std::cout << " Current_point " << current_point.first << "/" << current_point.second << " doesn't exist - creating" << std::endl;
//#endif
// Determine our current node's base cumulative cost (unless we're at root, then set it to 0)
if (current_point == start) {
current_exitinfo.ccost = 0;
}
else {
// If our parent is UP from us, our cumulative cost is the parent's cost plus the DOWN cost from there.
if ((current_parent.first == current_point.first-1) && (current_parent.second == current_point.second)) {
current_exitinfo.ccost = parent_exitinfo.ccost + m.cost(current_parent.first, current_parent.second, DOWN);
}
// If our parent is LEFT from us, our cumulative cost is the parent's cost plus the RIGHT cost from there.
else if ((current_parent.first == current_point.first) && (current_parent.second == current_point.second-1)) {
current_exitinfo.ccost = parent_exitinfo.ccost + m.cost(current_parent.first, current_parent.second, RIGHT);
}
// If our parent is DOWN from us, our cumulative cost is the parent's cost plus the UP cost from there.
else if ((current_parent.first == current_point.first+1) && (current_parent.second == current_point.second)) {
current_exitinfo.ccost = parent_exitinfo.ccost + m.cost(current_parent.first, current_parent.second, UP);
}
// If our parent is RIGHT from us, our cumulative cost is the parent's cost plus the LEFT cost from there.
else if ((current_parent.first == current_point.first) && (current_parent.second == current_point.second+1)) {
current_exitinfo.ccost = parent_exitinfo.ccost + m.cost(current_parent.first, current_parent.second, LEFT);
}
else {
std::cout << "Error - didn't locate a parent node" << std::endl;
}
}
bool can_go_up = m.can_go_up(current_point.first, current_point.second);
bool can_go_left = m.can_go_left(current_point.first, current_point.second);
bool can_go_down = m.can_go_down(current_point.first, current_point.second);
bool can_go_right = m.can_go_right(current_point.first, current_point.second);
point up_point = make_pair(current_point.first-1, current_point.second);
point left_point = make_pair(current_point.first, current_point.second-1);
point down_point = make_pair(current_point.first+1, current_point.second);
point right_point = make_pair(current_point.first, current_point.second+1);
// Determine cost for all the exits from our current point that aren't our parent
if (can_go_up && (up_point != current_parent)) {
int ccost = m.cost(current_point.first, current_point.second, UP) + current_exitinfo.ccost;
if (ccost < it_lowest_ccost) it_lowest_ccost = ccost;
current_exitinfo.exits[UP] = up_point;
current_exitinfo.exit_ccosts[UP] = ccost;
}
else
{ // Mark that exit invalid
current_exitinfo.exits[UP] = make_pair(-1, -1);
current_exitinfo.exit_ccosts[UP] = -1;
}
if (can_go_left && (left_point != current_parent)) {
int ccost = m.cost(current_point.first, current_point.second, LEFT) + current_exitinfo.ccost;
if (ccost < it_lowest_ccost) it_lowest_ccost = ccost;
current_exitinfo.exits[LEFT] = left_point;
current_exitinfo.exit_ccosts[LEFT] = ccost;
}
else
{ // Mark that exit invalid
current_exitinfo.exits[LEFT] = make_pair(-1, -1);
current_exitinfo.exit_ccosts[LEFT] = -1;
}
if (can_go_down && (down_point != current_parent)) {
int ccost = m.cost(current_point.first, current_point.second, DOWN) + current_exitinfo.ccost;
if (ccost < it_lowest_ccost) it_lowest_ccost = ccost;
current_exitinfo.exits[DOWN] = down_point;
current_exitinfo.exit_ccosts[DOWN] = ccost;
}
else
{ // Mark that exit invalid
current_exitinfo.exits[DOWN] = make_pair(-1, -1);
current_exitinfo.exit_ccosts[DOWN] = -1;
}
if (can_go_right && (right_point != current_parent)) {
int ccost = m.cost(current_point.first, current_point.second, RIGHT) + current_exitinfo.ccost;
if (ccost < it_lowest_ccost) it_lowest_ccost = ccost;
current_exitinfo.exits[RIGHT] = right_point;
current_exitinfo.exit_ccosts[RIGHT] = ccost;
}
else
{ // Mark that exit invalid
current_exitinfo.exits[RIGHT] = make_pair(-1, -1);
current_exitinfo.exit_ccosts[RIGHT] = -1;
}
exit_map.insert(pair<point,exitinfo>(current_point, current_exitinfo)); // Insert our new node into the tree map
parent_map.insert(pair<point,point> (current_point, current_parent)); // and register it's parent
}
}
// Iterate over the current frontier row again, construct our next frontier based on the lowest cost exits from this one
// All these nodes should exist in the exit map now
for (std::list<point>::iterator it = current_frontier.begin(); it != current_frontier.end(); it++) {
point it_point = *it;
current_point = make_pair(it_point.first, it_point.second);
current_exitinfo = exit_map.at(current_point); // Get our known exit info for the current point
bool can_go_up = m.can_go_up(current_point.first, current_point.second);
bool can_go_left = m.can_go_left(current_point.first, current_point.second);
bool can_go_down = m.can_go_down(current_point.first, current_point.second);
bool can_go_right = m.can_go_right(current_point.first, current_point.second);
// If one or more exits are equal to our lowest cumulative cost, add them to the next frontier
if((current_exitinfo.exits[UP].first > -1) && (current_exitinfo.exits[UP].second > -1)) {
const int up_cost = current_exitinfo.ccost + m.cost(current_point.first, current_point.second, UP);
if (up_cost == it_lowest_ccost) {
const point up_point = make_pair(current_point.first-1, current_point.second);
// Try to register this node as the new node's parent - use the return value to check if we've seen it before
std::pair<std::map<point,point>::iterator,bool> ret;
ret = parent_map.insert(make_pair(up_point, current_point));
// If we've registered this node already, skip and mark the exit as invalid
if (ret.second == false) {
next_frontier.push_back(up_point); // Put the node at that exit in our next frontier
current_exitinfo.exits[UP] = make_pair(-1,-1); // Mark this exit invalid now
}
}
}
if((current_exitinfo.exits[LEFT].first > -1) && (current_exitinfo.exits[LEFT].second > -1)) {
const int left_cost = current_exitinfo.ccost + m.cost(current_point.first, current_point.second, LEFT);
if (left_cost == it_lowest_ccost) {
const point left_point = make_pair(current_point.first, current_point.second-1);
// Try to register this node as the new node's parent - use the return value to check if we've seen it before
std::pair<std::map<point,point>::iterator,bool> ret;
ret = parent_map.insert(make_pair(left_point, current_point));
// If we've registered this node already, skip and mark the exit as invalid
if (ret.second == false) {
next_frontier.push_back(left_point); // Put the node at that exit in our next frontier
current_exitinfo.exits[LEFT] = make_pair(-1,-1); // Mark this exit invalid now
}
}
}
if((current_exitinfo.exits[DOWN].first > -1) && (current_exitinfo.exits[DOWN].second > -1)) {
const int down_cost = current_exitinfo.ccost + m.cost(current_point.first, current_point.second, DOWN);
if (down_cost == it_lowest_ccost) {
const point down_point = make_pair(current_point.first+1, current_point.second);
// Try to register this node as the new node's parent - use the return value to check if we've seen it before
std::pair<std::map<point,point>::iterator,bool> ret;
ret = parent_map.insert(make_pair(down_point, current_point));
// If we've registered this node already, skip and mark the exit as invalid
if (ret.second == false) {
next_frontier.push_back(down_point); // Put the node at that exit in our next frontier
current_exitinfo.exits[DOWN] = make_pair(-1,-1); // Mark this exit invalid now
}
}
}
if((current_exitinfo.exits[RIGHT].first > -1) && (current_exitinfo.exits[RIGHT].second > -1)) {
const int right_cost = current_exitinfo.ccost + m.cost(current_point.first, current_point.second, RIGHT);
if (right_cost == it_lowest_ccost) {
const point right_point = make_pair(current_point.first, current_point.second+1);
// Try to register this node as the new node's parent - use the return value to check if we've seen it before
std::pair<std::map<point,point>::iterator,bool> ret;
ret = parent_map.insert(make_pair(right_point, current_point));
// If we've registered this node already, skip and mark the exit as invalid
if (ret.second == false) {
next_frontier.push_back(right_point); // Put the node at that exit in our next frontier
current_exitinfo.exits[RIGHT] = make_pair(-1,-1); // Mark this exit invalid now
}
}
}
exit_map.erase(current_point); // Remove our current point's entry from the map so we can replace it with updated exitinfo
exit_map.insert(pair<point,exitinfo>(current_point, current_exitinfo));
// Re-evaluate our current node to see if it has any valid exits left - if so, add it to the next frontier as well
int valid_exits = 0;
for (int i = 0; i < 4; i++) {
if (current_exitinfo.exits[i].first != -1 && current_exitinfo.exits[i].second != -1) {
valid_exits = 1;
}
}
if (valid_exits) {
next_frontier.push_back(current_point);
}
// If we found the end of the maze, exit the while loop after the current frontier
// If we happen to find multiple solutions this row, they will all be of equal cost
// Store our current lowest cost to return with the final path
if (current_point == end) {
found_path = true;
path_cost = it_lowest_ccost;
}
}
// While loop safety check
if (frontier_level > (5 * m.rows() * m.columns())) {
std::cout << "Runaway while loop - frontier level == " << frontier_level << std::endl;
throw(SolveException("Runaway While Loop - Exceeded maximum number of frontier levels", frontier_level));
}
current_frontier = next_frontier;
current_frontier.sort();
current_frontier.unique(); // Take care of a corner case where we add the same square twice from different sides
next_frontier.clear();
frontier_level++;
}
// If we are here, then we have found the end of the maze
current_point = end; // Start with the point at the end of the maze
pointlist.push_front(current_point); // Add that point to the list
current_parent = parent_map.at(current_point); // Get that node's parent
// Iterate backwards over our solution list until we hit -1/-1, the parent of 0,0
while (current_parent.first != -1 && current_parent.second != -1) {
current_point = current_parent; // Move backwards through the solution path
pointlist.push_front(current_point); // Add each point of the solution to the list
current_parent = parent_map.at(current_point); // Get the parent for each node
}
return pointlist;
}
path solve_tour(Maze& m, int rows, int cols)
{
point dungeons[5]; // Our array of dungeon points we need to visit
int cost_matrix[5][5]; // Our matrix of dungeon-to-dungeon sub-path costs
int perm_elements[4] = {1, 2, 3, 4}; // To calculate permutations
priority_queue<pair<corner_set, int>, vector<pair<corner_set,int>>, solution_cmp> solution_queue;
pair<point,point> dungeon_path_array[5]; // Our final array of shortest-cost dungeon paths to calculate
path lowest_cost_path; // Our final list of path points to return
// Make an array of all the "dungeons" we need to visit
dungeons[0] = make_pair(m.rows()/2, m.columns()/2); // Our start/end point in the center of the maze
dungeons[1] = make_pair(0, 0); // Top-Left Corner
dungeons[2] = make_pair(0, m.columns()-1); // Top-Right Corner
dungeons[3] = make_pair(m.rows()-1, m.columns()-1); // Bottom-Right Corner
dungeons[4] = make_pair(m.rows()-1, 0); // Bottom-Left Corner
// Create a matrix of the shortest path cost from each dungeon to each other dungeon
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
path p; // A list of points
int path_cost; // The travel cost of the path
// Call the bfs/djikstra routine with the matrix of end points.
//p = solve_bfs_custom(m, rows, cols, dungeons[j], dungeons[i]);
p = solve_dijkstra_custom(m, rows, cols, dungeons[j], dungeons[i], path_cost);
// I'm making the assumption here that we care about the maze weights, and not just the distance
// as the assignment appears to say, since we were given a weighted maze.
// If we don't actually care about the maze weights, then the cost of the paths is the length of the path.
#ifdef TOUR_BFS
cost_matrix[j][i] = p.size();
#else
cost_matrix[j][i] = path_cost;
#endif
}
}
#ifdef DEBUG
std::cout << endl;
std::cout << setw(4) << " " << setw(4) << "0" << setw(4) << "1" << setw(4) << "2" << setw(4) << "3" << setw(4) << "4" << std::endl << std::endl;
for (int j = 0; j < 5; j++) {
std::cout << setw(4) << j << setw(4) << cost_matrix[j][0] << setw(4) << cost_matrix[j][1] << setw(4) << cost_matrix[j][2] << setw(4) << cost_matrix[j][3] << setw(4) << cost_matrix[j][4] << std::endl;
}
std::cout << endl;
#endif
// Iterate over all permutations of our four corners, then find the cost for the set of paths
// start -> corner[0] -> corner[1] -> corner[2] -> corner[3] -> start
do {
corner_set corner_order;
corner_order.corners[0] = perm_elements[0];
corner_order.corners[1] = perm_elements[1];
corner_order.corners[2] = perm_elements[2];
corner_order.corners[3] = perm_elements[3];
// Calculate our final solution cost, adding up the cost for all six legs of the path
int solution_cost = cost_matrix[0] [perm_elements[0]] +
cost_matrix[perm_elements[0]][perm_elements[1]] +
cost_matrix[perm_elements[1]][perm_elements[2]] +
cost_matrix[perm_elements[2]][perm_elements[3]] +
cost_matrix[perm_elements[3]][0];
solution_queue.push(make_pair(corner_order, solution_cost));
#ifdef DEBUG
std::cout << "Solution Distance: " << solution_cost << " from " << perm_elements[0] << ' ' << perm_elements[1] << ' ' << perm_elements[2] << ' ' << perm_elements[3] << std::endl;
#endif
} while (std::next_permutation(perm_elements,perm_elements+4) );
pair<corner_set, int> lowest_cost_solution = solution_queue.top();
#ifdef DEBUG
std::cout << std::endl << "Lowest Solution Cost: " << lowest_cost_solution.second << " from " << lowest_cost_solution.first.corners[0] << " -> " << lowest_cost_solution.first.corners[1] << " -> " << lowest_cost_solution.first.corners[2] << " -> " << lowest_cost_solution.first.corners[3] << std::endl << std::endl;
#endif
dungeon_path_array[0] = make_pair( dungeons[0], dungeons[lowest_cost_solution.first.corners[0]]);
dungeon_path_array[1] = make_pair(dungeons[lowest_cost_solution.first.corners[0]], dungeons[lowest_cost_solution.first.corners[1]]);
dungeon_path_array[2] = make_pair(dungeons[lowest_cost_solution.first.corners[1]], dungeons[lowest_cost_solution.first.corners[2]]);
dungeon_path_array[3] = make_pair(dungeons[lowest_cost_solution.first.corners[2]], dungeons[lowest_cost_solution.first.corners[3]]);
dungeon_path_array[4] = make_pair(dungeons[lowest_cost_solution.first.corners[3]], dungeons[0] );
// Run all six legs of the path and concatenate them together
for (int i = 0; i < 5; ++i) {
int path_cost;
#ifdef DEBUG
std::cout << "Running path " << dungeon_path_array[i].first.first << "/" << dungeon_path_array[i].first.second << " to " << dungeon_path_array[i].second.first << "/" << dungeon_path_array[i].second.second << std::endl;
#endif
// As above, select if we want bfs of dijkstra for path fitness
#ifdef TOUR_BFS
path p = solve_bfs_custom(m, rows, cols, dungeon_path_array[i].first, dungeon_path_array[i].second);
#else
path p = solve_dijkstra_custom(m, rows, cols, dungeon_path_array[i].first, dungeon_path_array[i].second, path_cost);
#endif
// Remove the first element of every list list after the first so we don't have duplicates
if (i > 0) {
p.pop_front();
}
lowest_cost_path.splice(lowest_cost_path.end(), p);
}
#ifdef DEBUG
// Iterate over our final point list and print all the points before returning
std::cout << std::endl << "Final point list:" << std::endl;
for (const point & ipoint : lowest_cost_path)
{
std::cout << ipoint.first << "/" << ipoint.second << std::endl;
}
#endif
return lowest_cost_path;
}
| 48.345078 | 319 | 0.585729 | [
"vector"
] |
67485848eeac280451e225b4db45556e730bd5a1 | 2,303 | cpp | C++ | src/app/ModalController.cpp | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | src/app/ModalController.cpp | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | src/app/ModalController.cpp | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | // -----------------------------------------------
// ModalController.cpp
//
// Implementation of a base class to manage views
// and handle events
//
// Written by Nick Laiacona and Ed Zavada, 2010-2012
// Copyright (c) 2012, Dream Rock Studios, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// -----------------------------------------------
#include "pdg/app/ModalController.h"
#include "pdg/sys/graphics.h"
namespace pdg {
// redraw all of the views for active controllers, starting with
// our deepest descendents and working our way up.
void ModalController::redrawAll() {
if (!isActive()) return;
pdg::Controller::redrawAll();
#if 0
// recursively traverse to the deepest controller child
Children::iterator citr;
for(citr = mChildren.begin(); citr != mChildren.end(); citr++) {
Controller* child = *citr;
if( child->isActive() )
child->redrawAll();
}
// render this controller and all its views
if( isActive() )
redrawSelf(mPort->getDrawingArea());
#endif
}
ModalController::ModalController(Application* app, bool wantKeyUpDown, bool wantKeyPress,
bool wantMouseEnterLeave, bool wantAll)
: pdg::Controller(app,wantKeyUpDown,wantKeyPress,wantMouseEnterLeave,wantAll, kDontDrawWhileInactive) {
}
} // namespace pdg
| 34.893939 | 104 | 0.711246 | [
"render"
] |
67530d3c84e23738a5486b99923e811e2a04d890 | 712 | hpp | C++ | include/anserial/deserializer.hpp | mushrom/anserial | bc3fdbfeed5b1a74461b4326af19bca895811196 | [
"MIT"
] | null | null | null | include/anserial/deserializer.hpp | mushrom/anserial | bc3fdbfeed5b1a74461b4326af19bca895811196 | [
"MIT"
] | null | null | null | include/anserial/deserializer.hpp | mushrom/anserial | bc3fdbfeed5b1a74461b4326af19bca895811196 | [
"MIT"
] | null | null | null | #pragma once
#include <anserial/base_ent.hpp>
#include <anserial/s_node.hpp>
#include <stdint.h>
#include <vector>
namespace anserial {
class deserializer {
public:
deserializer() {};
deserializer(uint32_t *datas, size_t entities) {
deserialize(datas, entities);
}
deserializer(std::vector<uint32_t> datas) {
deserialize(datas);
}
// used for decoding
std::vector<s_node*> nodes;
// last assigned entity ID
uint32_t ent_counter = 0;
// returns just what is already parsed
s_node *deserialize();
// add entities to the deserialized tree
s_node *deserialize(uint32_t *datas, size_t entities);
s_node *deserialize(std::vector<uint32_t> datas);
};
// namespace anserial
}
| 19.243243 | 56 | 0.710674 | [
"vector"
] |
67565ee01168054c384d94adab46d779b2ba9284 | 1,831 | hpp | C++ | importer/polygonidentifyer.hpp | kcwu/osm-history-renderer | ead3e533e142586ba51a8c991d186c68e9b682fe | [
"BSD-2-Clause"
] | 42 | 2015-05-05T05:02:45.000Z | 2022-01-08T17:27:12.000Z | importer/polygonidentifyer.hpp | kcwu/osm-history-renderer | ead3e533e142586ba51a8c991d186c68e9b682fe | [
"BSD-2-Clause"
] | 10 | 2015-02-08T21:34:09.000Z | 2019-10-18T06:56:22.000Z | importer/polygonidentifyer.hpp | kcwu/osm-history-renderer | ead3e533e142586ba51a8c991d186c68e9b682fe | [
"BSD-2-Clause"
] | 16 | 2015-02-08T20:54:29.000Z | 2021-02-01T19:30:25.000Z | /**
* In OpenStreetMaps a closed way (a way with the sae start- and end-node)
* can be either a polygon or linestring. If it's the one or the other
* needs to be decided by looking at the tags. This class provides a list
* of tags that indicate a way looks like a polygon. This decision is only
* made based on the tags, the geometry of way (is it closed) needs to
* be checked by the caller separately.
*/
#ifndef IMPORTER_POLYGONIDENTIFYER_HPP
#define IMPORTER_POLYGONIDENTIFYER_HPP
/**
* list of tags that let a closed way look like a polygon
*/
const char *polygons[] =
{
"aeroway",
"amenity",
"area",
"building",
"harbour",
"historic",
"landuse",
"leisure",
"man_made",
"military",
"natural",
"power",
"place",
"shop",
"sport",
"tourism",
"water",
"waterway",
"wetland",
// 0-value signals end-of-list
0
};
/**
* Checks Tags against a list to decide if they look like the way
* could potentially be a polygon.
*/
class PolygonIdentifyer {
public:
/**
* checks the TagList against a list to decide if they look like the
* way could potentially be a polygon.
*/
static bool looksLikePolygon(const Osmium::OSM::TagList& tags) {
// iterate over all tags
for(Osmium::OSM::TagList::const_iterator it = tags.begin(); it != tags.end(); ++it) {
// iterate over all known polygon-tags
for(int i = 0; polygons[i] != 0; i++) {
// compare the tag name
if(0 == strcmp(polygons[i], it->key())) {
// yep, it looks like a polygon
return true;
}
}
}
// no, this could never be a polygon
return false;
}
};
#endif // IMPORTER_POLYGONIDENTIFYER_HPP
| 24.413333 | 93 | 0.59148 | [
"geometry"
] |
67570badf6a59e619b19a0ed1d0de6cc341bc705 | 15,416 | cpp | C++ | src/metadata/metadata1.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 13 | 2017-01-07T07:48:54.000Z | 2021-09-29T05:33:38.000Z | src/metadata/metadata1.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 27 | 2016-11-24T11:35:22.000Z | 2022-02-14T14:38:09.000Z | src/metadata/metadata1.cpp | melchor629/node-flac-bindings | 584bd52ef12de4562dca0f198220f2c136666ce2 | [
"0BSD"
] | 3 | 2017-10-19T10:12:11.000Z | 2019-10-11T16:21:09.000Z | #include "../mappings/mappings.hpp"
#include "../mappings/native_async_iterator.hpp"
#include "../mappings/native_iterator.hpp"
#include "../utils/async.hpp"
#include "../utils/enum.hpp"
#include <FLAC/metadata.h>
#include <memory>
namespace flac_bindings {
using namespace Napi;
class SimpleIterator: public ObjectWrap<SimpleIterator> {
FLAC__Metadata_SimpleIterator* it;
void throwIfStatusIsNotOk(const Napi::Env& env) {
auto status = FLAC__metadata_simple_iterator_status(it);
if (status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) {
throw Error::New(
env,
"Operation failed: "s + &FLAC__Metadata_SimpleIteratorStatusString[status][38]);
}
}
template<typename T>
void rejectIfStatusIsNotOk(typename AsyncBackgroundTask<T>::ExecutionProgress& c) {
auto status = FLAC__metadata_simple_iterator_status(it);
if (status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) {
c.reject("Operation failed: "s + &FLAC__Metadata_SimpleIteratorStatusString[status][38]);
}
}
template<typename R>
Napi::Value asyncImpl(
const Napi::Env& env,
const char* name,
const std::initializer_list<Napi::Value>& args,
std::function<R()> impl,
std::function<Napi::Value(const Napi::Env&, R)> converter = booleanToJs<R>) {
EscapableHandleScope scope(env);
auto worker = new AsyncBackgroundTask<R>(
env,
[impl](auto c) {
auto res = impl();
c.resolve(res);
},
nullptr,
name,
converter);
for (auto i = args.begin(); i != args.end(); i += 1) {
worker->Receiver().Set(i - args.begin(), *i);
}
worker->Queue();
return scope.Escape(worker->getPromise());
}
void checkStatus(Napi::Env env, bool succeeded) {
if (!succeeded) {
auto status = FLAC__metadata_simple_iterator_status(it);
// remove prefix FLAC__METADATA_SIMPLE_ITERATOR_STATUS_
auto statusString = FLAC__Metadata_SimpleIteratorStatusString[status] + 38;
auto error = Error::New(env, "SimpleIterator initialization failed: "s + statusString);
error.Set("status", numberToJs(env, status));
error.Set("statusString", String::New(env, statusString));
throw error;
}
}
public:
static Function init(Napi::Env env, FlacAddon& addon) {
EscapableHandleScope scope(env);
auto constructor = DefineClass(
env,
"SimpleIterator",
{
InstanceMethod(Napi::Symbol::WellKnown(env, "iterator"), &SimpleIterator::iterator),
InstanceMethod(
Napi::Symbol::WellKnown(env, "asyncIterator"),
&SimpleIterator::asyncIterator),
InstanceMethod("status", &SimpleIterator::status),
InstanceMethod("init", &SimpleIterator::init),
InstanceMethod("initAsync", &SimpleIterator::initAsync),
InstanceMethod("isWritable", &SimpleIterator::isWritable),
InstanceMethod("isLast", &SimpleIterator::isLast),
InstanceMethod("next", &SimpleIterator::next),
InstanceMethod("nextAsync", &SimpleIterator::nextAsync),
InstanceMethod("prev", &SimpleIterator::prev),
InstanceMethod("prevAsync", &SimpleIterator::prevAsync),
InstanceMethod("getBlockOffset", &SimpleIterator::getBlockOffset),
InstanceMethod("getBlockType", &SimpleIterator::getBlockType),
InstanceMethod("getBlockLength", &SimpleIterator::getBlockLength),
InstanceMethod("getApplicationId", &SimpleIterator::getApplicationId),
InstanceMethod("getApplicationIdAsync", &SimpleIterator::getApplicationIdAsync),
InstanceMethod("getBlock", &SimpleIterator::getBlock),
InstanceMethod("getBlockAsync", &SimpleIterator::getBlockAsync),
InstanceMethod("setBlock", &SimpleIterator::setBlock),
InstanceMethod("setBlockAsync", &SimpleIterator::setBlockAsync),
InstanceMethod("insertBlockAfter", &SimpleIterator::insertBlockAfter),
InstanceMethod("insertBlockAfterAsync", &SimpleIterator::insertBlockAfterAsync),
InstanceMethod("deleteBlock", &SimpleIterator::deleteBlock),
InstanceMethod("deleteBlockAsync", &SimpleIterator::deleteBlockAsync),
});
c_enum::declareInObject(constructor, "Status", createStatusEnum);
addon.simpleIteratorConstructor = Persistent(constructor);
return scope.Escape(objectFreeze(constructor)).As<Function>();
}
SimpleIterator(const CallbackInfo& info): ObjectWrap<SimpleIterator>(info) {
it = FLAC__metadata_simple_iterator_new();
if (it == nullptr) {
throw Error::New(info.Env(), "Could not allocate memory");
}
}
~SimpleIterator() {
FLAC__metadata_simple_iterator_delete(it);
}
Napi::Value iterator(const CallbackInfo& info) {
while (FLAC__metadata_simple_iterator_prev(it))
;
std::shared_ptr<bool> pastEnd(new bool(false));
return NativeIterator::newIterator(
info.Env(),
[this, pastEnd](auto env, auto) -> NativeIterator::IterationReturnValue {
if (FLAC__metadata_simple_iterator_is_last(it)) {
if (*pastEnd) {
return {};
}
*pastEnd = true;
}
auto metadata = FLAC__metadata_simple_iterator_get_block(it);
throwIfStatusIsNotOk(env);
FLAC__metadata_simple_iterator_next(it);
return Metadata::toJs(env, metadata, true);
});
}
Napi::Value asyncIterator(const CallbackInfo& info) {
using NAI = NativeAsyncIterator<FLAC__StreamMetadata*>;
std::shared_ptr<bool> hasRollbacked(new bool(false));
std::shared_ptr<bool> pastEnd(new bool(false));
return NAI::newIterator(
info.Env(),
"flac_bindings::SimpleIterator::asyncIterator",
[this, hasRollbacked, pastEnd](auto c, auto) -> NAI::IterationReturnValue {
if (!*hasRollbacked) {
while (FLAC__metadata_simple_iterator_prev(it))
;
*hasRollbacked = true;
}
if (FLAC__metadata_simple_iterator_is_last(it)) {
if (*pastEnd) {
return std::nullopt;
}
*pastEnd = true;
}
auto metadata = FLAC__metadata_simple_iterator_get_block(it);
rejectIfStatusIsNotOk<std::optional<FLAC__StreamMetadata*>>(c);
FLAC__metadata_simple_iterator_next(it);
return metadata;
},
[](auto env, auto* metadata) { return Metadata::toJs(env, metadata, true); });
}
Napi::Value status(const CallbackInfo& info) {
return numberToJs(info.Env(), FLAC__metadata_simple_iterator_status(it));
}
void init(const CallbackInfo& info) {
auto path = stringFromJs(info[0]);
auto readOnly = maybeBooleanFromJs<FLAC__bool>(info[1]).value_or(false);
auto preserve = maybeBooleanFromJs<FLAC__bool>(info[2]).value_or(false);
auto res = FLAC__metadata_simple_iterator_init(it, path.c_str(), readOnly, preserve);
checkStatus(info.Env(), res);
}
Napi::Value initAsync(const CallbackInfo& info) {
auto path = stringFromJs(info[0]);
auto readOnly = maybeBooleanFromJs<FLAC__bool>(info[1]).value_or(false);
auto preserve = maybeBooleanFromJs<FLAC__bool>(info[2]).value_or(false);
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::initAsync",
{info.This()},
[this, path, readOnly, preserve]() {
return FLAC__metadata_simple_iterator_init(it, path.c_str(), readOnly, preserve);
},
[this](auto env, auto value) {
this->checkStatus(env, value);
return env.Undefined();
});
}
Napi::Value isWritable(const CallbackInfo& info) {
return booleanToJs(info.Env(), FLAC__metadata_simple_iterator_is_writable(it));
}
Napi::Value isLast(const CallbackInfo& info) {
return booleanToJs(info.Env(), FLAC__metadata_simple_iterator_is_last(it));
}
Napi::Value next(const CallbackInfo& info) {
return booleanToJs(info.Env(), FLAC__metadata_simple_iterator_next(it));
}
Napi::Value nextAsync(const CallbackInfo& info) {
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::nextAsync",
{info.This()},
[this]() { return FLAC__metadata_simple_iterator_next(it); });
}
Napi::Value prev(const CallbackInfo& info) {
return booleanToJs(info.Env(), FLAC__metadata_simple_iterator_prev(it));
}
Napi::Value prevAsync(const CallbackInfo& info) {
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::prevAsync",
{info.This()},
[this]() { return FLAC__metadata_simple_iterator_prev(it); });
}
Napi::Value getBlockOffset(const CallbackInfo& info) {
auto ret = FLAC__metadata_simple_iterator_get_block_offset(it);
return numberToJs(info.Env(), ret);
}
Napi::Value getBlockType(const CallbackInfo& info) {
auto ret = FLAC__metadata_simple_iterator_get_block_type(it);
return numberToJs(info.Env(), ret);
}
Napi::Value getBlockLength(const CallbackInfo& info) {
auto ret = FLAC__metadata_simple_iterator_get_block_length(it);
return numberToJs(info.Env(), ret);
}
Napi::Value getApplicationId(const CallbackInfo& info) {
FLAC__byte id[4];
auto ret = FLAC__metadata_simple_iterator_get_application_id(it, id);
if (ret) {
return Buffer<FLAC__byte>::Copy(info.Env(), id, 4);
}
return info.Env().Null();
}
Napi::Value getApplicationIdAsync(const CallbackInfo& info) {
return asyncImpl<FLAC__byte*>(
info.Env(),
"flac_bindings::SimpleIterator:getApplicationId",
{info.This()},
[this]() -> FLAC__byte* {
FLAC__byte* id = new FLAC__byte[4];
if (FLAC__metadata_simple_iterator_get_application_id(it, id)) {
return id;
}
delete[] id;
return nullptr;
},
[](auto env, FLAC__byte* id) -> Napi::Value {
if (id != nullptr) {
auto buffer = Buffer<FLAC__byte>::Copy(env, id, 4);
delete[] id;
return buffer;
}
return env.Null();
});
}
Napi::Value getBlock(const CallbackInfo& info) {
auto metadata = FLAC__metadata_simple_iterator_get_block(it);
return Metadata::toJs(info.Env(), metadata);
}
Napi::Value getBlockAsync(const CallbackInfo& info) {
return asyncImpl<FLAC__StreamMetadata*>(
info.Env(),
"flac_bindings::SimpleIterator::getBlockAsync",
{info.This()},
[this]() { return FLAC__metadata_simple_iterator_get_block(it); },
[](auto env, auto metadata) { return Metadata::toJs(env, metadata, true); });
}
Napi::Value setBlock(const CallbackInfo& info) {
auto metadata = Metadata::fromJs(info[0]);
auto pad = maybeNumberFromJs<FLAC__bool>(info[1]).value_or(true);
auto ret = FLAC__metadata_simple_iterator_set_block(it, metadata, pad);
return booleanToJs(info.Env(), ret);
}
Napi::Value setBlockAsync(const CallbackInfo& info) {
FLAC__StreamMetadata* metadata = Metadata::fromJs(info[0]);
auto pad = maybeNumberFromJs<FLAC__bool>(info[1]).value_or(true);
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::setBlockAsync",
{info.This(), info[0]},
[this, metadata, pad]() {
return FLAC__metadata_simple_iterator_set_block(it, metadata, pad);
});
}
Napi::Value insertBlockAfter(const CallbackInfo& info) {
auto metadata = Metadata::fromJs(info[0]);
auto pad = maybeNumberFromJs<FLAC__bool>(info[1]).value_or(true);
auto ret = FLAC__metadata_simple_iterator_insert_block_after(it, metadata, pad);
return booleanToJs(info.Env(), ret);
}
Napi::Value insertBlockAfterAsync(const CallbackInfo& info) {
FLAC__StreamMetadata* metadata = Metadata::fromJs(info[0]);
auto pad = maybeNumberFromJs<FLAC__bool>(info[1]).value_or(true);
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::insertBlockAfterAsync",
{info.This(), info[0]},
[this, metadata, pad]() {
return FLAC__metadata_simple_iterator_insert_block_after(it, metadata, pad);
});
}
Napi::Value deleteBlock(const CallbackInfo& info) {
auto pad = maybeNumberFromJs<FLAC__bool>(info[0]).value_or(true);
auto ret = FLAC__metadata_simple_iterator_delete_block(it, pad);
return booleanToJs(info.Env(), ret);
}
Napi::Value deleteBlockAsync(const CallbackInfo& info) {
auto pad = maybeNumberFromJs<FLAC__bool>(info[0]).value_or(true);
return asyncImpl<FLAC__bool>(
info.Env(),
"flac_bindings::SimpleIterator::deleteBlockAsync",
{info.This(), info[0]},
[this, pad]() { return FLAC__metadata_simple_iterator_delete_block(it, pad); });
}
static c_enum::DefineReturnType createStatusEnum(const Napi::Env& env) {
auto obj1 = Object::New(env);
auto obj2 = Object::New(env);
c_enum::defineValue(obj1, obj2, "OK", FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
c_enum::defineValue(
obj1,
obj2,
"ILLEGAL_INPUT",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT);
c_enum::defineValue(
obj1,
obj2,
"ERROR_OPENING_FILE",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE);
c_enum::defineValue(
obj1,
obj2,
"NOT_A_FLAC_FILE",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE);
c_enum::defineValue(
obj1,
obj2,
"NOT_WRITABLE",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE);
c_enum::defineValue(
obj1,
obj2,
"BAD_METADATA",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA);
c_enum::defineValue(
obj1,
obj2,
"READ_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR);
c_enum::defineValue(
obj1,
obj2,
"SEEK_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR);
c_enum::defineValue(
obj1,
obj2,
"WRITE_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR);
c_enum::defineValue(
obj1,
obj2,
"RENAME_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR);
c_enum::defineValue(
obj1,
obj2,
"UNLINK_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR);
c_enum::defineValue(
obj1,
obj2,
"MEMORY_ALLOCATION_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR);
c_enum::defineValue(
obj1,
obj2,
"INTERNAL_ERROR",
FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR);
return std::make_tuple(obj1, obj2);
}
};
Function initMetadata1(Env env, FlacAddon& addon) {
EscapableHandleScope scope(env);
return scope.Escape(SimpleIterator::init(env, addon)).As<Function>();
}
}
| 35.520737 | 97 | 0.645887 | [
"object"
] |
67622ccf7b46b7dca6bb40deffa72589c945e6b8 | 14,934 | cpp | C++ | src/slaggy-engine/slaggy-engine/programs/HelloTriangleProgram.cpp | SlaggyWolfie/slaggy-engine | 846235c93a52a96be85c5274a1372bc09c16f144 | [
"MIT"
] | 1 | 2021-09-24T23:13:13.000Z | 2021-09-24T23:13:13.000Z | src/slaggy-engine/slaggy-engine/programs/HelloTriangleProgram.cpp | SlaggyWolfie/slaggy-engine | 846235c93a52a96be85c5274a1372bc09c16f144 | [
"MIT"
] | null | null | null | src/slaggy-engine/slaggy-engine/programs/HelloTriangleProgram.cpp | SlaggyWolfie/slaggy-engine | 846235c93a52a96be85c5274a1372bc09c16f144 | [
"MIT"
] | 2 | 2020-06-24T07:10:13.000Z | 2022-03-08T17:19:12.000Z | #include "HelloTriangleProgram.hpp"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
namespace slaggy
{
int HelloTriangleProgram::run()
{
// Initialize GLFW context with OpenGL version 3.3 using the Core OpenGL profile
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// MacOS-specific code
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// Create window
GLFWwindow* window = glfwCreateWindow(INITIAL_SCREEN_WIDTH, INITIAL_SCREEN_HEIGHT, "My OpenGL Window!", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window." << std::endl;
glfwTerminate();
return INIT_ERROR;
}
glfwMakeContextCurrent(window);
// Alternative suggestions by Resharper
//if (!gladLoadGLLoader(reinterpret_cast<GLADloadproc>(glfwGetProcAddress)))
//if (!gladLoadGLLoader(GLADloadproc(glfwGetProcAddress)))
// Initialize GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD." << std::endl;
return INIT_ERROR;
}
// Set viewport size within window and assign resize function
glViewport(0, 0, INITIAL_SCREEN_WIDTH, INITIAL_SCREEN_HEIGHT);
glfwSetWindowUserPointer(window, this);
auto framebufferResize = [](GLFWwindow* window, const int w, const int h)
{
static_cast<HelloTriangleProgram*>(glfwGetWindowUserPointer(window))->
framebuffer_size_callback(window, w, h);
};
glfwSetFramebufferSizeCallback(window, framebufferResize);
const unsigned int shaderProgram = init_shader(vertexShaderSource, fragmentShaderSource);
//draw_triangle(window, shaderProgram);
//draw_polygon_ebo(window, shaderProgram);
//ex_draw_two_triangles(window, shaderProgram);
//ex_draw_two_triangles_2(window, shaderProgram);
ex_draw_two_triangles_3(window, shaderProgram);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
}
unsigned int HelloTriangleProgram::init_shader(const char* vertexShaderSource, const char* fragmentShaderSource)
{
// Vertex Shader
const unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
glCompileShader(vertexShader);
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
// check for vertex errors
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment Shader
const unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
glCompileShader(fragmentShader);
// check for fragment errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
const unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog);
std::cout << "ERROR:SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
void HelloTriangleProgram::draw_triangle(GLFWwindow* window, const unsigned shaderProgram)
{
// Basic rendering setup
// Shape - Triangle
float vertices[]
{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
unsigned int vao, vbo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
//---------------------------------------------------------------------------//
// > bind the Vertex Array Object first, then bind and set vertex buffer(s),
// > and then configure vertex attributes(s).
// bind vertex array object
glBindVertexArray(vao);
// copy vertex array in a vertex buffer for OpenGL
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// set the vertex attribute pointers
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// > note that this is allowed, the call to glVertexAttribPointer registered VBO
// > as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// > You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO,
// > but this rarely happens. Modifying other VAOs requires a call to glBindVertexArray
// > anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
// > uncomment this call to draw in wireframe polygon
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//---------------------------------------------------------------------------//
// Program Loop (Render Loop)
while (!glfwWindowShouldClose(window))
{
// input (obviously)
process_input(window);
// rendering
glClearColor
(
_clearColor[0],
_clearColor[1],
_clearColor[2],
_clearColor[3]
);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
// > seeing as we only have a single VAO there's no need to bind it every time,
// > but we'll do so to keep things a bit more organized
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
// > no need to unbind it every time
//glBindVertexArray(0);
// double buffering, and poll IO events
glfwSwapBuffers(window);
glfwPollEvents();
}
// Clean-up!
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
void HelloTriangleProgram::draw_polygon_ebo(GLFWwindow* window, const unsigned shaderProgram)
{
// Basic rendering setup
// Shape - Rect (4 points)
float vertices[]
{
0.5f, 0.5f, 0.0f, // > top right
0.5f, -0.5f, 0.0f, // > bottom right
-0.5f, -0.5f, 0.0f, // > bottom left
-0.5f, 0.5f, 0.0f // > top left
};
// > note that we start from 0!
unsigned int indices[]
{
0, 1, 3, // > first triangle
1, 2, 3 // > second triangle
};
unsigned int vao, vbo, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
//---------------------------------------------------------------------------//
// > bind the Vertex Array Object first, then bind and set vertex buffer(s),
// > and then configure vertex attributes(s).
// bind vertex array object
glBindVertexArray(vao);
// copy vertex array in a vertex buffer for OpenGL
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// copy index array in an element buffer for OpenGL
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// set the vertex attribute pointers
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// > note that this is allowed, the call to glVertexAttribPointer registered VBO
// > as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// > You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO,
// > but this rarely happens. Modifying other VAOs requires a call to glBindVertexArray
// > anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
// > uncomment this call to draw in wireframe polygon
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//---------------------------------------------------------------------------//
// Program Loop (Render Loop)
while (!glfwWindowShouldClose(window))
{
// input (obviously)
process_input(window);
// rendering
glClearColor
(
_clearColor[0],
_clearColor[1],
_clearColor[2],
_clearColor[3]
);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
// > seeing as we only have a single VAO there's no need to bind it every time,
// > but we'll do so to keep things a bit more organized
glBindVertexArray(vao);
//glDrawArrays(GL_TRIANGLES, 0, 3);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
// > no need to unbind it every time
glBindVertexArray(0);
// double buffering, and poll IO events
glfwSwapBuffers(window);
glfwPollEvents();
}
// Clean-up!
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ebo);
}
void HelloTriangleProgram::ex_draw_two_triangles(GLFWwindow* window, const unsigned shaderProgram)
{
// vertices
float vertices[]
{
-0.5f, -0.5f, 0.0f, // bottom left
0.0f, -0.5f, 0.0f, // bottom middle
0.0f, 0.5f, 0.0f, // top middle
0.25f, 0.5f, 0.0f, // top middle
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
};
//float vertices[] = {
// // first triangle
// -0.9f, -0.5f, 0.0f, // left
// -0.0f, -0.5f, 0.0f, // right
// -0.45f, 0.5f, 0.0f, // top
// // second triangle
// 0.0f, -0.5f, 0.0f, // left
// 0.9f, -0.5f, 0.0f, // right
// 0.45f, 0.5f, 0.0f // top
//};
// Declare
unsigned int vao, vbo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
// write to vao (by basically selecting it or moving the current pointer to it)
// and then write to vbo
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// remove from selection basically
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
process_input(window);
glClearColor
(
_clearColor[0],
_clearColor[1],
_clearColor[2],
_clearColor[3]
);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 6);
glfwPollEvents();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
void HelloTriangleProgram::ex_draw_two_triangles_2(GLFWwindow* window, const unsigned shaderProgram)
{
// vertices
float tri0[]
{
-0.5f, -0.5f, 0.0f, // bottom left
0.0f, -0.5f, 0.0f, // bottom middle
0.0f, 0.5f, 0.0f, // top middle
};
float tri1[]
{
0.25f, 0.5f, 0.0f, // top middle
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
};
// Declare
unsigned int vao[2], vbo[2];
glGenVertexArrays(2, vao);
glGenBuffers(2, vbo);
// write to vao (by basically selecting it or moving the current pointer to it)
// and then write to vbo
glBindVertexArray(vao[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(tri0), tri0, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(vao[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(tri1), tri1, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// remove from selection basically
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
process_input(window);
glClearColor
(
_clearColor[0],
_clearColor[1],
_clearColor[2],
_clearColor[3]
);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(vao[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(vao[1]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(2, vao);
glDeleteBuffers(2, vbo);
}
void HelloTriangleProgram::ex_draw_two_triangles_3(GLFWwindow* window, const unsigned shaderProgram)
{
// vertices
float tri0[]
{
-0.5f, -0.5f, 0.0f, // bottom left
0.0f, -0.5f, 0.0f, // bottom middle
0.0f, 0.5f, 0.0f, // top middle
};
float tri1[]
{
0.25f, 0.5f, 0.0f, // top middle
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
};
// Declare
unsigned int vao[2], vbo[2];
glGenVertexArrays(2, vao);
glGenBuffers(2, vbo);
// write to vao (by basically selecting it or moving the current pointer to it)
// and then write to vbo
glBindVertexArray(vao[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(tri0), tri0, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(vao[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(tri1), tri1, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// remove from selection basically
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
const unsigned int extraShaderProgram = init_shader(vertexShaderSource, fragmentShader2Source);
while (!glfwWindowShouldClose(window))
{
process_input(window);
glClearColor
(
_clearColor[0],
_clearColor[1],
_clearColor[2],
_clearColor[3]
);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(vao[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glUseProgram(extraShaderProgram);
glBindVertexArray(vao[1]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(2, vao);
glDeleteBuffers(2, vbo);
}
void HelloTriangleProgram::framebuffer_size_callback(GLFWwindow* window, const int width, const int height)
{
glViewport(0, 0, width, height);
}
void HelloTriangleProgram::process_input(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)
{
set_clear_color(_defaultClearColor);
}
if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS)
{
// mildly dark red
set_clear_color(0.7f, 0, 0, 1);
}
}
void HelloTriangleProgram::set_clear_color(const std::array<float, 4>& color)
{
_clearColor = color;
}
void HelloTriangleProgram::set_clear_color(const float r, const float g, const float b, const float a)
{
_clearColor = { r, g, b, a };
}
} | 27.604436 | 124 | 0.685282 | [
"render",
"object",
"shape"
] |
6763f7192f6550646badca5a63b5cda4178e42ea | 8,213 | cpp | C++ | mods/bbsutils/telnetserver.cpp | lmorchard/apone | 1fa82927a9fbcbe953976ac9796f32092ad52ac2 | [
"MIT"
] | 8 | 2015-04-30T07:53:21.000Z | 2018-09-13T22:06:40.000Z | mods/bbsutils/telnetserver.cpp | lmorchard/apone | 1fa82927a9fbcbe953976ac9796f32092ad52ac2 | [
"MIT"
] | 5 | 2015-12-02T09:01:00.000Z | 2018-10-12T16:06:33.000Z | mods/bbsutils/telnetserver.cpp | lmorchard/apone | 1fa82927a9fbcbe953976ac9796f32092ad52ac2 | [
"MIT"
] | 2 | 2018-09-13T15:48:29.000Z | 2021-05-04T15:31:10.000Z | #include <coreutils/log.h>
#include "telnetserver.h"
#include <coreutils/utils.h>
#include <algorithm>
LOGSPACE("utils");
namespace bbs {
using namespace std;
using namespace utils;
// TELNETSERVER
void TelnetServer::OnAccept::exec(NL::Socket* socket, NL::SocketGroup* group, void* reference) {
auto *ts = static_cast<TelnetServer*>(reference);
auto* c = socket->accept();
group->add(c);
LOGD("Connection from %s:%d", c->hostTo(), c->portTo());
ts->sessions.push_back(make_shared<Session>(c, ts));
LOGD("Now %d active sessions", ts->sessions.size());
auto session = ts->sessions.back();
if(ts->connectCallback) {
session->startThread(ts->connectCallback);
}
}
void TelnetServer::OnRead::exec(NL::Socket* socket, NL::SocketGroup* group, void* reference) {
TelnetServer *ts = static_cast<TelnetServer*>(reference);
auto &session = ts->getSession(socket);
auto len = socket->read(&ts->buffer[0], 128);
session.handleIndata(ts->buffer, len);
}
void TelnetServer::OnDisconnect::exec(NL::Socket* socket, NL::SocketGroup* group, void* reference) {
LOGD("Connection from %s disconnected", socket->hostTo());
TelnetServer *ts = static_cast<TelnetServer*>(reference);
auto &session = ts->getSession(socket);
session.close();
group->remove(socket);
}
// Dummy class to make sure NL:init() is called before the socketServer is created
class TelnetInit {
public:
TelnetInit() {
if(!inited)
NL::init();
inited = true;
}
private:
static bool inited;
};
bool TelnetInit::inited = false;
TelnetServer::TelnetServer(int port) : init(new TelnetInit()), no_session(nullptr), socketServer(port), doQuit(false) {
delete init;
init = nullptr;
buffer.resize(128);
group.setCmdOnAccept(&onAccept);
group.setCmdOnRead(&onRead);
group.setCmdOnDisconnect(&onDisconnect);
group.add(&socketServer);
}
void TelnetServer::run() {
try {
while(!doQuit) {
group.listen(500, this);
for(auto it = sessions.begin(); it != sessions.end();) {
Session *session = it->get();
if(!session->valid()) {
LOGD("Session thread join");
session->join();
group.remove(session->getSocket());
session->getSocket()->disconnect();
delete session->getSocket();
it = sessions.erase(it);
} else
it++;
}
}
} catch(...) {
std::terminate();
}
}
void TelnetServer::stop() {
telnetMutex.lock();
doQuit = true;
telnetMutex.unlock();
mainThread.join();
}
void TelnetServer::runThread() {
mainThread = thread {&TelnetServer::run, this};
}
void TelnetServer::setOnConnect(Session::Callback callback) {
connectCallback = callback;
}
TelnetServer::Session& TelnetServer::getSession(NL::Socket* socket) {
for(auto &s : sessions) {
if(s->getSocket() == socket)
return *s;
}
return no_session;
}
// TELNETSESSION
void TelnetServer::Session::handleIndata(vector<uint8_t> &buffer, int len) {
lock_guard<mutex> guard(inMutex);
//buffer.resize(len);
//LOGD("Read [%02x]", buffer);
auto start = inBuffer.size();
for(int i=0; i<len; i++) {
auto b = buffer[i];
if(b >= SE || b == 13 || state != NORMAL) {
switch(state) {
case NORMAL:
if(b == IAC)
state = FOUND_IAC;
else if(b == CR) {
inBuffer.push_back(CR);
state = CR_READ;
}
break;
case CR_READ:
if(b == 0) {
inBuffer.push_back(LF);
} else {
inBuffer.push_back(b);
}
state = NORMAL;
break;
case FOUND_IAC:
if(b >= SE) {
option = b;
state = OPTION;
break;
}
inBuffer.push_back(IAC);
inBuffer.push_back(b);
break;
case OPTION:
if(option == SB) {
option = b;
setOption(option, b);
state = SUB_OPTION;
} else {
setOption(option, b);
state = NORMAL;
}
break;
case SUB_OPTION:
if(b == IAC) {
state = FOUND_IAC_SUB;
} else {
optionData.push_back(b);
}
break;
case FOUND_IAC_SUB:
if(b == SE) {
handleOptionData();
state = NORMAL;
} else {
optionData.push_back(IAC);
optionData.push_back(b);
state = SUB_OPTION;
}
break;
}
} else
inBuffer.push_back(b);
}
if(localEcho)
socket->send(&inBuffer[start], inBuffer.size()-start);
}
void TelnetServer::Session::putChar(int c) {
if(disconnected)
throw disconnect_excpetion{};
write({(uint8_t)c}, 1);
}
int TelnetServer::Session::write(const vector<uint8_t> &data, int len) {
if(disconnected)
throw disconnect_excpetion{};
if(len == -1) len = data.size();
try {
socket->send(&data[0], len);
} catch (NL::Exception e) {
close();
}
return len;
}
void TelnetServer::Session::write(const string &text) {
if(disconnected)
throw disconnect_excpetion{};
try {
socket->send(text.c_str(), text.length());
} catch (NL::Exception e) {
close();
}
}
//void TelnetServer::Session::handleIndata(vector<uint8_t> &buffer);
int TelnetServer::Session::read(std::vector<uint8_t> &data, int len) {
if(disconnected)
throw disconnect_excpetion{};
lock_guard<mutex> guard(inMutex);
auto rc = inBuffer.size();
if(rc > 0) {
data.insert(data.end(), inBuffer.begin(), inBuffer.end());
inBuffer.resize(0);
}
return rc;
}
char TelnetServer::Session::getChar() {
chrono::milliseconds ms { 100 };
while(true) {
if(disconnected)
throw disconnect_excpetion{};
inMutex.lock();
if(inBuffer.size() > 0)
break;
inMutex.unlock();
//this_thread::sleep_for(ms);
sleepms(100);
}
char c = inBuffer[0];
inBuffer.erase(inBuffer.begin());
inMutex.unlock();
return c;
}
bool TelnetServer::Session::hasChar() const {
lock_guard<mutex> guard(inMutex);
return (inBuffer.size() > 0);
}
string TelnetServer::Session::getLine() {
chrono::milliseconds ms { 100 };
while(true) {
if(disconnected)
throw disconnect_excpetion{};
inMutex.lock();
auto f = find(inBuffer.begin(), inBuffer.end(), CR);
if(f != inBuffer.end()) {
string line = string(inBuffer.begin(), f);
inBuffer.erase(inBuffer.begin(), ++f);
if(inBuffer.size() > 0 && inBuffer[0] == LF)
inBuffer.erase(inBuffer.begin());
inMutex.unlock();
return line;
}
inMutex.unlock();
//this_thread::sleep_for(ms);
sleepms(100);
}
}
void TelnetServer::Session::waitExplored() const {
if(termExplored)
return;
chrono::milliseconds ms { 100 };
int delay = 20;
while(true) {
if(disconnected)
throw disconnect_excpetion{};
if(termExplored)
return;
inMutex.lock();
inMutex.unlock();
//this_thread::sleep_for(ms);
sleepms(100);
if(delay-- == 0) {
termExplored = true;
}
}
}
int TelnetServer::Session::getWidth() const {
waitExplored();
return winWidth;
}
int TelnetServer::Session::getHeight() const {
waitExplored();
return winHeight;
}
std::string TelnetServer::Session::getTermType() const {
waitExplored();
return terminalType;
}
void TelnetServer::Session::disconnect() {
tsParent->group.remove(socket);
socket->disconnect();
}
void TelnetServer::Session::close() {
disconnected = true;
}
void TelnetServer::Session::startThread(Session::Callback callback) {
write(vector<uint8_t>({ IAC, DO, TERMINAL_TYPE }));
sessionThread = thread(callback, std::ref(*this));
}
void TelnetServer::Session::setOption(int opt, int val) {
LOGD("Set option %d %d", opt, val);
if(opt == WILL) {
if(val == TERMINAL_TYPE) {
write(std::vector<uint8_t>({ IAC, SB, TERMINAL_TYPE, 1, IAC, SE }));
if(!termExplored) {
write(vector<uint8_t>({ IAC, WILL, ECHO_CHARS }));
write(vector<uint8_t>({ IAC, WILL, SUPRESS_GO_AHEAD }));
write(vector<uint8_t>({ IAC, DO, WINDOW_SIZE }));
}
}
else if(val == WINDOW_SIZE)
write(std::vector<uint8_t>({ IAC, SB, WINDOW_SIZE, 1, IAC, SE }));
}
}
void TelnetServer::Session::handleOptionData() {
LOGD("optionData %d : %d bytes", (int)option, optionData.size());
if(option == TERMINAL_TYPE) {
terminalType = string(reinterpret_cast<char*>(&optionData[1]), optionData.size()-1);
LOGD("Termlinal type is '%s'", terminalType);
} else if(option == WINDOW_SIZE) {
winWidth = (optionData[0] << 8) | (optionData[1]&0xff);
winHeight = (optionData[2] << 8) | (optionData[3]&0xff);
LOGD("Window size is '%d x %d'", winWidth, winHeight);
termExplored = true;
}
optionData.resize(0);
}
}
| 21.613158 | 119 | 0.652502 | [
"vector"
] |
676918da4475cc0ddb5e3bdfadf71314c938f511 | 1,972 | cpp | C++ | src/brew/video/gl/GLShaderProgram.cpp | grrrrunz/brew | 13e17e2f6c9fb0f612c3a0bcabd233085ca15867 | [
"MIT"
] | 1 | 2018-02-09T16:20:50.000Z | 2018-02-09T16:20:50.000Z | src/brew/video/gl/GLShaderProgram.cpp | grrrrunz/brew | 13e17e2f6c9fb0f612c3a0bcabd233085ca15867 | [
"MIT"
] | null | null | null | src/brew/video/gl/GLShaderProgram.cpp | grrrrunz/brew | 13e17e2f6c9fb0f612c3a0bcabd233085ca15867 | [
"MIT"
] | null | null | null | /**
*
* |_ _ _
* |_)| (/_VV
*
* Copyright 2015-2018 Marcus v. Keil
*
* Created on: 03.01.18
*
*/
#include <brew/video/gl/GLShaderProgram.h>
#include <brew/video/gl/GLShader.h>
#include <brew/video/gl/GLExtensions.h>
namespace brew {
using gl = GL20;
GLShaderProgramContextHandle::GLShaderProgramContextHandle(GLContext& context, ShaderProgram& shaderProgram)
: GLObject(context) {
glId = gl::glCreateProgram();
auto& allocationData = getShaderProgramAllocationData(shaderProgram);
// Copy the shaders and clear the allocation data.
auto shaders = allocationData->shaders;
allocationData.reset();
for(auto& shader : shaders) {
auto& glShader = static_cast<GLShaderContextHandle&>(**shader);
gl::glAttachShader(glId, glShader.getGLId());
}
gl::glLinkProgram(glId);
// Note the different functions here: glGetProgram* instead of glGetShader*.
GLint status = 0;
gl::glGetProgramiv(glId, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint maxLength = 0;
gl::glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
gl::glGetProgramInfoLog(glId, maxLength, &maxLength, &infoLog[0]);
// We don't need the program anymore.
gl::glDeleteProgram(glId);
String errorMessage(infoLog.begin(), infoLog.end());
throw ShaderCompileException(errorMessage);
}
// Always detach shaders after a successful link.
for(auto& shader : shaders) {
auto& glShader = static_cast<GLShaderContextHandle&>(**shader);
gl::glDetachShader(glId, glShader.getGLId());
}
}
GLShaderProgramContextHandle::~GLShaderProgramContextHandle() {
gl::glDeleteProgram(glId);
}
void GLShaderProgramContextHandle::bind() {
gl::glUseProgram(glId);
}
void GLShaderProgramContextHandle::unbind() {
gl::glUseProgram(0);
}
} | 26.293333 | 108 | 0.679006 | [
"vector"
] |
6773136059f3469e8b602f92b863910e74a601d1 | 5,651 | cc | C++ | src/restore_driver.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | src/restore_driver.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | src/restore_driver.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2013, All Rights Reserved.
// Author: Cory Maccarrone <darkstar6262@gmail.com>
#include "src/restore_driver.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "boost/filesystem.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "src/backup_library.h"
#include "src/backup_volume.h"
#include "src/callback.h"
#include "src/common.h"
#include "src/file.h"
#include "src/fileset.h"
#include "src/gzip_encoder.h"
#include "src/md5_generator.h"
#include "src/status.h"
using std::pair;
using std::string;
using std::unique_ptr;
using std::vector;
namespace backup2 {
RestoreDriver::RestoreDriver(
const string& backup_filename,
const string& restore_path,
const uint64_t set_number)
: backup_filename_(backup_filename),
restore_path_(restore_path),
set_number_(set_number),
volume_change_callback_(
NewPermanentCallback(this, &RestoreDriver::ChangeBackupVolume)) {
}
int RestoreDriver::Restore() {
// Load up the restore volume. This should already exist and contain at least
// one backup set.
BackupLibrary library(new File(backup_filename_),
volume_change_callback_.get(),
new Md5Generator(),
new GzipEncoder(),
new BackupVolumeFactory());
Status retval = library.Init();
LOG_IF(FATAL, !retval.ok())
<< "Could not init library: " << retval.ToString();
// Get all the file sets contained in the backup.
StatusOr<vector<FileSet*> > filesets = library.LoadFileSets(true);
CHECK(filesets.ok()) << filesets.status().ToString();
LOG(INFO) << "Found " << filesets.value().size() << " backup sets.";
for (FileSet* fileset : filesets.value()) {
LOG(INFO) << " " << fileset->description();
}
// Pick out which set(s) we'll be restoring from, and what files to restore
// from given user input.
// TODO(darkstar62): Implement this. Right now we have limited support, but
// only for restoring from a single fileset.
FileSet* fileset = filesets.value()[set_number_];
// Extract out the directories from the filelist (these'll be ignored by the
// optimization below). We need to create them first anyway.
for (FileEntry* entry : fileset->GetFiles()) {
if (entry->GetBackupFile()->file_type == BackupFile::kFileTypeDirectory) {
boost::filesystem::path restore_path(restore_path_);
boost::filesystem::path file_path(entry->proper_filename());
boost::filesystem::path dest = restore_path;
dest /= file_path;
// Create the destination directories if they don't exist, and open the
// destination file.
File file(dest.string());
CHECK(file.CreateDirectories(false).ok());
}
}
// Determine the chunks we need, and in what order they should come for
// maximum performance.
vector<pair<FileChunk, const FileEntry*> > sorted_chunks =
library.OptimizeChunksForRestore(fileset->GetFiles());
// Start the restore process by iterating through the restore sets.
string last_filename = "";
File* file = NULL;
for (auto chunk_pair : sorted_chunks) {
FileChunk chunk = chunk_pair.first;
const FileEntry* entry = chunk_pair.second;
if (entry->proper_filename() != last_filename) {
if (file) {
file->Close();
delete file;
file = NULL;
}
boost::filesystem::path restore_path(restore_path_);
boost::filesystem::path file_path(entry->proper_filename());
boost::filesystem::path dest = restore_path;
dest /= file_path;
// Create the destination directories if they don't exist, and open the
// destination file.
file = new File(dest.string());
CHECK(file->CreateDirectories(true).ok());
CHECK(file->Open(File::Mode::kModeReadWrite).ok());
last_filename = entry->proper_filename();
}
string data;
retval = library.ReadChunk(chunk, &data);
CHECK(retval.ok()) << retval.ToString();
if (data.size() == 0) {
// Skip empty files.
// TODO(darkstar62): We need a better way to handle this.
continue;
}
// Seek to the location for this chunk.
file->Seek(chunk.chunk_offset);
file->Write(&data.at(0), data.size());
}
if (file) {
file->Close();
delete file;
}
return 0;
}
int RestoreDriver::List() {
// Load up the restore volume. This should already exist and contain at least
// one backup set.
BackupLibrary library(new File(backup_filename_),
volume_change_callback_.get(),
new Md5Generator(),
new GzipEncoder(),
new BackupVolumeFactory());
Status retval = library.Init();
LOG_IF(FATAL, !retval.ok())
<< "Could not init library: " << retval.ToString();
// Get all the file sets contained in the backup.
StatusOr<vector<FileSet*> > filesets = library.LoadFileSets(true);
CHECK(filesets.ok()) << filesets.status().ToString();
LOG(INFO) << "Found " << filesets.value().size() << " backup sets.";
for (uint64_t index = 0; index < filesets.value().size(); ++index) {
FileSet* fileset = filesets.value()[index];
LOG(INFO) << " " << index << " " << fileset->description();
}
return 0;
}
string RestoreDriver::ChangeBackupVolume(string /* needed_filename */) {
// If we're here, it means the backup library couldn't find the needed file,
// and we need to ask the user for the location of the file.
// TODO(darkstar62): The implementation of this will depend on the UI in use.
return "";
}
} // namespace backup2
| 32.477011 | 80 | 0.654574 | [
"vector"
] |
6778ac183798f2ad800fb13e588f7e456f15e131 | 88,720 | cpp | C++ | Engine/Code/engine.cpp | MarcRosellH/Advanced_Graphics_Programming | a7c9a3a968dfe9bb068c673de41e855fd969a220 | [
"MIT"
] | null | null | null | Engine/Code/engine.cpp | MarcRosellH/Advanced_Graphics_Programming | a7c9a3a968dfe9bb068c673de41e855fd969a220 | [
"MIT"
] | null | null | null | Engine/Code/engine.cpp | MarcRosellH/Advanced_Graphics_Programming | a7c9a3a968dfe9bb068c673de41e855fd969a220 | [
"MIT"
] | null | null | null | //
// engine.cpp : Put all your graphics stuff in this file. This is kind of the graphics module.
// In here, you should type all your OpenGL commands, and you can also type code to handle
// input platform events (e.g to move the camera or react to certain shortcuts), writing some
// graphics related GUI options, and so on.
//
#include "buffer_management.h"
#include <imgui.h>
#include <stb_image.h>
#include <stb_image_write.h>
#include <iostream>
GLuint CreateProgramFromSource(String programSource, const char* shaderName)
{
GLchar infoLogBuffer[1024] = {};
GLsizei infoLogBufferSize = sizeof(infoLogBuffer);
GLsizei infoLogSize;
GLint success;
char versionString[] = "#version 430\n";
char shaderNameDefine[128];
sprintf(shaderNameDefine, "#define %s\n", shaderName);
char vertexShaderDefine[] = "#define VERTEX\n";
char fragmentShaderDefine[] = "#define FRAGMENT\n";
const GLchar* vertexShaderSource[] = {
versionString,
shaderNameDefine,
vertexShaderDefine,
programSource.str
};
const GLint vertexShaderLengths[] = {
(GLint) strlen(versionString),
(GLint) strlen(shaderNameDefine),
(GLint) strlen(vertexShaderDefine),
(GLint) programSource.len
};
const GLchar* fragmentShaderSource[] = {
versionString,
shaderNameDefine,
fragmentShaderDefine,
programSource.str
};
const GLint fragmentShaderLengths[] = {
(GLint) strlen(versionString),
(GLint) strlen(shaderNameDefine),
(GLint) strlen(fragmentShaderDefine),
(GLint) programSource.len
};
GLuint vshader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vshader, ARRAY_COUNT(vertexShaderSource), vertexShaderSource, vertexShaderLengths);
glCompileShader(vshader);
glGetShaderiv(vshader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vshader, infoLogBufferSize, &infoLogSize, infoLogBuffer);
ELOG("glCompileShader() failed with vertex shader %s\nReported message:\n%s\n", shaderName, infoLogBuffer);
}
GLuint fshader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fshader, ARRAY_COUNT(fragmentShaderSource), fragmentShaderSource, fragmentShaderLengths);
glCompileShader(fshader);
glGetShaderiv(fshader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fshader, infoLogBufferSize, &infoLogSize, infoLogBuffer);
ELOG("glCompileShader() failed with fragment shader %s\nReported message:\n%s\n", shaderName, infoLogBuffer);
}
GLuint programHandle = glCreateProgram();
glAttachShader(programHandle, vshader);
glAttachShader(programHandle, fshader);
glLinkProgram(programHandle);
glGetProgramiv(programHandle, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(programHandle, infoLogBufferSize, &infoLogSize, infoLogBuffer);
ELOG("glLinkProgram() failed with program %s\nReported message:\n%s\n", shaderName, infoLogBuffer);
}
glUseProgram(0);
glDetachShader(programHandle, vshader);
glDetachShader(programHandle, fshader);
glDeleteShader(vshader);
glDeleteShader(fshader);
return programHandle;
}
u32 LoadProgram(App* app, const char* filepath, const char* programName)
{
String programSource = ReadTextFile(filepath);
Program program = {};
program.handle = CreateProgramFromSource(programSource, programName);
program.filepath = filepath;
program.programName = programName;
program.lastWriteTimestamp = GetFileLastWriteTimestamp(filepath);
app->programs.push_back(program);
return app->programs.size() - 1;
}
Image LoadImage(const char* filename)
{
Image img = {};
stbi_set_flip_vertically_on_load(true);
img.pixels = stbi_load(filename, &img.size.x, &img.size.y, &img.nchannels, 0);
if (img.pixels)
{
img.stride = img.size.x * img.nchannels;
}
else
{
ELOG("Could not open file %s", filename);
}
return img;
}
void FreeImage(Image image)
{
stbi_image_free(image.pixels);
}
GLuint CreateTexture2DFromImage(Image image)
{
GLenum internalFormat = GL_RGB8;
GLenum dataFormat = GL_RGB;
GLenum dataType = GL_UNSIGNED_BYTE;
switch (image.nchannels)
{
case 3: dataFormat = GL_RGB; internalFormat = GL_RGB8; break;
case 4: dataFormat = GL_RGBA; internalFormat = GL_RGBA8; break;
default: ELOG("LoadTexture2D() - Unsupported number of channels");
}
GLuint texHandle;
glGenTextures(1, &texHandle);
glBindTexture(GL_TEXTURE_2D, texHandle);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, image.size.x, image.size.y, 0, dataFormat, dataType, image.pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return texHandle;
}
u32 LoadTexture2D(App* app, const char* filepath)
{
for (u32 texIdx = 0; texIdx < app->textures.size(); ++texIdx)
if (app->textures[texIdx].filepath == filepath)
return texIdx;
Image image = LoadImage(filepath);
if (image.pixels)
{
Texture tex = {};
tex.handle = CreateTexture2DFromImage(image);
tex.filepath = filepath;
u32 texIdx = app->textures.size();
app->textures.push_back(tex);
FreeImage(image);
return texIdx;
}
else
{
return UINT32_MAX;
}
}
Image LoadSkyboxPixels(App* app, const char* filepath)
{
Image image = LoadImage(filepath);
return image;
}
unsigned int loadCubemap(std::vector<std::string> faces, App* app)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data
);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
unsigned int loadIrradiancemap(std::vector<std::string> faces, App* app)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, data
);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
void Init(App* app)
{
// Set up error callback
if (GLVersion.major > 4 || (GLVersion.major == 4 && GLVersion.minor >= 3))
{
glDebugMessageCallback(OnGlError, app);
}
// Get and save current opengl version
app->info.version = (char*)(glGetString(GL_VERSION));
// Get and save current renderer
app->info.renderer = (char*)(glGetString(GL_RENDERER));
// Get and save current vendor
app->info.vendor = (char*)(glGetString(GL_VENDOR));
// Get and save glsl version
app->info.glslVersion = (char*)(glGetString(GL_SHADING_LANGUAGE_VERSION));
// Get and save number of extensions and extension names
glGetIntegerv(GL_NUM_EXTENSIONS, &app->info.numExtensions);
app->info.extensions = new std::string[app->info.numExtensions];
for (int i = 0; i < app->info.numExtensions; ++i)
{
app->info.extensions[i] = (char*)glGetStringi(GL_EXTENSIONS, GLuint(i));
}
/*// Geometry
glGenBuffers(1, &app->embeddedVertices);
glBindBuffer(GL_ARRAY_BUFFER, app->embeddedVertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(app->vertices), app->vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &app->embeddedElements);
glBindBuffer(GL_ARRAY_BUFFER, app->embeddedElements);
glBufferData(GL_ARRAY_BUFFER, sizeof(app->indices), app->indices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Attribute state
glGenVertexArrays(1, &app->vao);
glBindVertexArray(app->vao);
glBindBuffer(GL_ARRAY_BUFFER, app->embeddedVertices);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexV3V2), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexV3V2), (void*)12);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, app->embeddedElements);
glBindVertexArray(0);*/
app->texturedGeometryProgramIdx = LoadProgram(app, "shaders.glsl", "SHOW_TEXTURED_MESH");
Program& texturedGeometryProgram = app->programs[app->texturedGeometryProgramIdx];
app->programUniformTexture = glGetUniformLocation(texturedGeometryProgram.handle, "uTexture");
app->ConvolutionShader = LoadProgram(app, "ConvolutionShader.glsl", "CONVOLUTION");
app->diceTexIdx = LoadTexture2D(app, "dice.png");
app->whiteTexIdx = LoadTexture2D(app, "color_white.png");
app->blackTexIdx = LoadTexture2D(app, "color_black.png");
app->normalTexIdx = LoadTexture2D(app, "color_normal.png");
app->magentaTexIdx = LoadTexture2D(app, "color_magenta.png");
app->waterNormalMapIdx = LoadTexture2D(app, "water_normal.png");
app->waterDudvMapIdx = LoadTexture2D(app, "water_dudv.png");
// Create uniform buffers
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &app->maxUniformBufferSize);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &app->uniformBlockAlignment);
app->uniformBuffer = CreateConstantBuffer(app->maxUniformBufferSize);
// Load models
app->patrickModelIdx = LoadModel(app, "Patrick/Patrick.obj");
app->roomModelIdx = LoadModel(app, "Lake/Erlaufsee.obj");
app->planeModelIdx = LoadModel(app, "Patrick/plane2.obj");
// Entities initalization
app->entities.push_back(Entity{vec3(12.29F, 11.9F, -24.4F), vec3(0,0,0), vec3(0.2F,0.2F,0.2F), app->patrickModelIdx, 1.0F});
app->entities.push_back(Entity{ vec3(2.89F,0.72F,2.37F), vec3(0.0F,90.0F,0.0F), vec3(0.1F,0.1F,0.1F), app->patrickModelIdx, 1.0F });
//app->entities.push_back(Entity{ vec3(0,0,0), vec3(0,0,0), vec3(1,1,1), app->patrickModelIdx });
//app->entities.push_back(Entity{ vec3(6,0,-6), vec3(45,0,90), vec3(1,1,1), app->patrickModelIdx });
//app->entities.push_back(Entity{ vec3(0,0,-6), vec3(0,90,0), vec3(1,1,1), app->patrickModelIdx });
//app->entities.push_back(Entity{ vec3(-6,0,-6), vec3(45,45,45), vec3(1,1,1), app->patrickModelIdx });
//app->entities.push_back(Entity{ vec3(0,0,-50), vec3(0,0,0), vec3(10,10,10), app->patrickModelIdx });
app->entities.push_back(Entity{ vec3(-12.270,-3.67,0), vec3(0,0,0), vec3(1,1,1), app->roomModelIdx });
// Lights initialization
app->lights.push_back(Light{ LIGHTTYPE_DIRECTIONAL, vec3(1,1,1), vec3(0,0,0), vec3(1,-1,1), 100.0F, 2.0F });
//app->lights.push_back(Light{ LIGHTTYPE_DIRECTIONAL, vec3(0,0,1), vec3(0,0,0), vec3(0,0,1), 100.0F, 100.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(1,1,1), vec3(0,1,1), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(1,1,0), vec3(6,1,1), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(1,0,1), vec3(-6,1,1), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(1,0,0), vec3(-6,1,-5), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(0,1,1), vec3(0,0,-5), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(0,1,0), vec3(6,0,-5), vec3(0,0,0), 5.0F, 1.0F });
//app->lights.push_back(Light{ LIGHTTYPE_POINT, vec3(1,0,0), vec3(0,0,-42), vec3(0,0,0), 30.0F, 1.0F });
// Camera initialization
SetCamera(app->cam);
LoadSphere(app);
app->skyBox = LoadProgram(app, "Skybox.glsl", "SKYBOX");
// Shader loading and attribute management
// [Forward Render]
app->texturedMeshProgramIdx = LoadProgram(app, "shaders.glsl", "SHOW_TEXTURED_MESH");
Program& texturedMeshProgram = app->programs[app->texturedMeshProgramIdx];
GLint attributeCount;
glGetProgramiv(texturedMeshProgram.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount);
for (GLint i = 0; i < attributeCount; ++i)
{
GLchar attrName[32];
GLsizei attrLen;
GLint attrSize;
GLenum attrType;
glGetActiveAttrib(texturedMeshProgram.handle, i,
ARRAY_COUNT(attrName),
&attrLen,
&attrSize,
&attrType,
attrName);
GLint attrLocation = glGetAttribLocation(texturedMeshProgram.handle, attrName);
texturedMeshProgram.vertexInputLayout.attributes.push_back({ (u8)attrLocation, GetAttribComponentCount(attrType) });
}
app->texturedMeshProgram_uTexture = glGetUniformLocation(texturedMeshProgram.handle, "uTexture");
app->texturedMeshProgram_uColor = glGetUniformLocation(texturedMeshProgram.handle, "uColor");
// [Water] Clipping plane Program
app->clippedMeshIdx = LoadProgram(app, "shaders.glsl", "CLIPPED_MESHES");
Program& clippedMeshProgram = app->programs[app->clippedMeshIdx];
GLint clippedAttributeCount;
glGetProgramiv(clippedMeshProgram.handle, GL_ACTIVE_ATTRIBUTES, &clippedAttributeCount);
for (GLint i = 0; i < clippedAttributeCount; ++i)
{
GLchar attrName[32];
GLsizei attrLen;
GLint attrSize;
GLenum attrType;
glGetActiveAttrib(clippedMeshProgram.handle, i,
ARRAY_COUNT(attrName),
&attrLen,
&attrSize,
&attrType,
attrName);
GLint attrLocation = glGetAttribLocation(clippedMeshProgram.handle, attrName);
clippedMeshProgram.vertexInputLayout.attributes.push_back({ (u8)attrLocation, GetAttribComponentCount(attrType) });
}
app->clippedProgram_uProj = glGetUniformLocation(clippedMeshProgram.handle, "uProj");
app->clippedProgram_uView = glGetUniformLocation(clippedMeshProgram.handle, "uView");
app->clippedProgram_uModel = glGetUniformLocation(clippedMeshProgram.handle, "uModel");
app->clippedProgram_uClippingPlane = glGetUniformLocation(clippedMeshProgram.handle, "uClippingPlane");
app->clipperProgram_uTexture = glGetUniformLocation(clippedMeshProgram.handle, "uTexture");
app->clipperProgram_uSkybox = glGetUniformLocation(clippedMeshProgram.handle, "uSkybox");
app->clipperProgram_uColor = glGetUniformLocation(clippedMeshProgram.handle, "uColor");
// [Water] Effect Program
app->waterEffectProgramIdx = LoadProgram(app, "shaders.glsl", "WATER_EFFECT");
Program& waterEffectProgram = app->programs[app->waterEffectProgramIdx];
GLint waterEffectAttributeCount;
glGetProgramiv(waterEffectProgram.handle, GL_ACTIVE_ATTRIBUTES, &waterEffectAttributeCount);
for (GLint i = 0; i < waterEffectAttributeCount; ++i)
{
GLchar attrName[32];
GLsizei attrLen;
GLint attrSize;
GLenum attrType;
glGetActiveAttrib(waterEffectProgram.handle, i,
ARRAY_COUNT(attrName),
&attrLen,
&attrSize,
&attrType,
attrName);
GLint attrLocation = glGetAttribLocation(waterEffectProgram.handle, attrName);
waterEffectProgram.vertexInputLayout.attributes.push_back({ (u8)attrLocation, GetAttribComponentCount(attrType) });
}
app->waterEffectProgram_uProj = glGetUniformLocation(waterEffectProgram.handle, "uProj");
app->waterEffectProgram_uView = glGetUniformLocation(waterEffectProgram.handle, "uView");
app->waterEffectProgram_uViewportSize = glGetUniformLocation(waterEffectProgram.handle, "viewportSize");
app->waterEffectProgram_uViewMatInv = glGetUniformLocation(waterEffectProgram.handle, "viewMatInv");
app->waterEffectProgram_uProjMatInv = glGetUniformLocation(waterEffectProgram.handle, "projectionMatInv");
app->waterEffectProgram_uReflectionMap = glGetUniformLocation(waterEffectProgram.handle, "reflectionMap");
app->waterEffectProgram_uReflectionDepth = glGetUniformLocation(waterEffectProgram.handle, "reflectionDepth");
app->waterEffectProgram_uRefractionMap = glGetUniformLocation(waterEffectProgram.handle, "refractionMap");
app->waterEffectProgram_uRefractionDepth = glGetUniformLocation(waterEffectProgram.handle, "refractionDepth");
app->waterEffectProgram_uNormalMap = glGetUniformLocation(waterEffectProgram.handle, "normalMap");
app->waterEffectProgram_uDudvMap = glGetUniformLocation(waterEffectProgram.handle, "dudvMap");
app->waterEffectProgram_uSkybox = glGetUniformLocation(waterEffectProgram.handle, "skyBox");
// [Deferred Render] Geometry Pass Program
app->deferredGeometryPassProgramIdx = LoadProgram(app, "shaders.glsl", "DEFERRED_GEOMETRY_PASS");
Program& deferredGeoPassProgram = app->programs[app->deferredGeometryPassProgramIdx];
GLint deferredGeoAttributeCount;
glGetProgramiv(deferredGeoPassProgram.handle, GL_ACTIVE_ATTRIBUTES, &deferredGeoAttributeCount);
for (GLint i = 0; i < deferredGeoAttributeCount; ++i)
{
GLchar attrName[32];
GLsizei attrLen;
GLint attrSize;
GLenum attrType;
glGetActiveAttrib(deferredGeoPassProgram.handle, i,
ARRAY_COUNT(attrName),
&attrLen,
&attrSize,
&attrType,
attrName);
GLint attrLocation = glGetAttribLocation(deferredGeoPassProgram.handle, attrName);
deferredGeoPassProgram.vertexInputLayout.attributes.push_back({ (u8)attrLocation, GetAttribComponentCount(attrType) });
}
app->deferredGeometryProgram_uTexture = glGetUniformLocation(deferredGeoPassProgram.handle, "uTexture");
app->deferredGeometryProgram_uColor = glGetUniformLocation(deferredGeoPassProgram.handle, "uColor");
app->deferredGeometryProgram_uSkybox = glGetUniformLocation(deferredGeoPassProgram.handle, "skybox");
app->deferredGeometryProgram_uIrradiance = glGetUniformLocation(deferredGeoPassProgram.handle, "irradianceMap");
Program& skyBoxProgram = app->programs[app->skyBox];
app->skyboxProgram_uSkybox = glGetUniformLocation(skyBoxProgram.handle, "skybox");
Program& convolutionProgram = app->programs[app->ConvolutionShader];
app->convolutionProgram_uSkybox = glGetUniformLocation(convolutionProgram.handle, "environmentMap");
// [Deferred Render] Lighting Pass Program
app->deferredLightingPassProgramIdx = LoadProgram(app, "shaders.glsl", "DEFERRED_LIGHTING_PASS");
Program& deferredLightingPassProgram = app->programs[app->deferredLightingPassProgramIdx];
GLint deferredLightAttributeCount;
glGetProgramiv(deferredLightingPassProgram.handle, GL_ACTIVE_ATTRIBUTES, &deferredLightAttributeCount);
for (GLint i = 0; i < deferredLightAttributeCount; ++i)
{
GLchar attrName[32];
GLsizei attrLen;
GLint attrSize;
GLenum attrType;
glGetActiveAttrib(deferredLightingPassProgram.handle, i,
ARRAY_COUNT(attrName),
&attrLen,
&attrSize,
&attrType,
attrName);
GLint attrLocation = glGetAttribLocation(deferredLightingPassProgram.handle, attrName);
deferredLightingPassProgram.vertexInputLayout.attributes.push_back({ (u8)attrLocation, GetAttribComponentCount(attrType) });
}
app->deferredLightingProgram_uGPosition = glGetUniformLocation(deferredLightingPassProgram.handle, "uGPosition");
app->deferredLightingProgram_uGNormals = glGetUniformLocation(deferredLightingPassProgram.handle, "uGNormals");
app->deferredLightingProgram_uGDiffuse = glGetUniformLocation(deferredLightingPassProgram.handle, "uGDiffuse");
// [Framebuffers]
// FORWARD BUFFERS
// [Framebuffer] Forward Buffer
// [Texture] Depth
glGenTextures(1, &app->forwardDepthAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->forwardDepthAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, app->displaySize.x, app->displaySize.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Render
glGenTextures(1, &app->forwardRenderAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->forwardRenderAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &app->forwardFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, app->forwardFrameBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, app->forwardRenderAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, app->forwardDepthAttachmentHandle, 0);
GLenum drawForwardBuffer[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(ARRAY_COUNT(drawForwardBuffer), drawForwardBuffer);
GLenum forwardFrameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (forwardFrameBufferStatus != GL_FRAMEBUFFER_COMPLETE)
{
switch (forwardFrameBufferStatus)
{
case GL_FRAMEBUFFER_UNDEFINED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNDEFINED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); break;
case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNSUPPORTED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"); break;
default: ELOG("Unknown framebuffer status error"); break;
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// DEFERRED BUFFERS
// [Framebuffer] GBuffer
// [Texture] Positions
glGenTextures(1, &app->positionAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->positionAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Normals
glGenTextures(1, &app->normalsAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->normalsAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Diffuse
glGenTextures(1, &app->diffuseAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->diffuseAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Depth
glGenTextures(1, &app->depthAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->depthAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, app->displaySize.x, app->displaySize.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &app->gBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, app->gBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, app->positionAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, app->normalsAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, app->diffuseAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, app->depthAttachmentHandle, 0);
GLenum drawBuffersGBuffer[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(ARRAY_COUNT(drawBuffersGBuffer), drawBuffersGBuffer);
GLenum frameBufferStatusGBuffer = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (frameBufferStatusGBuffer != GL_FRAMEBUFFER_COMPLETE)
{
switch (frameBufferStatusGBuffer)
{
case GL_FRAMEBUFFER_UNDEFINED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNDEFINED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); break;
case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNSUPPORTED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"); break;
default: ELOG("Unknown framebuffer status error"); break;
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// [Framebuffer] FBuffer
glGenTextures(1, &app->finalRenderAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->finalRenderAttachmentHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &app->fBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, app->fBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, app->finalRenderAttachmentHandle, 0);
GLenum drawBuffersFBuffer[] = { GL_COLOR_ATTACHMENT3 };
glDrawBuffers(ARRAY_COUNT(drawBuffersFBuffer), drawBuffersFBuffer);
GLenum frameBufferStatusFBuffer = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (frameBufferStatusFBuffer != GL_FRAMEBUFFER_COMPLETE)
{
switch (frameBufferStatusFBuffer)
{
case GL_FRAMEBUFFER_UNDEFINED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNDEFINED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); break;
case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNSUPPORTED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"); break;
default: ELOG("Unknown framebuffer status error"); break;
}
}
// [Texture] Reflection color
glGenTextures(1, &app->waterReflectionAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->waterReflectionAttachmentHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Reflection depth
glGenTextures(1, &app->waterReflectionDepthAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->waterReflectionDepthAttachmentHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, app->displaySize.x, app->displaySize.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
// [Framebuffer] Reflection buffer
glGenFramebuffers(1, &app->waterReflectionFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, app->waterReflectionFrameBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT4, app->waterReflectionAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, app->waterReflectionDepthAttachmentHandle, 0);
GLenum waterReflectionBuffer[] = { GL_COLOR_ATTACHMENT5 };
glDrawBuffers(ARRAY_COUNT(waterReflectionBuffer), waterReflectionBuffer);
GLenum waterReflectionFrameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (waterReflectionFrameBufferStatus != GL_FRAMEBUFFER_COMPLETE)
{
switch (waterReflectionFrameBufferStatus)
{
case GL_FRAMEBUFFER_UNDEFINED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNDEFINED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); break;
case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNSUPPORTED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"); break;
default: ELOG("Unknown framebuffer status error"); break;
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// [Texture] Refraction color
glGenTextures(1, &app->waterRefractionAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->waterRefractionAttachmentHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, app->displaySize.x, app->displaySize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
// [Texture] Refraction depth
glGenTextures(1, &app->waterRefractionDepthAttachmentHandle);
glBindTexture(GL_TEXTURE_2D, app->waterRefractionDepthAttachmentHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, app->displaySize.x, app->displaySize.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);
// [Framebuffer] Refraction buffer
glGenFramebuffers(1, &app->waterRefractionFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, app->waterRefractionFrameBuffer);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT5, app->waterRefractionAttachmentHandle, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, app->waterRefractionDepthAttachmentHandle, 0);
GLenum waterRefractionBuffer[] = { GL_COLOR_ATTACHMENT5 };
glDrawBuffers(ARRAY_COUNT(waterRefractionBuffer), waterRefractionBuffer);
GLenum waterRefractionFrameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (waterRefractionFrameBufferStatus != GL_FRAMEBUFFER_COMPLETE)
{
switch (waterRefractionFrameBufferStatus)
{
case GL_FRAMEBUFFER_UNDEFINED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNDEFINED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); break;
case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("Framebuffer status error: GL_FRAMEBUFFER_UNSUPPORTED"); break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: ELOG("Framebuffer status error: GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"); break;
default: ELOG("Unknown framebuffer status error"); break;
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
app->currentFBOAttachmentType = FBOAttachmentType::FINAL;
app->mode = Mode_Deferred;
std::vector<std::string> faces =
{
"right.jpg",
"left.jpg",
"top.jpg",
"bottom.jpg",
"front.jpg",
"back.jpg"
};
//LoadCubeMaps(app);
app->cubeMapId = loadCubemap(faces, app);
LoadIrradianceMap(app);
// app->irradianceMapId = loadIrradiancemap(faces, app);
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
}
void LoadIrradianceMap(App* app)
{
glGenFramebuffers(1, &app->captureFBO);
glGenRenderbuffers(1, &app->captureRBO);
glBindFramebuffer(GL_FRAMEBUFFER, app->captureFBO);
glBindRenderbuffer(GL_RENDERBUFFER, app->captureRBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, app->captureRBO);
glGenTextures(1, &app->irradianceMapId);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->irradianceMapId);
for (u32 i = 0; i < 6; i++)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 32, 32, 0,
GL_RGB, GL_FLOAT, nullptr);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindFramebuffer(GL_FRAMEBUFFER, app->captureFBO);
glBindRenderbuffer(GL_RENDERBUFFER, app->captureRBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 32, 32);
Program& convolutionProgram = app->programs[app->ConvolutionShader];
glUseProgram(convolutionProgram.handle);
glm::mat4 captureProjection = glm::perspective(glm::radians(90.0f), 1.0f, 0.1f, 10.0f);
glm::mat4 captureViews[] =
{
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)),
glm::lookAt(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f))
};
i32 projLoc = glGetUniformLocation(convolutionProgram.handle, "projection");
glUniformMatrix4fv(projLoc, 1, GL_FALSE, &captureProjection[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->convolutionProgram_uSkybox, 0);
glViewport(0, 0, 32, 32); // don't forget to configure the viewport to the capture dimensions.
glBindFramebuffer(GL_FRAMEBUFFER, app->captureFBO);
for (unsigned int i = 0; i < 6; ++i)
{
i32 viewLoc = glGetUniformLocation(convolutionProgram.handle, "view");
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &captureViews[i][0][0]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, app->irradianceMapId, 0);
glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
RenderSkybox(app);
}
glUseProgram(0);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Gui(App* app)
{
static bool p_open = true;
static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDocking;
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->GetWorkPos());
ImGui::SetNextWindowSize(viewport->GetWorkSize());
ImGui::SetNextWindowViewport(viewport->ID);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &p_open, window_flags);
ImGui::PopStyleVar();
// DockSpace
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
}
ImGui::Begin("Menu");
ImGui::Text("FPS: %f", 1.0f / app->deltaTime);
if (ImGui::CollapsingHeader("Entities"))
{
std::string name;
for (u32 i = 0; i < app->entities.size(); ++i)
{
Entity& e = app->entities[i];
name = ("Entity " + std::to_string(i));
if (ImGui::TreeNode(name.c_str()))
{
// Position edit
ImGui::DragFloat3("Position", (float*)&e.position, 0.01F);
ImGui::Spacing();
// Rotation edit
ImGui::DragFloat3("Rotation", (float*)&e.rotation, 0.01F);
ImGui::Spacing();
// Scale edit
ImGui::DragFloat3("Scale", (float*)&e.scale, 0.01F);
ImGui::Spacing();
ImGui::DragFloat("Metallic", (float*)&e.metallic, 0.01F, 0, 1);
ImGui::TreePop();
}
}
}
if (ImGui::CollapsingHeader("Lights"))
{
std::string name;
for (u32 i = 0; i < app->lights.size(); ++i)
{
Light& l = app->lights[i];
name = (l.type == LIGHTTYPE_DIRECTIONAL) ? ("Directional Light " + std::to_string(i)):
("Point Light " + std::to_string(i));
if (ImGui::TreeNode(name.c_str()))
{
// Position edit
ImGui::DragFloat3("Position", (float*)&l.position, 0.01F);
ImGui::Spacing();
// Direction edit
ImGui::DragFloat3("Direction", (float*)&l.direction, 0.01F);
ImGui::Spacing();
// Color edit
float c[3] = { l.color.r, l.color.g, l.color.b };
ImGui::ColorEdit3("Color", c);
l.color.r = c[0];
l.color.g = c[1];
l.color.b = c[2];
ImGui::Spacing();
// Intensity edit
ImGui::DragFloat("Intensity", &l.intensity, 0.01F, 0.0F, 0.0F, "%.04f");
l.intensity = (l.intensity < 0.0F) ? 0.0F : l.intensity;
ImGui::Spacing();
// Radius edit
if (l.type == LIGHTTYPE_POINT)
{
ImGui::DragFloat("Radius", &l.radius, 0.01F, 0.0F, 0.0F, "%.04f");
l.radius = (l.radius < 0.0F) ? 0.0F : l.radius;
ImGui::Spacing();
}
ImGui::TreePop();
}
}
}
if (ImGui::CollapsingHeader("Render"))
{
const char* items[] = { "Forward", "Deferred"};
static const char* curr = items[1];
if (ImGui::BeginCombo("##combo", curr))
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
bool is_selected = (curr == items[n]);
if (ImGui::Selectable(items[n], is_selected))
curr = items[n];
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
if (strcmp(curr, items[0]) == 0)
app->mode = Mode::Mode_TexturedMesh;
if (strcmp(curr, items[1]) == 0)
app->mode = Mode::Mode_Deferred;
}
ImGui::EndCombo();
}
const char* items2[] = { "Position", "Normals", "Diffuse", "Depth", "Final" };
static const char* curr2 = items2[4];
if (curr == "Deferred" && ImGui::BeginCombo("##combo2", curr2))
{
for (int n = 0; n < IM_ARRAYSIZE(items2); n++)
{
bool is_selected = (curr2 == items2[n]);
if (ImGui::Selectable(items2[n], is_selected))
curr2 = items2[n];
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
if (strcmp(curr2, items2[0]) == 0)
app->currentFBOAttachmentType = FBOAttachmentType::POSITION;
if (strcmp(curr2, items2[1]) == 0)
app->currentFBOAttachmentType = FBOAttachmentType::NORMALS;
if (strcmp(curr2, items2[2]) == 0)
app->currentFBOAttachmentType = FBOAttachmentType::DIFFUSE;
if (strcmp(curr2, items2[3]) == 0)
app->currentFBOAttachmentType = FBOAttachmentType::DEPTH;
if (strcmp(curr2, items2[4]) == 0)
app->currentFBOAttachmentType = FBOAttachmentType::FINAL;
}
ImGui::EndCombo();
}
}
if (ImGui::CollapsingHeader("Info"))
{
ImGui::Text("OpenGL version: %s", app->info.version.c_str());
ImGui::Text("OpenGL renderer: %s", app->info.renderer.c_str());
ImGui::Text("OpenGL vendor: %s", app->info.vendor.c_str());
ImGui::Text("OpenGL GLSL version: %s", app->info.glslVersion.c_str());
ImGui::Text("OpenGL %d extensions:", app->info.numExtensions);
for (int i = 0; i < app->info.numExtensions; ++i)
{
ImGui::Text("\t%s", app->info.extensions[i].c_str());
}
}
ImGui::End(); // End menu
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{ 0, 0 });
ImGui::Begin("Scene");
ImVec2 size = ImGui::GetContentRegionAvail();
GLuint currentAttachment = 0;
switch (app->mode)
{
case Mode::Mode_TexturedMesh:
currentAttachment = app->forwardRenderAttachmentHandle;
break;
case Mode::Mode_Deferred:
switch (app->currentFBOAttachmentType)
{
case FBOAttachmentType::POSITION:
{
currentAttachment = app->positionAttachmentHandle;
}
break;
case FBOAttachmentType::NORMALS:
{
currentAttachment = app->normalsAttachmentHandle;
}
break;
case FBOAttachmentType::DIFFUSE:
{
currentAttachment = app->diffuseAttachmentHandle;
}
break;
case FBOAttachmentType::DEPTH:
{
currentAttachment = app->depthAttachmentHandle;
}
break;
case FBOAttachmentType::FINAL:
{
currentAttachment = app->finalRenderAttachmentHandle;
}
break;
default:
{} break;
}
break;
default:
{} break;
}
ImGui::Image((ImTextureID)currentAttachment, size, { 0, 1 }, { 1, 0 });
app->isFocused = ImGui::IsWindowFocused();
ImGui::End(); // End scene
ImGui::PopStyleVar();
ImGui::End(); // End dockspace
}
void Update(App* app)
{
HandleInput(app);
app->projectionMat = GetProjectionMatrix(app->cam);
app->viewMat = GetViewMatrix(app->cam);
// Shader hot-reload
for (u64 i = 0; i < app->programs.size(); ++i)
{
Program& program = app->programs[i];
u64 currentTimestamp = GetFileLastWriteTimestamp(program.filepath.c_str());
if (currentTimestamp > program.lastWriteTimestamp)
{
glDeleteProgram(program.handle);
String programSource = ReadTextFile(program.filepath.c_str());
const char* programName = program.programName.c_str();
program.handle = CreateProgramFromSource(programSource, programName);
program.lastWriteTimestamp = currentTimestamp;
}
}
// Push buffer parameters
BindBuffer(app->uniformBuffer);
app->uniformBuffer.data = (u8*)glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY);
app->uniformBuffer.head = 0;
// Global parameters
app->globalParamsOffset = app->uniformBuffer.head;
PushVec3(app->uniformBuffer, app->cam.position);
PushUInt(app->uniformBuffer, app->lights.size());
for (u32 i = 0; i < app->lights.size(); ++i)
{
AlignHead(app->uniformBuffer, sizeof(vec4));
Light& light = app->lights[i];
PushUInt(app->uniformBuffer, light.type);
PushVec3(app->uniformBuffer, light.color);
PushVec3(app->uniformBuffer, light.direction);
PushFloat(app->uniformBuffer, light.intensity);
PushVec3(app->uniformBuffer, light.position);
PushFloat(app->uniformBuffer, light.radius);
}
app->globalParamsSize = app->uniformBuffer.head - app->globalParamsOffset;
// Local parameters
for (u32 i = 0; i < app->entities.size(); ++i)
{
AlignHead(app->uniformBuffer, app->uniformBlockAlignment);
Entity& ref = app->entities[i];
glm::mat4 world = MatrixFromPositionRotationScale(ref.position, ref.rotation, ref.scale);
glm::mat4 worldViewProjectionMatrix = app->projectionMat * app->viewMat * world;
ref.localParamsOffset = app->uniformBuffer.head;
PushMat4(app->uniformBuffer, world);
PushMat4(app->uniformBuffer, worldViewProjectionMatrix);
PushFloat(app->uniformBuffer, ref.metallic);
ref.localParamsSize = app->uniformBuffer.head - ref.localParamsOffset;
}
// Unmap buffer
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void Render(App* app)
{
glClearColor(0.f, 0.f, 0.f, 1.0f);
switch (app->mode)
{
case Mode_TexturedQuad:
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glEnable(GL_DEPTH_TEST);
Program& programTexturedGeometry = app->programs[app->texturedGeometryProgramIdx];
glUseProgram(programTexturedGeometry.handle);
glBindVertexArray(app->vao);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glUniform1i(app->programUniformTexture, 0);
glActiveTexture(GL_TEXTURE0);
GLuint textureHandle = app->textures[app->diceTexIdx].handle;
glBindTexture(GL_TEXTURE_2D, textureHandle);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
glBindVertexArray(0);
glUseProgram(0);
}
break;
case Mode_TexturedMesh:
{
glBindFramebuffer(GL_FRAMEBUFFER, app->forwardFrameBuffer);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Program& texturedMeshProgram = app->programs[app->texturedMeshProgramIdx];
glUseProgram(texturedMeshProgram.handle);
GLuint cp = glGetUniformLocation(texturedMeshProgram.handle, "cameraPos");
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->uniformBuffer.handle, app->globalParamsOffset, app->globalParamsSize);
for (u32 it = 0; it < app->entities.size(); ++it)
{
Entity& ref = app->entities[it];
Model& model = app->models[ref.modelIdx];
Mesh& mesh = app->meshes[model.meshIdx];
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(1), app->uniformBuffer.handle, ref.localParamsOffset, ref.localParamsSize);
for (u32 i = 0; i < mesh.submeshes.size(); ++i)
{
GLuint vao = FindVAO(mesh, i, texturedMeshProgram);
glBindVertexArray(vao);
u32 submeshMaterialIdx = model.materialIdx[i];
Material& submeshMaterial = app->materials[submeshMaterialIdx];
bool hasTex = submeshMaterial.albedoTextureIdx < UINT32_MAX && submeshMaterial.albedoTextureIdx != 0 ? true : false;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, app->textures[hasTex ? submeshMaterial.albedoTextureIdx : app->whiteTexIdx].handle);
glUniform1i(app->texturedMeshProgram_uTexture, 0);
glUniform3f(app->texturedMeshProgram_uColor, (hasTex) ? 1.0F : submeshMaterial.albedo.r, (hasTex) ? 1.0F : submeshMaterial.albedo.g, (hasTex) ? 1.0F : submeshMaterial.albedo.b);
glUniform3f(cp, app->cam.position.x, app->cam.position.y, app->cam.position.z);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->irradianceMapId);
glUniform1i(app->deferredGeometryProgram_uIrradiance, 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->deferredGeometryProgram_uSkybox, 2);
Submesh& submesh = mesh.submeshes[i];
glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset);
}
}
glUseProgram(0);
glDepthMask(GL_FALSE);
Program& skyBoxProgram = app->programs[app->skyBox];
glUseProgram(skyBoxProgram.handle);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->deferredGeometryProgram_uSkybox, 0);
glDepthFunc(GL_LEQUAL);
i32 projLoc = glGetUniformLocation(skyBoxProgram.handle, "projection");
i32 viewLoc = glGetUniformLocation(skyBoxProgram.handle, "view");
glUniformMatrix4fv(projLoc, 1, GL_FALSE, &app->projectionMat[0][0]);
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &app->viewMat[0][0]);
// glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
// glBindTexture(GL_TEXTURE_CUBE_MAP, app->irradianceMapId);
RenderSkybox(app);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glUseProgram(0);
glDepthMask(GL_TRUE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
RenderQuad(app);
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
break;
case Mode_Deferred:
{
/* Water reflection */
glBindFramebuffer(GL_FRAMEBUFFER, app->waterReflectionFrameBuffer);
GLenum buffers[] = { GL_COLOR_ATTACHMENT4 };
glDrawBuffers(ARRAY_COUNT(buffers), buffers);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glEnable(GL_DEPTH_TEST);
// glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CLIP_DISTANCE0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Program& clippedMeshProgram = app->programs[app->clippedMeshIdx];
glUseProgram(clippedMeshProgram.handle);
Camera reflectCamera = app->cam;
reflectCamera.position.y = -reflectCamera.position.y;
reflectCamera.pitch = -reflectCamera.pitch;
reflectCamera.aspectRatio = app->displaySize.x / app->displaySize.y;
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->uniformBuffer.handle, app->globalParamsOffset, app->globalParamsSize);
glUniform4i(app->clippedProgram_uClippingPlane, 0, 1, 0, 0);
for (int i = 0; i < app->entities.size(); ++i)
{
Entity& e = app->entities[i];
Model& model = app->models[e.modelIdx];
Mesh& mesh = app->meshes[model.meshIdx];
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(1), app->uniformBuffer.handle, e.localParamsOffset, e.localParamsSize);
glUniformMatrix4fv(app->clippedProgram_uProj, 1, GL_FALSE, &GetProjectionMatrix(reflectCamera)[0][0]);
glUniformMatrix4fv(app->clippedProgram_uView, 1, GL_FALSE, &GetViewMatrix(reflectCamera)[0][0]);
glUniformMatrix4fv(app->clippedProgram_uModel, 1, GL_FALSE, &MatrixFromPositionRotationScale(e.position, e.rotation, e.scale)[0][0]);
for (u32 i = 0; i < mesh.submeshes.size(); ++i)
{
GLuint vao = FindVAO(mesh, i, clippedMeshProgram);
glBindVertexArray(vao);
u32 subMatIdx = model.materialIdx[i];
Material& submesh_material = app->materials[subMatIdx];
bool hasTex = submesh_material.albedoTextureIdx < UINT32_MAX&& submesh_material.albedoTextureIdx != 0 ? true : false;
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, app->textures[(hasTex) ? submesh_material.albedoTextureIdx : app->whiteTexIdx].handle);
glUniform1i(app->clipperProgram_uTexture, 4);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->clipperProgram_uSkybox, 5);
glUniform3f(app->clipperProgram_uColor, (hasTex) ? 1.0F : submesh_material.albedo.r, (hasTex) ? 1.0F : submesh_material.albedo.g, (hasTex) ? 1.0F : submesh_material.albedo.b);
Submesh& submesh = mesh.submeshes[i];
glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset);
glBindVertexArray(0);
}
}
glUseProgram(0);
glDisable(GL_CLIP_DISTANCE0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
/* Water refraction */
glBindFramebuffer(GL_FRAMEBUFFER, app->waterRefractionFrameBuffer);
GLenum wbuffers[] = { GL_COLOR_ATTACHMENT5 };
glDrawBuffers(ARRAY_COUNT(wbuffers), wbuffers);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CLIP_DISTANCE0);
glUseProgram(clippedMeshProgram.handle);
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->uniformBuffer.handle, app->globalParamsOffset, app->globalParamsSize);
glUniform4i(app->clippedProgram_uClippingPlane, 0, -1, 0, 0);
for (int i = 0; i < app->entities.size(); ++i)
{
Entity& e = app->entities[i];
Model& model = app->models[e.modelIdx];
Mesh& mesh = app->meshes[model.meshIdx];
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(1), app->uniformBuffer.handle, e.localParamsOffset, e.localParamsSize);
glUniformMatrix4fv(app->clippedProgram_uProj, 1, GL_FALSE, &GetProjectionMatrix(app->cam)[0][0]);
glUniformMatrix4fv(app->clippedProgram_uView, 1, GL_FALSE, &GetViewMatrix(app->cam)[0][0]);
glUniformMatrix4fv(app->clippedProgram_uModel, 1, GL_FALSE, &MatrixFromPositionRotationScale(e.position, e.rotation, e.scale)[0][0]);
for (u32 i = 0; i < mesh.submeshes.size(); ++i)
{
GLuint vao = FindVAO(mesh, i, clippedMeshProgram);
glBindVertexArray(vao);
u32 subMatIdx = model.materialIdx[i];
Material& submesh_material = app->materials[subMatIdx];
bool hasTex = submesh_material.albedoTextureIdx < UINT32_MAX&& submesh_material.albedoTextureIdx != 0 ? true : false;
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, app->textures[(hasTex) ? submesh_material.albedoTextureIdx : app->whiteTexIdx].handle);
glUniform1i(app->clipperProgram_uTexture, 4);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->clipperProgram_uSkybox, 5);
glUniform3f(app->clipperProgram_uColor, (hasTex) ? 1.0F : submesh_material.albedo.r, (hasTex) ? 1.0F : submesh_material.albedo.g, (hasTex) ? 1.0F : submesh_material.albedo.b);
Submesh& submesh = mesh.submeshes[i];
glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset);
glBindVertexArray(0);
}
}
glUseProgram(0);
glDisable(GL_CLIP_DISTANCE0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
/* First pass (geometry) */
glBindFramebuffer(GL_FRAMEBUFFER, app->gBuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLenum drawBuffersGBuffer[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
glDrawBuffers(ARRAY_COUNT(drawBuffersGBuffer), drawBuffersGBuffer);
glViewport(0, 0, app->displaySize.x, app->displaySize.y);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_TRUE);
Program& deferredGeometryPassProgram = app->programs[app->deferredGeometryPassProgramIdx];
glUseProgram(deferredGeometryPassProgram.handle);
GLuint cp = glGetUniformLocation(deferredGeometryPassProgram.handle, "cameraPos");
for (const Entity& entity : app->entities)
{
Model& model = app->models[entity.modelIdx];
Mesh& mesh = app->meshes[model.meshIdx];
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(1), app->uniformBuffer.handle, entity.localParamsOffset, entity.localParamsSize);
for (u32 i = 0; i < mesh.submeshes.size(); ++i)
{
GLuint vao = FindVAO(mesh, i, deferredGeometryPassProgram);
glBindVertexArray(vao);
u32 submesh_material_index = model.materialIdx[i];
Material& submesh_material = app->materials[submesh_material_index];
bool hasTex = submesh_material.albedoTextureIdx < UINT32_MAX && submesh_material.albedoTextureIdx != 0 ? true : false;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, app->textures[(hasTex) ? submesh_material.albedoTextureIdx : app->whiteTexIdx].handle);
glUniform1i(app->deferredGeometryProgram_uTexture, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->irradianceMapId);
glUniform1i(app->deferredGeometryProgram_uIrradiance, 1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->deferredGeometryProgram_uSkybox, 2);
glUniform3f(app->deferredGeometryProgram_uColor, (hasTex) ? 1.0F : submesh_material.albedo.r, (hasTex) ? 1.0F : submesh_material.albedo.g, (hasTex) ? 1.0F : submesh_material.albedo.b);
glUniform3f(cp, app->cam.position.x, app->cam.position.y, app->cam.position.z);
Submesh& submesh = mesh.submeshes[i];
glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset);
glBindVertexArray(0);
}
}
glUseProgram(0);
glDepthMask(GL_FALSE);
Program& skyBoxProgram = app->programs[app->skyBox];
glUseProgram(skyBoxProgram.handle);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->deferredGeometryProgram_uSkybox, 0);
glDepthFunc(GL_LEQUAL);
i32 projLoc = glGetUniformLocation(skyBoxProgram.handle, "projection");
i32 viewLoc = glGetUniformLocation(skyBoxProgram.handle, "view");
glUniformMatrix4fv(projLoc, 1, GL_FALSE, &app->projectionMat[0][0]);
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &app->viewMat[0][0]);
RenderSkybox(app);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glUseProgram(0);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//glEnable(GL_BLEND);
//glBlendFunc(GL_ONE, GL_ONE);
glBindFramebuffer(GL_FRAMEBUFFER, app->gBuffer);
Program& waterEffectProgram = app->programs[app->waterEffectProgramIdx];
glUseProgram(waterEffectProgram.handle);
GLenum drawwBuffersGBuffer[] = {GL_COLOR_ATTACHMENT2 };
glDrawBuffers(ARRAY_COUNT(drawwBuffersGBuffer), drawwBuffersGBuffer);
glUniformMatrix4fv(app->waterEffectProgram_uProj, 1, GL_FALSE, &app->projectionMat[0][0]);
glUniformMatrix4fv(app->waterEffectProgram_uView, 1, GL_FALSE, &app->viewMat[0][0]);
glUniform2f(app->waterEffectProgram_uViewportSize, app->displaySize.x, app->displaySize.y);
glUniformMatrix4fv(app->waterEffectProgram_uViewMatInv, 1, GL_FALSE, &glm::inverse(app->viewMat)[0][0]);
glUniformMatrix4fv(app->waterEffectProgram_uProjMatInv, 1, GL_FALSE, &glm::inverse(app->projectionMat)[0][0]);
glActiveTexture(GL_TEXTURE6);
glBindTexture(GL_TEXTURE_2D, app->waterReflectionAttachmentHandle);
glUniform1i(app->waterEffectProgram_uReflectionMap, 6);
glActiveTexture(GL_TEXTURE7);
glBindTexture(GL_TEXTURE_2D, app->waterReflectionDepthAttachmentHandle);
glUniform1i(app->waterEffectProgram_uReflectionDepth, 7);
glActiveTexture(GL_TEXTURE8);
glBindTexture(GL_TEXTURE_2D, app->waterRefractionAttachmentHandle);
glUniform1i(app->waterEffectProgram_uRefractionMap, 8);
glActiveTexture(GL_TEXTURE9);
glBindTexture(GL_TEXTURE_2D, app->waterRefractionDepthAttachmentHandle);
glUniform1i(app->waterEffectProgram_uRefractionDepth, 9);
glActiveTexture(GL_TEXTURE10);
glBindTexture(GL_TEXTURE_2D, app->waterNormalMapIdx);
glUniform1i(app->waterEffectProgram_uNormalMap, 10);
glActiveTexture(GL_TEXTURE11);
glBindTexture(GL_TEXTURE_2D, app->waterDudvMapIdx);
glUniform1i(app->waterEffectProgram_uDudvMap, 11);
glActiveTexture(GL_TEXTURE12);
glBindTexture(GL_TEXTURE_CUBE_MAP, app->cubeMapId);
glUniform1i(app->waterEffectProgram_uSkybox, 12);
{
Model& model = app->models[app->planeModelIdx];
Mesh& mesh = app->meshes[model.meshIdx];
for (u32 i = 0; i < mesh.submeshes.size(); ++i)
{
GLuint vao = FindVAO(mesh, i, waterEffectProgram);
glBindVertexArray(vao);
Submesh& submesh = mesh.submeshes[i];
glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset);
}
}
//glBlitFramebuffer(0, 0, app->displaySize.x, app->displaySize.x, 0, 0, app->displaySize.x, app->displaySize.x, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
/* Second pass (lighting) */
glBindFramebuffer(GL_FRAMEBUFFER, app->fBuffer);
glClear(GL_COLOR_BUFFER_BIT);
GLenum drawBuffersFBuffer[] = { GL_COLOR_ATTACHMENT3 };
glDrawBuffers(ARRAY_COUNT(drawBuffersFBuffer), drawBuffersFBuffer);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
//glDepthMask(GL_FALSE);
Program& deferredLightingPassProgram = app->programs[app->deferredLightingPassProgramIdx];
glUseProgram(deferredLightingPassProgram.handle);
glUniform1i(app->deferredLightingProgram_uGPosition, 1);
glUniform1i(app->deferredLightingProgram_uGNormals, 2);
glUniform1i(app->deferredLightingProgram_uGDiffuse, 3);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, app->positionAttachmentHandle);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, app->normalsAttachmentHandle);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, app->diffuseAttachmentHandle);
glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->uniformBuffer.handle, app->globalParamsOffset, app->globalParamsSize);
glBindFramebuffer(GL_READ_FRAMEBUFFER, app->gBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, app->fBuffer);
glBlitFramebuffer(0, 0, app->displaySize.x, app->displaySize.x, 0, 0, app->displaySize.x, app->displaySize.x, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
RenderQuad(app);
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
break;
default:
break;
}
}
GLuint FindVAO(Mesh& mesh, u32 submeshIndex, const Program& program)
{
Submesh& submesh = mesh.submeshes[submeshIndex];
for (u32 i = 0; i < (u32)submesh.vaos.size(); ++i)
{
if (submesh.vaos[i].programHandle == program.handle)
return submesh.vaos[i].handle;
}
GLuint vaoHandle = 0;
glGenVertexArrays(1, &vaoHandle);
glBindVertexArray(vaoHandle);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBufferHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indexBufferHandle);
for (u32 i = 0; i < program.vertexInputLayout.attributes.size(); ++i)
{
bool attributeWasLinked = false;
for (u32 j = 0; j < submesh.vertexBufferLayout.attributes.size(); ++j)
{
if (program.vertexInputLayout.attributes[i].location == submesh.vertexBufferLayout.attributes[j].location)
{
const u32 index = submesh.vertexBufferLayout.attributes[j].location;
const u32 ncomp = submesh.vertexBufferLayout.attributes[j].componentCount;
const u32 offset = submesh.vertexBufferLayout.attributes[j].offset+submesh.vertexOffset;
const u32 stride = submesh.vertexBufferLayout.stride;
glVertexAttribPointer(index, ncomp, GL_FLOAT, GL_FALSE, stride, (void*)(u64)offset);
glEnableVertexAttribArray(index);
attributeWasLinked = true;
break;
}
}
}
glBindVertexArray(0);
Vao vao = { vaoHandle, program.handle };
submesh.vaos.push_back(vao);
return vaoHandle;
}
void OnGlError(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
if (severity == GL_DEBUG_SEVERITY_NOTIFICATION)
return;
ELOG("OpenGL debug message: %s", message);
switch (source)
{
case GL_DEBUG_SOURCE_API: ELOG(" - source: GL_DEBUG_SOURCE_API"); break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: ELOG(" - source: GL_DEBUG_SOURCE_WINDOW_SYSTEM"); break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: ELOG(" - source: GL_DEBUG_SOURCE_SHADER_COMPILER"); break;
case GL_DEBUG_SOURCE_THIRD_PARTY: ELOG(" - source: GL_DEBUG_SOURCE_THIRD_PARTY"); break;
case GL_DEBUG_SOURCE_APPLICATION: ELOG(" - source: GL_DEBUG_SOURCE_APPLICATION"); break;
case GL_DEBUG_SOURCE_OTHER: ELOG(" - source: GL_DEBUG_SOURCE_OTHER"); break;
}
switch (type)
{
case GL_DEBUG_TYPE_ERROR: ELOG(" - type: GL_DEBUG_TYPE_ERROR"); break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: ELOG(" - type: GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR"); break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: ELOG(" - type: GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR"); break;
case GL_DEBUG_TYPE_PORTABILITY: ELOG(" - type: GL_DEBUG_TYPE_PORTABILITY"); break;
case GL_DEBUG_TYPE_PERFORMANCE: ELOG(" - type: GL_DEBUG_TYPE_PERFORMANCE"); break;
case GL_DEBUG_TYPE_MARKER: ELOG(" - type: GL_DEBUG_TYPE_MARKER"); break;
case GL_DEBUG_TYPE_PUSH_GROUP: ELOG(" - type: GL_DEBUG_TYPE_PUSH_GROUP"); break;
case GL_DEBUG_TYPE_POP_GROUP: ELOG(" - type: GL_DEBUG_TYPE_POP_GROUP"); break;
case GL_DEBUG_TYPE_OTHER: ELOG(" - type: GL_DEBUG_TYPE_OTHER"); break;
}
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: ELOG(" - severity: GL_DEBUG_SEVERITY_HIGH"); break;
case GL_DEBUG_SEVERITY_MEDIUM: ELOG(" - severity: GL_DEBUG_SEVERITY_MEDIUM"); break;
case GL_DEBUG_SEVERITY_LOW: ELOG(" - severity: GL_DEBUG_SEVERITY_LOW"); break;
case GL_DEBUG_SEVERITY_NOTIFICATION: ELOG(" - severity: GL_DEBUG_SEVERITY_NOTIFICATION"); break;
}
}
glm::mat4 MatrixFromPositionRotationScale(const vec3& position, const vec3& rotation, const vec3& scale)
{
glm::mat4 ret = glm::translate(position);
glm::vec3 radianRotation = glm::radians(rotation);
ret = glm::rotate(ret, radianRotation.x, glm::vec3(1.F, 0.F, 0.F));
ret = glm::rotate(ret, radianRotation.y, glm::vec3(0.F, 1.F, 0.F));
ret = glm::rotate(ret, radianRotation.z, glm::vec3(0.F, 0.F, 1.F));
return glm::scale(ret, scale);
}
void RenderQuad(App* app)
{
if (app->quadVAO == 0)
{
float vertices[] = {
-1.0F, 1.0F, 0.0F, 0.0F, 1.0F,
-1.0F, -1.0F, 0.0F, 0.0F, 0.0F,
1.0F, 1.0F, 0.0F, 1.0F, 1.0F,
1.0F, -1.0F, 0.0F, 1.0F, 0.0F,
};
glGenVertexArrays(1, &app->quadVAO);
glGenBuffers(1, &app->quadVBO);
glBindVertexArray(app->quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, app->quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
}
glBindVertexArray(app->quadVAO);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindVertexArray(0);
}
void SetCamera(Camera& cam)
{
cam.position = vec3(0.F, 10.F, 10.F);
cam.front = vec3(0.F, 0.F, -1.F);
cam.up = vec3(0.F, 1.F, 0.F);
cam.worldUp = cam.up;
cam.yaw = -90.F;
cam.pitch = 0.F;
cam.speed = 0.25F;
}
void SetAspectRatio(Camera& cam, float dsX, float dsY)
{
cam.aspectRatio = dsX / dsY;
}
glm::mat4 GetViewMatrix(Camera& cam)
{
return glm::lookAt(cam.position, cam.position + cam.front, cam.up);
}
glm::mat4 GetProjectionMatrix(Camera& cam)
{
return glm::perspective(glm::radians(cam.fov), cam.aspectRatio, cam.nearPlane, cam.farPlane);
}
void HandleInput(App* app)
{
if (app->input.keys[K_W] == BUTTON_PRESSED)app->cam.position += (app->cam.front * app->cam.speed); // Forward
if(app->input.keys[K_A] == BUTTON_PRESSED)app->cam.position -= (app->cam.right * app->cam.speed); // Left
if(app->input.keys[K_S] == BUTTON_PRESSED)app->cam.position -= (app->cam.front * app->cam.speed); // Backward
if(app->input.keys[K_D] == BUTTON_PRESSED)app->cam.position += (app->cam.right * app->cam.speed); // Right
if(app->input.keys[K_X] == BUTTON_PRESSED)app->cam.position += (app->cam.up * app->cam.speed); // Up
if(app->input.keys[K_C] == BUTTON_PRESSED)app->cam.position -= (app->cam.up * app->cam.speed); // Down
if (app->input.mouseButtons[LEFT] == BUTTON_PRESSED)
{
float xOS = app->input.mouseDelta.x * 0.15F; // 0.1F is the sensitivity
float yOS = app->input.mouseDelta.y * 0.15F;
if (app->isFocused)
{
app->cam.yaw += xOS;
app->cam.pitch += yOS;
app->cam.pitch = (app->cam.pitch > 89.F) ? 89.F : app->cam.pitch;
app->cam.pitch = (app->cam.pitch < -89.F) ? -89.F : app->cam.pitch;
glm::vec3 newFront = vec3(
cos(glm::radians(app->cam.yaw)) * cos(glm::radians(app->cam.pitch)),
sin(glm::radians(app->cam.pitch)),
sin(glm::radians(app->cam.yaw)) * cos(glm::radians(app->cam.pitch)));
app->cam.front = glm::normalize(newFront);
app->cam.right = glm::normalize(glm::cross(app->cam.front, app->cam.worldUp));
app->cam.up = glm::normalize(glm::cross(app->cam.right, app->cam.front));
}
}
SetAspectRatio(app->cam, (float)app->displaySize.x, (float)app->displaySize.y);
}
u8 GetAttribComponentCount(const GLenum& type)
{
switch (type)
{
case GL_FLOAT: return 1; break;
case GL_FLOAT_VEC2: return 2; break;
case GL_FLOAT_VEC3: return 3; break;
case GL_FLOAT_VEC4: return 4; break;
case GL_FLOAT_MAT2: return 4; break;
case GL_FLOAT_MAT3: return 9; break;
case GL_FLOAT_MAT4: return 16; break;
case GL_FLOAT_MAT2x3: return 6; break;
case GL_FLOAT_MAT2x4: return 8; break;
case GL_FLOAT_MAT3x2: return 6; break;
case GL_FLOAT_MAT3x4: return 12; break;
case GL_FLOAT_MAT4x2: return 8; break;
case GL_FLOAT_MAT4x3: return 12; break;
case GL_INT: return 1; break;
case GL_INT_VEC2: return 2; break;
case GL_INT_VEC3: return 3; break;
case GL_INT_VEC4: return 4; break;
case GL_UNSIGNED_INT: return 1; break;
case GL_UNSIGNED_INT_VEC2: return 2; break;
case GL_UNSIGNED_INT_VEC3: return 3; break;
case GL_UNSIGNED_INT_VEC4: return 4; break;
case GL_DOUBLE: return 1; break;
case GL_DOUBLE_VEC2: return 2; break;
case GL_DOUBLE_VEC3: return 3; break;
case GL_DOUBLE_VEC4: return 4; break;
case GL_DOUBLE_MAT2: return 4; break;
case GL_DOUBLE_MAT3: return 9; break;
case GL_DOUBLE_MAT4: return 16;
case GL_DOUBLE_MAT2x3: return 6; break;
case GL_DOUBLE_MAT2x4: return 8; break;
case GL_DOUBLE_MAT3x2: return 6; break;
case GL_DOUBLE_MAT3x4: return 12; break;
case GL_DOUBLE_MAT4x2: return 8; break;
case GL_DOUBLE_MAT4x3: return 12; break;
default: return 0; break;
}
// default should return always 0 if no defined type is sent in
// but let's be sure
return 0;
}
void LoadSphere(App* app)
{
glGenVertexArrays(1, &app->sphereVAO);
unsigned int vbo, ebo;
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
std::vector<glm::vec3> positions;
std::vector<glm::vec2> uv;
std::vector<glm::vec3> normals;
std::vector<unsigned int> indices;
const unsigned int X_SEGMENTS = 64;
const unsigned int Y_SEGMENTS = 64;
for (unsigned int y = 0; y <= Y_SEGMENTS; ++y)
{
for (unsigned int x = 0; x <= X_SEGMENTS; ++x)
{
float xSegment = (float)x / (float)X_SEGMENTS;
float ySegment = (float)y / (float)Y_SEGMENTS;
float xPos = std::cos(xSegment * 2.0f * PI) * std::sin(ySegment * PI);
float yPos = std::cos(ySegment * PI);
float zPos = std::sin(xSegment * 2.0f * PI) * std::sin(ySegment * PI);
positions.push_back(glm::vec3(xPos, yPos, zPos));
uv.push_back(glm::vec2(xSegment, ySegment));
normals.push_back(glm::vec3(xPos, yPos, zPos));
}
}
bool oddRow = false;
for (unsigned int y = 0; y < Y_SEGMENTS; ++y)
{
if (!oddRow)
{
for (unsigned int x = 0; x <= X_SEGMENTS; ++x)
{
indices.push_back(y * (X_SEGMENTS + 1) + x);
indices.push_back((y + 1) * (X_SEGMENTS + 1) + x);
}
}
else
{
for (int x = X_SEGMENTS; x >= 0; --x)
{
indices.push_back((y + 1) * (X_SEGMENTS + 1) + x);
indices.push_back(y * (X_SEGMENTS + 1) + x);
}
}
oddRow = !oddRow;
}
app->sphereIdxCount = indices.size();
std::vector<float> data;
for (std::size_t i = 0; i < positions.size(); ++i)
{
data.push_back(positions[i].x);
data.push_back(positions[i].y);
data.push_back(positions[i].z);
if (uv.size() > 0)
{
data.push_back(uv[i].x);
data.push_back(uv[i].y);
}
if (normals.size() > 0)
{
data.push_back(normals[i].x);
data.push_back(normals[i].y);
data.push_back(normals[i].z);
}
}
glBindVertexArray(app->sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), &data[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
float stride = (3 + 2 + 3) * sizeof(float);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (void*)(5 * sizeof(float)));
}
void RenderSphere(App* app)
{
glBindVertexArray(app->sphereVAO);
glDrawElements(GL_TRIANGLE_STRIP, app->sphereIdxCount, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void RenderSkybox(App* app)
{
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_FALSE);
if (app->SKyboxVAO == 0)
{
float skyboxVertices[] = {
// positions
-1000.0f, 1000.0f, -1000.0f,
-1000.0f, -1000.0f, -1000.0f,
1000.0f, -1000.0f, -1000.0f,
1000.0f, -1000.0f, -1000.0f,
1000.0f, 1000.0f, -1000.0f,
-1000.0f, 1000.0f, -1000.0f,
-1000.0f, -1000.0f, 1000.0f,
-1000.0f, -1000.0f, -1000.0f,
-1000.0f, 1000.0f, -1000.0f,
-1000.0f, 1000.0f, -1000.0f,
-1000.0f, 1000.0f, 1000.0f,
-1000.0f, -1000.0f, 1000.0f,
1000.0f, -1000.0f, -1000.0f,
1000.0f, -1000.0f, 1000.0f,
1000.0f, 1000.0f, 1000.0f,
1000.0f, 1000.0f, 1000.0f,
1000.0f, 1000.0f, -1000.0f,
1000.0f, -1000.0f, -1000.0f,
-1000.0f, -1000.0f, 1000.0f,
-1000.0f, 1000.0f, 1000.0f,
1000.0f, 1000.0f, 1000.0f,
1000.0f, 1000.0f, 1000.0f,
1000.0f, -1000.0f, 1000.0f,
-1000.0f, -1000.0f, 1000.0f,
-1000.0f, 1000.0f, -1000.0f,
1000.0f, 1000.0f, -1000.0f,
1000.0f, 1000.0f, 1000.0f,
1000.0f, 1000.0f, 1000.0f,
-1000.0f, 1000.0f, 1000.0f,
-1000.0f, 1000.0f, -1000.0f,
-1000.0f, -1000.0f, -1000.0f,
-1000.0f, -1000.0f, 1000.0f,
1000.0f, -1000.0f, -1000.0f,
1000.0f, -1000.0f, -1000.0f,
-1000.0f, -1000.0f, 1000.0f,
1000.0f, -1000.0f, 1000.0f
};
// skybox VAO
glGenVertexArrays(1, &app->SKyboxVAO);
glGenBuffers(1, &app->SkyboxVBO);
glBindVertexArray(app->SKyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, app->SkyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
//Unbinding
glBindVertexArray(0);
}
glBindVertexArray(app->SKyboxVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);
}
//void HDRImage(const char* filename)
//{
// //load
// int w = 0;
// int h = 0;
// int comp = 0;
// float* hdrData = nullptr;
// if (stbi_is_hdr(filename))
// {
// stbi_set_flip_vertically_on_load(true);
// hdrData = stbi_loadf(filename, &w, &h, &comp, 0);
// }
//
// //unload
// if (hdrData != nullptr)
// {
// stbi_image_free(hdrData);
// hdrData = nullptr;
// }
//}
//void BakeCubemap(App* app)
//{
// /* OpenGLState glState;
// glState.faceCulling = false;
// glState.apply();
//
//
// */
// Program& programTexturedGeometry = app->programs[app->texturedGeometryProgramIdx];
// glUseProgram(programTexturedGeometry.handle);
//
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, )
//
//
//}
| 42.694899 | 204 | 0.656954 | [
"mesh",
"geometry",
"render",
"vector",
"model"
] |
678283179560d339c3a9614bb58832408a04f7cf | 12,831 | hpp | C++ | cplus/libcfsec/cfsec/CFSecISOTZoneBuff.hpp | msobkow/cfsec_2_13 | 4f5b2d82d4265e1373955a63bea4d1a9fc35a64e | [
"Apache-2.0"
] | null | null | null | cplus/libcfsec/cfsec/CFSecISOTZoneBuff.hpp | msobkow/cfsec_2_13 | 4f5b2d82d4265e1373955a63bea4d1a9fc35a64e | [
"Apache-2.0"
] | null | null | null | cplus/libcfsec/cfsec/CFSecISOTZoneBuff.hpp | msobkow/cfsec_2_13 | 4f5b2d82d4265e1373955a63bea4d1a9fc35a64e | [
"Apache-2.0"
] | null | null | null | #pragma once
// Description: C++18 specification for a ISOTZone buffer object.
/*
* org.msscf.msscf.CFSec
*
* Copyright (c) 2020 Mark Stephen Sobkow
*
* MSS Code Factory CFSec 2.13 Security Essentials
*
* Copyright 2020-2021 Mark Stephen Sobkow
*
* This file is part of MSS Code Factory.
*
* MSS Code Factory is available under dual commercial license from Mark Stephen
* Sobkow, or under the terms of the GNU General Public License, Version 3
* or later.
*
* MSS Code Factory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MSS Code Factory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>.
*
* Donations to support MSS Code Factory can be made at
* https://www.paypal.com/paypalme2/MarkSobkow
*
* Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing.
*
* Manufactured by MSS Code Factory 2.12
*/
#include <cflib/ICFLibPublic.hpp>
#include <cfsec/ICFSecSchema.hpp>
namespace cfsec {
class CFSecISOTZonePKey;
class CFSecISOTZoneHPKey;
class CFSecISOTZoneHBuff;
class CFSecISOTZoneByOffsetIdxKey;
class CFSecISOTZoneByUTZNameIdxKey;
class CFSecISOTZoneByIso8601IdxKey;
class CFSecISOTZoneBuff : public cflib::ICFLibCloneableObj
{
public:
static const std::string GENDEFNAME;
static const classcode_t CLASS_CODE;
static const std::string CLASS_NAME;
static const std::string COLNAME_ISOTZONEID;
static const std::string COLNAME_ISO8601;
static const std::string COLNAME_TZNAME;
static const std::string COLNAME_TZHOUROFFSET;
static const std::string COLNAME_TZMINOFFSET;
static const std::string COLNAME_DESCRIPTION;
static const std::string COLNAME_VISIBLE;
static const char* S_INIT_CREATEDBY;
static const char* S_INIT_UPDATEDBY;
static const std::string S_VALUE;
static const std::string S_VALUE_LENGTH;
static const int16_t ISOTZONEID_INIT_VALUE;
static const std::string ISO8601_INIT_VALUE;
static const std::string TZNAME_INIT_VALUE;
static const int16_t TZHOUROFFSET_INIT_VALUE;
static const int16_t TZMINOFFSET_INIT_VALUE;
static const std::string DESCRIPTION_INIT_VALUE;
static const bool VISIBLE_INIT_VALUE;
static const int16_t ISOTZONEID_MIN_VALUE;
static const int16_t TZHOUROFFSET_MIN_VALUE;
static const int16_t TZMINOFFSET_MIN_VALUE;
static const int16_t TZHOUROFFSET_MAX_VALUE;
static const int16_t TZMINOFFSET_MAX_VALUE;
static const std::string::size_type ISO8601_MAX_LEN;
static const std::string::size_type TZNAME_MAX_LEN;
static const std::string::size_type DESCRIPTION_MAX_LEN;
protected:
uuid_t createdByUserId;
std::chrono::system_clock::time_point createdAt;
uuid_t updatedByUserId;
std::chrono::system_clock::time_point updatedAt;
int16_t requiredISOTZoneId;
std::string* requiredIso8601;
std::string* requiredTZName;
int16_t requiredTZHourOffset;
int16_t requiredTZMinOffset;
std::string* requiredDescription;
bool requiredVisible;
int32_t requiredRevision;
public:
CFSecISOTZoneBuff();
CFSecISOTZoneBuff( const CFSecISOTZoneBuff& src );
virtual ~CFSecISOTZoneBuff();
virtual const std::string& getClassName() const;
virtual cflib::ICFLibCloneableObj* clone();
virtual const classcode_t getClassCode() const;
virtual bool implementsClassCode( const classcode_t argClassCode );
virtual const uuid_ptr_t getCreatedByUserId() const;
virtual void setCreatedByUserId( const uuid_ptr_t value );
virtual const std::chrono::system_clock::time_point& getCreatedAt() const;
virtual void setCreatedAt( const std::chrono::system_clock::time_point& value );
virtual const uuid_ptr_t getUpdatedByUserId() const;
virtual void setUpdatedByUserId( const uuid_ptr_t value );
virtual const std::chrono::system_clock::time_point& getUpdatedAt() const;
virtual void setUpdatedAt( const std::chrono::system_clock::time_point& value );
virtual const int16_t getRequiredISOTZoneId() const;
virtual const int16_t* getRequiredISOTZoneIdReference() const;
virtual void setRequiredISOTZoneId( const int16_t value );
virtual const std::string& getRequiredIso8601() const;
virtual const std::string* getRequiredIso8601Reference() const;
virtual void setRequiredIso8601( const std::string& value );
virtual const std::string& getRequiredTZName() const;
virtual const std::string* getRequiredTZNameReference() const;
virtual void setRequiredTZName( const std::string& value );
virtual const int16_t getRequiredTZHourOffset() const;
virtual const int16_t* getRequiredTZHourOffsetReference() const;
virtual void setRequiredTZHourOffset( const int16_t value );
virtual const int16_t getRequiredTZMinOffset() const;
virtual const int16_t* getRequiredTZMinOffsetReference() const;
virtual void setRequiredTZMinOffset( const int16_t value );
virtual const std::string& getRequiredDescription() const;
virtual const std::string* getRequiredDescriptionReference() const;
virtual void setRequiredDescription( const std::string& value );
virtual const bool getRequiredVisible() const;
virtual const bool* getRequiredVisibleReference() const;
virtual void setRequiredVisible( const bool value );
virtual int32_t getRequiredRevision() const;
virtual void setRequiredRevision( int32_t value );
virtual size_t hashCode() const;
bool operator <( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator <( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator <( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator <( const CFSecISOTZonePKey& rhs );
bool operator <( const CFSecISOTZoneHPKey& rhs );
bool operator <( const CFSecISOTZoneHBuff& rhs );
bool operator <( const CFSecISOTZoneBuff& rhs );
bool operator <=( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator <=( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator <=( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator <=( const CFSecISOTZonePKey& rhs );
bool operator <=( const CFSecISOTZoneHPKey& rhs );
bool operator <=( const CFSecISOTZoneHBuff& rhs );
bool operator <=( const CFSecISOTZoneBuff& rhs );
bool operator ==( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator ==( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator ==( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator ==( const CFSecISOTZonePKey& rhs );
bool operator ==( const CFSecISOTZoneHPKey& rhs );
bool operator ==( const CFSecISOTZoneHBuff& rhs );
bool operator ==( const CFSecISOTZoneBuff& rhs );
bool operator !=( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator !=( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator !=( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator !=( const CFSecISOTZonePKey& rhs );
bool operator !=( const CFSecISOTZoneHPKey& rhs );
bool operator !=( const CFSecISOTZoneHBuff& rhs );
bool operator !=( const CFSecISOTZoneBuff& rhs );
bool operator >=( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator >=( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator >=( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator >=( const CFSecISOTZonePKey& rhs );
bool operator >=( const CFSecISOTZoneHPKey& rhs );
bool operator >=( const CFSecISOTZoneHBuff& rhs );
bool operator >=( const CFSecISOTZoneBuff& rhs );
bool operator >( const CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator >( const CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator >( const CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator >( const CFSecISOTZonePKey& rhs );
bool operator >( const CFSecISOTZoneHPKey& rhs );
bool operator >( const CFSecISOTZoneHBuff& rhs );
bool operator >( const CFSecISOTZoneBuff& rhs );
cfsec::CFSecISOTZoneBuff operator =( cfsec::CFSecISOTZoneBuff& src );
cfsec::CFSecISOTZoneBuff operator =( cfsec::CFSecISOTZoneHBuff& src );
virtual std::string toString();
};
}
namespace std {
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator <(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator <=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator ==(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator !=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator >=(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByOffsetIdxKey& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByUTZNameIdxKey& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneByIso8601IdxKey& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZonePKey& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHPKey& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneHBuff& rhs );
bool operator >(const cfsec::CFSecISOTZoneBuff& lhs, const cfsec::CFSecISOTZoneBuff& rhs );
template<> struct hash<cfsec::CFSecISOTZoneBuff> {
typedef cfsec::CFSecISOTZoneBuff argument_type;
typedef size_t result_type;
result_type operator()(argument_type const& s) const {
return( s.hashCode() );
}
};
}
| 47.876866 | 105 | 0.766971 | [
"object"
] |
678b05ce6d1046cafa86e310eda697d59450c40d | 960 | cpp | C++ | src/luogu/P1007/23690813_ac_100_25ms_808k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/P1007/23690813_ac_100_25ms_808k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/P1007/23690813_ac_100_25ms_808k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cctype>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <iostream>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <map>
using namespace std;
int read() {
int ret;
bool f = 0;
char ch;
while(!isdigit(ch = getchar())) (ch == '-') && (f = 1);
for(ret = ch - '0'; isdigit(ch = getchar()); ret *= 10, ret += ch - '0');
return f ? -ret : ret;
}
void print(int x) {
if(x < 0) {
x = -x;
putchar('-');
}
if(x > 9) print(x / 10);
putchar(x % 10 + '0');
}
int main() {
int l = read(), n = read(), maxans = 0, minans = 0;
for(int i = 1; i <= n; ++i) {
int t = read();
maxans = max(maxans, max(t, (l + 1 - t)));
minans = max(minans, min(t, (l + 1 - t)));
}
print(minans);
putchar(' ');
print(maxans);
putchar('\n');
return 0;
} | 20 | 77 | 0.50625 | [
"vector"
] |
096b468f9bfcc08291e5d14b88e2f4dd9ca8a9f9 | 15,674 | cpp | C++ | src/wire/core/detail/reference_resolver.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 5 | 2016-04-07T19:49:39.000Z | 2021-08-03T05:24:11.000Z | src/wire/core/detail/reference_resolver.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | null | null | null | src/wire/core/detail/reference_resolver.cpp | zmij/wire | 9981eb9ea182fc49ef7243eed26b9d37be70a395 | [
"Artistic-2.0"
] | 1 | 2020-12-27T11:47:31.000Z | 2020-12-27T11:47:31.000Z | /*
* reference_resolver.cpp
*
* Created on: Oct 3, 2016
* Author: zmij
*/
#include <wire/core/detail/reference_resolver.hpp>
#include <wire/core/detail/configuration_options.hpp>
#include <wire/core/connector.hpp>
#include <wire/core/reference.hpp>
#include <wire/core/proxy.hpp>
#include <wire/core/locator.hpp>
#include <wire/util/make_unique.hpp>
#include <wire/util/timed_cache.hpp>
#include <tbb/concurrent_hash_map.h>
#include <mutex>
#if DEBUG_OUTPUT >= 1
#include <iostream>
#endif
namespace wire {
namespace core {
namespace detail {
struct reference_resolver::impl {
using mutex_type = ::std::mutex;
using lock_guard = ::std::lock_guard<mutex_type>;
using endpoint_rotation_type = endpoint_rotation< endpoint_list >;
using endpoint_rotation_ptr = ::std::shared_ptr< endpoint_rotation_type >;
using endpoint_cache_item = util::timed_cache< endpoint_rotation_type, 10 >;
using hash_value_type = ::std::size_t;
using endpoint_cache = ::tbb::concurrent_hash_map<hash_value_type, endpoint_cache_item>;
using endpoint_accessor = endpoint_cache::accessor;
using endpoint_const_accessor = endpoint_cache::const_accessor;
using shared_count = ::std::shared_ptr< ::std::size_t >;
connector_weak_ptr connector_;
mutex_type locator_mtx_;
reference_data locator_ref_;
locator_prx locator_;
locator_registry_prx locator_reg_;
endpoint_cache endpoints_;
void
set_owner(connector_ptr c)
{
connector_ = c;
auto const& options = c->options();
locator_ref_ = options.locator_ref;
}
connector_ptr
get_connector()
{
auto cnctr = connector_.lock();
if (!cnctr) {
throw errors::connector_destroyed{"Connector was already destroyed"};
}
return cnctr;
}
void
get_locator_async(functional::callback< locator_prx > result,
functional::exception_callback exception,
context_type const& ctx,
invocation_options const& opts)
{
using functional::report_exception;
auto cnctr = get_connector();
locator_prx loc;
{
lock_guard lock{locator_mtx_};
loc = locator_;
}
if (locator_ref_.object_id.empty()) {
auto const& options = cnctr->options();
locator_ref_ = options.locator_ref;
}
if (!loc && !locator_ref_.object_id.empty()) {
#if DEBUG_OUTPUT >= 1
::std::cerr <<::getpid() << " Connecting to locator "
<< locator_ref_ << "\n";
#endif
try {
if (locator_ref_.endpoints.empty())
throw errors::runtime_error{ "Locator reference must have endpoints" };
object_prx prx = cnctr->make_proxy(locator_ref_);
checked_cast_async< locator_proxy >(
prx,
[this, result](locator_prx loc)
{
if (loc) {
set_locator(loc);
}
try {
result(loc);
} catch (...) {}
},
[exception](::std::exception_ptr ex)
{
#if DEBUG_OUTPUT >= 1
::std::cerr <<::getpid() << " Exception in checked_cast<locator_proxy>\n";
#endif
report_exception(exception, ex);
}, nullptr, ctx, opts
);
} catch (...) {
report_exception(exception, ::std::current_exception());
}
} else {
try {
result(loc);
} catch (...) {}
}
}
void
get_locator_registry_async(
functional::callback< locator_registry_prx > result,
functional::exception_callback exception,
context_type const& ctx,
invocation_options const& opts)
{
using functional::report_exception;
locator_registry_prx reg;
{
lock_guard lock{locator_mtx_};
reg = locator_reg_;
}
if (!reg) {
get_locator_async(
[this, result, exception, ctx, opts](locator_prx loc)
{
if (loc) {
#if DEBUG_OUTPUT >= 1
::std::cerr <<::getpid() << " Try to obtain locator registry proxy from locator "
<< *loc << "\n";
#endif
loc->get_registry_async(
[this, result](locator_registry_prx reg)
{
if (reg) {
lock_guard lock{locator_mtx_};
locator_reg_ = reg;
}
try {
result(locator_reg_);
} catch (...) {}
}, exception, nullptr, ctx, opts);
} else {
try {
result(locator_reg_);
} catch (...) {}
}
},
#if DEBUG_OUTPUT >= 1
[exception](::std::exception_ptr ex)
{
::std::cerr <<::getpid() << " Exception in get_locator_registry\n";
report_exception(exception, ex);
},
#else
exception,
#endif
ctx, opts);
} else {
try {
result(reg);
} catch (...) {}
}
}
void
set_locator(locator_prx loc)
{
lock_guard lock{locator_mtx_};
locator_ref_ = loc->wire_get_reference()->data();
locator_ = loc;
}
// TODO Make the member static and pass connector_ptr as argument
static void
get_connection(
connector_ptr connector,
endpoint_rotation_ptr ep_rot,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
shared_count retries,
invocation_options const& opts)
{
using functional::report_exception;
if (!connector) {
report_exception(exception,
errors::connector_destroyed{"Connector was already destroyed"});
}
++(*retries);
connector->get_outgoing_connection_async(
ep_rot->next(), result,
[connector, ep_rot, result, exception, retries, opts](::std::exception_ptr ex)
{
// Check retry count
if (*retries < ep_rot->size()) {
// Rethrow the exception
try {
::std::rethrow_exception(ex);
} catch (errors::connection_refused const& ex) {
// Retry if the exception is connection_refused
// and retry count doesn't exceed retry count
get_connection(connector, ep_rot, result,
exception, retries, opts);
} catch (...) {
// Other exceptions are not retryable at this level
report_exception(exception, ::std::current_exception());
}
} else {
// Out of endpoint variants
report_exception(exception, ex);
}
},
opts);
}
void
get_connection(endpoint_rotation_ptr ep_rot,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
invocation_options const& opts)
{
auto retries = ::std::make_shared<::std::size_t>(0);
get_connection(connector_.lock(), ep_rot, result, exception, retries, opts);
}
bool
get_connection(endpoint_const_accessor const& eps,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
invocation_options const& opts )
{
if (!eps.empty() && eps->second && !eps->second.stale()) {
endpoint_rotation_ptr ep_rot = eps->second;
if (!ep_rot)
return false;
auto retries = ::std::make_shared<::std::size_t>(0);
get_connection(ep_rot, result, exception, opts);
return true;
}
return false;
}
void
cache_store(hash_value_type key, endpoint_rotation_ptr const& eps)
{
endpoint_accessor f;
endpoints_.insert(f, key);
f->second = eps;
}
void
cache_store(reference_data const& ref, endpoint_rotation_ptr const& eps)
{
cache_store(hash(*eps), eps);
cache_store(id_facet_hash(ref), eps);
if (ref.adapter.is_initialized()) {
cache_store(hash(ref.adapter.get()), eps);
}
}
bool
cache_lookup(reference_data const& ref,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
invocation_options const& opts)
{
endpoint_accessor eps;
if (!ref.endpoints.empty()) {
// Fixed endpoints list, return one
auto eps_hash = hash(ref.endpoints);
if (endpoints_.insert(eps, eps_hash) || !eps->second) {
eps->second = endpoint_cache_item{ ref.endpoints };
}
return get_connection(eps, result, exception, opts);
}
// Find endpoints by object_id
auto id_hash = id_facet_hash(ref);
if (endpoints_.find(eps, id_hash) && get_connection(eps, result, exception, opts)) {
return true;
}
if (ref.adapter.is_initialized()) {
// Find endpoints by adapter id
auto adapter_hash = hash(ref.adapter.get());
if (endpoints_.find(eps, adapter_hash)
&& get_connection(eps, result, exception, opts)) {
// Cache to object id
endpoint_accessor oid_eps;
endpoints_.insert(oid_eps, id_hash);
oid_eps->second = eps->second;
return true;
}
}
return false;
}
void
resolve_reference_async(reference_data const& ref,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
invocation_options const& opts
)
{
using functional::report_exception;
if (!cache_lookup(ref, result, exception, opts)) {
// Don't check endpoints - they are checked by lookup function
get_locator_async(
[this, ref, result, exception, opts](locator_prx loc)
{
if (!loc) {
report_exception( exception, errors::no_locator{} );
return;
}
if (ref.adapter.is_initialized()) {
loc->find_adapter_async(ref.adapter.get(),
[this, ref, result, exception, opts](object_prx obj)
{
auto const& objref = obj->wire_get_reference()->data();
auto eps = make_enpoint_rotation(objref);
cache_store(ref, eps);
get_connection(eps, result, exception, opts);
},
exception, nullptr, no_context, opts);
} else {
// Lookup by object id
loc->find_object_async(ref.object_id,
[this, ref, result, exception, opts](object_prx obj)
{
auto const& objref = obj->wire_get_reference()->data();
// Well-known object can have no endpoints initialized, only adapter set
if (objref.endpoints.empty()) {
// Resolve by adapter, if any
if (objref.adapter.is_initialized()) {
resolve_reference_async(objref, result, exception, opts);
} else {
// This is an error situation - locator returned
// a proxy containing only object id
report_exception( exception, object_not_found{ ref.object_id } );
}
} else {
auto eps = make_enpoint_rotation(objref);
cache_store(ref, eps);
get_connection(eps, result, exception, opts);
}
}, exception, nullptr, no_context, opts);
}
}, exception, no_context, opts);
}
}
endpoint_rotation_ptr
make_enpoint_rotation(
const wire::core::reference_data& objref)
{
return ::std::make_shared<endpoint_rotation_type>(objref.endpoints);
}
};
reference_resolver::reference_resolver()
: pimpl_{ util::make_unique<impl>() }
{
}
reference_resolver::reference_resolver(connector_ptr cnctr, reference_data loc_ref)
: pimpl_{ util::make_unique<impl>() }
{
pimpl_->connector_ = cnctr;
pimpl_->locator_ref_ = loc_ref;
}
reference_resolver::reference_resolver(reference_resolver&& rhs)
: pimpl_{ ::std::move(rhs.pimpl_) }
{
}
reference_resolver::~reference_resolver() = default;
void
reference_resolver::set_owner(connector_ptr c)
{
pimpl_->set_owner(c);
}
void
reference_resolver::set_locator(locator_prx loc)
{
pimpl_->set_locator(loc);
}
void
reference_resolver::get_locator_async(functional::callback<locator_prx> result,
functional::exception_callback exception,
context_type const& ctx,
invocation_options const& opts) const
{
pimpl_->get_locator_async(result, exception, ctx, opts);
}
void
reference_resolver::get_locator_registry_async(
functional::callback<locator_registry_prx> result,
functional::exception_callback exception,
context_type const& ctx,
invocation_options const& opts) const
{
pimpl_->get_locator_registry_async(result, exception, ctx, opts);
}
void
reference_resolver::resolve_reference_async(reference_data const& ref,
functional::callback<connection_ptr> result,
functional::exception_callback exception,
invocation_options const& opts
) const
{
pimpl_->resolve_reference_async(ref, result, exception, opts);
}
} /* namespace detail */
} /* namespace core */
} /* namespace wire */
| 35.461538 | 105 | 0.508613 | [
"object"
] |
09727b13eb64d0956730b84c4a8ed0d41957d7c1 | 842 | cc | C++ | solutions/kattis/molekule.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/kattis/molekule.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/kattis/molekule.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define debug(...) 0
#ifdef LOCAL
#include "../../_library/cc/debug.h"
#endif
void dfs(vector<vector<int>>& adj, vector<int>& col, int u, int c) {
col[u] = c;
for (int v : adj[u]) {
if (!col[v])
dfs(adj, col, v, c == 1 ? 2 : 1);
}
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
#if defined(FILE) && !defined(LOCAL)
freopen(FILE ".in", "r", stdin), freopen(FILE ".out", "w", stdout);
#endif
int N;
cin >> N;
vector<array<int, 2>> edges(N - 1);
vector<vector<int>> adj(N);
for (int i = 0; i < N - 1; ++i) {
int u, v;
cin >> u >> v;
--u, --v;
edges[i] = {u, v};
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> col(N);
dfs(adj, col, 0, 0);
for (auto& [u, v] : edges) {
cout << (int)(col[u] == 1) << "\n";
}
}
| 20.047619 | 69 | 0.515439 | [
"vector"
] |
097af6c4bf124660e76b1842a4a1416b17adb6fa | 3,579 | cpp | C++ | Sample/LTest.cpp | dora-BYR/MemoryPool | 6cb25ad205523436deef6b156e0ba43952453bac | [
"MIT"
] | 11 | 2016-05-21T22:00:14.000Z | 2021-08-07T02:34:23.000Z | Sample/LTest.cpp | dora-BYR/MemoryPool | 6cb25ad205523436deef6b156e0ba43952453bac | [
"MIT"
] | 1 | 2016-05-21T22:00:39.000Z | 2016-05-21T22:00:39.000Z | Sample/LTest.cpp | dora-BYR/MemoryPool | 6cb25ad205523436deef6b156e0ba43952453bac | [
"MIT"
] | 2 | 2016-10-13T09:32:08.000Z | 2017-07-15T09:31:35.000Z | //
// Created by 龙辉 on 16/4/12.
// Copyright (c) 2016 yuemo studio. All rights reserved.
//
#include "LTest.h"
#include "LMemoryPool.h"
#include <string>
void LTest::test_memPool() {
printf("//////////////////////////////// 内存池功能测试 ////////////////////////////////\n");
LTestObject1 * pObject = nullptr;
auto pPool = NS_LONG::LMemoryPool::create(sizeof(LTestObject1), 200);
pPool->getObject(pObject);
pObject->setID(201604);
printf("sizeof(LTestObject) = %d\n", sizeof(LTestObject1));
printf("sizeof(* pObject) = %d\n", sizeof(* pObject));
printf("1: object.m_nId = %d, object.m_nName = %s\n", pObject->getID(), pObject->getName());
pPool->printStatus();
pPool->recycleObject(pObject);
pPool->printStatus();
//
LTestObject1 * pObject1 = nullptr;
pPool->getObject(pObject1);
pObject1->setID(201605);
pObject1->setName("test object1");
printf("2: object1.m_nId = %d, object1.m_nName = %s\n", pObject1->getID(), pObject1->getName());
pPool->printStatus();
// 增加新对象大小的内存区
// add pool trunk with size of another new class object
pPool->addPoolTrunk(sizeof(LTestObject2), 30);
pPool->printStatus();
LTestObject2 * pObject2 = nullptr;
for (int i = 0; i < 22; ++i) {
pPool->getObject(pObject2);
pObject2->setID(i);
pObject2->setSex("famale");
pObject2->setName("test object2");
printf("2: object2.m_nId = %d, object2.m_nName = %s, object2.m_szSex = %s\n", pObject2->getID(), pObject2->getName(), pObject2->getSex());
}
pPool->printStatus();
// 内存池区自动智能扩展测试
printf("Test for auto-reSize to pool (size: 30 -> 60)\n");
for (int i = 0; i < 13; ++i) {
pPool->getObject(pObject2);
pObject2->setID(i);
pObject2->setSex("famale");
pObject2->setName("test object2");
printf("2: object2.m_nId = %d, object2.m_nName = %s, object2.m_szSex = %s\n", pObject2->getID(), pObject2->getName(), pObject2->getSex());
}
pPool->printStatus();
// 非对象方式获取和使用内存
int nDataBufferLength = 512;
int nBlockInitCount = 1;
pPool->addPoolTrunk(nDataBufferLength, nBlockInitCount);
pPool->printStatus();
void * p = pPool->getBuffer(nDataBufferLength);
const char * szName = "use memory as buffer";
memcpy(p, szName, strlen(szName));
printf("3: string = %s\n", p);
pPool->printStatus();
// 销毁内存池
delete pPool;
pPool = nullptr;
printf("3: string = %s\n", p);
}
void LTest::test_performance() {
printf("\n//////////////////////////////// 性能测试 ////////////////////////////////\n");
unsigned long nCount = 1867284;
unsigned long nInitCount = 2000000;
// 系统方法创建对象
clock_t tick1,tick2;
tick1 = clock();
// new
for (int i = 0; i < nCount; ++i) {
LTestObject * pObject = new LTestObject();
// delete pObject1;
// pObject1 = nullptr;
}
tick2 = clock();
printf("create: pool unused = %.4f ms\n", (tick2 - tick1)/1000.0);
// 通过对象池创建对象
auto pPool = NS_LONG::LMemoryPool::create(sizeof(LTestObject), nInitCount);
tick1 = clock();
for (int i = 0; i < nCount; ++i) {
LTestObject * pObject = nullptr;
pPool->getObject(pObject);
//pObject->setID(i);
//pObject->setName("longhui");
//printf("pObject->m_nId = %d, pObject->m_nName = %s\n", pObject->getID(), pObject->getName());
//pPool->recycleObject(pObject);
}
tick2 = clock();
printf("create: pool used = %.4f ms\n", (tick2 - tick1)/1000.0);
pPool->printStatus();
} | 33.448598 | 146 | 0.583962 | [
"object"
] |
0980e05dc787f4ace8473c898945ac68871aa38a | 574,919 | cpp | C++ | Source/Rhi/Private/Direct3D12Rhi/Direct3D12Rhi.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 187 | 2015-11-02T21:27:57.000Z | 2022-02-17T21:39:17.000Z | Source/Rhi/Private/Direct3D12Rhi/Direct3D12Rhi.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | null | null | null | Source/Rhi/Private/Direct3D12Rhi/Direct3D12Rhi.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 20 | 2015-11-04T19:17:01.000Z | 2021-11-18T11:23:25.000Z | /*********************************************************\
* Copyright (c) 2012-2021 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
/**
* @brief
* Direct3D 12 RHI amalgamated/unity build implementation
*
* @remarks
* == Dependencies ==
* Direct3D 12 runtime and Direct3D 12 capable graphics driver, nothing else.
*
* == Preprocessor Definitions ==
* - Set "RHI_DIRECT3D12_EXPORTS" as preprocessor definition when building this library as shared library
* - Do also have a look into the RHI header file documentation
*/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <Rhi/Public/Rhi.h>
// Set Windows version to Windows Vista (0x0600), we don't support Windows XP (0x0501)
#ifdef WINVER
#undef WINVER
#endif
#define WINVER 0x0600
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
// Exclude some stuff from "windows.h" to speed up compilation a bit
#define NOGDICAPMASKS
#define NOMENUS
#define NOICONS
#define NOKEYSTATES
#define NOSYSCOMMANDS
#define NORASTEROPS
#define OEMRESOURCE
#define NOATOM
#define NOMEMMGR
#define NOMETAFILE
#define NOOPENFILE
#define NOSCROLL
#define NOSERVICE
#define NOSOUND
#define NOWH
#define NOCOMM
#define NOKANJI
#define NOHELP
#define NOPROFILER
#define NODEFERWINDOWPOS
#define NOMCX
#define NOCRYPT
#include <Windows.h>
// Get rid of some nasty OS macros
#undef max
//[-------------------------------------------------------]
//[ Direct3D12Rhi/MakeID.h ]
//[-------------------------------------------------------]
/*
Author:
Emil Persson, A.K.A. Humus.
http://www.humus.name
Version history:
1.0 - Initial release.
1.01 - Code review fixes. Code reviewed by Denis A. Gladkiy.
1.02 - Fixed an off-by-one error in DestroyRange() found by Markus Billeter
License:
Public Domain
This file is released in the hopes that it will be useful. Use in whatever way you like, but no guarantees that it
actually works or fits any particular purpose. It has been unit-tested and benchmarked though, and seems to do
what it was designed to do, and seems pretty quick at it too.
Notes:
There are many applications where it is desired to generate unique IDs at runtime for various resources, such that they can be
distinguished, sorted or otherwise processed in an efficient manner. It can in some cases replace hashes, handles and pointers.
In cases where resource pointers are used as IDs, it offers a unique ID that requires far fewer bits, especially for 64bit apps.
The design goal of this implementation was to return the most compact IDs as possible, limiting to a specific range if necessary.
The properties of this system are as follows:
- Creating a new ID returns the smallest possible unused ID.
- Creating a new range of IDs returns the smallest possible continuous range of the specified size.
- Created IDs remain valid until destroyed.
- Destroying an ID returns it to the pool and may be returned by subsequent allocations.
- The system is NOT thread-safe.
Performance properties:
- Creating an ID is O(1) and generally super-cheap.
- Destroying an ID is also cheap, but O(log(n)), where n is the current number of distinct available ranges.
- The system merges available ranges when IDs are destroyed, keeping said n generally very small in practice.
- After warmup, no further memory allocations should be necessary, or be very rare.
- The system uses very little memory.
- It is possible to construct a pathological case where fragmentation would cause n to become large. This can be done by
first allocating a very large range of IDs, then deleting every other ID, causing a new range to be allocated for every
free ID, or as many ranges as there are free IDs. I believe nothing close to this situation happens in practical applications.
In tests, millions of random scattered creations and deletions only resulted in a relatively short list in the worst case.
This is because freed IDs are quickly reused and ranges eagerly merged.
Where would this system be useful? It was originally thought up as a replacement for resource pointers as part of sort-ids
in rendering. Using for instance a 64-bit sort-id packing various flags and states, putting a pointer in there takes an
awful lot of bits, especially considering the actual possible resources range in the thousands at most. This got far worse
of course with the switch to 64bit as pointers are now twice as large and essentially eats all bits except bottom few for
alignment.
Another application would be for managing a shared pool of resources. IDs could be handed out as handles and used to access
the actual resource from an array. By always returning the lowest possible ID or range of IDs we get very good cache behavior
since all active resources will grouped together in the bottom part of the array. Using IDs instead of pointers for handles
also allows easy resizing of the allocated memory since IDs can remain the same even if the underlying storage changed.
*/
#ifdef RHI_DEBUG
#include <cstdio> // For printf(). Remove if you don't need the PrintRanges() function (mostly for debugging anyway).
#endif
#include <cstdint> // uint32_t
#include <limits> // std::numeric_limits<type>::max()
#include <cstdlib>
#include <cstring>
class MakeID final
{
private:
// Change to uint16_t here for a more compact implementation if 16bit or less IDs work for you.
typedef uint16_t uint;
struct Range
{
uint m_First;
uint m_Last;
};
Rhi::IAllocator& m_Allocator;
Range *m_Ranges; // Sorted array of ranges of free IDs
uint m_Count; // Number of ranges in list
uint m_Capacity; // Total capacity of range list
MakeID & operator=(const MakeID &) = delete;
MakeID(const MakeID &) = delete;
public:
MakeID(Rhi::IAllocator& allocator, const uint max_id = std::numeric_limits<uint>::max()) :
m_Allocator(allocator),
m_Ranges(static_cast<Range*>(allocator.reallocate(nullptr, 0, sizeof(Range), 1))),
m_Count(1),
m_Capacity(1)
{
// Start with a single range, from 0 to max allowed ID (specified)
m_Ranges[0].m_First = 0;
m_Ranges[0].m_Last = max_id;
}
~MakeID()
{
m_Allocator.reallocate(m_Ranges, 0, 0, 1);
}
bool CreateID(uint &id)
{
if (m_Ranges[0].m_First <= m_Ranges[0].m_Last)
{
id = m_Ranges[0].m_First;
// If current range is full and there is another one, that will become the new current range
if (m_Ranges[0].m_First == m_Ranges[0].m_Last && m_Count > 1)
{
DestroyRange(0);
}
else
{
++m_Ranges[0].m_First;
}
return true;
}
// No available ID left
return false;
}
bool CreateRangeID(uint &id, const uint count)
{
uint i = 0;
do
{
const uint range_count = 1u + m_Ranges[i].m_Last - m_Ranges[i].m_First;
if (count <= range_count)
{
id = m_Ranges[i].m_First;
// If current range is full and there is another one, that will become the new current range
if (count == range_count && i + 1 < m_Count)
{
DestroyRange(i);
}
else
{
m_Ranges[i].m_First += count;
}
return true;
}
++i;
} while (i < m_Count);
// No range of free IDs was large enough to create the requested continuous ID sequence
return false;
}
bool DestroyID(const uint id)
{
return DestroyRangeID(id, 1);
}
bool DestroyRangeID(const uint id, const uint count)
{
const uint end_id = static_cast<uint>(id + count);
// Binary search of the range list
uint i0 = 0u;
uint i1 = m_Count - 1u;
for (;;)
{
const uint i = (i0 + i1) / 2u;
if (id < m_Ranges[i].m_First)
{
// Before current range, check if neighboring
if (end_id >= m_Ranges[i].m_First)
{
if (end_id != m_Ranges[i].m_First)
return false; // Overlaps a range of free IDs, thus (at least partially) invalid IDs
// Neighbor id, check if neighboring previous range too
if (i > i0 && id - 1 == m_Ranges[i - 1].m_Last)
{
// Merge with previous range
m_Ranges[i - 1].m_Last = m_Ranges[i].m_Last;
DestroyRange(i);
}
else
{
// Just grow range
m_Ranges[i].m_First = id;
}
return true;
}
else
{
// Non-neighbor id
if (i != i0)
{
// Cull upper half of list
i1 = i - 1u;
}
else
{
// Found our position in the list, insert the deleted range here
InsertRange(i);
m_Ranges[i].m_First = id;
m_Ranges[i].m_Last = end_id - 1u;
return true;
}
}
}
else if (id > m_Ranges[i].m_Last)
{
// After current range, check if neighboring
if (id - 1 == m_Ranges[i].m_Last)
{
// Neighbor id, check if neighboring next range too
if (i < i1 && end_id == m_Ranges[i + 1].m_First)
{
// Merge with next range
m_Ranges[i].m_Last = m_Ranges[i + 1].m_Last;
DestroyRange(i + 1u);
}
else
{
// Just grow range
m_Ranges[i].m_Last += count;
}
return true;
}
else
{
// Non-neighbor id
if (i != i1)
{
// Cull bottom half of list
i0 = i + 1u;
}
else
{
// Found our position in the list, insert the deleted range here
InsertRange(i + 1u);
m_Ranges[i + 1].m_First = id;
m_Ranges[i + 1].m_Last = end_id - 1u;
return true;
}
}
}
else
{
// Inside a free block, not a valid ID
return false;
}
}
}
bool IsID(const uint id) const
{
// Binary search of the range list
uint i0 = 0u;
uint i1 = m_Count - 1u;
for (;;)
{
const uint i = (i0 + i1) / 2u;
if (id < m_Ranges[i].m_First)
{
if (i == i0)
return true;
// Cull upper half of list
i1 = i - 1u;
}
else if (id > m_Ranges[i].m_Last)
{
if (i == i1)
return true;
// Cull bottom half of list
i0 = i + 1u;
}
else
{
// Inside a free block, not a valid ID
return false;
}
}
}
uint GetAvailableIDs() const
{
uint count = m_Count;
uint i = 0;
do
{
count += m_Ranges[i].m_Last - m_Ranges[i].m_First;
++i;
} while (i < m_Count);
return count;
}
uint GetLargestContinuousRange() const
{
uint max_count = 0;
uint i = 0;
do
{
uint count = m_Ranges[i].m_Last - m_Ranges[i].m_First + 1u;
if (count > max_count)
max_count = count;
++i;
} while (i < m_Count);
return max_count;
}
#ifdef RHI_DEBUG
void PrintRanges() const
{
uint i = 0;
for (;;)
{
if (m_Ranges[i].m_First < m_Ranges[i].m_Last)
printf("%u-%u", m_Ranges[i].m_First, m_Ranges[i].m_Last);
else if (m_Ranges[i].m_First == m_Ranges[i].m_Last)
printf("%u", m_Ranges[i].m_First);
else
printf("-");
++i;
if (i >= m_Count)
{
printf("\n");
return;
}
printf(", ");
}
}
#endif
private:
void InsertRange(const uint index)
{
if (m_Count >= m_Capacity)
{
m_Ranges = static_cast<Range *>(m_Allocator.reallocate(m_Ranges, sizeof(Range) * m_Capacity, (m_Capacity + m_Capacity) * sizeof(Range), 1));
m_Capacity += m_Capacity;
}
::memmove(m_Ranges + index + 1, m_Ranges + index, (m_Count - index) * sizeof(Range));
++m_Count;
}
void DestroyRange(const uint index)
{
--m_Count;
::memmove(m_Ranges + index, m_Ranges + index + 1, (m_Count - index) * sizeof(Range));
}
};
//[-------------------------------------------------------]
//[ Direct3D11Rhi/D3D12.h ]
//[-------------------------------------------------------]
/*
We don't use the Direct3D headers from the DirectX SDK because there are several issues:
- Licensing: It's not allowed to redistribute the Direct3D headers, meaning everyone would
have to get them somehow before compiling this project
- The Direct3D headers are somewhat chaotic and include tons of other headers.
This slows down compilation and the more headers are included, the higher the risk of
naming or redefinition conflicts.
Do not include this header within headers which are usually used by users as well, do only
use it inside cpp-files. It must still be possible that users of this RHI
can use the Direct3D headers for features not covered by this RHI.
*/
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
struct DXGI_RGBA;
struct DXGI_RESIDENCY;
struct DXGI_MATRIX_3X2_F;
struct DXGI_SURFACE_DESC;
struct DXGI_ADAPTER_DESC;
struct DXGI_SHARED_RESOURCE;
struct DXGI_FRAME_STATISTICS;
struct DXGI_SWAP_CHAIN_DESC1;
struct DXGI_PRESENT_PARAMETERS;
struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC;
struct IDXGIOutput;
struct IDXGISurface;
struct IDXGIAdapter;
struct IDXGIAdapter1;
struct D3D12_HEAP_DESC;
struct D3D12_TILE_SHAPE;
struct D3D12_SAMPLER_DESC;
struct D3D12_DISCARD_REGION;
struct D3D12_PACKED_MIP_INFO;
struct D3D12_TILE_REGION_SIZE;
struct D3D12_TILE_RANGE_FLAGS;
struct D3D12_SUBRESOURCE_TILING;
struct D3D12_SO_DECLARATION_ENTRY;
struct D3D12_STREAM_OUTPUT_BUFFER_VIEW;
struct D3D12_TILED_RESOURCE_COORDINATE;
struct D3D12_UNORDERED_ACCESS_VIEW_DESC;
struct D3D12_COMPUTE_PIPELINE_STATE_DESC;
struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT;
struct ID3D12Heap;
struct ID3D12Resource;
struct ID3D12RootSignature;
// TODO(co) Direct3D 12 update
struct ID3D10Blob;
struct D3D10_SHADER_MACRO;
typedef __interface ID3DInclude *LPD3D10INCLUDE;
struct ID3DX12ThreadPump;
typedef DWORD D3DCOLOR;
//[-------------------------------------------------------]
//[ Definitions ]
//[-------------------------------------------------------]
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgiformat.h"
typedef enum DXGI_FORMAT
{
DXGI_FORMAT_UNKNOWN = 0,
DXGI_FORMAT_R32G32B32A32_TYPELESS = 1,
DXGI_FORMAT_R32G32B32A32_FLOAT = 2,
DXGI_FORMAT_R32G32B32A32_UINT = 3,
DXGI_FORMAT_R32G32B32A32_SINT = 4,
DXGI_FORMAT_R32G32B32_TYPELESS = 5,
DXGI_FORMAT_R32G32B32_FLOAT = 6,
DXGI_FORMAT_R32G32B32_UINT = 7,
DXGI_FORMAT_R32G32B32_SINT = 8,
DXGI_FORMAT_R16G16B16A16_TYPELESS = 9,
DXGI_FORMAT_R16G16B16A16_FLOAT = 10,
DXGI_FORMAT_R16G16B16A16_UNORM = 11,
DXGI_FORMAT_R16G16B16A16_UINT = 12,
DXGI_FORMAT_R16G16B16A16_SNORM = 13,
DXGI_FORMAT_R16G16B16A16_SINT = 14,
DXGI_FORMAT_R32G32_TYPELESS = 15,
DXGI_FORMAT_R32G32_FLOAT = 16,
DXGI_FORMAT_R32G32_UINT = 17,
DXGI_FORMAT_R32G32_SINT = 18,
DXGI_FORMAT_R32G8X24_TYPELESS = 19,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20,
DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21,
DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22,
DXGI_FORMAT_R10G10B10A2_TYPELESS = 23,
DXGI_FORMAT_R10G10B10A2_UNORM = 24,
DXGI_FORMAT_R10G10B10A2_UINT = 25,
DXGI_FORMAT_R11G11B10_FLOAT = 26,
DXGI_FORMAT_R8G8B8A8_TYPELESS = 27,
DXGI_FORMAT_R8G8B8A8_UNORM = 28,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29,
DXGI_FORMAT_R8G8B8A8_UINT = 30,
DXGI_FORMAT_R8G8B8A8_SNORM = 31,
DXGI_FORMAT_R8G8B8A8_SINT = 32,
DXGI_FORMAT_R16G16_TYPELESS = 33,
DXGI_FORMAT_R16G16_FLOAT = 34,
DXGI_FORMAT_R16G16_UNORM = 35,
DXGI_FORMAT_R16G16_UINT = 36,
DXGI_FORMAT_R16G16_SNORM = 37,
DXGI_FORMAT_R16G16_SINT = 38,
DXGI_FORMAT_R32_TYPELESS = 39,
DXGI_FORMAT_D32_FLOAT = 40,
DXGI_FORMAT_R32_FLOAT = 41,
DXGI_FORMAT_R32_UINT = 42,
DXGI_FORMAT_R32_SINT = 43,
DXGI_FORMAT_R24G8_TYPELESS = 44,
DXGI_FORMAT_D24_UNORM_S8_UINT = 45,
DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46,
DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47,
DXGI_FORMAT_R8G8_TYPELESS = 48,
DXGI_FORMAT_R8G8_UNORM = 49,
DXGI_FORMAT_R8G8_UINT = 50,
DXGI_FORMAT_R8G8_SNORM = 51,
DXGI_FORMAT_R8G8_SINT = 52,
DXGI_FORMAT_R16_TYPELESS = 53,
DXGI_FORMAT_R16_FLOAT = 54,
DXGI_FORMAT_D16_UNORM = 55,
DXGI_FORMAT_R16_UNORM = 56,
DXGI_FORMAT_R16_UINT = 57,
DXGI_FORMAT_R16_SNORM = 58,
DXGI_FORMAT_R16_SINT = 59,
DXGI_FORMAT_R8_TYPELESS = 60,
DXGI_FORMAT_R8_UNORM = 61,
DXGI_FORMAT_R8_UINT = 62,
DXGI_FORMAT_R8_SNORM = 63,
DXGI_FORMAT_R8_SINT = 64,
DXGI_FORMAT_A8_UNORM = 65,
DXGI_FORMAT_R1_UNORM = 66,
DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67,
DXGI_FORMAT_R8G8_B8G8_UNORM = 68,
DXGI_FORMAT_G8R8_G8B8_UNORM = 69,
DXGI_FORMAT_BC1_TYPELESS = 70,
DXGI_FORMAT_BC1_UNORM = 71,
DXGI_FORMAT_BC1_UNORM_SRGB = 72,
DXGI_FORMAT_BC2_TYPELESS = 73,
DXGI_FORMAT_BC2_UNORM = 74,
DXGI_FORMAT_BC2_UNORM_SRGB = 75,
DXGI_FORMAT_BC3_TYPELESS = 76,
DXGI_FORMAT_BC3_UNORM = 77,
DXGI_FORMAT_BC3_UNORM_SRGB = 78,
DXGI_FORMAT_BC4_TYPELESS = 79,
DXGI_FORMAT_BC4_UNORM = 80,
DXGI_FORMAT_BC4_SNORM = 81,
DXGI_FORMAT_BC5_TYPELESS = 82,
DXGI_FORMAT_BC5_UNORM = 83,
DXGI_FORMAT_BC5_SNORM = 84,
DXGI_FORMAT_B5G6R5_UNORM = 85,
DXGI_FORMAT_B5G5R5A1_UNORM = 86,
DXGI_FORMAT_B8G8R8A8_UNORM = 87,
DXGI_FORMAT_B8G8R8X8_UNORM = 8,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89,
DXGI_FORMAT_B8G8R8A8_TYPELESS = 90,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91,
DXGI_FORMAT_B8G8R8X8_TYPELESS = 92,
DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93,
DXGI_FORMAT_BC6H_TYPELESS = 94,
DXGI_FORMAT_BC6H_UF16 = 95,
DXGI_FORMAT_BC6H_SF16 = 96,
DXGI_FORMAT_BC7_TYPELESS = 97,
DXGI_FORMAT_BC7_UNORM = 98,
DXGI_FORMAT_BC7_UNORM_SRGB = 99,
DXGI_FORMAT_AYUV = 100,
DXGI_FORMAT_Y410 = 101,
DXGI_FORMAT_Y416 = 102,
DXGI_FORMAT_NV12 = 103,
DXGI_FORMAT_P010 = 104,
DXGI_FORMAT_P016 = 105,
DXGI_FORMAT_420_OPAQUE = 106,
DXGI_FORMAT_YUY2 = 107,
DXGI_FORMAT_Y210 = 108,
DXGI_FORMAT_Y216 = 109,
DXGI_FORMAT_NV11 = 110,
DXGI_FORMAT_AI44 = 111,
DXGI_FORMAT_IA44 = 112,
DXGI_FORMAT_P8 = 113,
DXGI_FORMAT_A8P8 = 114,
DXGI_FORMAT_B4G4R4A4_UNORM = 115,
DXGI_FORMAT_P208 = 130,
DXGI_FORMAT_V208 = 131,
DXGI_FORMAT_V408 = 132,
DXGI_FORMAT_FORCE_UINT = 0xffffffff
} DXGI_FORMAT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef struct DXGI_RATIONAL
{
UINT Numerator;
UINT Denominator;
} DXGI_RATIONAL;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef enum DXGI_MODE_SCANLINE_ORDER
{
DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED = 0,
DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE = 1,
DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2,
DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3
} DXGI_MODE_SCANLINE_ORDER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef enum DXGI_MODE_SCALING
{
DXGI_MODE_SCALING_UNSPECIFIED = 0,
DXGI_MODE_SCALING_CENTERED = 1,
DXGI_MODE_SCALING_STRETCHED = 2
} DXGI_MODE_SCALING;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef struct DXGI_MODE_DESC
{
UINT Width;
UINT Height;
DXGI_RATIONAL RefreshRate;
DXGI_FORMAT Format;
DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
DXGI_MODE_SCALING Scaling;
} DXGI_MODE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef struct DXGI_SAMPLE_DESC
{
UINT Count;
UINT Quality;
} DXGI_SAMPLE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef enum DXGI_MODE_ROTATION
{
DXGI_MODE_ROTATION_UNSPECIFIED = 0,
DXGI_MODE_ROTATION_IDENTITY = 1,
DXGI_MODE_ROTATION_ROTATE90 = 2,
DXGI_MODE_ROTATION_ROTATE180 = 3,
DXGI_MODE_ROTATION_ROTATE270 = 4
} DXGI_MODE_ROTATION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgitype.h"
typedef enum DXGI_COLOR_SPACE_TYPE
{
DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = 0,
DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = 1,
DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = 2,
DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = 3,
DXGI_COLOR_SPACE_RESERVED = 4,
DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = 5,
DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = 6,
DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = 7,
DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = 8,
DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = 9,
DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = 10,
DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = 11,
DXGI_COLOR_SPACE_CUSTOM = 0xFFFFFFFF
} DXGI_COLOR_SPACE_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
typedef UINT DXGI_USAGE;
#define DXGI_MWA_NO_ALT_ENTER (1 << 1)
#define DXGI_USAGE_RENDER_TARGET_OUTPUT 0x00000020UL
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
typedef enum DXGI_SWAP_EFFECT
{
DXGI_SWAP_EFFECT_DISCARD = 0,
DXGI_SWAP_EFFECT_SEQUENTIAL = 1,
DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3,
DXGI_SWAP_EFFECT_FLIP_DISCARD = 4
} DXGI_SWAP_EFFECT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
typedef struct DXGI_SWAP_CHAIN_DESC
{
DXGI_MODE_DESC BufferDesc;
DXGI_SAMPLE_DESC SampleDesc;
DXGI_USAGE BufferUsage;
UINT BufferCount;
HWND OutputWindow;
BOOL Windowed;
DXGI_SWAP_EFFECT SwapEffect;
UINT Flags;
} DXGI_SWAP_CHAIN_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h"
enum D3D_FEATURE_LEVEL
{
D3D_FEATURE_LEVEL_9_1 = 0x9100,
D3D_FEATURE_LEVEL_9_2 = 0x9200,
D3D_FEATURE_LEVEL_9_3 = 0x9300,
D3D_FEATURE_LEVEL_10_0 = 0xa000,
D3D_FEATURE_LEVEL_10_1 = 0xa100,
D3D_FEATURE_LEVEL_11_0 = 0xb000,
D3D_FEATURE_LEVEL_11_1 = 0xb100,
D3D_FEATURE_LEVEL_12_0 = 0xc000,
D3D_FEATURE_LEVEL_12_1 = 0xc100
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h"
typedef enum D3D_PRIMITIVE_TOPOLOGY
{
D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0,
D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1,
D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2,
D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3,
D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4,
D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5,
D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10,
D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11,
D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12,
D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13,
D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33,
D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34,
D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35,
D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36,
D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37,
D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38,
D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39,
D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40,
D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41,
D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42,
D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43,
D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44,
D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45,
D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46,
D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47,
D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48,
D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49,
D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50,
D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51,
D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52,
D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53,
D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54,
D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55,
D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56,
D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57,
D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58,
D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59,
D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60,
D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61,
D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62,
D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63,
D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64,
D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED,
D3D10_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
D3D10_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST,
D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ,
D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ,
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ,
D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ,
D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED,
D3D11_PRIMITIVE_TOPOLOGY_POINTLIST = D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
D3D11_PRIMITIVE_TOPOLOGY_LINELIST = D3D_PRIMITIVE_TOPOLOGY_LINELIST,
D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ,
D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ,
D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ,
D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST,
D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST
} D3D_PRIMITIVE_TOPOLOGY;
// "Microsoft DirectX SDK (June 2010)" -> "D3Dcommon.h"
struct D3D_SHADER_MACRO
{
LPCSTR Name;
LPCSTR Definition;
};
enum D3D_INCLUDE_TYPE
{
D3D_INCLUDE_LOCAL = 0,
D3D_INCLUDE_SYSTEM = (D3D_INCLUDE_LOCAL + 1),
D3D10_INCLUDE_LOCAL = D3D_INCLUDE_LOCAL,
D3D10_INCLUDE_SYSTEM = D3D_INCLUDE_SYSTEM,
D3D_INCLUDE_FORCE_DWORD = 0x7fffffff
};
DECLARE_INTERFACE(ID3DInclude)
{
STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) PURE;
STDMETHOD(Close)(THIS_ LPCVOID pData) PURE;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h"
typedef ID3D10Blob ID3DBlob;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3dcompiler.h"
#define D3DCOMPILE_DEBUG (1 << 0)
#define D3DCOMPILE_SKIP_VALIDATION (1 << 1)
#define D3DCOMPILE_SKIP_OPTIMIZATION (1 << 2)
#define D3DCOMPILE_ENABLE_STRICTNESS (1 << 11)
#define D3DCOMPILE_OPTIMIZATION_LEVEL0 (1 << 14)
#define D3DCOMPILE_OPTIMIZATION_LEVEL1 0
#define D3DCOMPILE_OPTIMIZATION_LEVEL2 ((1 << 14) | (1 << 15))
#define D3DCOMPILE_OPTIMIZATION_LEVEL3 (1 << 15)
#define D3DCOMPILE_WARNINGS_ARE_ERRORS (1 << 18)
#define D3DCOMPILE_ALL_RESOURCES_BOUND (1 << 21)
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_VIEWPORT
{
FLOAT TopLeftX;
FLOAT TopLeftY;
FLOAT Width;
FLOAT Height;
FLOAT MinDepth;
FLOAT MaxDepth;
} D3D12_VIEWPORT;
typedef RECT D3D12_RECT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_BOX
{
UINT left;
UINT top;
UINT front;
UINT right;
UINT bottom;
UINT back;
} D3D12_BOX;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_INPUT_CLASSIFICATION
{
D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0,
D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1
} D3D12_INPUT_CLASSIFICATION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_INPUT_ELEMENT_DESC
{
LPCSTR SemanticName;
UINT SemanticIndex;
DXGI_FORMAT Format;
UINT InputSlot;
UINT AlignedByteOffset;
D3D12_INPUT_CLASSIFICATION InputSlotClass;
UINT InstanceDataStepRate;
} D3D12_INPUT_ELEMENT_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RESOURCE_DIMENSION
{
D3D12_RESOURCE_DIMENSION_UNKNOWN = 0,
D3D12_RESOURCE_DIMENSION_BUFFER = 1,
D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2,
D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3,
D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4
} D3D12_RESOURCE_DIMENSION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_TEXTURE_LAYOUT
{
D3D12_TEXTURE_LAYOUT_UNKNOWN = 0,
D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1,
D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2,
D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3
} D3D12_TEXTURE_LAYOUT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RESOURCE_FLAGS
{
D3D12_RESOURCE_FLAG_NONE = 0,
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4,
D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8,
D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10,
D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20
} D3D12_RESOURCE_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_DESC
{
D3D12_RESOURCE_DIMENSION Dimension;
UINT64 Alignment;
UINT64 Width;
UINT Height;
UINT16 DepthOrArraySize;
UINT16 MipLevels;
DXGI_FORMAT Format;
DXGI_SAMPLE_DESC SampleDesc;
D3D12_TEXTURE_LAYOUT Layout;
D3D12_RESOURCE_FLAGS Flags;
} D3D12_RESOURCE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RESOURCE_STATES
{
D3D12_RESOURCE_STATE_COMMON = 0,
D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x1,
D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x2,
D3D12_RESOURCE_STATE_RENDER_TARGET = 0x4,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x8,
D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x10,
D3D12_RESOURCE_STATE_DEPTH_READ = 0x20,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x40,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x80,
D3D12_RESOURCE_STATE_STREAM_OUT = 0x100,
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x200,
D3D12_RESOURCE_STATE_COPY_DEST = 0x400,
D3D12_RESOURCE_STATE_COPY_SOURCE = 0x800,
D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000,
D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000,
D3D12_RESOURCE_STATE_GENERIC_READ = ((((( 0x1 | 0x2) | 0x40) | 0x80) | 0x200) | 0x800),
D3D12_RESOURCE_STATE_PRESENT = 0,
D3D12_RESOURCE_STATE_PREDICATION = 0x200
} D3D12_RESOURCE_STATES;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RESOURCE_BARRIER_TYPE
{
D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0,
D3D12_RESOURCE_BARRIER_TYPE_ALIASING = (D3D12_RESOURCE_BARRIER_TYPE_TRANSITION + 1),
D3D12_RESOURCE_BARRIER_TYPE_UAV = (D3D12_RESOURCE_BARRIER_TYPE_ALIASING + 1)
} D3D12_RESOURCE_BARRIER_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RESOURCE_BARRIER_FLAGS
{
D3D12_RESOURCE_BARRIER_FLAG_NONE = 0,
D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1,
D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2
} D3D12_RESOURCE_BARRIER_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_TRANSITION_BARRIER
{
ID3D12Resource *pResource;
UINT Subresource;
D3D12_RESOURCE_STATES StateBefore;
D3D12_RESOURCE_STATES StateAfter;
} D3D12_RESOURCE_TRANSITION_BARRIER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_ALIASING_BARRIER
{
ID3D12Resource *pResourceBefore;
ID3D12Resource *pResourceAfter;
} D3D12_RESOURCE_ALIASING_BARRIER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_UAV_BARRIER
{
ID3D12Resource *pResource;
} D3D12_RESOURCE_UAV_BARRIER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_BARRIER
{
D3D12_RESOURCE_BARRIER_TYPE Type;
D3D12_RESOURCE_BARRIER_FLAGS Flags;
union
{
D3D12_RESOURCE_TRANSITION_BARRIER Transition;
D3D12_RESOURCE_ALIASING_BARRIER Aliasing;
D3D12_RESOURCE_UAV_BARRIER UAV;
};
} D3D12_RESOURCE_BARRIER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_RTV_DIMENSION
{
D3D12_RTV_DIMENSION_UNKNOWN = 0,
D3D12_RTV_DIMENSION_BUFFER = 1,
D3D12_RTV_DIMENSION_TEXTURE1D = 2,
D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3,
D3D12_RTV_DIMENSION_TEXTURE2D = 4,
D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5,
D3D12_RTV_DIMENSION_TEXTURE2DMS = 6,
D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7,
D3D12_RTV_DIMENSION_TEXTURE3D = 8
} D3D12_RTV_DIMENSION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_BUFFER_RTV
{
UINT64 FirstElement;
UINT NumElements;
} D3D12_BUFFER_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_RTV
{
UINT MipSlice;
} D3D12_TEX1D_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_ARRAY_RTV
{
UINT MipSlice;
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX1D_ARRAY_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_RTV
{
UINT MipSlice;
UINT PlaneSlice;
} D3D12_TEX2D_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_RTV
{
UINT UnusedField_NothingToDefine;
} D3D12_TEX2DMS_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_ARRAY_RTV
{
UINT MipSlice;
UINT FirstArraySlice;
UINT ArraySize;
UINT PlaneSlice;
} D3D12_TEX2D_ARRAY_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_ARRAY_RTV
{
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX2DMS_ARRAY_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX3D_RTV
{
UINT MipSlice;
UINT FirstWSlice;
UINT WSize;
} D3D12_TEX3D_RTV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RENDER_TARGET_VIEW_DESC
{
DXGI_FORMAT Format;
D3D12_RTV_DIMENSION ViewDimension;
union
{
D3D12_BUFFER_RTV Buffer;
D3D12_TEX1D_RTV Texture1D;
D3D12_TEX1D_ARRAY_RTV Texture1DArray;
D3D12_TEX2D_RTV Texture2D;
D3D12_TEX2D_ARRAY_RTV Texture2DArray;
D3D12_TEX2DMS_RTV Texture2DMS;
D3D12_TEX2DMS_ARRAY_RTV Texture2DMSArray;
D3D12_TEX3D_RTV Texture3D;
};
} D3D12_RENDER_TARGET_VIEW_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_COMMAND_LIST_TYPE
{
D3D12_COMMAND_LIST_TYPE_DIRECT = 0,
D3D12_COMMAND_LIST_TYPE_BUNDLE = 1,
D3D12_COMMAND_LIST_TYPE_COMPUTE = 2,
D3D12_COMMAND_LIST_TYPE_COPY = 3
} D3D12_COMMAND_LIST_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RANGE
{
SIZE_T Begin;
SIZE_T End;
} D3D12_RANGE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef UINT64 D3D12_GPU_VIRTUAL_ADDRESS;
#define D3D12_REQ_SUBRESOURCES 30720
#define D3D12_FLOAT32_MAX 3.402823466e+38f
#define D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES 0xffffffff
#define D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND 0xffffffff
#define D3D12_DEFAULT_DEPTH_BIAS 0
#define D3D12_DEFAULT_DEPTH_BIAS_CLAMP 0.0f
#define D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS 0.0f
#define D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT 8
#define D3D12_SHADER_COMPONENT_MAPPING_MASK 0x7
#define D3D12_SHADER_COMPONENT_MAPPING_SHIFT 3
#define D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES (1<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*4))
#define D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(Src0,Src1,Src2,Src3) ((((Src0)&D3D12_SHADER_COMPONENT_MAPPING_MASK)| \
(((Src1)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<D3D12_SHADER_COMPONENT_MAPPING_SHIFT)| \
(((Src2)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*2))| \
(((Src3)&D3D12_SHADER_COMPONENT_MAPPING_MASK)<<(D3D12_SHADER_COMPONENT_MAPPING_SHIFT*3))| \
D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES))
#define D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(ComponentToExtract,Mapping) ((D3D12_SHADER_COMPONENT_MAPPING)(Mapping >> (D3D12_SHADER_COMPONENT_MAPPING_SHIFT*ComponentToExtract) & D3D12_SHADER_COMPONENT_MAPPING_MASK))
#define D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0,1,2,3)
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_COMMAND_QUEUE_FLAGS
{
D3D12_COMMAND_QUEUE_FLAG_NONE = 0,
D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1
} D3D12_COMMAND_QUEUE_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_COMMAND_QUEUE_PRIORITY
{
D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0,
D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100
} D3D12_COMMAND_QUEUE_PRIORITY;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_COMMAND_QUEUE_DESC
{
D3D12_COMMAND_LIST_TYPE Type;
INT Priority;
D3D12_COMMAND_QUEUE_FLAGS Flags;
UINT NodeMask;
} D3D12_COMMAND_QUEUE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RESOURCE_ALLOCATION_INFO
{
UINT64 SizeInBytes;
UINT64 Alignment;
} D3D12_RESOURCE_ALLOCATION_INFO;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_HEAP_TYPE
{
D3D12_HEAP_TYPE_DEFAULT = 1,
D3D12_HEAP_TYPE_UPLOAD = 2,
D3D12_HEAP_TYPE_READBACK = 3,
D3D12_HEAP_TYPE_CUSTOM = 4
} D3D12_HEAP_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_CPU_PAGE_PROPERTY
{
D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0,
D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1,
D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2,
D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3
} D3D12_CPU_PAGE_PROPERTY;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_MEMORY_POOL
{
D3D12_MEMORY_POOL_UNKNOWN = 0,
D3D12_MEMORY_POOL_L0 = 1,
D3D12_MEMORY_POOL_L1 = 2
} D3D12_MEMORY_POOL;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_HEAP_PROPERTIES
{
D3D12_HEAP_TYPE Type;
D3D12_CPU_PAGE_PROPERTY CPUPageProperty;
D3D12_MEMORY_POOL MemoryPoolPreference;
UINT CreationNodeMask;
UINT VisibleNodeMask;
} D3D12_HEAP_PROPERTIES;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_HEAP_FLAGS
{
D3D12_HEAP_FLAG_NONE = 0,
D3D12_HEAP_FLAG_SHARED = 0x1,
D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4,
D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8,
D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20,
D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40,
D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80,
D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0,
D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xc0,
D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44,
D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84
} D3D12_HEAP_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DEPTH_STENCIL_VALUE
{
FLOAT Depth;
UINT8 Stencil;
} D3D12_DEPTH_STENCIL_VALUE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_CLEAR_VALUE
{
DXGI_FORMAT Format;
union
{
FLOAT Color[4];
D3D12_DEPTH_STENCIL_VALUE DepthStencil;
};
} D3D12_CLEAR_VALUE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_FENCE_FLAGS
{
D3D12_FENCE_FLAG_NONE = 0,
D3D12_FENCE_FLAG_SHARED = 0x1,
D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2
} D3D12_FENCE_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_FEATURE
{
D3D12_FEATURE_D3D12_OPTIONS = 0,
D3D12_FEATURE_ARCHITECTURE = (D3D12_FEATURE_D3D12_OPTIONS + 1),
D3D12_FEATURE_FEATURE_LEVELS = (D3D12_FEATURE_ARCHITECTURE + 1),
D3D12_FEATURE_FORMAT_SUPPORT = (D3D12_FEATURE_FEATURE_LEVELS + 1),
D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = (D3D12_FEATURE_FORMAT_SUPPORT + 1),
D3D12_FEATURE_FORMAT_INFO = (D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS + 1),
D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = (D3D12_FEATURE_FORMAT_INFO + 1)
} D3D12_FEATURE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_TILE_MAPPING_FLAGS
{
D3D12_TILE_MAPPING_FLAG_NONE = 0,
D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1
} D3D12_TILE_MAPPING_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_CPU_DESCRIPTOR_HANDLE
{
SIZE_T ptr;
} D3D12_CPU_DESCRIPTOR_HANDLE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_GPU_DESCRIPTOR_HANDLE
{
UINT64 ptr;
} D3D12_GPU_DESCRIPTOR_HANDLE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DESCRIPTOR_HEAP_TYPE
{
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV = 0,
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER = (D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + 1),
D3D12_DESCRIPTOR_HEAP_TYPE_RTV = (D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + 1),
D3D12_DESCRIPTOR_HEAP_TYPE_DSV = (D3D12_DESCRIPTOR_HEAP_TYPE_RTV + 1),
D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES = (D3D12_DESCRIPTOR_HEAP_TYPE_DSV + 1)
} D3D12_DESCRIPTOR_HEAP_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DESCRIPTOR_HEAP_FLAGS
{
D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0,
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1
} D3D12_DESCRIPTOR_HEAP_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DESCRIPTOR_HEAP_DESC
{
D3D12_DESCRIPTOR_HEAP_TYPE Type;
UINT NumDescriptors;
D3D12_DESCRIPTOR_HEAP_FLAGS Flags;
UINT NodeMask;
} D3D12_DESCRIPTOR_HEAP_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_TILE_COPY_FLAGS
{
D3D12_TILE_COPY_FLAG_NONE = 0,
D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1,
D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2,
D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4
} D3D12_TILE_COPY_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_PRIMITIVE_TOPOLOGY_TYPE
{
D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4
} D3D12_PRIMITIVE_TOPOLOGY_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef D3D_PRIMITIVE_TOPOLOGY D3D12_PRIMITIVE_TOPOLOGY;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_CLEAR_FLAGS
{
D3D12_CLEAR_FLAG_DEPTH = 0x1,
D3D12_CLEAR_FLAG_STENCIL = 0x2
} D3D12_CLEAR_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_QUERY_HEAP_TYPE
{
D3D12_QUERY_HEAP_TYPE_OCCLUSION = 0,
D3D12_QUERY_HEAP_TYPE_TIMESTAMP = 1,
D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS = 2,
D3D12_QUERY_HEAP_TYPE_SO_STATISTICS = 3
} D3D12_QUERY_HEAP_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_QUERY_TYPE
{
D3D12_QUERY_TYPE_OCCLUSION = 0,
D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1,
D3D12_QUERY_TYPE_TIMESTAMP = 2,
D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6,
D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7
} D3D12_QUERY_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_QUERY_HEAP_DESC
{
D3D12_QUERY_HEAP_TYPE Type;
UINT Count;
UINT NodeMask;
} D3D12_QUERY_HEAP_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_PREDICATION_OP
{
D3D12_PREDICATION_OP_EQUAL_ZERO = 0,
D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1
} D3D12_PREDICATION_OP;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_QUERY_DATA_PIPELINE_STATISTICS
{
UINT64 IAVertices;
UINT64 IAPrimitives;
UINT64 VSInvocations;
UINT64 GSInvocations;
UINT64 GSPrimitives;
UINT64 CInvocations;
UINT64 CPrimitives;
UINT64 PSInvocations;
UINT64 HSInvocations;
UINT64 DSInvocations;
UINT64 CSInvocations;
} D3D12_QUERY_DATA_PIPELINE_STATISTICS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_VERTEX_BUFFER_VIEW
{
D3D12_GPU_VIRTUAL_ADDRESS BufferLocation;
UINT SizeInBytes;
UINT StrideInBytes;
} D3D12_VERTEX_BUFFER_VIEW;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_INDEX_BUFFER_VIEW
{
D3D12_GPU_VIRTUAL_ADDRESS BufferLocation;
UINT SizeInBytes;
DXGI_FORMAT Format;
} D3D12_INDEX_BUFFER_VIEW;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_CONSTANT_BUFFER_VIEW_DESC
{
D3D12_GPU_VIRTUAL_ADDRESS BufferLocation;
UINT SizeInBytes;
} D3D12_CONSTANT_BUFFER_VIEW_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DSV_DIMENSION
{
D3D12_DSV_DIMENSION_UNKNOWN = 0,
D3D12_DSV_DIMENSION_TEXTURE1D = 1,
D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2,
D3D12_DSV_DIMENSION_TEXTURE2D = 3,
D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4,
D3D12_DSV_DIMENSION_TEXTURE2DMS = 5,
D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6
} D3D12_DSV_DIMENSION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DSV_FLAGS
{
D3D12_DSV_FLAG_NONE = 0,
D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1,
D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2
} D3D12_DSV_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_DSV
{
UINT MipSlice;
} D3D12_TEX1D_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_ARRAY_DSV
{
UINT MipSlice;
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX1D_ARRAY_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_DSV
{
UINT MipSlice;
} D3D12_TEX2D_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_ARRAY_DSV
{
UINT MipSlice;
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX2D_ARRAY_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_DSV
{
UINT UnusedField_NothingToDefine;
} D3D12_TEX2DMS_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_ARRAY_DSV
{
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX2DMS_ARRAY_DSV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DEPTH_STENCIL_VIEW_DESC
{
DXGI_FORMAT Format;
D3D12_DSV_DIMENSION ViewDimension;
D3D12_DSV_FLAGS Flags;
union
{
D3D12_TEX1D_DSV Texture1D;
D3D12_TEX1D_ARRAY_DSV Texture1DArray;
D3D12_TEX2D_DSV Texture2D;
D3D12_TEX2D_ARRAY_DSV Texture2DArray;
D3D12_TEX2DMS_DSV Texture2DMS;
D3D12_TEX2DMS_ARRAY_DSV Texture2DMSArray;
};
} D3D12_DEPTH_STENCIL_VIEW_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_SRV_DIMENSION
{
D3D12_SRV_DIMENSION_UNKNOWN = 0,
D3D12_SRV_DIMENSION_BUFFER = 1,
D3D12_SRV_DIMENSION_TEXTURE1D = 2,
D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3,
D3D12_SRV_DIMENSION_TEXTURE2D = 4,
D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5,
D3D12_SRV_DIMENSION_TEXTURE2DMS = 6,
D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7,
D3D12_SRV_DIMENSION_TEXTURE3D = 8,
D3D12_SRV_DIMENSION_TEXTURECUBE = 9,
D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10
} D3D12_SRV_DIMENSION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_BUFFER_SRV_FLAGS
{
D3D12_BUFFER_SRV_FLAG_NONE = 0,
D3D12_BUFFER_SRV_FLAG_RAW = 0x1
} D3D12_BUFFER_SRV_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_BUFFER_SRV
{
UINT64 FirstElement;
UINT NumElements;
UINT StructureByteStride;
D3D12_BUFFER_SRV_FLAGS Flags;
} D3D12_BUFFER_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
FLOAT ResourceMinLODClamp;
} D3D12_TEX1D_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX1D_ARRAY_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
UINT FirstArraySlice;
UINT ArraySize;
FLOAT ResourceMinLODClamp;
} D3D12_TEX1D_ARRAY_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
UINT PlaneSlice;
FLOAT ResourceMinLODClamp;
} D3D12_TEX2D_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2D_ARRAY_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
UINT FirstArraySlice;
UINT ArraySize;
UINT PlaneSlice;
FLOAT ResourceMinLODClamp;
} D3D12_TEX2D_ARRAY_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_SRV
{
UINT UnusedField_NothingToDefine;
} D3D12_TEX2DMS_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX2DMS_ARRAY_SRV
{
UINT FirstArraySlice;
UINT ArraySize;
} D3D12_TEX2DMS_ARRAY_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEX3D_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
FLOAT ResourceMinLODClamp;
} D3D12_TEX3D_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEXCUBE_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
FLOAT ResourceMinLODClamp;
} D3D12_TEXCUBE_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEXCUBE_ARRAY_SRV
{
UINT MostDetailedMip;
UINT MipLevels;
UINT First2DArrayFace;
UINT NumCubes;
FLOAT ResourceMinLODClamp;
} D3D12_TEXCUBE_ARRAY_SRV;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_SHADER_RESOURCE_VIEW_DESC
{
DXGI_FORMAT Format;
D3D12_SRV_DIMENSION ViewDimension;
UINT Shader4ComponentMapping;
union
{
D3D12_BUFFER_SRV Buffer;
D3D12_TEX1D_SRV Texture1D;
D3D12_TEX1D_ARRAY_SRV Texture1DArray;
D3D12_TEX2D_SRV Texture2D;
D3D12_TEX2D_ARRAY_SRV Texture2DArray;
D3D12_TEX2DMS_SRV Texture2DMS;
D3D12_TEX2DMS_ARRAY_SRV Texture2DMSArray;
D3D12_TEX3D_SRV Texture3D;
D3D12_TEXCUBE_SRV TextureCube;
D3D12_TEXCUBE_ARRAY_SRV TextureCubeArray;
};
} D3D12_SHADER_RESOURCE_VIEW_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_SUBRESOURCE_DATA
{
const void *pData;
LONG_PTR RowPitch;
LONG_PTR SlicePitch;
} D3D12_SUBRESOURCE_DATA;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_MEMCPY_DEST
{
void *pData;
SIZE_T RowPitch;
SIZE_T SlicePitch;
} D3D12_MEMCPY_DEST;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_SUBRESOURCE_FOOTPRINT
{
DXGI_FORMAT Format;
UINT Width;
UINT Height;
UINT Depth;
UINT RowPitch;
} D3D12_SUBRESOURCE_FOOTPRINT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT
{
UINT64 Offset;
D3D12_SUBRESOURCE_FOOTPRINT Footprint;
} D3D12_PLACED_SUBRESOURCE_FOOTPRINT;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_TEXTURE_COPY_TYPE
{
D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0,
D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1
} D3D12_TEXTURE_COPY_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_TEXTURE_COPY_LOCATION
{
ID3D12Resource *pResource;
D3D12_TEXTURE_COPY_TYPE Type;
union
{
D3D12_PLACED_SUBRESOURCE_FOOTPRINT PlacedFootprint;
UINT SubresourceIndex;
};
} D3D12_TEXTURE_COPY_LOCATION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DESCRIPTOR_RANGE_TYPE
{
D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0,
D3D12_DESCRIPTOR_RANGE_TYPE_UAV = (D3D12_DESCRIPTOR_RANGE_TYPE_SRV + 1),
D3D12_DESCRIPTOR_RANGE_TYPE_CBV = (D3D12_DESCRIPTOR_RANGE_TYPE_UAV + 1),
D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = (D3D12_DESCRIPTOR_RANGE_TYPE_CBV + 1)
} D3D12_DESCRIPTOR_RANGE_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DESCRIPTOR_RANGE
{
D3D12_DESCRIPTOR_RANGE_TYPE RangeType;
UINT NumDescriptors;
UINT BaseShaderRegister;
UINT RegisterSpace;
UINT OffsetInDescriptorsFromTableStart;
} D3D12_DESCRIPTOR_RANGE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D_ROOT_SIGNATURE_VERSION
{
D3D_ROOT_SIGNATURE_VERSION_1 = 0x1
} D3D_ROOT_SIGNATURE_VERSION;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_ROOT_PARAMETER_TYPE
{
D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0,
D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = (D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE + 1),
D3D12_ROOT_PARAMETER_TYPE_CBV = (D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS + 1),
D3D12_ROOT_PARAMETER_TYPE_SRV = (D3D12_ROOT_PARAMETER_TYPE_CBV + 1),
D3D12_ROOT_PARAMETER_TYPE_UAV = (D3D12_ROOT_PARAMETER_TYPE_SRV + 1)
} D3D12_ROOT_PARAMETER_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_ROOT_DESCRIPTOR_TABLE
{
UINT NumDescriptorRanges;
_Field_size_full_(NumDescriptorRanges) const D3D12_DESCRIPTOR_RANGE *pDescriptorRanges;
} D3D12_ROOT_DESCRIPTOR_TABLE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_ROOT_CONSTANTS
{
UINT ShaderRegister;
UINT RegisterSpace;
UINT Num32BitValues;
} D3D12_ROOT_CONSTANTS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_ROOT_DESCRIPTOR
{
UINT ShaderRegister;
UINT RegisterSpace;
} D3D12_ROOT_DESCRIPTOR;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_SHADER_VISIBILITY
{
D3D12_SHADER_VISIBILITY_ALL = 0,
D3D12_SHADER_VISIBILITY_VERTEX = 1,
D3D12_SHADER_VISIBILITY_HULL = 2,
D3D12_SHADER_VISIBILITY_DOMAIN = 3,
D3D12_SHADER_VISIBILITY_GEOMETRY = 4,
D3D12_SHADER_VISIBILITY_PIXEL = 5
} D3D12_SHADER_VISIBILITY;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_ROOT_PARAMETER
{
D3D12_ROOT_PARAMETER_TYPE ParameterType;
union
{
D3D12_ROOT_DESCRIPTOR_TABLE DescriptorTable;
D3D12_ROOT_CONSTANTS Constants;
D3D12_ROOT_DESCRIPTOR Descriptor;
};
D3D12_SHADER_VISIBILITY ShaderVisibility;
} D3D12_ROOT_PARAMETER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_STATIC_BORDER_COLOR
{
D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0,
D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = (D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK + 1),
D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = (D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK + 1)
} D3D12_STATIC_BORDER_COLOR;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_FILTER
{
D3D12_FILTER_MIN_MAG_MIP_POINT = 0,
D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
D3D12_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
D3D12_FILTER_ANISOTROPIC = 0x55,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
D3D12_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100,
D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101,
D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104,
D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105,
D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110,
D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111,
D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114,
D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115,
D3D12_FILTER_MINIMUM_ANISOTROPIC = 0x155,
D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180,
D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181,
D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184,
D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185,
D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190,
D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191,
D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194,
D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195,
D3D12_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5
} D3D12_FILTER;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_TEXTURE_ADDRESS_MODE
{
D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3,
D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5
} D3D12_TEXTURE_ADDRESS_MODE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_COMPARISON_FUNC
{
D3D12_COMPARISON_FUNC_NEVER = 1,
D3D12_COMPARISON_FUNC_LESS = 2,
D3D12_COMPARISON_FUNC_EQUAL = 3,
D3D12_COMPARISON_FUNC_LESS_EQUAL = 4,
D3D12_COMPARISON_FUNC_GREATER = 5,
D3D12_COMPARISON_FUNC_NOT_EQUAL = 6,
D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7,
D3D12_COMPARISON_FUNC_ALWAYS = 8
} D3D12_COMPARISON_FUNC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_STATIC_SAMPLER_DESC
{
D3D12_FILTER Filter;
D3D12_TEXTURE_ADDRESS_MODE AddressU;
D3D12_TEXTURE_ADDRESS_MODE AddressV;
D3D12_TEXTURE_ADDRESS_MODE AddressW;
FLOAT MipLODBias;
UINT MaxAnisotropy;
D3D12_COMPARISON_FUNC ComparisonFunc;
D3D12_STATIC_BORDER_COLOR BorderColor;
FLOAT MinLOD;
FLOAT MaxLOD;
UINT ShaderRegister;
UINT RegisterSpace;
D3D12_SHADER_VISIBILITY ShaderVisibility;
} D3D12_STATIC_SAMPLER_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_ROOT_SIGNATURE_FLAGS
{
D3D12_ROOT_SIGNATURE_FLAG_NONE = 0,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1,
D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2,
D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4,
D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8,
D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10,
D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40
} D3D12_ROOT_SIGNATURE_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_ROOT_SIGNATURE_DESC
{
UINT NumParameters;
_Field_size_full_(NumParameters) const D3D12_ROOT_PARAMETER *pParameters;
UINT NumStaticSamplers;
_Field_size_full_(NumStaticSamplers) const D3D12_STATIC_SAMPLER_DESC *pStaticSamplers;
D3D12_ROOT_SIGNATURE_FLAGS Flags;
} D3D12_ROOT_SIGNATURE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_SHADER_BYTECODE
{
_Field_size_bytes_full_(BytecodeLength) const void *pShaderBytecode;
SIZE_T BytecodeLength;
} D3D12_SHADER_BYTECODE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_STREAM_OUTPUT_DESC
{
_Field_size_full_(NumEntries) const D3D12_SO_DECLARATION_ENTRY *pSODeclaration;
UINT NumEntries;
_Field_size_full_(NumStrides) const UINT *pBufferStrides;
UINT NumStrides;
UINT RasterizedStream;
} D3D12_STREAM_OUTPUT_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_BLEND
{
D3D12_BLEND_ZERO = 1,
D3D12_BLEND_ONE = 2,
D3D12_BLEND_SRC_COLOR = 3,
D3D12_BLEND_INV_SRC_COLOR = 4,
D3D12_BLEND_SRC_ALPHA = 5,
D3D12_BLEND_INV_SRC_ALPHA = 6,
D3D12_BLEND_DEST_ALPHA = 7,
D3D12_BLEND_INV_DEST_ALPHA = 8,
D3D12_BLEND_DEST_COLOR = 9,
D3D12_BLEND_INV_DEST_COLOR = 10,
D3D12_BLEND_SRC_ALPHA_SAT = 11,
D3D12_BLEND_BLEND_FACTOR = 14,
D3D12_BLEND_INV_BLEND_FACTOR = 15,
D3D12_BLEND_SRC1_COLOR = 16,
D3D12_BLEND_INV_SRC1_COLOR = 17,
D3D12_BLEND_SRC1_ALPHA = 18,
D3D12_BLEND_INV_SRC1_ALPHA = 19
} D3D12_BLEND;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_BLEND_OP
{
D3D12_BLEND_OP_ADD = 1,
D3D12_BLEND_OP_SUBTRACT = 2,
D3D12_BLEND_OP_REV_SUBTRACT = 3,
D3D12_BLEND_OP_MIN = 4,
D3D12_BLEND_OP_MAX = 5
} D3D12_BLEND_OP;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_LOGIC_OP
{
D3D12_LOGIC_OP_CLEAR = 0,
D3D12_LOGIC_OP_SET = (D3D12_LOGIC_OP_CLEAR + 1),
D3D12_LOGIC_OP_COPY = (D3D12_LOGIC_OP_SET + 1),
D3D12_LOGIC_OP_COPY_INVERTED = (D3D12_LOGIC_OP_COPY + 1),
D3D12_LOGIC_OP_NOOP = (D3D12_LOGIC_OP_COPY_INVERTED + 1),
D3D12_LOGIC_OP_INVERT = (D3D12_LOGIC_OP_NOOP + 1),
D3D12_LOGIC_OP_AND = (D3D12_LOGIC_OP_INVERT + 1),
D3D12_LOGIC_OP_NAND = (D3D12_LOGIC_OP_AND + 1),
D3D12_LOGIC_OP_OR = (D3D12_LOGIC_OP_NAND + 1),
D3D12_LOGIC_OP_NOR = (D3D12_LOGIC_OP_OR + 1),
D3D12_LOGIC_OP_XOR = (D3D12_LOGIC_OP_NOR + 1),
D3D12_LOGIC_OP_EQUIV = (D3D12_LOGIC_OP_XOR + 1),
D3D12_LOGIC_OP_AND_REVERSE = (D3D12_LOGIC_OP_EQUIV + 1),
D3D12_LOGIC_OP_AND_INVERTED = (D3D12_LOGIC_OP_AND_REVERSE + 1),
D3D12_LOGIC_OP_OR_REVERSE = (D3D12_LOGIC_OP_AND_INVERTED + 1),
D3D12_LOGIC_OP_OR_INVERTED = (D3D12_LOGIC_OP_OR_REVERSE + 1)
} D3D12_LOGIC_OP;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RENDER_TARGET_BLEND_DESC
{
BOOL BlendEnable;
BOOL LogicOpEnable;
D3D12_BLEND SrcBlend;
D3D12_BLEND DestBlend;
D3D12_BLEND_OP BlendOp;
D3D12_BLEND SrcBlendAlpha;
D3D12_BLEND DestBlendAlpha;
D3D12_BLEND_OP BlendOpAlpha;
D3D12_LOGIC_OP LogicOp;
UINT8 RenderTargetWriteMask;
} D3D12_RENDER_TARGET_BLEND_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_BLEND_DESC
{
BOOL AlphaToCoverageEnable;
BOOL IndependentBlendEnable;
D3D12_RENDER_TARGET_BLEND_DESC RenderTarget[8];
} D3D12_BLEND_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_COLOR_WRITE_ENABLE
{
D3D12_COLOR_WRITE_ENABLE_RED = 1,
D3D12_COLOR_WRITE_ENABLE_GREEN = 2,
D3D12_COLOR_WRITE_ENABLE_BLUE = 4,
D3D12_COLOR_WRITE_ENABLE_ALPHA = 8,
D3D12_COLOR_WRITE_ENABLE_ALL = (((D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN) | D3D12_COLOR_WRITE_ENABLE_BLUE | D3D12_COLOR_WRITE_ENABLE_ALPHA))
} D3D12_COLOR_WRITE_ENABLE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_CONSERVATIVE_RASTERIZATION_MODE
{
D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0,
D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1
} D3D12_CONSERVATIVE_RASTERIZATION_MODE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_FILL_MODE
{
D3D12_FILL_MODE_WIREFRAME = 2,
D3D12_FILL_MODE_SOLID = 3
} D3D12_FILL_MODE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_CULL_MODE
{
D3D12_CULL_MODE_NONE = 1,
D3D12_CULL_MODE_FRONT = 2,
D3D12_CULL_MODE_BACK = 3
} D3D12_CULL_MODE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_RASTERIZER_DESC
{
D3D12_FILL_MODE FillMode;
D3D12_CULL_MODE CullMode;
BOOL FrontCounterClockwise;
INT DepthBias;
FLOAT DepthBiasClamp;
FLOAT SlopeScaledDepthBias;
BOOL DepthClipEnable;
BOOL MultisampleEnable;
BOOL AntialiasedLineEnable;
UINT ForcedSampleCount;
D3D12_CONSERVATIVE_RASTERIZATION_MODE ConservativeRaster;
} D3D12_RASTERIZER_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_STENCIL_OP
{
D3D12_STENCIL_OP_KEEP = 1,
D3D12_STENCIL_OP_ZERO = 2,
D3D12_STENCIL_OP_REPLACE = 3,
D3D12_STENCIL_OP_INCR_SAT = 4,
D3D12_STENCIL_OP_DECR_SAT = 5,
D3D12_STENCIL_OP_INVERT = 6,
D3D12_STENCIL_OP_INCR = 7,
D3D12_STENCIL_OP_DECR = 8
} D3D12_STENCIL_OP;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DEPTH_STENCILOP_DESC
{
D3D12_STENCIL_OP StencilFailOp;
D3D12_STENCIL_OP StencilDepthFailOp;
D3D12_STENCIL_OP StencilPassOp;
D3D12_COMPARISON_FUNC StencilFunc;
} D3D12_DEPTH_STENCILOP_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_DEPTH_WRITE_MASK
{
D3D12_DEPTH_WRITE_MASK_ZERO = 0,
D3D12_DEPTH_WRITE_MASK_ALL = 1
} D3D12_DEPTH_WRITE_MASK;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_DEPTH_STENCIL_DESC
{
BOOL DepthEnable;
D3D12_DEPTH_WRITE_MASK DepthWriteMask;
D3D12_COMPARISON_FUNC DepthFunc;
BOOL StencilEnable;
UINT8 StencilReadMask;
UINT8 StencilWriteMask;
D3D12_DEPTH_STENCILOP_DESC FrontFace;
D3D12_DEPTH_STENCILOP_DESC BackFace;
} D3D12_DEPTH_STENCIL_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_INPUT_LAYOUT_DESC
{
_Field_size_full_(NumElements) const D3D12_INPUT_ELEMENT_DESC *pInputElementDescs;
UINT NumElements;
} D3D12_INPUT_LAYOUT_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE
{
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0,
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1,
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2
} D3D12_INDEX_BUFFER_STRIP_CUT_VALUE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_CACHED_PIPELINE_STATE
{
_Field_size_bytes_full_(CachedBlobSizeInBytes) const void *pCachedBlob;
SIZE_T CachedBlobSizeInBytes;
} D3D12_CACHED_PIPELINE_STATE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_PIPELINE_STATE_FLAGS
{
D3D12_PIPELINE_STATE_FLAG_NONE = 0,
D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x1
} D3D12_PIPELINE_STATE_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_GRAPHICS_PIPELINE_STATE_DESC
{
ID3D12RootSignature *pRootSignature;
D3D12_SHADER_BYTECODE VS;
D3D12_SHADER_BYTECODE PS;
D3D12_SHADER_BYTECODE DS;
D3D12_SHADER_BYTECODE HS;
D3D12_SHADER_BYTECODE GS;
D3D12_STREAM_OUTPUT_DESC StreamOutput;
D3D12_BLEND_DESC BlendState;
UINT SampleMask;
D3D12_RASTERIZER_DESC RasterizerState;
D3D12_DEPTH_STENCIL_DESC DepthStencilState;
D3D12_INPUT_LAYOUT_DESC InputLayout;
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE IBStripCutValue;
D3D12_PRIMITIVE_TOPOLOGY_TYPE PrimitiveTopologyType;
UINT NumRenderTargets;
DXGI_FORMAT RTVFormats[8];
DXGI_FORMAT DSVFormat;
DXGI_SAMPLE_DESC SampleDesc;
UINT NodeMask;
D3D12_CACHED_PIPELINE_STATE CachedPSO;
D3D12_PIPELINE_STATE_FLAGS Flags;
} D3D12_GRAPHICS_PIPELINE_STATE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_COMPUTE_PIPELINE_STATE_DESC
{
ID3D12RootSignature *pRootSignature;
D3D12_SHADER_BYTECODE CS;
UINT NodeMask;
D3D12_CACHED_PIPELINE_STATE CachedPSO;
D3D12_PIPELINE_STATE_FLAGS Flags;
} D3D12_COMPUTE_PIPELINE_STATE_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef enum D3D12_INDIRECT_ARGUMENT_TYPE
{
D3D12_INDIRECT_ARGUMENT_TYPE_DRAW = 0,
D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED = (D3D12_INDIRECT_ARGUMENT_TYPE_DRAW + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH = (D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW = (D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW = (D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT = (D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW = (D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW = (D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW + 1),
D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW = (D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW + 1)
} D3D12_INDIRECT_ARGUMENT_TYPE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_INDIRECT_ARGUMENT_DESC
{
D3D12_INDIRECT_ARGUMENT_TYPE Type;
union
{
struct
{
UINT Slot;
} VertexBuffer;
struct
{
UINT RootParameterIndex;
UINT DestOffsetIn32BitValues;
UINT Num32BitValuesToSet;
} Constant;
struct
{
UINT RootParameterIndex;
} ConstantBufferView;
struct
{
UINT RootParameterIndex;
} ShaderResourceView;
struct
{
UINT RootParameterIndex;
} UnorderedAccessView;
};
} D3D12_INDIRECT_ARGUMENT_DESC;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
typedef struct D3D12_COMMAND_SIGNATURE_DESC
{
UINT ByteStride;
UINT NumArgumentDescs;
_Field_size_full_(NumArgumentDescs) const D3D12_INDIRECT_ARGUMENT_DESC *pArgumentDescs;
UINT NodeMask;
} D3D12_COMMAND_SIGNATURE_DESC;
#ifdef RHI_DEBUG
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h"
typedef enum D3D12_DEBUG_FEATURE
{
D3D12_DEBUG_FEATURE_NONE = 0,
D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DRAW = 0x1,
D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DISPATCH = 0x2
} D3D12_DEBUG_FEATURE;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h"
typedef enum D3D12_RLDO_FLAGS
{
D3D12_RLDO_NONE = 0,
D3D12_RLDO_SUMMARY = 0x1,
D3D12_RLDO_DETAIL = 0x2,
D3D12_RLDO_IGNORE_INTERNAL = 0x4
} D3D12_RLDO_FLAGS;
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "pix_win.h"
static constexpr UINT PIX_EVENT_ANSI_VERSION = 1;
#endif
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("aec22fb8-76f3-4639-9be0-28eb43a67a2e")
IDXGIObject : public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE SetPrivateData(_In_ REFGUID Name, UINT DataSize, _In_reads_bytes_(DataSize) const void *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(_In_ REFGUID Name, _In_ const IUnknown *pUnknown) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPrivateData(_In_ REFGUID Name, _Inout_ UINT *pDataSize, _Out_writes_bytes_(*pDataSize) void *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE GetParent(_In_ REFIID riid, _COM_Outptr_ void **ppParent) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("3d3e0379-f9de-4d58-bb6c-18d62992f1a6")
IDXGIDeviceSubObject : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE GetDevice(_In_ REFIID riid, _COM_Outptr_ void **ppDevice) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("310d36a0-d2e7-4c0a-aa04-6a9d23b8886a")
IDXGISwapChain : public IDXGIDeviceSubObject
{
virtual HRESULT STDMETHODCALLTYPE Present(UINT SyncInterval, UINT Flags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT Buffer, _In_ REFIID riid, _COM_Outptr_ void **ppSurface) = 0;
virtual HRESULT STDMETHODCALLTYPE SetFullscreenState(BOOL Fullscreen, _In_opt_ IDXGIOutput *pTarget) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFullscreenState(_Out_opt_ BOOL *pFullscreen, _COM_Outptr_opt_result_maybenull_ IDXGIOutput **ppTarget) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDesc(_Out_ DXGI_SWAP_CHAIN_DESC *pDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE ResizeTarget(_In_ const DXGI_MODE_DESC *pNewTargetParameters) = 0;
virtual HRESULT STDMETHODCALLTYPE GetContainingOutput(_COM_Outptr_ IDXGIOutput **ppOutput) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFrameStatistics(_Out_ DXGI_FRAME_STATISTICS *pStats) = 0;
virtual HRESULT STDMETHODCALLTYPE GetLastPresentCount(_Out_ UINT *pLastPresentCount) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_2.h"
MIDL_INTERFACE("790a45f7-0d42-4876-983a-0a55cfe6f4aa")
IDXGISwapChain1 : public IDXGISwapChain
{
virtual HRESULT STDMETHODCALLTYPE GetDesc1(_Out_ DXGI_SWAP_CHAIN_DESC1 *pDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFullscreenDesc(_Out_ DXGI_SWAP_CHAIN_FULLSCREEN_DESC *pDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHwnd(_Out_ HWND *pHwnd) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCoreWindow(_In_ REFIID refiid, _COM_Outptr_ void **ppUnk) = 0;
virtual HRESULT STDMETHODCALLTYPE Present1(UINT SyncInterval, UINT PresentFlags, _In_ const DXGI_PRESENT_PARAMETERS *pPresentParameters) = 0;
virtual BOOL STDMETHODCALLTYPE IsTemporaryMonoSupported(void) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRestrictToOutput(_Out_ IDXGIOutput **ppRestrictToOutput) = 0;
virtual HRESULT STDMETHODCALLTYPE SetBackgroundColor(_In_ const DXGI_RGBA *pColor) = 0;
virtual HRESULT STDMETHODCALLTYPE GetBackgroundColor(_Out_ DXGI_RGBA *pColor) = 0;
virtual HRESULT STDMETHODCALLTYPE SetRotation(_In_ DXGI_MODE_ROTATION Rotation) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRotation(_Out_ DXGI_MODE_ROTATION *pRotation) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_3.h"
MIDL_INTERFACE("a8be2ac4-199f-4946-b331-79599fb98de7")
IDXGISwapChain2 : public IDXGISwapChain1
{
virtual HRESULT STDMETHODCALLTYPE SetSourceSize(UINT Width, UINT Height) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceSize(_Out_ UINT *pWidth, _Out_ UINT *pHeight) = 0;
virtual HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT MaxLatency) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(_Out_ UINT *pMaxLatency) = 0;
virtual HANDLE STDMETHODCALLTYPE GetFrameLatencyWaitableObject(void) = 0;
virtual HRESULT STDMETHODCALLTYPE SetMatrixTransform(const DXGI_MATRIX_3X2_F *pMatrix) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMatrixTransform(_Out_ DXGI_MATRIX_3X2_F *pMatrix) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "dxgi1_4.h"
MIDL_INTERFACE("94d99bdb-f1f8-4ab0-b236-7da0170edab1")
IDXGISwapChain3 : public IDXGISwapChain2
{
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex(void) = 0;
virtual HRESULT STDMETHODCALLTYPE CheckColorSpaceSupport(_In_ DXGI_COLOR_SPACE_TYPE ColorSpace, _Out_ UINT *pColorSpaceSupport) = 0;
virtual HRESULT STDMETHODCALLTYPE SetColorSpace1(_In_ DXGI_COLOR_SPACE_TYPE ColorSpace) = 0;
virtual HRESULT STDMETHODCALLTYPE ResizeBuffers1(_In_ UINT BufferCount, _In_ UINT Width, _In_ UINT Height, _In_ DXGI_FORMAT Format, _In_ UINT SwapChainFlags, _In_reads_(BufferCount) const UINT *pCreationNodeMask, _In_reads_(BufferCount) IUnknown *const *ppPresentQueue) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("7b7166ec-21c7-44ae-b21a-c9ae321ae369")
IDXGIFactory : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE EnumAdapters(UINT Adapter, _COM_Outptr_ IDXGIAdapter **ppAdapter) = 0;
virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation(HWND WindowHandle, UINT Flags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation(_Out_ HWND *pWindowHandle) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(_In_ IUnknown *pDevice, _In_ DXGI_SWAP_CHAIN_DESC *pDesc, _COM_Outptr_ IDXGISwapChain **ppSwapChain) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE Module, _COM_Outptr_ IDXGIAdapter **ppAdapter) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("770aae78-f26f-4dba-a829-253c83d1b387")
IDXGIFactory1 : public IDXGIFactory
{
virtual HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT Adapter, __out IDXGIAdapter1 **ppAdapter) = 0;
virtual BOOL STDMETHODCALLTYPE IsCurrent(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("50c83a1c-e072-4c48-87b0-3630fa36a6d0")
IDXGIFactory2 : public IDXGIFactory1
{
virtual BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled(void) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(_In_ IUnknown *pDevice, _In_ HWND hWnd, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ const DXGI_SWAP_CHAIN_FULLSCREEN_DESC *pFullscreenDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(_In_ IUnknown *pDevice, _In_ IUnknown *pWindow, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(_In_ HANDLE hResource, _Out_ LUID *pLuid) = 0;
virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0;
virtual void STDMETHODCALLTYPE UnregisterStereoStatus(_In_ DWORD dwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(_In_ HWND WindowHandle, _In_ UINT wMsg, _Out_ DWORD *pdwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(_In_ HANDLE hEvent, _Out_ DWORD *pdwCookie) = 0;
virtual void STDMETHODCALLTYPE UnregisterOcclusionStatus(_In_ DWORD dwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(_In_ IUnknown *pDevice, _In_ const DXGI_SWAP_CHAIN_DESC1 *pDesc, _In_opt_ IDXGIOutput *pRestrictToOutput, _COM_Outptr_ IDXGISwapChain1 **ppSwapChain) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("25483823-cd46-4c7d-86ca-47aa95b837bd")
IDXGIFactory3 : public IDXGIFactory2
{
virtual UINT STDMETHODCALLTYPE GetCreationFlags(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("1bc6ea02-ef36-464f-bf0c-21ca39e5168a")
IDXGIFactory4 : public IDXGIFactory3
{
virtual HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(_In_ LUID AdapterLuid, _In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0;
virtual HRESULT STDMETHODCALLTYPE EnumWarpAdapter(_In_ REFIID riid, _COM_Outptr_ void **ppvAdapter) = 0;
};
// "Microsoft DirectX SDK (June 2010)" -> "DXGI.h"
struct DXGI_ADAPTER_DESC
{
WCHAR Description[128];
UINT VendorId;
UINT DeviceId;
UINT SubSysId;
UINT Revision;
SIZE_T DedicatedVideoMemory;
SIZE_T DedicatedSystemMemory;
SIZE_T SharedSystemMemory;
LUID AdapterLuid;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("2411e7e1-12ac-4ccf-bd14-9798e8534dc0")
IDXGIAdapter : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE EnumOutputs(UINT Output, __out IDXGIOutput **ppOutput) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDesc(__out DXGI_ADAPTER_DESC *pDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(__in REFGUID InterfaceName, __out LARGE_INTEGER *pUMDVersion) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "DXGI.h"
MIDL_INTERFACE("54ec77fa-1377-44e6-8c32-88fd5f44c84c")
IDXGIDevice : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE GetAdapter(_COM_Outptr_ IDXGIAdapter **pAdapter) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSurface(_In_ const DXGI_SURFACE_DESC *pDesc, UINT NumSurfaces, DXGI_USAGE Usage, _In_opt_ const DXGI_SHARED_RESOURCE *pSharedResource, _COM_Outptr_ IDXGISurface **ppSurface) = 0;
virtual HRESULT STDMETHODCALLTYPE QueryResourceResidency(_In_reads_(NumResources) IUnknown *const *ppResources, _Out_writes_(NumResources) DXGI_RESIDENCY *pResidencyStatus, UINT NumResources) = 0;
virtual HRESULT STDMETHODCALLTYPE SetGPUThreadPriority(INT Priority) = 0;
virtual HRESULT STDMETHODCALLTYPE GetGPUThreadPriority(_Out_ INT *pPriority) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3Dcommon.h"
MIDL_INTERFACE("8BA5FB08-5195-40e2-AC58-0D989C3A0102")
ID3D10Blob : public IUnknown
{
virtual LPVOID STDMETHODCALLTYPE GetBufferPointer(void) = 0;
virtual SIZE_T STDMETHODCALLTYPE GetBufferSize(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("c4fec28f-7966-4e95-9f94-f431cb56c3b8")
ID3D12Object : public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE GetPrivateData(_In_ REFGUID guid, _Inout_ UINT *pDataSize, _Out_writes_bytes_opt_( *pDataSize ) void *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE SetPrivateData(_In_ REFGUID guid, _In_ UINT DataSize, _In_reads_bytes_opt_(DataSize) const void *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(_In_ REFGUID guid, _In_opt_ const IUnknown *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE SetName(_In_z_ LPCWSTR Name) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("905db94b-a00c-4140-9df5-2b64ca9ea357")
ID3D12DeviceChild : public ID3D12Object
{
virtual HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, _COM_Outptr_opt_ void **ppvDevice) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("c54a6b66-72df-4ee8-8be5-a946a1429214")
ID3D12RootSignature : public ID3D12DeviceChild
{
// Nothing here
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("63ee58fb-1268-4835-86da-f008ce62f0d6")
ID3D12Pageable : public ID3D12DeviceChild
{
// Nothing here
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("0d9658ae-ed45-469e-a61d-970ec583cab4")
ID3D12QueryHeap : public ID3D12Pageable
{
// Nothing here
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("0a753dcf-c4d8-4b91-adf6-be5a60d95a76")
ID3D12Fence : public ID3D12Pageable
{
virtual UINT64 STDMETHODCALLTYPE GetCompletedValue(void) = 0;
virtual HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64 Value, HANDLE hEvent) = 0;
virtual HRESULT STDMETHODCALLTYPE Signal(UINT64 Value) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("696442be-a72e-4059-bc79-5b5c98040fad")
ID3D12Resource : public ID3D12Pageable
{
virtual HRESULT STDMETHODCALLTYPE Map(UINT Subresource, _In_opt_ const D3D12_RANGE *pReadRange, _Outptr_opt_result_bytebuffer_(_Inexpressible_("Dependent on resource")) void **ppData) = 0;
virtual void STDMETHODCALLTYPE Unmap(UINT Subresource, _In_opt_ const D3D12_RANGE *pWrittenRange) = 0;
virtual D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc(void) = 0;
virtual D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress( void) = 0;
virtual HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT DstSubresource, _In_opt_ const D3D12_BOX *pDstBox, _In_ const void *pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) = 0;
virtual HRESULT STDMETHODCALLTYPE ReadFromSubresource(_Out_ void *pDstData, UINT DstRowPitch, UINT DstDepthPitch, UINT SrcSubresource, _In_opt_ const D3D12_BOX *pSrcBox) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHeapProperties(_Out_opt_ D3D12_HEAP_PROPERTIES *pHeapProperties, _Out_opt_ D3D12_HEAP_FLAGS *pHeapFlags) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("765a30f3-f624-4c6f-a828-ace948622445")
ID3D12PipelineState : public ID3D12Pageable
{
virtual HRESULT STDMETHODCALLTYPE GetCachedBlob(_COM_Outptr_ ID3DBlob* *ppBlob) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("8efb471d-616c-4f49-90f7-127bb763fa51")
ID3D12DescriptorHeap : public ID3D12Pageable
{
virtual D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc(void) = 0;
virtual D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart(void) = 0;
virtual D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("6102dee4-af59-4b09-b999-b44d73f09b24")
ID3D12CommandAllocator : public ID3D12Pageable
{
virtual HRESULT STDMETHODCALLTYPE Reset(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("c36a797c-ec80-4f0a-8985-a7b2475082d1")
ID3D12CommandSignature : public ID3D12Pageable
{
// Nothing here
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("7116d91c-e7e4-47ce-b8c6-ec8168f437e5")
ID3D12CommandList : public ID3D12DeviceChild
{
virtual D3D12_COMMAND_LIST_TYPE STDMETHODCALLTYPE GetType(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("5b160d0f-ac1b-4185-8ba8-b3ae42a5a455")
ID3D12GraphicsCommandList : public ID3D12CommandList
{
virtual HRESULT STDMETHODCALLTYPE Close(void) = 0;
virtual HRESULT STDMETHODCALLTYPE Reset(_In_ ID3D12CommandAllocator *pAllocator, _In_opt_ ID3D12PipelineState *pInitialState) = 0;
virtual void STDMETHODCALLTYPE ClearState(_In_opt_ ID3D12PipelineState *pPipelineState) = 0;
virtual void STDMETHODCALLTYPE DrawInstanced(_In_ UINT VertexCountPerInstance, _In_ UINT InstanceCount, _In_ UINT StartVertexLocation, _In_ UINT StartInstanceLocation) = 0;
virtual void STDMETHODCALLTYPE DrawIndexedInstanced(_In_ UINT IndexCountPerInstance, _In_ UINT InstanceCount, _In_ UINT StartIndexLocation, _In_ INT BaseVertexLocation, _In_ UINT StartInstanceLocation) = 0;
virtual void STDMETHODCALLTYPE Dispatch(_In_ UINT ThreadGroupCountX, _In_ UINT ThreadGroupCountY, _In_ UINT ThreadGroupCountZ) = 0;
virtual void STDMETHODCALLTYPE CopyBufferRegion(_In_ ID3D12Resource *pDstBuffer, UINT64 DstOffset, _In_ ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT64 NumBytes) = 0;
virtual void STDMETHODCALLTYPE CopyTextureRegion(_In_ const D3D12_TEXTURE_COPY_LOCATION *pDst, UINT DstX, UINT DstY, UINT DstZ, _In_ const D3D12_TEXTURE_COPY_LOCATION *pSrc, _In_opt_ const D3D12_BOX *pSrcBox) = 0;
virtual void STDMETHODCALLTYPE CopyResource(_In_ ID3D12Resource *pDstResource, _In_ ID3D12Resource *pSrcResource) = 0;
virtual void STDMETHODCALLTYPE CopyTiles(_In_ ID3D12Resource *pTiledResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate, _In_ const D3D12_TILE_REGION_SIZE *pTileRegionSize, _In_ ID3D12Resource *pBuffer, UINT64 BufferStartOffsetInBytes, D3D12_TILE_COPY_FLAGS Flags) = 0;
virtual void STDMETHODCALLTYPE ResolveSubresource(_In_ ID3D12Resource *pDstResource, _In_ UINT DstSubresource, _In_ ID3D12Resource *pSrcResource, _In_ UINT SrcSubresource, _In_ DXGI_FORMAT Format) = 0;
virtual void STDMETHODCALLTYPE IASetPrimitiveTopology(_In_ D3D12_PRIMITIVE_TOPOLOGY PrimitiveTopology) = 0;
virtual void STDMETHODCALLTYPE RSSetViewports(_In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumViewports, _In_reads_( NumViewports) const D3D12_VIEWPORT *pViewports) = 0;
virtual void STDMETHODCALLTYPE RSSetScissorRects(_In_range_(0, D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) UINT NumRects, _In_reads_( NumRects) const D3D12_RECT *pRects) = 0;
virtual void STDMETHODCALLTYPE OMSetBlendFactor(_In_opt_ const FLOAT BlendFactor[4]) = 0;
virtual void STDMETHODCALLTYPE OMSetStencilRef(_In_ UINT StencilRef) = 0;
virtual void STDMETHODCALLTYPE SetPipelineState(_In_ ID3D12PipelineState *pPipelineState) = 0;
virtual void STDMETHODCALLTYPE ResourceBarrier(_In_ UINT NumBarriers, _In_reads_(NumBarriers) const D3D12_RESOURCE_BARRIER *pBarriers) = 0;
virtual void STDMETHODCALLTYPE ExecuteBundle(_In_ ID3D12GraphicsCommandList *pCommandList) = 0;
virtual void STDMETHODCALLTYPE SetDescriptorHeaps(_In_ UINT NumDescriptorHeaps, _In_reads_(NumDescriptorHeaps) ID3D12DescriptorHeap **ppDescriptorHeaps) = 0;
virtual void STDMETHODCALLTYPE SetComputeRootSignature(_In_ ID3D12RootSignature *pRootSignature) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRootSignature(_In_ ID3D12RootSignature *pRootSignature) = 0;
virtual void STDMETHODCALLTYPE SetComputeRootDescriptorTable(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) = 0;
virtual void STDMETHODCALLTYPE SetComputeRoot32BitConstant(_In_ UINT RootParameterIndex, _In_ UINT SrcData, _In_ UINT DestOffsetIn32BitValues) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRoot32BitConstant(_In_ UINT RootParameterIndex, _In_ UINT SrcData, _In_ UINT DestOffsetIn32BitValues) = 0;
virtual void STDMETHODCALLTYPE SetComputeRoot32BitConstants(_In_ UINT RootParameterIndex, _In_ UINT Num32BitValuesToSet, _In_reads_(Num32BitValuesToSet * sizeof(UINT)) const void *pSrcData, _In_ UINT DestOffsetIn32BitValues) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRoot32BitConstants(_In_ UINT RootParameterIndex, _In_ UINT Num32BitValuesToSet, _In_reads_(Num32BitValuesToSet * sizeof(UINT)) const void *pSrcData, _In_ UINT DestOffsetIn32BitValues) = 0;
virtual void STDMETHODCALLTYPE SetComputeRootConstantBufferView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE SetComputeRootShaderResourceView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(_In_ UINT RootParameterIndex, _In_ D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) = 0;
virtual void STDMETHODCALLTYPE IASetIndexBuffer(_In_opt_ const D3D12_INDEX_BUFFER_VIEW *pView) = 0;
virtual void STDMETHODCALLTYPE IASetVertexBuffers(_In_ UINT StartSlot, _In_ UINT NumViews, _In_reads_opt_(NumViews) const D3D12_VERTEX_BUFFER_VIEW *pViews) = 0;
virtual void STDMETHODCALLTYPE SOSetTargets(_In_ UINT StartSlot, _In_ UINT NumViews, _In_reads_opt_(NumViews) const D3D12_STREAM_OUTPUT_BUFFER_VIEW *pViews) = 0;
virtual void STDMETHODCALLTYPE OMSetRenderTargets(_In_ UINT NumRenderTargetDescriptors, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE *pRenderTargetDescriptors, _In_ BOOL RTsSingleHandleToDescriptorRange, _In_opt_ const D3D12_CPU_DESCRIPTOR_HANDLE *pDepthStencilDescriptor) = 0;
virtual void STDMETHODCALLTYPE ClearDepthStencilView(_In_ D3D12_CPU_DESCRIPTOR_HANDLE DepthStencilView, _In_ D3D12_CLEAR_FLAGS ClearFlags, _In_ FLOAT Depth, _In_ UINT8 Stencil, _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0;
virtual void STDMETHODCALLTYPE ClearRenderTargetView(_In_ D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView, _In_ const FLOAT ColorRGBA[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0;
virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(_In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, _In_ ID3D12Resource *pResource, _In_ const UINT Values[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0;
virtual void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(_In_ D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, _In_ D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, _In_ ID3D12Resource *pResource, _In_ const FLOAT Values[4], _In_ UINT NumRects, _In_reads_(NumRects) const D3D12_RECT *pRects) = 0;
virtual void STDMETHODCALLTYPE DiscardResource(_In_ ID3D12Resource *pResource, _In_opt_ const D3D12_DISCARD_REGION *pRegion) = 0;
virtual void STDMETHODCALLTYPE BeginQuery(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT Index) = 0;
virtual void STDMETHODCALLTYPE EndQuery(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT Index) = 0;
virtual void STDMETHODCALLTYPE ResolveQueryData(_In_ ID3D12QueryHeap *pQueryHeap, _In_ D3D12_QUERY_TYPE Type, _In_ UINT StartIndex, _In_ UINT NumQueries, _In_ ID3D12Resource *pDestinationBuffer, _In_ UINT64 AlignedDestinationBufferOffset) = 0;
virtual void STDMETHODCALLTYPE SetPredication(_In_opt_ ID3D12Resource *pBuffer, _In_ UINT64 AlignedBufferOffset, _In_ D3D12_PREDICATION_OP Operation) = 0;
virtual void STDMETHODCALLTYPE SetMarker(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0;
virtual void STDMETHODCALLTYPE BeginEvent(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0;
virtual void STDMETHODCALLTYPE EndEvent(void) = 0;
virtual void STDMETHODCALLTYPE ExecuteIndirect(_In_ ID3D12CommandSignature *pCommandSignature, _In_ UINT MaxCommandCount, _In_ ID3D12Resource *pArgumentBuffer, _In_ UINT64 ArgumentBufferOffset, _In_opt_ ID3D12Resource *pCountBuffer, _In_ UINT64 CountBufferOffset) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("0ec870a6-5d7e-4c22-8cfc-5baae07616ed")
ID3D12CommandQueue : public ID3D12Pageable
{
virtual void STDMETHODCALLTYPE UpdateTileMappings(_In_ ID3D12Resource *pResource, UINT NumResourceRegions, _In_reads_opt_(NumResourceRegions) const D3D12_TILED_RESOURCE_COORDINATE *pResourceRegionStartCoordinates, _In_reads_opt_(NumResourceRegions) const D3D12_TILE_REGION_SIZE *pResourceRegionSizes, _In_opt_ ID3D12Heap *pHeap, UINT NumRanges, _In_reads_opt_(NumRanges) const D3D12_TILE_RANGE_FLAGS *pRangeFlags, _In_reads_opt_(NumRanges) const UINT *pHeapRangeStartOffsets, _In_reads_opt_(NumRanges) const UINT *pRangeTileCounts, D3D12_TILE_MAPPING_FLAGS Flags) = 0;
virtual void STDMETHODCALLTYPE CopyTileMappings(_In_ ID3D12Resource *pDstResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pDstRegionStartCoordinate, _In_ ID3D12Resource *pSrcResource, _In_ const D3D12_TILED_RESOURCE_COORDINATE *pSrcRegionStartCoordinate, _In_ const D3D12_TILE_REGION_SIZE *pRegionSize, D3D12_TILE_MAPPING_FLAGS Flags) = 0;
virtual void STDMETHODCALLTYPE ExecuteCommandLists(_In_ UINT NumCommandLists, _In_reads_(NumCommandLists) ID3D12CommandList *const *ppCommandLists) = 0;
virtual void STDMETHODCALLTYPE SetMarker(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0;
virtual void STDMETHODCALLTYPE BeginEvent(UINT Metadata, _In_reads_bytes_opt_(Size) const void *pData, UINT Size) = 0;
virtual void STDMETHODCALLTYPE EndEvent(void) = 0;
virtual HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence *pFence, UINT64 Value) = 0;
virtual HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence *pFence, UINT64 Value) = 0;
virtual HRESULT STDMETHODCALLTYPE GetTimestampFrequency(_Out_ UINT64 *pFrequency) = 0;
virtual HRESULT STDMETHODCALLTYPE GetClockCalibration(_Out_ UINT64 *pGpuTimestamp, _Out_ UINT64 *pCpuTimestamp) = 0;
virtual D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE GetDesc(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
MIDL_INTERFACE("189819f1-1db6-4b57-be54-1821339b85f7")
ID3D12Device : public ID3D12Object
{
virtual UINT STDMETHODCALLTYPE GetNodeCount(void) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateCommandQueue(_In_ const D3D12_COMMAND_QUEUE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppCommandQueue) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateCommandAllocator(_In_ D3D12_COMMAND_LIST_TYPE type, REFIID riid, _COM_Outptr_ void **ppCommandAllocator) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(_In_ const D3D12_GRAPHICS_PIPELINE_STATE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppPipelineState) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateComputePipelineState(_In_ const D3D12_COMPUTE_PIPELINE_STATE_DESC *pDesc, REFIID riid, _COM_Outptr_ void **ppPipelineState) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateCommandList(_In_ UINT nodeMask, _In_ D3D12_COMMAND_LIST_TYPE type, _In_ ID3D12CommandAllocator *pCommandAllocator, _In_opt_ ID3D12PipelineState *pInitialState, REFIID riid, _COM_Outptr_ void **ppCommandList) = 0;
virtual HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE Feature, _Inout_updates_bytes_(FeatureSupportDataSize) void *pFeatureSupportData, UINT FeatureSupportDataSize) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(_In_ const D3D12_DESCRIPTOR_HEAP_DESC *pDescriptorHeapDesc, REFIID riid, _COM_Outptr_ void **ppvHeap) = 0;
virtual UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(_In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapType) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateRootSignature(_In_ UINT nodeMask, _In_reads_(blobLengthInBytes) const void *pBlobWithRootSignature, _In_ SIZE_T blobLengthInBytes, REFIID riid, _COM_Outptr_ void **ppvRootSignature) = 0;
virtual void STDMETHODCALLTYPE CreateConstantBufferView(_In_opt_ const D3D12_CONSTANT_BUFFER_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CreateShaderResourceView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_SHADER_RESOURCE_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CreateUnorderedAccessView(_In_opt_ ID3D12Resource *pResource, _In_opt_ ID3D12Resource *pCounterResource, _In_opt_ const D3D12_UNORDERED_ACCESS_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CreateRenderTargetView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_RENDER_TARGET_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CreateDepthStencilView(_In_opt_ ID3D12Resource *pResource, _In_opt_ const D3D12_DEPTH_STENCIL_VIEW_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CreateSampler(_In_ const D3D12_SAMPLER_DESC *pDesc, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptor) = 0;
virtual void STDMETHODCALLTYPE CopyDescriptors(_In_ UINT NumDestDescriptorRanges, _In_reads_(NumDestDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE *pDestDescriptorRangeStarts, _In_reads_opt_(NumDestDescriptorRanges) const UINT *pDestDescriptorRangeSizes, _In_ UINT NumSrcDescriptorRanges, _In_reads_(NumSrcDescriptorRanges) const D3D12_CPU_DESCRIPTOR_HANDLE *pSrcDescriptorRangeStarts, _In_reads_opt_(NumSrcDescriptorRanges) const UINT *pSrcDescriptorRangeSizes, _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) = 0;
virtual void STDMETHODCALLTYPE CopyDescriptorsSimple(_In_ UINT NumDescriptors, _In_ D3D12_CPU_DESCRIPTOR_HANDLE DestDescriptorRangeStart, _In_ D3D12_CPU_DESCRIPTOR_HANDLE SrcDescriptorRangeStart, _In_ D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeapsType) = 0;
virtual D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo(_In_ UINT visibleMask, _In_ UINT numResourceDescs, _In_reads_(numResourceDescs) const D3D12_RESOURCE_DESC *pResourceDescs) = 0;
virtual D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(_In_ UINT nodeMask, D3D12_HEAP_TYPE heapType) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateCommittedResource(_In_ const D3D12_HEAP_PROPERTIES *pHeapProperties, D3D12_HEAP_FLAGS HeapFlags, _In_ const D3D12_RESOURCE_DESC *pResourceDesc, D3D12_RESOURCE_STATES InitialResourceState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riidResource, _COM_Outptr_opt_ void **ppvResource) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateHeap(_In_ const D3D12_HEAP_DESC *pDesc, REFIID riid, _COM_Outptr_opt_ void **ppvHeap) = 0;
virtual HRESULT STDMETHODCALLTYPE CreatePlacedResource(_In_ ID3D12Heap *pHeap, UINT64 HeapOffset, _In_ const D3D12_RESOURCE_DESC *pDesc, D3D12_RESOURCE_STATES InitialState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riid, _COM_Outptr_opt_ void **ppvResource) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateReservedResource(_In_ const D3D12_RESOURCE_DESC *pDesc, D3D12_RESOURCE_STATES InitialState, _In_opt_ const D3D12_CLEAR_VALUE *pOptimizedClearValue, REFIID riid, _COM_Outptr_opt_ void **ppvResource) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSharedHandle(_In_ ID3D12DeviceChild *pObject, _In_opt_ const SECURITY_ATTRIBUTES *pAttributes, DWORD Access, _In_opt_ LPCWSTR Name, _Out_ HANDLE *pHandle) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenSharedHandle(_In_ HANDLE NTHandle, REFIID riid, _COM_Outptr_opt_ void **ppvObj) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenSharedHandleByName(_In_ LPCWSTR Name, DWORD Access, _Out_ HANDLE *pNTHandle) = 0;
virtual HRESULT STDMETHODCALLTYPE MakeResident(UINT NumObjects, _In_reads_(NumObjects) ID3D12Pageable *const *ppObjects) = 0;
virtual HRESULT STDMETHODCALLTYPE Evict(UINT NumObjects, _In_reads_(NumObjects) ID3D12Pageable *const *ppObjects) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateFence(UINT64 InitialValue, D3D12_FENCE_FLAGS Flags, REFIID riid, _COM_Outptr_ void **ppFence) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason(void) = 0;
virtual void STDMETHODCALLTYPE GetCopyableFootprints(_In_ const D3D12_RESOURCE_DESC *pResourceDesc, _In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource, _In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources, UINT64 BaseOffset, _Out_writes_opt_(NumSubresources) D3D12_PLACED_SUBRESOURCE_FOOTPRINT *pLayouts, _Out_writes_opt_(NumSubresources) UINT *pNumRows, _Out_writes_opt_(NumSubresources) UINT64 *pRowSizeInBytes, _Out_opt_ UINT64 *pTotalBytes) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueryHeap(_In_ const D3D12_QUERY_HEAP_DESC *pDesc, REFIID riid, _COM_Outptr_opt_ void **ppvHeap) = 0;
virtual HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL Enable) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateCommandSignature(_In_ const D3D12_COMMAND_SIGNATURE_DESC *pDesc, _In_opt_ ID3D12RootSignature *pRootSignature, REFIID riid, _COM_Outptr_opt_ void **ppvCommandSignature) = 0;
virtual void STDMETHODCALLTYPE GetResourceTiling(_In_ ID3D12Resource *pTiledResource, _Out_opt_ UINT *pNumTilesForEntireResource, _Out_opt_ D3D12_PACKED_MIP_INFO *pPackedMipDesc, _Out_opt_ D3D12_TILE_SHAPE *pStandardTileShapeForNonPackedMips, _Inout_opt_ UINT *pNumSubresourceTilings, _In_ UINT FirstSubresourceTilingToGet, _Out_writes_(*pNumSubresourceTilings) D3D12_SUBRESOURCE_TILING *pSubresourceTilingsForNonPackedMips) = 0;
virtual LUID STDMETHODCALLTYPE GetAdapterLuid(void) = 0;
};
#ifdef RHI_DEBUG
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h"
MIDL_INTERFACE("344488b7-6846-474b-b989-f027448245e0")
ID3D12Debug : public IUnknown
{
virtual void STDMETHODCALLTYPE EnableDebugLayer(void) = 0;
};
// "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "d3d12sdklayers.h"
MIDL_INTERFACE("3febd6dd-4973-4787-8194-e45f9e28923e")
ID3D12DebugDevice : public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE SetFeatureMask(D3D12_DEBUG_FEATURE Mask) = 0;
virtual D3D12_DEBUG_FEATURE STDMETHODCALLTYPE GetFeatureMask(void) = 0;
virtual HRESULT STDMETHODCALLTYPE ReportLiveDeviceObjects(D3D12_RLDO_FLAGS Flags) = 0;
};
#endif
//[-------------------------------------------------------]
//[ Direct3D12Rhi/D3D12X.h ]
//[-------------------------------------------------------]
// TODO(co) Remove unused stuff when done with the Direct3D 12 RHI implementation
//[-------------------------------------------------------]
//[ Global variables ]
//[-------------------------------------------------------]
struct CD3DX12_DEFAULT {};
extern const DECLSPEC_SELECTANY CD3DX12_DEFAULT D3D12_DEFAULT;
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
//------------------------------------------------------------------------------------------------
struct CD3DX12_CPU_DESCRIPTOR_HANDLE : public D3D12_CPU_DESCRIPTOR_HANDLE
{
CD3DX12_CPU_DESCRIPTOR_HANDLE()
{}
explicit CD3DX12_CPU_DESCRIPTOR_HANDLE(const D3D12_CPU_DESCRIPTOR_HANDLE &o) :
D3D12_CPU_DESCRIPTOR_HANDLE(o)
{}
CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetScaledByIncrementSize)
{
InitOffsetted(other, offsetScaledByIncrementSize);
}
CD3DX12_CPU_DESCRIPTOR_HANDLE(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &other, INT offsetInDescriptors, UINT descriptorIncrementSize)
{
InitOffsetted(other, offsetInDescriptors, descriptorIncrementSize);
}
CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetInDescriptors, UINT descriptorIncrementSize)
{
ptr += offsetInDescriptors * descriptorIncrementSize;
return *this;
}
CD3DX12_CPU_DESCRIPTOR_HANDLE& Offset(INT offsetScaledByIncrementSize)
{
ptr += offsetScaledByIncrementSize;
return *this;
}
[[nodiscard]] bool operator==(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other)
{
return (ptr == other.ptr);
}
[[nodiscard]] bool operator!=(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE& other)
{
return (ptr != other.ptr);
}
CD3DX12_CPU_DESCRIPTOR_HANDLE &operator=(const D3D12_CPU_DESCRIPTOR_HANDLE &other)
{
ptr = other.ptr;
return *this;
}
inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize)
{
InitOffsetted(*this, base, offsetScaledByIncrementSize);
}
inline void InitOffsetted(_In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize)
{
InitOffsetted(*this, base, offsetInDescriptors, descriptorIncrementSize);
}
static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetScaledByIncrementSize)
{
handle.ptr = base.ptr + offsetScaledByIncrementSize;
}
static inline void InitOffsetted(_Out_ D3D12_CPU_DESCRIPTOR_HANDLE &handle, _In_ const D3D12_CPU_DESCRIPTOR_HANDLE &base, INT offsetInDescriptors, UINT descriptorIncrementSize)
{
handle.ptr = base.ptr + offsetInDescriptors * descriptorIncrementSize;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_RESOURCE_BARRIER : public D3D12_RESOURCE_BARRIER
{
CD3DX12_RESOURCE_BARRIER()
{}
explicit CD3DX12_RESOURCE_BARRIER(const D3D12_RESOURCE_BARRIER &o) :
D3D12_RESOURCE_BARRIER(o)
{}
[[nodiscard]] static inline CD3DX12_RESOURCE_BARRIER Transition(
_In_ ID3D12Resource* pResource,
D3D12_RESOURCE_STATES stateBefore,
D3D12_RESOURCE_STATES stateAfter,
UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE)
{
CD3DX12_RESOURCE_BARRIER result = {};
D3D12_RESOURCE_BARRIER &barrier = result;
result.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
result.Flags = flags;
barrier.Transition.pResource = pResource;
barrier.Transition.StateBefore = stateBefore;
barrier.Transition.StateAfter = stateAfter;
barrier.Transition.Subresource = subresource;
return result;
}
[[nodiscard]] static inline CD3DX12_RESOURCE_BARRIER Aliasing(
_In_ ID3D12Resource* pResourceBefore,
_In_ ID3D12Resource* pResourceAfter)
{
CD3DX12_RESOURCE_BARRIER result = {};
D3D12_RESOURCE_BARRIER &barrier = result;
result.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
barrier.Aliasing.pResourceBefore = pResourceBefore;
barrier.Aliasing.pResourceAfter = pResourceAfter;
return result;
}
[[nodiscard]] static inline CD3DX12_RESOURCE_BARRIER UAV(_In_ ID3D12Resource* pResource)
{
CD3DX12_RESOURCE_BARRIER result = {};
D3D12_RESOURCE_BARRIER &barrier = result;
result.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
barrier.UAV.pResource = pResource;
return result;
}
[[nodiscard]] operator const D3D12_RESOURCE_BARRIER&() const
{
return *this;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_HEAP_PROPERTIES : public D3D12_HEAP_PROPERTIES
{
CD3DX12_HEAP_PROPERTIES()
{}
explicit CD3DX12_HEAP_PROPERTIES(const D3D12_HEAP_PROPERTIES &o) :
D3D12_HEAP_PROPERTIES(o)
{}
CD3DX12_HEAP_PROPERTIES(
D3D12_CPU_PAGE_PROPERTY cpuPageProperty,
D3D12_MEMORY_POOL memoryPoolPreference,
UINT creationNodeMask = 1,
UINT nodeMask = 1 )
{
Type = D3D12_HEAP_TYPE_CUSTOM;
CPUPageProperty = cpuPageProperty;
MemoryPoolPreference = memoryPoolPreference;
CreationNodeMask = creationNodeMask;
VisibleNodeMask = nodeMask;
}
explicit CD3DX12_HEAP_PROPERTIES(
D3D12_HEAP_TYPE type,
UINT creationNodeMask = 1,
UINT nodeMask = 1 )
{
Type = type;
CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
CreationNodeMask = creationNodeMask;
VisibleNodeMask = nodeMask;
}
[[nodiscard]] operator const D3D12_HEAP_PROPERTIES&() const
{
return *this;
}
[[nodiscard]] bool IsCPUAccessible() const
{
return Type == D3D12_HEAP_TYPE_UPLOAD || Type == D3D12_HEAP_TYPE_READBACK || (Type == D3D12_HEAP_TYPE_CUSTOM &&
(CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE || CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK));
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_RESOURCE_DESC : public D3D12_RESOURCE_DESC
{
CD3DX12_RESOURCE_DESC()
{}
explicit CD3DX12_RESOURCE_DESC( const D3D12_RESOURCE_DESC& o ) :
D3D12_RESOURCE_DESC( o )
{}
CD3DX12_RESOURCE_DESC(
D3D12_RESOURCE_DIMENSION dimension,
UINT64 alignment,
UINT64 width,
UINT height,
UINT16 depthOrArraySize,
UINT16 mipLevels,
DXGI_FORMAT format,
UINT sampleCount,
UINT sampleQuality,
D3D12_TEXTURE_LAYOUT layout,
D3D12_RESOURCE_FLAGS flags )
{
Dimension = dimension;
Alignment = alignment;
Width = width;
Height = height;
DepthOrArraySize = depthOrArraySize;
MipLevels = mipLevels;
Format = format;
SampleDesc.Count = sampleCount;
SampleDesc.Quality = sampleQuality;
Layout = layout;
Flags = flags;
}
[[nodiscard]] static inline CD3DX12_RESOURCE_DESC Buffer(
const D3D12_RESOURCE_ALLOCATION_INFO& resAllocInfo,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE )
{
return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, resAllocInfo.Alignment, resAllocInfo.SizeInBytes,
1, 1, 1, DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags );
}
[[nodiscard]] static inline CD3DX12_RESOURCE_DESC Buffer(
UINT64 width,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE,
UINT64 alignment = 0 )
{
return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_BUFFER, alignment, width, 1, 1, 1,
DXGI_FORMAT_UNKNOWN, 1, 0, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags );
}
[[nodiscard]] static inline CD3DX12_RESOURCE_DESC Tex1D(
DXGI_FORMAT format,
UINT64 width,
UINT16 arraySize = 1,
UINT16 mipLevels = 0,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE,
D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
UINT64 alignment = 0 )
{
return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE1D, alignment, width, 1, arraySize,
mipLevels, format, 1, 0, layout, flags );
}
[[nodiscard]] static inline CD3DX12_RESOURCE_DESC Tex2D(
DXGI_FORMAT format,
UINT64 width,
UINT height,
UINT16 arraySize = 1,
UINT16 mipLevels = 0,
UINT sampleCount = 1,
UINT sampleQuality = 0,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE,
D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
UINT64 alignment = 0 )
{
return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE2D, alignment, width, height, arraySize,
mipLevels, format, sampleCount, sampleQuality, layout, flags );
}
[[nodiscard]] static inline CD3DX12_RESOURCE_DESC Tex3D(
DXGI_FORMAT format,
UINT64 width,
UINT height,
UINT16 depth,
UINT16 mipLevels = 0,
D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE,
D3D12_TEXTURE_LAYOUT layout = D3D12_TEXTURE_LAYOUT_UNKNOWN,
UINT64 alignment = 0 )
{
return CD3DX12_RESOURCE_DESC( D3D12_RESOURCE_DIMENSION_TEXTURE3D, alignment, width, height, depth,
mipLevels, format, 1, 0, layout, flags );
}
[[nodiscard]] inline UINT16 Depth() const
{
return (Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u);
}
[[nodiscard]] inline UINT16 ArraySize() const
{
return (Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D ? DepthOrArraySize : 1u);
}
[[nodiscard]] inline UINT8 PlaneCount(_In_ ID3D12Device*) const
{
// TODO(co) Implement me
// return D3D12GetFormatPlaneCount(pDevice, Format);
return 0;
}
[[nodiscard]] inline UINT Subresources(_In_ ID3D12Device* pDevice) const
{
return static_cast<UINT>(MipLevels * ArraySize() * PlaneCount(pDevice));
}
[[nodiscard]] inline UINT CalcSubresource(UINT, UINT, UINT)
{
// TODO(co) Implement me
// return D3D12CalcSubresource(MipSlice, ArraySlice, PlaneSlice, MipLevels, ArraySize());
return 0;
}
[[nodiscard]] operator const D3D12_RESOURCE_DESC&() const
{
return *this;
}
};
[[nodiscard]] inline bool operator==( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r )
{
return l.Dimension == r.Dimension &&
l.Alignment == r.Alignment &&
l.Width == r.Width &&
l.Height == r.Height &&
l.DepthOrArraySize == r.DepthOrArraySize &&
l.MipLevels == r.MipLevels &&
l.Format == r.Format &&
l.SampleDesc.Count == r.SampleDesc.Count &&
l.SampleDesc.Quality == r.SampleDesc.Quality &&
l.Layout == r.Layout &&
l.Flags == r.Flags;
}
[[nodiscard]] inline bool operator!=( const D3D12_RESOURCE_DESC& l, const D3D12_RESOURCE_DESC& r )
{
return !( l == r );
}
//------------------------------------------------------------------------------------------------
struct CD3DX12_RANGE : public D3D12_RANGE
{
CD3DX12_RANGE()
{}
explicit CD3DX12_RANGE(const D3D12_RANGE &o) :
D3D12_RANGE(o)
{}
CD3DX12_RANGE(
SIZE_T begin,
SIZE_T end )
{
Begin = begin;
End = end;
}
[[nodiscard]] operator const D3D12_RANGE&() const
{
return *this;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_DESCRIPTOR_RANGE : public D3D12_DESCRIPTOR_RANGE
{
CD3DX12_DESCRIPTOR_RANGE()
{}
explicit CD3DX12_DESCRIPTOR_RANGE(const D3D12_DESCRIPTOR_RANGE &o) :
D3D12_DESCRIPTOR_RANGE(o)
{}
CD3DX12_DESCRIPTOR_RANGE(
D3D12_DESCRIPTOR_RANGE_TYPE rangeType,
UINT numDescriptors,
UINT baseShaderRegister,
UINT registerSpace = 0,
UINT offsetInDescriptorsFromTableStart =
D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND)
{
Init(rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart);
}
inline void Init(
D3D12_DESCRIPTOR_RANGE_TYPE rangeType,
UINT numDescriptors,
UINT baseShaderRegister,
UINT registerSpace = 0,
UINT offsetInDescriptorsFromTableStart =
D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND)
{
Init(*this, rangeType, numDescriptors, baseShaderRegister, registerSpace, offsetInDescriptorsFromTableStart);
}
static inline void Init(
_Out_ D3D12_DESCRIPTOR_RANGE &range,
D3D12_DESCRIPTOR_RANGE_TYPE rangeType,
UINT numDescriptors,
UINT baseShaderRegister,
UINT registerSpace = 0,
UINT offsetInDescriptorsFromTableStart =
D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND)
{
range.RangeType = rangeType;
range.NumDescriptors = numDescriptors;
range.BaseShaderRegister = baseShaderRegister;
range.RegisterSpace = registerSpace;
range.OffsetInDescriptorsFromTableStart = offsetInDescriptorsFromTableStart;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_ROOT_DESCRIPTOR_TABLE : public D3D12_ROOT_DESCRIPTOR_TABLE
{
CD3DX12_ROOT_DESCRIPTOR_TABLE()
{}
explicit CD3DX12_ROOT_DESCRIPTOR_TABLE(const D3D12_ROOT_DESCRIPTOR_TABLE &o) :
D3D12_ROOT_DESCRIPTOR_TABLE(o)
{}
CD3DX12_ROOT_DESCRIPTOR_TABLE(
UINT numDescriptorRanges,
_In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges)
{
Init(numDescriptorRanges, _pDescriptorRanges);
}
inline void Init(
UINT numDescriptorRanges,
_In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges)
{
Init(*this, numDescriptorRanges, _pDescriptorRanges);
}
static inline void Init(
_Out_ D3D12_ROOT_DESCRIPTOR_TABLE &rootDescriptorTable,
UINT numDescriptorRanges,
_In_reads_opt_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* _pDescriptorRanges)
{
rootDescriptorTable.NumDescriptorRanges = numDescriptorRanges;
rootDescriptorTable.pDescriptorRanges = _pDescriptorRanges;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_ROOT_CONSTANTS : public D3D12_ROOT_CONSTANTS
{
CD3DX12_ROOT_CONSTANTS()
{}
explicit CD3DX12_ROOT_CONSTANTS(const D3D12_ROOT_CONSTANTS &o) :
D3D12_ROOT_CONSTANTS(o)
{}
CD3DX12_ROOT_CONSTANTS(
UINT num32BitValues,
UINT shaderRegister,
UINT registerSpace = 0)
{
Init(num32BitValues, shaderRegister, registerSpace);
}
inline void Init(
UINT num32BitValues,
UINT shaderRegister,
UINT registerSpace = 0)
{
Init(*this, num32BitValues, shaderRegister, registerSpace);
}
static inline void Init(
_Out_ D3D12_ROOT_CONSTANTS &rootConstants,
UINT num32BitValues,
UINT shaderRegister,
UINT registerSpace = 0)
{
rootConstants.Num32BitValues = num32BitValues;
rootConstants.ShaderRegister = shaderRegister;
rootConstants.RegisterSpace = registerSpace;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_ROOT_DESCRIPTOR : public D3D12_ROOT_DESCRIPTOR
{
CD3DX12_ROOT_DESCRIPTOR()
{}
explicit CD3DX12_ROOT_DESCRIPTOR(const D3D12_ROOT_DESCRIPTOR &o) :
D3D12_ROOT_DESCRIPTOR(o)
{}
CD3DX12_ROOT_DESCRIPTOR(
UINT shaderRegister,
UINT registerSpace = 0)
{
Init(shaderRegister, registerSpace);
}
inline void Init(
UINT shaderRegister,
UINT registerSpace = 0)
{
Init(*this, shaderRegister, registerSpace);
}
static inline void Init(_Out_ D3D12_ROOT_DESCRIPTOR &table, UINT shaderRegister, UINT registerSpace = 0)
{
table.ShaderRegister = shaderRegister;
table.RegisterSpace = registerSpace;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_ROOT_PARAMETER : public D3D12_ROOT_PARAMETER
{
CD3DX12_ROOT_PARAMETER() {}
explicit CD3DX12_ROOT_PARAMETER(const D3D12_ROOT_PARAMETER &o) :
D3D12_ROOT_PARAMETER(o)
{}
static inline void InitAsDescriptorTable(
_Out_ D3D12_ROOT_PARAMETER &rootParam,
UINT numDescriptorRanges,
_In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
rootParam.ShaderVisibility = visibility;
CD3DX12_ROOT_DESCRIPTOR_TABLE::Init(rootParam.DescriptorTable, numDescriptorRanges, pDescriptorRanges);
}
static inline void InitAsConstants(
_Out_ D3D12_ROOT_PARAMETER &rootParam,
UINT num32BitValues,
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
rootParam.ShaderVisibility = visibility;
CD3DX12_ROOT_CONSTANTS::Init(rootParam.Constants, num32BitValues, shaderRegister, registerSpace);
}
static inline void InitAsConstantBufferView(
_Out_ D3D12_ROOT_PARAMETER &rootParam,
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
rootParam.ShaderVisibility = visibility;
CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace);
}
static inline void InitAsShaderResourceView(
_Out_ D3D12_ROOT_PARAMETER &rootParam,
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV;
rootParam.ShaderVisibility = visibility;
CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace);
}
static inline void InitAsUnorderedAccessView(
_Out_ D3D12_ROOT_PARAMETER &rootParam,
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
rootParam.ShaderVisibility = visibility;
CD3DX12_ROOT_DESCRIPTOR::Init(rootParam.Descriptor, shaderRegister, registerSpace);
}
inline void InitAsDescriptorTable(
UINT numDescriptorRanges,
_In_reads_(numDescriptorRanges) const D3D12_DESCRIPTOR_RANGE* pDescriptorRanges,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
InitAsDescriptorTable(*this, numDescriptorRanges, pDescriptorRanges, visibility);
}
inline void InitAsConstants(
UINT num32BitValues,
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
InitAsConstants(*this, num32BitValues, shaderRegister, registerSpace, visibility);
}
inline void InitAsConstantBufferView(
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
InitAsConstantBufferView(*this, shaderRegister, registerSpace, visibility);
}
inline void InitAsShaderResourceView(
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
InitAsShaderResourceView(*this, shaderRegister, registerSpace, visibility);
}
inline void InitAsUnorderedAccessView(
UINT shaderRegister,
UINT registerSpace = 0,
D3D12_SHADER_VISIBILITY visibility = D3D12_SHADER_VISIBILITY_ALL)
{
InitAsUnorderedAccessView(*this, shaderRegister, registerSpace, visibility);
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_ROOT_SIGNATURE_DESC : public D3D12_ROOT_SIGNATURE_DESC
{
CD3DX12_ROOT_SIGNATURE_DESC()
{}
explicit CD3DX12_ROOT_SIGNATURE_DESC(const D3D12_ROOT_SIGNATURE_DESC &o) :
D3D12_ROOT_SIGNATURE_DESC(o)
{}
CD3DX12_ROOT_SIGNATURE_DESC(
UINT numParameters,
_In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters,
UINT numStaticSamplers = 0,
_In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL,
D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE)
{
Init(numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags);
}
CD3DX12_ROOT_SIGNATURE_DESC(CD3DX12_DEFAULT)
{
Init(0, NULL, 0, NULL, D3D12_ROOT_SIGNATURE_FLAG_NONE);
}
inline void Init(
UINT numParameters,
_In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters,
UINT numStaticSamplers = 0,
_In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL,
D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE)
{
Init(*this, numParameters, _pParameters, numStaticSamplers, _pStaticSamplers, flags);
}
static inline void Init(
_Out_ D3D12_ROOT_SIGNATURE_DESC &desc,
UINT numParameters,
_In_reads_opt_(numParameters) const D3D12_ROOT_PARAMETER* _pParameters,
UINT numStaticSamplers = 0,
_In_reads_opt_(numStaticSamplers) const D3D12_STATIC_SAMPLER_DESC* _pStaticSamplers = NULL,
D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE)
{
desc.NumParameters = numParameters;
desc.pParameters = _pParameters;
desc.NumStaticSamplers = numStaticSamplers;
desc.pStaticSamplers = _pStaticSamplers;
desc.Flags = flags;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_RASTERIZER_DESC : public D3D12_RASTERIZER_DESC
{
CD3DX12_RASTERIZER_DESC()
{}
explicit CD3DX12_RASTERIZER_DESC( const D3D12_RASTERIZER_DESC& o ) :
D3D12_RASTERIZER_DESC( o )
{}
explicit CD3DX12_RASTERIZER_DESC( CD3DX12_DEFAULT )
{
FillMode = D3D12_FILL_MODE_SOLID;
CullMode = D3D12_CULL_MODE_BACK;
FrontCounterClockwise = FALSE;
DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
DepthClipEnable = TRUE;
MultisampleEnable = FALSE;
AntialiasedLineEnable = FALSE;
ForcedSampleCount = 0;
ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
}
explicit CD3DX12_RASTERIZER_DESC(
D3D12_FILL_MODE fillMode,
D3D12_CULL_MODE cullMode,
BOOL frontCounterClockwise,
INT depthBias,
FLOAT depthBiasClamp,
FLOAT slopeScaledDepthBias,
BOOL depthClipEnable,
BOOL multisampleEnable,
BOOL antialiasedLineEnable,
UINT forcedSampleCount,
D3D12_CONSERVATIVE_RASTERIZATION_MODE conservativeRaster)
{
FillMode = fillMode;
CullMode = cullMode;
FrontCounterClockwise = frontCounterClockwise;
DepthBias = depthBias;
DepthBiasClamp = depthBiasClamp;
SlopeScaledDepthBias = slopeScaledDepthBias;
DepthClipEnable = depthClipEnable;
MultisampleEnable = multisampleEnable;
AntialiasedLineEnable = antialiasedLineEnable;
ForcedSampleCount = forcedSampleCount;
ConservativeRaster = conservativeRaster;
}
~CD3DX12_RASTERIZER_DESC()
{}
[[nodiscard]] operator const D3D12_RASTERIZER_DESC&() const
{
return *this;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_BLEND_DESC : public D3D12_BLEND_DESC
{
CD3DX12_BLEND_DESC()
{}
explicit CD3DX12_BLEND_DESC( const D3D12_BLEND_DESC& o ) :
D3D12_BLEND_DESC( o )
{}
explicit CD3DX12_BLEND_DESC( CD3DX12_DEFAULT )
{
AlphaToCoverageEnable = FALSE;
IndependentBlendEnable = FALSE;
const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc =
{
FALSE,FALSE,
D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
D3D12_LOGIC_OP_NOOP,
D3D12_COLOR_WRITE_ENABLE_ALL,
};
for (UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
RenderTarget[ i ] = defaultRenderTargetBlendDesc;
}
~CD3DX12_BLEND_DESC()
{}
[[nodiscard]] operator const D3D12_BLEND_DESC&() const
{
return *this;
}
};
//------------------------------------------------------------------------------------------------
struct CD3DX12_BOX : public D3D12_BOX
{
CD3DX12_BOX()
{}
explicit CD3DX12_BOX( const D3D12_BOX& o ) :
D3D12_BOX( o )
{}
explicit CD3DX12_BOX(
UINT Left,
UINT Right )
{
left = Left;
top = 0;
front = 0;
right = Right;
bottom = 1;
back = 1;
}
explicit CD3DX12_BOX(
UINT Left,
UINT Top,
UINT Right,
UINT Bottom )
{
left = Left;
top = Top;
front = 0;
right = Right;
bottom = Bottom;
back = 1;
}
explicit CD3DX12_BOX(
UINT Left,
UINT Top,
UINT Front,
UINT Right,
UINT Bottom,
UINT Back )
{
left = Left;
top = Top;
front = Front;
right = Right;
bottom = Bottom;
back = Back;
}
~CD3DX12_BOX() {}
[[nodiscard]] operator const D3D12_BOX&() const
{
return *this;
}
};
[[nodiscard]] inline bool operator==( const D3D12_BOX& l, const D3D12_BOX& r )
{
return l.left == r.left && l.top == r.top && l.front == r.front &&
l.right == r.right && l.bottom == r.bottom && l.back == r.back;
}
[[nodiscard]] inline bool operator!=( const D3D12_BOX& l, const D3D12_BOX& r )
{ return !( l == r ); }
//------------------------------------------------------------------------------------------------
struct CD3DX12_TEXTURE_COPY_LOCATION : public D3D12_TEXTURE_COPY_LOCATION
{
CD3DX12_TEXTURE_COPY_LOCATION()
{}
explicit CD3DX12_TEXTURE_COPY_LOCATION(const D3D12_TEXTURE_COPY_LOCATION &o) :
D3D12_TEXTURE_COPY_LOCATION(o)
{}
CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes)
{
pResource = pRes;
}
CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, D3D12_PLACED_SUBRESOURCE_FOOTPRINT const& Footprint)
{
pResource = pRes;
Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
PlacedFootprint = Footprint;
}
CD3DX12_TEXTURE_COPY_LOCATION(ID3D12Resource* pRes, UINT Sub)
{
pResource = pRes;
Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
SubresourceIndex = Sub;
}
};
//------------------------------------------------------------------------------------------------
// Returns required size of a buffer to be used for data upload
[[nodiscard]] inline UINT64 GetRequiredIntermediateSize(
_In_ ID3D12Resource* pDestinationResource,
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources)
{
D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc();
UINT64 RequiredSize = 0;
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, 0, nullptr, nullptr, nullptr, &RequiredSize);
pDevice->Release();
return RequiredSize;
}
//------------------------------------------------------------------------------------------------
// Row-by-row memcpy
inline void MemcpySubresource(
_In_ const D3D12_MEMCPY_DEST* pDest,
_In_ const D3D12_SUBRESOURCE_DATA* pSrc,
SIZE_T RowSizeInBytes,
UINT NumRows,
UINT NumSlices)
{
for (UINT z = 0; z < NumSlices; ++z)
{
BYTE* pDestSlice = reinterpret_cast<BYTE*>(pDest->pData) + pDest->SlicePitch * z;
const BYTE* pSrcSlice = reinterpret_cast<const BYTE*>(pSrc->pData) + pSrc->SlicePitch * z;
for (UINT y = 0; y < NumRows; ++y)
{
memcpy(pDestSlice + pDest->RowPitch * y,
pSrcSlice + pSrc->RowPitch * y,
RowSizeInBytes);
}
}
}
//------------------------------------------------------------------------------------------------
// All arrays must be populated (e.g. by calling GetCopyableFootprints)
[[nodiscard]] inline UINT64 UpdateSubresources(
_In_ ID3D12GraphicsCommandList* pCmdList,
_In_ ID3D12Resource* pDestinationResource,
_In_ ID3D12Resource* pIntermediate,
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,
UINT64 RequiredSize,
_In_reads_(NumSubresources) const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts,
_In_reads_(NumSubresources) const UINT* pNumRows,
_In_reads_(NumSubresources) const UINT64* pRowSizesInBytes,
_In_reads_(NumSubresources) const D3D12_SUBRESOURCE_DATA* pSrcData)
{
// Minor validation
D3D12_RESOURCE_DESC IntermediateDesc = pIntermediate->GetDesc();
D3D12_RESOURCE_DESC DestinationDesc = pDestinationResource->GetDesc();
if (IntermediateDesc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER ||
IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
RequiredSize > (SIZE_T)-1 ||
(DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER &&
(FirstSubresource != 0 || NumSubresources != 1)))
{
return 0;
}
BYTE* pData;
HRESULT hr = pIntermediate->Map(0, NULL, reinterpret_cast<void**>(&pData));
if (FAILED(hr))
{
return 0;
}
for (UINT i = 0; i < NumSubresources; ++i)
{
if (pRowSizesInBytes[i] > (SIZE_T)-1) return 0;
D3D12_MEMCPY_DEST DestData = { pData + pLayouts[i].Offset, pLayouts[i].Footprint.RowPitch, pLayouts[i].Footprint.RowPitch * pNumRows[i] };
MemcpySubresource(&DestData, &pSrcData[i], (SIZE_T)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth);
}
pIntermediate->Unmap(0, NULL);
if (DestinationDesc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER)
{
CD3DX12_BOX SrcBox( UINT( pLayouts[0].Offset ), UINT( pLayouts[0].Offset + pLayouts[0].Footprint.Width ) );
pCmdList->CopyBufferRegion(
pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, pLayouts[0].Footprint.Width);
}
else
{
for (UINT i = 0; i < NumSubresources; ++i)
{
CD3DX12_TEXTURE_COPY_LOCATION Dst(pDestinationResource, i + FirstSubresource);
CD3DX12_TEXTURE_COPY_LOCATION Src(pIntermediate, pLayouts[i]);
pCmdList->CopyTextureRegion(&Dst, 0, 0, 0, &Src, nullptr);
}
}
return RequiredSize;
}
//------------------------------------------------------------------------------------------------
// Heap-allocating UpdateSubresources implementation
[[nodiscard]] inline UINT64 UpdateSubresources(
_In_ ID3D12GraphicsCommandList* pCmdList,
_In_ ID3D12Resource* pDestinationResource,
_In_ ID3D12Resource* pIntermediate,
UINT64 IntermediateOffset,
_In_range_(0,D3D12_REQ_SUBRESOURCES) UINT FirstSubresource,
_In_range_(0,D3D12_REQ_SUBRESOURCES-FirstSubresource) UINT NumSubresources,
_In_reads_(NumSubresources) D3D12_SUBRESOURCE_DATA* pSrcData)
{
UINT64 RequiredSize = 0;
UINT64 MemToAlloc = static_cast<UINT64>(sizeof(D3D12_PLACED_SUBRESOURCE_FOOTPRINT) + sizeof(UINT) + sizeof(UINT64)) * NumSubresources;
if (MemToAlloc > SIZE_MAX)
{
return 0;
}
void* pMem = HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(MemToAlloc));
if (pMem == NULL)
{
return 0;
}
D3D12_PLACED_SUBRESOURCE_FOOTPRINT* pLayouts = reinterpret_cast<D3D12_PLACED_SUBRESOURCE_FOOTPRINT*>(pMem);
UINT64* pRowSizesInBytes = reinterpret_cast<UINT64*>(pLayouts + NumSubresources);
UINT* pNumRows = reinterpret_cast<UINT*>(pRowSizesInBytes + NumSubresources);
D3D12_RESOURCE_DESC Desc = pDestinationResource->GetDesc();
ID3D12Device* pDevice = nullptr;
pDestinationResource->GetDevice(__uuidof(*pDevice), reinterpret_cast<void**>(&pDevice));
pDevice->GetCopyableFootprints(&Desc, FirstSubresource, NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, &RequiredSize);
pDevice->Release();
UINT64 Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData);
HeapFree(GetProcessHeap(), 0, pMem);
return Result;
}
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Direct3D12Rhi
{
class VertexArray;
class RootSignature;
class Direct3D12RuntimeLinking;
}
//[-------------------------------------------------------]
//[ Macros & definitions ]
//[-------------------------------------------------------]
#ifdef RHI_DEBUG
/*
* @brief
* Check whether or not the given resource is owned by the given RHI
*/
#define RHI_MATCH_CHECK(rhiReference, resourceReference) \
RHI_ASSERT(mContext, &rhiReference == &(resourceReference).getRhi(), "Direct3D 12 error: The given resource is owned by another RHI instance")
/*
* @brief
* Debug break on execution failure
*/
#define FAILED_DEBUG_BREAK(toExecute) if (FAILED(toExecute)) { DEBUG_BREAK; }
#else
/*
* @brief
* Check whether or not the given resource is owned by the given RHI
*/
#define RHI_MATCH_CHECK(rhiReference, resourceReference)
/*
* @brief
* Debug break on execution failure
*/
#define FAILED_DEBUG_BREAK(toExecute) toExecute;
#endif
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
namespace
{
namespace detail
{
//[-------------------------------------------------------]
//[ Global definitions ]
//[-------------------------------------------------------]
static constexpr const char* HLSL_NAME = "HLSL"; ///< ASCII name of this shader language, always valid (do not free the memory the returned pointer is pointing to)
static constexpr const uint32_t NUMBER_OF_BUFFERED_FRAMES = 2;
//[-------------------------------------------------------]
//[ Global functions ]
//[-------------------------------------------------------]
template <typename T0, typename T1>
inline T0 align(const T0 x, const T1 a)
{
return (x + (a-1)) & (T0)(~(a-1));
}
inline void updateWidthHeight(uint32_t mipmapIndex, uint32_t textureWidth, uint32_t textureHeight, uint32_t& width, uint32_t& height)
{
Rhi::ITexture::getMipmapSize(mipmapIndex, textureWidth, textureHeight);
if (width > textureWidth)
{
width = textureWidth;
}
if (height > textureHeight)
{
height = textureHeight;
}
}
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
class UploadCommandListAllocator final
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
inline UploadCommandListAllocator() :
mD3D12Device(nullptr),
mD3D12CommandAllocator(nullptr),
mD3D12GraphicsCommandList(nullptr),
mD3D12ResourceUploadBuffer(nullptr),
mD3D12GpuVirtualAddress{},
mData(nullptr),
mOffset(0),
mNumberOfUploadBufferBytes(0)
{}
inline ID3D12GraphicsCommandList* getD3D12GraphicsCommandList() const
{
return mD3D12GraphicsCommandList;
}
inline ID3D12Resource* getD3D12ResourceUploadBuffer() const
{
return mD3D12ResourceUploadBuffer;
}
inline uint8_t* getData() const
{
return mData;
}
void create(ID3D12Device& d3d12Device)
{
mD3D12Device = &d3d12Device;
[[maybe_unused]] HRESULT result = d3d12Device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&mD3D12CommandAllocator));
ASSERT(SUCCEEDED(result), "Direct3D 12 create command allocator failed")
// Create the command list
result = d3d12Device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, mD3D12CommandAllocator, nullptr, IID_PPV_ARGS(&mD3D12GraphicsCommandList));
ASSERT(SUCCEEDED(result), "Direct3D 12 create command list failed")
// Command lists are created in the recording state, but there is nothing to record yet. The main loop expects it to be closed, so close it now.
result = mD3D12GraphicsCommandList->Close();
ASSERT(SUCCEEDED(result), "Direct3D 12 close command list failed")
}
void destroy()
{
if (nullptr != mD3D12GraphicsCommandList)
{
mD3D12GraphicsCommandList->Release();
}
if (nullptr != mD3D12CommandAllocator)
{
mD3D12CommandAllocator->Release();
}
if (nullptr != mD3D12ResourceUploadBuffer)
{
mD3D12ResourceUploadBuffer->Release();
}
}
void begin(uint32_t numberOfUploadBufferBytes)
{
ASSERT(nullptr != mD3D12Device, "Invalid Direct3D 12 device")
mD3D12CommandAllocator->Reset();
mD3D12GraphicsCommandList->Reset(mD3D12CommandAllocator, nullptr);
if (numberOfUploadBufferBytes != mNumberOfUploadBufferBytes)
{
mNumberOfUploadBufferBytes = numberOfUploadBufferBytes;
if (nullptr != mD3D12ResourceUploadBuffer)
{
mD3D12ResourceUploadBuffer->Release();
}
mD3D12ResourceUploadBuffer = createBuffer(*mD3D12Device, D3D12_HEAP_TYPE_UPLOAD, numberOfUploadBufferBytes);
}
mOffset = 0;
mData = nullptr;
}
void end()
{
if (nullptr != mData)
{
const D3D12_RANGE d3d12Range = { 0, mOffset };
mD3D12ResourceUploadBuffer->Unmap(0, &d3d12Range);
}
[[maybe_unused]] HRESULT result = mD3D12GraphicsCommandList->Close();
ASSERT(SUCCEEDED(result), "Direct3D 12 close command list failed")
}
uint32_t allocateUploadBuffer(uint32_t size, uint32_t alignment)
{
const uint32_t alignedOffset = align(mOffset, alignment);
if (alignedOffset + size > mNumberOfUploadBufferBytes)
{
// TODO(co) Reallocate
ASSERT(false, "Direct3D 12 allocate upload buffer failed")
}
if (nullptr == mData)
{
mD3D12GpuVirtualAddress = mD3D12ResourceUploadBuffer->GetGPUVirtualAddress();
const D3D12_RANGE d3d12Range = { 0, 0 };
[[maybe_unused]] HRESULT result = mD3D12ResourceUploadBuffer->Map(0, &d3d12Range, reinterpret_cast<void**>(&mData));
ASSERT(SUCCEEDED(result), "Direct3D 12 map buffer failed")
}
mOffset = alignedOffset + size;
return alignedOffset;
}
//[-------------------------------------------------------]
//[ Private static methods ]
//[-------------------------------------------------------]
private:
static ID3D12Resource* createBuffer(ID3D12Device& d3d12Device, D3D12_HEAP_TYPE d3dHeapType, size_t numberOfBytes)
{
D3D12_HEAP_PROPERTIES d3d12HeapProperties = {};
d3d12HeapProperties.Type = d3dHeapType;
D3D12_RESOURCE_DESC d3d12ResourceDesc = {};
d3d12ResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d3d12ResourceDesc.Width = numberOfBytes;
d3d12ResourceDesc.Height = 1;
d3d12ResourceDesc.DepthOrArraySize = 1;
d3d12ResourceDesc.MipLevels = 1;
d3d12ResourceDesc.SampleDesc.Count = 1;
d3d12ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* d3d12Resource = nullptr;
const D3D12_RESOURCE_STATES d3d12ResourceStates = (d3dHeapType == D3D12_HEAP_TYPE_READBACK) ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_GENERIC_READ;
[[maybe_unused]] HRESULT result = d3d12Device.CreateCommittedResource(&d3d12HeapProperties, D3D12_HEAP_FLAG_NONE, &d3d12ResourceDesc, d3d12ResourceStates, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&d3d12Resource));
ASSERT(SUCCEEDED(result), "Direct3D 12 create committed resource failed")
return d3d12Resource;
}
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3D12Device* mD3D12Device;
ID3D12CommandAllocator* mD3D12CommandAllocator;
ID3D12GraphicsCommandList* mD3D12GraphicsCommandList;
ID3D12Resource* mD3D12ResourceUploadBuffer;
D3D12_GPU_VIRTUAL_ADDRESS mD3D12GpuVirtualAddress;
uint8_t* mData;
uint32_t mOffset;
uint32_t mNumberOfUploadBufferBytes;
};
struct UploadContext final
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
inline UploadContext() :
mCurrentFrameIndex(0),
mCurrentUploadCommandListAllocator(nullptr),
mCurrentD3d12GraphicsCommandList(nullptr)
{}
inline void create(ID3D12Device& d3d12Device)
{
for (uint32_t i = 0; i < NUMBER_OF_BUFFERED_FRAMES; ++i)
{
mUploadCommandListAllocator[i].create(d3d12Device);
}
begin();
}
inline void destroy()
{
for (uint32_t i = 0; i < NUMBER_OF_BUFFERED_FRAMES; ++i)
{
mUploadCommandListAllocator[i].destroy();
}
}
inline UploadCommandListAllocator* getUploadCommandListAllocator() const
{
return mCurrentUploadCommandListAllocator;
}
inline ID3D12GraphicsCommandList* getD3d12GraphicsCommandList() const
{
return mCurrentD3d12GraphicsCommandList;
}
void begin()
{
// End previous upload command list allocator
if (nullptr != mCurrentUploadCommandListAllocator)
{
mCurrentUploadCommandListAllocator->end();
mCurrentFrameIndex = (mCurrentFrameIndex + 1) % NUMBER_OF_BUFFERED_FRAMES;
}
// Begin new upload command list allocator
const uint32_t numberOfUploadBufferBytes = 1024 * 1024 * 1024; // TODO(co) This must be a decent size with emergency reallocation if really necessary
mCurrentUploadCommandListAllocator = &mUploadCommandListAllocator[mCurrentFrameIndex];
mCurrentD3d12GraphicsCommandList = mCurrentUploadCommandListAllocator->getD3D12GraphicsCommandList();
mCurrentUploadCommandListAllocator->begin(numberOfUploadBufferBytes);
}
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
UploadCommandListAllocator mUploadCommandListAllocator[NUMBER_OF_BUFFERED_FRAMES];
// Current
uint32_t mCurrentFrameIndex;
::detail::UploadCommandListAllocator* mCurrentUploadCommandListAllocator;
ID3D12GraphicsCommandList* mCurrentD3d12GraphicsCommandList;
};
/*
* @brief
* Descriptor heap
*/
class DescriptorHeap final
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
inline DescriptorHeap(Rhi::IAllocator& allocator, ID3D12Device& d3d12Device, D3D12_DESCRIPTOR_HEAP_TYPE d3d12DescriptorHeapType, uint16_t size, bool shaderVisible) :
mD3D12DescriptorHeap(nullptr),
mD3D12CpuDescriptorHandleForHeapStart{},
mD3D12GpuDescriptorHandleForHeapStart{},
mDescriptorSize(0),
mMakeIDAllocator(allocator, size - 1u)
{
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeadDescription = {};
d3d12DescriptorHeadDescription.Type = d3d12DescriptorHeapType;
d3d12DescriptorHeadDescription.NumDescriptors = size;
d3d12DescriptorHeadDescription.Flags = shaderVisible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeadDescription, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&mD3D12DescriptorHeap));
mD3D12CpuDescriptorHandleForHeapStart = mD3D12DescriptorHeap->GetCPUDescriptorHandleForHeapStart();
mD3D12GpuDescriptorHandleForHeapStart = mD3D12DescriptorHeap->GetGPUDescriptorHandleForHeapStart();
mDescriptorSize = d3d12Device.GetDescriptorHandleIncrementSize(d3d12DescriptorHeapType);
}
inline ~DescriptorHeap()
{
mD3D12DescriptorHeap->Release();
}
inline uint16_t allocate(uint16_t count)
{
uint16_t index = 0;
[[maybe_unused]] const bool result = mMakeIDAllocator.CreateRangeID(index, count);
ASSERT(result, "Direct3D 12 create range ID failed")
return index;
}
inline void release(uint16_t offset, uint16_t count)
{
[[maybe_unused]] const bool result = mMakeIDAllocator.DestroyRangeID(offset, count);
ASSERT(result, "Direct3D 12 destroy range ID failed")
}
inline ID3D12DescriptorHeap* getD3D12DescriptorHeap() const
{
return mD3D12DescriptorHeap;
}
inline D3D12_CPU_DESCRIPTOR_HANDLE getD3D12CpuDescriptorHandleForHeapStart() const
{
return mD3D12CpuDescriptorHandleForHeapStart;
}
inline D3D12_CPU_DESCRIPTOR_HANDLE getOffsetD3D12CpuDescriptorHandleForHeapStart(uint16_t offset) const
{
D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle = mD3D12CpuDescriptorHandleForHeapStart;
d3d12CpuDescriptorHandle.ptr += offset * mDescriptorSize;
return d3d12CpuDescriptorHandle;
}
inline D3D12_GPU_DESCRIPTOR_HANDLE getD3D12GpuDescriptorHandleForHeapStart() const
{
return mD3D12GpuDescriptorHandleForHeapStart;
}
inline uint32_t getDescriptorSize() const
{
return mDescriptorSize;
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit DescriptorHeap(const DescriptorHeap& source) = delete;
DescriptorHeap& operator =(const DescriptorHeap& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3D12DescriptorHeap* mD3D12DescriptorHeap;
D3D12_CPU_DESCRIPTOR_HANDLE mD3D12CpuDescriptorHandleForHeapStart;
D3D12_GPU_DESCRIPTOR_HANDLE mD3D12GpuDescriptorHandleForHeapStart;
uint32_t mDescriptorSize;
MakeID mMakeIDAllocator;
};
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
} // detail
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Direct3D12Rhi
{
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Direct3D12Rhi.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 RHI class
*/
class Direct3D12Rhi final : public Rhi::IRhi
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
public:
static constexpr uint32_t NUMBER_OF_FRAMES = 2;
//[-------------------------------------------------------]
//[ Public data ]
//[-------------------------------------------------------]
public:
MakeID VertexArrayMakeId;
MakeID GraphicsPipelineStateMakeId;
MakeID ComputePipelineStateMakeId;
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] context
* RHI context, the RHI context instance must stay valid as long as the RHI instance exists
*
* @note
* - Do never ever use a not properly initialized RHI. Use "Rhi::IRhi::isInitialized()" to check the initialization state.
*/
explicit Direct3D12Rhi(const Rhi::Context& context);
/**
* @brief
* Destructor
*/
virtual ~Direct3D12Rhi() override;
/**
* @brief
* Return the DXGI factory instance
*
* @return
* The DXGI factory instance, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline IDXGIFactory4& getDxgiFactory4() const
{
RHI_ASSERT(mContext, nullptr != mDxgiFactory4, "Invalid Direct3D 12 DXGI factory 4")
return *mDxgiFactory4;
}
/**
* @brief
* Return the Direct3D 12 device
*
* @return
* The Direct3D 12 device, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Device& getD3D12Device() const
{
RHI_ASSERT(mContext, nullptr != mD3D12Device, "Invalid Direct3D 12 device")
return *mD3D12Device;
}
/**
* @brief
* Return the Direct3D 12 command queue
*
* @return
* The Direct3D 12 command queue, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12CommandQueue* getD3D12CommandQueue() const
{
return mD3D12CommandQueue;
}
/**
* @brief
* Return the Direct3D 12 graphics command list
*
* @return
* The Direct3D 12 graphics command list, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12GraphicsCommandList* getD3D12GraphicsCommandList() const
{
return mD3D12GraphicsCommandList;
}
/**
* @brief
* Get the render target to render into
*
* @return
* Render target currently bound to the output-merger state, a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline Rhi::IRenderTarget* omGetRenderTarget() const
{
return mRenderTarget;
}
/**
* @brief
* Get the upload context
*
* @return
* Upload context
*/
[[nodiscard]] inline ::detail::UploadContext& getUploadContext()
{
return mUploadContext;
}
//[-------------------------------------------------------]
//[ Descriptor heaps ]
//[-------------------------------------------------------]
[[nodiscard]] inline ::detail::DescriptorHeap& getShaderResourceViewDescriptorHeap() const
{
RHI_ASSERT(mContext, nullptr != mShaderResourceViewDescriptorHeap, "Invalid Direct3D 12 shader resource view descriptor heap")
return *mShaderResourceViewDescriptorHeap;
}
[[nodiscard]] inline ::detail::DescriptorHeap& getRenderTargetViewDescriptorHeap() const
{
RHI_ASSERT(mContext, nullptr != mShaderResourceViewDescriptorHeap, "Invalid Direct3D 12 render target view descriptor heap")
return *mRenderTargetViewDescriptorHeap;
}
[[nodiscard]] inline ::detail::DescriptorHeap& getDepthStencilViewDescriptorHeap() const
{
RHI_ASSERT(mContext, nullptr != mShaderResourceViewDescriptorHeap, "Invalid Direct3D 12 depth stencil target view descriptor heap")
return *mDepthStencilViewDescriptorHeap;
}
[[nodiscard]] inline ::detail::DescriptorHeap& getSamplerDescriptorHeap() const
{
RHI_ASSERT(mContext, nullptr != mSamplerDescriptorHeap, "Invalid Direct3D 12 sampler descriptor heap")
return *mSamplerDescriptorHeap;
}
void dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer);
//[-------------------------------------------------------]
//[ Graphics ]
//[-------------------------------------------------------]
void setGraphicsRootSignature(Rhi::IRootSignature* rootSignature);
void setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState);
void setGraphicsResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup);
void setGraphicsVertexArray(Rhi::IVertexArray* vertexArray); // Input-assembler (IA) stage
void setGraphicsViewports(uint32_t numberOfViewports, const Rhi::Viewport* viewports); // Rasterizer (RS) stage
void setGraphicsScissorRectangles(uint32_t numberOfScissorRectangles, const Rhi::ScissorRectangle* scissorRectangles); // Rasterizer (RS) stage
void setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget); // Output-merger (OM) stage
void clearGraphics(uint32_t clearFlags, const float color[4], float z, uint32_t stencil);
void drawGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
void drawGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
void drawIndexedGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
void drawIndexedGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
void drawMeshTasks(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
void drawMeshTasksEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset = 0, uint32_t numberOfDraws = 1);
//[-------------------------------------------------------]
//[ Compute ]
//[-------------------------------------------------------]
void setComputeRootSignature(Rhi::IRootSignature* rootSignature);
void setComputePipelineState(Rhi::IComputePipelineState* computePipelineState);
void setComputeResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup);
void dispatchCompute(uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ);
//[-------------------------------------------------------]
//[ Resource ]
//[-------------------------------------------------------]
void resolveMultisampleFramebuffer(Rhi::IRenderTarget& destinationRenderTarget, Rhi::IFramebuffer& sourceMultisampleFramebuffer);
void copyResource(Rhi::IResource& destinationResource, Rhi::IResource& sourceResource);
void generateMipmaps(Rhi::IResource& resource);
//[-------------------------------------------------------]
//[ Query ]
//[-------------------------------------------------------]
void resetQueryPool(Rhi::IQueryPool& queryPool, uint32_t firstQueryIndex, uint32_t numberOfQueries);
void beginQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex, uint32_t queryControlFlags);
void endQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex);
void writeTimestampQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex);
//[-------------------------------------------------------]
//[ Debug ]
//[-------------------------------------------------------]
#ifdef RHI_DEBUG
void setDebugMarker(const char* name);
void beginDebugEvent(const char* name);
void endDebugEvent();
#endif
//[-------------------------------------------------------]
//[ Public virtual Rhi::IRhi methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getName() const override
{
return "Direct3D12";
}
[[nodiscard]] inline virtual bool isInitialized() const override
{
// Is there a Direct3D 12 command queue?
return (nullptr != mD3D12CommandQueue);
}
[[nodiscard]] virtual bool isDebugEnabled() override;
//[-------------------------------------------------------]
//[ Shader language ]
//[-------------------------------------------------------]
[[nodiscard]] virtual uint32_t getNumberOfShaderLanguages() const override;
[[nodiscard]] virtual const char* getShaderLanguageName(uint32_t index) const override;
[[nodiscard]] virtual Rhi::IShaderLanguage* getShaderLanguage(const char* shaderLanguageName = nullptr) override;
//[-------------------------------------------------------]
//[ Resource creation ]
//[-------------------------------------------------------]
[[nodiscard]] virtual Rhi::IRenderPass* createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat = Rhi::TextureFormat::UNKNOWN, uint8_t numberOfMultisamples = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::IQueryPool* createQueryPool(Rhi::QueryType queryType, uint32_t numberOfQueries = 1 RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::ISwapChain* createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool useExternalContext = false RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::IFramebuffer* createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::IBufferManager* createBufferManager() override;
[[nodiscard]] virtual Rhi::ITextureManager* createTextureManager() override;
[[nodiscard]] virtual Rhi::IRootSignature* createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::IGraphicsPipelineState* createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::IComputePipelineState* createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
[[nodiscard]] virtual Rhi::ISamplerState* createSamplerState(const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
//[-------------------------------------------------------]
//[ Resource handling ]
//[-------------------------------------------------------]
[[nodiscard]] virtual bool map(Rhi::IResource& resource, uint32_t subresource, Rhi::MapType mapType, uint32_t mapFlags, Rhi::MappedSubresource& mappedSubresource) override;
virtual void unmap(Rhi::IResource& resource, uint32_t subresource) override;
[[nodiscard]] virtual bool getQueryPoolResults(Rhi::IQueryPool& queryPool, uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex = 0, uint32_t numberOfQueries = 1, uint32_t strideInBytes = 0, uint32_t queryResultFlags = 0) override;
//[-------------------------------------------------------]
//[ Operation ]
//[-------------------------------------------------------]
virtual void dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer) override;
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(mContext, Direct3D12Rhi, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Direct3D12Rhi(const Direct3D12Rhi& source) = delete;
Direct3D12Rhi& operator =(const Direct3D12Rhi& source) = delete;
/**
* @brief
* Initialize the capabilities
*/
void initializeCapabilities();
/**
* @brief
* Unset the currently used vertex array
*/
void unsetGraphicsVertexArray();
#ifdef RHI_DEBUG
/**
* @brief
* Reports information about a device object's lifetime for debugging
*/
void debugReportLiveDeviceObjects();
#endif
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Direct3D12RuntimeLinking* mDirect3D12RuntimeLinking; ///< Direct3D 12 runtime linking instance, always valid
IDXGIFactory4* mDxgiFactory4; ///< DXGI factors instance, always valid for a correctly initialized RHI
ID3D12Device* mD3D12Device; ///< The Direct3D 12 device, null pointer on error (we don't check because this would be a total overhead, the user has to use "Rhi::IRhi::isInitialized()" and is asked to never ever use a not properly initialized RHI)
ID3D12CommandQueue* mD3D12CommandQueue; ///< The Direct3D 12 command queue, null pointer on error (we don't check because this would be a total overhead, the user has to use "Rhi::IRhi::isInitialized()" and is asked to never ever use a not properly initialized RHI)
ID3D12CommandAllocator* mD3D12CommandAllocator;
ID3D12GraphicsCommandList* mD3D12GraphicsCommandList;
Rhi::IShaderLanguage* mShaderLanguageHlsl; ///< HLSL shader language instance (we keep a reference to it), can be a null pointer
::detail::UploadContext mUploadContext;
::detail::DescriptorHeap* mShaderResourceViewDescriptorHeap;
::detail::DescriptorHeap* mRenderTargetViewDescriptorHeap;
::detail::DescriptorHeap* mDepthStencilViewDescriptorHeap;
::detail::DescriptorHeap* mSamplerDescriptorHeap;
//[-------------------------------------------------------]
//[ State related ]
//[-------------------------------------------------------]
Rhi::IRenderTarget* mRenderTarget; ///< Output-merger (OM) stage: Currently set render target (we keep a reference to it), can be a null pointer
D3D12_PRIMITIVE_TOPOLOGY mD3D12PrimitiveTopology; ///< State cache to avoid making redundant Direct3D 12 calls
RootSignature* mGraphicsRootSignature; ///< Currently set graphics root signature (we keep a reference to it), can be a null pointer
RootSignature* mComputeRootSignature; ///< Currently set compute root signature (we keep a reference to it), can be a null pointer
VertexArray* mVertexArray; ///< Currently set vertex array (we keep a reference to it), can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Direct3D12RuntimeLinking.h ]
//[-------------------------------------------------------]
//[-------------------------------------------------------]
//[ Macros & definitions ]
//[-------------------------------------------------------]
// Redirect D3D12* function calls to funcPtr_D3D12*
#ifndef FNPTR
#define FNPTR(name) funcPtr_##name
#endif
//[-------------------------------------------------------]
//[ DXGI core functions ]
//[-------------------------------------------------------]
#define FNDEF_DXGI(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args
FNDEF_DXGI(HRESULT, CreateDXGIFactory1, (REFIID riid, _COM_Outptr_ void **ppFactory));
#define CreateDXGIFactory1 FNPTR(CreateDXGIFactory1)
//[-------------------------------------------------------]
//[ D3D12 core functions ]
//[-------------------------------------------------------]
#define FNDEF_D3D12(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args
FNDEF_D3D12(HRESULT, D3D12CreateDevice, (_In_opt_ IUnknown* pAdapter, D3D_FEATURE_LEVEL MinimumFeatureLevel, _In_ REFIID riid, _COM_Outptr_opt_ void** ppDevice));
FNDEF_D3D12(HRESULT, D3D12SerializeRootSignature, (_In_ const D3D12_ROOT_SIGNATURE_DESC* pRootSignature, _In_ D3D_ROOT_SIGNATURE_VERSION Version, _Out_ ID3DBlob** ppBlob, _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorBlob));
#define D3D12CreateDevice FNPTR(D3D12CreateDevice)
#define D3D12SerializeRootSignature FNPTR(D3D12SerializeRootSignature)
#ifdef RHI_DEBUG
FNDEF_D3D12(HRESULT, D3D12GetDebugInterface, (_In_ REFIID riid, _COM_Outptr_opt_ void** ppvDebug));
#define D3D12GetDebugInterface FNPTR(D3D12GetDebugInterface)
#endif
//[-------------------------------------------------------]
//[ D3DCompiler functions ]
//[-------------------------------------------------------]
#define FNDEF_D3DX12(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args
typedef __interface ID3D10Blob *LPD3D10BLOB; // "__interface" is no keyword of the ISO C++ standard, shouldn't be a problem because this in here is Microsoft Windows only and it's also within the Direct3D headers we have to use
typedef ID3D10Blob ID3DBlob;
FNDEF_D3DX12(HRESULT, D3DCompile, (LPCVOID, SIZE_T, LPCSTR, CONST D3D_SHADER_MACRO*, ID3DInclude*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**, ID3DBlob**));
FNDEF_D3DX12(HRESULT, D3DCreateBlob, (SIZE_T Size, ID3DBlob** ppBlob));
#define D3DCompile FNPTR(D3DCompile)
#define D3DCreateBlob FNPTR(D3DCreateBlob)
/**
* @brief
* Direct3D 12 runtime linking
*/
class Direct3D12RuntimeLinking final
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
*/
inline explicit Direct3D12RuntimeLinking(Direct3D12Rhi& direct3D12Rhi) :
mDirect3D12Rhi(direct3D12Rhi),
mDxgiSharedLibrary(nullptr),
mD3D12SharedLibrary(nullptr),
mD3DCompilerSharedLibrary(nullptr),
mEntryPointsRegistered(false),
mInitialized(false)
{}
/**
* @brief
* Destructor
*/
~Direct3D12RuntimeLinking()
{
// Destroy the shared library instances
if (nullptr != mDxgiSharedLibrary)
{
::FreeLibrary(static_cast<HMODULE>(mDxgiSharedLibrary));
}
if (nullptr != mD3D12SharedLibrary)
{
::FreeLibrary(static_cast<HMODULE>(mD3D12SharedLibrary));
}
if (nullptr != mD3DCompilerSharedLibrary)
{
::FreeLibrary(static_cast<HMODULE>(mD3DCompilerSharedLibrary));
}
}
/**
* @brief
* Return whether or not Direct3D 12 is available
*
* @return
* "true" if Direct3D 12 is available, else "false"
*/
[[nodiscard]] bool isDirect3D12Avaiable()
{
// Already initialized?
if (!mInitialized)
{
// We're now initialized
mInitialized = true;
// Load the shared libraries
if (loadSharedLibraries())
{
// Load the DXGI, D3D12 and D3DCompiler entry points
mEntryPointsRegistered = (loadDxgiEntryPoints() && loadD3D12EntryPoints() && loadD3DCompilerEntryPoints());
}
}
// Entry points successfully registered?
return mEntryPointsRegistered;
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Direct3D12RuntimeLinking(const Direct3D12RuntimeLinking& source) = delete;
Direct3D12RuntimeLinking& operator =(const Direct3D12RuntimeLinking& source) = delete;
/**
* @brief
* Load the shared libraries
*
* @return
* "true" if all went fine, else "false"
*/
[[nodiscard]] bool loadSharedLibraries()
{
// Load the shared library
mDxgiSharedLibrary = ::LoadLibraryExA("dxgi.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (nullptr != mDxgiSharedLibrary)
{
mD3D12SharedLibrary = ::LoadLibraryExA("d3d12.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (nullptr != mD3D12SharedLibrary)
{
mD3DCompilerSharedLibrary = ::LoadLibraryExA("D3DCompiler_47.dll", nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (nullptr == mD3DCompilerSharedLibrary)
{
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 12 library \"D3DCompiler_47.dll\"")
}
}
else
{
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 12 library \"d3d12.dll\"")
}
}
else
{
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to load in the shared Direct3D 12 library \"dxgi.dll\"")
}
// Done
return (nullptr != mDxgiSharedLibrary && nullptr != mD3D12SharedLibrary && nullptr != mD3DCompilerSharedLibrary);
}
/**
* @brief
* Load the DXGI entry points
*
* @return
* "true" if all went fine, else "false"
*/
[[nodiscard]] bool loadDxgiEntryPoints()
{
bool result = true; // Success by default
// Define a helper macro
#define IMPORT_FUNC(funcName) \
if (result) \
{ \
void* symbol = ::GetProcAddress(static_cast<HMODULE>(mDxgiSharedLibrary), #funcName); \
if (nullptr != symbol) \
{ \
*(reinterpret_cast<void**>(&(funcName))) = symbol; \
} \
else \
{ \
wchar_t moduleFilename[MAX_PATH]; \
moduleFilename[0] = '\0'; \
::GetModuleFileNameW(static_cast<HMODULE>(mDxgiSharedLibrary), moduleFilename, MAX_PATH); \
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 12 DXGI shared library \"%s\"", #funcName, moduleFilename) \
result = false; \
} \
}
// Load the entry points
IMPORT_FUNC(CreateDXGIFactory1)
// Undefine the helper macro
#undef IMPORT_FUNC
// Done
return result;
}
/**
* @brief
* Load the D3D12 entry points
*
* @return
* "true" if all went fine, else "false"
*/
[[nodiscard]] bool loadD3D12EntryPoints()
{
bool result = true; // Success by default
// Define a helper macro
#define IMPORT_FUNC(funcName) \
if (result) \
{ \
void* symbol = ::GetProcAddress(static_cast<HMODULE>(mD3D12SharedLibrary), #funcName); \
if (nullptr != symbol) \
{ \
*(reinterpret_cast<void**>(&(funcName))) = symbol; \
} \
else \
{ \
wchar_t moduleFilename[MAX_PATH]; \
moduleFilename[0] = '\0'; \
::GetModuleFileNameW(static_cast<HMODULE>(mD3D12SharedLibrary), moduleFilename, MAX_PATH); \
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 12 shared library \"%s\"", #funcName, moduleFilename) \
result = false; \
} \
}
// Load the entry points
IMPORT_FUNC(D3D12CreateDevice)
IMPORT_FUNC(D3D12SerializeRootSignature)
#ifdef RHI_DEBUG
IMPORT_FUNC(D3D12GetDebugInterface)
#endif
// Undefine the helper macro
#undef IMPORT_FUNC
// Done
return result;
}
/**
* @brief
* Load the D3DCompiler entry points
*
* @return
* "true" if all went fine, else "false"
*/
[[nodiscard]] bool loadD3DCompilerEntryPoints()
{
bool result = true; // Success by default
// Define a helper macro
#define IMPORT_FUNC(funcName) \
if (result) \
{ \
void* symbol = ::GetProcAddress(static_cast<HMODULE>(mD3DCompilerSharedLibrary), #funcName); \
if (nullptr != symbol) \
{ \
*(reinterpret_cast<void**>(&(funcName))) = symbol; \
} \
else \
{ \
wchar_t moduleFilename[MAX_PATH]; \
moduleFilename[0] = '\0'; \
::GetModuleFileNameW(static_cast<HMODULE>(mD3DCompilerSharedLibrary), moduleFilename, MAX_PATH); \
RHI_LOG(mDirect3D12Rhi.getContext(), CRITICAL, "Failed to locate the entry point \"%s\" within the Direct3D 12 shared library \"%s\"", #funcName, moduleFilename) \
result = false; \
} \
}
// Load the entry points
IMPORT_FUNC(D3DCompile)
IMPORT_FUNC(D3DCreateBlob)
// Undefine the helper macro
#undef IMPORT_FUNC
// Done
return result;
}
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Direct3D12Rhi& mDirect3D12Rhi; ///< Owner Direct3D 12 RHI instance
void* mDxgiSharedLibrary; ///< DXGI shared library, can be a null pointer
void* mD3D12SharedLibrary; ///< D3D12 shared library, can be a null pointer
void* mD3DCompilerSharedLibrary; ///< D3DCompiler shared library, can be a null pointer
bool mEntryPointsRegistered; ///< Entry points successfully registered?
bool mInitialized; ///< Already initialized?
};
//[-------------------------------------------------------]
//[ Global definitions ]
//[-------------------------------------------------------]
// In order to assign debug names to Direct3D resources we need to use the "WKPDID_D3DDebugObjectName"-GUID. This GUID
// is defined within the "D3Dcommon.h" header and it's required to add the library "dxguid.lib" in which the symbol
// is defined.
// -> See "ID3D12Device::SetPrivateData method"-documentation at MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ff476533%28v=vs.85%29.aspx
// The "Community Additions" states: "If you get a missing symbol error: Note that WKPDID_D3DDebugObjectName
// requires both that you include D3Dcommon.h, and that you link against dxguid.lib."
// -> We don't want to deal with a 800 KB library "just" for such a tiny symbol for several reasons. For once it's not
// allowed to redistribute "dxguid.lib" due to DirectX SDK licensing terms. Another reason for avoiding libraries
// were ever possible is that every library will increase the complexity of the build system and will also make
// it harder to port to other platforms - we already would need 32 bit and 64 bit versions for standard Windows
// systems. We don't want that just for resolving a tiny symbol.
//
// "WKPDID_D3DDebugObjectName" is defined within the "D3Dcommon.h"-header as
// DEFINE_GUID(WKPDID_D3DDebugObjectName,0x429b8c22,0x9188,0x4b0c,0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00);
//
// While the "DEFINE_GUID"-macro is defined within the "Guiddef.h"-header as
// #ifdef INITGUID
// #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
// EXTERN_C const GUID DECLSPEC_SELECTANY name \
// = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
// #else
// #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
// EXTERN_C const GUID FAR name
// #endif // INITGUID
//
// "GUID" is a structure defined within the "Guiddef.h"-header as
// typedef struct _GUID {
// unsigned long Data1;
// unsigned short Data2;
// unsigned short Data3;
// unsigned char Data4[ 8 ];
// } GUID;
#define RHI_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) constexpr GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
RHI_DEFINE_GUID(WKPDID_D3DDebugObjectName, 0x429b8c22, 0x9188, 0x4b0c, 0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00);
//[-------------------------------------------------------]
//[ Global functions ]
//[-------------------------------------------------------]
/**
* @brief
* Creates, loads and compiles a shader from source code
*
* @param[in] context
* RHI context
* @param[in] shaderModel
* ASCII shader model (for example "vs_5_0", "gs_5_0", "ps_5_0"), must be a valid pointer
* @param[in] sourceCode
* ASCII shader ASCII source code, must be a valid pointer
* @param[in] entryPoint
* Optional ASCII entry point, if null pointer "main" is used
* @param[in] optimizationLevel
* Optimization level
*
* @return
* The loaded and compiled shader, can be a null pointer, release the instance if you no longer need it
*/
[[nodiscard]] ID3DBlob* loadShaderFromSourcecode(const Rhi::Context& context, const char* shaderModel, const char* sourceCode, const char* entryPoint, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel)
{
// Sanity checks
RHI_ASSERT(context, nullptr != shaderModel, "Invalid Direct3D 12 shader model")
RHI_ASSERT(context, nullptr != sourceCode, "Invalid Direct3D 12 shader source code")
// Get compile flags
// -> "DX12 Do's And Don'ts" ( https://developer.nvidia.com/dx12-dos-and-donts ) "Use the /all_resources_bound / D3DCOMPILE_ALL_RESOURCES_BOUND compile flag if possible"
UINT compileFlags = (D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE_ALL_RESOURCES_BOUND);
switch (optimizationLevel)
{
case Rhi::IShaderLanguage::OptimizationLevel::DEBUG:
compileFlags |= D3DCOMPILE_DEBUG;
compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
break;
case Rhi::IShaderLanguage::OptimizationLevel::NONE:
compileFlags |= D3DCOMPILE_SKIP_VALIDATION;
compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
break;
case Rhi::IShaderLanguage::OptimizationLevel::LOW:
compileFlags |= D3DCOMPILE_SKIP_VALIDATION;
compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0;
break;
case Rhi::IShaderLanguage::OptimizationLevel::MEDIUM:
compileFlags |= D3DCOMPILE_SKIP_VALIDATION;
compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL1;
break;
case Rhi::IShaderLanguage::OptimizationLevel::HIGH:
compileFlags |= D3DCOMPILE_SKIP_VALIDATION;
compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL2;
break;
case Rhi::IShaderLanguage::OptimizationLevel::ULTRA:
compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
break;
}
// Compile
ID3DBlob* d3dBlob = nullptr;
ID3DBlob* errorD3dBlob = nullptr;
if (FAILED(D3DCompile(sourceCode, strlen(sourceCode), nullptr, nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, compileFlags, 0, &d3dBlob, &errorD3dBlob)))
{
if (nullptr != errorD3dBlob)
{
if (context.getLog().print(Rhi::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), static_cast<char*>(errorD3dBlob->GetBufferPointer())))
{
DEBUG_BREAK;
}
errorD3dBlob->Release();
}
return nullptr;
}
if (nullptr != errorD3dBlob)
{
errorD3dBlob->Release();
}
// Done
return d3dBlob;
}
void handleDeviceLost(const Direct3D12Rhi& direct3D12Rhi, HRESULT result)
{
// If the device was removed either by a disconnection or a driver upgrade, we must recreate all device resources
if (DXGI_ERROR_DEVICE_REMOVED == result || DXGI_ERROR_DEVICE_RESET == result)
{
if (DXGI_ERROR_DEVICE_REMOVED == result)
{
result = direct3D12Rhi.getD3D12Device().GetDeviceRemovedReason();
}
RHI_LOG(direct3D12Rhi.getContext(), CRITICAL, "Direct3D 12 device lost on present: Reason code 0x%08X", static_cast<unsigned int>(result))
// TODO(co) Add device lost handling if needed. Probably more complex to recreate all device resources.
}
}
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Mapping.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 mapping
*/
class Mapping final
{
//[-------------------------------------------------------]
//[ Public static methods ]
//[-------------------------------------------------------]
public:
//[-------------------------------------------------------]
//[ Rhi::VertexAttributeFormat and semantic ]
//[-------------------------------------------------------]
/**
* @brief
* "Rhi::VertexAttributeFormat" to Direct3D 12 format
*
* @param[in] vertexAttributeFormat
* "Rhi::VertexAttributeFormat" to map
*
* @return
* Direct3D 12 format
*/
[[nodiscard]] static DXGI_FORMAT getDirect3D12Format(Rhi::VertexAttributeFormat vertexAttributeFormat)
{
static constexpr DXGI_FORMAT MAPPING[] =
{
DXGI_FORMAT_R32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_1
DXGI_FORMAT_R32G32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_2
DXGI_FORMAT_R32G32B32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_3
DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::VertexAttributeFormat::FLOAT_4
DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::VertexAttributeFormat::R8G8B8A8_UNORM
DXGI_FORMAT_R8G8B8A8_UINT, // Rhi::VertexAttributeFormat::R8G8B8A8_UINT
DXGI_FORMAT_R16G16_SINT, // Rhi::VertexAttributeFormat::SHORT_2
DXGI_FORMAT_R16G16B16A16_SINT, // Rhi::VertexAttributeFormat::SHORT_4
DXGI_FORMAT_R32_UINT // Rhi::VertexAttributeFormat::UINT_1
};
return MAPPING[static_cast<int>(vertexAttributeFormat)];
}
//[-------------------------------------------------------]
//[ Rhi::BufferUsage ]
//[-------------------------------------------------------]
/**
* @brief
* "Rhi::BufferUsage" to Direct3D 12 usage and CPU access flags
*
* @param[in] bufferUsage
* "Rhi::BufferUsage" to map
* @param[out] cpuAccessFlags
* Receives the CPU access flags
*
* @return
* Direct3D 12 usage // TODO(co) Use correct Direct3D 12 type
*/
[[nodiscard]] static uint32_t getDirect3D12UsageAndCPUAccessFlags([[maybe_unused]] Rhi::BufferUsage bufferUsage, [[maybe_unused]] uint32_t& cpuAccessFlags)
{
// TODO(co) Direct3D 12
/*
// Direct3D 12 only supports a subset of the OpenGL usage indications
// -> See "D3D12_USAGE enumeration "-documentation at http://msdn.microsoft.com/en-us/library/windows/desktop/ff476259%28v=vs.85%29.aspx
switch (bufferUsage)
{
case Rhi::BufferUsage::STREAM_DRAW:
case Rhi::BufferUsage::STREAM_COPY:
case Rhi::BufferUsage::STATIC_DRAW:
case Rhi::BufferUsage::STATIC_COPY:
cpuAccessFlags = 0;
return D3D12_USAGE_IMMUTABLE;
case Rhi::BufferUsage::STREAM_READ:
case Rhi::BufferUsage::STATIC_READ:
cpuAccessFlags = D3D12_CPU_ACCESS_READ;
return D3D12_USAGE_STAGING;
case Rhi::BufferUsage::DYNAMIC_DRAW:
case Rhi::BufferUsage::DYNAMIC_COPY:
cpuAccessFlags = D3D12_CPU_ACCESS_WRITE;
return D3D12_USAGE_DYNAMIC;
default:
case Rhi::BufferUsage::DYNAMIC_READ:
cpuAccessFlags = 0;
return D3D12_USAGE_DEFAULT;
}
*/
return 0;
}
//[-------------------------------------------------------]
//[ Rhi::IndexBufferFormat ]
//[-------------------------------------------------------]
/**
* @brief
* "Rhi::IndexBufferFormat" to Direct3D 12 format
*
* @param[in] indexBufferFormat
* "Rhi::IndexBufferFormat" to map
*
* @return
* Direct3D 12 format
*/
[[nodiscard]] static DXGI_FORMAT getDirect3D12Format(Rhi::IndexBufferFormat::Enum indexBufferFormat)
{
static constexpr DXGI_FORMAT MAPPING[] =
{
DXGI_FORMAT_R32_UINT, // Rhi::IndexBufferFormat::UNSIGNED_CHAR - One byte per element, uint8_t (may not be supported by each API) - Not supported by Direct3D 12
DXGI_FORMAT_R16_UINT, // Rhi::IndexBufferFormat::UNSIGNED_SHORT - Two bytes per element, uint16_t
DXGI_FORMAT_R32_UINT // Rhi::IndexBufferFormat::UNSIGNED_INT - Four bytes per element, uint32_t (may not be supported by each API)
};
return MAPPING[indexBufferFormat];
}
//[-------------------------------------------------------]
//[ Rhi::TextureFormat ]
//[-------------------------------------------------------]
/**
* @brief
* "Rhi::TextureFormat" to Direct3D 12 format
*
* @param[in] textureFormat
* "Rhi::TextureFormat" to map
*
* @return
* Direct3D 12 format
*/
[[nodiscard]] static DXGI_FORMAT getDirect3D12Format(Rhi::TextureFormat::Enum textureFormat)
{
static constexpr DXGI_FORMAT MAPPING[] =
{
DXGI_FORMAT_R8_UNORM, // Rhi::TextureFormat::R8 - 8-bit pixel format, all bits red
DXGI_FORMAT_B8G8R8X8_UNORM, // Rhi::TextureFormat::R8G8B8 - 24-bit pixel format, 8 bits for red, green and blue
DXGI_FORMAT_R8G8B8A8_UNORM, // Rhi::TextureFormat::R8G8B8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, // Rhi::TextureFormat::R8G8B8A8_SRGB - 32-bit pixel format, 8 bits for red, green, blue and alpha; sRGB = RGB hardware gamma correction, the alpha channel always remains linear
DXGI_FORMAT_B8G8R8A8_UNORM, // Rhi::TextureFormat::B8G8R8A8 - 32-bit pixel format, 8 bits for red, green, blue and alpha
DXGI_FORMAT_R11G11B10_FLOAT, // Rhi::TextureFormat::R11G11B10F - 32-bit float format using 11 bits the red and green channel, 10 bits the blue channel; red and green channels have a 6 bits mantissa and a 5 bits exponent and blue has a 5 bits mantissa and 5 bits exponent
DXGI_FORMAT_R16G16B16A16_FLOAT, // Rhi::TextureFormat::R16G16B16A16F - 64-bit float format using 16 bits for the each channel (red, green, blue, alpha)
DXGI_FORMAT_R32G32B32A32_FLOAT, // Rhi::TextureFormat::R32G32B32A32F - 128-bit float format using 32 bits for the each channel (red, green, blue, alpha)
DXGI_FORMAT_BC1_UNORM, // Rhi::TextureFormat::BC1 - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block)
DXGI_FORMAT_BC1_UNORM_SRGB, // Rhi::TextureFormat::BC1_SRGB - DXT1 compression (known as BC1 in DirectX 10, RGB compression: 8:1, 8 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear
DXGI_FORMAT_BC2_UNORM, // Rhi::TextureFormat::BC2 - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block)
DXGI_FORMAT_BC2_UNORM_SRGB, // Rhi::TextureFormat::BC2_SRGB - DXT3 compression (known as BC2 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear
DXGI_FORMAT_BC3_UNORM, // Rhi::TextureFormat::BC3 - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block)
DXGI_FORMAT_BC3_UNORM_SRGB, // Rhi::TextureFormat::BC3_SRGB - DXT5 compression (known as BC3 in DirectX 10, RGBA compression: 4:1, 16 bytes per block); sRGB = RGB hardware gamma correction, the alpha channel always remains linear
DXGI_FORMAT_BC4_UNORM, // Rhi::TextureFormat::BC4 - 1 component texture compression (also known as 3DC+/ATI1N, known as BC4 in DirectX 10, 8 bytes per block)
DXGI_FORMAT_BC5_UNORM, // Rhi::TextureFormat::BC5 - 2 component texture compression (luminance & alpha compression 4:1 -> normal map compression, also known as 3DC/ATI2N, known as BC5 in DirectX 10, 16 bytes per block)
DXGI_FORMAT_UNKNOWN, // Rhi::TextureFormat::ETC1 - 3 component texture compression meant for mobile devices - not supported in Direct3D 12
DXGI_FORMAT_R16_UNORM, // Rhi::TextureFormat::R16_UNORM - 16-bit unsigned-normalized-integer format that supports 16 bits for the red channel
DXGI_FORMAT_R32_UINT, // Rhi::TextureFormat::R32_UINT - 32-bit unsigned integer format
DXGI_FORMAT_R32_FLOAT, // Rhi::TextureFormat::R32_FLOAT - 32-bit float format
DXGI_FORMAT_D32_FLOAT, // Rhi::TextureFormat::D32_FLOAT - 32-bit float depth format
DXGI_FORMAT_R16G16_SNORM, // Rhi::TextureFormat::R16G16_SNORM - A two-component, 32-bit signed-normalized-integer format that supports 16 bits for the red channel and 16 bits for the green channel
DXGI_FORMAT_R16G16_FLOAT, // Rhi::TextureFormat::R16G16_FLOAT - A two-component, 32-bit floating-point format that supports 16 bits for the red channel and 16 bits for the green channel
DXGI_FORMAT_UNKNOWN // Rhi::TextureFormat::UNKNOWN - Unknown
};
return MAPPING[textureFormat];
}
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/TextureHelper.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 texture helper
*/
class TextureHelper final
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
public:
enum class TextureType
{
TEXTURE_1D,
TEXTURE_1D_ARRAY,
TEXTURE_2D,
TEXTURE_2D_ARRAY,
TEXTURE_CUBE,
TEXTURE_CUBE_ARRAY,
TEXTURE_3D
};
//[-------------------------------------------------------]
//[ Public static methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] static ID3D12Resource* CreateTexture(ID3D12Device& d3d12Device, TextureType textureType, uint32_t width, uint32_t height, uint32_t depth, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, uint8_t numberOfMultisamples, uint32_t numberOfMipmaps, uint32_t textureFlags, const Rhi::OptimizedTextureClearValue* optimizedTextureClearValue)
{
D3D12_HEAP_PROPERTIES d3d12HeapProperties = {};
d3d12HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
// Get Direct3D 12 resource description
D3D12_RESOURCE_DESC d3d12ResourceDesc = {};
d3d12ResourceDesc.Dimension = (textureType <= TextureType::TEXTURE_1D_ARRAY) ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : ((textureType <= TextureType::TEXTURE_CUBE_ARRAY) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D);
d3d12ResourceDesc.Width = width;
d3d12ResourceDesc.Height = height;
d3d12ResourceDesc.DepthOrArraySize = static_cast<uint16_t>((TextureType::TEXTURE_3D == textureType) ? depth : numberOfSlices);
d3d12ResourceDesc.MipLevels = static_cast<uint16_t>(numberOfMipmaps);
d3d12ResourceDesc.Format = Mapping::getDirect3D12Format(textureFormat);
d3d12ResourceDesc.SampleDesc.Count = numberOfMultisamples;
d3d12ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
{ // Get Direct3D 12 resource description flags
uint32_t descriptionFlags = 0;
if (textureFlags & Rhi::TextureFlag::RENDER_TARGET)
{
descriptionFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
if (Rhi::TextureFormat::isDepth(textureFormat))
{
descriptionFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
if ((textureFlags & Rhi::TextureFlag::SHADER_RESOURCE) == 0)
{
descriptionFlags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
}
}
}
if (textureFlags & Rhi::TextureFlag::UNORDERED_ACCESS)
{
descriptionFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
}
d3d12ResourceDesc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(descriptionFlags);
}
// Get Direct3D 12 resource states and clear value
D3D12_RESOURCE_STATES d3d12ResourceStates = D3D12_RESOURCE_STATE_COPY_DEST;
D3D12_CLEAR_VALUE d3d12ClearValue = {};
if (textureFlags & Rhi::TextureFlag::RENDER_TARGET)
{
if (Rhi::TextureFormat::isDepth(textureFormat))
{
d3d12ResourceStates = D3D12_RESOURCE_STATE_DEPTH_WRITE;
d3d12ClearValue.Format = d3d12ResourceDesc.Format;
if (nullptr != optimizedTextureClearValue)
{
d3d12ClearValue.DepthStencil.Depth = optimizedTextureClearValue->DepthStencil.depth;
}
}
else
{
d3d12ResourceStates = D3D12_RESOURCE_STATE_RENDER_TARGET;
if (nullptr != optimizedTextureClearValue)
{
d3d12ClearValue.Format = d3d12ResourceDesc.Format;
memcpy(d3d12ClearValue.Color, optimizedTextureClearValue->color, sizeof(float) * 4);
}
}
}
// Create the Direct3D 12 texture resource
ID3D12Resource* d3d12Texture = nullptr;
const HRESULT result = d3d12Device.CreateCommittedResource(&d3d12HeapProperties, D3D12_HEAP_FLAG_NONE, &d3d12ResourceDesc, d3d12ResourceStates, d3d12ClearValue.Format ? &d3d12ClearValue : nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&d3d12Texture));
return (SUCCEEDED(result) ? d3d12Texture : nullptr);
}
static void SetTextureData(::detail::UploadContext& uploadContext, ID3D12Resource& d3d12Resource, uint32_t width, uint32_t height, uint32_t depth, Rhi::TextureFormat::Enum textureFormat, uint32_t numberOfMipmaps, uint32_t mip, uint32_t slice, const void* data, [[maybe_unused]] uint32_t size, uint32_t pitch)
{
// TODO(co) This should never ever happen
if (nullptr == uploadContext.getUploadCommandListAllocator())
{
return;
}
const D3D12_RESOURCE_DESC d3d12ResourceDesc = d3d12Resource.GetDesc();
// Texture copy destination
D3D12_TEXTURE_COPY_LOCATION d3d12TextureCopyLocationDestination;
d3d12TextureCopyLocationDestination.pResource = &d3d12Resource;
d3d12TextureCopyLocationDestination.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
// Texture copy source
D3D12_TEXTURE_COPY_LOCATION d3d12TextureCopyLocationSource;
d3d12TextureCopyLocationSource.pResource = uploadContext.getUploadCommandListAllocator()->getD3D12ResourceUploadBuffer();
d3d12TextureCopyLocationSource.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Format = d3d12ResourceDesc.Format;
// Get the number of rows
uint32_t numberOfColumns = width;
uint32_t numberOfRows = height;
const bool isCompressed = Rhi::TextureFormat::isCompressed(textureFormat);
if (isCompressed)
{
numberOfColumns = (numberOfColumns + 3) >> 2;
numberOfRows = (numberOfRows + 3) >> 2;
}
numberOfRows *= depth;
ASSERT(pitch * numberOfRows == size, "Direct3D 12: Invalid size")
// Grab upload buffer space
static constexpr uint32_t D3D12_TEXTURE_DATA_PITCH_ALIGNMENT = 256; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
static constexpr uint32_t D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT = 512; // "Microsoft Windows 10 SDK" -> "10.0.10240.0" -> "D3D12.h"
const uint32_t destinationPitch = ::detail::align(pitch, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
const uint32_t destinationOffset = uploadContext.getUploadCommandListAllocator()->allocateUploadBuffer(destinationPitch * numberOfRows, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
// Copy data in place
const uint8_t* sourceData = reinterpret_cast<const uint8_t*>(data);
uint8_t* destinationData = uploadContext.getUploadCommandListAllocator()->getData() + destinationOffset;
const uint32_t sourcePitch = pitch;
for (uint32_t r = 0; r < numberOfRows; ++r)
{
memcpy(destinationData, sourceData, sourcePitch);
destinationData += destinationPitch;
sourceData += sourcePitch;
}
// Issue a copy from upload buffer to texture
d3d12TextureCopyLocationDestination.SubresourceIndex = mip + slice * numberOfMipmaps;
d3d12TextureCopyLocationSource.PlacedFootprint.Offset = destinationOffset;
if (isCompressed)
{
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Width = ::detail::align(width, 4);
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Height = ::detail::align(height, 4);
}
else
{
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Width = width;
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Height = height;
}
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.Depth = depth;
d3d12TextureCopyLocationSource.PlacedFootprint.Footprint.RowPitch = destinationPitch;
uploadContext.getD3d12GraphicsCommandList()->CopyTextureRegion(&d3d12TextureCopyLocationDestination, 0, 0, 0, &d3d12TextureCopyLocationSource, nullptr);
D3D12_RESOURCE_BARRIER d3d12ResourceBarrier;
d3d12ResourceBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
d3d12ResourceBarrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
d3d12ResourceBarrier.Transition.pResource = &d3d12Resource;
d3d12ResourceBarrier.Transition.Subresource = d3d12TextureCopyLocationDestination.SubresourceIndex;
d3d12ResourceBarrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
d3d12ResourceBarrier.Transition.StateAfter = static_cast<D3D12_RESOURCE_STATES>(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
uploadContext.getD3d12GraphicsCommandList()->ResourceBarrier(1, &d3d12ResourceBarrier);
}
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/RootSignature.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 root signature ("pipeline layout" in Vulkan terminology) class
*/
class RootSignature final : public Rhi::IRootSignature
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] rootSignature
* Root signature to use
*/
RootSignature(Direct3D12Rhi& direct3D12Rhi, const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IRootSignature(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mRootSignature(rootSignature),
mD3D12RootSignature(nullptr)
{
const Rhi::Context& context = direct3D12Rhi.getContext();
{ // We need a backup of the given root signature
{ // Copy the parameter data
const uint32_t numberOfParameters = mRootSignature.numberOfParameters;
if (numberOfParameters > 0)
{
mRootSignature.parameters = RHI_MALLOC_TYPED(context, Rhi::RootParameter, numberOfParameters);
Rhi::RootParameter* destinationRootParameters = const_cast<Rhi::RootParameter*>(mRootSignature.parameters);
memcpy(destinationRootParameters, rootSignature.parameters, sizeof(Rhi::RootParameter) * numberOfParameters);
// Copy the descriptor table data
for (uint32_t i = 0; i < numberOfParameters; ++i)
{
Rhi::RootParameter& destinationRootParameter = destinationRootParameters[i];
const Rhi::RootParameter& sourceRootParameter = rootSignature.parameters[i];
if (Rhi::RootParameterType::DESCRIPTOR_TABLE == destinationRootParameter.parameterType)
{
const uint32_t numberOfDescriptorRanges = destinationRootParameter.descriptorTable.numberOfDescriptorRanges;
destinationRootParameter.descriptorTable.descriptorRanges = reinterpret_cast<uintptr_t>(RHI_MALLOC_TYPED(context, Rhi::DescriptorRange, numberOfDescriptorRanges));
memcpy(reinterpret_cast<Rhi::DescriptorRange*>(destinationRootParameter.descriptorTable.descriptorRanges), reinterpret_cast<const Rhi::DescriptorRange*>(sourceRootParameter.descriptorTable.descriptorRanges), sizeof(Rhi::DescriptorRange) * numberOfDescriptorRanges);
}
}
}
}
{ // Copy the static sampler data
const uint32_t numberOfStaticSamplers = mRootSignature.numberOfStaticSamplers;
if (numberOfStaticSamplers > 0)
{
mRootSignature.staticSamplers = RHI_MALLOC_TYPED(context, Rhi::StaticSampler, numberOfStaticSamplers);
memcpy(const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers), rootSignature.staticSamplers, sizeof(Rhi::StaticSampler) * numberOfStaticSamplers);
}
}
}
// Create temporary Direct3D 12 root signature instance data
// -> "Rhi::RootSignature" is not identical to "D3D12_ROOT_SIGNATURE_DESC" because it had to be extended by information required by OpenGL
D3D12_ROOT_SIGNATURE_DESC d3d12RootSignatureDesc;
{
{ // Copy the parameter data
const uint32_t numberOfRootParameters = rootSignature.numberOfParameters;
d3d12RootSignatureDesc.NumParameters = numberOfRootParameters;
if (numberOfRootParameters > 0)
{
d3d12RootSignatureDesc.pParameters = RHI_MALLOC_TYPED(context, D3D12_ROOT_PARAMETER, numberOfRootParameters);
D3D12_ROOT_PARAMETER* d3dRootParameters = const_cast<D3D12_ROOT_PARAMETER*>(d3d12RootSignatureDesc.pParameters);
for (uint32_t parameterIndex = 0; parameterIndex < numberOfRootParameters; ++parameterIndex)
{
D3D12_ROOT_PARAMETER& d3dRootParameter = d3dRootParameters[parameterIndex];
const Rhi::RootParameter& rootParameter = rootSignature.parameters[parameterIndex];
// Copy the descriptor table data and determine the shader visibility of the Direct3D 12 root parameter
uint32_t shaderVisibility = ~0u;
if (Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType)
{
const uint32_t numberOfDescriptorRanges = rootParameter.descriptorTable.numberOfDescriptorRanges;
d3dRootParameter.DescriptorTable.NumDescriptorRanges = numberOfDescriptorRanges;
d3dRootParameter.DescriptorTable.pDescriptorRanges = RHI_MALLOC_TYPED(context, D3D12_DESCRIPTOR_RANGE, numberOfDescriptorRanges);
// "Rhi::DescriptorRange" is not identical to "D3D12_DESCRIPTOR_RANGE" because it had to be extended by information required by OpenGL
for (uint32_t descriptorRangeIndex = 0; descriptorRangeIndex < numberOfDescriptorRanges; ++descriptorRangeIndex)
{
const Rhi::DescriptorRange& descriptorRange = reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)[descriptorRangeIndex];
memcpy(const_cast<D3D12_DESCRIPTOR_RANGE*>(&d3dRootParameter.DescriptorTable.pDescriptorRanges[descriptorRangeIndex]), &descriptorRange, sizeof(D3D12_DESCRIPTOR_RANGE));
if (~0u == shaderVisibility)
{
shaderVisibility = static_cast<uint32_t>(descriptorRange.shaderVisibility);
if (shaderVisibility == static_cast<uint32_t>(Rhi::ShaderVisibility::COMPUTE) || shaderVisibility == static_cast<uint32_t>(Rhi::ShaderVisibility::ALL_GRAPHICS))
{
shaderVisibility = static_cast<uint32_t>(Rhi::ShaderVisibility::ALL);
}
}
else if (shaderVisibility != static_cast<uint32_t>(descriptorRange.shaderVisibility))
{
shaderVisibility = static_cast<uint32_t>(Rhi::ShaderVisibility::ALL);
}
}
}
if (~0u == shaderVisibility)
{
shaderVisibility = static_cast<uint32_t>(Rhi::ShaderVisibility::ALL);
}
// Set root parameter
d3dRootParameter.ParameterType = static_cast<D3D12_ROOT_PARAMETER_TYPE>(rootParameter.parameterType);
d3dRootParameter.ShaderVisibility = static_cast<D3D12_SHADER_VISIBILITY>(shaderVisibility);
}
}
else
{
d3d12RootSignatureDesc.pParameters = nullptr;
}
}
{ // Copy the static sampler data
// -> "Rhi::StaticSampler" is identical to "D3D12_STATIC_SAMPLER_DESC" so there's no additional mapping work to be done in here
const uint32_t numberOfStaticSamplers = rootSignature.numberOfStaticSamplers;
d3d12RootSignatureDesc.NumStaticSamplers = numberOfStaticSamplers;
if (numberOfStaticSamplers > 0)
{
d3d12RootSignatureDesc.pStaticSamplers = RHI_MALLOC_TYPED(context, D3D12_STATIC_SAMPLER_DESC, numberOfStaticSamplers);
memcpy(const_cast<D3D12_STATIC_SAMPLER_DESC*>(d3d12RootSignatureDesc.pStaticSamplers), rootSignature.staticSamplers, sizeof(Rhi::StaticSampler) * numberOfStaticSamplers);
}
else
{
d3d12RootSignatureDesc.pStaticSamplers = nullptr;
}
}
// Copy flags
// -> "Rhi::RootSignatureFlags" is identical to "D3D12_ROOT_SIGNATURE_FLAGS" so there's no additional mapping work to be done in here
d3d12RootSignatureDesc.Flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(rootSignature.flags);
}
{ // Create the Direct3D 12 root signature instance
ID3DBlob* d3dBlobSignature = nullptr;
ID3DBlob* d3dBlobError = nullptr;
if (SUCCEEDED(D3D12SerializeRootSignature(&d3d12RootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &d3dBlobSignature, &d3dBlobError)))
{
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateRootSignature(0, d3dBlobSignature->GetBufferPointer(), d3dBlobSignature->GetBufferSize(), IID_PPV_ARGS(&mD3D12RootSignature))))
{
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Root signature", 17) // 17 = "Root signature: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12RootSignature->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create the Direct3D 12 root signature instance")
}
d3dBlobSignature->Release();
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create the Direct3D 12 root signature instance: %s", (nullptr != d3dBlobError) ? reinterpret_cast<char*>(d3dBlobError->GetBufferPointer()) : "Unknown error")
if (nullptr != d3dBlobError)
{
d3dBlobError->Release();
}
}
}
// Free temporary Direct3D 12 root signature instance data
if (nullptr != d3d12RootSignatureDesc.pParameters)
{
for (uint32_t i = 0; i < d3d12RootSignatureDesc.NumParameters; ++i)
{
const D3D12_ROOT_PARAMETER& d3d12RootParameter = d3d12RootSignatureDesc.pParameters[i];
if (D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE == d3d12RootParameter.ParameterType)
{
RHI_FREE(context, const_cast<D3D12_DESCRIPTOR_RANGE*>(d3d12RootParameter.DescriptorTable.pDescriptorRanges));
}
}
RHI_FREE(context, const_cast<D3D12_ROOT_PARAMETER*>(d3d12RootSignatureDesc.pParameters));
}
RHI_FREE(context, const_cast<D3D12_STATIC_SAMPLER_DESC*>(d3d12RootSignatureDesc.pStaticSamplers));
}
/**
* @brief
* Destructor
*/
virtual ~RootSignature() override
{
// Release the Direct3D 12 root signature
if (nullptr != mD3D12RootSignature)
{
mD3D12RootSignature->Release();
}
// Destroy the backup of the given root signature
const Rhi::Context& context = getRhi().getContext();
if (nullptr != mRootSignature.parameters)
{
for (uint32_t i = 0; i < mRootSignature.numberOfParameters; ++i)
{
const Rhi::RootParameter& rootParameter = mRootSignature.parameters[i];
if (Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType)
{
RHI_FREE(context, reinterpret_cast<Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges));
}
}
RHI_FREE(context, const_cast<Rhi::RootParameter*>(mRootSignature.parameters));
}
RHI_FREE(context, const_cast<Rhi::StaticSampler*>(mRootSignature.staticSamplers));
}
/**
* @brief
* Return the root signature data
*
* @return
* The root signature data
*/
[[nodiscard]] inline const Rhi::RootSignature& getRootSignature() const
{
return mRootSignature;
}
/**
* @brief
* Return the Direct3D 12 root signature
*
* @return
* The Direct3D 12 root signature, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12RootSignature* getD3D12RootSignature() const
{
return mD3D12RootSignature;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IRootSignature methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] virtual Rhi::IResourceGroup* createResourceGroup(uint32_t rootParameterIndex, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override;
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), RootSignature, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit RootSignature(const RootSignature& source) = delete;
RootSignature& operator =(const RootSignature& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Rhi::RootSignature mRootSignature;
ID3D12RootSignature* mD3D12RootSignature; ///< Direct3D 12 root signature, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/VertexBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 vertex buffer object (VBO, "array buffer" in OpenGL terminology) class
*/
class VertexBuffer final : public Rhi::IVertexBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the vertex buffer, must be valid
* @param[in] data
* Vertex buffer data, can be a null pointer (empty buffer)
* @param[in] bufferUsage
* Indication of the buffer usage
*/
VertexBuffer(Direct3D12Rhi& direct3D12Rhi, uint32_t numberOfBytes, const void* data, [[maybe_unused]] Rhi::BufferUsage bufferUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IVertexBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mNumberOfBytes(numberOfBytes),
mD3D12Resource(nullptr)
{
// TODO(co) This is only meant for the Direct3D 12 RHI implementation kickoff.
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
// TODO(co) Add buffer usage setting support
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(mNumberOfBytes);
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&mD3D12Resource))))
{
// Data given?
if (nullptr != data)
{
// Copy the data to the vertex buffer
UINT8* pVertexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
if (SUCCEEDED(mD3D12Resource->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin))))
{
memcpy(pVertexDataBegin, data, mNumberOfBytes);
mD3D12Resource->Unmap(0, nullptr);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to map Direct3D 12 vertex buffer")
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "VBO", 6) // 6 = "VBO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 vertex buffer resource")
}
}
/**
* @brief
* Destructor
*/
virtual ~VertexBuffer() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the number of bytes within the vertex buffer
*
* @return
* The number of bytes within the vertex buffer
*/
[[nodiscard]] inline uint32_t getNumberOfBytes() const
{
return mNumberOfBytes;
}
/**
* @brief
* Return the Direct3D vertex buffer resource instance
*
* @return
* The Direct3D vertex buffer resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), VertexBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit VertexBuffer(const VertexBuffer& source) = delete;
VertexBuffer& operator =(const VertexBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
uint32_t mNumberOfBytes; ///< Number of bytes within the vertex buffer
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/IndexBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 index buffer object (IBO, "element array buffer" in OpenGL terminology) class
*/
class IndexBuffer final : public Rhi::IIndexBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the index buffer, must be valid
* @param[in] data
* Index buffer data, can be a null pointer (empty buffer)
* @param[in] bufferUsage
* Indication of the buffer usage
* @param[in] indexBufferFormat
* Index buffer data format
*/
IndexBuffer(Direct3D12Rhi& direct3D12Rhi, uint32_t numberOfBytes, const void* data, [[maybe_unused]] Rhi::BufferUsage bufferUsage, Rhi::IndexBufferFormat::Enum indexBufferFormat RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IIndexBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3D12Resource(nullptr)
{
// Sanity check
// TODO(co) Check this, there's "DXGI_FORMAT_R8_UINT" which might work in Direct3D 12
RHI_ASSERT(direct3D12Rhi.getContext(), Rhi::IndexBufferFormat::UNSIGNED_CHAR != indexBufferFormat, "\"Rhi::IndexBufferFormat::UNSIGNED_CHAR\" is not supported by Direct3D 12")
// TODO(co) This is only meant for the Direct3D 12 RHI implementation kickoff.
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
// TODO(co) Add buffer usage setting support
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(numberOfBytes);
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&mD3D12Resource))))
{
// Data given?
if (nullptr != data)
{
// Copy the data to the index buffer
UINT8* pIndexDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
if (SUCCEEDED(mD3D12Resource->Map(0, &readRange, reinterpret_cast<void**>(&pIndexDataBegin))))
{
memcpy(pIndexDataBegin, data, numberOfBytes);
mD3D12Resource->Unmap(0, nullptr);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to map Direct3D 12 index buffer")
}
}
// Fill the Direct3D 12 index buffer view
mD3D12IndexBufferView.BufferLocation = mD3D12Resource->GetGPUVirtualAddress();
mD3D12IndexBufferView.SizeInBytes = numberOfBytes;
mD3D12IndexBufferView.Format = Mapping::getDirect3D12Format(indexBufferFormat);
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "IBO", 6) // 6 = "IBO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 index buffer resource")
mD3D12IndexBufferView.BufferLocation = 0;
mD3D12IndexBufferView.SizeInBytes = 0;
mD3D12IndexBufferView.Format = DXGI_FORMAT_UNKNOWN;
}
}
/**
* @brief
* Destructor
*/
virtual ~IndexBuffer() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the Direct3D index buffer resource instance
*
* @return
* The Direct3D index buffer resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
/**
* @brief
* Return the Direct3D 12 index buffer view
*
* @return
* The Direct3D 12 index buffer view
*/
[[nodiscard]] inline const D3D12_INDEX_BUFFER_VIEW& getD3D12IndexBufferView() const
{
return mD3D12IndexBufferView;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), IndexBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit IndexBuffer(const IndexBuffer& source) = delete;
IndexBuffer& operator =(const IndexBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3D12Resource* mD3D12Resource;
D3D12_INDEX_BUFFER_VIEW mD3D12IndexBufferView;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/VertexArray.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 vertex array class
*/
class VertexArray final : public Rhi::IVertexArray
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] vertexAttributes
* Vertex attributes ("vertex declaration" in Direct3D 9 terminology, "input layout" in Direct3D 10 & 11 terminology)
* @param[in] numberOfVertexBuffers
* Number of vertex buffers, having zero vertex buffers is valid
* @param[in] vertexBuffers
* At least numberOfVertexBuffers instances of vertex array vertex buffers, can be a null pointer in case there are zero vertex buffers, the data is internally copied and you have to free your memory if you no longer need it
* @param[in] indexBuffer
* Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer
* @param[in] id
* The unique compact vertex array ID
*/
VertexArray(Direct3D12Rhi& direct3D12Rhi, const Rhi::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Rhi::VertexArrayVertexBuffer* vertexBuffers, IndexBuffer* indexBuffer, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IVertexArray(direct3D12Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mIndexBuffer(indexBuffer),
mNumberOfSlots(numberOfVertexBuffers),
mD3D12VertexBufferViews(nullptr),
mVertexBuffers(nullptr)
{
// Add a reference to the given index buffer
if (nullptr != mIndexBuffer)
{
mIndexBuffer->addReference();
}
// Add a reference to the used vertex buffers
if (mNumberOfSlots > 0)
{
const Rhi::Context& context = direct3D12Rhi.getContext();
mD3D12VertexBufferViews = RHI_MALLOC_TYPED(context, D3D12_VERTEX_BUFFER_VIEW, mNumberOfSlots);
mVertexBuffers = RHI_MALLOC_TYPED(context, VertexBuffer*, mNumberOfSlots);
{ // Loop through all vertex buffers
D3D12_VERTEX_BUFFER_VIEW* currentD3D12VertexBufferView = mD3D12VertexBufferViews;
VertexBuffer** currentVertexBuffer = mVertexBuffers;
const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + mNumberOfSlots;
for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer, ++currentD3D12VertexBufferView, ++currentVertexBuffer)
{
// TODO(co) Add security check: Is the given resource one of the currently used RHI?
*currentVertexBuffer = static_cast<VertexBuffer*>(vertexBuffer->vertexBuffer);
(*currentVertexBuffer)->addReference();
currentD3D12VertexBufferView->BufferLocation = (*currentVertexBuffer)->getD3D12Resource()->GetGPUVirtualAddress();
currentD3D12VertexBufferView->SizeInBytes = (*currentVertexBuffer)->getNumberOfBytes();
}
}
{ // Gather slot related data
const Rhi::VertexAttribute* attribute = vertexAttributes.attributes;
const Rhi::VertexAttribute* attributesEnd = attribute + vertexAttributes.numberOfAttributes;
for (; attribute < attributesEnd; ++attribute)
{
mD3D12VertexBufferViews[attribute->inputSlot].StrideInBytes = attribute->strideInBytes;
}
}
}
}
/**
* @brief
* Destructor
*/
virtual ~VertexArray() override
{
// Release the index buffer reference
if (nullptr != mIndexBuffer)
{
mIndexBuffer->releaseReference();
}
// Cleanup Direct3D 12 input slot data, if needed
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
const Rhi::Context& context = direct3D12Rhi.getContext();
RHI_FREE(context, mD3D12VertexBufferViews);
// Release the reference to the used vertex buffers
if (nullptr != mVertexBuffers)
{
// Release references
VertexBuffer** vertexBuffersEnd = mVertexBuffers + mNumberOfSlots;
for (VertexBuffer** vertexBuffer = mVertexBuffers; vertexBuffer < vertexBuffersEnd; ++vertexBuffer)
{
(*vertexBuffer)->releaseReference();
}
// Cleanup
RHI_FREE(context, mVertexBuffers);
}
// Free the unique compact vertex array ID
direct3D12Rhi.VertexArrayMakeId.DestroyID(getId());
}
/**
* @brief
* Return the used index buffer
*
* @return
* The used index buffer, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline IndexBuffer* getIndexBuffer() const
{
return mIndexBuffer;
}
/**
* @brief
* Set the Direct3D 12 vertex declaration and stream source
*
* @param[in] d3d12GraphicsCommandList
* Direct3D 12 graphics command list to feed
*/
void setDirect3DIASetInputLayoutAndStreamSource(ID3D12GraphicsCommandList& d3d12GraphicsCommandList) const
{
d3d12GraphicsCommandList.IASetVertexBuffers(0, mNumberOfSlots, mD3D12VertexBufferViews);
// Set the used index buffer
// -> In case of no index buffer we don't set null indices, there's not really a point in it
if (nullptr != mIndexBuffer)
{
// Set the Direct3D 12 indices
d3d12GraphicsCommandList.IASetIndexBuffer(&static_cast<IndexBuffer*>(mIndexBuffer)->getD3D12IndexBufferView());
}
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), VertexArray, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit VertexArray(const VertexArray& source) = delete;
VertexArray& operator =(const VertexArray& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
IndexBuffer* mIndexBuffer; ///< Optional index buffer to use, can be a null pointer, the vertex array instance keeps a reference to the index buffer
// Direct3D 12 input slots
UINT mNumberOfSlots; ///< Number of used Direct3D 12 input slots
D3D12_VERTEX_BUFFER_VIEW* mD3D12VertexBufferViews;
// For proper vertex buffer reference counter behaviour
VertexBuffer** mVertexBuffers; ///< Vertex buffers (we keep a reference to it) used by this vertex array, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/TextureBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 texture buffer object (TBO) class
*/
class TextureBuffer final : public Rhi::ITextureBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the texture buffer, must be valid
* @param[in] data
* Texture buffer data, can be a null pointer (empty buffer)
* @param[in] bufferUsage
* Indication of the buffer usage
* @param[in] textureFormat
* Texture buffer data format
*/
TextureBuffer(Direct3D12Rhi& direct3D12Rhi, uint32_t numberOfBytes, const void* data, [[maybe_unused]] Rhi::BufferUsage bufferUsage, Rhi::TextureFormat::Enum textureFormat RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITextureBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mNumberOfBytes(numberOfBytes),
mTextureFormat(textureFormat),
mD3D12Resource(nullptr)
{
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), (numberOfBytes % Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat)) == 0, "The Direct3D 12 texture buffer size must be a multiple of the selected texture format bytes per texel")
// TODO(co) This is only meant for the Direct3D 12 RHI implementation kickoff.
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(numberOfBytes);
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
if (SUCCEEDED(d3d12Device.CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&mD3D12Resource))))
{
// Data given?
if (nullptr != data)
{
// Copy the data to the texture buffer
UINT8* pTextureDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
if (SUCCEEDED(mD3D12Resource->Map(0, &readRange, reinterpret_cast<void**>(&pTextureDataBegin))))
{
memcpy(pTextureDataBegin, data, numberOfBytes);
mD3D12Resource->Unmap(0, nullptr);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to map Direct3D 12 texture buffer")
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "TBO", 6) // 6 = "TBO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 texture buffer resource")
}
}
/**
* @brief
* Destructor
*/
virtual ~TextureBuffer() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the number of bytes
*
* @return
* The number of bytes
*/
[[nodiscard]] inline uint32_t getNumberOfBytes() const
{
return mNumberOfBytes;
}
/**
* @brief
* Return the texture format
*
* @return
* The texture format
*/
[[nodiscard]] inline Rhi::TextureFormat::Enum getTextureFormat() const
{
return mTextureFormat;
}
/**
* @brief
* Return the Direct3D 12 texture buffer resource instance
*
* @return
* The Direct3D 12 texture buffer resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TextureBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TextureBuffer(const TextureBuffer& source) = delete;
TextureBuffer& operator =(const TextureBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
uint32_t mNumberOfBytes;
Rhi::TextureFormat::Enum mTextureFormat;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/StructuredBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 structured buffer object (SBO) class
*/
class StructuredBuffer final : public Rhi::IStructuredBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the structured buffer, must be valid
* @param[in] data
* Structured buffer data, can be a null pointer (empty buffer)
* @param[in] bufferUsage
* Indication of the buffer usage
* @param[in] numberOfStructureBytes
* Number of structure bytes
*/
StructuredBuffer(Direct3D12Rhi& direct3D12Rhi, [[maybe_unused]] uint32_t numberOfBytes, [[maybe_unused]] const void* data, [[maybe_unused]] Rhi::BufferUsage bufferUsage, [[maybe_unused]] uint32_t numberOfStructureBytes RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IStructuredBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER)
// TODO(co) Direct3D 12 update
// mD3D12Buffer(nullptr),
// mD3D12ShaderResourceViewTexture(nullptr)
{
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), (numberOfBytes % numberOfStructureBytes) == 0, "The Direct3D 12 structured buffer size must be a multiple of the given number of structure bytes")
RHI_ASSERT(direct3D12Rhi.getContext(), (numberOfBytes % (sizeof(float) * 4)) == 0, "Performance: The Direct3D 12 structured buffer should be aligned to a 128-bit stride, see \"Understanding Structured Buffer Performance\" by Evan Hart, posted Apr 17 2015 at 11:33AM - https://developer.nvidia.com/content/understanding-structured-buffer-performance")
// TODO(co) Direct3D 12 update
/*
{ // Buffer part
// Direct3D 12 buffer description
D3D12_BUFFER_DESC d3d12BufferDesc;
d3d12BufferDesc.ByteWidth = numberOfBytes;
d3d12BufferDesc.Usage = Mapping::getDirect3D12UsageAndCPUAccessFlags(bufferUsage, d3d12BufferDesc.CPUAccessFlags);
d3d12BufferDesc.BindFlags = D3D12_BIND_SHADER_RESOURCE;
//d3d12BufferDesc.CPUAccessFlags = <filled above>;
d3d12BufferDesc.MiscFlags = 0;
d3d12BufferDesc.StructureByteStride = 0;
// Data given?
if (nullptr != data)
{
// Direct3D 12 subresource data
D3D12_SUBRESOURCE_DATA d3d12SubresourceData;
d3d12SubresourceData.pSysMem = data;
d3d12SubresourceData.SysMemPitch = 0;
d3d12SubresourceData.SysMemSlicePitch = 0;
// Create the Direct3D 12 constant buffer
FAILED_DEBUG_BREAK(direct3D12Rhi.getD3D12Device().CreateBuffer(&d3d12BufferDesc, &d3d12SubresourceData, &mD3D12Buffer))
}
else
{
// Create the Direct3D 12 constant buffer
FAILED_DEBUG_BREAK(direct3D12Rhi.getD3D12Device().CreateBuffer(&d3d12BufferDesc, nullptr, &mD3D12Buffer))
}
}
{ // Shader resource view part
// Direct3D 12 shader resource view description
D3D12_SHADER_RESOURCE_VIEW_DESC d3d12ShaderResourceViewDesc = {};
d3d12ShaderResourceViewDesc.Format = Mapping::getDirect3D12Format(textureFormat);
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
d3d12ShaderResourceViewDesc.Buffer.ElementOffset = 0;
d3d12ShaderResourceViewDesc.Buffer.ElementWidth = numberOfBytes / Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat);
// Create the Direct3D 12 shader resource view instance
FAILED_DEBUG_BREAK(direct3D12Rhi.getD3D12Device().CreateShaderResourceView(mD3D12Buffer, &d3d12ShaderResourceViewDesc, &mD3D12ShaderResourceViewTexture))
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
if (nullptr != mD3D12Resource)
{
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "SBO", 6) // 6 = "SBO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
#endif
*/
}
/**
* @brief
* Destructor
*/
virtual ~StructuredBuffer() override
{
// TODO(co) Direct3D 12 update
/*
// Release the used resources
if (nullptr != mD3D12Buffer)
{
mD3D12Buffer->Release();
mD3D12Buffer = nullptr;
}
*/
}
/**
* @brief
* Return the Direct3D structured buffer instance
*
* @return
* The Direct3D structured buffer instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
// TODO(co) Direct3D 12 update
//[[nodiscard]] inline ID3D12Buffer* getD3D12Buffer() const
//{
// return mD3D12Buffer;
//}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), StructuredBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit StructuredBuffer(const StructuredBuffer& source) = delete;
StructuredBuffer& operator =(const StructuredBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
// TODO(co) Direct3D 12 update
//ID3D12Buffer* mD3D12Buffer; ///< Direct3D texture buffer instance, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/IndirectBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 indirect buffer object class
*/
class IndirectBuffer final : public Rhi::IIndirectBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the indirect buffer, must be valid
* @param[in] data
* Indirect buffer data, can be a null pointer (empty buffer)
* @param[in] indirectBufferFlags
* Indirect buffer flags, see "Rhi::IndirectBufferFlag"
*/
IndirectBuffer(Direct3D12Rhi& direct3D12Rhi, uint32_t numberOfBytes, const void* data, uint32_t indirectBufferFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IIndirectBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3D12CommandSignature(nullptr),
mD3D12Resource(nullptr)
{
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 || (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0, "Invalid Direct3D 12 flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" is missing")
RHI_ASSERT(direct3D12Rhi.getContext(), !((indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) != 0 && (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) != 0), "Invalid Direct3D 12 flags, indirect buffer element type specification \"DRAW_ARGUMENTS\" or \"DRAW_INDEXED_ARGUMENTS\" must be set, but not both at one and the same time")
RHI_ASSERT(direct3D12Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawArguments)) == 0, "Direct3D 12 indirect buffer element type flags specification is \"DRAW_ARGUMENTS\" but the given number of bytes don't align to this")
RHI_ASSERT(direct3D12Rhi.getContext(), (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_INDEXED_ARGUMENTS) == 0 || (numberOfBytes % sizeof(Rhi::DrawIndexedArguments)) == 0, "Direct3D 12 indirect buffer element type flags specification is \"DRAW_INDEXED_ARGUMENTS\" but the given number of bytes don't align to this")
// TODO(co) This is only meant for the Direct3D 12 RHI implementation kickoff.
// Note: using upload heaps to transfer static data like vert buffers is not
// recommended. Every time the GPU needs it, the upload heap will be marshalled
// over. Please read up on Default Heap usage. An upload heap is used here for
// code simplicity and because there are very few verts to actually transfer.
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(numberOfBytes);
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
if (SUCCEEDED(d3d12Device.CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&mD3D12Resource))))
{
// Data given?
if (nullptr != data)
{
// Copy the data to the indirect buffer
UINT8* pIndirectDataBegin;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
if (SUCCEEDED(mD3D12Resource->Map(0, &readRange, reinterpret_cast<void**>(&pIndirectDataBegin))))
{
memcpy(pIndirectDataBegin, data, numberOfBytes);
mD3D12Resource->Unmap(0, nullptr);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to map Direct3D 12 indirect buffer")
}
}
D3D12_INDIRECT_ARGUMENT_DESC d3dIndirectArgumentDescription[1];
d3dIndirectArgumentDescription[0].Type = (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) ? D3D12_INDIRECT_ARGUMENT_TYPE_DRAW : D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
D3D12_COMMAND_SIGNATURE_DESC d3d12CommandSignatureDescription;
d3d12CommandSignatureDescription.ByteStride = (indirectBufferFlags & Rhi::IndirectBufferFlag::DRAW_ARGUMENTS) ? sizeof(Rhi::DrawArguments) : sizeof(Rhi::DrawIndexedArguments);
d3d12CommandSignatureDescription.NumArgumentDescs = 1;
d3d12CommandSignatureDescription.pArgumentDescs = d3dIndirectArgumentDescription;
d3d12CommandSignatureDescription.NodeMask = 0;
if (FAILED(d3d12Device.CreateCommandSignature(&d3d12CommandSignatureDescription, nullptr, IID_PPV_ARGS(&mD3D12CommandSignature))))
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 command signature")
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "IndirectBufferObject", 23) // 23 = "IndirectBufferObject: " including terminating zero
if (nullptr != mD3D12CommandSignature)
{
FAILED_DEBUG_BREAK(mD3D12CommandSignature->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 indirect buffer resource")
}
}
/**
* @brief
* Destructor
*/
virtual ~IndirectBuffer() override
{
// Release the used resources
if (nullptr != mD3D12CommandSignature)
{
mD3D12CommandSignature->Release();
}
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the Direct3D 12 command signature instance
*
* @return
* The Direct3D 12 command signature instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12CommandSignature* getD3D12CommandSignature() const
{
return mD3D12CommandSignature;
}
/**
* @brief
* Return the Direct3D 12 indirect buffer resource instance
*
* @return
* The Direct3D 12 indirect buffer resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IIndirectBuffer methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const uint8_t* getEmulationData() const override
{
return nullptr;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), IndirectBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit IndirectBuffer(const IndirectBuffer& source) = delete;
IndirectBuffer& operator =(const IndirectBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3D12CommandSignature* mD3D12CommandSignature;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/UniformBuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 uniform buffer object (UBO, "constant buffer" in Direct3D terminology) interface
*/
class UniformBuffer final : public Rhi::IUniformBuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] numberOfBytes
* Number of bytes within the uniform buffer, must be valid
* @param[in] data
* Uniform buffer data, can be a null pointer (empty buffer)
* @param[in] bufferUsage
* Indication of the buffer usage
*/
UniformBuffer(Direct3D12Rhi& direct3D12Rhi, uint32_t numberOfBytes, const void* data, [[maybe_unused]] Rhi::BufferUsage bufferUsage RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
Rhi::IUniformBuffer(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mNumberOfBytesOnGpu(::detail::align(numberOfBytes, 256)), // Constant buffer size is required to be 256-byte aligned, no assert because other RHI implementations have another alignment (DirectX 11 e.g. 16), see "ID3D12Device::CreateConstantBufferView method" at https://msdn.microsoft.com/de-de/library/windows/desktop/dn788659%28v=vs.85%29.aspx
mD3D12Resource(nullptr),
mMappedData(nullptr)
{
// TODO(co) Add buffer usage setting support
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_UPLOAD);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(mNumberOfBytesOnGpu);
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&mD3D12Resource))))
{
// Data given?
if (nullptr != data)
{
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
if (SUCCEEDED(mD3D12Resource->Map(0, &readRange, reinterpret_cast<void**>(&mMappedData))))
{
memcpy(mMappedData, data, numberOfBytes);
mD3D12Resource->Unmap(0, nullptr);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to map Direct3D 12 uniform buffer")
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "UBO", 6) // 6 = "UBO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 uniform buffer resource")
}
}
/**
* @brief
* Destructor
*/
virtual ~UniformBuffer() override
{
// Release the Direct3D 12 constant buffer
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the number of bytes on GPU
*
* @return
* The number of bytes on GPU
*/
[[nodiscard]] inline uint32_t getNumberOfBytesOnGpu() const
{
return mNumberOfBytesOnGpu;
}
/**
* @brief
* Return the Direct3D uniform buffer resource instance
*
* @return
* The Direct3D uniform buffer resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), UniformBuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit UniformBuffer(const UniformBuffer& source) = delete;
UniformBuffer& operator =(const UniformBuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
uint32_t mNumberOfBytesOnGpu;
ID3D12Resource* mD3D12Resource;
uint8_t* mMappedData;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Buffer/BufferManager.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 buffer manager interface
*/
class BufferManager final : public Rhi::IBufferManager
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
*/
inline explicit BufferManager(Direct3D12Rhi& direct3D12Rhi) :
IBufferManager(direct3D12Rhi)
{}
/**
* @brief
* Destructor
*/
inline virtual ~BufferManager() override
{
// Nothing here
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IBufferManager methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual Rhi::IVertexBuffer* createVertexBuffer(uint32_t numberOfBytes, const void* data = nullptr, [[maybe_unused]] uint32_t bufferFlags = 0, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), VertexBuffer)(direct3D12Rhi, numberOfBytes, data, bufferUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IIndexBuffer* createIndexBuffer(uint32_t numberOfBytes, const void* data = nullptr, [[maybe_unused]] uint32_t bufferFlags = 0, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, Rhi::IndexBufferFormat::Enum indexBufferFormat = Rhi::IndexBufferFormat::UNSIGNED_SHORT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), IndexBuffer)(direct3D12Rhi, numberOfBytes, data, bufferUsage, indexBufferFormat RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IVertexArray* createVertexArray(const Rhi::VertexAttributes& vertexAttributes, uint32_t numberOfVertexBuffers, const Rhi::VertexArrayVertexBuffer* vertexBuffers, Rhi::IIndexBuffer* indexBuffer = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
#ifdef RHI_DEBUG
{
const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers;
for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer)
{
RHI_ASSERT(direct3D12Rhi.getContext(), &direct3D12Rhi == &vertexBuffer->vertexBuffer->getRhi(), "Direct3D 12 error: The given vertex buffer resource is owned by another RHI instance")
}
}
#endif
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == indexBuffer || &direct3D12Rhi == &indexBuffer->getRhi(), "Direct3D 12 error: The given index buffer resource is owned by another RHI instance")
// Create vertex array
uint16_t id = 0;
if (direct3D12Rhi.VertexArrayMakeId.CreateID(id))
{
return RHI_NEW(direct3D12Rhi.getContext(), VertexArray)(direct3D12Rhi, vertexAttributes, numberOfVertexBuffers, vertexBuffers, static_cast<IndexBuffer*>(indexBuffer), id RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
// Error: Ensure a correct reference counter behaviour
const Rhi::VertexArrayVertexBuffer* vertexBufferEnd = vertexBuffers + numberOfVertexBuffers;
for (const Rhi::VertexArrayVertexBuffer* vertexBuffer = vertexBuffers; vertexBuffer < vertexBufferEnd; ++vertexBuffer)
{
vertexBuffer->vertexBuffer->addReference();
vertexBuffer->vertexBuffer->releaseReference();
}
if (nullptr != indexBuffer)
{
indexBuffer->addReference();
indexBuffer->releaseReference();
}
return nullptr;
}
[[nodiscard]] inline virtual Rhi::ITextureBuffer* createTextureBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t = Rhi::BufferFlag::SHADER_RESOURCE, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW, Rhi::TextureFormat::Enum textureFormat = Rhi::TextureFormat::R32G32B32A32F RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), TextureBuffer)(direct3D12Rhi, numberOfBytes, data, bufferUsage, textureFormat RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IStructuredBuffer* createStructuredBuffer(uint32_t numberOfBytes, const void* data, [[maybe_unused]] uint32_t bufferFlags, Rhi::BufferUsage bufferUsage, uint32_t numberOfStructureBytes RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), StructuredBuffer)(direct3D12Rhi, numberOfBytes, data, bufferUsage, numberOfStructureBytes RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IIndirectBuffer* createIndirectBuffer(uint32_t numberOfBytes, const void* data = nullptr, uint32_t indirectBufferFlags = 0, [[maybe_unused]] Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), IndirectBuffer)(direct3D12Rhi, numberOfBytes, data, indirectBufferFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IUniformBuffer* createUniformBuffer(uint32_t numberOfBytes, const void* data = nullptr, Rhi::BufferUsage bufferUsage = Rhi::BufferUsage::STATIC_DRAW RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Don't remove this reminder comment block: There are no buffer flags by intent since an uniform buffer can't be used for unordered access and as a consequence an uniform buffer must always used as shader resource to not be pointless
// RHI_ASSERT(direct3D12Rhi.getContext(), (bufferFlags & Rhi::BufferFlag::UNORDERED_ACCESS) == 0, "Invalid Direct3D 12 buffer flags, uniform buffer can't be used for unordered access")
// RHI_ASSERT(direct3D12Rhi.getContext(), (bufferFlags & Rhi::BufferFlag::SHADER_RESOURCE) != 0, "Invalid Direct3D 12 buffer flags, uniform buffer must be used as shader resource")
// Create the uniform buffer
return RHI_NEW(direct3D12Rhi.getContext(), UniformBuffer)(direct3D12Rhi, numberOfBytes, data, bufferUsage RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), BufferManager, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit BufferManager(const BufferManager& source) = delete;
BufferManager& operator =(const BufferManager& source) = delete;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/Texture1D.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 1D texture class
*/
class Texture1D final : public Rhi::ITexture1D
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
*/
Texture1D(Direct3D12Rhi& direct3D12Rhi, uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITexture1D(direct3D12Rhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mD3D12Resource(nullptr)
{
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_1D, width, 1, 1, 1, textureFormat, 1, mNumberOfMipmaps, textureFlags, nullptr);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
// Upload the current mipmap
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, 1);
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, 1, 1, textureFormat, mNumberOfMipmaps, mipmap, 0, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next mipmap and ensure the size is always at least 1x1
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
width = getHalfSize(width);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "1D texture", 13) // 13 = "1D texture: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~Texture1D() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DDXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Texture1D, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Texture1D(const Texture1D& source) = delete;
Texture1D& operator =(const Texture1D& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/Texture1DArray.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 1D array texture class
*/
class Texture1DArray final : public Rhi::ITexture1DArray
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] numberOfSlices
* Number of slices, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
*/
Texture1DArray(Direct3D12Rhi& direct3D12Rhi, uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITexture1DArray(direct3D12Rhi, width, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mNumberOfSlices(numberOfSlices),
mD3D12Resource(nullptr)
{
// TODO(co) Add "Rhi::TextureFlag::GENERATE_MIPMAPS" support, also for render target textures
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_1D_ARRAY, width, 1, 1, numberOfSlices, textureFormat, 1, mNumberOfMipmaps, textureFlags, nullptr);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
// Data layout
// - Direct3D 12 wants: DDS files are organized in slice-major order, like this:
// Slice0: Mip0, Mip1, Mip2, etc.
// Slice1: Mip0, Mip1, Mip2, etc.
// etc.
// - The RHI provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// etc.
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, 1);
for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice)
{
// Upload the current mipmap
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, 1, 1, textureFormat, mNumberOfMipmaps, mipmap, arraySlice, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next slice
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
// Move on to the next mipmap and ensure the size is always at least 1x1
width = getHalfSize(width);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "1D texture array", 19) // 19 = "1D texture array: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~Texture1DArray() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DDXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the number of slices
*
* @return
* The number of slices
*/
[[nodiscard]] inline uint32_t getNumberOfSlices() const
{
return mNumberOfSlices;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Texture1DArray, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Texture1DArray(const Texture1DArray& source) = delete;
Texture1DArray& operator =(const Texture1DArray& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
uint32_t mNumberOfSlices;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/Texture2D.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 2D texture class
*/
class Texture2D final : public Rhi::ITexture2D
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] height
* Texture height, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
* @param[in] numberOfMultisamples
* The number of multisamples per pixel (valid values: 1, 2, 4, 8)
* @param[in] optimizedTextureClearValue
* Optional optimized texture clear value
*/
Texture2D(Direct3D12Rhi& direct3D12Rhi, uint32_t width, uint32_t height, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags, uint8_t numberOfMultisamples, const Rhi::OptimizedTextureClearValue* optimizedTextureClearValue RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITexture2D(direct3D12Rhi, width, height RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mD3D12Resource(nullptr)
{
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfMultisamples == 1 || numberOfMultisamples == 2 || numberOfMultisamples == 4 || numberOfMultisamples == 8, "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfMultisamples == 1 || nullptr == data, "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfMultisamples == 1 || 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS), "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfMultisamples == 1 || 0 == (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS), "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfMultisamples == 1 || 0 != (textureFlags & Rhi::TextureFlag::RENDER_TARGET), "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), 0 == (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS) || nullptr != data, "Invalid Direct3D 12 texture parameters")
RHI_ASSERT(direct3D12Rhi.getContext(), (textureFlags & Rhi::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "Direct3D 12 render target textures can't be filled using provided data")
// TODO(co) Add "Rhi::TextureFlag::GENERATE_MIPMAPS" support, also for render target textures
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width, height) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_2D, width, height, 1, 1, textureFormat, numberOfMultisamples, mNumberOfMipmaps, textureFlags, optimizedTextureClearValue);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
// Upload the current mipmap
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height);
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, height, 1, textureFormat, mNumberOfMipmaps, mipmap, 0, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next mipmap and ensure the size is always at least 1x1
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
width = getHalfSize(width);
height = getHalfSize(height);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "2D texture", 13) // 13 = "2D texture: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~Texture2D() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DDXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
/**
* @brief
* Set minimum maximum mipmap index
*
* @param[in] minimumMipmapIndex
* Minimum mipmap index, the most detailed mipmap, also known as base mipmap, 0 by default
* @param[in] maximumMipmapIndex
* Maximum mipmap index, the least detailed mipmap, <number of mipmaps> by default
*/
inline void setMinimumMaximumMipmapIndex([[maybe_unused]] uint32_t minimumMipmapIndex, [[maybe_unused]] uint32_t maximumMipmapIndex)
{
// TODO(co) Implement me
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Texture2D, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Texture2D(const Texture2D& source) = delete;
Texture2D& operator =(const Texture2D& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/Texture2DArray.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 2D array texture class
*/
class Texture2DArray final : public Rhi::ITexture2DArray
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] height
* Texture height, must be >0
* @param[in] numberOfSlices
* Number of slices, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
*/
Texture2DArray(Direct3D12Rhi& direct3D12Rhi, uint32_t width, uint32_t height, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITexture2DArray(direct3D12Rhi, width, height, numberOfSlices RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mNumberOfSlices(numberOfSlices),
mD3D12Resource(nullptr)
{
// TODO(co) Add "Rhi::TextureFlag::GENERATE_MIPMAPS" support, also for render target textures
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width, height) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_2D_ARRAY, width, height, 1, numberOfSlices, textureFormat, 1, mNumberOfMipmaps, textureFlags, nullptr);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
// Data layout
// - Direct3D 12 wants: DDS files are organized in slice-major order, like this:
// Slice0: Mip0, Mip1, Mip2, etc.
// Slice1: Mip0, Mip1, Mip2, etc.
// etc.
// - The RHI provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// etc.
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height);
for (uint32_t arraySlice = 0; arraySlice < numberOfSlices; ++arraySlice)
{
// Upload the current mipmap
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, height, 1, textureFormat, mNumberOfMipmaps, mipmap, arraySlice, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next slice
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
// Move on to the next mipmap and ensure the size is always at least 1x1
width = getHalfSize(width);
height = getHalfSize(height);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "2D texture array", 19) // 19 = "2D texture array: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~Texture2DArray() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DDXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the number of slices
*
* @return
* The number of slices
*/
[[nodiscard]] inline uint32_t getNumberOfSlices() const
{
return mNumberOfSlices;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Texture2DArray, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Texture2DArray(const Texture2DArray& source) = delete;
Texture2DArray& operator =(const Texture2DArray& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
uint32_t mNumberOfSlices;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/Texture3D.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 3D texture class
*/
class Texture3D final : public Rhi::ITexture3D
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] height
* Texture height, must be >0
* @param[in] depth
* Texture depth, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
*/
Texture3D(Direct3D12Rhi& direct3D12Rhi, uint32_t width, uint32_t height, uint32_t depth, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITexture3D(direct3D12Rhi, width, height, depth RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mD3D12Resource(nullptr)
{
// TODO(co) Add "Rhi::TextureFlag::GENERATE_MIPMAPS" support, also for render target textures
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width, height) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_3D, width, height, depth, 1, textureFormat, 1, mNumberOfMipmaps, textureFlags, nullptr);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
// Data layout: The RHI provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// Mip1: Slice0, Slice1, Slice2, Slice3, Slice4, Slice5
// etc.
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
// Upload the current mipmap
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height) * depth;
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, height, depth, textureFormat, mNumberOfMipmaps, mipmap, 0, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next mipmap and ensure the size is always at least 1x1x1
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
width = getHalfSize(width);
height = getHalfSize(height);
depth = getHalfSize(depth);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "3D texture", 13) // 13 = "3D texture: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~Texture3D() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DDXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Texture3D, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Texture3D(const Texture3D& source) = delete;
Texture3D& operator =(const Texture3D& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/TextureCube.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 cube texture class
*/
class TextureCube final : public Rhi::ITextureCube
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] width
* Texture width, must be >0
* @param[in] textureFormat
* Texture format
* @param[in] data
* Texture data, can be a null pointer
* @param[in] textureFlags
* Texture flags, see "Rhi::TextureFlag::Enum"
*/
TextureCube(Direct3D12Rhi& direct3D12Rhi, uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data, uint32_t textureFlags RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ITextureCube(direct3D12Rhi, width RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiFormat(Mapping::getDirect3D12Format(textureFormat)),
mNumberOfMipmaps(0),
mD3D12Resource(nullptr)
{
static constexpr uint32_t NUMBER_OF_SLICES = 6; // In Direct3D 12, a cube map is a 2D array texture with six slices
// TODO(co) Add "Rhi::TextureFlag::GENERATE_MIPMAPS" support, also for render target textures
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (textureFlags & Rhi::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (textureFlags & Rhi::TextureFlag::GENERATE_MIPMAPS));
mNumberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? Rhi::ITexture::getNumberOfMipmaps(width) : 1;
RHI_ASSERT(direct3D12Rhi.getContext(), !generateMipmaps, "TODO(co) Direct3D 12 texture mipmap generation isn't implemented, yet")
if (generateMipmaps)
{
mNumberOfMipmaps = 1;
}
// Create the Direct3D 12 texture resource
mD3D12Resource = TextureHelper::CreateTexture(direct3D12Rhi.getD3D12Device(), TextureHelper::TextureType::TEXTURE_CUBE, width, width, 1, NUMBER_OF_SLICES, textureFormat, 1, mNumberOfMipmaps, textureFlags, nullptr);
if (nullptr != mD3D12Resource)
{
// Upload all mipmaps in case the user provided us with texture data
if (nullptr != data)
{
// Data layout
// - Direct3D 12 wants: DDS files are organized in face-major order, like this:
// Face0: Mip0, Mip1, Mip2, etc.
// Face1: Mip0, Mip1, Mip2, etc.
// etc.
// - The RHI provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Face0, Face1, Face2, Face3, Face4, Face5
// Mip1: Face0, Face1, Face2, Face3, Face4, Face5
// etc.
for (uint32_t mipmap = 0; mipmap < mNumberOfMipmaps; ++mipmap)
{
// TODO(co) Is it somehow possible to upload a whole cube texture mipmap in one burst?
const uint32_t numberOfBytesPerRow = Rhi::TextureFormat::getNumberOfBytesPerRow(textureFormat, width);
const uint32_t numberOfBytesPerSlice = Rhi::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, width);
for (uint32_t arraySlice = 0; arraySlice < NUMBER_OF_SLICES; ++arraySlice)
{
// Upload the current mipmap
TextureHelper::SetTextureData(direct3D12Rhi.getUploadContext(), *mD3D12Resource, width, width, 1, textureFormat, mNumberOfMipmaps, mipmap, arraySlice, data, numberOfBytesPerSlice, numberOfBytesPerRow);
// Move on to the next slice
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
// Move on to the next mipmap and ensure the size is always at least 1x1
width = getHalfSize(width);
}
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Cube texture", 15) // 15 = "Cube texture: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12Resource->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
}
/**
* @brief
* Destructor
*/
virtual ~TextureCube() override
{
if (nullptr != mD3D12Resource)
{
mD3D12Resource->Release();
}
}
/**
* @brief
* Return the DXGI format
*
* @return
* The DXGI format
*/
[[nodiscard]] inline DXGI_FORMAT getDxgiFormat() const
{
return mDxgiFormat;
}
/**
* @brief
* Return the number of mipmaps
*
* @return
* The number of mipmaps
*/
[[nodiscard]] inline uint32_t getNumberOfMipmaps() const
{
return mNumberOfMipmaps;
}
/**
* @brief
* Return the Direct3D 12 resource instance
*
* @return
* The Direct3D 12 resource instance, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12Resource* getD3D12Resource() const
{
return mD3D12Resource;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TextureCube, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TextureCube(const TextureCube& source) = delete;
TextureCube& operator =(const TextureCube& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
DXGI_FORMAT mDxgiFormat;
uint32_t mNumberOfMipmaps;
ID3D12Resource* mD3D12Resource;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Texture/TextureManager.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 texture manager interface
*/
class TextureManager final : public Rhi::ITextureManager
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
*/
inline explicit TextureManager(Direct3D12Rhi& direct3D12Rhi) :
ITextureManager(direct3D12Rhi)
{}
/**
* @brief
* Destructor
*/
inline virtual ~TextureManager() override
{}
//[-------------------------------------------------------]
//[ Public virtual Rhi::ITextureManager methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] virtual Rhi::ITexture1D* createTexture1D(uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0, "Direct3D 12 create texture 1D was called with invalid parameters")
// Create 1D texture resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), Texture1D)(direct3D12Rhi, width, textureFormat, data, textureFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITexture1DArray* createTexture1DArray(uint32_t width, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0 && numberOfSlices > 0, "Direct3D 12 create texture 1D array was called with invalid parameters")
// Create 1D texture array resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), Texture1DArray)(direct3D12Rhi, width, numberOfSlices, textureFormat, data, textureFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITexture2D* createTexture2D(uint32_t width, uint32_t height, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT, uint8_t numberOfMultisamples = 1, const Rhi::OptimizedTextureClearValue* optimizedTextureClearValue = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0 && height > 0, "Direct3D 12 create texture 2D was called with invalid parameters")
// Create 2D texture resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), Texture2D)(direct3D12Rhi, width, height, textureFormat, data, textureFlags, numberOfMultisamples, optimizedTextureClearValue RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITexture2DArray* createTexture2DArray(uint32_t width, uint32_t height, uint32_t numberOfSlices, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0 && height > 0 && numberOfSlices > 0, "Direct3D 12 create texture 2D array was called with invalid parameters")
// Create 2D texture array resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), Texture2DArray)(direct3D12Rhi, width, height, numberOfSlices, textureFormat, data, textureFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITexture3D* createTexture3D(uint32_t width, uint32_t height, uint32_t depth, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0 && height > 0 && depth > 0, "Direct3D 12 create texture 3D was called with invalid parameters")
// Create 3D texture resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), Texture3D)(direct3D12Rhi, width, height, depth, textureFormat, data, textureFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITextureCube* createTextureCube(uint32_t width, Rhi::TextureFormat::Enum textureFormat, const void* data = nullptr, uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), width > 0, "Direct3D 12 create texture cube was called with invalid parameters")
// Create cube texture resource, texture usage isn't supported
return RHI_NEW(direct3D12Rhi.getContext(), TextureCube)(direct3D12Rhi, width, textureFormat, data, textureFlags RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::ITextureCubeArray* createTextureCubeArray([[maybe_unused]] uint32_t width, [[maybe_unused]] uint32_t numberOfSlices, [[maybe_unused]] Rhi::TextureFormat::Enum textureFormat, [[maybe_unused]] const void* data = nullptr, [[maybe_unused]] uint32_t textureFlags = 0, [[maybe_unused]] Rhi::TextureUsage textureUsage = Rhi::TextureUsage::DEFAULT RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// TODO(co) Implement me
#ifdef RHI_DEBUG
debugName = debugName;
#endif
return nullptr;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TextureManager, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TextureManager(const TextureManager& source) = delete;
TextureManager& operator =(const TextureManager& source) = delete;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/State/SamplerState.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 sampler state class
*/
class SamplerState final : public Rhi::ISamplerState
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] samplerState
* Sampler state to use
*/
SamplerState(Direct3D12Rhi& direct3D12Rhi, const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ISamplerState(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mSamplerState(samplerState)
{
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), samplerState.filter != Rhi::FilterMode::UNKNOWN, "Direct3D 12 filter mode must not be unknown")
RHI_ASSERT(direct3D12Rhi.getContext(), samplerState.maxAnisotropy <= direct3D12Rhi.getCapabilities().maximumAnisotropy, "Maximum Direct3D 12 anisotropy value violated")
}
/**
* @brief
* Destructor
*/
virtual ~SamplerState() override
{
// Nothing here
}
/**
* @brief
* Return the sampler state
*
* @return
* The sampler state
*/
[[nodiscard]] inline const Rhi::SamplerState& getSamplerState() const
{
return mSamplerState;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), SamplerState, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit SamplerState(const SamplerState& source) = delete;
SamplerState& operator =(const SamplerState& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Rhi::SamplerState mSamplerState;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/RenderTarget/RenderPass.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 render pass interface
*/
class RenderPass final : public Rhi::IRenderPass
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] rhi
* Owner RHI instance
* @param[in] numberOfColorAttachments
* Number of color render target textures, must be <="Rhi::Capabilities::maximumNumberOfSimultaneousRenderTargets"
* @param[in] colorAttachmentTextureFormats
* The color render target texture formats, can be a null pointer or can contain null pointers, if not a null pointer there must be at
* least "numberOfColorAttachments" textures in the provided C-array of pointers
* @param[in] depthStencilAttachmentTextureFormat
* The optional depth stencil render target texture format, can be a "Rhi::TextureFormat::UNKNOWN" if there should be no depth buffer
*/
RenderPass(Rhi::IRhi& rhi, uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IRenderPass(rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mNumberOfColorAttachments(numberOfColorAttachments),
mDepthStencilAttachmentTextureFormat(depthStencilAttachmentTextureFormat)
{
RHI_ASSERT(rhi.getContext(), mNumberOfColorAttachments < 8, "Invalid number of Direct3D 12 color attachments")
memcpy(mColorAttachmentTextureFormats, colorAttachmentTextureFormats, sizeof(Rhi::TextureFormat::Enum) * mNumberOfColorAttachments);
}
/**
* @brief
* Destructor
*/
inline virtual ~RenderPass() override
{}
/**
* @brief
* Return the number of color render target textures
*
* @return
* The number of color render target textures
*/
[[nodiscard]] inline uint32_t getNumberOfColorAttachments() const
{
return mNumberOfColorAttachments;
}
/**
* @brief
* Return the number of render target textures (color and depth stencil)
*
* @return
* The number of render target textures (color and depth stencil)
*/
[[nodiscard]] inline uint32_t getNumberOfAttachments() const
{
return (mDepthStencilAttachmentTextureFormat != Rhi::TextureFormat::Enum::UNKNOWN) ? (mNumberOfColorAttachments + 1) : mNumberOfColorAttachments;
}
/**
* @brief
* Return the color attachment texture format
*
* @param[in] colorAttachmentIndex
* Color attachment index
*
* @return
* The color attachment texture format
*/
[[nodiscard]] inline Rhi::TextureFormat::Enum getColorAttachmentTextureFormat(uint32_t colorAttachmentIndex) const
{
RHI_ASSERT(getRhi().getContext(), colorAttachmentIndex < mNumberOfColorAttachments, "Invalid Direct3D 12 color attachment index")
return mColorAttachmentTextureFormats[colorAttachmentIndex];
}
/**
* @brief
* Return the depth stencil attachment texture format
*
* @return
* The depth stencil attachment texture format
*/
[[nodiscard]] inline Rhi::TextureFormat::Enum getDepthStencilAttachmentTextureFormat() const
{
return mDepthStencilAttachmentTextureFormat;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), RenderPass, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit RenderPass(const RenderPass& source) = delete;
RenderPass& operator =(const RenderPass& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
uint32_t mNumberOfColorAttachments;
Rhi::TextureFormat::Enum mColorAttachmentTextureFormats[8];
Rhi::TextureFormat::Enum mDepthStencilAttachmentTextureFormat;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/QueryPool.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 asynchronous query pool interface
*/
class QueryPool final : public Rhi::IQueryPool
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] queryType
* Query type
* @param[in] numberOfQueries
* Number of queries
*/
QueryPool(Direct3D12Rhi& direct3D12Rhi, Rhi::QueryType queryType, uint32_t numberOfQueries RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IQueryPool(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mQueryType(queryType),
mNumberOfQueries(numberOfQueries),
mD3D12QueryHeap(nullptr),
mD3D12ResourceQueryHeapResultReadback(nullptr),
mResolveToFrameNumber(0)
{
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
uint32_t numberOfBytesPerQuery = 0;
{ // Get Direct3D 12 query description
D3D12_QUERY_HEAP_DESC d3d12QueryHeapDesc = {};
switch (queryType)
{
case Rhi::QueryType::OCCLUSION:
d3d12QueryHeapDesc.Type = D3D12_QUERY_HEAP_TYPE_OCCLUSION;
numberOfBytesPerQuery = sizeof(uint64_t);
break;
case Rhi::QueryType::PIPELINE_STATISTICS:
d3d12QueryHeapDesc.Type = D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS;
numberOfBytesPerQuery = sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS);
break;
case Rhi::QueryType::TIMESTAMP:
d3d12QueryHeapDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP;
numberOfBytesPerQuery = sizeof(uint64_t);
break;
}
d3d12QueryHeapDesc.Count = numberOfQueries;
// Create Direct3D 12 query heap
FAILED_DEBUG_BREAK(d3d12Device.CreateQueryHeap(&d3d12QueryHeapDesc, IID_PPV_ARGS(&mD3D12QueryHeap)))
}
{ // Create the Direct3D 12 resource for query heap result readback
// -> Due to the asynchronous nature of queries (see "ID3D12GraphicsCommandList::ResolveQueryData()"), we need a result readback buffer which can hold enough frames
// +1 = One more frame as an instance is guaranteed to be written to if "Direct3D12Rhi::NUMBER_OF_FRAMES" frames have been dispatched since. This is due to a fact that present stalls when none of the maximum number of frames are done/available.
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_READBACK);
const D3D12_RESOURCE_DESC d3d12ResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(static_cast<UINT64>(numberOfBytesPerQuery) * numberOfQueries * (Direct3D12Rhi::NUMBER_OF_FRAMES + 1));
FAILED_DEBUG_BREAK(d3d12Device.CreateCommittedResource(&d3d12XHeapProperties, D3D12_HEAP_FLAG_NONE, &d3d12ResourceDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&mD3D12ResourceQueryHeapResultReadback)))
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
switch (queryType)
{
case Rhi::QueryType::OCCLUSION:
{
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Occlusion query", 18) // 18 = "Occlusion query: " including terminating zero
if (nullptr != mD3D12QueryHeap)
{
FAILED_DEBUG_BREAK(mD3D12QueryHeap->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
if (nullptr != mD3D12ResourceQueryHeapResultReadback)
{
FAILED_DEBUG_BREAK(mD3D12ResourceQueryHeapResultReadback->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
break;
}
case Rhi::QueryType::PIPELINE_STATISTICS:
{
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Pipeline statistics query", 28) // 28 = "Pipeline statistics query: " including terminating zero
if (nullptr != mD3D12QueryHeap)
{
FAILED_DEBUG_BREAK(mD3D12QueryHeap->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
if (nullptr != mD3D12ResourceQueryHeapResultReadback)
{
FAILED_DEBUG_BREAK(mD3D12ResourceQueryHeapResultReadback->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
break;
}
case Rhi::QueryType::TIMESTAMP:
{
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Timestamp query", 18) // 18 = "Timestamp query: " including terminating zero
if (nullptr != mD3D12QueryHeap)
{
FAILED_DEBUG_BREAK(mD3D12QueryHeap->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
if (nullptr != mD3D12ResourceQueryHeapResultReadback)
{
FAILED_DEBUG_BREAK(mD3D12ResourceQueryHeapResultReadback->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
break;
}
}
#endif
}
/**
* @brief
* Destructor
*/
virtual ~QueryPool() override
{
if (nullptr != mD3D12QueryHeap)
{
mD3D12QueryHeap->Release();
}
if (nullptr != mD3D12ResourceQueryHeapResultReadback)
{
mD3D12ResourceQueryHeapResultReadback->Release();
}
}
/**
* @brief
* Return the query type
*
* @return
* The query type
*/
[[nodiscard]] inline Rhi::QueryType getQueryType() const
{
return mQueryType;
}
/**
* @brief
* Return the number of queries
*
* @return
* The number of queries
*/
[[nodiscard]] inline uint32_t getNumberOfQueries() const
{
return mNumberOfQueries;
}
/**
* @brief
* Return the Direct3D 12 query heap
*
* @return
* The Direct3D 12 query heap
*/
[[nodiscard]] inline ID3D12QueryHeap* getD3D12QueryHeap() const
{
return mD3D12QueryHeap;
}
/**
* @brief
* Get asynchronous query pool results
*
* @param[in] numberOfDataBytes
* Number of data bytes
* @param[out] data
* Receives the query data
* @param[in] firstQueryIndex
* First query index (e.g. 0)
* @param[in] numberOfQueries
* Number of queries (e.g. 1)
* @param[in] strideInBytes
* Stride in bytes, 0 is only valid in case there's just a single query
* @param[in] d3d12GraphicsCommandList
* Direct3D 12 graphics command list
*/
void getQueryPoolResults([[maybe_unused]] uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex, uint32_t numberOfQueries, [[maybe_unused]] uint32_t strideInBytes, ID3D12GraphicsCommandList& d3d12GraphicsCommandList)
{
// Query pool type dependent processing
// -> We don't support "Rhi::QueryResultFlags::WAIT"
RHI_ASSERT(getRhi().getContext(), firstQueryIndex < mNumberOfQueries, "Direct3D 12 out-of-bounds query index")
RHI_ASSERT(getRhi().getContext(), (firstQueryIndex + numberOfQueries) <= mNumberOfQueries, "Direct3D 12 out-of-bounds query index")
D3D12_QUERY_TYPE d3d12QueryType = D3D12_QUERY_TYPE_OCCLUSION;
uint32_t numberOfBytesPerQuery = 0;
switch (mQueryType)
{
case Rhi::QueryType::OCCLUSION:
{
RHI_ASSERT(getRhi().getContext(), 1 == numberOfQueries || sizeof(uint64_t) == strideInBytes, "Direct3D 12 stride in bytes must be 8 bytes for occlusion query type")
d3d12QueryType = D3D12_QUERY_TYPE_OCCLUSION;
numberOfBytesPerQuery = sizeof(uint64_t);
break;
}
case Rhi::QueryType::PIPELINE_STATISTICS:
{
static_assert(sizeof(Rhi::PipelineStatisticsQueryResult) == sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS), "Direct3D 12 structure mismatch detected");
RHI_ASSERT(getRhi().getContext(), numberOfDataBytes >= sizeof(Rhi::PipelineStatisticsQueryResult), "Direct3D 12 out-of-memory query access")
RHI_ASSERT(getRhi().getContext(), 1 == numberOfQueries || strideInBytes >= sizeof(Rhi::PipelineStatisticsQueryResult), "Direct3D 12 out-of-memory query access")
RHI_ASSERT(getRhi().getContext(), 1 == numberOfQueries || sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == strideInBytes, "Direct3D 12 stride in bytes must be 88 bytes for pipeline statistics query type")
d3d12QueryType = D3D12_QUERY_TYPE_PIPELINE_STATISTICS;
numberOfBytesPerQuery = sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS);
break;
}
case Rhi::QueryType::TIMESTAMP: // TODO(co) Convert time to nanoseconds, see e.g. http://reedbeta.com/blog/gpu-profiling-101/
{
RHI_ASSERT(getRhi().getContext(), 1 == numberOfQueries || sizeof(uint64_t) == strideInBytes, "Direct3D 12 stride in bytes must be 8 bytes for timestamp query type")
d3d12QueryType = D3D12_QUERY_TYPE_TIMESTAMP;
numberOfBytesPerQuery = sizeof(uint64_t);
break;
}
}
{ // Resolve query data from the current frame
const uint64_t resolveToBaseAddress = static_cast<uint64_t>(numberOfBytesPerQuery) * mNumberOfQueries * mResolveToFrameNumber + static_cast<uint64_t>(numberOfBytesPerQuery) * firstQueryIndex;
d3d12GraphicsCommandList.ResolveQueryData(mD3D12QueryHeap, d3d12QueryType, firstQueryIndex, numberOfQueries, mD3D12ResourceQueryHeapResultReadback, resolveToBaseAddress);
}
// Readback query result by grabbing readback data for the queries from a finished frame "Direct3D12Rhi::NUMBER_OF_FRAMES" ago
// +1 = One more frame as an instance is guaranteed to be written to if "Direct3D12Rhi::NUMBER_OF_FRAMES" frames have been dispatched since. This is due to a fact that present stalls when none of the maximum number of frames are done/available.
const uint32_t readbackFrameNumber = (mResolveToFrameNumber + 1) % (Direct3D12Rhi::NUMBER_OF_FRAMES + 1);
const uint32_t readbackBaseOffset = numberOfBytesPerQuery * mNumberOfQueries * readbackFrameNumber + numberOfBytesPerQuery * firstQueryIndex;
const D3D12_RANGE d3d12Range = { readbackBaseOffset, readbackBaseOffset + numberOfBytesPerQuery * numberOfQueries };
uint64_t* timingData = nullptr;
FAILED_DEBUG_BREAK(mD3D12ResourceQueryHeapResultReadback->Map(0, &d3d12Range, reinterpret_cast<void**>(&timingData)))
memcpy(data, timingData, numberOfBytesPerQuery * numberOfQueries);
mD3D12ResourceQueryHeapResultReadback->Unmap(0, nullptr);
mResolveToFrameNumber = readbackFrameNumber;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), QueryPool, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit QueryPool(const QueryPool& source) = delete;
QueryPool& operator =(const QueryPool& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Rhi::QueryType mQueryType;
uint32_t mNumberOfQueries;
ID3D12QueryHeap* mD3D12QueryHeap;
ID3D12Resource* mD3D12ResourceQueryHeapResultReadback;
uint32_t mResolveToFrameNumber;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/RenderTarget/SwapChain.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 swap chain class
*/
class SwapChain final : public Rhi::ISwapChain
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] renderPass
* Render pass to use, the swap chain keeps a reference to the render pass
* @param[in] windowHandle
* Information about the window to render into
*/
SwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
ISwapChain(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mDxgiSwapChain3(nullptr),
mD3D12DescriptorHeapRenderTargetView(nullptr),
mD3D12DescriptorHeapDepthStencilView(nullptr),
mRenderTargetViewDescriptorSize(0),
mD3D12ResourceRenderTargets{},
mD3D12ResourceDepthStencil(nullptr),
mSynchronizationInterval(0),
mFrameIndex(0),
mFenceEvent(nullptr),
mD3D12Fence(nullptr),
mFenceValue(0)
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(renderPass.getRhi());
const RenderPass& d3d12RenderPass = static_cast<RenderPass&>(renderPass);
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), 1 == d3d12RenderPass.getNumberOfColorAttachments(), "There must be exactly one Direct3D 12 render pass color attachment")
// Get the native window handle
const HWND hWnd = reinterpret_cast<HWND>(windowHandle.nativeWindowHandle);
// Get our IDXGI factory instance
IDXGIFactory4& dxgiFactory4 = direct3D12Rhi.getDxgiFactory4();
// Get the width and height of the given native window and ensure they are never ever zero
// -> See "getSafeWidthAndHeight()"-method comments for details
long width = 1;
long height = 1;
{
// Get the client rectangle of the given native window
RECT rect;
::GetClientRect(hWnd, &rect);
// Get the width and height...
width = rect.right - rect.left;
height = rect.bottom - rect.top;
// ... and ensure that none of them is ever zero
if (width < 1)
{
width = 1;
}
if (height < 1)
{
height = 1;
}
}
// TODO(co) Add tearing support, see Direct3D 11 RHI implementation
// Determines whether tearing support is available for fullscreen borderless windows
// -> To unlock frame rates of UWP applications on the Windows Store and providing support for both AMD Freesync and NVIDIA's G-SYNC we must explicitly allow tearing
// -> See "Windows Dev Center" -> "Variable refresh rate displays": https://msdn.microsoft.com/en-us/library/windows/desktop/mt742104(v=vs.85).aspx
// Create the swap chain
DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc = {};
dxgiSwapChainDesc.BufferCount = Direct3D12Rhi::NUMBER_OF_FRAMES;
dxgiSwapChainDesc.BufferDesc.Width = static_cast<UINT>(width);
dxgiSwapChainDesc.BufferDesc.Height = static_cast<UINT>(height);
dxgiSwapChainDesc.BufferDesc.Format = Mapping::getDirect3D12Format(d3d12RenderPass.getColorAttachmentTextureFormat(0));
dxgiSwapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
dxgiSwapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
dxgiSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
dxgiSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
dxgiSwapChainDesc.OutputWindow = hWnd;
dxgiSwapChainDesc.SampleDesc.Count = 1;
dxgiSwapChainDesc.Windowed = TRUE;
IDXGISwapChain* dxgiSwapChain = nullptr;
FAILED_DEBUG_BREAK(dxgiFactory4.CreateSwapChain(direct3D12Rhi.getD3D12CommandQueue(), &dxgiSwapChainDesc, &dxgiSwapChain))
if (FAILED(dxgiSwapChain->QueryInterface(IID_PPV_ARGS(&mDxgiSwapChain3))))
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to retrieve the Direct3D 12 DXGI swap chain 3")
}
dxgiSwapChain->Release();
// Disable alt-return for automatic fullscreen state change
// -> We handle this manually to have more control over it
FAILED_DEBUG_BREAK(dxgiFactory4.MakeWindowAssociation(hWnd, DXGI_MWA_NO_ALT_ENTER))
// Create the Direct3D 12 views
if (nullptr != mDxgiSwapChain3)
{
createDirect3D12Views();
}
// Create synchronization objects
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&mD3D12Fence))))
{
mFenceValue = 1;
// Create an event handle to use for frame synchronization
mFenceEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != mFenceEvent, "Failed to create an Direct3D 12 event handle to use for frame synchronization. Error code %u", ::GetLastError())
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create Direct3D 12 fence instance")
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Swap chain", 13) // 13 = "Swap chain: " including terminating zero
// Assign a debug name to the DXGI swap chain
if (nullptr != mDxgiSwapChain3)
{
FAILED_DEBUG_BREAK(mDxgiSwapChain3->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
// Assign a debug name to the Direct3D 12 frame resources
for (int frame = 0; frame < Direct3D12Rhi::NUMBER_OF_FRAMES; ++frame)
{
if (nullptr != mD3D12ResourceRenderTargets[frame])
{
FAILED_DEBUG_BREAK(mD3D12ResourceRenderTargets[frame]->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
}
if (nullptr != mD3D12ResourceDepthStencil)
{
FAILED_DEBUG_BREAK(mD3D12ResourceDepthStencil->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
// Assign a debug name to the Direct3D 12 descriptor heaps
if (nullptr != mD3D12DescriptorHeapRenderTargetView)
{
FAILED_DEBUG_BREAK(mD3D12DescriptorHeapRenderTargetView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
if (nullptr != mD3D12DescriptorHeapDepthStencilView)
{
FAILED_DEBUG_BREAK(mD3D12DescriptorHeapDepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
}
#endif
}
/**
* @brief
* Destructor
*/
virtual ~SwapChain() override
{
// "DXGI Overview - Destroying a Swap Chain" at MSDN http://msdn.microsoft.com/en-us/library/bb205075.aspx states
// "You may not release a swap chain in full-screen mode because doing so may create thread contention (which will
// cause DXGI to raise a non-continuable exception). Before releasing a swap chain, first switch to windowed mode
// (using IDXGISwapChain::SetFullscreenState( FALSE, NULL )) and then call IUnknown::Release."
if (getFullscreenState())
{
setFullscreenState(false);
}
// Release the used resources
destroyDirect3D12Views();
if (nullptr != mDxgiSwapChain3)
{
mDxgiSwapChain3->Release();
}
// Destroy synchronization objects
if (nullptr != mFenceEvent)
{
::CloseHandle(mFenceEvent);
}
if (nullptr != mD3D12Fence)
{
mD3D12Fence->Release();
}
}
/**
* @brief
* Return the DXGI swap chain 3 instance
*
* @return
* The DXGI swap chain 3 instance, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline IDXGISwapChain3* getDxgiSwapChain3() const
{
return mDxgiSwapChain3;
}
/**
* @brief
* Return the Direct3D 12 render target view descriptor heap instance
*
* @return
* The Direct3D 12 render target view descriptor heap instance, null pointer on error, do not release the returned instance unless you added an own reference to it
*
* @note
* - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain
*/
[[nodiscard]] inline ID3D12DescriptorHeap* getD3D12DescriptorHeapRenderTargetView() const
{
return mD3D12DescriptorHeapRenderTargetView;
}
/**
* @brief
* Return the Direct3D 12 depth stencil view descriptor heap instance
*
* @return
* The Direct3D 12 depth stencil view descriptor heap instance, null pointer on error, do not release the returned instance unless you added an own reference to it
*
* @note
* - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain
*/
[[nodiscard]] inline ID3D12DescriptorHeap* getD3D12DescriptorHeapDepthStencilView() const
{
return mD3D12DescriptorHeapDepthStencilView;
}
/**
* @brief
* Return the render target view descriptor size
*
* @return
* The render target view descriptor size
*
* @note
* - It's highly recommended to not keep any backups of this value, else issues may occur when resizing the swap chain
*/
[[nodiscard]] inline UINT getRenderTargetViewDescriptorSize() const
{
return mRenderTargetViewDescriptorSize;
}
/**
* @brief
* Return the index of the Direct3D 12 resource render target which is currently used as back buffer
*
* @return
* The index of the Direct3D 12 resource render target which is currently used as back buffer
*
* @note
* - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain
*/
[[nodiscard]] inline UINT getBackD3D12ResourceRenderTargetFrameIndex() const
{
return mFrameIndex;
}
/**
* @brief
* Return the Direct3D 12 resource render target which is currently used as back buffer
*
* @return
* The Direct3D 12 resource render target which is currently used as back buffer, null pointer on error, do not release the returned instance unless you added an own reference to it
*
* @note
* - It's highly recommended to not keep any references to the returned instance, else issues may occur when resizing the swap chain
*/
[[nodiscard]] inline ID3D12Resource* getBackD3D12ResourceRenderTarget() const
{
return mD3D12ResourceRenderTargets[mFrameIndex];
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IRenderTarget methods ]
//[-------------------------------------------------------]
public:
virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override
{
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
// Get the Direct3D 12 swap chain description
DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc;
FAILED_DEBUG_BREAK(mDxgiSwapChain3->GetDesc(&dxgiSwapChainDesc))
// Get the width and height
long swapChainWidth = 1;
long swapChainHeight = 1;
{
// Get the client rectangle of the native output window
// -> Don't use the width and height stored in "DXGI_SWAP_CHAIN_DESC" -> "DXGI_MODE_DESC"
// because it might have been modified in order to avoid zero values
RECT rect;
::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect);
// Get the width and height...
swapChainWidth = rect.right - rect.left;
swapChainHeight = rect.bottom - rect.top;
// ... and ensure that none of them is ever zero
if (swapChainWidth < 1)
{
swapChainWidth = 1;
}
if (swapChainHeight < 1)
{
swapChainHeight = 1;
}
}
// Write out the width and height
width = static_cast<UINT>(swapChainWidth);
height = static_cast<UINT>(swapChainHeight);
}
else
{
// Set known default return values
width = 1;
height = 1;
}
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::ISwapChain methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] virtual Rhi::handle getNativeWindowHandle() const override
{
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
// Get the Direct3D 12 swap chain description
DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc;
FAILED_DEBUG_BREAK(mDxgiSwapChain3->GetDesc(&dxgiSwapChainDesc))
// Return the native window handle
return reinterpret_cast<Rhi::handle>(dxgiSwapChainDesc.OutputWindow);
}
// Error!
return NULL_HANDLE;
}
inline virtual void setVerticalSynchronizationInterval(uint32_t synchronizationInterval) override
{
mSynchronizationInterval = synchronizationInterval;
}
virtual void present() override
{
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
handleDeviceLost(static_cast<Direct3D12Rhi&>(getRenderPass().getRhi()), mDxgiSwapChain3->Present(mSynchronizationInterval, 0));
// Wait for the GPU to be done with all resources
waitForPreviousFrame();
}
}
virtual void resizeBuffers() override
{
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Get the currently set render target
Rhi::IRenderTarget* renderTargetBackup = direct3D12Rhi.omGetRenderTarget();
// In case this swap chain is the current render target, we have to unset it before continuing
if (this == renderTargetBackup)
{
direct3D12Rhi.setGraphicsRenderTarget(nullptr);
}
else
{
renderTargetBackup = nullptr;
}
// Release the views
destroyDirect3D12Views();
// Get the swap chain width and height, ensures they are never ever zero
UINT width = 1;
UINT height = 1;
getSafeWidthAndHeight(width, height);
// Resize the Direct3D 12 swap chain
// -> Preserve the existing buffer count and format
const HRESULT result = mDxgiSwapChain3->ResizeBuffers(Direct3D12Rhi::NUMBER_OF_FRAMES, width, height, Mapping::getDirect3D12Format(static_cast<RenderPass&>(getRenderPass()).getColorAttachmentTextureFormat(0)), 0);
if (SUCCEEDED(result))
{
// Create the Direct3D 12 views
// TODO(co) Rescue and reassign the resource debug name
createDirect3D12Views();
// If required, restore the previously set render target
if (nullptr != renderTargetBackup)
{
direct3D12Rhi.setGraphicsRenderTarget(renderTargetBackup);
}
}
else
{
handleDeviceLost(direct3D12Rhi, result);
}
}
}
[[nodiscard]] virtual bool getFullscreenState() const override
{
// Window mode by default
BOOL fullscreen = FALSE;
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
FAILED_DEBUG_BREAK(mDxgiSwapChain3->GetFullscreenState(&fullscreen, nullptr))
}
// Done
return (FALSE != fullscreen);
}
virtual void setFullscreenState(bool fullscreen) override
{
// Is there a valid swap chain?
if (nullptr != mDxgiSwapChain3)
{
const HRESULT result = mDxgiSwapChain3->SetFullscreenState(fullscreen, nullptr);
if (FAILED(result))
{
// TODO(co) Better error handling
RHI_ASSERT(static_cast<Direct3D12Rhi&>(getRhi()).getContext(), false, "Failed to set Direct3D 12 fullscreen state")
}
}
}
inline virtual void setRenderWindow([[maybe_unused]] Rhi::IRenderWindow* renderWindow) override
{
// TODO(sw) implement me
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), SwapChain, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit SwapChain(const SwapChain& source) = delete;
SwapChain& operator =(const SwapChain& source) = delete;
/**
* @brief
* Return the swap chain width and height
*
* @param[out] width
* Receives the swap chain width
* @param[out] height
* Receives the swap chain height
*
* @remarks
* For instance "IDXGISwapChain::ResizeBuffers()" can automatically choose the width and height to match the client
* rectangle of the native window, but as soon as the width or height is zero we will get the error message
* "DXGI Error: The buffer height inferred from the output window is zero. Taking 8 as a reasonable default instead"
* "D3D12: ERROR: ID3D12Device::CreateTexture2D: The Dimensions are invalid. For feature level D3D_FEATURE_LEVEL_12_0,
* the Width (value = 116) must be between 1 and 16384, inclusively. The Height (value = 0) must be between 1 and 16384,
* inclusively. And, the ArraySize (value = 1) must be between 1 and 2048, inclusively. [ STATE_CREATION ERROR #101: CREATETEXTURE2D_INVALIDDIMENSIONS ]"
* including an evil memory leak. So, best to use this method which gets the width and height of the native output
* window manually and ensures it's never zero.
*
* @note
* - "mDxgiSwapChain3" must be valid when calling this method
*/
void getSafeWidthAndHeight(uint32_t& width, uint32_t& height) const
{
// Get the Direct3D 12 swap chain description
DXGI_SWAP_CHAIN_DESC dxgiSwapChainDesc;
FAILED_DEBUG_BREAK(mDxgiSwapChain3->GetDesc(&dxgiSwapChainDesc))
// Get the client rectangle of the native output window
RECT rect;
::GetClientRect(dxgiSwapChainDesc.OutputWindow, &rect);
// Get the width and height...
long swapChainWidth = rect.right - rect.left;
long swapChainHeight = rect.bottom - rect.top;
// ... and ensure that none of them is ever zero
if (swapChainWidth < 1)
{
swapChainWidth = 1;
}
if (swapChainHeight < 1)
{
swapChainHeight = 1;
}
// Write out the width and height
width = static_cast<UINT>(swapChainWidth);
height = static_cast<UINT>(swapChainHeight);
}
/**
* @brief
* Create the Direct3D 12 views
*/
void createDirect3D12Views()
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != mDxgiSwapChain3, "Invalid Direct3D 12 DXGI swap chain 3")
// TODO(co) Debug name gets lost when resizing a window, fix this
// Get the Direct3D 12 device instance
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
{ // Describe and create a render target view (RTV) descriptor heap
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = Direct3D12Rhi::NUMBER_OF_FRAMES;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
d3d12DescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(&mD3D12DescriptorHeapRenderTargetView))))
{
mRenderTargetViewDescriptorSize = d3d12Device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
{ // Create frame resources
CD3DX12_CPU_DESCRIPTOR_HANDLE d3d12XCpuDescriptorHandle(mD3D12DescriptorHeapRenderTargetView->GetCPUDescriptorHandleForHeapStart());
// Create a RTV for each frame
for (UINT frame = 0; frame < Direct3D12Rhi::NUMBER_OF_FRAMES; ++frame)
{
if (SUCCEEDED(mDxgiSwapChain3->GetBuffer(frame, IID_PPV_ARGS(&mD3D12ResourceRenderTargets[frame]))))
{
d3d12Device.CreateRenderTargetView(mD3D12ResourceRenderTargets[frame], nullptr, d3d12XCpuDescriptorHandle);
d3d12XCpuDescriptorHandle.Offset(1, mRenderTargetViewDescriptorSize);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to retrieve frame buffer from Direct3D 12 DXGI swap chain")
}
}
}
mFrameIndex = mDxgiSwapChain3->GetCurrentBackBufferIndex();
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to describe and create a Direct3D 12 render target view (RTV) descriptor heap")
}
}
// Describe and create a depth stencil view (DSV) descriptor heap
const Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat = static_cast<RenderPass&>(getRenderPass()).getDepthStencilAttachmentTextureFormat();
if (Rhi::TextureFormat::Enum::UNKNOWN != depthStencilAttachmentTextureFormat)
{
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = 1;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
d3d12DescriptorHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(&mD3D12DescriptorHeapDepthStencilView))))
{
D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
depthStencilDesc.Format = Mapping::getDirect3D12Format(depthStencilAttachmentTextureFormat);
depthStencilDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
depthStencilDesc.Flags = D3D12_DSV_FLAG_NONE;
D3D12_CLEAR_VALUE depthOptimizedClearValue = {};
depthOptimizedClearValue.Format = depthStencilDesc.Format;
depthOptimizedClearValue.DepthStencil.Depth = 0.0f; // z = 0 instead of 1 due to usage of Reversed-Z (see e.g. https://developer.nvidia.com/content/depth-precision-visualized and https://nlguillemot.wordpress.com/2016/12/07/reversed-z-in-opengl/)
depthOptimizedClearValue.DepthStencil.Stencil = 0;
// Get the swap chain width and height, ensures they are never ever zero
UINT width = 1;
UINT height = 1;
getSafeWidthAndHeight(width, height);
const CD3DX12_HEAP_PROPERTIES d3d12XHeapProperties(D3D12_HEAP_TYPE_DEFAULT);
const CD3DX12_RESOURCE_DESC d3d12XResourceDesc = CD3DX12_RESOURCE_DESC::Tex2D(depthStencilDesc.Format, width, height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
if (SUCCEEDED(d3d12Device.CreateCommittedResource(
&d3d12XHeapProperties,
D3D12_HEAP_FLAG_NONE,
&d3d12XResourceDesc,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
&depthOptimizedClearValue,
IID_PPV_ARGS(&mD3D12ResourceDepthStencil)
)))
{
d3d12Device.CreateDepthStencilView(mD3D12ResourceDepthStencil, &depthStencilDesc, mD3D12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart());
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create the Direct3D 12 depth stencil view (DSV) resource")
}
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to describe and create a Direct3D 12 depth stencil view (DSV) descriptor heap")
}
}
}
/**
* @brief
* Destroy the Direct3D 12 views
*/
void destroyDirect3D12Views()
{
// Wait for the GPU to be done with all resources
waitForPreviousFrame();
// Release Direct3D 12 resources
for (int frame = 0; frame < Direct3D12Rhi::NUMBER_OF_FRAMES; ++frame)
{
if (nullptr != mD3D12ResourceRenderTargets[frame])
{
mD3D12ResourceRenderTargets[frame]->Release();
mD3D12ResourceRenderTargets[frame] = nullptr;
}
}
if (nullptr != mD3D12ResourceDepthStencil)
{
mD3D12ResourceDepthStencil->Release();
mD3D12ResourceDepthStencil = nullptr;
}
// Release Direct3D 12 descriptor heap
if (nullptr != mD3D12DescriptorHeapRenderTargetView)
{
mD3D12DescriptorHeapRenderTargetView->Release();
mD3D12DescriptorHeapRenderTargetView = nullptr;
}
if (nullptr != mD3D12DescriptorHeapDepthStencilView)
{
mD3D12DescriptorHeapDepthStencilView->Release();
mD3D12DescriptorHeapDepthStencilView = nullptr;
}
}
/**
* @brief
* Wait for the GPU to be done with all resources
*/
void waitForPreviousFrame()
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != mDxgiSwapChain3, "Invalid Direct3D 12 DXGI swap chain 3")
// TODO(co) This is the most simple but least effective approach and only meant for the Direct3D 12 RHI implementation kickoff.
// Signal and increment the fence value
const UINT64 fence = mFenceValue;
if (SUCCEEDED(direct3D12Rhi.getD3D12CommandQueue()->Signal(mD3D12Fence, fence)))
{
++mFenceValue;
// Wait until the previous frame is finished
if (mD3D12Fence->GetCompletedValue() < fence)
{
if (SUCCEEDED(mD3D12Fence->SetEventOnCompletion(fence, mFenceEvent)))
{
::WaitForSingleObject(mFenceEvent, INFINITE);
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to set Direct3D 12 event on completion")
}
}
mFrameIndex = mDxgiSwapChain3->GetCurrentBackBufferIndex();
}
}
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
IDXGISwapChain3* mDxgiSwapChain3; ///< The DXGI swap chain 3 instance, null pointer on error
ID3D12DescriptorHeap* mD3D12DescriptorHeapRenderTargetView; ///< The Direct3D 12 render target view descriptor heap instance, null pointer on error
ID3D12DescriptorHeap* mD3D12DescriptorHeapDepthStencilView; ///< The Direct3D 12 depth stencil view descriptor heap instance, null pointer on error
UINT mRenderTargetViewDescriptorSize; ///< Render target view descriptor size
ID3D12Resource* mD3D12ResourceRenderTargets[Direct3D12Rhi::NUMBER_OF_FRAMES]; ///< The Direct3D 12 render target instances, null pointer on error
ID3D12Resource* mD3D12ResourceDepthStencil; ///< The Direct3D 12 depth stencil instance, null pointer on error
// Synchronization objects
uint32_t mSynchronizationInterval;
UINT mFrameIndex;
HANDLE mFenceEvent;
ID3D12Fence* mD3D12Fence;
UINT64 mFenceValue;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/RenderTarget/Framebuffer.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 framebuffer class
*
* @todo
* - TODO(co) "D3D12GraphicsCommandList::OMSetRenderTargets()" supports using a single Direct3D 12 render target view descriptor heap instance with multiple targets in it, use it
*/
class Framebuffer final : public Rhi::IFramebuffer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] renderPass
* Render pass to use, the swap chain keeps a reference to the render pass
* @param[in] colorFramebufferAttachments
* The color render target textures, can be a null pointer or can contain null pointers, if not a null pointer there must be at
* least "Rhi::IRenderPass::getNumberOfColorAttachments()" textures in the provided C-array of pointers
* @param[in] depthStencilFramebufferAttachment
* The depth stencil render target texture, can be a null pointer
*
* @note
* - The framebuffer keeps a reference to the provided texture instances
*/
Framebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IFramebuffer(renderPass RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mNumberOfColorTextures(static_cast<RenderPass&>(renderPass).getNumberOfColorAttachments()),
mColorTextures(nullptr), // Set below
mDepthStencilTexture(nullptr),
mWidth(UINT_MAX),
mHeight(UINT_MAX),
mD3D12DescriptorHeapRenderTargetViews(nullptr),
mD3D12DescriptorHeapDepthStencilView(nullptr)
{
// Get the Direct3D 12 device instance
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(renderPass.getRhi());
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
// Add a reference to the used color textures
if (mNumberOfColorTextures > 0)
{
const Rhi::Context& context = direct3D12Rhi.getContext();
mColorTextures = RHI_MALLOC_TYPED(context, Rhi::ITexture*, mNumberOfColorTextures);
mD3D12DescriptorHeapRenderTargetViews = RHI_MALLOC_TYPED(context, ID3D12DescriptorHeap*, mNumberOfColorTextures);
// Loop through all color textures
ID3D12DescriptorHeap** d3d12DescriptorHeapRenderTargetView = mD3D12DescriptorHeapRenderTargetViews;
Rhi::ITexture** colorTexturesEnd = mColorTextures + mNumberOfColorTextures;
for (Rhi::ITexture** colorTexture = mColorTextures; colorTexture < colorTexturesEnd; ++colorTexture, ++colorFramebufferAttachments, ++d3d12DescriptorHeapRenderTargetView)
{
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != colorFramebufferAttachments->texture, "Invalid Direct3D 12 color framebuffer attachment texture")
// TODO(co) Add security check: Is the given resource one of the currently used RHI?
*colorTexture = colorFramebufferAttachments->texture;
(*colorTexture)->addReference();
// Evaluate the color texture type
switch ((*colorTexture)->getResourceType())
{
case Rhi::ResourceType::TEXTURE_2D:
{
const Texture2D* texture2D = static_cast<Texture2D*>(*colorTexture);
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), colorFramebufferAttachments->mipmapIndex < Rhi::ITexture2D::getNumberOfMipmaps(texture2D->getWidth(), texture2D->getHeight()), "Invalid Direct3D 12 color framebuffer attachment mipmap index")
RHI_ASSERT(direct3D12Rhi.getContext(), 0 == colorFramebufferAttachments->layerIndex, "Invalid Direct3D 12 color framebuffer attachment layer index")
// Update the framebuffer width and height if required
::detail::updateWidthHeight(colorFramebufferAttachments->mipmapIndex, texture2D->getWidth(), texture2D->getHeight(), mWidth, mHeight);
// Get the Direct3D 12 resource
ID3D12Resource* d3d12Resource = texture2D->getD3D12Resource();
// Create the Direct3D 12 render target view instance
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = 1;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(d3d12DescriptorHeapRenderTargetView))))
{
D3D12_RENDER_TARGET_VIEW_DESC d3d12RenderTargetViewDesc = {};
d3d12RenderTargetViewDesc.Format = static_cast<DXGI_FORMAT>(texture2D->getDxgiFormat());
d3d12RenderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
d3d12RenderTargetViewDesc.Texture2D.MipSlice = colorFramebufferAttachments->mipmapIndex;
d3d12Device.CreateRenderTargetView(d3d12Resource, &d3d12RenderTargetViewDesc, (*d3d12DescriptorHeapRenderTargetView)->GetCPUDescriptorHandleForHeapStart());
}
break;
}
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
{
// Update the framebuffer width and height if required
const Texture2DArray* texture2DArray = static_cast<Texture2DArray*>(*colorTexture);
::detail::updateWidthHeight(colorFramebufferAttachments->mipmapIndex, texture2DArray->getWidth(), texture2DArray->getHeight(), mWidth, mHeight);
// Get the Direct3D 12 resource
ID3D12Resource* d3d12Resource = texture2DArray->getD3D12Resource();
// Create the Direct3D 12 render target view instance
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = 1;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(d3d12DescriptorHeapRenderTargetView))))
{
D3D12_RENDER_TARGET_VIEW_DESC d3d12RenderTargetViewDesc = {};
d3d12RenderTargetViewDesc.Format = static_cast<DXGI_FORMAT>(texture2DArray->getDxgiFormat());
d3d12RenderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
d3d12RenderTargetViewDesc.Texture2DArray.MipSlice = colorFramebufferAttachments->mipmapIndex;
d3d12RenderTargetViewDesc.Texture2DArray.FirstArraySlice = colorFramebufferAttachments->layerIndex;
d3d12RenderTargetViewDesc.Texture2DArray.ArraySize = 1;
d3d12RenderTargetViewDesc.Texture2DArray.PlaneSlice = 0;
d3d12Device.CreateRenderTargetView(d3d12Resource, &d3d12RenderTargetViewDesc, (*d3d12DescriptorHeapRenderTargetView)->GetCPUDescriptorHandleForHeapStart());
}
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
RHI_ASSERT(direct3D12Rhi.getContext(), false, "The type of the given color texture at index %u is not supported by the Direct3D 12 RHI implementation", colorTexture - mColorTextures)
*d3d12DescriptorHeapRenderTargetView = nullptr;
break;
}
}
}
// Add a reference to the used depth stencil texture
if (nullptr != depthStencilFramebufferAttachment)
{
mDepthStencilTexture = depthStencilFramebufferAttachment->texture;
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != mDepthStencilTexture, "Invalid Direct3D 12 depth stencil framebuffer attachment texture")
mDepthStencilTexture->addReference();
// Evaluate the depth stencil texture type
switch (mDepthStencilTexture->getResourceType())
{
case Rhi::ResourceType::TEXTURE_2D:
{
const Texture2D* texture2D = static_cast<Texture2D*>(mDepthStencilTexture);
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), depthStencilFramebufferAttachment->mipmapIndex < Rhi::ITexture2D::getNumberOfMipmaps(texture2D->getWidth(), texture2D->getHeight()), "Invalid Direct3D 12 depth stencil framebuffer attachment mipmap index")
RHI_ASSERT(direct3D12Rhi.getContext(), 0 == depthStencilFramebufferAttachment->layerIndex, "Invalid Direct3D 12 depth stencil framebuffer attachment layer index")
// Update the framebuffer width and height if required
::detail::updateWidthHeight(depthStencilFramebufferAttachment->mipmapIndex, texture2D->getWidth(), texture2D->getHeight(), mWidth, mHeight);
// Get the Direct3D 12 resource
ID3D12Resource* d3d12Resource = texture2D->getD3D12Resource();
// Create the Direct3D 12 render target view instance
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = 1;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(&mD3D12DescriptorHeapDepthStencilView))))
{
D3D12_RENDER_TARGET_VIEW_DESC d3d12RenderTargetViewDesc = {};
d3d12RenderTargetViewDesc.Format = static_cast<DXGI_FORMAT>(texture2D->getDxgiFormat());
d3d12RenderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
d3d12RenderTargetViewDesc.Texture2D.MipSlice = depthStencilFramebufferAttachment->mipmapIndex;
d3d12Device.CreateRenderTargetView(d3d12Resource, &d3d12RenderTargetViewDesc, mD3D12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart());
}
break;
}
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
{
// Update the framebuffer width and height if required
const Texture2DArray* texture2DArray = static_cast<Texture2DArray*>(mDepthStencilTexture);
::detail::updateWidthHeight(depthStencilFramebufferAttachment->mipmapIndex, texture2DArray->getWidth(), texture2DArray->getHeight(), mWidth, mHeight);
// Get the Direct3D 12 resource
ID3D12Resource* d3d12Resource = texture2DArray->getD3D12Resource();
// Create the Direct3D 12 render target view instance
D3D12_DESCRIPTOR_HEAP_DESC d3d12DescriptorHeapDesc = {};
d3d12DescriptorHeapDesc.NumDescriptors = 1;
d3d12DescriptorHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
if (SUCCEEDED(d3d12Device.CreateDescriptorHeap(&d3d12DescriptorHeapDesc, IID_PPV_ARGS(&mD3D12DescriptorHeapDepthStencilView))))
{
D3D12_RENDER_TARGET_VIEW_DESC d3d12RenderTargetViewDesc = {};
d3d12RenderTargetViewDesc.Format = static_cast<DXGI_FORMAT>(texture2DArray->getDxgiFormat());
d3d12RenderTargetViewDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
d3d12RenderTargetViewDesc.Texture2DArray.MipSlice = depthStencilFramebufferAttachment->mipmapIndex;
d3d12RenderTargetViewDesc.Texture2DArray.FirstArraySlice = depthStencilFramebufferAttachment->layerIndex;
d3d12RenderTargetViewDesc.Texture2DArray.ArraySize = 1;
d3d12RenderTargetViewDesc.Texture2DArray.PlaneSlice = 0;
d3d12Device.CreateRenderTargetView(d3d12Resource, &d3d12RenderTargetViewDesc, mD3D12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart());
}
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
RHI_ASSERT(direct3D12Rhi.getContext(), false, "The type of the given depth stencil texture is not supported by the Direct3D 12 RHI implementation")
break;
}
}
// Validate the framebuffer width and height
if (0 == mWidth || UINT_MAX == mWidth)
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Invalid Direct3D 12 framebuffer width")
mWidth = 1;
}
if (0 == mHeight || UINT_MAX == mHeight)
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Invalid Direct3D 12 framebuffer height")
mHeight = 1;
}
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "FBO", 6) // 6 = "FBO: " including terminating zero
const size_t detailedDebugNameLength = strlen(detailedDebugName);
{ // Assign a debug name to the Direct3D 12 render target view, do also add the index to the name
const size_t adjustedDetailedDebugNameLength = detailedDebugNameLength + 5; // Direct3D 12 supports 8 render targets ("D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT", so: One digit + one [ + one ] + one space + terminating zero = 5 characters)
const Rhi::Context& context = direct3D12Rhi.getContext();
char* nameWithIndex = RHI_MALLOC_TYPED(context, char, detailedDebugNameLength);
ID3D12DescriptorHeap** d3d12DescriptorHeapRenderTargetViewsEnd = mD3D12DescriptorHeapRenderTargetViews + mNumberOfColorTextures;
for (ID3D12DescriptorHeap** d3d12DescriptorHeapRenderTargetView = mD3D12DescriptorHeapRenderTargetViews; d3d12DescriptorHeapRenderTargetView < d3d12DescriptorHeapRenderTargetViewsEnd; ++d3d12DescriptorHeapRenderTargetView)
{
sprintf_s(nameWithIndex, detailedDebugNameLength, "%s [%u]", detailedDebugName, static_cast<uint32_t>(d3d12DescriptorHeapRenderTargetView - mD3D12DescriptorHeapRenderTargetViews));
FAILED_DEBUG_BREAK((*d3d12DescriptorHeapRenderTargetView)->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(adjustedDetailedDebugNameLength), nameWithIndex))
}
RHI_FREE(context, nameWithIndex);
}
// Assign a debug name to the Direct3D 12 depth stencil view
if (nullptr != mD3D12DescriptorHeapDepthStencilView)
{
FAILED_DEBUG_BREAK(mD3D12DescriptorHeapDepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(detailedDebugNameLength), detailedDebugName))
}
#endif
}
/**
* @brief
* Destructor
*/
virtual ~Framebuffer() override
{
// Release the reference to the used color textures
const Rhi::Context& context = getRhi().getContext();
if (nullptr != mD3D12DescriptorHeapRenderTargetViews)
{
// Release references
ID3D12DescriptorHeap** d3d12DescriptorHeapRenderTargetViewsEnd = mD3D12DescriptorHeapRenderTargetViews + mNumberOfColorTextures;
for (ID3D12DescriptorHeap** d3d12DescriptorHeapRenderTargetView = mD3D12DescriptorHeapRenderTargetViews; d3d12DescriptorHeapRenderTargetView < d3d12DescriptorHeapRenderTargetViewsEnd; ++d3d12DescriptorHeapRenderTargetView)
{
(*d3d12DescriptorHeapRenderTargetView)->Release();
}
// Cleanup
RHI_FREE(context, mD3D12DescriptorHeapRenderTargetViews);
}
if (nullptr != mColorTextures)
{
// Release references
Rhi::ITexture** colorTexturesEnd = mColorTextures + mNumberOfColorTextures;
for (Rhi::ITexture** colorTexture = mColorTextures; colorTexture < colorTexturesEnd; ++colorTexture)
{
(*colorTexture)->releaseReference();
}
// Cleanup
RHI_FREE(context, mColorTextures);
}
// Release the reference to the used depth stencil texture
if (nullptr != mD3D12DescriptorHeapDepthStencilView)
{
// Release reference
mD3D12DescriptorHeapDepthStencilView->Release();
}
if (nullptr != mDepthStencilTexture)
{
// Release reference
mDepthStencilTexture->releaseReference();
}
}
/**
* @brief
* Return the number of color textures
*
* @return
* The number of color textures
*/
[[nodiscard]] inline uint32_t getNumberOfColorTextures() const
{
return mNumberOfColorTextures;
}
/**
* @brief
* Return the color textures
*
* @return
* The color textures, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline Rhi::ITexture** getColorTextures() const
{
return mColorTextures;
}
/**
* @brief
* Return the depth stencil texture
*
* @return
* The depth stencil texture, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline Rhi::ITexture* getDepthStencilTexture() const
{
return mDepthStencilTexture;
}
/**
* @brief
* Return the Direct3D 12 render target view descriptor heap instance
*
* @return
* The Direct3D 12 render target view descriptor heap instance, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12DescriptorHeap** getD3D12DescriptorHeapRenderTargetViews() const
{
return mD3D12DescriptorHeapRenderTargetViews;
}
/**
* @brief
* Return the Direct3D 12 depth stencil view descriptor heap instance
*
* @return
* The Direct3D 12 depth stencil view descriptor heap instance, null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12DescriptorHeap* getD3D12DescriptorHeapDepthStencilView() const
{
return mD3D12DescriptorHeapDepthStencilView;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IRenderTarget methods ]
//[-------------------------------------------------------]
public:
inline virtual void getWidthAndHeight(uint32_t& width, uint32_t& height) const override
{
// No fancy implementation in here, just copy over the internal information
width = mWidth;
height = mHeight;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), Framebuffer, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Framebuffer(const Framebuffer& source) = delete;
Framebuffer& operator =(const Framebuffer& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
// Generic part
uint32_t mNumberOfColorTextures; ///< Number of color render target textures
Rhi::ITexture** mColorTextures; ///< The color render target textures (we keep a reference to it), can be a null pointer or can contain null pointers, if not a null pointer there must be at least "m_nNumberOfColorTextures" textures in the provided C-array of pointers
Rhi::ITexture* mDepthStencilTexture; ///< The depth stencil render target texture (we keep a reference to it), can be a null pointer
uint32_t mWidth; ///< The framebuffer width
uint32_t mHeight; ///< The framebuffer height
// Direct3D 12 part
ID3D12DescriptorHeap** mD3D12DescriptorHeapRenderTargetViews; ///< The Direct3D 12 render target view descriptor heap instance, null pointer on error
ID3D12DescriptorHeap* mD3D12DescriptorHeapDepthStencilView; ///< The Direct3D 12 depth stencil view descriptor heap instance, null pointer on error
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/VertexShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL vertex shader class
*/
class VertexShaderHlsl final : public Rhi::IVertexShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a vertex shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
VertexShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IVertexShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobVertexShader(nullptr)
{
// Backup the vertex shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobVertexShader))
memcpy(mD3DBlobVertexShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a vertex shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
VertexShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IVertexShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobVertexShader(nullptr)
{
// Create the Direct3D 12 binary large object for the vertex shader
mD3DBlobVertexShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "vs_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobVertexShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobVertexShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~VertexShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobVertexShader)
{
mD3DBlobVertexShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 vertex shader blob
*
* @return
* Direct3D 12 vertex shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobVertexShader() const
{
return mD3DBlobVertexShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), VertexShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit VertexShaderHlsl(const VertexShaderHlsl& source) = delete;
VertexShaderHlsl& operator =(const VertexShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobVertexShader; ///< Direct3D 12 vertex shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/TessellationControlShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL tessellation control shader ("hull shader" in Direct3D terminology) class
*/
class TessellationControlShaderHlsl final : public Rhi::ITessellationControlShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a tessellation control shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
TessellationControlShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITessellationControlShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobHullShader(nullptr)
{
// Backup the hull shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobHullShader))
memcpy(mD3DBlobHullShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a tessellation control shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
TessellationControlShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITessellationControlShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobHullShader(nullptr)
{
// Create the Direct3D 12 binary large object for the hull shader
mD3DBlobHullShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "hs_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobHullShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobHullShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
inline virtual ~TessellationControlShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobHullShader)
{
mD3DBlobHullShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 hull shader blob
*
* @return
* Direct3D 12 hull shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobHullShader() const
{
return mD3DBlobHullShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TessellationControlShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TessellationControlShaderHlsl(const TessellationControlShaderHlsl& source) = delete;
TessellationControlShaderHlsl& operator =(const TessellationControlShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobHullShader; ///< Direct3D 12 hull shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/TessellationEvaluationShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL tessellation evaluation shader ("domain shader" in Direct3D terminology) class
*/
class TessellationEvaluationShaderHlsl final : public Rhi::ITessellationEvaluationShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a tessellation evaluation shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
TessellationEvaluationShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITessellationEvaluationShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobDomainShader(nullptr)
{
// Backup the domain shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobDomainShader))
memcpy(mD3DBlobDomainShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a tessellation evaluation shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
TessellationEvaluationShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITessellationEvaluationShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobDomainShader(nullptr)
{
// Create the Direct3D 12 binary large object for the domain shader
mD3DBlobDomainShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "ds_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobDomainShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobDomainShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~TessellationEvaluationShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobDomainShader)
{
mD3DBlobDomainShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 domain shader blob
*
* @return
* Direct3D 12 domain shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobDomainShader() const
{
return mD3DBlobDomainShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TessellationEvaluationShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TessellationEvaluationShaderHlsl(const TessellationEvaluationShaderHlsl& source) = delete;
TessellationEvaluationShaderHlsl& operator =(const TessellationEvaluationShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobDomainShader; ///< Direct3D 12 domain shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/GeometryShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL geometry shader class
*/
class GeometryShaderHlsl final : public Rhi::IGeometryShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a geometry shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
GeometryShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IGeometryShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobGeometryShader(nullptr)
{
// Backup the geometry shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobGeometryShader))
memcpy(mD3DBlobGeometryShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a geometry shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
GeometryShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IGeometryShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobGeometryShader(nullptr)
{
// Create the Direct3D 12 binary large object for the geometry shader
mD3DBlobGeometryShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "gs_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobGeometryShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobGeometryShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~GeometryShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobGeometryShader)
{
mD3DBlobGeometryShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 geometry shader blob
*
* @return
* Direct3D 12 geometry shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobGeometryShader() const
{
return mD3DBlobGeometryShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), GeometryShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit GeometryShaderHlsl(const GeometryShaderHlsl& source) = delete;
GeometryShaderHlsl& operator =(const GeometryShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobGeometryShader; ///< Direct3D 12 geometry shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/FragmentShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL fragment shader class (FS, "pixel shader" in Direct3D terminology)
*/
class FragmentShaderHlsl final : public Rhi::IFragmentShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a fragment shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
FragmentShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IFragmentShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobFragmentShader(nullptr)
{
// Backup the fragment shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobFragmentShader))
memcpy(mD3DBlobFragmentShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a fragment shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
FragmentShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IFragmentShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobFragmentShader(nullptr)
{
// Create the Direct3D 12 binary large object for the fragment shader
mD3DBlobFragmentShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "ps_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobFragmentShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobFragmentShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~FragmentShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobFragmentShader)
{
mD3DBlobFragmentShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 fragment shader blob
*
* @return
* Direct3D 12 fragment shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobFragmentShader() const
{
return mD3DBlobFragmentShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), FragmentShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit FragmentShaderHlsl(const FragmentShaderHlsl& source) = delete;
FragmentShaderHlsl& operator =(const FragmentShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobFragmentShader; ///< Direct3D 12 mesh shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/TaskShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL task shader class (TS, "amplification shader" in Direct3D terminology)
*/
class TaskShaderHlsl final : public Rhi::ITaskShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a task shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
TaskShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITaskShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobTaskShader(nullptr)
{
// Backup the task shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobTaskShader))
memcpy(mD3DBlobTaskShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a task shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
TaskShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
ITaskShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobTaskShader(nullptr)
{
// Create the Direct3D 12 binary large object for the task shader
mD3DBlobTaskShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "ps_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobTaskShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobTaskShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~TaskShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobTaskShader)
{
mD3DBlobTaskShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 task shader blob
*
* @return
* Direct3D 12 task shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobTaskShader() const
{
return mD3DBlobTaskShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), TaskShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit TaskShaderHlsl(const TaskShaderHlsl& source) = delete;
TaskShaderHlsl& operator =(const TaskShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobTaskShader; ///< Direct3D 12 task shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/MeshShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL mesh shader class (MS)
*/
class MeshShaderHlsl final : public Rhi::IMeshShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a mesh shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
MeshShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IMeshShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobMeshShader(nullptr)
{
// Backup the mesh shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobMeshShader))
memcpy(mD3DBlobMeshShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a mesh shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
MeshShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IMeshShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobMeshShader(nullptr)
{
// Create the Direct3D 12 binary large object for the mesh shader
mD3DBlobMeshShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "ps_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobMeshShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobMeshShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~MeshShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobMeshShader)
{
mD3DBlobMeshShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 mesh shader blob
*
* @return
* Direct3D 12 mesh shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobMeshShader() const
{
return mD3DBlobMeshShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), MeshShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit MeshShaderHlsl(const MeshShaderHlsl& source) = delete;
MeshShaderHlsl& operator =(const MeshShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobMeshShader; ///< Direct3D 12 mesh shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/ComputeShaderHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL compute shader class (CS)
*/
class ComputeShaderHlsl final : public Rhi::IComputeShader
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for creating a compute shader from shader bytecode
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] shaderBytecode
* Shader bytecode
*/
ComputeShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IComputeShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobComputeShader(nullptr)
{
// Backup the compute shader bytecode
FAILED_DEBUG_BREAK(D3DCreateBlob(shaderBytecode.getNumberOfBytes(), &mD3DBlobComputeShader))
memcpy(mD3DBlobComputeShader->GetBufferPointer(), shaderBytecode.getBytecode(), shaderBytecode.getNumberOfBytes());
}
/**
* @brief
* Constructor for creating a compute shader from shader source code
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] sourceCode
* Shader ASCII source code, must be valid
*/
ComputeShaderHlsl(Direct3D12Rhi& direct3D12Rhi, const char* sourceCode, Rhi::IShaderLanguage::OptimizationLevel optimizationLevel, Rhi::ShaderBytecode* shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IComputeShader(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3DBlobComputeShader(nullptr)
{
// Create the Direct3D 12 binary large object for the compute shader
mD3DBlobComputeShader = loadShaderFromSourcecode(direct3D12Rhi.getContext(), "cs_5_0", sourceCode, nullptr, optimizationLevel);
// Return shader bytecode, if requested do to so
if (nullptr != shaderBytecode)
{
shaderBytecode->setBytecodeCopy(static_cast<uint32_t>(mD3DBlobComputeShader->GetBufferSize()), static_cast<uint8_t*>(mD3DBlobComputeShader->GetBufferPointer()));
}
}
/**
* @brief
* Destructor
*/
virtual ~ComputeShaderHlsl() override
{
// Release the Direct3D 12 shader binary large object
if (nullptr != mD3DBlobComputeShader)
{
mD3DBlobComputeShader->Release();
}
}
/**
* @brief
* Return the Direct3D 12 compute shader blob
*
* @return
* Direct3D 12 compute shader blob, can be a null pointer on error, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3DBlob* getD3DBlobComputeShader() const
{
return mD3DBlobComputeShader;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShader methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), ComputeShaderHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit ComputeShaderHlsl(const ComputeShaderHlsl& source) = delete;
ComputeShaderHlsl& operator =(const ComputeShaderHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3DBlob* mD3DBlobComputeShader; ///< Direct3D 12 compute shader blob, can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/GraphicsProgramHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL graphics program class
*/
class GraphicsProgramHlsl final : public Rhi::IGraphicsProgram
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor for traditional graphics program
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] vertexShaderHlsl
* Vertex shader the graphics program is using, can be a null pointer
* @param[in] tessellationControlShaderHlsl
* Tessellation control shader the graphics program is using, can be a null pointer
* @param[in] tessellationEvaluationShaderHlsl
* Tessellation evaluation shader the graphics program is using, can be a null pointer
* @param[in] geometryShaderHlsl
* Geometry shader the graphics program is using, can be a null pointer
* @param[in] fragmentShaderHlsl
* Fragment shader the graphics program is using, can be a null pointer
*
* @note
* - The graphics program keeps a reference to the provided shaders and releases it when no longer required
*/
GraphicsProgramHlsl(Direct3D12Rhi& direct3D12Rhi, VertexShaderHlsl* vertexShaderHlsl, TessellationControlShaderHlsl* tessellationControlShaderHlsl, TessellationEvaluationShaderHlsl* tessellationEvaluationShaderHlsl, GeometryShaderHlsl* geometryShaderHlsl, FragmentShaderHlsl* fragmentShaderHlsl RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IGraphicsProgram(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mVertexShaderHlsl(vertexShaderHlsl),
mTessellationControlShaderHlsl(tessellationControlShaderHlsl),
mTessellationEvaluationShaderHlsl(tessellationEvaluationShaderHlsl),
mGeometryShaderHlsl(geometryShaderHlsl),
mFragmentShaderHlsl(fragmentShaderHlsl)
{
// Add references to the provided shaders
if (nullptr != mVertexShaderHlsl)
{
mVertexShaderHlsl->addReference();
}
if (nullptr != mTessellationControlShaderHlsl)
{
mTessellationControlShaderHlsl->addReference();
}
if (nullptr != mTessellationEvaluationShaderHlsl)
{
mTessellationEvaluationShaderHlsl->addReference();
}
if (nullptr != mGeometryShaderHlsl)
{
mGeometryShaderHlsl->addReference();
}
if (nullptr != mFragmentShaderHlsl)
{
mFragmentShaderHlsl->addReference();
}
}
/**
* @brief
* Constructor for task and mesh shader based graphics program
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] taskShaderHlsl
* Task shader the graphics program is using, can be a null pointer
* @param[in] meshShaderHlsl
* Mesh shader the graphics program is using
* @param[in] fragmentShaderHlsl
* Fragment shader the graphics program is using, can be a null pointer
*
* @note
* - The graphics program keeps a reference to the provided shaders and releases it when no longer required
*/
GraphicsProgramHlsl(Direct3D12Rhi& direct3D12Rhi, TaskShaderHlsl* taskShaderHlsl, MeshShaderHlsl& meshShaderHlsl, FragmentShaderHlsl* fragmentShaderHlsl RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IGraphicsProgram(direct3D12Rhi RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mVertexShaderHlsl(nullptr),
mTessellationControlShaderHlsl(nullptr),
mTessellationEvaluationShaderHlsl(nullptr),
mGeometryShaderHlsl(nullptr),
mFragmentShaderHlsl(fragmentShaderHlsl),
mTaskShaderHlsl(taskShaderHlsl),
mMeshShaderHlsl(&meshShaderHlsl)
{
// Add references to the provided shaders
if (nullptr != mFragmentShaderHlsl)
{
mFragmentShaderHlsl->addReference();
}
if (nullptr != mTaskShaderHlsl)
{
mTaskShaderHlsl->addReference();
}
mMeshShaderHlsl->addReference();
}
/**
* @brief
* Destructor
*/
virtual ~GraphicsProgramHlsl() override
{
// Release the shader references
if (nullptr != mVertexShaderHlsl)
{
mVertexShaderHlsl->releaseReference();
}
if (nullptr != mTessellationControlShaderHlsl)
{
mTessellationControlShaderHlsl->releaseReference();
}
if (nullptr != mTessellationEvaluationShaderHlsl)
{
mTessellationEvaluationShaderHlsl->releaseReference();
}
if (nullptr != mGeometryShaderHlsl)
{
mGeometryShaderHlsl->releaseReference();
}
if (nullptr != mFragmentShaderHlsl)
{
mFragmentShaderHlsl->releaseReference();
}
if (nullptr != mTaskShaderHlsl)
{
mTaskShaderHlsl->releaseReference();
}
if (nullptr != mMeshShaderHlsl)
{
mMeshShaderHlsl->releaseReference();
}
}
//[-------------------------------------------------------]
//[ Traditional graphics program ]
//[-------------------------------------------------------]
/**
* @brief
* Return the HLSL vertex shader the graphics program is using
*
* @return
* The HLSL vertex shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline VertexShaderHlsl* getVertexShaderHlsl() const
{
return mVertexShaderHlsl;
}
/**
* @brief
* Return the HLSL tessellation control shader the graphics program is using
*
* @return
* The HLSL tessellation control shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline TessellationControlShaderHlsl* getTessellationControlShaderHlsl() const
{
return mTessellationControlShaderHlsl;
}
/**
* @brief
* Return the HLSL tessellation evaluation shader the graphics program is using
*
* @return
* The HLSL tessellation evaluation shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline TessellationEvaluationShaderHlsl* getTessellationEvaluationShaderHlsl() const
{
return mTessellationEvaluationShaderHlsl;
}
/**
* @brief
* Return the HLSL geometry shader the graphics program is using
*
* @return
* The HLSL geometry shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline GeometryShaderHlsl* getGeometryShaderHlsl() const
{
return mGeometryShaderHlsl;
}
//[-------------------------------------------------------]
//[ Both graphics programs ]
//[-------------------------------------------------------]
/**
* @brief
* Return the HLSL fragment shader the graphics program is using
*
* @return
* The HLSL fragment shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline FragmentShaderHlsl* getFragmentShaderHlsl() const
{
return mFragmentShaderHlsl;
}
//[-------------------------------------------------------]
//[ Task and mesh shader based graphics program ]
//[-------------------------------------------------------]
/**
* @brief
* Return the HLSL task shader the graphics program is using
*
* @return
* The HLSL task shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline TaskShaderHlsl* getTaskShaderHlsl() const
{
return mTaskShaderHlsl;
}
/**
* @brief
* Return the HLSL mesh shader the graphics program is using
*
* @return
* The HLSL mesh shader the graphics program is using, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline MeshShaderHlsl* getMeshShaderHlsl() const
{
return mMeshShaderHlsl;
}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IGraphicsProgram methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] virtual Rhi::handle getUniformHandle(const char*) override
{
RHI_ASSERT(getRhi().getContext(), false, "The Direct3D 12 RHI graphics program HLSL implementation doesn't have legacy uniform support")
return NULL_HANDLE;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), GraphicsProgramHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit GraphicsProgramHlsl(const GraphicsProgramHlsl& source) = delete;
GraphicsProgramHlsl& operator =(const GraphicsProgramHlsl& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
// Traditional graphics program
VertexShaderHlsl* mVertexShaderHlsl; ///< Vertex shader the graphics program is using (we keep a reference to it), can be a null pointer
TessellationControlShaderHlsl* mTessellationControlShaderHlsl; ///< Tessellation control shader the graphics program is using (we keep a reference to it), can be a null pointer
TessellationEvaluationShaderHlsl* mTessellationEvaluationShaderHlsl; ///< Tessellation evaluation shader the graphics program is using (we keep a reference to it), can be a null pointer
GeometryShaderHlsl* mGeometryShaderHlsl; ///< Geometry shader the graphics program is using (we keep a reference to it), can be a null pointer
// Both graphics programs
FragmentShaderHlsl* mFragmentShaderHlsl; ///< Fragment shader the graphics program is using (we keep a reference to it), can be a null pointer
// Task and mesh shader based graphics program
TaskShaderHlsl* mTaskShaderHlsl; ///< Task shader the graphics program is using (we keep a reference to it), can be a null pointer
MeshShaderHlsl* mMeshShaderHlsl; ///< Mesh shader the graphics program is using (we keep a reference to it), can be a null pointer
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/Shader/ShaderLanguageHlsl.h ]
//[-------------------------------------------------------]
/**
* @brief
* HLSL shader language class
*/
class ShaderLanguageHlsl final : public Rhi::IShaderLanguage
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
*/
inline explicit ShaderLanguageHlsl(Direct3D12Rhi& direct3D12Rhi) :
IShaderLanguage(direct3D12Rhi)
{}
/**
* @brief
* Destructor
*/
inline virtual ~ShaderLanguageHlsl() override
{}
//[-------------------------------------------------------]
//[ Public virtual Rhi::IShaderLanguage methods ]
//[-------------------------------------------------------]
public:
[[nodiscard]] inline virtual const char* getShaderLanguageName() const override
{
return ::detail::HLSL_NAME;
}
[[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromBytecode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 vertex shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support
return RHI_NEW(direct3D12Rhi.getContext(), VertexShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IVertexShader* createVertexShaderFromSourceCode([[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// There's no need to check for "Rhi::Capabilities::vertexShader", we know there's vertex shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), VertexShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// "hull shader" in Direct3D terminology
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 tessellation control shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support
return RHI_NEW(direct3D12Rhi.getContext(), TessellationControlShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITessellationControlShader* createTessellationControlShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// "hull shader" in Direct3D terminology
// There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation control shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), TessellationControlShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// "domain shader" in Direct3D terminology
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 tessellation evaluation shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support
return RHI_NEW(direct3D12Rhi.getContext(), TessellationEvaluationShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITessellationEvaluationShader* createTessellationEvaluationShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// "domain shader" in Direct3D terminology
// There's no need to check for "Rhi::Capabilities::maximumNumberOfPatchVertices", we know there's tessellation evaluation shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), TessellationEvaluationShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 geometry shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support
return RHI_NEW(direct3D12Rhi.getContext(), GeometryShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IGeometryShader* createGeometryShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// There's no need to check for "Rhi::Capabilities::maximumNumberOfGsOutputVertices", we know there's geometry shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), GeometryShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 fragment shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support
return RHI_NEW(direct3D12Rhi.getContext(), FragmentShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IFragmentShader* createFragmentShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// There's no need to check for "Rhi::Capabilities::fragmentShader", we know there's fragment shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), FragmentShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), direct3D12Rhi.getCapabilities().meshShader, "Direct3D 12 task shader support is unavailable, DirectX 12 Ultimate needed")
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 task shader bytecode is invalid")
// Create the task shader
return RHI_NEW(direct3D12Rhi.getContext(), TaskShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::ITaskShader* createTaskShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), direct3D12Rhi.getCapabilities().meshShader, "Direct3D 12 task shader support is unavailable, DirectX 12 Ultimate needed")
// Create the task shader
return RHI_NEW(direct3D12Rhi.getContext(), TaskShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), direct3D12Rhi.getCapabilities().meshShader, "Direct3D 12 mesh shader support is unavailable, DirectX 12 Ultimate needed")
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 mesh shader bytecode is invalid")
// Create the task shader
return RHI_NEW(direct3D12Rhi.getContext(), MeshShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IMeshShader* createMeshShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
RHI_ASSERT(direct3D12Rhi.getContext(), direct3D12Rhi.getCapabilities().meshShader, "Direct3D 12 mesh shader support is unavailable, DirectX 12 Ultimate needed")
// Create the task shader
return RHI_NEW(direct3D12Rhi.getContext(), MeshShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromBytecode(const Rhi::ShaderBytecode& shaderBytecode RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity check
RHI_ASSERT(direct3D12Rhi.getContext(), shaderBytecode.getNumberOfBytes() > 0 && nullptr != shaderBytecode.getBytecode(), "Direct3D 12 compute shader bytecode is invalid")
// There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support
return RHI_NEW(direct3D12Rhi.getContext(), ComputeShaderHlsl)(direct3D12Rhi, shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] inline virtual Rhi::IComputeShader* createComputeShaderFromSourceCode(const Rhi::ShaderSourceCode& shaderSourceCode, Rhi::ShaderBytecode* shaderBytecode = nullptr RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
// There's no need to check for "Rhi::Capabilities::computeShader", we know there's compute shader support
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
return RHI_NEW(direct3D12Rhi.getContext(), ComputeShaderHlsl)(direct3D12Rhi, shaderSourceCode.sourceCode, getOptimizationLevel(), shaderBytecode RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, [[maybe_unused]] const Rhi::VertexAttributes& vertexAttributes, Rhi::IVertexShader* vertexShader, Rhi::ITessellationControlShader* tessellationControlShader, Rhi::ITessellationEvaluationShader* tessellationEvaluationShader, Rhi::IGeometryShader* geometryShader, Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER) override
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
// -> A shader can be a null pointer, but if it's not the shader and graphics program language must match
// -> Optimization: Comparing the shader language name by directly comparing the pointer address of
// the name is safe because we know that we always reference to one and the same name address
// TODO(co) Add security check: Is the given resource one of the currently used RHI?
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == vertexShader || vertexShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 vertex shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == tessellationControlShader || tessellationControlShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 tessellation control shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == tessellationEvaluationShader || tessellationEvaluationShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 tessellation evaluation shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == geometryShader || geometryShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 geometry shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == fragmentShader || fragmentShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 fragment shader language mismatch")
// Create the graphics program
return RHI_NEW(direct3D12Rhi.getContext(), GraphicsProgramHlsl)(direct3D12Rhi, static_cast<VertexShaderHlsl*>(vertexShader), static_cast<TessellationControlShaderHlsl*>(tessellationControlShader), static_cast<TessellationEvaluationShaderHlsl*>(tessellationEvaluationShader), static_cast<GeometryShaderHlsl*>(geometryShader), static_cast<FragmentShaderHlsl*>(fragmentShader) RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
[[nodiscard]] virtual Rhi::IGraphicsProgram* createGraphicsProgram([[maybe_unused]] const Rhi::IRootSignature& rootSignature, Rhi::ITaskShader* taskShader, Rhi::IMeshShader& meshShader, Rhi::IFragmentShader* fragmentShader RHI_RESOURCE_DEBUG_NAME_PARAMETER)
{
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
// Sanity checks
// -> A shader can be a null pointer, but if it's not the shader and graphics program language must match
// -> Optimization: Comparing the shader language name by directly comparing the pointer address of
// the name is safe because we know that we always reference to one and the same name address
// TODO(co) Add security check: Is the given resource one of the currently used RHI?
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == taskShader || taskShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 task shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), meshShader.getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 mesh shader language mismatch")
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr == fragmentShader || fragmentShader->getShaderLanguageName() == ::detail::HLSL_NAME, "Direct3D 12 fragment shader language mismatch")
// Create the graphics program
return RHI_NEW(direct3D12Rhi.getContext(), GraphicsProgramHlsl)(direct3D12Rhi, static_cast<TaskShaderHlsl*>(taskShader), static_cast<MeshShaderHlsl&>(meshShader), static_cast<FragmentShaderHlsl*>(fragmentShader) RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), ShaderLanguageHlsl, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit ShaderLanguageHlsl(const ShaderLanguageHlsl& source) = delete;
ShaderLanguageHlsl& operator =(const ShaderLanguageHlsl& source) = delete;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/State/GraphicsPipelineState.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 graphics pipeline state class
*/
class GraphicsPipelineState final : public Rhi::IGraphicsPipelineState
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] graphicsPipelineState
* Graphics pipeline state to use
* @param[in] id
* The unique compact graphics pipeline state ID
*/
GraphicsPipelineState(Direct3D12Rhi& direct3D12Rhi, const Rhi::GraphicsPipelineState& graphicsPipelineState, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IGraphicsPipelineState(direct3D12Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3D12PrimitiveTopology(static_cast<D3D12_PRIMITIVE_TOPOLOGY>(graphicsPipelineState.primitiveTopology)),
mD3D12GraphicsPipelineState(nullptr),
mRootSignature(graphicsPipelineState.rootSignature),
mGraphicsProgram(graphicsPipelineState.graphicsProgram),
mRenderPass(graphicsPipelineState.renderPass)
{
// Add a reference to the referenced RHI resources
mRootSignature->addReference();
mGraphicsProgram->addReference();
mRenderPass->addReference();
// Define the vertex input layout
// -> No dynamic allocations/deallocations in here, a fixed maximum number of supported attributes must be sufficient
static constexpr uint32_t MAXIMUM_NUMBER_OF_ATTRIBUTES = 16; // 16 elements per vertex are already pretty many
const uint32_t numberOfVertexAttributes = graphicsPipelineState.vertexAttributes.numberOfAttributes;
RHI_ASSERT(direct3D12Rhi.getContext(), numberOfVertexAttributes < MAXIMUM_NUMBER_OF_ATTRIBUTES, "Too many vertex attributes (%u) provided. The limit of the Direct3D 12 RHI implementation is %u.", numberOfVertexAttributes, MAXIMUM_NUMBER_OF_ATTRIBUTES)
D3D12_INPUT_ELEMENT_DESC d3d12InputElementDescs[MAXIMUM_NUMBER_OF_ATTRIBUTES];
for (uint32_t vertexAttribute = 0; vertexAttribute < numberOfVertexAttributes; ++vertexAttribute)
{
const Rhi::VertexAttribute& currentVertexAttribute = graphicsPipelineState.vertexAttributes.attributes[vertexAttribute];
D3D12_INPUT_ELEMENT_DESC& d3d12InputElementDesc = d3d12InputElementDescs[vertexAttribute];
d3d12InputElementDesc.SemanticName = currentVertexAttribute.semanticName;
d3d12InputElementDesc.SemanticIndex = currentVertexAttribute.semanticIndex;
d3d12InputElementDesc.Format = Mapping::getDirect3D12Format(currentVertexAttribute.vertexAttributeFormat);
d3d12InputElementDesc.InputSlot = currentVertexAttribute.inputSlot;
d3d12InputElementDesc.AlignedByteOffset = currentVertexAttribute.alignedByteOffset;
// Per-instance instead of per-vertex?
if (currentVertexAttribute.instancesPerElement > 0)
{
d3d12InputElementDesc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; // Input classification (D3D12_INPUT_CLASSIFICATION)
d3d12InputElementDesc.InstanceDataStepRate = currentVertexAttribute.instancesPerElement; // Instance data step rate (UINT)
}
else
{
d3d12InputElementDesc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; // Input classification (D3D12_INPUT_CLASSIFICATION)
d3d12InputElementDesc.InstanceDataStepRate = 0; // Instance data step rate (UINT)
}
}
// Describe and create the graphics pipeline state object (PSO)
D3D12_GRAPHICS_PIPELINE_STATE_DESC d3d12GraphicsPipelineState = {};
d3d12GraphicsPipelineState.InputLayout = { d3d12InputElementDescs, numberOfVertexAttributes };
d3d12GraphicsPipelineState.pRootSignature = static_cast<RootSignature*>(mRootSignature)->getD3D12RootSignature();
{ // Set shaders
GraphicsProgramHlsl* graphicsProgramHlsl = static_cast<GraphicsProgramHlsl*>(mGraphicsProgram);
const MeshShaderHlsl* meshShaderHlsl = graphicsProgramHlsl->getMeshShaderHlsl();
if (nullptr != meshShaderHlsl)
{
// Task and mesh shader based graphics program
{ // Task shader
const TaskShaderHlsl* taskShaderHlsl = graphicsProgramHlsl->getTaskShaderHlsl();
if (nullptr != taskShaderHlsl)
{
// TODO(co) "DirectX 12 Ultimate" needed
// ID3DBlob* d3dBlobTaskShader = taskShaderHlsl->getD3DBlobTaskShader();
// d3d12GraphicsPipelineState.AS = { reinterpret_cast<UINT8*>(d3dBlobTaskShader->GetBufferPointer()), d3dBlobTaskShader->GetBufferSize() };
}
}
{ // Mesh shader
// TODO(co) "DirectX 12 Ultimate" needed
// ID3DBlob* d3dBlobMeshShader = meshShaderHlsl->getD3DBlobMeshShader();
// d3d12GraphicsPipelineState.MS = { reinterpret_cast<UINT8*>(d3dBlobMeshShader->GetBufferPointer()), d3dBlobMeshShader->GetBufferSize() };
}
{ // Fragment shader (FS, "pixel shader" in Direct3D terminology)
const FragmentShaderHlsl* fragmentShaderHlsl = graphicsProgramHlsl->getFragmentShaderHlsl();
if (nullptr != fragmentShaderHlsl)
{
ID3DBlob* d3dBlobFragmentShader = graphicsProgramHlsl->getFragmentShaderHlsl()->getD3DBlobFragmentShader();
d3d12GraphicsPipelineState.PS = { reinterpret_cast<UINT8*>(d3dBlobFragmentShader->GetBufferPointer()), d3dBlobFragmentShader->GetBufferSize() };
}
}
}
else
{
// Traditional graphics program
{ // Vertex shader
const VertexShaderHlsl* vertexShaderHlsl = graphicsProgramHlsl->getVertexShaderHlsl();
if (nullptr != vertexShaderHlsl)
{
ID3DBlob* d3dBlobVertexShader = vertexShaderHlsl->getD3DBlobVertexShader();
d3d12GraphicsPipelineState.VS = { reinterpret_cast<UINT8*>(d3dBlobVertexShader->GetBufferPointer()), d3dBlobVertexShader->GetBufferSize() };
}
}
{ // Tessellation control shader (TCS, "hull shader" in Direct3D terminology)
const TessellationControlShaderHlsl* tessellationControlShaderHlsl = graphicsProgramHlsl->getTessellationControlShaderHlsl();
if (nullptr != tessellationControlShaderHlsl)
{
ID3DBlob* d3dBlobHullShader = tessellationControlShaderHlsl->getD3DBlobHullShader();
d3d12GraphicsPipelineState.HS = { reinterpret_cast<UINT8*>(d3dBlobHullShader->GetBufferPointer()), d3dBlobHullShader->GetBufferSize() };
}
}
{ // Tessellation evaluation shader (TES, "domain shader" in Direct3D terminology)
const TessellationEvaluationShaderHlsl* tessellationEvaluationShaderHlsl = graphicsProgramHlsl->getTessellationEvaluationShaderHlsl();
if (nullptr != tessellationEvaluationShaderHlsl)
{
ID3DBlob* d3dBlobDomainShader = tessellationEvaluationShaderHlsl->getD3DBlobDomainShader();
d3d12GraphicsPipelineState.DS = { reinterpret_cast<UINT8*>(d3dBlobDomainShader->GetBufferPointer()), d3dBlobDomainShader->GetBufferSize() };
}
}
{ // Geometry shader
const GeometryShaderHlsl* geometryShaderHlsl = graphicsProgramHlsl->getGeometryShaderHlsl();
if (nullptr != geometryShaderHlsl)
{
ID3DBlob* d3dBlobGeometryShader = geometryShaderHlsl->getD3DBlobGeometryShader();
d3d12GraphicsPipelineState.GS = { reinterpret_cast<UINT8*>(d3dBlobGeometryShader->GetBufferPointer()), d3dBlobGeometryShader->GetBufferSize() };
}
}
{ // Fragment shader (FS, "pixel shader" in Direct3D terminology)
const FragmentShaderHlsl* fragmentShaderHlsl = graphicsProgramHlsl->getFragmentShaderHlsl();
if (nullptr != fragmentShaderHlsl)
{
ID3DBlob* d3dBlobFragmentShader = graphicsProgramHlsl->getFragmentShaderHlsl()->getD3DBlobFragmentShader();
d3d12GraphicsPipelineState.PS = { reinterpret_cast<UINT8*>(d3dBlobFragmentShader->GetBufferPointer()), d3dBlobFragmentShader->GetBufferSize() };
}
}
}
}
d3d12GraphicsPipelineState.PrimitiveTopologyType = static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(graphicsPipelineState.primitiveTopologyType);
memcpy(&d3d12GraphicsPipelineState.RasterizerState, &graphicsPipelineState.rasterizerState, sizeof(D3D12_RASTERIZER_DESC));
memcpy(&d3d12GraphicsPipelineState.DepthStencilState, &graphicsPipelineState.depthStencilState, sizeof(D3D12_DEPTH_STENCIL_DESC));
{
// TODO(co) "D3D12_RENDER_TARGET_BLEND_DESC" and "D3D11_RENDER_TARGET_BLEND_DESC" are different, we probably want to switch to "D3D12_RENDER_TARGET_BLEND_DESC"
/*
typedef struct D3D12_RENDER_TARGET_BLEND_DESC
{
BOOL BlendEnable;
BOOL LogicOpEnable;
D3D12_BLEND SrcBlend;
D3D12_BLEND DestBlend;
D3D12_BLEND_OP BlendOp;
D3D12_BLEND SrcBlendAlpha;
D3D12_BLEND DestBlendAlpha;
D3D12_BLEND_OP BlendOpAlpha;
D3D12_LOGIC_OP LogicOp;
UINT8 RenderTargetWriteMask;
} D3D12_RENDER_TARGET_BLEND_DESC;
typedef struct D3D11_RENDER_TARGET_BLEND_DESC
{
BOOL BlendEnable;
D3D11_BLEND SrcBlend;
D3D11_BLEND DestBlend;
D3D11_BLEND_OP BlendOp;
D3D11_BLEND SrcBlendAlpha;
D3D11_BLEND DestBlendAlpha;
D3D11_BLEND_OP BlendOpAlpha;
UINT8 RenderTargetWriteMask;
} D3D11_RENDER_TARGET_BLEND_DESC;
*/
D3D12_BLEND_DESC& d3d12BlendDesc = d3d12GraphicsPipelineState.BlendState;
const Rhi::BlendState& blendState = graphicsPipelineState.blendState;
d3d12BlendDesc.AlphaToCoverageEnable = blendState.alphaToCoverageEnable;
d3d12BlendDesc.IndependentBlendEnable = blendState.independentBlendEnable;
for (uint32_t renderTargetIndex = 0; renderTargetIndex < 8; ++renderTargetIndex)
{
D3D12_RENDER_TARGET_BLEND_DESC& d3d12RenderTargetBlendDesc = d3d12BlendDesc.RenderTarget[renderTargetIndex];
const Rhi::RenderTargetBlendDesc& renderTargetBlendDesc = blendState.renderTarget[renderTargetIndex];
d3d12RenderTargetBlendDesc.BlendEnable = renderTargetBlendDesc.blendEnable;
d3d12RenderTargetBlendDesc.LogicOpEnable = false;
d3d12RenderTargetBlendDesc.SrcBlend = static_cast<D3D12_BLEND>(renderTargetBlendDesc.srcBlend);
d3d12RenderTargetBlendDesc.DestBlend = static_cast<D3D12_BLEND>(renderTargetBlendDesc.destBlend);
d3d12RenderTargetBlendDesc.BlendOp = static_cast<D3D12_BLEND_OP>(renderTargetBlendDesc.blendOp);
d3d12RenderTargetBlendDesc.SrcBlendAlpha = static_cast<D3D12_BLEND>(renderTargetBlendDesc.srcBlendAlpha);
d3d12RenderTargetBlendDesc.DestBlendAlpha = static_cast<D3D12_BLEND>(renderTargetBlendDesc.destBlendAlpha);
d3d12RenderTargetBlendDesc.BlendOpAlpha = static_cast<D3D12_BLEND_OP>(renderTargetBlendDesc.blendOpAlpha);
d3d12RenderTargetBlendDesc.LogicOp = D3D12_LOGIC_OP_CLEAR;
d3d12RenderTargetBlendDesc.RenderTargetWriteMask = renderTargetBlendDesc.renderTargetWriteMask;
}
}
d3d12GraphicsPipelineState.SampleMask = UINT_MAX;
d3d12GraphicsPipelineState.NumRenderTargets = graphicsPipelineState.numberOfRenderTargets;
for (uint32_t i = 0; i < graphicsPipelineState.numberOfRenderTargets; ++i)
{
d3d12GraphicsPipelineState.RTVFormats[i] = Mapping::getDirect3D12Format(graphicsPipelineState.renderTargetViewFormats[i]);
}
d3d12GraphicsPipelineState.DSVFormat = Mapping::getDirect3D12Format(graphicsPipelineState.depthStencilViewFormat);
d3d12GraphicsPipelineState.SampleDesc.Count = 1;
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateGraphicsPipelineState(&d3d12GraphicsPipelineState, IID_PPV_ARGS(&mD3D12GraphicsPipelineState))))
{
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Graphics PSO", 15) // 15 = "Graphics PSO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12GraphicsPipelineState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create the Direct3D 12 graphics pipeline state object")
}
}
/**
* @brief
* Destructor
*/
virtual ~GraphicsPipelineState() override
{
// Release the Direct3D 12 graphics pipeline state
if (nullptr != mD3D12GraphicsPipelineState)
{
mD3D12GraphicsPipelineState->Release();
}
// Release referenced RHI resources
mRootSignature->releaseReference();
mGraphicsProgram->releaseReference();
mRenderPass->releaseReference();
// Free the unique compact graphics pipeline state ID
static_cast<Direct3D12Rhi&>(getRhi()).GraphicsPipelineStateMakeId.DestroyID(getId());
}
/**
* @brief
* Return the Direct3D 12 primitive topology
*
* @return
* The Direct3D 12 primitive topology
*/
[[nodiscard]] inline D3D12_PRIMITIVE_TOPOLOGY getD3D12PrimitiveTopology() const
{
return mD3D12PrimitiveTopology;
}
/**
* @brief
* Return the Direct3D 12 graphics pipeline state
*
* @return
* The Direct3D 12 graphics pipeline state, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12PipelineState* getD3D12GraphicsPipelineState() const
{
return mD3D12GraphicsPipelineState;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), GraphicsPipelineState, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit GraphicsPipelineState(const GraphicsPipelineState& source) = delete;
GraphicsPipelineState& operator =(const GraphicsPipelineState& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
D3D12_PRIMITIVE_TOPOLOGY mD3D12PrimitiveTopology;
ID3D12PipelineState* mD3D12GraphicsPipelineState; ///< Direct3D 12 graphics pipeline state, can be a null pointer
Rhi::IRootSignature* mRootSignature;
Rhi::IGraphicsProgram* mGraphicsProgram;
Rhi::IRenderPass* mRenderPass;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/State/ComputePipelineState.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 compute pipeline state class
*/
class ComputePipelineState final : public Rhi::IComputePipelineState
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D12Rhi
* Owner Direct3D 12 RHI instance
* @param[in] rootSignature
* Root signature shader to use
* @param[in] computeShader
* Compute shader to use
* @param[in] id
* The unique compact compute pipeline state ID
*/
ComputePipelineState(Direct3D12Rhi& direct3D12Rhi, Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader, uint16_t id RHI_RESOURCE_DEBUG_NAME_PARAMETER) :
IComputePipelineState(direct3D12Rhi, id RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mD3D12ComputePipelineState(nullptr),
mRootSignature(rootSignature),
mComputeShader(computeShader)
{
// Add a reference to the given root signature and compute shader
rootSignature.addReference();
computeShader.addReference();
// Describe and create the compute pipeline state object (PSO)
D3D12_COMPUTE_PIPELINE_STATE_DESC d3d12ComputePipelineState = {};
d3d12ComputePipelineState.pRootSignature = static_cast<RootSignature&>(rootSignature).getD3D12RootSignature();
{ // Set compute shader
ID3DBlob* d3dBlobComputeShader = static_cast<ComputeShaderHlsl&>(computeShader).getD3DBlobComputeShader();
d3d12ComputePipelineState.CS = { reinterpret_cast<UINT8*>(d3dBlobComputeShader->GetBufferPointer()), d3dBlobComputeShader->GetBufferSize() };
}
if (SUCCEEDED(direct3D12Rhi.getD3D12Device().CreateComputePipelineState(&d3d12ComputePipelineState, IID_PPV_ARGS(&mD3D12ComputePipelineState))))
{
// Assign a default name to the resource for debugging purposes
#ifdef RHI_DEBUG
RHI_DECORATED_DEBUG_NAME(debugName, detailedDebugName, "Compute PSO", 14) // 14 = "Compute PSO: " including terminating zero
FAILED_DEBUG_BREAK(mD3D12ComputePipelineState->SetPrivateData(WKPDID_D3DDebugObjectName, static_cast<UINT>(strlen(detailedDebugName)), detailedDebugName))
#endif
}
else
{
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Failed to create the Direct3D 12 compute pipeline state object")
}
}
/**
* @brief
* Destructor
*/
virtual ~ComputePipelineState() override
{
// Release the Direct3D 12 compute pipeline state
if (nullptr != mD3D12ComputePipelineState)
{
mD3D12ComputePipelineState->Release();
}
// Release the root signature and compute shader reference
mRootSignature.releaseReference();
mComputeShader.releaseReference();
// Free the unique compact compute pipeline state ID
static_cast<Direct3D12Rhi&>(getRhi()).ComputePipelineStateMakeId.DestroyID(getId());
}
/**
* @brief
* Return the Direct3D 12 compute pipeline state
*
* @return
* The Direct3D 12 compute pipeline state, can be a null pointer, do not release the returned instance unless you added an own reference to it
*/
[[nodiscard]] inline ID3D12PipelineState* getD3D12ComputePipelineState() const
{
return mD3D12ComputePipelineState;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), ComputePipelineState, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit ComputePipelineState(const ComputePipelineState& source) = delete;
ComputePipelineState& operator =(const ComputePipelineState& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
ID3D12PipelineState* mD3D12ComputePipelineState; ///< Direct3D 12 compute pipeline state, can be a null pointer
Rhi::IRootSignature& mRootSignature;
Rhi::IComputeShader& mComputeShader;
};
//[-------------------------------------------------------]
//[ Direct3D12Rhi/ResourceGroup.h ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 12 resource group class
*/
class ResourceGroup final : public Rhi::IResourceGroup
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] rootSignature
* Root signature
* @param[in] d3d12DescriptorHeapType
* Direct3D 12 descriptor heap type
* @param[in] numberOfResources
* Number of resources, having no resources is invalid
* @param[in] resources
* At least "numberOfResources" resource pointers, must be valid, the resource group will keep a reference to the resources
* @param[in] samplerStates
* If not a null pointer at least "numberOfResources" sampler state pointers, must be valid if there's at least one texture resource, the resource group will keep a reference to the sampler states
*/
ResourceGroup(RootSignature& rootSignature, D3D12_DESCRIPTOR_HEAP_TYPE d3d12DescriptorHeapType, uint32_t numberOfResources, Rhi::IResource** resources, Rhi::ISamplerState** samplerStates RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT) :
IResourceGroup(rootSignature.getRhi() RHI_RESOURCE_DEBUG_PASS_PARAMETER),
mRootSignature(rootSignature),
mD3D12DescriptorHeapType(d3d12DescriptorHeapType),
mNumberOfResources(numberOfResources),
mResources(RHI_MALLOC_TYPED(rootSignature.getRhi().getContext(), Rhi::IResource*, mNumberOfResources)),
mSamplerStates(nullptr),
mDescriptorHeapOffset(0),
mDescriptorHeapSize(static_cast<uint16_t>(numberOfResources))
{
mRootSignature.addReference();
// Sanity check
const Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
RHI_ASSERT(direct3D12Rhi.getContext(), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == mD3D12DescriptorHeapType || D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER == mD3D12DescriptorHeapType, "Invalid Direct3D 12 descriptor heap type, must be \"D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV\" or \"D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER\"")
// Process all resources and add our reference to the RHI resource
if (nullptr != samplerStates)
{
mSamplerStates = RHI_MALLOC_TYPED(direct3D12Rhi.getContext(), Rhi::ISamplerState*, mNumberOfResources);
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex] = samplerStates[resourceIndex];
if (nullptr != samplerState)
{
samplerState->addReference();
}
}
}
ID3D12Device& d3d12Device = direct3D12Rhi.getD3D12Device();
if (D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == d3d12DescriptorHeapType)
{
::detail::DescriptorHeap& descriptorHeap = direct3D12Rhi.getShaderResourceViewDescriptorHeap();
mDescriptorHeapOffset = descriptorHeap.allocate(static_cast<uint16_t>(numberOfResources));
const uint32_t descriptorSize = descriptorHeap.getDescriptorSize();
D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle = descriptorHeap.getD3D12CpuDescriptorHandleForHeapStart();
d3d12CpuDescriptorHandle.ptr += mDescriptorHeapOffset * descriptorSize;
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources)
{
Rhi::IResource* resource = *resources;
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != resource, "Invalid Direct3D 12 resource")
mResources[resourceIndex] = resource;
resource->addReference();
// Check the type of resource to set
// TODO(co) Some additional resource type root signature security checks in debug build?
const Rhi::ResourceType resourceType = resource->getResourceType();
switch (resourceType)
{
case Rhi::ResourceType::INDEX_BUFFER:
{
// TODO(co)
RHI_ASSERT(direct3D12Rhi.getContext(), false, "TODO(co) Implement me")
/*
const IndexBuffer* indexBuffer = static_cast<IndexBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != indexBuffer->getD3D12Resource(), "Invalid Direct3D 12 index buffer resource")
const D3D12_CONSTANT_BUFFER_VIEW_DESC d3d12ConstantBufferViewDesc = { indexBuffer->getD3D12Resource()->GetGPUVirtualAddress(), indexBuffer->getNumberOfBytesOnGpu() };
d3d12Device.CreateConstantBufferView(&d3d12ConstantBufferViewDesc, d3d12CpuDescriptorHandle);
*/
break;
}
case Rhi::ResourceType::VERTEX_BUFFER:
{
// TODO(co)
RHI_ASSERT(direct3D12Rhi.getContext(), false, "TODO(co) Implement me")
/*
const VertexBuffer* vertexBuffer = static_cast<VertexBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != vertexBuffer->getD3D12Resource(), "Invalid Direct3D 12 vertex buffer resource")
const D3D12_CONSTANT_BUFFER_VIEW_DESC d3d12ConstantBufferViewDesc = { vertexBuffer->getD3D12Resource()->GetGPUVirtualAddress(), vertexBuffer->getNumberOfBytesOnGpu() };
d3d12Device.CreateConstantBufferView(&d3d12ConstantBufferViewDesc, d3d12CpuDescriptorHandle);
*/
break;
}
case Rhi::ResourceType::TEXTURE_BUFFER:
{
const TextureBuffer* textureBuffer = static_cast<TextureBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != textureBuffer->getD3D12Resource(), "Invalid Direct3D 12 texture buffer resource")
const Rhi::TextureFormat::Enum textureFormat = textureBuffer->getTextureFormat();
D3D12_SHADER_RESOURCE_VIEW_DESC d3d12ShaderResourceViewDesc = {};
d3d12ShaderResourceViewDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
d3d12ShaderResourceViewDesc.Format = Mapping::getDirect3D12Format(textureFormat);
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
d3d12ShaderResourceViewDesc.Buffer.FirstElement = 0;
d3d12ShaderResourceViewDesc.Buffer.NumElements = textureBuffer->getNumberOfBytes() / Rhi::TextureFormat::getNumberOfBytesPerElement(textureFormat);
d3d12Device.CreateShaderResourceView(textureBuffer->getD3D12Resource(), &d3d12ShaderResourceViewDesc, d3d12CpuDescriptorHandle);
break;
}
case Rhi::ResourceType::STRUCTURED_BUFFER:
{
// TODO(co)
RHI_ASSERT(direct3D12Rhi.getContext(), false, "TODO(co) Implement me")
/*
const StructuredBuffer* structuredBuffer = static_cast<StructuredBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != structuredBuffer->getD3D12Resource(), "Invalid Direct3D 12 structured buffer resource")
const D3D12_CONSTANT_BUFFER_VIEW_DESC d3d12ConstantBufferViewDesc = { structuredBuffer->getD3D12Resource()->GetGPUVirtualAddress(), structuredBuffer->getNumberOfBytesOnGpu() };
d3d12Device.CreateConstantBufferView(&d3d12ConstantBufferViewDesc, d3d12CpuDescriptorHandle);
*/
break;
}
case Rhi::ResourceType::INDIRECT_BUFFER:
{
// TODO(co)
RHI_ASSERT(direct3D12Rhi.getContext(), false, "TODO(co) Implement me")
/*
const IndirectBuffer* indirectBuffer = static_cast<IndirectBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != indirectBuffer->getD3D12Resource(), "Invalid Direct3D 12 indirect buffer resource")
const D3D12_CONSTANT_BUFFER_VIEW_DESC d3d12ConstantBufferViewDesc = { indirectBuffer->getD3D12Resource()->GetGPUVirtualAddress(), indirectBuffer->getNumberOfBytesOnGpu() };
d3d12Device.CreateConstantBufferView(&d3d12ConstantBufferViewDesc, d3d12CpuDescriptorHandle);
*/
break;
}
case Rhi::ResourceType::UNIFORM_BUFFER:
{
const UniformBuffer* uniformBuffer = static_cast<UniformBuffer*>(resource);
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != uniformBuffer->getD3D12Resource(), "Invalid Direct3D 12 uniform buffer resource")
const D3D12_CONSTANT_BUFFER_VIEW_DESC d3d12ConstantBufferViewDesc = { uniformBuffer->getD3D12Resource()->GetGPUVirtualAddress(), uniformBuffer->getNumberOfBytesOnGpu() };
d3d12Device.CreateConstantBufferView(&d3d12ConstantBufferViewDesc, d3d12CpuDescriptorHandle);
break;
}
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_2D:
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
{
// Evaluate the texture type and create the Direct3D 12 shader resource view
ID3D12Resource* d3d12Resource = nullptr;
D3D12_SHADER_RESOURCE_VIEW_DESC d3d12ShaderResourceViewDesc = {};
d3d12ShaderResourceViewDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
switch (resourceType)
{
case Rhi::ResourceType::TEXTURE_1D:
{
const Texture1D* texture1D = static_cast<Texture1D*>(resource);
d3d12ShaderResourceViewDesc.Format = texture1D->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
d3d12ShaderResourceViewDesc.Texture1D.MipLevels = texture1D->getNumberOfMipmaps();
d3d12Resource = texture1D->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
{
const Texture1DArray* texture1DArray = static_cast<Texture1DArray*>(resource);
d3d12ShaderResourceViewDesc.Format = texture1DArray->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
d3d12ShaderResourceViewDesc.Texture1DArray.MipLevels = texture1DArray->getNumberOfMipmaps();
d3d12ShaderResourceViewDesc.Texture1DArray.ArraySize = texture1DArray->getNumberOfSlices();
d3d12Resource = texture1DArray->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_2D:
{
const Texture2D* texture2D = static_cast<Texture2D*>(resource);
d3d12ShaderResourceViewDesc.Format = texture2D->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
d3d12ShaderResourceViewDesc.Texture2D.MipLevels = texture2D->getNumberOfMipmaps();
d3d12Resource = texture2D->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
{
const Texture2DArray* texture2DArray = static_cast<Texture2DArray*>(resource);
d3d12ShaderResourceViewDesc.Format = texture2DArray->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
d3d12ShaderResourceViewDesc.Texture2DArray.MipLevels = texture2DArray->getNumberOfMipmaps();
d3d12ShaderResourceViewDesc.Texture2DArray.ArraySize = texture2DArray->getNumberOfSlices();
d3d12Resource = texture2DArray->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_3D:
{
const Texture3D* texture3D = static_cast<Texture3D*>(resource);
d3d12ShaderResourceViewDesc.Format = texture3D->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
d3d12ShaderResourceViewDesc.Texture3D.MipLevels = texture3D->getNumberOfMipmaps();
d3d12Resource = texture3D->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_CUBE:
{
const TextureCube* textureCube = static_cast<TextureCube*>(resource);
d3d12ShaderResourceViewDesc.Format = textureCube->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
d3d12ShaderResourceViewDesc.TextureCube.MipLevels = textureCube->getNumberOfMipmaps();
d3d12Resource = textureCube->getD3D12Resource();
break;
}
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
{
// TODO(co) Implement me
/*
const TextureCubeArray* textureCubeArray = static_cast<TextureCubeArray*>(resource);
d3d12ShaderResourceViewDesc.Format = textureCubeArray->getDxgiFormat();
d3d12ShaderResourceViewDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
d3d12ShaderResourceViewDesc.TextureCubeArray.MipLevels = textureCubeArray->getNumberOfMipmaps();
d3d12Resource = textureCubeArray->getD3D12Resource();
*/
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Invalid Direct3D 12 RHI implementation resource type")
break;
}
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != d3d12Resource, "Invalid Direct3D 12 resource")
d3d12Device.CreateShaderResourceView(d3d12Resource, &d3d12ShaderResourceViewDesc, d3d12CpuDescriptorHandle);
break;
}
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Invalid Direct3D 12 RHI implementation resource type")
break;
}
d3d12CpuDescriptorHandle.ptr += descriptorSize;
}
RHI_ASSERT(direct3D12Rhi.getContext(), d3d12CpuDescriptorHandle.ptr == descriptorHeap.getD3D12CpuDescriptorHandleForHeapStart().ptr + (mDescriptorHeapOffset + mNumberOfResources) * descriptorSize, "Direct3D 12 descriptor heap invalid")
}
else
{
::detail::DescriptorHeap& descriptorHeap = direct3D12Rhi.getSamplerDescriptorHeap();
mDescriptorHeapOffset = descriptorHeap.allocate(static_cast<uint16_t>(numberOfResources));
const uint32_t descriptorSize = descriptorHeap.getDescriptorSize();
D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandle = descriptorHeap.getD3D12CpuDescriptorHandleForHeapStart();
d3d12CpuDescriptorHandle.ptr += mDescriptorHeapOffset * descriptorSize;
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources)
{
Rhi::IResource* resource = *resources;
RHI_ASSERT(direct3D12Rhi.getContext(), nullptr != resource, "Invalid Direct3D 12 resource")
mResources[resourceIndex] = resource;
resource->addReference();
// Check the type of resource to set
// TODO(co) Some additional resource type root signature security checks in debug build?
switch (resource->getResourceType())
{
case Rhi::ResourceType::SAMPLER_STATE:
d3d12Device.CreateSampler(reinterpret_cast<const D3D12_SAMPLER_DESC*>(&static_cast<SamplerState*>(resource)->getSamplerState()), d3d12CpuDescriptorHandle);
break;
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_2D:
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
RHI_ASSERT(direct3D12Rhi.getContext(), false, "Invalid Direct3D 12 RHI implementation resource type")
break;
}
d3d12CpuDescriptorHandle.ptr += descriptorSize;
}
RHI_ASSERT(direct3D12Rhi.getContext(), d3d12CpuDescriptorHandle.ptr == descriptorHeap.getD3D12CpuDescriptorHandleForHeapStart().ptr + (mDescriptorHeapOffset + mNumberOfResources) * descriptorSize, "Direct3D 12 descriptor heap invalid")
}
}
/**
* @brief
* Destructor
*/
virtual ~ResourceGroup() override
{
// Remove our reference from the RHI resources
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
const Rhi::Context& context = direct3D12Rhi.getContext();
if (nullptr != mSamplerStates)
{
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
Rhi::ISamplerState* samplerState = mSamplerStates[resourceIndex];
if (nullptr != samplerState)
{
samplerState->releaseReference();
}
}
RHI_FREE(context, mSamplerStates);
}
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
mResources[resourceIndex]->releaseReference();
}
RHI_FREE(context, mResources);
mRootSignature.releaseReference();
// Release descriptor heap
((D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == mD3D12DescriptorHeapType) ? direct3D12Rhi.getShaderResourceViewDescriptorHeap() : direct3D12Rhi.getSamplerDescriptorHeap()).release(mDescriptorHeapOffset, mDescriptorHeapSize);
}
/**
* @brief
* Return the Direct3D 12 descriptor heap type
*
* @return
* The Direct3D 12 descriptor heap type ("D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV" or "D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER")
*/
[[nodiscard]] inline D3D12_DESCRIPTOR_HEAP_TYPE getD3D12DescriptorHeapType() const
{
return mD3D12DescriptorHeapType;
}
/**
* @brief
* Return the descriptor heap offset
*
* @return
* The descriptor heap offset
*/
[[nodiscard]] inline uint16_t getDescriptorHeapOffset() const
{
return mDescriptorHeapOffset;
}
/**
* @brief
* Return the descriptor heap size
*
* @return
* The descriptor heap size
*/
[[nodiscard]] inline uint16_t getDescriptorHeapSize() const
{
return mDescriptorHeapSize;
}
//[-------------------------------------------------------]
//[ Protected virtual Rhi::RefCount methods ]
//[-------------------------------------------------------]
protected:
inline virtual void selfDestruct() override
{
RHI_DELETE(getRhi().getContext(), ResourceGroup, this);
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit ResourceGroup(const ResourceGroup& source) = delete;
ResourceGroup& operator =(const ResourceGroup& source) = delete;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
RootSignature& mRootSignature; ///< Root signature
D3D12_DESCRIPTOR_HEAP_TYPE mD3D12DescriptorHeapType; ///< The Direct3D 12 descriptor heap type ("D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV" or "D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER")
uint32_t mNumberOfResources; ///< Number of resources this resource group groups together
Rhi::IResource** mResources; ///< RHI resource, we keep a reference to it
Rhi::ISamplerState** mSamplerStates; ///< Sampler states, we keep a reference to it
uint16_t mDescriptorHeapOffset;
uint16_t mDescriptorHeapSize;
};
Rhi::IResourceGroup* RootSignature::createResourceGroup([[maybe_unused]] uint32_t rootParameterIndex, uint32_t numberOfResources, Rhi::IResource** resources, [[maybe_unused]] Rhi::ISamplerState** samplerStates RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// Sanity checks
Direct3D12Rhi& direct3D12Rhi = static_cast<Direct3D12Rhi&>(getRhi());
const Rhi::Context& context = direct3D12Rhi.getContext();
RHI_ASSERT(context, numberOfResources > 0, "The number of Direct3D 12 resources must not be zero")
RHI_ASSERT(context, nullptr != resources, "The Direct3D 12 resource pointers must be valid")
// Figure out the Direct3D 12 descriptor heap type
D3D12_DESCRIPTOR_HEAP_TYPE d3d12DescriptorHeapType = D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES;
for (uint32_t resourceIndex = 0; resourceIndex < numberOfResources; ++resourceIndex)
{
Rhi::IResource* resource = *resources;
RHI_ASSERT(context, nullptr != resource, "Invalid Direct3D 12 resource")
const Rhi::ResourceType resourceType = resource->getResourceType();
if (Rhi::ResourceType::SAMPLER_STATE == resourceType)
{
RHI_ASSERT(context, D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES == d3d12DescriptorHeapType || D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER == d3d12DescriptorHeapType, "Direct3D 12 resource groups can't mix samplers with other resource types")
d3d12DescriptorHeapType = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
}
else
{
RHI_ASSERT(context, D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES == d3d12DescriptorHeapType || D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV == d3d12DescriptorHeapType, "Direct3D 12 resource groups can't mix samplers with other resource types")
d3d12DescriptorHeapType = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
}
}
// Create resource group
return RHI_NEW(context, ResourceGroup)(*this, d3d12DescriptorHeapType, numberOfResources, resources, samplerStates RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Direct3D12Rhi
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
namespace
{
namespace detail
{
//[-------------------------------------------------------]
//[ Global functions ]
//[-------------------------------------------------------]
namespace ImplementationDispatch
{
//[-------------------------------------------------------]
//[ Command buffer ]
//[-------------------------------------------------------]
void DispatchCommandBuffer(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::DispatchCommandBuffer* realData = static_cast<const Rhi::Command::DispatchCommandBuffer*>(data);
RHI_ASSERT(rhi.getContext(), nullptr != realData->commandBufferToDispatch, "The Direct3D 12 command buffer to dispatch must be valid")
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).dispatchCommandBufferInternal(*realData->commandBufferToDispatch);
}
//[-------------------------------------------------------]
//[ Graphics ]
//[-------------------------------------------------------]
void SetGraphicsRootSignature(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetGraphicsRootSignature* realData = static_cast<const Rhi::Command::SetGraphicsRootSignature*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsRootSignature(realData->rootSignature);
}
void SetGraphicsPipelineState(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetGraphicsPipelineState* realData = static_cast<const Rhi::Command::SetGraphicsPipelineState*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsPipelineState(realData->graphicsPipelineState);
}
void SetGraphicsResourceGroup(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetGraphicsResourceGroup* realData = static_cast<const Rhi::Command::SetGraphicsResourceGroup*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsResourceGroup(realData->rootParameterIndex, realData->resourceGroup);
}
void SetGraphicsVertexArray(const void* data, Rhi::IRhi& rhi)
{
// Input-assembler (IA) stage
const Rhi::Command::SetGraphicsVertexArray* realData = static_cast<const Rhi::Command::SetGraphicsVertexArray*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsVertexArray(realData->vertexArray);
}
void SetGraphicsViewports(const void* data, Rhi::IRhi& rhi)
{
// Rasterizer (RS) stage
const Rhi::Command::SetGraphicsViewports* realData = static_cast<const Rhi::Command::SetGraphicsViewports*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsViewports(realData->numberOfViewports, (nullptr != realData->viewports) ? realData->viewports : reinterpret_cast<const Rhi::Viewport*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData)));
}
void SetGraphicsScissorRectangles(const void* data, Rhi::IRhi& rhi)
{
// Rasterizer (RS) stage
const Rhi::Command::SetGraphicsScissorRectangles* realData = static_cast<const Rhi::Command::SetGraphicsScissorRectangles*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsScissorRectangles(realData->numberOfScissorRectangles, (nullptr != realData->scissorRectangles) ? realData->scissorRectangles : reinterpret_cast<const Rhi::ScissorRectangle*>(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData)));
}
void SetGraphicsRenderTarget(const void* data, Rhi::IRhi& rhi)
{
// Output-merger (OM) stage
const Rhi::Command::SetGraphicsRenderTarget* realData = static_cast<const Rhi::Command::SetGraphicsRenderTarget*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setGraphicsRenderTarget(realData->renderTarget);
}
void ClearGraphics(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::ClearGraphics* realData = static_cast<const Rhi::Command::ClearGraphics*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).clearGraphics(realData->clearFlags, realData->color, realData->z, realData->stencil);
}
void DrawGraphics(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::DrawGraphics* realData = static_cast<const Rhi::Command::DrawGraphics*>(data);
if (nullptr != realData->indirectBuffer)
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawGraphics(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws);
}
else
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws);
}
}
void DrawIndexedGraphics(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::DrawIndexedGraphics* realData = static_cast<const Rhi::Command::DrawIndexedGraphics*>(data);
if (nullptr != realData->indirectBuffer)
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawIndexedGraphics(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws);
}
else
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawIndexedGraphicsEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws);
}
}
void DrawMeshTasks(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::DrawMeshTasks* realData = static_cast<const Rhi::Command::DrawMeshTasks*>(data);
if (nullptr != realData->indirectBuffer)
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawMeshTasks(*realData->indirectBuffer, realData->indirectBufferOffset, realData->numberOfDraws);
}
else
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).drawMeshTasksEmulated(Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->indirectBufferOffset, realData->numberOfDraws);
}
}
//[-------------------------------------------------------]
//[ Compute ]
//[-------------------------------------------------------]
void SetComputeRootSignature(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetComputeRootSignature* realData = static_cast<const Rhi::Command::SetComputeRootSignature*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setComputeRootSignature(realData->rootSignature);
}
void SetComputePipelineState(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetComputePipelineState* realData = static_cast<const Rhi::Command::SetComputePipelineState*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setComputePipelineState(realData->computePipelineState);
}
void SetComputeResourceGroup(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetComputeResourceGroup* realData = static_cast<const Rhi::Command::SetComputeResourceGroup*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setComputeResourceGroup(realData->rootParameterIndex, realData->resourceGroup);
}
void DispatchCompute(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::DispatchCompute* realData = static_cast<const Rhi::Command::DispatchCompute*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).dispatchCompute(realData->groupCountX, realData->groupCountY, realData->groupCountZ);
}
//[-------------------------------------------------------]
//[ Resource ]
//[-------------------------------------------------------]
void SetTextureMinimumMaximumMipmapIndex(const void* data, [[maybe_unused]] Rhi::IRhi& rhi)
{
const Rhi::Command::SetTextureMinimumMaximumMipmapIndex* realData = static_cast<const Rhi::Command::SetTextureMinimumMaximumMipmapIndex*>(data);
RHI_ASSERT(static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).getContext(), realData->texture->getResourceType() == Rhi::ResourceType::TEXTURE_2D, "Unsupported Direct3D 12 texture resource type")
static_cast<Direct3D12Rhi::Texture2D*>(realData->texture)->setMinimumMaximumMipmapIndex(realData->minimumMipmapIndex, realData->maximumMipmapIndex);
}
void ResolveMultisampleFramebuffer(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::ResolveMultisampleFramebuffer* realData = static_cast<const Rhi::Command::ResolveMultisampleFramebuffer*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).resolveMultisampleFramebuffer(*realData->destinationRenderTarget, *realData->sourceMultisampleFramebuffer);
}
void CopyResource(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::CopyResource* realData = static_cast<const Rhi::Command::CopyResource*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).copyResource(*realData->destinationResource, *realData->sourceResource);
}
void GenerateMipmaps(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::GenerateMipmaps* realData = static_cast<const Rhi::Command::GenerateMipmaps*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).generateMipmaps(*realData->resource);
}
void CopyUniformBufferData(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::CopyUniformBufferData* realData = static_cast<const Rhi::Command::CopyUniformBufferData*>(data);
Rhi::MappedSubresource mappedSubresource;
if (rhi.map(*realData->uniformBuffer, 0, Rhi::MapType::WRITE_DISCARD, 0, mappedSubresource))
{
memcpy(mappedSubresource.data, Rhi::CommandPacketHelper::getAuxiliaryMemory(realData), realData->numberOfBytes);
rhi.unmap(*realData->uniformBuffer, 0);
}
}
void SetUniform(const void*, [[maybe_unused]] Rhi::IRhi& rhi)
{
RHI_ASSERT(rhi.getContext(), false, "The set uniform command isn't supported by the Direct3D 12 RHI implementation")
}
//[-------------------------------------------------------]
//[ Query ]
//[-------------------------------------------------------]
void ResetQueryPool(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::ResetQueryPool* realData = static_cast<const Rhi::Command::ResetQueryPool*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).resetQueryPool(*realData->queryPool, realData->firstQueryIndex, realData->numberOfQueries);
}
void BeginQuery(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::BeginQuery* realData = static_cast<const Rhi::Command::BeginQuery*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).beginQuery(*realData->queryPool, realData->queryIndex, realData->queryControlFlags);
}
void EndQuery(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::EndQuery* realData = static_cast<const Rhi::Command::EndQuery*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).endQuery(*realData->queryPool, realData->queryIndex);
}
void WriteTimestampQuery(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::WriteTimestampQuery* realData = static_cast<const Rhi::Command::WriteTimestampQuery*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).writeTimestampQuery(*realData->queryPool, realData->queryIndex);
}
//[-------------------------------------------------------]
//[ Debug ]
//[-------------------------------------------------------]
#ifdef RHI_DEBUG
void SetDebugMarker(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::SetDebugMarker* realData = static_cast<const Rhi::Command::SetDebugMarker*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).setDebugMarker(realData->name);
}
void BeginDebugEvent(const void* data, Rhi::IRhi& rhi)
{
const Rhi::Command::BeginDebugEvent* realData = static_cast<const Rhi::Command::BeginDebugEvent*>(data);
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).beginDebugEvent(realData->name);
}
void EndDebugEvent(const void*, Rhi::IRhi& rhi)
{
static_cast<Direct3D12Rhi::Direct3D12Rhi&>(rhi).endDebugEvent();
}
#else
void SetDebugMarker(const void*, Rhi::IRhi&)
{
// Nothing here
}
void BeginDebugEvent(const void*, Rhi::IRhi&)
{
// Nothing here
}
void EndDebugEvent(const void*, Rhi::IRhi&)
{
// Nothing here
}
#endif
}
//[-------------------------------------------------------]
//[ Global definitions ]
//[-------------------------------------------------------]
static constexpr Rhi::ImplementationDispatchFunction DISPATCH_FUNCTIONS[static_cast<uint8_t>(Rhi::CommandDispatchFunctionIndex::NUMBER_OF_FUNCTIONS)] =
{
// Command buffer
&ImplementationDispatch::DispatchCommandBuffer,
// Graphics
&ImplementationDispatch::SetGraphicsRootSignature,
&ImplementationDispatch::SetGraphicsPipelineState,
&ImplementationDispatch::SetGraphicsResourceGroup,
&ImplementationDispatch::SetGraphicsVertexArray, // Input-assembler (IA) stage
&ImplementationDispatch::SetGraphicsViewports, // Rasterizer (RS) stage
&ImplementationDispatch::SetGraphicsScissorRectangles, // Rasterizer (RS) stage
&ImplementationDispatch::SetGraphicsRenderTarget, // Output-merger (OM) stage
&ImplementationDispatch::ClearGraphics,
&ImplementationDispatch::DrawGraphics,
&ImplementationDispatch::DrawIndexedGraphics,
&ImplementationDispatch::DrawMeshTasks,
// Compute
&ImplementationDispatch::SetComputeRootSignature,
&ImplementationDispatch::SetComputePipelineState,
&ImplementationDispatch::SetComputeResourceGroup,
&ImplementationDispatch::DispatchCompute,
// Resource
&ImplementationDispatch::SetTextureMinimumMaximumMipmapIndex,
&ImplementationDispatch::ResolveMultisampleFramebuffer,
&ImplementationDispatch::CopyResource,
&ImplementationDispatch::GenerateMipmaps,
&ImplementationDispatch::CopyUniformBufferData,
&ImplementationDispatch::SetUniform,
// Query
&ImplementationDispatch::ResetQueryPool,
&ImplementationDispatch::BeginQuery,
&ImplementationDispatch::EndQuery,
&ImplementationDispatch::WriteTimestampQuery,
// Debug
&ImplementationDispatch::SetDebugMarker,
&ImplementationDispatch::BeginDebugEvent,
&ImplementationDispatch::EndDebugEvent
};
//[-------------------------------------------------------]
//[ Anonymous detail namespace ]
//[-------------------------------------------------------]
} // detail
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Direct3D12Rhi
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
Direct3D12Rhi::Direct3D12Rhi(const Rhi::Context& context) :
IRhi(Rhi::NameId::DIRECT3D12, context),
VertexArrayMakeId(context.getAllocator()),
GraphicsPipelineStateMakeId(context.getAllocator()),
ComputePipelineStateMakeId(context.getAllocator()),
mDirect3D12RuntimeLinking(nullptr),
mDxgiFactory4(nullptr),
mD3D12Device(nullptr),
mD3D12CommandQueue(nullptr),
mD3D12CommandAllocator(nullptr),
mD3D12GraphicsCommandList(nullptr),
mShaderLanguageHlsl(nullptr),
mShaderResourceViewDescriptorHeap(nullptr),
mRenderTargetViewDescriptorHeap(nullptr),
mDepthStencilViewDescriptorHeap(nullptr),
mSamplerDescriptorHeap(nullptr),
mRenderTarget(nullptr),
mD3D12PrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_UNDEFINED),
mGraphicsRootSignature(nullptr),
mComputeRootSignature(nullptr),
mVertexArray(nullptr)
{
mDirect3D12RuntimeLinking = RHI_NEW(mContext, Direct3D12RuntimeLinking)(*this);
// Is Direct3D 12 available?
if (mDirect3D12RuntimeLinking->isDirect3D12Avaiable())
{
// Create the DXGI factory instance
if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&mDxgiFactory4))))
{
// Enable the Direct3D 12 debug layer
#ifdef RHI_DEBUG
{
ID3D12Debug* d3d12Debug = nullptr;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&d3d12Debug))))
{
d3d12Debug->EnableDebugLayer();
d3d12Debug->Release();
}
}
#endif
// Create the Direct3D 12 device
// -> In case of failure, create an emulated device instance so we can at least test the DirectX 12 API
if (FAILED(D3D12CreateDevice(nullptr, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&mD3D12Device))))
{
RHI_LOG(mContext, CRITICAL, "Failed to create Direct3D 12 device instance. Creating an emulated Direct3D 11 device instance instead.")
// Create the DXGI adapter instance
IDXGIAdapter* dxgiAdapter = nullptr;
if (SUCCEEDED(mDxgiFactory4->EnumWarpAdapter(IID_PPV_ARGS(&dxgiAdapter))))
{
// Create the emulated Direct3D 12 device
if (FAILED(D3D12CreateDevice(dxgiAdapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&mD3D12Device))))
{
RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 12 device instance")
}
// Release the DXGI adapter instance
dxgiAdapter->Release();
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to create Direct3D 12 DXGI adapter instance")
}
}
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to create Direct3D 12 DXGI factory instance")
}
// Is there a valid Direct3D 12 device instance?
if (nullptr != mD3D12Device)
{
// Describe and create the command queue
D3D12_COMMAND_QUEUE_DESC d3d12CommandQueueDesc;
d3d12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
d3d12CommandQueueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
d3d12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
d3d12CommandQueueDesc.NodeMask = 0;
if (SUCCEEDED(mD3D12Device->CreateCommandQueue(&d3d12CommandQueueDesc, IID_PPV_ARGS(&mD3D12CommandQueue))))
{
// Create the command allocator
if (SUCCEEDED(mD3D12Device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&mD3D12CommandAllocator))))
{
// Create the command list
if (SUCCEEDED(mD3D12Device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, mD3D12CommandAllocator, nullptr, IID_PPV_ARGS(&mD3D12GraphicsCommandList))))
{
// Command lists are created in the recording state, but there is nothing to record yet. The main loop expects it to be closed, so close it now.
if (SUCCEEDED(mD3D12GraphicsCommandList->Close()))
{
// Initialize the capabilities
initializeCapabilities();
// Create and begin upload context
mUploadContext.create(*mD3D12Device);
// Create descriptor heaps
// TODO(co) The initial descriptor heap sizes are probably too small, additionally the descriptor heap should be able to dynamically grow during runtime (in case it can't be avoided)
mShaderResourceViewDescriptorHeap = RHI_NEW(mContext, ::detail::DescriptorHeap)(mContext.getAllocator(), *mD3D12Device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 64, true);
mRenderTargetViewDescriptorHeap = RHI_NEW(mContext, ::detail::DescriptorHeap)(mContext.getAllocator(), *mD3D12Device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 16, false);
mDepthStencilViewDescriptorHeap = RHI_NEW(mContext, ::detail::DescriptorHeap)(mContext.getAllocator(), *mD3D12Device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 16, false);
mSamplerDescriptorHeap = RHI_NEW(mContext, ::detail::DescriptorHeap)(mContext.getAllocator(), *mD3D12Device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 16, true);
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to close the Direct3D 12 command list instance")
}
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 12 command list instance")
}
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 12 command allocator instance")
}
}
else
{
RHI_LOG(mContext, CRITICAL, "Failed to create the Direct3D 12 command queue instance")
}
}
}
}
Direct3D12Rhi::~Direct3D12Rhi()
{
// Set no vertex array reference, in case we have one
setGraphicsVertexArray(nullptr);
// Release instances
if (nullptr != mRenderTarget)
{
mRenderTarget->releaseReference();
mRenderTarget = nullptr;
}
#ifdef RHI_STATISTICS
{ // For debugging: At this point there should be no resource instances left, validate this!
// -> Are the currently any resource instances?
const uint32_t numberOfCurrentResources = getStatistics().getNumberOfCurrentResources();
if (numberOfCurrentResources > 0)
{
// Error!
if (numberOfCurrentResources > 1)
{
RHI_LOG(mContext, CRITICAL, "The Direct3D 12 RHI implementation is going to be destroyed, but there are still %u resource instances left (memory leak)", numberOfCurrentResources)
}
else
{
RHI_LOG(mContext, CRITICAL, "The Direct3D 12 RHI implementation is going to be destroyed, but there is still one resource instance left (memory leak)")
}
// Use debug output to show the current number of resource instances
getStatistics().debugOutputCurrentResouces(mContext);
}
}
#endif
// Release the graphics and compute root signature instance, in case we have one
if (nullptr != mGraphicsRootSignature)
{
mGraphicsRootSignature->releaseReference();
}
if (nullptr != mComputeRootSignature)
{
mComputeRootSignature->releaseReference();
}
// Destroy upload context
mUploadContext.destroy();
// Release descriptor heaps
RHI_DELETE(mContext, ::detail::DescriptorHeap, mShaderResourceViewDescriptorHeap);
RHI_DELETE(mContext, ::detail::DescriptorHeap, mRenderTargetViewDescriptorHeap);
RHI_DELETE(mContext, ::detail::DescriptorHeap, mDepthStencilViewDescriptorHeap);
RHI_DELETE(mContext, ::detail::DescriptorHeap, mSamplerDescriptorHeap);
// Release the HLSL shader language instance, in case we have one
if (nullptr != mShaderLanguageHlsl)
{
mShaderLanguageHlsl->releaseReference();
}
// Release the Direct3D 12 command queue we've created
if (nullptr != mD3D12GraphicsCommandList)
{
mD3D12GraphicsCommandList->Release();
mD3D12GraphicsCommandList = nullptr;
}
if (nullptr != mD3D12CommandAllocator)
{
mD3D12CommandAllocator->Release();
mD3D12CommandAllocator = nullptr;
}
if (nullptr != mD3D12CommandQueue)
{
mD3D12CommandQueue->Release();
mD3D12CommandQueue = nullptr;
}
// Release the Direct3D 12 device we've created
if (nullptr != mD3D12Device)
{
mD3D12Device->Release();
mD3D12Device = nullptr;
}
// Release the DXGI factory instance
if (nullptr != mDxgiFactory4)
{
mDxgiFactory4->Release();
mDxgiFactory4 = nullptr;
}
// Destroy the Direct3D 12 runtime linking instance
RHI_DELETE(mContext, Direct3D12RuntimeLinking, mDirect3D12RuntimeLinking);
}
void Direct3D12Rhi::dispatchCommandBufferInternal(const Rhi::CommandBuffer& commandBuffer)
{
// Loop through all commands
const uint8_t* commandPacketBuffer = commandBuffer.getCommandPacketBuffer();
Rhi::ConstCommandPacket constCommandPacket = commandPacketBuffer;
while (nullptr != constCommandPacket)
{
{ // Dispatch command packet
const Rhi::CommandDispatchFunctionIndex commandDispatchFunctionIndex = Rhi::CommandPacketHelper::loadCommandDispatchFunctionIndex(constCommandPacket);
const void* command = Rhi::CommandPacketHelper::loadCommand(constCommandPacket);
detail::DISPATCH_FUNCTIONS[static_cast<uint32_t>(commandDispatchFunctionIndex)](command, *this);
}
{ // Next command
const uint32_t nextCommandPacketByteIndex = Rhi::CommandPacketHelper::getNextCommandPacketByteIndex(constCommandPacket);
constCommandPacket = (~0u != nextCommandPacketByteIndex) ? &commandPacketBuffer[nextCommandPacketByteIndex] : nullptr;
}
}
}
//[-------------------------------------------------------]
//[ Graphics ]
//[-------------------------------------------------------]
void Direct3D12Rhi::setGraphicsRootSignature(Rhi::IRootSignature* rootSignature)
{
if (nullptr != mGraphicsRootSignature)
{
mGraphicsRootSignature->releaseReference();
}
mGraphicsRootSignature = static_cast<RootSignature*>(rootSignature);
if (nullptr != mGraphicsRootSignature)
{
mGraphicsRootSignature->addReference();
// Sanity check
RHI_MATCH_CHECK(*this, *rootSignature)
// Set graphics root signature
mD3D12GraphicsCommandList->SetGraphicsRootSignature(mGraphicsRootSignature->getD3D12RootSignature());
}
}
void Direct3D12Rhi::setGraphicsPipelineState(Rhi::IGraphicsPipelineState* graphicsPipelineState)
{
if (nullptr != graphicsPipelineState)
{
// Sanity check
RHI_MATCH_CHECK(*this, *graphicsPipelineState)
// Set primitive topology
// -> The "Rhi::PrimitiveTopology" values directly map to Direct3D 9 & 10 & 11 && 12 constants, do not change them
const GraphicsPipelineState* direct3D12GraphicsPipelineState = static_cast<const GraphicsPipelineState*>(graphicsPipelineState);
if (mD3D12PrimitiveTopology != direct3D12GraphicsPipelineState->getD3D12PrimitiveTopology())
{
mD3D12PrimitiveTopology = direct3D12GraphicsPipelineState->getD3D12PrimitiveTopology();
mD3D12GraphicsCommandList->IASetPrimitiveTopology(mD3D12PrimitiveTopology);
}
// Set graphics pipeline state
mD3D12GraphicsCommandList->SetPipelineState(direct3D12GraphicsPipelineState->getD3D12GraphicsPipelineState());
}
else
{
// TODO(co) Handle this situation?
}
}
void Direct3D12Rhi::setGraphicsResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup)
{
// Security checks
#ifdef RHI_DEBUG
{
RHI_ASSERT(mContext, nullptr != mGraphicsRootSignature, "No Direct3D 12 RHI implementation graphics root signature set")
const Rhi::RootSignature& rootSignature = mGraphicsRootSignature->getRootSignature();
RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The Direct3D 12 RHI implementation root parameter index is out of bounds")
const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex];
RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The Direct3D 12 RHI implementation root parameter index doesn't reference a descriptor table")
RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The Direct3D 12 RHI implementation descriptor ranges is a null pointer")
}
#endif
if (nullptr != resourceGroup)
{
// Sanity check
RHI_MATCH_CHECK(*this, *resourceGroup)
// Set Direct3D 12 graphics root descriptor table
const ResourceGroup* direct3D12ResourceGroup = static_cast<ResourceGroup*>(resourceGroup);
const ::detail::DescriptorHeap& descriptorHeap = (direct3D12ResourceGroup->getD3D12DescriptorHeapType() == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) ? *mShaderResourceViewDescriptorHeap : *mSamplerDescriptorHeap;
D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle = descriptorHeap.getD3D12GpuDescriptorHandleForHeapStart();
d3d12GpuDescriptorHandle.ptr += static_cast<UINT64>(direct3D12ResourceGroup->getDescriptorHeapOffset()) * descriptorHeap.getDescriptorSize();
mD3D12GraphicsCommandList->SetGraphicsRootDescriptorTable(rootParameterIndex, d3d12GpuDescriptorHandle);
}
else
{
// TODO(co) Handle this situation?
}
}
void Direct3D12Rhi::setGraphicsVertexArray(Rhi::IVertexArray* vertexArray)
{
// Input-assembler (IA) stage
// New vertex array?
if (mVertexArray != vertexArray)
{
if (nullptr != vertexArray)
{
// Sanity check
RHI_MATCH_CHECK(*this, *vertexArray)
// Begin debug event
RHI_BEGIN_DEBUG_EVENT_FUNCTION(this)
// Unset the currently used vertex array
unsetGraphicsVertexArray();
// Set new vertex array and add a reference to it
mVertexArray = static_cast<VertexArray*>(vertexArray);
mVertexArray->addReference();
mVertexArray->setDirect3DIASetInputLayoutAndStreamSource(*mD3D12GraphicsCommandList);
// End debug event
RHI_END_DEBUG_EVENT(this)
}
else
{
// Unset the currently used vertex array
unsetGraphicsVertexArray();
}
}
}
void Direct3D12Rhi::setGraphicsViewports(uint32_t numberOfViewports, const Rhi::Viewport* viewports)
{
// Rasterizer (RS) stage
// Sanity check
RHI_ASSERT(mContext, numberOfViewports > 0 && nullptr != viewports, "Invalid Direct3D 12 rasterizer state viewports")
// Set the Direct3D 12 viewports
// -> "Rhi::Viewport" directly maps to Direct3D 12, do not change it
// -> Let Direct3D 12 perform the index validation for us (the Direct3D 12 debug features are pretty good)
mD3D12GraphicsCommandList->RSSetViewports(numberOfViewports, reinterpret_cast<const D3D12_VIEWPORT*>(viewports));
}
void Direct3D12Rhi::setGraphicsScissorRectangles(uint32_t numberOfScissorRectangles, const Rhi::ScissorRectangle* scissorRectangles)
{
// Rasterizer (RS) stage
// Sanity check
RHI_ASSERT(mContext, numberOfScissorRectangles > 0 && nullptr != scissorRectangles, "Invalid Direct3D 12 rasterizer state scissor rectangles")
// Set the Direct3D 12 scissor rectangles
// -> "Rhi::ScissorRectangle" directly maps to Direct3D 9 & 10 & 11 & 12, do not change it
// -> Let Direct3D 12 perform the index validation for us (the Direct3D 12 debug features are pretty good)
mD3D12GraphicsCommandList->RSSetScissorRects(numberOfScissorRectangles, reinterpret_cast<const D3D12_RECT*>(scissorRectangles));
}
void Direct3D12Rhi::setGraphicsRenderTarget(Rhi::IRenderTarget* renderTarget)
{
// Output-merger (OM) stage
// New render target?
if (mRenderTarget != renderTarget)
{
// Unset the previous render target
if (nullptr != mRenderTarget)
{
// Evaluate the render target type
switch (mRenderTarget->getResourceType())
{
case Rhi::ResourceType::SWAP_CHAIN:
{
// Get the Direct3D 12 swap chain instance
SwapChain* swapChain = static_cast<SwapChain*>(mRenderTarget);
// Inform Direct3D 12 about the resource transition
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(swapChain->getBackD3D12ResourceRenderTarget(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
break;
}
case Rhi::ResourceType::FRAMEBUFFER:
{
// TODO(co) Implement resource transition handling (first "Direct3D12Rhi::Texture2D" needs to be cleaned up)
/*
// Get the Direct3D 12 framebuffer instance
Framebuffer* framebuffer = static_cast<Framebuffer*>(mRenderTarget);
// Inform Direct3D 12 about the resource transitions
const uint32_t numberOfColorTextures = framebuffer->getNumberOfColorTextures();
for (uint32_t i = 0; i < numberOfColorTextures; ++i)
{
// TODO(co) Resource type handling, currently only 2D texture is supported
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(static_cast<Texture2D*>(framebuffer->getColorTextures()[i])->getD3D12Resource(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_GENERIC_READ);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
}
if (nullptr != framebuffer->getDepthStencilTexture())
{
// TODO(co) Resource type handling, currently only 2D texture is supported
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(static_cast<Texture2D*>(framebuffer->getDepthStencilTexture())->getD3D12Resource(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_GENERIC_READ);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
}
*/
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_2D:
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
// Not handled in here
break;
}
// Release the render target reference, in case we have one
mRenderTarget->releaseReference();
mRenderTarget = nullptr;
}
// Set a render target?
if (nullptr != renderTarget)
{
// Sanity check
RHI_MATCH_CHECK(*this, *renderTarget)
// Set new render target and add a reference to it
mRenderTarget = renderTarget;
mRenderTarget->addReference();
// Evaluate the render target type
switch (mRenderTarget->getResourceType())
{
case Rhi::ResourceType::SWAP_CHAIN:
{
// Get the Direct3D 12 swap chain instance
SwapChain* swapChain = static_cast<SwapChain*>(mRenderTarget);
{ // Inform Direct3D 12 about the resource transition
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(swapChain->getBackD3D12ResourceRenderTarget(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
}
// Set Direct3D 12 render target
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(swapChain->getD3D12DescriptorHeapRenderTargetView()->GetCPUDescriptorHandleForHeapStart(), static_cast<INT>(swapChain->getBackD3D12ResourceRenderTargetFrameIndex()), swapChain->getRenderTargetViewDescriptorSize());
CD3DX12_CPU_DESCRIPTOR_HANDLE dsvHandle(swapChain->getD3D12DescriptorHeapDepthStencilView()->GetCPUDescriptorHandleForHeapStart());
mD3D12GraphicsCommandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
break;
}
case Rhi::ResourceType::FRAMEBUFFER:
{
// Get the Direct3D 12 framebuffer instance
Framebuffer* framebuffer = static_cast<Framebuffer*>(mRenderTarget);
// Set the Direct3D 12 render targets
const uint32_t numberOfColorTextures = framebuffer->getNumberOfColorTextures();
D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandlesRenderTarget[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT];
for (uint32_t i = 0; i < numberOfColorTextures; ++i)
{
d3d12CpuDescriptorHandlesRenderTarget[i] = framebuffer->getD3D12DescriptorHeapRenderTargetViews()[i]->GetCPUDescriptorHandleForHeapStart();
// TODO(co) Implement resource transition handling (first "Direct3D12Rhi::Texture2D" needs to be cleaned up)
/*
{ // Inform Direct3D 12 about the resource transition
// TODO(co) Resource type handling, currently only 2D texture is supported
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(static_cast<Texture2D*>(framebuffer->getColorTextures()[i])->getD3D12Resource(), D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_RENDER_TARGET);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
}
*/
}
ID3D12DescriptorHeap* d3d12DescriptorHeapDepthStencilView = framebuffer->getD3D12DescriptorHeapDepthStencilView();
if (nullptr != d3d12DescriptorHeapDepthStencilView)
{
// TODO(co) Implement resource transition handling (first "Direct3D12Rhi::Texture2D" needs to be cleaned up)
/*
{ // Inform Direct3D 12 about the resource transition
// TODO(co) Resource type handling, currently only 2D texture is supported
CD3DX12_RESOURCE_BARRIER d3d12XResourceBarrier = CD3DX12_RESOURCE_BARRIER::Transition(static_cast<Texture2D*>(framebuffer->getDepthStencilTexture())->getD3D12Resource(), D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_RENDER_TARGET);
mD3D12GraphicsCommandList->ResourceBarrier(1, &d3d12XResourceBarrier);
}
*/
// Set the Direct3D 12 render targets
D3D12_CPU_DESCRIPTOR_HANDLE d3d12CpuDescriptorHandlesDepthStencil = d3d12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart();
mD3D12GraphicsCommandList->OMSetRenderTargets(numberOfColorTextures, d3d12CpuDescriptorHandlesRenderTarget, FALSE, &d3d12CpuDescriptorHandlesDepthStencil);
}
else
{
mD3D12GraphicsCommandList->OMSetRenderTargets(numberOfColorTextures, d3d12CpuDescriptorHandlesRenderTarget, FALSE, nullptr);
}
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_2D:
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
// Not handled in here
break;
}
}
else
{
mD3D12GraphicsCommandList->OMSetRenderTargets(0, nullptr, FALSE, nullptr);
}
}
}
void Direct3D12Rhi::clearGraphics(uint32_t clearFlags, const float color[4], float z, uint32_t stencil)
{
// Unlike Direct3D 9, OpenGL or OpenGL ES 3, Direct3D 12 clears a given render target view and not the currently bound
// -> No resource transition required in here, it's handled inside "Direct3D12Rhi::omSetRenderTarget()"
// Sanity check
RHI_ASSERT(mContext, z >= 0.0f && z <= 1.0f, "The Direct3D 12 clear graphics z value must be between [0, 1] (inclusive)")
// Begin debug event
RHI_BEGIN_DEBUG_EVENT_FUNCTION(this)
// Render target set?
if (nullptr != mRenderTarget)
{
// Evaluate the render target type
switch (mRenderTarget->getResourceType())
{
case Rhi::ResourceType::SWAP_CHAIN:
{
// Get the Direct3D 12 swap chain instance
SwapChain* swapChain = static_cast<SwapChain*>(mRenderTarget);
// Clear the Direct3D 12 render target view?
if (clearFlags & Rhi::ClearFlag::COLOR)
{
CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(swapChain->getD3D12DescriptorHeapRenderTargetView()->GetCPUDescriptorHandleForHeapStart(), static_cast<INT>(swapChain->getBackD3D12ResourceRenderTargetFrameIndex()), swapChain->getRenderTargetViewDescriptorSize());
mD3D12GraphicsCommandList->ClearRenderTargetView(rtvHandle, color, 0, nullptr);
}
{ // Clear the Direct3D 12 depth stencil view?
ID3D12DescriptorHeap* d3d12DescriptorHeapDepthStencilView = swapChain->getD3D12DescriptorHeapDepthStencilView();
if (nullptr != d3d12DescriptorHeapDepthStencilView)
{
// Get the Direct3D 12 clear flags
UINT direct3D12ClearFlags = (clearFlags & Rhi::ClearFlag::DEPTH) ? D3D12_CLEAR_FLAG_DEPTH : 0u;
if (clearFlags & Rhi::ClearFlag::STENCIL)
{
direct3D12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL;
}
if (0 != direct3D12ClearFlags)
{
// Clear the Direct3D 12 depth stencil view
mD3D12GraphicsCommandList->ClearDepthStencilView(d3d12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart(), static_cast<D3D12_CLEAR_FLAGS>(direct3D12ClearFlags), z, static_cast<UINT8>(stencil), 0, nullptr);
}
}
}
break;
}
case Rhi::ResourceType::FRAMEBUFFER:
{
// Get the Direct3D 12 framebuffer instance
Framebuffer* framebuffer = static_cast<Framebuffer*>(mRenderTarget);
// Clear all Direct3D 12 render target views?
if (clearFlags & Rhi::ClearFlag::COLOR)
{
// Loop through all Direct3D 12 render target views
ID3D12DescriptorHeap **d3d12DescriptorHeapRenderTargetViews = framebuffer->getD3D12DescriptorHeapRenderTargetViews() + framebuffer->getNumberOfColorTextures();
for (ID3D12DescriptorHeap **d3d12DescriptorHeapRenderTargetView = framebuffer->getD3D12DescriptorHeapRenderTargetViews(); d3d12DescriptorHeapRenderTargetView < d3d12DescriptorHeapRenderTargetViews; ++d3d12DescriptorHeapRenderTargetView)
{
// Valid Direct3D 12 render target view?
if (nullptr != *d3d12DescriptorHeapRenderTargetView)
{
mD3D12GraphicsCommandList->ClearRenderTargetView((*d3d12DescriptorHeapRenderTargetView)->GetCPUDescriptorHandleForHeapStart(), color, 0, nullptr);
}
}
}
// Clear the Direct3D 12 depth stencil view?
ID3D12DescriptorHeap* d3d12DescriptorHeapDepthStencilView = framebuffer->getD3D12DescriptorHeapDepthStencilView();
if (nullptr != d3d12DescriptorHeapDepthStencilView)
{
// Get the Direct3D 12 clear flags
UINT direct3D12ClearFlags = (clearFlags & Rhi::ClearFlag::DEPTH) ? D3D12_CLEAR_FLAG_DEPTH : 0u;
if (clearFlags & Rhi::ClearFlag::STENCIL)
{
direct3D12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL;
}
if (0 != direct3D12ClearFlags)
{
// Clear the Direct3D 12 depth stencil view
mD3D12GraphicsCommandList->ClearDepthStencilView(d3d12DescriptorHeapDepthStencilView->GetCPUDescriptorHandleForHeapStart(), static_cast<D3D12_CLEAR_FLAGS>(direct3D12ClearFlags), z, static_cast<UINT8>(stencil), 0, nullptr);
}
}
break;
}
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::VERTEX_BUFFER:
case Rhi::ResourceType::INDEX_BUFFER:
case Rhi::ResourceType::TEXTURE_BUFFER:
case Rhi::ResourceType::STRUCTURED_BUFFER:
case Rhi::ResourceType::INDIRECT_BUFFER:
case Rhi::ResourceType::UNIFORM_BUFFER:
case Rhi::ResourceType::TEXTURE_1D:
case Rhi::ResourceType::TEXTURE_1D_ARRAY:
case Rhi::ResourceType::TEXTURE_2D:
case Rhi::ResourceType::TEXTURE_2D_ARRAY:
case Rhi::ResourceType::TEXTURE_3D:
case Rhi::ResourceType::TEXTURE_CUBE:
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
// Not handled in here
break;
}
}
else
{
// In case no render target is currently set we don't have to do anything in here
}
// End debug event
RHI_END_DEBUG_EVENT(this)
}
void Direct3D12Rhi::drawGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws)
{
// Sanity checks
RHI_MATCH_CHECK(*this, indirectBuffer)
RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 12 draws must not be zero")
// It's possible to draw without "mVertexArray"
// Execute Direct3D 12 indirect
const IndirectBuffer& d3d12IndirectBuffer = static_cast<const IndirectBuffer&>(indirectBuffer);
mD3D12GraphicsCommandList->ExecuteIndirect(d3d12IndirectBuffer.getD3D12CommandSignature(), numberOfDraws, d3d12IndirectBuffer.getD3D12Resource(), indirectBufferOffset, nullptr, 0);
}
void Direct3D12Rhi::drawGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset, uint32_t numberOfDraws)
{
// Sanity checks
RHI_ASSERT(mContext, nullptr != emulationData, "The Direct3D 12 emulation data must be valid")
RHI_ASSERT(mContext, numberOfDraws > 0, "The number of Direct3D 12 draws must not be zero")
// TODO(co) Currently no buffer overflow check due to lack of interface provided data
emulationData += indirectBufferOffset;
// Emit the draw calls
#ifdef RHI_DEBUG
if (numberOfDraws > 1)
{
beginDebugEvent("Multi-draw-indirect emulation");
}
#endif
for (uint32_t i = 0; i < numberOfDraws; ++i)
{
const Rhi::DrawArguments& drawArguments = *reinterpret_cast<const Rhi::DrawArguments*>(emulationData);
// Draw
mD3D12GraphicsCommandList->DrawInstanced(
drawArguments.vertexCountPerInstance, // Vertex count per instance (UINT)
drawArguments.instanceCount, // Instance count (UINT)
drawArguments.startVertexLocation, // Start vertex location (UINT)
drawArguments.startInstanceLocation // Start instance location (UINT)
);
// Advance
emulationData += sizeof(Rhi::DrawArguments);
}
#ifdef RHI_DEBUG
if (numberOfDraws > 1)
{
endDebugEvent();
}
#endif
}
void Direct3D12Rhi::drawIndexedGraphics(const Rhi::IIndirectBuffer& indirectBuffer, uint32_t indirectBufferOffset, uint32_t numberOfDraws)
{
// Sanity checks
RHI_MATCH_CHECK(*this, indirectBuffer)
RHI_ASSERT(mContext, numberOfDraws > 0, "Number of Direct3D 12 draws must not be zero")
RHI_ASSERT(mContext, nullptr != mVertexArray, "Direct3D 12 draw indexed needs a set vertex array")
RHI_ASSERT(mContext, nullptr != mVertexArray->getIndexBuffer(), "Direct3D 12 draw indexed needs a set vertex array which contains an index buffer")
// Execute Direct3D 12 indirect
const IndirectBuffer& d3d12IndirectBuffer = static_cast<const IndirectBuffer&>(indirectBuffer);
mD3D12GraphicsCommandList->ExecuteIndirect(d3d12IndirectBuffer.getD3D12CommandSignature(), numberOfDraws, d3d12IndirectBuffer.getD3D12Resource(), indirectBufferOffset, nullptr, 0);
}
void Direct3D12Rhi::drawIndexedGraphicsEmulated(const uint8_t* emulationData, uint32_t indirectBufferOffset, uint32_t numberOfDraws)
{
// Sanity checks
RHI_ASSERT(mContext, nullptr != emulationData, "The Direct3D 12 emulation data must be valid")
RHI_ASSERT(mContext, numberOfDraws > 0, "The number of Direct3D 12 draws must not be zero")
// TODO(co) Currently no buffer overflow check due to lack of interface provided data
emulationData += indirectBufferOffset;
// Emit the draw calls
#ifdef RHI_DEBUG
if (numberOfDraws > 1)
{
beginDebugEvent("Multi-indexed-draw-indirect emulation");
}
#endif
for (uint32_t i = 0; i < numberOfDraws; ++i)
{
const Rhi::DrawIndexedArguments& drawIndexedArguments = *reinterpret_cast<const Rhi::DrawIndexedArguments*>(emulationData);
// Draw
mD3D12GraphicsCommandList->DrawIndexedInstanced(
drawIndexedArguments.indexCountPerInstance, // Index count per instance (UINT)
drawIndexedArguments.instanceCount, // Instance count (UINT)
drawIndexedArguments.startIndexLocation, // Start index location (UINT)
drawIndexedArguments.baseVertexLocation, // Base vertex location (INT)
drawIndexedArguments.startInstanceLocation // Start instance location (UINT)
);
// Advance
emulationData += sizeof(Rhi::DrawIndexedArguments);
}
#ifdef RHI_DEBUG
if (numberOfDraws > 1)
{
endDebugEvent();
}
#endif
}
void Direct3D12Rhi::drawMeshTasks([[maybe_unused]] const Rhi::IIndirectBuffer& indirectBuffer, [[maybe_unused]] uint32_t indirectBufferOffset, [[maybe_unused]] uint32_t numberOfDraws)
{
// Sanity checks
RHI_ASSERT(mContext, numberOfDraws > 0, "The number of null draws must not be zero")
// TODO(co) Implement me
}
void Direct3D12Rhi::drawMeshTasksEmulated([[maybe_unused]] const uint8_t* emulationData, uint32_t, [[maybe_unused]] uint32_t numberOfDraws)
{
// Sanity checks
RHI_ASSERT(mContext, nullptr != emulationData, "The null emulation data must be valid")
RHI_ASSERT(mContext, numberOfDraws > 0, "The number of null draws must not be zero")
// TODO(co) Implement me
}
//[-------------------------------------------------------]
//[ Compute ]
//[-------------------------------------------------------]
void Direct3D12Rhi::setComputeRootSignature(Rhi::IRootSignature* rootSignature)
{
if (nullptr != mComputeRootSignature)
{
mComputeRootSignature->releaseReference();
}
mComputeRootSignature = static_cast<RootSignature*>(rootSignature);
if (nullptr != mComputeRootSignature)
{
mComputeRootSignature->addReference();
// Sanity check
RHI_MATCH_CHECK(*this, *rootSignature)
// Set compute root signature
mD3D12GraphicsCommandList->SetComputeRootSignature(mComputeRootSignature->getD3D12RootSignature());
}
}
void Direct3D12Rhi::setComputePipelineState(Rhi::IComputePipelineState* computePipelineState)
{
if (nullptr != computePipelineState)
{
// Sanity check
RHI_MATCH_CHECK(*this, *computePipelineState)
// Set compute pipeline state
mD3D12GraphicsCommandList->SetPipelineState(static_cast<ComputePipelineState*>(computePipelineState)->getD3D12ComputePipelineState());
}
else
{
// TODO(co) Handle this situation?
}
}
void Direct3D12Rhi::setComputeResourceGroup(uint32_t rootParameterIndex, Rhi::IResourceGroup* resourceGroup)
{
// Security checks
#ifdef RHI_DEBUG
{
RHI_ASSERT(mContext, nullptr != mComputeRootSignature, "No Direct3D 12 RHI implementation compute root signature set")
const Rhi::RootSignature& rootSignature = mComputeRootSignature->getRootSignature();
RHI_ASSERT(mContext, rootParameterIndex < rootSignature.numberOfParameters, "The Direct3D 12 RHI implementation root parameter index is out of bounds")
const Rhi::RootParameter& rootParameter = rootSignature.parameters[rootParameterIndex];
RHI_ASSERT(mContext, Rhi::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType, "The Direct3D 12 RHI implementation root parameter index doesn't reference a descriptor table")
RHI_ASSERT(mContext, nullptr != reinterpret_cast<const Rhi::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "The Direct3D 12 RHI implementation descriptor ranges is a null pointer")
}
#endif
if (nullptr != resourceGroup)
{
// Sanity check
RHI_MATCH_CHECK(*this, *resourceGroup)
// Set Direct3D 12 compute root descriptor table
const ResourceGroup* direct3D12ResourceGroup = static_cast<ResourceGroup*>(resourceGroup);
const ::detail::DescriptorHeap& descriptorHeap = (direct3D12ResourceGroup->getD3D12DescriptorHeapType() == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) ? *mShaderResourceViewDescriptorHeap : *mSamplerDescriptorHeap;
D3D12_GPU_DESCRIPTOR_HANDLE d3d12GpuDescriptorHandle = descriptorHeap.getD3D12GpuDescriptorHandleForHeapStart();
d3d12GpuDescriptorHandle.ptr += static_cast<UINT64>(direct3D12ResourceGroup->getDescriptorHeapOffset()) * descriptorHeap.getDescriptorSize();
mD3D12GraphicsCommandList->SetComputeRootDescriptorTable(rootParameterIndex, d3d12GpuDescriptorHandle);
}
else
{
// TODO(co) Handle this situation?
}
}
void Direct3D12Rhi::dispatchCompute(uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ)
{
mD3D12GraphicsCommandList->Dispatch(groupCountX, groupCountY, groupCountZ);
}
//[-------------------------------------------------------]
//[ Resource ]
//[-------------------------------------------------------]
void Direct3D12Rhi::resolveMultisampleFramebuffer(Rhi::IRenderTarget&, Rhi::IFramebuffer&)
{
// TODO(co) Implement me
}
void Direct3D12Rhi::copyResource(Rhi::IResource&, Rhi::IResource&)
{
// TODO(co) Implement me
}
void Direct3D12Rhi::generateMipmaps(Rhi::IResource&)
{
// TODO(co) Implement me
}
//[-------------------------------------------------------]
//[ Query ]
//[-------------------------------------------------------]
void Direct3D12Rhi::resetQueryPool([[maybe_unused]] Rhi::IQueryPool& queryPool, [[maybe_unused]] uint32_t firstQueryIndex, [[maybe_unused]] uint32_t numberOfQueries)
{
// Sanity checks
RHI_MATCH_CHECK(*this, queryPool)
RHI_ASSERT(mContext, firstQueryIndex < static_cast<const QueryPool&>(queryPool).getNumberOfQueries(), "Direct3D 12 out-of-bounds query index")
RHI_ASSERT(mContext, (firstQueryIndex + numberOfQueries) <= static_cast<const QueryPool&>(queryPool).getNumberOfQueries(), "Direct3D 12 out-of-bounds query index")
// Nothing to do in here for Direct3D 12
}
void Direct3D12Rhi::beginQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex, uint32_t)
{
// Sanity check
RHI_MATCH_CHECK(*this, queryPool)
// Query pool type dependent processing
const QueryPool& d3d12QueryPool = static_cast<const QueryPool&>(queryPool);
RHI_ASSERT(mContext, queryIndex < d3d12QueryPool.getNumberOfQueries(), "Direct3D 12 out-of-bounds query index")
switch (d3d12QueryPool.getQueryType())
{
case Rhi::QueryType::OCCLUSION:
mD3D12GraphicsCommandList->BeginQuery(d3d12QueryPool.getD3D12QueryHeap(), D3D12_QUERY_TYPE_OCCLUSION, queryIndex);
break;
case Rhi::QueryType::PIPELINE_STATISTICS:
mD3D12GraphicsCommandList->BeginQuery(d3d12QueryPool.getD3D12QueryHeap(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, queryIndex);
break;
case Rhi::QueryType::TIMESTAMP:
RHI_ASSERT(mContext, false, "Direct3D 12 begin query isn't allowed for timestamp queries, use \"Rhi::Command::WriteTimestampQuery\" instead")
break;
}
}
void Direct3D12Rhi::endQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex)
{
// Sanity check
RHI_MATCH_CHECK(*this, queryPool)
// Query pool type dependent processing
const QueryPool& d3d12QueryPool = static_cast<const QueryPool&>(queryPool);
RHI_ASSERT(mContext, queryIndex < d3d12QueryPool.getNumberOfQueries(), "Direct3D 12 out-of-bounds query index")
switch (d3d12QueryPool.getQueryType())
{
case Rhi::QueryType::OCCLUSION:
mD3D12GraphicsCommandList->EndQuery(d3d12QueryPool.getD3D12QueryHeap(), D3D12_QUERY_TYPE_OCCLUSION, queryIndex);
break;
case Rhi::QueryType::PIPELINE_STATISTICS:
mD3D12GraphicsCommandList->EndQuery(d3d12QueryPool.getD3D12QueryHeap(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, queryIndex);
break;
case Rhi::QueryType::TIMESTAMP:
RHI_ASSERT(mContext, false, "Direct3D 12 end query isn't allowed for timestamp queries, use \"Rhi::Command::WriteTimestampQuery\" instead")
break;
}
}
void Direct3D12Rhi::writeTimestampQuery(Rhi::IQueryPool& queryPool, uint32_t queryIndex)
{
// Sanity check
RHI_MATCH_CHECK(*this, queryPool)
// Query pool type dependent processing
const QueryPool& d3d12QueryPool = static_cast<const QueryPool&>(queryPool);
RHI_ASSERT(mContext, queryIndex < d3d12QueryPool.getNumberOfQueries(), "Direct3D 12 out-of-bounds query index")
switch (d3d12QueryPool.getQueryType())
{
case Rhi::QueryType::OCCLUSION:
RHI_ASSERT(mContext, false, "Direct3D 12 write timestamp query isn't allowed for occlusion queries, use \"Rhi::Command::BeginQuery\" and \"Rhi::Command::EndQuery\" instead")
break;
case Rhi::QueryType::PIPELINE_STATISTICS:
RHI_ASSERT(mContext, false, "Direct3D 12 write timestamp query isn't allowed for pipeline statistics queries, use \"Rhi::Command::BeginQuery\" and \"Rhi::Command::EndQuery\" instead")
break;
case Rhi::QueryType::TIMESTAMP:
mD3D12GraphicsCommandList->EndQuery(d3d12QueryPool.getD3D12QueryHeap(), D3D12_QUERY_TYPE_TIMESTAMP, queryIndex);
break;
}
}
//[-------------------------------------------------------]
//[ Debug ]
//[-------------------------------------------------------]
#ifdef RHI_DEBUG
void Direct3D12Rhi::setDebugMarker(const char* name)
{
if (nullptr != mD3D12GraphicsCommandList)
{
RHI_ASSERT(mContext, nullptr != name, "Direct3D 12 debug marker names must not be a null pointer")
const UINT size = static_cast<UINT>((strlen(name) + 1) * sizeof(name[0]));
mD3D12GraphicsCommandList->SetMarker(PIX_EVENT_ANSI_VERSION, name, size);
}
}
void Direct3D12Rhi::beginDebugEvent(const char* name)
{
if (nullptr != mD3D12GraphicsCommandList)
{
RHI_ASSERT(mContext, nullptr != name, "Direct3D 12 debug event names must not be a null pointer")
const UINT size = static_cast<UINT>((strlen(name) + 1) * sizeof(name[0]));
mD3D12GraphicsCommandList->BeginEvent(PIX_EVENT_ANSI_VERSION, name, size);
}
}
void Direct3D12Rhi::endDebugEvent()
{
if (nullptr != mD3D12GraphicsCommandList)
{
mD3D12GraphicsCommandList->EndEvent();
}
}
#endif
//[-------------------------------------------------------]
//[ Public virtual Rhi::IRhi methods ]
//[-------------------------------------------------------]
bool Direct3D12Rhi::isDebugEnabled()
{
#ifdef RHI_DEBUG
return true;
#else
return false;
#endif
}
//[-------------------------------------------------------]
//[ Shader language ]
//[-------------------------------------------------------]
uint32_t Direct3D12Rhi::getNumberOfShaderLanguages() const
{
uint32_t numberOfShaderLanguages = 1; // HLSL support is always there
// Done, return the number of supported shader languages
return numberOfShaderLanguages;
}
const char* Direct3D12Rhi::getShaderLanguageName([[maybe_unused]] uint32_t index) const
{
RHI_ASSERT(mContext, index < getNumberOfShaderLanguages(), "Direct3D 12: Shader language index is out-of-bounds")
return ::detail::HLSL_NAME;
}
Rhi::IShaderLanguage* Direct3D12Rhi::getShaderLanguage(const char* shaderLanguageName)
{
// In case "shaderLanguage" is a null pointer, use the default shader language
if (nullptr != shaderLanguageName)
{
// Optimization: Check for shader language name pointer match, first
if (::detail::HLSL_NAME == shaderLanguageName || !stricmp(shaderLanguageName, ::detail::HLSL_NAME))
{
// If required, create the HLSL shader language instance right now
if (nullptr == mShaderLanguageHlsl)
{
mShaderLanguageHlsl = RHI_NEW(mContext, ShaderLanguageHlsl)(*this);
mShaderLanguageHlsl->addReference(); // Internal RHI reference
}
// Return the shader language instance
return mShaderLanguageHlsl;
}
// Error!
return nullptr;
}
// Return the HLSL shader language instance as default
return getShaderLanguage(::detail::HLSL_NAME);
}
//[-------------------------------------------------------]
//[ Resource creation ]
//[-------------------------------------------------------]
Rhi::IRenderPass* Direct3D12Rhi::createRenderPass(uint32_t numberOfColorAttachments, const Rhi::TextureFormat::Enum* colorAttachmentTextureFormats, Rhi::TextureFormat::Enum depthStencilAttachmentTextureFormat, [[maybe_unused]] uint8_t numberOfMultisamples RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
return RHI_NEW(mContext, RenderPass)(*this, numberOfColorAttachments, colorAttachmentTextureFormats, depthStencilAttachmentTextureFormat RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
Rhi::IQueryPool* Direct3D12Rhi::createQueryPool([[maybe_unused]] Rhi::QueryType queryType, [[maybe_unused]] uint32_t numberOfQueries RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
RHI_ASSERT(mContext, numberOfQueries > 0, "Direct3D 12: Number of queries mustn't be zero")
return RHI_NEW(mContext, QueryPool)(*this, queryType, numberOfQueries RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
Rhi::ISwapChain* Direct3D12Rhi::createSwapChain(Rhi::IRenderPass& renderPass, Rhi::WindowHandle windowHandle, bool RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// Sanity checks
RHI_MATCH_CHECK(*this, renderPass)
RHI_ASSERT(mContext, NULL_HANDLE != windowHandle.nativeWindowHandle, "Direct3D 12: The provided native window handle must not be a null handle")
// Create the swap chain
return RHI_NEW(mContext, SwapChain)(renderPass, windowHandle RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
Rhi::IFramebuffer* Direct3D12Rhi::createFramebuffer(Rhi::IRenderPass& renderPass, const Rhi::FramebufferAttachment* colorFramebufferAttachments, const Rhi::FramebufferAttachment* depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// Sanity check
RHI_MATCH_CHECK(*this, renderPass)
// Create the framebuffer
return RHI_NEW(mContext, Framebuffer)(renderPass, colorFramebufferAttachments, depthStencilFramebufferAttachment RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
Rhi::IBufferManager* Direct3D12Rhi::createBufferManager()
{
return RHI_NEW(mContext, BufferManager)(*this);
}
Rhi::ITextureManager* Direct3D12Rhi::createTextureManager()
{
return RHI_NEW(mContext, TextureManager)(*this);
}
Rhi::IRootSignature* Direct3D12Rhi::createRootSignature(const Rhi::RootSignature& rootSignature RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
return RHI_NEW(mContext, RootSignature)(*this, rootSignature RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
Rhi::IGraphicsPipelineState* Direct3D12Rhi::createGraphicsPipelineState(const Rhi::GraphicsPipelineState& graphicsPipelineState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// Sanity checks
RHI_ASSERT(mContext, nullptr != graphicsPipelineState.rootSignature, "Direct3D 12: Invalid graphics pipeline state root signature")
RHI_ASSERT(mContext, nullptr != graphicsPipelineState.graphicsProgram, "Direct3D 12: Invalid graphics pipeline state graphics program")
RHI_ASSERT(mContext, nullptr != graphicsPipelineState.renderPass, "Direct3D 12: Invalid graphics pipeline state render pass")
// Create graphics pipeline state
uint16_t id = 0;
if (GraphicsPipelineStateMakeId.CreateID(id))
{
return RHI_NEW(mContext, GraphicsPipelineState)(*this, graphicsPipelineState, id RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
// Error: Ensure a correct reference counter behaviour
graphicsPipelineState.rootSignature->addReference();
graphicsPipelineState.rootSignature->releaseReference();
graphicsPipelineState.graphicsProgram->addReference();
graphicsPipelineState.graphicsProgram->releaseReference();
graphicsPipelineState.renderPass->addReference();
graphicsPipelineState.renderPass->releaseReference();
return nullptr;
}
Rhi::IComputePipelineState* Direct3D12Rhi::createComputePipelineState(Rhi::IRootSignature& rootSignature, Rhi::IComputeShader& computeShader RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// Sanity checks
RHI_MATCH_CHECK(*this, rootSignature)
RHI_MATCH_CHECK(*this, computeShader)
// Create the compute pipeline state
uint16_t id = 0;
if (ComputePipelineStateMakeId.CreateID(id))
{
return RHI_NEW(mContext, ComputePipelineState)(*this, rootSignature, computeShader, id RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
// Error: Ensure a correct reference counter behaviour
rootSignature.addReference();
rootSignature.releaseReference();
computeShader.addReference();
computeShader.releaseReference();
return nullptr;
}
Rhi::ISamplerState* Direct3D12Rhi::createSamplerState(const Rhi::SamplerState& samplerState RHI_RESOURCE_DEBUG_NAME_PARAMETER_NO_DEFAULT)
{
// No debug name possible since all sampler states are inside a descriptor heap
return RHI_NEW(mContext, SamplerState)(*this, samplerState RHI_RESOURCE_DEBUG_PASS_PARAMETER);
}
//[-------------------------------------------------------]
//[ Resource handling ]
//[-------------------------------------------------------]
bool Direct3D12Rhi::map(Rhi::IResource& resource, uint32_t, Rhi::MapType, uint32_t, Rhi::MappedSubresource& mappedSubresource)
{
// The "Rhi::MapType" values directly map to Direct3D 10 & 11 constants, do not change them
// The "Rhi::MappedSubresource" structure directly maps to Direct3D 11, do not change it
// Define helper macro
// TODO(co) Port to Direct3D 12
#define TEXTURE_RESOURCE(type, typeClass) \
case type: \
{ \
return false; \
}
// Evaluate the resource type
switch (resource.getResourceType())
{
case Rhi::ResourceType::VERTEX_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
return SUCCEEDED(static_cast<VertexBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
case Rhi::ResourceType::INDEX_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
return SUCCEEDED(static_cast<IndexBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
case Rhi::ResourceType::TEXTURE_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
// TODO(co) Port to Direct3D 12
return false;
// return SUCCEEDED(static_cast<TextureBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
case Rhi::ResourceType::STRUCTURED_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
// TODO(co) Port to Direct3D 12
return false;
// return SUCCEEDED(static_cast<StructuredBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
case Rhi::ResourceType::INDIRECT_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
return SUCCEEDED(static_cast<IndirectBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
case Rhi::ResourceType::UNIFORM_BUFFER:
{
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
CD3DX12_RANGE readRange(0, 0); // We do not intend to read from this resource on the CPU
return SUCCEEDED(static_cast<UniformBuffer&>(resource).getD3D12Resource()->Map(0, &readRange, reinterpret_cast<void**>(&mappedSubresource.data)));
}
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D, Texture1D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D_ARRAY, Texture1DArray)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D, Texture2D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D_ARRAY, Texture2DArray)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_3D, Texture3D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE, TextureCube)
//TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE_ARRAY, TextureCubeArray) // TODO(co) Implement me
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
// Nothing we can map, set known return values
mappedSubresource.data = nullptr;
mappedSubresource.rowPitch = 0;
mappedSubresource.depthPitch = 0;
// Error!
return false;
}
// Undefine helper macro
#undef TEXTURE_RESOURCE
}
void Direct3D12Rhi::unmap(Rhi::IResource& resource, uint32_t)
{
// Define helper macro
// TODO(co) Port to Direct3D 12
#define TEXTURE_RESOURCE(type, typeClass) \
case type: \
{ \
break; \
}
// Evaluate the resource type
switch (resource.getResourceType())
{
case Rhi::ResourceType::VERTEX_BUFFER:
static_cast<VertexBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
case Rhi::ResourceType::INDEX_BUFFER:
static_cast<IndexBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
case Rhi::ResourceType::TEXTURE_BUFFER:
// TODO(co) Port to Direct3D 12
// static_cast<TextureBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
case Rhi::ResourceType::STRUCTURED_BUFFER:
// TODO(co) Port to Direct3D 12
// static_cast<StructuredBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
case Rhi::ResourceType::INDIRECT_BUFFER:
static_cast<IndirectBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
case Rhi::ResourceType::UNIFORM_BUFFER:
static_cast<UniformBuffer&>(resource).getD3D12Resource()->Unmap(0, nullptr);
break;
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D, Texture1D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_1D_ARRAY, Texture1DArray)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D, Texture2D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_2D_ARRAY, Texture2DArray)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_3D, Texture3D)
TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE, TextureCube)
// TEXTURE_RESOURCE(Rhi::ResourceType::TEXTURE_CUBE_ARRAY, TextureCubeArray) // TODO(co) Implement me
case Rhi::ResourceType::TEXTURE_CUBE_ARRAY:
case Rhi::ResourceType::ROOT_SIGNATURE:
case Rhi::ResourceType::RESOURCE_GROUP:
case Rhi::ResourceType::GRAPHICS_PROGRAM:
case Rhi::ResourceType::VERTEX_ARRAY:
case Rhi::ResourceType::RENDER_PASS:
case Rhi::ResourceType::QUERY_POOL:
case Rhi::ResourceType::SWAP_CHAIN:
case Rhi::ResourceType::FRAMEBUFFER:
case Rhi::ResourceType::GRAPHICS_PIPELINE_STATE:
case Rhi::ResourceType::COMPUTE_PIPELINE_STATE:
case Rhi::ResourceType::SAMPLER_STATE:
case Rhi::ResourceType::VERTEX_SHADER:
case Rhi::ResourceType::TESSELLATION_CONTROL_SHADER:
case Rhi::ResourceType::TESSELLATION_EVALUATION_SHADER:
case Rhi::ResourceType::GEOMETRY_SHADER:
case Rhi::ResourceType::FRAGMENT_SHADER:
case Rhi::ResourceType::TASK_SHADER:
case Rhi::ResourceType::MESH_SHADER:
case Rhi::ResourceType::COMPUTE_SHADER:
default:
// Nothing we can unmap
break;
}
// Undefine helper macro
#undef TEXTURE_RESOURCE
}
bool Direct3D12Rhi::getQueryPoolResults(Rhi::IQueryPool& queryPool, uint32_t numberOfDataBytes, uint8_t* data, uint32_t firstQueryIndex, uint32_t numberOfQueries, uint32_t strideInBytes, uint32_t)
{
// Sanity checks
RHI_MATCH_CHECK(*this, queryPool)
RHI_ASSERT(mContext, numberOfDataBytes >= sizeof(UINT64), "Direct3D 12 out-of-memory query access")
RHI_ASSERT(mContext, 1 == numberOfQueries || strideInBytes > 0, "Direct3D 12 invalid stride in bytes")
RHI_ASSERT(mContext, numberOfDataBytes >= strideInBytes * numberOfQueries, "Direct3D 12 out-of-memory query access")
RHI_ASSERT(mContext, nullptr != data, "Direct3D 12 out-of-memory query access")
RHI_ASSERT(mContext, numberOfQueries > 0, "Direct3D 12 number of queries mustn't be zero")
// Get query pool results
static_cast<QueryPool&>(queryPool).getQueryPoolResults(numberOfDataBytes, data, firstQueryIndex, numberOfQueries, strideInBytes, *mD3D12GraphicsCommandList);
// Done
return true;
}
//[-------------------------------------------------------]
//[ Operations ]
//[-------------------------------------------------------]
void Direct3D12Rhi::dispatchCommandBuffer(const Rhi::CommandBuffer& commandBuffer)
{
// Sanity check
RHI_ASSERT(mContext, !commandBuffer.isEmpty(), "The Direct3D 12 command buffer to dispatch mustn't be empty")
// Command list allocators can only be reset when the associated
// command lists have finished execution on the GPU; apps should use
// fences to determine GPU execution progress.
if (SUCCEEDED(mD3D12CommandAllocator->Reset()))
{
// However, when ExecuteCommandList() is called on a particular command
// list, that command list can then be reset at any time and must be before
// re-recording.
if (SUCCEEDED(mD3D12GraphicsCommandList->Reset(mD3D12CommandAllocator, nullptr)))
{
// Set descriptor heaps
ID3D12DescriptorHeap* d3d12DescriptorHeaps[] = { mShaderResourceViewDescriptorHeap->getD3D12DescriptorHeap(), mSamplerDescriptorHeap->getD3D12DescriptorHeap() };
mD3D12GraphicsCommandList->SetDescriptorHeaps(2, d3d12DescriptorHeaps);
}
// Reset our cached states where needed
mD3D12PrimitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
// Dispatch command buffer
dispatchCommandBufferInternal(commandBuffer);
{ // End scene
// Begin debug event
RHI_BEGIN_DEBUG_EVENT_FUNCTION(this)
// Finish previous uploads and start new ones
ID3D12CommandList* uploadD3d12CommandList = mUploadContext.getD3d12GraphicsCommandList();
mUploadContext.begin();
// We need to forget about the currently set render target
setGraphicsRenderTarget(nullptr);
// We need to forget about the currently set vertex array
unsetGraphicsVertexArray();
// End debug event
RHI_END_DEBUG_EVENT(this)
// Close and execute the command list
if (SUCCEEDED(mD3D12GraphicsCommandList->Close()))
{
if (nullptr != uploadD3d12CommandList)
{
ID3D12CommandList* commandLists[] = { uploadD3d12CommandList, mD3D12GraphicsCommandList };
mD3D12CommandQueue->ExecuteCommandLists(_countof(commandLists), commandLists);
}
else
{
ID3D12CommandList* commandLists[] = { mD3D12GraphicsCommandList };
mD3D12CommandQueue->ExecuteCommandLists(_countof(commandLists), commandLists);
}
}
// Release the graphics and compute root signature instance, in case we have one
if (nullptr != mGraphicsRootSignature)
{
mGraphicsRootSignature->releaseReference();
mGraphicsRootSignature = nullptr;
}
if (nullptr != mComputeRootSignature)
{
mComputeRootSignature->releaseReference();
mComputeRootSignature = nullptr;
}
}
}
}
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
void Direct3D12Rhi::initializeCapabilities()
{
// TODO(co) Direct3D 12 update
// There are no Direct3D 12 device capabilities we could query on runtime, they depend on the chosen feature level
// -> Have a look at "Devices -> Direct3D 12 on Downlevel Hardware -> Introduction" at MSDN http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx
// for a table with a list of the minimum resources supported by Direct3D 12 at the different feature levels
{ // Get device name
// Get DXGI adapter
IDXGIAdapter* dxgiAdapter = nullptr;
mDxgiFactory4->EnumAdapterByLuid(mD3D12Device->GetAdapterLuid(), IID_PPV_ARGS(&dxgiAdapter));
// The adapter contains a description like "AMD Radeon R9 200 Series"
DXGI_ADAPTER_DESC dxgiAdapterDesc = {};
dxgiAdapter->GetDesc(&dxgiAdapterDesc);
// Convert UTF-16 string to UTF-8
const size_t numberOfCharacters = _countof(mCapabilities.deviceName) - 1;
::WideCharToMultiByte(CP_UTF8, 0, dxgiAdapterDesc.Description, static_cast<int>(wcslen(dxgiAdapterDesc.Description)), mCapabilities.deviceName, static_cast<int>(numberOfCharacters), nullptr, nullptr);
mCapabilities.deviceName[numberOfCharacters] = '\0';
// Release references
dxgiAdapter->Release();
}
// Preferred swap chain texture format
mCapabilities.preferredSwapChainColorTextureFormat = Rhi::TextureFormat::Enum::R8G8B8A8;
mCapabilities.preferredSwapChainDepthStencilTextureFormat = Rhi::TextureFormat::Enum::D32_FLOAT;
// Evaluate the chosen feature level
switch (D3D_FEATURE_LEVEL_12_0)
// switch (mD3D12Device->GetFeatureLevel()) // TODO(co) Direct3D 12 update
{
case D3D_FEATURE_LEVEL_9_1:
// Maximum number of viewports (always at least 1)
mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
mCapabilities.maximumNumberOfSimultaneousRenderTargets = 1;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 2048;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 0;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 0;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0;
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = false;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = false;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.1 has no tessellation support
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.1 has no geometry shader support
break;
case D3D_FEATURE_LEVEL_9_2:
// Maximum number of viewports (always at least 1)
mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
mCapabilities.maximumNumberOfSimultaneousRenderTargets = 1;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 2048;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 0;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 0;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0;
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = false;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = false;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.2 has no tessellation support
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.2 has no geometry shader support
break;
case D3D_FEATURE_LEVEL_9_3:
// Maximum number of viewports (always at least 1)
mCapabilities.maximumNumberOfViewports = 1; // Direct3D 9 only supports a single viewport
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
mCapabilities.maximumNumberOfSimultaneousRenderTargets = 4;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 4096;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 0;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 0;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 0;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 0;
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 1; // Don't want to support the legacy DirectX 9 multisample support
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = true;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = false;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 9.3 has no tessellation support
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 0; // Direct3D 9.3 has no geometry shader support
break;
case D3D_FEATURE_LEVEL_10_0:
// Maximum number of viewports (always at least 1)
// TODO(co) Direct3D 12 update
// mCapabilities.maximumNumberOfViewports = D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1;
mCapabilities.maximumNumberOfViewports = 8;
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
// TODO(co) Direct3D 12 update
//mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT;
mCapabilities.maximumNumberOfSimultaneousRenderTargets = 8;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 8192;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 512;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 512;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 0;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB.
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 8;
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = true;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = true;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 10 has no tessellation support
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 1024;
break;
case D3D_FEATURE_LEVEL_10_1:
// Maximum number of viewports (always at least 1)
// TODO(co) Direct3D 12 update
//mCapabilities.maximumNumberOfViewports = D3D10_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1;
mCapabilities.maximumNumberOfViewports = 8;
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
// TODO(co) Direct3D 12 update
//mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT;
mCapabilities.maximumNumberOfSimultaneousRenderTargets = 8;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 8192;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 512;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 512;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 512;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB.
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 8;
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = true;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = true;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 0; // Direct3D 10.1 has no tessellation support
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 1024;
break;
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_11_1:
case D3D_FEATURE_LEVEL_12_0:
case D3D_FEATURE_LEVEL_12_1:
// Maximum number of viewports (always at least 1)
// TODO(co) Direct3D 12 update
//mCapabilities.maximumNumberOfViewports = D3D12_VIEWPORT_AND_SCISSORRECT_MAX_INDEX + 1;
mCapabilities.maximumNumberOfViewports = 8;
// Maximum number of simultaneous render targets (if <1 render to texture is not supported)
mCapabilities.maximumNumberOfSimultaneousRenderTargets = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
// Maximum texture dimension
mCapabilities.maximumTextureDimension = 16384;
// Maximum number of 1D texture array slices (usually 512, in case there's no support for 1D texture arrays it's 0)
mCapabilities.maximumNumberOf1DTextureArraySlices = 512;
// Maximum number of 2D texture array slices (usually 512, in case there's no support for 2D texture arrays it's 0)
mCapabilities.maximumNumberOf2DTextureArraySlices = 512;
// Maximum number of cube texture array slices (usually 512, in case there's no support for cube texture arrays it's 0)
mCapabilities.maximumNumberOfCubeTextureArraySlices = 512;
// Maximum texture buffer (TBO) size in texel (>65536, typically much larger than that of one-dimensional texture, in case there's no support for texture buffer it's 0)
mCapabilities.maximumTextureBufferSize = mCapabilities.maximumStructuredBufferSize = 128 * 1024 * 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention the texture buffer? Currently the OpenGL 3 minimum is used: 128 MiB.
// Maximum number of multisamples (always at least 1, usually 8)
mCapabilities.maximumNumberOfMultisamples = 8;
// Maximum anisotropy (always at least 1, usually 16)
mCapabilities.maximumAnisotropy = 16;
// Maximum indirect buffer size in bytes
mCapabilities.maximumIndirectBufferSize = 128 * 1024; // 128 KiB
// Instanced arrays supported? (shader model 3 feature, vertex array element advancing per-instance instead of per-vertex)
mCapabilities.instancedArrays = true;
// Draw instanced supported? (shader model 4 feature, build in shader variable holding the current instance ID)
mCapabilities.drawInstanced = true;
// Maximum number of vertices per patch (usually 0 for no tessellation support or 32 which is the maximum number of supported vertices per patch)
mCapabilities.maximumNumberOfPatchVertices = 32;
// Maximum number of vertices a geometry shader can emit (usually 0 for no geometry shader support or 1024)
mCapabilities.maximumNumberOfGsOutputVertices = 1024; // TODO(co) http://msdn.microsoft.com/en-us/library/ff476876%28v=vs.85%29.aspx does not mention it, so I assume it's 1024
break;
}
// TODO(co) Implement me, remove this when done
mCapabilities.maximumNumberOfCubeTextureArraySlices = 0;
// The rest is the same for all feature levels
// Maximum uniform buffer (UBO) size in bytes (usually at least 4096 * 16 bytes, in case there's no support for uniform buffer it's 0)
// -> Same as DirectX 11: See https://msdn.microsoft.com/en-us/library/windows/desktop/ff819065(v=vs.85).aspx - "Resource Limits (Direct3D 11)" - "Number of elements in a constant buffer D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT (4096)"
// -> One element = float4 = 16 bytes
mCapabilities.maximumUniformBufferSize = 4096 * 16;
// Left-handed coordinate system with clip space depth value range 0..1
mCapabilities.upperLeftOrigin = mCapabilities.zeroToOneClipZ = true;
// Individual uniforms ("constants" in Direct3D terminology) supported? If not, only uniform buffer objects are supported.
mCapabilities.individualUniforms = false;
// Base vertex supported for draw calls?
mCapabilities.baseVertex = true;
// Direct3D 12 has native multithreading // TODO(co) But do only set this to true if it has been tested
mCapabilities.nativeMultithreading = false;
// Direct3D 12 has shader bytecode support
// TODO(co) Implement shader bytecode support
mCapabilities.shaderBytecode = false;
// Is there support for vertex shaders (VS)?
mCapabilities.vertexShader = true;
// Is there support for fragment shaders (FS)?
mCapabilities.fragmentShader = true;
// Is there support for task shaders (TS) and mesh shaders (MS)?
mCapabilities.meshShader = false; // TODO(co) "DirectX 12 Ultimate" needed
// Is there support for compute shaders (CS)?
mCapabilities.computeShader = true;
}
void Direct3D12Rhi::unsetGraphicsVertexArray()
{
// Release the currently used vertex array reference, in case we have one
if (nullptr != mVertexArray)
{
// Set no Direct3D 12 input layout
mD3D12GraphicsCommandList->IASetVertexBuffers(0, 0, nullptr);
// Release reference
mVertexArray->releaseReference();
mVertexArray = nullptr;
}
}
#ifdef RHI_DEBUG
void Direct3D12Rhi::debugReportLiveDeviceObjects()
{
ID3D12DebugDevice* d3d12DebugDevice = nullptr;
if (SUCCEEDED(mD3D12Device->QueryInterface(IID_PPV_ARGS(&d3d12DebugDevice))))
{
d3d12DebugDevice->ReportLiveDeviceObjects(static_cast<D3D12_RLDO_FLAGS>(D3D12_RLDO_DETAIL | D3D12_RLDO_IGNORE_INTERNAL));
d3d12DebugDevice->Release();
}
}
#endif
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Direct3D12Rhi
//[-------------------------------------------------------]
//[ Global functions ]
//[-------------------------------------------------------]
// Export the instance creation function
#ifdef RHI_DIRECT3D12_EXPORTS
#define DIRECT3D12RHI_FUNCTION_EXPORT GENERIC_FUNCTION_EXPORT
#else
#define DIRECT3D12RHI_FUNCTION_EXPORT
#endif
DIRECT3D12RHI_FUNCTION_EXPORT Rhi::IRhi* createDirect3D12RhiInstance(const Rhi::Context& context)
{
return RHI_NEW(context, Direct3D12Rhi::Direct3D12Rhi)(context);
}
#undef DIRECT3D12RHI_FUNCTION_EXPORT
| 40.246342 | 569 | 0.692816 | [
"mesh",
"geometry",
"render",
"object",
"model",
"3d"
] |
09821833cbc90d5eb889c09f95d6be8836709e74 | 4,157 | cc | C++ | chrome/browser/feedback/feedback_uploader_unittest.cc | hokein/chromium | 69328672dd0c5b93e0b65fc344feb11bbdc37b6b | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-04-27T20:21:55.000Z | 2019-04-27T20:21:55.000Z | chrome/browser/feedback/feedback_uploader_unittest.cc | hokein/chromium | 69328672dd0c5b93e0b65fc344feb11bbdc37b6b | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/feedback/feedback_uploader_unittest.cc | hokein/chromium | 69328672dd0c5b93e0b65fc344feb11bbdc37b6b | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/feedback/feedback_uploader.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "chrome/browser/feedback/feedback_uploader_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kReportOne[] = "one";
const char kReportTwo[] = "two";
const char kReportThree[] = "three";
const char kReportFour[] = "four";
const char kReportFive[] = "five";
const base::TimeDelta kRetryDelayForTest =
base::TimeDelta::FromMilliseconds(100);
BrowserContextKeyedService* CreateFeedbackUploaderService(
content::BrowserContext* context) {
return new feedback::FeedbackUploader(Profile::FromBrowserContext(context));
}
} // namespace
namespace feedback {
class FeedbackUploaderTest : public testing::Test {
protected:
FeedbackUploaderTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_),
profile_(new TestingProfile()),
expected_reports_(0) {
FeedbackUploaderFactory::GetInstance()->SetTestingFactory(
profile_.get(), &CreateFeedbackUploaderService);
uploader_ = FeedbackUploaderFactory::GetForBrowserContext(profile_.get());
uploader_->setup_for_test(
base::Bind(&FeedbackUploaderTest::MockDispatchReport,
base::Unretained(this)),
kRetryDelayForTest);
}
virtual ~FeedbackUploaderTest() {
FeedbackUploaderFactory::GetInstance()->SetTestingFactory(
profile_.get(), NULL);
}
void QueueReport(const std::string& data) {
uploader_->QueueReport(make_scoped_ptr(new std::string(data)));
}
void ReportFailure(const std::string& data) {
uploader_->RetryReport(make_scoped_ptr(new std::string(data)));
}
void MockDispatchReport(scoped_ptr<std::string> report_data) {
dispatched_reports_.push_back(*report_data.get());
// Dispatch will always update the timer, whether successful or not,
// simulate the same behavior.
uploader_->UpdateUploadTimer();
if (dispatched_reports_.size() >= expected_reports_) {
if (run_loop_.get())
run_loop_->Quit();
}
}
void RunMessageLoop() {
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
}
base::MessageLoop message_loop_;
scoped_ptr<base::RunLoop> run_loop_;
content::TestBrowserThread ui_thread_;
scoped_ptr<TestingProfile> profile_;
FeedbackUploader* uploader_;
std::vector<std::string> dispatched_reports_;
size_t expected_reports_;
};
TEST_F(FeedbackUploaderTest, QueueMultiple) {
dispatched_reports_.clear();
QueueReport(kReportOne);
QueueReport(kReportTwo);
QueueReport(kReportThree);
QueueReport(kReportFour);
EXPECT_EQ(dispatched_reports_.size(), 4u);
EXPECT_EQ(dispatched_reports_[0], kReportOne);
EXPECT_EQ(dispatched_reports_[1], kReportTwo);
EXPECT_EQ(dispatched_reports_[2], kReportThree);
EXPECT_EQ(dispatched_reports_[3], kReportFour);
}
#if defined(OS_WIN) || defined(OS_ANDROID)
// crbug.com/330547
#define MAYBE_QueueMultipleWithFailures DISABLED_QueueMultipleWithFailures
#else
#define MAYBE_QueueMultipleWithFailures QueueMultipleWithFailures
#endif
TEST_F(FeedbackUploaderTest, MAYBE_QueueMultipleWithFailures) {
dispatched_reports_.clear();
QueueReport(kReportOne);
QueueReport(kReportTwo);
QueueReport(kReportThree);
QueueReport(kReportFour);
ReportFailure(kReportThree);
ReportFailure(kReportTwo);
QueueReport(kReportFive);
expected_reports_ = 7;
RunMessageLoop();
EXPECT_EQ(dispatched_reports_.size(), 7u);
EXPECT_EQ(dispatched_reports_[0], kReportOne);
EXPECT_EQ(dispatched_reports_[1], kReportTwo);
EXPECT_EQ(dispatched_reports_[2], kReportThree);
EXPECT_EQ(dispatched_reports_[3], kReportFour);
EXPECT_EQ(dispatched_reports_[4], kReportFive);
EXPECT_EQ(dispatched_reports_[5], kReportThree);
EXPECT_EQ(dispatched_reports_[6], kReportTwo);
}
} // namespace feedback
| 30.123188 | 78 | 0.752706 | [
"vector"
] |
0989959d97924d7ec6fee3320b1a37a8f8b62165 | 16,105 | hpp | C++ | Example/MoyaComparison/Pods/Realm/include/core/realm/util/shunting_yard_parser.hpp | QuentinArnault/NetworkStack | c4d4f2a1d6a4a35ee9b7d42f47606b1ccfd87591 | [
"Apache-2.0"
] | 36 | 2017-01-26T15:54:50.000Z | 2021-06-17T03:15:17.000Z | Example/MoyaComparison/Pods/Realm/include/core/realm/util/shunting_yard_parser.hpp | QuentinArnault/NetworkStack | c4d4f2a1d6a4a35ee9b7d42f47606b1ccfd87591 | [
"Apache-2.0"
] | 24 | 2017-02-07T20:52:11.000Z | 2021-06-10T07:26:18.000Z | Example/MoyaComparison/Pods/Realm/include/core/realm/util/shunting_yard_parser.hpp | QuentinArnault/NetworkStack | c4d4f2a1d6a4a35ee9b7d42f47606b1ccfd87591 | [
"Apache-2.0"
] | 11 | 2017-10-25T14:51:51.000Z | 2021-03-26T10:52:49.000Z | /*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_SHUNTING_YARD_PARSER_HPP
#define REALM_UTIL_SHUNTING_YARD_PARSER_HPP
#include <utility>
#include <vector>
#include <realm/util/assert.hpp>
namespace realm {
namespace util {
class ShuntingYardParserBase {
public:
enum class Token {
error, // value parsed with errors
value,
oper, // operator
left_paren,
right_paren,
end_of_input
};
enum class Side { left, right };
};
/// Edsger Dijkstra's shunting yard algorithm.
///
/// The `Context` type must define these types:
///
/// - `Operator`, whose values must represent particular operators (prefix,
/// infix, and postfix). For example, it could be an index into a table of
/// operators.
/// - `Value`, which is the type of the operands for operators, and the type of
/// the result of performing the associated operations.
/// - `Location`, which is taken to represent a location (of a token) in the
/// input.
///
/// The `Context` type must also define these functions:
///
/// bool next_token(Token& tok, Value& val, Operator& oper, Location& loc)
/// bool is_prefix_operator(const Operator&) const noexcept
/// bool is_postfix_operator(const Operator&) const noexcept
/// int get_precedence_level(const Operator&) const noexcept
/// bool is_prec_right_associative(int precedence_level) const noexcept
/// bool perform_unop(Operator, Value value, Value& result, bool& error)
/// bool perform_binop(Operator, Value left, Value right, Value& result, bool& error)
/// bool check_result(const Value& result, const Location&)
/// bool missing_operand(const Operator&, Side, const Location&)
/// bool missing_operator_before(const Value& preceding_value, const Location&)
/// bool unmatched_paren(Side, const Location&)
/// bool empty_parentheses(const Location&) // Location is closing parenthesis
/// bool empty_input(const Location&) // Location is end of input
///
/// If `next_token()` returns false, parsing will be terminated
/// immediately. Otherwise, `next_token()` must set `tok` to the appropriate
/// value, and `loc` to the location of the token in the input, or to the end of
/// input if `tok` is set to `Token::end_of_input`. If the extracted token is
/// `Token::value` (operand), then it must set `value` to the appropriate
/// value. If the extracted token is `Token::oper` (operator), then it must set
/// `oper` to the appropriate value.
///
/// If `perform_unop()` or `perform_binop()` returns false, parsing will be
/// terminated immediately. Otherwise, on success, they must set `result` to the
/// appropriate value, and on failure, they must set `error` to true. If they
/// set `error` to true, it does not matter whether they also modify
/// `result`. The prior value of `error` is guaranteed to be false.
///
/// If `check_result()` returns false, parsing will be terminated immediately.
///
/// If `missing_operand()`, `missing_operator_before()`, `unmatched_paren()`,
/// `empty_parentheses()`, or `empty_input()` returns false, parsing will be
/// terminated immediately.
template<class Context> class ShuntingYardParser: public ShuntingYardParserBase {
public:
using Operator = typename Context::Operator;
using Value = typename Context::Value;
using Location = typename Context::Location;
/// If an error occurred and/or parsing was terminated (see class-level
/// documentation), this function returns false. Otherwise, it sets `result`
/// and returns true.
bool parse(Context&, Value& result);
private:
struct ErrorTag {};
struct LeftParenTag {};
struct ValueSlot {
bool error;
Value value;
ValueSlot(Value);
ValueSlot(ErrorTag);
};
struct OperSlot {
enum class Type { normal, left_paren, error };
Type type;
Operator oper;
Location loc;
OperSlot(Operator, const Location&);
OperSlot(LeftParenTag, const Location&);
OperSlot(ErrorTag);
};
// The operator stack contains only prefix and infix operators.
std::vector<ValueSlot> m_value_stack;
std::vector<OperSlot> m_operator_stack;
bool do_parse(Context&, Value&);
bool perform_prefix_or_infix_oper(Operator, const Location&, Context&);
bool perform_prefix_or_postfix_oper(Operator, const Location&, Context&);
void perform_error_operation() noexcept;
void clear_stacks() noexcept;
};
// Implementation
template<class Context> inline bool ShuntingYardParser<Context>::parse(Context& context, Value& result)
{
try {
bool unterminated = do_parse(context, result); // Throws
clear_stacks();
return unterminated;
}
catch (...) {
clear_stacks();
throw;
}
}
template<class Context> inline ShuntingYardParser<Context>::ValueSlot::ValueSlot(Value val):
error{false},
value{std::move(val)}
{
}
template<class Context> inline ShuntingYardParser<Context>::ValueSlot::ValueSlot(ErrorTag):
error{true},
value{Value{}}
{
}
template<class Context> inline ShuntingYardParser<Context>::OperSlot::OperSlot(Operator op, const Location& loc):
type{Type::normal},
oper{std::move(op)},
loc{loc}
{
}
template<class Context> inline ShuntingYardParser<Context>::OperSlot::OperSlot(LeftParenTag, const Location& loc):
type{Type::left_paren},
oper{Operator{}},
loc{loc}
{
}
template<class Context> inline ShuntingYardParser<Context>::OperSlot::OperSlot(ErrorTag):
type{Type::error},
oper{Operator{}},
loc{Location{}}
{
}
template<class Context> bool ShuntingYardParser<Context>::do_parse(Context& context, Value& result)
{
Token token = Token{};
Value value = Value{};
Operator oper = Operator{};
Location loc = Location{};
want_operand:
if (!context.next_token(token, value, oper, loc)) // Throws
return false;
want_operand_2:
switch (token) {
case Token::error:
m_value_stack.emplace_back(ErrorTag{}); // Throws
goto have_operand;
case Token::value:
m_value_stack.emplace_back(std::move(value)); // Throws
goto have_operand;
case Token::oper:
if (context.is_prefix_operator(oper)) {
m_operator_stack.emplace_back(std::move(oper), loc); // Throws
goto want_operand;
}
if (!context.missing_operand(oper, Side::left, loc)) // Throws
return false;
m_value_stack.emplace_back(ErrorTag{}); // Throws
goto have_operand_2;
case Token::left_paren:
m_operator_stack.emplace_back(LeftParenTag{}, loc); // Throws
goto want_operand;
case Token::right_paren:
if (!m_operator_stack.empty()) {
const OperSlot& slot = m_operator_stack.back();
// This cannot be an injected error operator, because such an
// operator would not have been injected when the right-hand
// side operand is missing.
REALM_ASSERT(slot.type != OperSlot::Type::error);
if (slot.type == OperSlot::Type::normal) {
if (!context.missing_operand(slot.oper, Side::right, slot.loc)) // Throws
return false;
}
else {
if (!context.empty_parentheses(loc)) // Throws
return false;
}
}
m_value_stack.emplace_back(ErrorTag{}); // Throws
goto have_operand_2;
case Token::end_of_input:
if (m_operator_stack.empty()) {
// Assume `loc` was set to point to end of input
if (!context.empty_input(loc)) // Throws
return false;
}
else {
const OperSlot& slot = m_operator_stack.back();
// This cannot be an injected error operator, because such an
// operator would not have been injected when the right-hand
// side operand is missing.
REALM_ASSERT(slot.type != OperSlot::Type::error);
if (slot.type == OperSlot::Type::normal)
if (!context.missing_operand(slot.oper, Side::right, slot.loc)) // Throws
return false;
// If the operator slot contains a left parenthesis,
// unmatched_paren() will be called later.
}
m_value_stack.emplace_back(ErrorTag{}); // Throws
goto end_of_input;
}
REALM_ASSERT(false);
return false;
have_operand:
if (!context.next_token(token, value, oper, loc)) // Throws
return false;
have_operand_2:
switch (token) {
case Token::error:
goto missing_operator_2;
case Token::value:
goto missing_operator;
case Token::oper:
if (!context.is_prefix_operator(oper)) { // infix or postfix
while (!m_operator_stack.empty()) {
OperSlot& slot = m_operator_stack.back();
if (slot.type == OperSlot::Type::left_paren)
break;
if (slot.type == OperSlot::Type::error)
break;
const Operator& left_oper = slot.oper;
const Operator& right_oper = oper;
int left_prec = context.get_precedence_level(left_oper);
int right_prec = context.get_precedence_level(right_oper);
if (left_prec < right_prec)
break;
if (left_prec == right_prec) {
int precedence = left_prec;
if (context.is_prec_right_associative(precedence))
break;
}
OperSlot slot_2 = std::move(slot);
m_operator_stack.pop_back();
perform_prefix_or_infix_oper(std::move(slot_2.oper), slot_2.loc,
context); // Throws
}
if (context.is_postfix_operator(oper)) {
if (!perform_prefix_or_postfix_oper(std::move(oper), loc, context)) // Throws
return false;
goto have_operand;
}
m_operator_stack.emplace_back(std::move(oper), loc); // Throws
goto want_operand;
}
goto missing_operator;
case Token::left_paren:
goto missing_operator;
case Token::right_paren:
for (;;) {
if (m_operator_stack.empty()) {
if (!context.unmatched_paren(Side::right, loc)) // Throws
return false;
break;
}
OperSlot slot = std::move(m_operator_stack.back());
m_operator_stack.pop_back();
if (slot.type == OperSlot::Type::left_paren)
break;
if (slot.type == OperSlot::Type::error) {
perform_error_operation();
continue;
}
perform_prefix_or_infix_oper(std::move(slot.oper), slot.loc, context); // Throws
}
goto have_operand;
case Token::end_of_input:
goto end_of_input;
}
REALM_ASSERT(false);
return false;
missing_operator:
REALM_ASSERT(!m_value_stack.empty());
{
const ValueSlot& slot = m_value_stack.back();
if (!slot.error) {
if (!context.missing_operator_before(slot.value, loc)) // Throws
return false;
}
}
missing_operator_2:
m_operator_stack.emplace_back(ErrorTag{}); // Throws
goto want_operand_2;
end_of_input:
while (!m_operator_stack.empty()) {
OperSlot slot = std::move(m_operator_stack.back());
m_operator_stack.pop_back();
if (slot.type == OperSlot::Type::left_paren) {
if (!context.unmatched_paren(Side::left, slot.loc)) // Throws
return false;
continue;
}
if (slot.type == OperSlot::Type::error) {
perform_error_operation();
continue;
}
perform_prefix_or_infix_oper(std::move(slot.oper), slot.loc, context); // Throws
}
REALM_ASSERT(!m_value_stack.empty());
ValueSlot slot = std::move(m_value_stack.back());
m_value_stack.pop_back();
if (slot.error)
return false;
if (!context.check_result(slot.value, loc)) // Throws
return false;
result = std::move(slot.value);
return true;
}
template<class Context>
inline bool ShuntingYardParser<Context>::perform_prefix_or_infix_oper(Operator oper,
const Location& loc,
Context& context)
{
if (context.is_prefix_operator(oper))
return perform_prefix_or_postfix_oper(std::move(oper), loc, context); // Throws
REALM_ASSERT(m_value_stack.size() >= 2);
ValueSlot right = std::move(m_value_stack.back());
m_value_stack.pop_back();
ValueSlot left = std::move(m_value_stack.back());
m_value_stack.pop_back();
if (left.error || left.error) {
error:
m_value_stack.emplace_back(ErrorTag{}); // Throws
return true;
}
Value result = Value{};
bool error = false;
if (!context.perform_binop(std::move(oper), loc, std::move(left.value), std::move(right.value),
result, error)) // Throws
return false;
if (error)
goto error;
m_value_stack.emplace_back(std::move(result)); // Throws
return true;
}
template<class Context>
inline bool ShuntingYardParser<Context>::perform_prefix_or_postfix_oper(Operator oper,
const Location& loc,
Context& context)
{
REALM_ASSERT(!m_value_stack.empty());
ValueSlot slot = std::move(m_value_stack.back());
m_value_stack.pop_back();
if (slot.error) {
error:
m_value_stack.emplace_back(ErrorTag{}); // Throws
return true;
}
Value result = Value{};
bool error = false;
if (!context.perform_unop(std::move(oper), loc, std::move(slot.value),
result, error)) // Throws
return false;
if (error)
goto error;
m_value_stack.emplace_back(std::move(result)); // Throws
return true;
}
template<class Context> inline void ShuntingYardParser<Context>::perform_error_operation() noexcept
{
REALM_ASSERT(m_value_stack.size() >= 2);
m_value_stack.pop_back();
m_value_stack.pop_back();
m_value_stack.emplace_back(ErrorTag{}); // Throws
}
template<class Context> inline void ShuntingYardParser<Context>::clear_stacks() noexcept
{
m_value_stack.clear();
m_operator_stack.clear();
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_SHUNTING_YARD_PARSER_HPP
| 36.602273 | 114 | 0.598013 | [
"vector"
] |
098efd956ec007ba7cfd5334f3842dd4982678d1 | 3,922 | cpp | C++ | src/CommandLineOptions.cpp | Sourin-chatterjee/SpinParser | 23fa90c327b8a4543e5afac1b64d18df40975182 | [
"MIT"
] | 18 | 2021-06-03T16:03:02.000Z | 2022-02-28T00:48:53.000Z | src/CommandLineOptions.cpp | Sourin-chatterjee/SpinParser | 23fa90c327b8a4543e5afac1b64d18df40975182 | [
"MIT"
] | 3 | 2021-10-08T15:51:51.000Z | 2022-03-31T22:20:01.000Z | src/CommandLineOptions.cpp | Sourin-chatterjee/SpinParser | 23fa90c327b8a4543e5afac1b64d18df40975182 | [
"MIT"
] | 2 | 2022-02-10T17:15:05.000Z | 2022-02-11T19:54:27.000Z | /**
* @file CommandLineOptions.cpp
* @author Finn Lasse Buessen
* @brief Parser for command line arguments.
*
* @copyright Copyright (c) 2020
*/
#include <iostream>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "CommandLineOptions.hpp"
CommandLineOptions::CommandLineOptions(int argc, char **argv)
{
namespace po = boost::program_options;
po::options_description generalOptions("General options");
generalOptions.add_options()
("help,h", po::bool_switch(), "print help message and exit")
("resourcePath,r", po::value<std::string>()->value_name("DIR"), "search path for .xml resource files");
po::options_description checkpointingOptions("Checkpointing options");
checkpointingOptions.add_options()
("checkpointTime,t", po::value<int>()->default_value(3600)->value_name("TIME"), "checkpoint interval in seconds")
("forceRestart,f", po::bool_switch(), "start new calculation even if checkpoint data is available")
("defer,d", po::bool_switch(), "archive all vertex data for deferred measurements in post processing");
po::options_description outputOptions("Output options");
outputOptions.add_options()
("verbose,v", po::bool_switch(), "enable verbose output")
("debugLattice", po::bool_switch(), "print lattice debug information in .ldf format");
po::options_description hiddenOptions("Hidden options");
hiddenOptions.add_options()
("taskFile", po::value<std::string>()->required(), "taskFile");
po::options_description allOptions;
allOptions.add(generalOptions).add(checkpointingOptions).add(outputOptions).add(hiddenOptions);
po::positional_options_description positionalOptions;
positionalOptions.add("taskFile", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(allOptions).positional(positionalOptions).run(), vm);
_help = vm["help"].as<bool>();
_verbose = vm["verbose"].as<bool>();
_checkpointTime = vm["checkpointTime"].as<int>();
_forceRestart = vm["forceRestart"].as<bool>();
_deferMeasurements = vm["defer"].as<bool>();
_debugLattice = vm["debugLattice"].as<bool>();
_taskFile = (vm.count("taskFile")) ? vm["taskFile"].as<std::string>() : "";
if (vm.count("resourcePath")) _resourcePath = vm["resourcePath"].as<std::string>();
else
{
if (boost::filesystem::is_directory(boost::filesystem::path(argv[0]).remove_filename().parent_path().append("res").string())) _resourcePath = boost::filesystem::path(argv[0]).remove_filename().parent_path().append("res").string();
else _resourcePath = boost::filesystem::path(argv[0]).remove_filename().string();
}
if (_help)
{
std::cout << "NAME" << std::endl;
std::cout << "\tSpinParser - Spin Pseudofermion Algorithms for Research on Spin Ensembles via Renormalization" << std::endl << std::endl;
std::cout << "SYNOPSIS" << std::endl;
std::cout << "\tSpinParser [OPTION]... FILE" << std::endl << std::endl;
std::cout << "DESCRIPTION" << std::endl;
std::cout << "\tThe SpinParser allows to solve pf-FRG flow equations with model parameters specified in FILE. " << std::endl << std::endl;
std::cout << "\tMandatory arguments to long options are mandatory for short options too. " << std::endl << std::endl;
std::cout << generalOptions << std::endl << outputOptions << std::endl << checkpointingOptions << std::endl;
}
else po::notify(vm);
}
bool CommandLineOptions::help() const
{
return _help;
}
bool CommandLineOptions::verbose() const
{
return _verbose;
}
int CommandLineOptions::checkpointTime() const
{
return _checkpointTime;
}
bool CommandLineOptions::forceRestart() const
{
return _forceRestart;
}
bool CommandLineOptions::deferMeasurements() const
{
return _deferMeasurements;
}
bool CommandLineOptions::debugLattice() const
{
return _debugLattice;
}
std::string CommandLineOptions::taskFile() const
{
return _taskFile;
}
std::string CommandLineOptions::resourcePath() const
{
return _resourcePath;
}
| 34.104348 | 232 | 0.722845 | [
"model"
] |
0991fb0ce7dce2dbc991441215928c256362a1bf | 31,863 | cpp | C++ | aspects/fluid/potential/GunnsGasFan.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 18 | 2020-01-23T12:14:09.000Z | 2022-02-27T22:11:35.000Z | aspects/fluid/potential/GunnsGasFan.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 39 | 2020-11-20T12:19:35.000Z | 2022-02-22T18:45:55.000Z | aspects/fluid/potential/GunnsGasFan.cpp | nasa/gunns | 248323939a476abe5178538cd7a3512b5f42675c | [
"NASA-1.3"
] | 7 | 2020-02-10T19:25:43.000Z | 2022-03-16T01:10:00.000Z | /************************** TRICK HEADER ***********************************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
PURPOSE:
(Classes for the GUNNS Gas Fan Model.)
REQUIREMENTS:
()
REFERENCE:
()
ASSUMPTIONS AND LIMITATIONS:
()
LIBRARY DEPENDENCY:
((software/exceptions/TsNumericalException.o)
(aspects/fluid/potential/GunnsGasFanCurve.o)
(aspects/fluid/potential/GunnsGasFan.o)
(core/GunnsFluidPotential.o))
PROGRAMMERS:
((Jason Harvey) (L-3 Communications) (Install) (2012-07))
***************************************************************************************************/
#include <complex>
#include <string>
#include "GunnsGasFan.hh"
#include "software/exceptions/TsInitializationException.hh"
#include "software/exceptions/TsNumericalException.hh"
#include "math/MsMath.hh"
/// @details These coefficients define a generalized shaft power curve for impellers with specific
/// speed between 0.2 and 5 radians, which covers most radial, mixed and axial flow pumps.
const double GunnsGasFan::mSpecificSpeedRadial = 0.2;
const double GunnsGasFan::mSpecificSpeedAxial = 5.0;
const double GunnsGasFan::mPowerCoeffsRadial[] = {0.42, 0.69, -0.11, 0.0};
const double GunnsGasFan::mPowerCoeffsAxial[] = {2.0, -5.98, 8.78, -3.8};
const double GunnsGasFan::mRefCoeffsRadial[] = {1.09, 0.33, -0.59, -0.39, 1.32, -0.76};
const double GunnsGasFan::mRefCoeffsAxial[] = {1.69, -5.45, 9.62, -4.88, 0.022, -0.013};
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] name (--) Name of object.
/// @param[in,out] nodes (--) Pointer to nodes.
/// @param[in] maxConductivity (m2) Max conductivity.
/// @param[in] expansionScaleFactor (--) Scale factor for isentropic gas cooling.
/// @param[in] referenceDensity (kg/m3) Reference fluid density for power curve.
/// @param[in] referenceSpeed (revolution/min) Reference impeller speed for power curve.
/// @param[in] referenceCoeff0 (kPa) Reference performance curve 0th-order coefficient.
/// @param[in] referenceCoeff1 (kPa) Reference performance curve 1th-order coefficient.
/// @param[in] referenceCoeff2 (kPa) Reference performance curve 2th-order coefficient.
/// @param[in] referenceCoeff3 (kPa) Reference performance curve 3th-order coefficient.
/// @param[in] referenceCoeff4 (kPa) Reference performance curve 4th-order coefficient.
/// @param[in] referenceCoeff5 (kPa) Reference performance curve 5th-order coefficient.
/// @param[in] bestEfficiency (--) (0-1) Efficiency at best efficiency point at reference.
/// @param[in] referenceQBep (m3/s) Volume flow rate at best efficiency point at reference.
/// @param[in] referencePBep (kPa) Pressure rise at best efficiency point at reference.
/// @param[in] filterGain (--) (0-1) Flow filter gain for system curve estimate.
/// @param[in] driveRatio (--) Gear ratio of motor to impeller speed.
/// @param[in] thermalLength (m) Impeller length for thermal convection.
/// @param[in] thermalDiameter (m) Impeller inner diameter for thermal convection.
/// @param[in] surfaceRoughness (m) Impeller wall surface roughness for convection.
/// @param[in] checkValveActive (--) Flag indicating that the built in check valve function is active.
///
/// @details Default constructs this GUNNS Gas Fan link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanConfigData::GunnsGasFanConfigData(const std::string& name,
GunnsNodeList* nodes,
const double maxConductivity,
const double expansionScaleFactor,
const double referenceDensity,
const double referenceSpeed,
const double referenceCoeff0,
const double referenceCoeff1,
const double referenceCoeff2,
const double referenceCoeff3,
const double referenceCoeff4,
const double referenceCoeff5,
const double bestEfficiency,
const double referenceQBep,
const double filterGain,
const double driveRatio,
const double thermalLength,
const double thermalDiameter,
const double surfaceRoughness,
const bool checkValveActive)
:
GunnsFluidPotentialConfigData(name, nodes, maxConductivity, expansionScaleFactor),
mReferenceDensity(referenceDensity),
mReferenceSpeed (referenceSpeed),
mReferenceCoeff0 (referenceCoeff0),
mReferenceCoeff1 (referenceCoeff1),
mReferenceCoeff2 (referenceCoeff2),
mReferenceCoeff3 (referenceCoeff3),
mReferenceCoeff4 (referenceCoeff4),
mReferenceCoeff5 (referenceCoeff5),
mBestEfficiency (bestEfficiency),
mReferenceQBep (referenceQBep),
mFilterGain (filterGain),
mDriveRatio (driveRatio),
mThermalLength (thermalLength),
mThermalDiameter (thermalDiameter),
mSurfaceRoughness(surfaceRoughness),
mCheckValveActive(checkValveActive)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source object to copy.
///
/// @details Copy constructs this GUNNS Gas Fan link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanConfigData::GunnsGasFanConfigData(const GunnsGasFanConfigData& that)
:
GunnsFluidPotentialConfigData(that),
mReferenceDensity(that.mReferenceDensity),
mReferenceSpeed (that.mReferenceSpeed),
mReferenceCoeff0 (that.mReferenceCoeff0),
mReferenceCoeff1 (that.mReferenceCoeff1),
mReferenceCoeff2 (that.mReferenceCoeff2),
mReferenceCoeff3 (that.mReferenceCoeff3),
mReferenceCoeff4 (that.mReferenceCoeff4),
mReferenceCoeff5 (that.mReferenceCoeff5),
mBestEfficiency (that.mBestEfficiency),
mReferenceQBep (that.mReferenceQBep),
mFilterGain (that.mFilterGain),
mDriveRatio (that.mDriveRatio),
mThermalLength (that.mThermalLength),
mThermalDiameter (that.mThermalDiameter),
mSurfaceRoughness(that.mSurfaceRoughness),
mCheckValveActive(that.mCheckValveActive)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Gas Fan link model configuration data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanConfigData::~GunnsGasFanConfigData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] malfBlockageFlag (--) Blockage malfunction flag.
/// @param[in] malfBlockageValue (--) Blockage malfunction fractional value (0-1).
/// @param[in] sourcePressure (kPa) Initial pressure rise of the link.
/// @param[in] motorSpeed (revolution/min) Initial speed of the motor.
/// @param[in] wallTemperature (K) Initial impeller wall temperature.
///
/// @details Default constructs this GUNNS Gas Fan link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanInputData::GunnsGasFanInputData(const bool malfBlockageFlag,
const double malfBlockageValue,
const double sourcePressure,
const double motorSpeed,
const double wallTemperature)
:
GunnsFluidPotentialInputData(malfBlockageFlag, malfBlockageValue, sourcePressure),
mMotorSpeed (motorSpeed),
mWallTemperature(wallTemperature)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] that (--) Source object to copy.
///
/// @details Copy constructs this GUNNS Gas Fan link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanInputData::GunnsGasFanInputData(const GunnsGasFanInputData& that)
:
GunnsFluidPotentialInputData(that),
mMotorSpeed (that.mMotorSpeed),
mWallTemperature(that.mWallTemperature)
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Gas Fan link model input data.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFanInputData::~GunnsGasFanInputData()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @note This should be followed by a call to the initialize method before calling an update
/// method.
///
/// @details Default constructs this GUNNS Gas Fan link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFan::GunnsGasFan()
:
GunnsFluidPotential(),
mReferenceDensity(0.0),
mReferenceSpeed(0.0),
mReferenceQBep(0.0),
mFilterGain(0.0),
mDriveRatio(0.0),
mThermalDiameter(0.0),
mThermalSurfaceArea(0.0),
mThermalROverD(0.0),
mReferenceQ(0.0),
mReferencePowerBep(0.0),
mSpecificSpeed(0.0),
mMotorSpeed(0.0),
mWallTemperature(0.0),
mWallHeatFlux(0.0),
mImpellerTorque(0.0),
mImpellerSpeed(0.0),
mImpellerPower(0.0),
mSystemConstant(0.0),
mSourceQ(0.0),
mCheckValveActive(false),
mCheckValvePosition(0.0),
mCurve()
{
for (int i=0; i<6; ++i) {
mReferenceCoeffs[i] = 0.0;
mAffinityCoeffs[i] = 0.0;
}
mPowerCoeffs[0] = 0.0;
mPowerCoeffs[1] = 0.0;
mPowerCoeffs[2] = 0.0;
mPowerCoeffs[3] = 0.0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Default destructs this GUNNS Gas Fan link model.
///////////////////////////////////////////////////////////////////////////////////////////////////
GunnsGasFan::~GunnsGasFan()
{
// nothing to do
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] configData (--) Configuration data.
/// @param[in] inputData (--) Input data.
/// @param[in,out] links (--) Link vector.
/// @param[in] port0 (--) Nominal inlet port map index.
/// @param[in] port1 (--) Nominal outlet port map index.
///
/// @returns void
///
/// @throws TsInitializationException
///
/// @details Initializes this GUNNS Gas Fan link model with configuration and input data. Some
/// validation of config data is needed before state data can be derived from it.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::initialize(const GunnsGasFanConfigData& configData,
const GunnsGasFanInputData& inputData,
std::vector<GunnsBasicLink*>& links,
const int port0,
const int port1)
{
/// - First initialize & validate parent.
GunnsFluidPotential::initialize(configData, inputData, links, port0, port1);
/// - Reset initialization status flag.
mInitFlag = false;
/// - Initialize from configuration data.
mReferenceSpeed = configData.mReferenceSpeed;
mReferenceDensity = configData.mReferenceDensity;
mReferenceCoeffs[0] = configData.mReferenceCoeff0;
mReferenceCoeffs[1] = configData.mReferenceCoeff1;
mReferenceCoeffs[2] = configData.mReferenceCoeff2;
mReferenceCoeffs[3] = configData.mReferenceCoeff3;
mReferenceCoeffs[4] = configData.mReferenceCoeff4;
mReferenceCoeffs[5] = configData.mReferenceCoeff5;
mReferenceQBep = configData.mReferenceQBep;
mFilterGain = configData.mFilterGain;
mDriveRatio = configData.mDriveRatio;
mCheckValveActive = configData.mCheckValveActive;
mThermalDiameter = configData.mThermalDiameter;
mThermalSurfaceArea = configData.mThermalLength * UnitConversion::PI_UTIL * mThermalDiameter;
if (mThermalSurfaceArea > DBL_EPSILON) {
mThermalROverD = configData.mSurfaceRoughness / configData.mThermalDiameter;
} else {
mThermalROverD = 0.0;
}
/// - Find reference power curve from reference pressure curve and best efficiency point.
/// Specific speed is limited to between 0.2 and 5.0 radians, which covers the majority of
/// radial, mixed & axial flow centrifugal pumps & fans.
if (mReferenceQBep > 0.0 and configData.mBestEfficiency > 0.0) {
/// - Throw an exception if best efficiency is outside (0-1).
if (1.0 < configData.mBestEfficiency) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Best efficiency outside (0-1).");
}
/// - If reference coefficients 1-5 are zero, the model needs to calculate its own
/// - reference curve.
bool defineCurve = true;
for(int i = 1; i < 6; i++){
if(mReferenceCoeffs[i] != 0.0){
defineCurve = false;
}
}
/// - Calculate pressure at best efficiency point (or use the user inputed value)
double pressureBep = 0.0;
if(defineCurve){
pressureBep = mReferenceCoeffs[0];
} else{
mCurve.setCoeffs(mReferenceCoeffs);
pressureBep = mCurve.evaluate(mReferenceQBep);
}
/// - Calculate Specific Speed
mSpecificSpeed = mReferenceSpeed / UnitConversion::SEC_PER_MIN_PER_2PI * sqrt(mReferenceQBep)
* pow(UnitConversion::KPA_PER_PA * mReferenceDensity / pressureBep, 0.75);
mSpecificSpeed = MsMath::limitRange(0.2, mSpecificSpeed, 5.0);
const double frac = (mSpecificSpeed - mSpecificSpeedRadial)
/ (mSpecificSpeedAxial - mSpecificSpeedRadial);
/// - If a Pressure at BEP is defined, use it to calculate Reference performance curve. The
/// Config curve coefficients are ignored.
if(defineCurve){
for(int i = 0; i < 6; i++){
mReferenceCoeffs[i] = mRefCoeffsRadial[i] + frac * (mRefCoeffsAxial[i] - mRefCoeffsRadial[i]);
mReferenceCoeffs[i] *= pressureBep / pow(mReferenceQBep, double(i));
}
}
/// - Calculate power at BEP and power curve
mReferencePowerBep = UnitConversion::PA_PER_KPA * pressureBep * mReferenceQBep
/ configData.mBestEfficiency;
mPowerCoeffs[0] = mPowerCoeffsRadial[0] + frac * (mPowerCoeffsAxial[0] - mPowerCoeffsRadial[0]);
mPowerCoeffs[1] = mPowerCoeffsRadial[1] + frac * (mPowerCoeffsAxial[1] - mPowerCoeffsRadial[1]);
mPowerCoeffs[2] = mPowerCoeffsRadial[2] + frac * (mPowerCoeffsAxial[2] - mPowerCoeffsRadial[2]);
mPowerCoeffs[3] = mPowerCoeffsRadial[3] + frac * (mPowerCoeffsAxial[3] - mPowerCoeffsRadial[3]);
} else {
mSpecificSpeed = 0.0;
}
/// - Find the root of the reference curve, which represents the maximum volumetric flow rate
/// the fan can produce at reference conditions. This may fail if the curve has an even
/// number of positive real roots. It should ideally have exactly 1 such root. Note this
/// imposes a maximum limit of 1000.0 m3/s on the fan curve root.
try {
mReferenceQ = 0.0;
mCurve.improveRoot(mReferenceQ, mReferenceCoeffs, 1000.0);
} catch (TsNumericalException &e) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Can't find a suitable real root in reference curve.");
}
/// - Throw an exception if the reference flow rate at best efficiency is greater than the
/// reference curve max flow.
if (mReferenceQ <= mReferenceQBep) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Reference flow at best efficiency point >= reference curve maximum flow.");
}
/// - Initialize from input data.
mMotorSpeed = inputData.mMotorSpeed;
mWallTemperature = inputData.mWallTemperature;
/// - Initialize the system constant somewhere in the ballpark of fan performance boundaries
/// to kick-start the flow on first pass.
mSystemConstant = mReferenceQ / sqrt(std::max(DBL_EPSILON, mReferenceCoeffs[0]));
/// - Initialize remaining state data.
mWallHeatFlux = 0.0;
mImpellerTorque = 0.0;
mImpellerSpeed = 0.0;
mImpellerPower = 0.0;
mAffinityCoeffs[0] = 0.0;
mAffinityCoeffs[1] = 0.0;
mAffinityCoeffs[2] = 0.0;
mAffinityCoeffs[3] = 0.0;
mAffinityCoeffs[4] = 0.0;
mAffinityCoeffs[5] = 0.0;
mSourceQ = 0.0;
mCheckValvePosition = 0.0;
/// - Create the internal fluid.
createInternalFluid();
/// - Validates the link initialization.
//
validate();
/// - Set initialization status flag to indicate successful initialization.
mInitFlag = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @returns void
///
/// @throws TsInitializationException
///
/// @details Validates this GUNNS Gas Fan Model link model initial state. Some validation of
/// config data has already occurred in the initialize method, so this method just checks
/// the final state of the link.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::validate() const
{
/// - Throw an exception if reference density is non-positive.
if (mReferenceDensity < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Reference density < DBL_EPSILON.");
}
/// - Throw an exception if reference speed is non-positive.
if (mReferenceSpeed < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Reference speed < DBL_EPSILON.");
}
/// - Throw an exception if reference curve at Q=0 is non-positive.
if (mReferenceCoeffs[0] < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Reference curve dead-head pressure < DBL_EPSILON.");
}
/// - Throw an exception if drive ratio is non-positive.
if (mDriveRatio < DBL_EPSILON) {
GUNNS_ERROR(TsInitializationException, "Invalid Configuration Data",
"Drive ratio < DBL_EPSILON.");
}
/// - Throw an exception if initial motor speed is negative,
if (mMotorSpeed < 0.0) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data", "Motor speed < 0.");
}
/// - Throw an exception if initial wall temperature is negative,
if (mWallTemperature < 0.0) {
GUNNS_ERROR(TsInitializationException, "Invalid Input Data", "Wall temperature < 0.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Derived classes should call their base class implementation too.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::restartModel()
{
/// - Reset the base class.
GunnsFluidPotential::restartModel();
/// - Reset non-config & non-checkpointed attributes.
mImpellerSpeed = 0.0;
mImpellerPower = 0.0;
mAffinityCoeffs[0] = 0.0;
mAffinityCoeffs[1] = 0.0;
mAffinityCoeffs[2] = 0.0;
mAffinityCoeffs[3] = 0.0;
mAffinityCoeffs[4] = 0.0;
mAffinityCoeffs[5] = 0.0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Time step (not used).
///
/// @returns void
///
/// @details Updates this GUNNS Gas Fan link model source pressure. Also calculates check valve
/// position is active, and updates the effective conductivity.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::updateState(const double dt __attribute__((unused)))
{
/// - Protect for divide by zero on drive ratio; also setting drive ratio to zero disconnects
/// the impeller from the motor, allowing manual control of the impeller speed for tuning.
if (mDriveRatio > DBL_EPSILON) {
mImpellerSpeed = mMotorSpeed / mDriveRatio;
} else {
GUNNS_WARNING("impeller is disconnected from motor.");
}
computeSourcePressure();
/// - Check if check valve active/closed
double deltaPress = mSourcePressure + mNodes[0]->getOutflow()->getPressure() - mNodes[1]->getOutflow()->getPressure();
if(deltaPress > 0.0 or !mCheckValveActive){
mCheckValvePosition = 1.0;
} else{
mCheckValvePosition = 0.0;
}
mEffectiveConductivity = mMaxConductivity * mCheckValvePosition;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] dt (s) Time step.
/// @param[in] flowRate (kg/s) Mass flow rate.
///
/// @return void
///
/// @details Updates this GUNNS Gas Fan link model internal fluid thermal state and fluid outputs
/// to the motor.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::updateFluid(const double dt __attribute__((unused)), const double flowRate)
{
/// - Impeller power. Power is kept as a class attribute for reference & display. We have two
/// different ways to calculate power depending on the user's need. This first method
/// represents total shaft power load including useful power imparted to the flow downstream
/// plus wasted power due to aerodynamic inefficiencies, bearing & seal friction, etc. This
/// equation is an empirical observation of typical pump/fan performance as a function of
/// best efficiency, flow rate and pump specific speed.
if (mSpecificSpeed > 0.0 and mImpellerSpeed > FLT_EPSILON) {
const double speedRatio = mImpellerSpeed / mReferenceSpeed;
const double affinityQ = mReferenceQBep * speedRatio;
const double densityFactor = mNodes[0]->getOutflow()->getDensity() / mReferenceDensity;
const double affinityP = speedRatio * speedRatio * speedRatio
* mReferencePowerBep * densityFactor;
const double QQbep = MsMath::limitRange(0.0, mVolFlowRate, mReferenceQ * speedRatio)
/ std::max(affinityQ, DBL_EPSILON);
mImpellerPower = affinityP * (mPowerCoeffs[0]
+ mPowerCoeffs[1] * QQbep
+ mPowerCoeffs[2] * QQbep * QQbep
+ mPowerCoeffs[3] * QQbep * QQbep * QQbep);
/// - This version of power is only the useful power imparted to the flow downstream, and does
/// not include power wasted to aero inefficiencies or friction.
} else {
mImpellerPower = UnitConversion::PA_PER_KPA * fabs(mVolFlowRate) * mSourcePressure;
}
/// - Shaft torque opposes motor spin so has opposite sign. Motor speed units are converted to
/// r/s to relate to torque in N*m and power in Watts. Torque on the shaft is zero if the
/// drive ratio is zero, i.e. impeller is disconnected from the motor.
if (mMotorSpeed > FLT_EPSILON and mDriveRatio > DBL_EPSILON) {
mImpellerTorque = -mImpellerPower * UnitConversion::SEC_PER_MIN_PER_2PI / mMotorSpeed;
} else {
mImpellerTorque = 0.0;
}
/// - Perform heat convection between the internal fluid and pipe wall.
mWallHeatFlux = GunnsFluidUtils::computeConvectiveHeatFlux(mInternalFluid,
flowRate,
mThermalROverD,
mThermalDiameter,
mThermalSurfaceArea,
mWallTemperature);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @return void
///
/// @details Calculates the pressure produced by the impeller as a function of impeller speed,
/// inlet density & flow rate. Implements the fan performance (P-Q) curve as a 5th-order
/// polynomial. Affects of inlet density & fan speed follow the fan Affinity Laws.
///
/// There is naturally an unstable feedback loop between fan pressure and flow rate, which
/// causes these parameters to oscillate wildly if undamped. To prevent this, we estimate
/// the system's pressure curve and solve for the flow rate (Q) at which the system & fan
/// curves intersect, and fan pressure approaches that point.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::computeSourcePressure()
{
/// - Impeller inlet fluid density uses the source node based on last-pass flow direction.
const int sourcePort = determineSourcePort(mFlux, 0, 1);
const double sourceDensity = mNodes[sourcePort]->getOutflow()->getDensity();
/// - The impeller generates no pressure if it is stopped or there is no fluid.
if (mImpellerSpeed > FLT_EPSILON and sourceDensity > FLT_EPSILON) {
/// - Scale fan curve coefficients based on speed and density. This implements the Affinity
/// Laws in the polynomial as:
/// Coeff_order = Coeff_ref_order * (rho/rho_ref) * (N/N_ref)^(2-order).
const double densityFactor = sourceDensity / mReferenceDensity;
const double speedFactor = mImpellerSpeed / mReferenceSpeed;
for (int order=0; order<6; ++order) {
mAffinityCoeffs[order] = mReferenceCoeffs[order] * densityFactor
* pow(speedFactor, 2.0 - order);
}
/// - Estimate system conductivity based on last-pass flow rate & pressure. We assume the
/// system that the fan is flowing through follows the GUNNS fluid pressure-flow
/// relationship: Q = Gsys * sqrt(dp). Thus, the network's minimum linearization
/// potential should be configured to be no more than about 5% of maximum fan dead-head
/// delta-pressure, for best results.
///
/// - Min/max limits are set to avoid locking up the pressure, and the result is
/// filtered for further stability as needed.
const double gSys = std::max(mReferenceQ * speedFactor * 0.0001, mVolFlowRate)
/ sqrt(MsMath::limitRange(DBL_EPSILON, mSourcePressure, mAffinityCoeffs[0]));
mSystemConstant = mFilterGain * gSys + (1.0 - mFilterGain) * mSystemConstant;
/// - Generate the coefficients for the (fan - system) polynomial, the root of which is the
/// predicted flow rate.
double coeffs[6];
for (int order=0; order<6; ++order) {
coeffs[order] = mAffinityCoeffs[order];
}
if (mSystemConstant > DBL_EPSILON) {
coeffs[2] -= 1.0 / mSystemConstant / mSystemConstant;
}
/// - Use a root-finding algorithm to solve for the predicted source flow. The maximum flow
/// the fan can create is scaled by impeller speed by the Affinity Law, and is used as the
/// upper bound for the root-finders.
try {
mCurve.improveRoot(mSourceQ, coeffs, mReferenceQ * speedFactor);
} catch (TsNumericalException &e) {
GUNNS_WARNING(" failed to find the impeller-system intersection.");
}
/// - Finally, evaluate the fan curve for produced delta-pressure.
mCurve.setCoeffs(mAffinityCoeffs);
mSourcePressure = std::max(0.0, mCurve.evaluate(mSourceQ));
} else {
mSourcePressure = 0.0;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (m2) New Thermal Surface Area.
///
/// @returns void
///
/// @details Sets the thermal surface area of this this GUNNS Gas Fan link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::setThermalSurfaceArea(const double value)
{
mThermalSurfaceArea = std::max(0.0, value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (K) New Wall Temperature.
///
/// @returns void
///
/// @details Sets the wall temperature of this this GUNNS Gas Fan link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::setWallTemperature(const double value)
{
mWallTemperature = std::max(0.0, value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (revolution/min) New Motor Speed Temperature.
///
/// @returns void
///
/// @details Sets the motor speed of this this GUNNS Gas Fan link model.
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::setMotorSpeed(const double value)
{
mMotorSpeed = value;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @param[in] value (--) Check valve on/off flag
///
/// @returns void
///
/// @details Turns on or off the check valve functionality
////////////////////////////////////////////////////////////////////////////////////////////////////
void GunnsGasFan::setCheckValveFlag(const bool value)
{
mCheckValveActive = value;
}
| 47.986446 | 122 | 0.550545 | [
"object",
"vector",
"model"
] |
0998da8a6f1a885859d54707d46a8cdd6df6a6c8 | 9,972 | cpp | C++ | inetsrv/iis/svcs/staxcore/fcache2/sdcache/sdcache.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/iis/svcs/staxcore/fcache2/sdcache/sdcache.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/iis/svcs/staxcore/fcache2/sdcache/sdcache.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
SDCACHE.CPP
This file implements the security descriptor cache.
Our goal is to enable the file handle cache to consume less memory
representing security descriptors, by enabling duplicate
security descriptors to be detected and referenced in here.
--*/
#include <windows.h>
#include <dbgtrace.h>
#include "fdlhash.h"
#include "rwnew.h"
#include "refptr2.h"
#include "xmemwrpr.h"
#include "sdcache.h"
//#include "cintrnl.h"
BOOL
IsSelfRelativeSecurityDescriptor( PSECURITY_DESCRIPTOR pSecDesc ) {
SECURITY_DESCRIPTOR_CONTROL control ;
DWORD dwRevision ;
if (GetSecurityDescriptorControl( pSecDesc, &control, &dwRevision ))
return (control & SE_SELF_RELATIVE) != 0;
else
return FALSE;
}
BOOL
CSDKey::IsValid() {
/*++
Routine Description :
This function validates that the key object is correctly constructed.
We do NOT allow any NULL pointers, and we must have valid self relative
security descriptors embedded.
Arguments :
NONE.
Return Value :
TRUE if correctly initialized, FALSE otherwise
--*/
_ASSERT( m_pMapping != 0 ) ;
_ASSERT( m_pSecDesc != 0 ) ;
_ASSERT( IsValidSecurityDescriptor( m_pSecDesc ) ) ;
_ASSERT( IsSelfRelativeSecurityDescriptor( m_pSecDesc ) ) ;
_ASSERT( m_cbSecDesc > 0 ) ;
_ASSERT( (DWORD)m_cbSecDesc == GetSecurityDescriptorLength( m_pSecDesc ) ) ;
return m_pMapping != 0 &&
m_pSecDesc != 0 &&
IsValidSecurityDescriptor( m_pSecDesc ) &&
IsSelfRelativeSecurityDescriptor( m_pSecDesc ) &&
m_cbSecDesc > 0 &&
(DWORD)m_cbSecDesc == GetSecurityDescriptorLength( m_pSecDesc ) ;
}
int
CSDKey::MatchKey( CSDKey left,
CSDKey right
) {
/*++
Routine Description :
This function must compare 2 security descriptor keys,
and correctly define an ordering on the keys.
(The hash table we're used in sorts buckets).
Arguments :
left, right - the two keys to be compared
Return Value :
-1 if left < right
0 if left == right
1 if left > right
--*/
//
// Validate our arguments !
//
_ASSERT( left.IsValid() ) ;
_ASSERT( right.IsValid() ) ;
//
// perform the comparison !
//
int iResult = memcmp( left.m_pMapping, right.m_pMapping, sizeof(GENERIC_MAPPING));
if( iResult != 0 ) {
iResult = left.m_cbSecDesc - right.m_cbSecDesc ;
if( iResult == 0 ) {
iResult = memcmp( left.m_pSecDesc, right.m_pSecDesc, left.m_cbSecDesc ) ;
}
}
return iResult ;
}
DWORD
CSDKey::HashKey( CSDKey Key ) {
/*++
Routine Description :
This function computes a hash on security descriptors.
We ignore the GENERIC_MAPPING part of the key - this
will vary very rarely.
We're a static function so we can be passed as a function
pointer.
We simply look at the security descriptor as an array of DWORD's
and sum them up.
Arguments :
Key - compute the hash of this security descriptor
Return Value :
A Hash Value - no failure cases can occur
--*/
//
// Very simple - sum all of the bits in the security descriptor !
//
_ASSERT( Key.IsValid() ) ;
DWORD cb = (DWORD)Key.m_cbSecDesc ;
cb /= 4 ;
DWORD* pdw = (DWORD*)Key.m_pSecDesc ;
DWORD* pdwEnd = pdw + cb ;
DWORD Sum = 0 ;
while( pdw != pdwEnd ) {
Sum += *pdw++ ;
}
return Sum ;
}
void*
CSDObject::operator new( size_t size,
CSDKey& key
) {
/*++
Routine Description :
This function allocates memory of a CSDObject,
we require special handle because CSDObjects are variable length.
Arguments :
size - the size as generated by the compiler
key - the security descriptor we're going to stick in here
Return Value :
Allocated memory - NULL if failure
--*/
_ASSERT( size >= sizeof(CSDObject) ) ;
_ASSERT( key.IsValid() ) ;
size += key.m_cbSecDesc - sizeof( DWORD ) ;
return ::new BYTE[size] ;
}
void
CSDObject::operator delete( void* lpv ) {
/*++
Routine Description :
Release a CSDObject !
Arguments :
lpv - where the CSDObject was before it was destructed
Return Value :
None.
--*/
::delete(lpv) ;
}
long
CSDObject::Release() {
/*++
Routine Description :
This function drops a reference to a CSDObject.
WARNING - we will grab locks on the CSDObjectContainer
that is holding this item, the last reference MUST NEVER
BE RELEASED WITHIN A LOCK !
If the reference count drops to one, that means that the only reference
remaining on the object is the one from the hash table.
So we grab the hash table lock exclusively, so we can prevent new references
from being added, and we then do a InterlockedCompareExchange to drop
the reference count to 0. We need to do this to ensure that between
the time we decrement the ref. count and the time we grab the lock, that
another user doesn't simultaneously raise and drop the ref. count.
Arguments :
None.
Return Value :
the resulting refcount.
--*/
_ASSERT( IsValid() ) ;
CSDObject* pdelete = 0 ;
long l = InterlockedDecrement( (long*)&m_cRefCount ) ;
_ASSERT( l>=1 ) ;
if( l == 1 ) {
m_pContainer->m_lock.ExclusiveLock() ;
if( InterlockedCompareExchange( (long*)&m_cRefCount, 0, 1) == 1 ) {
m_pContainer->m_table.Delete( this ) ;
pdelete = this ;
}
m_pContainer->m_lock.ExclusiveUnlock() ;
}
if( pdelete ) {
delete pdelete ;
l = 0 ;
}
return l ;
}
//
// Check that we are a valid object !
//
BOOL
CSDObject::IsValid() {
/*++
Routine Description :
This function checks that we were properly constructed -
if allocation of our memory succeeds, nothing should stand
in the way of producing a completely initialized object !
Arguments :
None.
Return Value :
TRUE if correctly constructed, FALSE otherwise !
--*/
_ASSERT( m_dwSignature == SIGNATURE ) ;
_ASSERT( m_pContainer != 0 ) ;
_ASSERT( m_cRefCount >= 0 ) ;
CSDKey key( &m_mapping, SecurityDescriptor() ) ;
_ASSERT( key.IsValid() ) ;
_ASSERT( CSDKey::HashKey( key ) == m_dwHash ) ;
return m_dwSignature == SIGNATURE &&
m_pContainer != 0 &&
m_cRefCount >= 0 &&
key.IsValid() &&
CSDKey::HashKey( key ) == m_dwHash ;
}
BOOL
CSDObject::AccessCheck( HANDLE hToken,
ACCESS_MASK accessMask,
CACHE_ACCESS_CHECK pfnAccessCheck
) {
/*++
Routine Description :
This function performs an ACCESS Check to determine whether
a client has the specified permissions to the object.
Arguments :
hToken - Client Token
accessMask - the Client's desired access
Return Value :
TRUE if the client has access,
FALSE otherwise !
--*/
if( hToken == 0 )
return TRUE ;
_ASSERT( hToken != 0 ) ;
_ASSERT( accessMask != 0 ) ;
_ASSERT( IsValid() ) ;
BYTE psFile[256] ;
DWORD dwPS = sizeof( psFile ) ;
DWORD dwGrantedAccess = 0 ;
BOOL fAccess = FALSE ;
BOOL f = FALSE ;
if( pfnAccessCheck ) {
f = pfnAccessCheck( SecurityDescriptor(),
hToken,
accessMask,
&m_mapping,
(PRIVILEGE_SET*)psFile,
&dwPS,
&dwGrantedAccess,
&fAccess
) ;
} else {
f = ::AccessCheck( SecurityDescriptor(),
hToken,
accessMask,
&m_mapping,
(PRIVILEGE_SET*)psFile,
&dwPS,
&dwGrantedAccess,
&fAccess
) ;
}
DWORD dw = GetLastError() ;
return f && fAccess ;
}
//
// Now - find or create a given security descriptor
// item !
//
CSDObject*
CSDObjectContainer::FindOrCreate( DWORD dwHash,
CSDKey& key
) {
/*++
Routine Description :
This function will either locate a matching security
descriptor in the cache, or return a pointer to a new
CSDObject created and placed into the cache.
NOTE : We must always ADD a reference while the lock is held,
because Release() will try to re-enter the lock and remove
the object from the hash table !
Arguments :
dwHash - the hash of the sought security descriptor
key - describes the security descriptor and GENERIC_MAPPING
we are to locate !
Return Value :
A pointer to a CSDObject in the cache, or NULL if failure.
A NULL means the object was not found, and we couldn't allocate
memory to insert a new one !
--*/
_ASSERT( key.IsValid() ) ;
_ASSERT( CSDKey::HashKey(key) == dwHash ) ;
CSDObject* pObject = 0 ;
m_lock.ShareLock() ;
SDTABLE::ITER iter =
m_table.SearchKeyHashIter( dwHash,
key,
pObject
) ;
if( pObject ) {
pObject->AddRef() ;
m_lock.ShareUnlock() ;
} else {
if( !m_lock.SharedToPartial() ) {
m_lock.ShareUnlock() ;
m_lock.PartialLock() ;
iter = m_table.SearchKeyHashIter( dwHash,
key,
pObject
) ;
}
if( pObject != 0 ) {
pObject->AddRef() ;
} else {
pObject = new( key ) CSDObject( dwHash, key, this ) ;
if( pObject != 0 ) {
m_lock.FirstPartialToExclusive() ;
BOOL fInsert =
m_table.InsertDataHashIter( iter,
dwHash,
key,
pObject
) ;
m_lock.ExclusiveUnlock() ;
if( !fInsert ) {
pObject->Release() ;
pObject = 0 ;
}
return pObject ;
}
}
m_lock.PartialUnlock() ;
}
return pObject ;
} // End FindOrCreate()
CSDMultiContainer::Init() {
/*++
Routine Description :
Initialize everything so we're ready to go !
Arguments :
None.
Return Value :
TRUE if successfull, FALSE otherwise !
--*/
BOOL fReturn = TRUE ;
for( int i=0; i<CONTAINERS && fReturn; i++ ) {
fReturn &= m_rgContainer[i].Init() ;
}
return fReturn ;
}
| 21.307692 | 84 | 0.622543 | [
"object"
] |
09bf794ed0a66c807f03641f161c78cc09ffc592 | 12,896 | hpp | C++ | include/Zenject/FactoryFromBinderBase.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Zenject/FactoryFromBinderBase.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/Zenject/FactoryFromBinderBase.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: Zenject.ScopeConcreteIdArgConditionCopyNonLazyBinder
#include "Zenject/ScopeConcreteIdArgConditionCopyNonLazyBinder.hpp"
// Including type: System.Guid
#include "System/Guid.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: FactoryBindInfo
class FactoryBindInfo;
// Forward declaring type: BindInfo
class BindInfo;
// Forward declaring type: IProvider
class IProvider;
// Skipping declaration: ConditionCopyNonLazyBinder because it is already included!
// Forward declaring type: ConcreteBinderGeneric`1<TContract>
template<typename TContract>
class ConcreteBinderGeneric_1;
// Forward declaring type: InjectContext
class InjectContext;
// Forward declaring type: NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder
class NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: GameObject
class GameObject;
// Forward declaring type: Object
class Object;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Size: 0x38
#pragma pack(push, 1)
// Autogenerated type: Zenject.FactoryFromBinderBase
// [NoReflectionBakingAttribute] Offset: DDC900
class FactoryFromBinderBase : public Zenject::ScopeConcreteIdArgConditionCopyNonLazyBinder {
public:
// Nested type: Zenject::FactoryFromBinderBase::$get_AllParentTypes$d__17
class $get_AllParentTypes$d__17;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass20_0
class $$c__DisplayClass20_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass21_0
class $$c__DisplayClass21_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass23_0
class $$c__DisplayClass23_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass24_0
class $$c__DisplayClass24_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass26_0
class $$c__DisplayClass26_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass27_0
class $$c__DisplayClass27_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass28_0
class $$c__DisplayClass28_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass29_0
class $$c__DisplayClass29_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass30_0
class $$c__DisplayClass30_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass31_0
class $$c__DisplayClass31_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass32_0
class $$c__DisplayClass32_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass33_0
class $$c__DisplayClass33_0;
// Nested type: Zenject::FactoryFromBinderBase::$$c__DisplayClass34_0
class $$c__DisplayClass34_0;
// [CompilerGeneratedAttribute] Offset: 0xDDEA58
// private Zenject.DiContainer <BindContainer>k__BackingField
// Size: 0x8
// Offset: 0x20
Zenject::DiContainer* BindContainer;
// Field size check
static_assert(sizeof(Zenject::DiContainer*) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xDDEA68
// private Zenject.FactoryBindInfo <FactoryBindInfo>k__BackingField
// Size: 0x8
// Offset: 0x28
Zenject::FactoryBindInfo* FactoryBindInfo;
// Field size check
static_assert(sizeof(Zenject::FactoryBindInfo*) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xDDEA78
// private System.Type <ContractType>k__BackingField
// Size: 0x8
// Offset: 0x30
System::Type* ContractType;
// Field size check
static_assert(sizeof(System::Type*) == 0x8);
// Creating value type constructor for type: FactoryFromBinderBase
FactoryFromBinderBase(Zenject::DiContainer* BindContainer_ = {}, Zenject::FactoryBindInfo* FactoryBindInfo_ = {}, System::Type* ContractType_ = {}) noexcept : BindContainer{BindContainer_}, FactoryBindInfo{FactoryBindInfo_}, ContractType{ContractType_} {}
// public System.Void .ctor(Zenject.DiContainer bindContainer, System.Type contractType, Zenject.BindInfo bindInfo, Zenject.FactoryBindInfo factoryBindInfo)
// Offset: 0x161D294
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FactoryFromBinderBase* New_ctor(Zenject::DiContainer* bindContainer, System::Type* contractType, Zenject::BindInfo* bindInfo, Zenject::FactoryBindInfo* factoryBindInfo) {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::FactoryFromBinderBase::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FactoryFromBinderBase*, creationType>(bindContainer, contractType, bindInfo, factoryBindInfo)));
}
// Zenject.DiContainer get_BindContainer()
// Offset: 0x161D34C
Zenject::DiContainer* get_BindContainer();
// private System.Void set_BindContainer(Zenject.DiContainer value)
// Offset: 0x161D354
void set_BindContainer(Zenject::DiContainer* value);
// protected Zenject.FactoryBindInfo get_FactoryBindInfo()
// Offset: 0x161D35C
Zenject::FactoryBindInfo* get_FactoryBindInfo();
// private System.Void set_FactoryBindInfo(Zenject.FactoryBindInfo value)
// Offset: 0x161D364
void set_FactoryBindInfo(Zenject::FactoryBindInfo* value);
// System.Func`2<Zenject.DiContainer,Zenject.IProvider> get_ProviderFunc()
// Offset: 0x161D36C
System::Func_2<Zenject::DiContainer*, Zenject::IProvider*>* get_ProviderFunc();
// System.Void set_ProviderFunc(System.Func`2<Zenject.DiContainer,Zenject.IProvider> value)
// Offset: 0x161D388
void set_ProviderFunc(System::Func_2<Zenject::DiContainer*, Zenject::IProvider*>* value);
// protected System.Type get_ContractType()
// Offset: 0x161D3A4
System::Type* get_ContractType();
// private System.Void set_ContractType(System.Type value)
// Offset: 0x161D3AC
void set_ContractType(System::Type* value);
// public System.Collections.Generic.IEnumerable`1<System.Type> get_AllParentTypes()
// Offset: 0x161D3B4
System::Collections::Generic::IEnumerable_1<System::Type*>* get_AllParentTypes();
// public Zenject.ConditionCopyNonLazyBinder FromNew()
// Offset: 0x161D46C
Zenject::ConditionCopyNonLazyBinder* FromNew();
// public Zenject.ConditionCopyNonLazyBinder FromResolve()
// Offset: 0x161D4A4
Zenject::ConditionCopyNonLazyBinder* FromResolve();
// public Zenject.ConditionCopyNonLazyBinder FromInstance(System.Object instance)
// Offset: 0x161D564
Zenject::ConditionCopyNonLazyBinder* FromInstance(::Il2CppObject* instance);
// public Zenject.ConditionCopyNonLazyBinder FromResolve(System.Object subIdentifier)
// Offset: 0x161D4AC
Zenject::ConditionCopyNonLazyBinder* FromResolve(::Il2CppObject* subIdentifier);
// Zenject.ConcreteBinderGeneric`1<T> CreateIFactoryBinder(out System.Guid factoryId)
// Offset: 0xFFFFFFFF
template<class T>
Zenject::ConcreteBinderGeneric_1<T>* CreateIFactoryBinder(System::Guid& factoryId) {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::FactoryFromBinderBase::CreateIFactoryBinder");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CreateIFactoryBinder", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<System::Guid&>()})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodThrow<Zenject::ConcreteBinderGeneric_1<T>*, false>(this, ___generic__method, factoryId);
}
// public Zenject.ConditionCopyNonLazyBinder FromComponentOn(UnityEngine.GameObject gameObject)
// Offset: 0x161D644
Zenject::ConditionCopyNonLazyBinder* FromComponentOn(UnityEngine::GameObject* gameObject);
// public Zenject.ConditionCopyNonLazyBinder FromComponentOn(System.Func`2<Zenject.InjectContext,UnityEngine.GameObject> gameObjectGetter)
// Offset: 0x161D728
Zenject::ConditionCopyNonLazyBinder* FromComponentOn(System::Func_2<Zenject::InjectContext*, UnityEngine::GameObject*>* gameObjectGetter);
// public Zenject.ConditionCopyNonLazyBinder FromComponentOnRoot()
// Offset: 0x161D800
Zenject::ConditionCopyNonLazyBinder* FromComponentOnRoot();
// public Zenject.ConditionCopyNonLazyBinder FromNewComponentOn(UnityEngine.GameObject gameObject)
// Offset: 0x161D87C
Zenject::ConditionCopyNonLazyBinder* FromNewComponentOn(UnityEngine::GameObject* gameObject);
// public Zenject.ConditionCopyNonLazyBinder FromNewComponentOn(System.Func`2<Zenject.InjectContext,UnityEngine.GameObject> gameObjectGetter)
// Offset: 0x161D960
Zenject::ConditionCopyNonLazyBinder* FromNewComponentOn(System::Func_2<Zenject::InjectContext*, UnityEngine::GameObject*>* gameObjectGetter);
// public Zenject.NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromNewComponentOnNewPrefab(UnityEngine.Object prefab)
// Offset: 0x161DA38
Zenject::NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder* FromNewComponentOnNewPrefab(UnityEngine::Object* prefab);
// public Zenject.NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInNewPrefab(UnityEngine.Object prefab)
// Offset: 0x161DB74
Zenject::NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder* FromComponentInNewPrefab(UnityEngine::Object* prefab);
// public Zenject.NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromComponentInNewPrefabResource(System.String resourcePath)
// Offset: 0x161DC9C
Zenject::NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder* FromComponentInNewPrefabResource(::Il2CppString* resourcePath);
// public Zenject.NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder FromNewComponentOnNewPrefabResource(System.String resourcePath)
// Offset: 0x161DDC4
Zenject::NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder* FromNewComponentOnNewPrefabResource(::Il2CppString* resourcePath);
// public Zenject.ConditionCopyNonLazyBinder FromNewScriptableObjectResource(System.String resourcePath)
// Offset: 0x161DEF8
Zenject::ConditionCopyNonLazyBinder* FromNewScriptableObjectResource(::Il2CppString* resourcePath);
// public Zenject.ConditionCopyNonLazyBinder FromScriptableObjectResource(System.String resourcePath)
// Offset: 0x161DFD0
Zenject::ConditionCopyNonLazyBinder* FromScriptableObjectResource(::Il2CppString* resourcePath);
// public Zenject.ConditionCopyNonLazyBinder FromResource(System.String resourcePath)
// Offset: 0x161E0A8
Zenject::ConditionCopyNonLazyBinder* FromResource(::Il2CppString* resourcePath);
// private Zenject.IProvider <.ctor>b__0_0(Zenject.DiContainer container)
// Offset: 0x161E174
Zenject::IProvider* $_ctor$b__0_0(Zenject::DiContainer* container);
// private UnityEngine.GameObject <FromComponentOnRoot>b__25_0(Zenject.InjectContext ctx)
// Offset: 0x161E224
UnityEngine::GameObject* $FromComponentOnRoot$b__25_0(Zenject::InjectContext* ctx);
}; // Zenject.FactoryFromBinderBase
#pragma pack(pop)
static check_size<sizeof(FactoryFromBinderBase), 48 + sizeof(System::Type*)> __Zenject_FactoryFromBinderBaseSizeCheck;
static_assert(sizeof(FactoryFromBinderBase) == 0x38);
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::FactoryFromBinderBase*, "Zenject", "FactoryFromBinderBase");
| 58.618182 | 299 | 0.76326 | [
"object",
"vector"
] |
09bfc4bbc2d16f9725690502a8f66d0c0ed60761 | 689 | cpp | C++ | DESIRE-Engine/src/Engine/Script/ScriptComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2020-10-04T18:50:01.000Z | 2020-10-04T18:50:01.000Z | DESIRE-Engine/src/Engine/Script/ScriptComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | null | null | null | DESIRE-Engine/src/Engine/Script/ScriptComponent.cpp | nyaki-HUN/DESIRE | dd579bffa77bc6999266c8011bc389bb96dee01d | [
"BSD-2-Clause"
] | 1 | 2018-09-18T08:03:33.000Z | 2018-09-18T08:03:33.000Z | #include "Engine/stdafx.h"
#include "Engine/Script/ScriptComponent.h"
#include "Engine/Core/String/String.h"
#include "Engine/Script/ScriptSystem.h"
ScriptComponent::ScriptComponent(GameObject& object)
: Component(object)
{
Modules::ScriptSystem->OnScriptComponentCreated(this);
}
ScriptComponent::~ScriptComponent()
{
Modules::ScriptSystem->OnScriptComponentDestroyed(this);
}
Component& ScriptComponent::CloneTo(GameObject& otherObject) const
{
DESIRE_TODO("Implement proper CloneTo");
ASSERT(false);
ScriptComponent* pNewComponent = Modules::ScriptSystem->CreateScriptComponentOnObject(otherObject, "TODO");
pNewComponent->SetEnabled(IsEnabled());
return *pNewComponent;
}
| 25.518519 | 108 | 0.793904 | [
"object"
] |
09c13e8cb9d5245a0239cbdb7c60a8a81141c9d6 | 7,646 | hpp | C++ | src/core/engine/engine.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | 7 | 2021-06-22T06:24:21.000Z | 2022-02-16T02:48:38.000Z | src/core/engine/engine.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | 4 | 2021-12-22T15:11:02.000Z | 2021-12-22T15:27:50.000Z | src/core/engine/engine.hpp | SJTU-IPADS/wukong-cube | ccabf1b754978322277dc881a43cedfd2687070f | [
"Apache-2.0"
] | 1 | 2022-01-19T04:23:18.000Z | 2022-01-19T04:23:18.000Z | /*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong
*
*/
#pragma once
#include <algorithm> //sort
#include <regex>
#include <tbb/concurrent_queue.h>
#include "core/common/global.hpp"
#include "core/common/type.hpp"
#include "core/common/coder.hpp"
// engine
#include "core/engine/sparql.hpp"
#include "core/engine/rdf.hpp"
#include "core/engine/msgr.hpp"
#ifdef TRDF_MODE
#include "core/engine/tsparql.hpp"
#endif
#include "core/store/dgraph.hpp"
#include "core/network/adaptor.hpp"
#include "core/sparql/query.hpp"
// utils
#include "utils/assertion.hpp"
#include "utils/timer.hpp"
namespace wukong {
#define BUSY_POLLING_THRESHOLD 10000000 // busy polling task queue 10s
#define MIN_SNOOZE_TIME 10 // MIX snooze time
#define MAX_SNOOZE_TIME 80 // MAX snooze time
// a vector of pointers of all local engines
class Engine;
std::vector<Engine *> engines;
class Engine {
private:
void execute(Bundle &bundle) {
if (bundle.type == SPARQL_QUERY) {
SPARQLQuery r = bundle.get_sparql_query();
sparql->execute_sparql_query(r);
} else if (bundle.type == GSTORE_CHECK) {
GStoreCheck r = bundle.get_gstore_check();
rdf->execute_gstore_check(r);
#ifdef DYNAMIC_GSTORE
} else if (bundle.type == DYNAMIC_LOAD) {
RDFLoad r = bundle.get_rdf_load();
rdf->execute_load_data(r);
#endif
} else { // print error msg and just skip the request
logstream(LOG_ERROR) << "Unsupported type of request." << LOG_endl;
}
}
int next_to_oblige(int own_id, int offset) {
if (Global::stealing_pattern == 0) { // pair stealing
if (offset == 1)
return ((Global::num_engines - 1) - own_id);
else
return -1;
} else if (Global::stealing_pattern == 1) { // ring stealing
return ((own_id + offset) % Global::num_engines);
}
return -1;
}
public:
const static uint64_t TIMEOUT_THRESHOLD = 10000; // 10 msec
int sid; // server id
int tid; // thread id
StringServer *str_server;
DGraph *graph;
Adaptor *adaptor;
Coder *coder;
Messenger *msgr;
#ifdef TRDF_MODE
TSPARQLEngine *sparql;
#else
SPARQLEngine *sparql;
#endif
RDFEngine *rdf;
bool at_work; // whether engine is at work or not
uint64_t last_time; // busy or not (work-oblige)
tbb::concurrent_queue<SPARQLQuery> runqueue; // task queue for sparql queries
Engine(int sid, int tid, StringServer *str_server, DGraph *graph, Adaptor *adaptor)
: sid(sid), tid(tid), last_time(timer::get_usec()),
str_server(str_server), graph(graph), adaptor(adaptor) {
coder = new Coder(sid, tid);
msgr = new Messenger(sid, tid, adaptor);
#ifdef TRDF_MODE
sparql = new TSPARQLEngine(sid, tid, str_server, graph, coder, msgr);
#else
sparql = new SPARQLEngine(sid, tid, str_server, graph, coder, msgr);
#endif
rdf = new RDFEngine(sid, tid, graph, coder, msgr);
}
void run() {
// NOTE: the 'tid' of engine is not start from 0,
// which can not be used by engines[] directly
int own_id = tid - Global::num_proxies;
uint64_t snooze_interval = MIN_SNOOZE_TIME;
// reset snooze
auto reset_snooze = [&snooze_interval](bool & at_work, uint64_t &last_time) {
at_work = true; // keep calm (no snooze)
last_time = timer::get_usec();
snooze_interval = MIN_SNOOZE_TIME;
};
while (true) {
at_work = false;
// check and send pending messages first
msgr->sweep_msgs();
// priority path: sparql stage (FIXME: only for SPARQL queries)
SPARQLQuery req;
at_work = sparql->prior_stage.try_pop(req);
if (at_work) {
reset_snooze(at_work, last_time);
sparql->execute_sparql_query(req);
continue; // exhaust all queries
}
// normal path: own runqueue
Bundle bundle;
while (adaptor->tryrecv(bundle)) {
if (bundle.type == SPARQL_QUERY) {
// to be fair, engine will handle sub-queries priority,
// instead of processing a new task.
SPARQLQuery req = bundle.get_sparql_query();
if (req.priority != 0) {
reset_snooze(at_work, last_time);
sparql->execute_sparql_query(req);
break;
}
runqueue.push(req);
} else {
// FIXME: Jump a queue!
reset_snooze(at_work, last_time);
execute(bundle);
break;
}
}
if (!at_work) {
SPARQLQuery req;
if (runqueue.try_pop(req)) {
// process a new SPARQL query
reset_snooze(at_work, last_time);
sparql->execute_sparql_query(req);
}
}
/// do work-obliger
// FIXME: Currently, we only steal SPARQL queries from the neighboring runqueues,
// If we could steal jobs from adaptor, it will significantly improve the effect
// Howeverm, we could not know the type of jobs in advance, and our work-obliger
// mechanism only works well with SPARQL queries.
if (Global::enable_workstealing) {
bool success;
int offset = 1;
int next_engine;
SPARQLQuery req;
do {
success = false;
next_engine = next_to_oblige(own_id, offset);
if (next_engine == -1)
break;
if (engines[next_engine]->at_work
&& ((timer::get_usec() - engines[next_engine]->last_time) >= TIMEOUT_THRESHOLD)
&& (engines[next_engine]->runqueue.try_pop(req))) {
reset_snooze(at_work, last_time);
sparql->execute_sparql_query(req);
success = true;
offset++;
}
} while (success);
}
if (at_work) continue; // keep calm (no snooze)
// busy polling a little while (BUSY_POLLING_THRESHOLD) before snooze
if ((timer::get_usec() - last_time) >= BUSY_POLLING_THRESHOLD) {
timer::cpu_relax(snooze_interval); // relax CPU (snooze)
// double snooze time till MAX_SNOOZE_TIME
snooze_interval *= snooze_interval < MAX_SNOOZE_TIME ? 2 : 1;
}
}
}
};
} // namespace wukong | 32.53617 | 107 | 0.567486 | [
"vector"
] |
09c75ba08483285f6b733ad42ab17313fdc1c489 | 17,146 | cpp | C++ | avs/vis_avs/r_water.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | avs/vis_avs/r_water.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | avs/vis_avs/r_water.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | /*
LICENSE
-------
Copyright 2005 Nullsoft, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Nullsoft nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// alphachannel safe 11/21/99
#include "r_defs.h"
#include "resource.h"
#include <commctrl.h>
#include <windows.h>
#include "timing.h"
#ifndef LASER
#define C_THISCLASS C_WaterClass
#define MOD_NAME "Trans / Water"
class C_THISCLASS : public C_RBASE2 {
protected:
public:
C_THISCLASS();
virtual ~C_THISCLASS();
virtual int render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h);
virtual char* get_desc() { return MOD_NAME; }
virtual HWND conf(HINSTANCE hInstance, HWND hwndParent);
virtual void load_config(unsigned char* data, int len);
virtual int save_config(unsigned char* data);
virtual int smp_getflags() { return 1; }
virtual int smp_begin(int max_threads, char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h);
virtual void smp_render(int this_thread, int max_threads, char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h);
virtual int smp_finish(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h); // return value is that of render() for fbstuff etc
unsigned int* lastframe;
int lastframe_len;
int enabled;
};
#define PUT_INT(y) \
data[pos] = (y)&255; \
data[pos + 1] = (y >> 8) & 255; \
data[pos + 2] = (y >> 16) & 255; \
data[pos + 3] = (y >> 24) & 255
#define GET_INT() (data[pos] | (data[pos + 1] << 8) | (data[pos + 2] << 16) | (data[pos + 3] << 24))
void C_THISCLASS::load_config(unsigned char* data, int len)
{
int pos = 0;
if (len - pos >= 4) {
enabled = GET_INT();
pos += 4;
}
}
int C_THISCLASS::save_config(unsigned char* data)
{
int pos = 0;
PUT_INT(enabled);
pos += 4;
return pos;
}
C_THISCLASS::C_THISCLASS()
{
enabled = 1;
lastframe_len = 0;
lastframe = NULL;
}
C_THISCLASS::~C_THISCLASS()
{
if (lastframe)
GlobalFree(lastframe);
}
#define _R(x) ((x)&0xff)
#define _G(x) (((x)) & 0xff00)
#define _B(x) (((x)) & 0xff0000)
#define _RGB(r, g, b) ((r) | ((g)&0xff00) | ((b)&0xff0000))
static const int zero = 0;
int C_THISCLASS::render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h)
{
smp_begin(1, visdata, isBeat, framebuffer, fbout, w, h);
if (isBeat & 0x80000000)
return 0;
smp_render(0, 1, visdata, isBeat, framebuffer, fbout, w, h);
return smp_finish(visdata, isBeat, framebuffer, fbout, w, h);
}
int C_THISCLASS::smp_begin(int max_threads, char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h)
{
if (!enabled)
return 0;
if (!lastframe || w * h != lastframe_len) {
if (lastframe)
GlobalFree(lastframe);
lastframe_len = w * h;
lastframe = (unsigned int*)GlobalAlloc(GPTR, w * h * sizeof(int));
}
return max_threads;
}
int C_THISCLASS::smp_finish(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h) // return value is that of render() for fbstuff etc
{
return !!enabled;
}
void C_THISCLASS::smp_render(int this_thread, int max_threads, char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h)
{
if (!enabled)
return;
unsigned int* f = (unsigned int*)framebuffer;
unsigned int* of = (unsigned int*)fbout;
unsigned int* lfo = (unsigned int*)lastframe;
int start_l = (this_thread * h) / max_threads;
int end_l;
if (this_thread >= max_threads - 1)
end_l = h;
else
end_l = ((this_thread + 1) * h) / max_threads;
int outh = end_l - start_l;
if (outh < 1)
return;
int skip_pix = start_l * w;
f += skip_pix;
of += skip_pix;
lfo += skip_pix;
int at_top = 0, at_bottom = 0;
if (!this_thread)
at_top = 1;
if (this_thread >= max_threads - 1)
at_bottom = 1;
timingEnter(0);
{
if (at_top)
// top line
{
int x;
// left edge
{
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
f++;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
// middle of line
x = (w - 2);
while (x--) {
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[-1]);
g += _G(f[-1]);
b += _B(f[-1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
f++;
r /= 2;
g /= 2;
b /= 2;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
// right block
{
int r = _R(f[-1]);
int g = _G(f[-1]);
int b = _B(f[-1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
f++;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
}
// middle block
{
int y = outh - at_top - at_bottom;
while (y--) {
int x;
// left edge
{
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r /= 2;
g /= 2;
b /= 2;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
// middle of line
x = (w - 2);
#ifdef NO_MMX
while (x--) {
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[-1]);
g += _G(f[-1]);
b += _B(f[-1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r /= 2;
g /= 2;
b /= 2;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
#else
__asm {
mov esi, f
mov edi, of
mov edx, lfo
mov ecx, x
mov ebx, w
shl ebx, 2
shr ecx, 1
sub esi, ebx
align 16
mmx_water_loop1:
movd mm0, [esi+ebx+4]
movd mm1, [esi+ebx-4]
punpcklbw mm0, [zero]
movd mm2, [esi+ebx*2]
punpcklbw mm1, [zero]
movd mm3, [esi]
punpcklbw mm2, [zero]
movd mm4, [edx]
paddw mm0, mm1
punpcklbw mm3, [zero]
movd mm7, [esi+ebx+8]
punpcklbw mm4, [zero]
paddw mm2, mm3
movd mm6, [esi+ebx]
paddw mm0, mm2
psrlw mm0, 1
punpcklbw mm7, [zero]
movd mm2, [esi+ebx*2+4]
psubw mm0, mm4
movd mm3, [esi+4]
packuswb mm0, mm0
movd [edi], mm0
punpcklbw mm6, [zero]
movd mm4, [edx+4]
punpcklbw mm2, [zero]
paddw mm7, mm6
punpcklbw mm3, [zero]
punpcklbw mm4, [zero]
paddw mm2, mm3
paddw mm7, mm2
add edx, 8
psrlw mm7, 1
add esi, 8
psubw mm7, mm4
packuswb mm7, mm7
movd [edi+4], mm7
add edi, 8
dec ecx
jnz mmx_water_loop1
add esi, ebx
mov f, esi
mov of, edi
mov lfo, edx
}
;
#endif
// right block
{
int r = _R(f[-1]);
int g = _G(f[-1]);
int b = _B(f[-1]);
r += _R(f[w]);
g += _G(f[w]);
b += _B(f[w]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r /= 2;
g /= 2;
b /= 2;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
}
}
// bottom line
if (at_bottom) {
int x;
// left edge
{
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
// middle of line
x = (w - 2);
while (x--) {
int r = _R(f[1]);
int g = _G(f[1]);
int b = _B(f[1]);
r += _R(f[-1]);
g += _G(f[-1]);
b += _B(f[-1]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r /= 2;
g /= 2;
b /= 2;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
// right block
{
int r = _R(f[-1]);
int g = _G(f[-1]);
int b = _B(f[-1]);
r += _R(f[-w]);
g += _G(f[-w]);
b += _B(f[-w]);
f++;
r -= _R(lfo[0]);
g -= _G(lfo[0]);
b -= _B(lfo[0]);
lfo++;
if (r < 0)
r = 0;
else if (r > 255)
r = 255;
if (g < 0)
g = 0;
else if (g > 255 * 256)
g = 255 * 256;
if (b < 0)
b = 0;
else if (b > 255 * 65536)
b = 255 * 65536;
*of++ = _RGB(r, g, b);
}
}
}
memcpy(lastframe + skip_pix, framebuffer + skip_pix, w * outh * sizeof(int));
#ifndef NO_MMX
__asm emms;
#endif
timingLeave(0);
}
C_RBASE* R_Water(char* desc)
{
if (desc) {
strcpy(desc, MOD_NAME);
return NULL;
}
return (C_RBASE*)new C_THISCLASS();
}
static C_THISCLASS* g_this;
static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_INITDIALOG:
if (g_this->enabled)
CheckDlgButton(hwndDlg, IDC_CHECK1, BST_CHECKED);
return 1;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_CHECK1) {
if (IsDlgButtonChecked(hwndDlg, IDC_CHECK1))
g_this->enabled = 1;
else
g_this->enabled = 0;
}
return 0;
}
return 0;
}
HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent)
{
g_this = this;
return CreateDialog(hInstance, MAKEINTRESOURCE(IDD_CFG_WATER), hwndParent, g_DlgProc);
}
#else
C_RBASE* R_Water(char* desc) { return NULL; }
#endif | 27.129747 | 160 | 0.38353 | [
"render"
] |
09cccf8987534982c55b57ecbe7616780889d54a | 2,713 | cpp | C++ | day02/day02.cpp | adrn/advent-of-code | d36c274b5e8ed872ea302113bf8f772b666fb694 | [
"MIT"
] | 2 | 2021-12-01T17:42:56.000Z | 2021-12-02T02:26:26.000Z | day02/day02.cpp | adrn/advent-of-code | d36c274b5e8ed872ea302113bf8f772b666fb694 | [
"MIT"
] | null | null | null | day02/day02.cpp | adrn/advent-of-code | d36c274b5e8ed872ea302113bf8f772b666fb694 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <charconv>
#include <stdexcept>
std::vector<std::string> split(std::string text, char sep) {
std::vector<std::string> tokens = {};
std::string token = "";
for (unsigned int i = 0; i < text.size(); i++) {
if ((char)text.at(i) != sep)
token += text.at(i);
else {
tokens.push_back(token);
token = "";
}
}
if (token.size() != 0)
tokens.push_back(token);
return tokens;
}
std::vector<int> get_move(std::string line) {
std::vector<int> move = {0, 0}; // (horizontal, depth)
auto tokens = split(line, ' ');
int step;
if (tokens.size() != 2)
throw std::runtime_error(
"Invalid command on line: '" + line + "'");
std::from_chars(tokens[1].data(), tokens[1].data() + tokens[1].size(), step);
if (tokens[0] == "forward")
move[0] = step;
else if (tokens[0] == "up")
move[1] = -step;
else if (tokens[0] == "down")
move[1] = step;
return move;
}
void part1(std::vector<std::string> lines) {
std::string line;
std::vector<int> pos = {0, 0}; // (horiztonal, depth)
for (auto line : lines) {
auto move = get_move(line);
pos[0] += move[0];
pos[1] += move[1];
}
std::cout << "Final position: " << pos[0] << ", " << pos[1] << std::endl;
std::cout << "Part 1 answer: " << pos[0] * pos[1] << std::endl;
}
void part2(std::vector<std::string> lines) {
std::string line;
std::vector<int> pos = {0, 0}; // (horiztonal, depth)
int aim = 0;
for (auto line : lines) {
auto raw_move = get_move(line);
if (raw_move[0] != 0) {
pos[0] += raw_move[0];
pos[1] += aim * raw_move[0];
} else if (raw_move[1] != 0)
aim += raw_move[1];
}
std::cout << "Final position: " << pos[0] << ", " << pos[1] << std::endl;
std::cout << "Part 2 answer: " << pos[0] * pos[1] << std::endl;
}
int main(int argc, char** argv) {
if (argc != 2)
throw std::runtime_error(
"Invalid number of command-line arguments: Pass only the path to the data file");
std::string datafile_path(argv[1]);
std::cout << "Loading data file at " << datafile_path << std::endl;
std::ifstream datafile (datafile_path);
std::vector<std::string> lines;
std::string line;
if (datafile.is_open()) {
while(std::getline(datafile, line))
lines.push_back(line);
datafile.close();
} else {
std::cout << "ERROR: failed to open data file" << std::endl;
}
part1(lines);
part2(lines);
}
| 25.35514 | 93 | 0.526723 | [
"vector"
] |
09e09097f0192c0f8665d093006afdc9bd0f0adb | 3,038 | cpp | C++ | test/algorithm/variable_length_encoding.cpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | 37 | 2015-02-22T17:15:44.000Z | 2022-02-24T02:24:41.000Z | test/algorithm/variable_length_encoding.cpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | null | null | null | test/algorithm/variable_length_encoding.cpp | lastfm/libmoost | 895db7cc5468626f520971648741488c373c5cff | [
"MIT"
] | 11 | 2015-02-12T04:35:06.000Z | 2022-01-19T12:46:32.000Z | /* vim:set ts=3 sw=3 sts=3 et: */
/**
* Copyright © 2008-2013 Last.fm Limited
*
* This file is part of libmoost.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <limits>
#include <vector>
#include "../../include/moost/algorithm/variable_length_encoding.hpp"
using namespace moost::algorithm;
BOOST_AUTO_TEST_SUITE( variable_length_encoding_test )
BOOST_AUTO_TEST_CASE( test_in_out )
{
std::vector<char> data;
std::back_insert_iterator< std::vector<char> > data_out(data);
variable_length_encoding::write(123, data_out);
std::vector<char>::iterator it = data.begin();
int i;
variable_length_encoding::read(i, it);
BOOST_CHECK_EQUAL(i, 123);
BOOST_CHECK(it == data.end());
}
BOOST_AUTO_TEST_CASE( test_zero )
{
std::vector<char> data;
std::back_insert_iterator< std::vector<char> > data_out(data);
variable_length_encoding::write(0, data_out);
std::vector<char>::iterator it = data.begin();
int i;
variable_length_encoding::read(i, it);
BOOST_CHECK_EQUAL(i, 0);
BOOST_CHECK(it == data.end());
BOOST_CHECK_EQUAL(data.size(), 1);
}
BOOST_AUTO_TEST_CASE( test_limits_min )
{
std::vector<char> data;
std::back_insert_iterator< std::vector<char> > data_out(data);
variable_length_encoding::write(std::numeric_limits<int>::min(), data_out);
std::vector<char>::iterator it = data.begin();
int i;
variable_length_encoding::read(i, it);
BOOST_CHECK_EQUAL(i, std::numeric_limits<int>::min());
BOOST_CHECK(it == data.end());
}
BOOST_AUTO_TEST_CASE( test_limits_max )
{
std::vector<char> data;
std::back_insert_iterator< std::vector<char> > data_out(data);
variable_length_encoding::write(std::numeric_limits<int>::max(), data_out);
std::vector<char>::iterator it = data.begin();
int i;
variable_length_encoding::read(i, it);
BOOST_CHECK_EQUAL(i, std::numeric_limits<int>::max());
BOOST_CHECK(it == data.end());
}
BOOST_AUTO_TEST_SUITE_END()
| 29.784314 | 77 | 0.731731 | [
"vector"
] |
09e57fe8e0b6187c7da48e9eb6d907a27a0c406d | 10,529 | cpp | C++ | source/xpe/internal.XPressoEffector.cpp | youdiaozi/c4d-nr-toolbox | ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6 | [
"BSD-3-Clause"
] | 16 | 2018-09-12T10:38:26.000Z | 2021-06-28T22:57:30.000Z | source/xpe/internal.XPressoEffector.cpp | youdiaozi/c4d-nr-toolbox | ca6c5f737c901e2f74aeb0bc7aa477387d1a5cd6 | [
"BSD-3-Clause"
] | 10 | 2018-09-11T17:20:09.000Z | 2020-06-02T04:11:01.000Z | source/xpe/internal.XPressoEffector.cpp | NiklasRosenstein/c4d-nr-toolbox | 28197ea7fcf396b5941277b049168d7faf00bfbf | [
"BSD-3-Clause"
] | 6 | 2018-11-30T23:34:49.000Z | 2021-04-02T15:03:23.000Z | /**
* Copyright (C) 2013-2015 Niklas Rosenstein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* TODO: Make Effector dirty when Tag changed.
*/
#include <c4d_graphview.h>
#include <customgui_inexclude.h>
#include <NiklasRosenstein/c4d/cleanup.hpp>
#include "MoDataNode.h"
#include "XPressoEffector.h"
#include "res/description/Oxpressoeffector.h"
#include "res/c4d_symbols.h"
#include "misc/raii.h"
#include "menu.h"
#define XPRESSOEFFECTOR_VERSION 1000
#define XPRESSOEFFECTOR_PRESETNAME "xpe-preset.c4d"
// This points to the preset tag loaded from the preset file. Loaded
// once on request.
static BaseTag* g_preset_tag = nullptr;
static BaseTag* GetPresetTag() {
if (!g_preset_tag) {
Filename filename = GeGetPluginResourcePath() + XPRESSOEFFECTOR_PRESETNAME;
BaseDocument* doc = LoadDocument(filename, SCENEFILTER_OBJECTS, nullptr);
if (!doc) return nullptr;
BaseObject* op = doc->GetFirstObject();
g_preset_tag = (op ? op->GetTag(Texpresso) : nullptr);
if (g_preset_tag) g_preset_tag->Remove();
KillDocument(doc);
}
if (g_preset_tag) return (BaseTag*) g_preset_tag->GetClone(COPYFLAGS_0, nullptr);
else return BaseTag::Alloc(Texpresso);
}
class XPressoEffectorData : public EffectorData {
typedef EffectorData super;
public:
static NodeData* Alloc() { return NewObjClear(XPressoEffectorData); }
XPressoEffectorData() : super(), m_x_dcount(0), m_d_dcount(0) { }
virtual ~XPressoEffectorData() { }
//| EffectorData Overrides
virtual void ModifyPoints(BaseObject* op, BaseObject* gen, BaseDocument* doc,
EffectorDataStruct* data, MoData* md, BaseThread* thread) {
if (!op || !gen || !doc || !md) return;
// Find the MoGraph selection.
GeData ge_selName;
op->GetParameter(ID_MG_BASEEFFECTOR_SELECTION, ge_selName, DESCFLAGS_GET_0);
String selName = ge_selName.GetString();
BaseSelect* sel = nullptr;
for (BaseTag* tag=gen->GetTag(Tmgselection); tag; tag=tag->GetNext()) {
if (tag->IsInstanceOf(Tmgselection) && tag->GetName() == selName) {
GetMGSelectionMessage data;
if (tag->Message(MSG_GET_MODATASELECTION, &data)) {
sel = data.sel;
}
break;
}
}
m_execInfo.md = md;
m_execInfo.gen = gen;
m_execInfo.falloff = GetFalloff();
m_execInfo.sel = sel;
if (m_execInfo.falloff && !m_execInfo.falloff->InitFalloff(nullptr, doc, op)) {
m_execInfo.falloff = nullptr;
}
if (m_execInfo.falloff) m_execInfo.falloff->SetMg(op->GetMg());
Bool easyOn = false;
m_execInfo.easyOn = &easyOn;
iferr (m_execInfo.easyValues = NewMemClear(Vector, md->GetCount()))
;
if (!m_execInfo.easyValues) {
GePrint(String(__FUNCTION__) + ": Failed to create easy values array.");
}
// Invoke all XPresso Tags.
for (BaseTag* tag=op->GetFirstTag(); tag; tag=tag->GetNext()) {
if (tag->IsInstanceOf(Texpresso)) {
GvNodeMaster* master = ((XPressoTag*) tag)->GetNodeMaster();
if (master) master->Execute(thread);
}
}
if (easyOn && m_execInfo.easyValues) {
super::ModifyPoints(op, gen, doc, data, md, thread);
}
if (m_execInfo.easyValues) DeleteMem(m_execInfo.easyValues);
m_execInfo.Clean();
}
virtual void CalcPointValue(BaseObject* op, BaseObject* gen, BaseDocument* doc,
EffectorDataStruct* data, Int32 index, MoData* md, const Vector& globalpos,
Float falloff_weight) {
if (!m_execInfo.easyValues) {
return;
}
// Set everything to the calculated interpolation values.
Vector* buf = (Vector*) data->strengths;
for (Int32 i=0; i < BLEND_COUNT / 3; i++, buf++) {
*buf = m_execInfo.easyValues[index];
}
}
virtual Int32 GetEffectorFlags() {
BaseObject* op = static_cast<BaseObject*>(Get());
if (!op) return 0;
BaseContainer* bc = op->GetDataInstance();
if (!bc) return 0;
Int32 flags = EFFECTORFLAGS_HASFALLOFF;
if (bc->GetBool(XPRESSOEFFECTOR_TIMEDEPENDENT)) {
flags |= EFFECTORFLAGS_TIMEDEPENDENT | EFFECTORFLAGS_CAMERADEPENDENT;
}
return flags;
}
//| ObjectData Overrides
virtual EXECUTIONRESULT Execute(BaseObject* op, BaseDocument* doc, BaseThread* bt,
Int32 priority, EXECUTIONFLAGS flags) {
if (!_UpdateDependencies(op, doc)) return EXECUTIONRESULT_USERBREAK;
return super::Execute(op, doc, bt, priority, flags);
}
//| NodeData Overrides
virtual Bool Init(GeListNode* node) {
if (!super::Init(node) || !node) return false;
BaseContainer* bc = static_cast<BaseObject*>(node)->GetDataInstance();
if (!bc) return false;
bc->SetBool(XPRESSOEFFECTOR_TIMEDEPENDENT, false);
bc->SetData(XPRESSOEFFECTOR_DEPENDENCIES, GeData(CUSTOMDATATYPE_INEXCLUDE_LIST, DEFAULTVALUE));
return true;
}
virtual Bool Message(GeListNode* node, Int32 type, void* pData) {
if (!node) return false;
// Calculate the dirty-count of all XPresso tags on the object.
Int32 dcnt = _CountXPressoTagsDirty(static_cast<BaseObject*>(node));
// If the calculated dirty-count differs from the stored count,
// we will mark the effector object as dirty.
if (dcnt != m_x_dcount) {
node->SetDirty(DIRTYFLAGS_DATA);
m_x_dcount = dcnt;
}
switch (type) {
/**
* Sent to retrieve the *MoData* stored in the effector. This
* is only true when called from within the `ExecuteEffector()`
* pipeline.
*/
case MSG_XPRESSOEFFECTOR_GETEXECINFO: {
if (pData) {
*((XPressoEffector_ExecInfo*) pData) = m_execInfo;
}
return pData != nullptr;
}
/**
* Open the XPresso Editor on a double click for the *first* XPresso
* tag found in the objects' tag list.
*/
case MSG_EDIT: {
BaseTag* tag = node ? ((BaseObject*) node)->GetTag(Texpresso) : nullptr;
GvWorld* world = GvGetWorld();
if (tag && world) {
return world->OpenDialog(Texpresso, ((XPressoTag*) tag)->GetNodeMaster());
}
break;
}
/**
* Add an XPresso Tag when the effector is inserted into the document.
*/
case MSG_MENUPREPARE: {
if (node) {
BaseTag* tag = GetPresetTag();
if (tag) ((BaseObject*) node)->InsertTag(tag);
}
break;
}
default:
break;
}
return super::Message(node, type, pData);
}
private:
Bool _UpdateDependencies(BaseObject* op, BaseDocument* doc) {
if (!op) return false;
// This variable will hold the current dirty-count.
Int32 dcount = 0;
// Compute the dirty-count of the objects in the dependency
// field.
BaseContainer* bc = op->GetDataInstance();
if (bc) {
// Retrieve the InExclude list from the object.
const InExcludeData* list = static_cast<const InExcludeData*>(
bc->GetCustomDataType(XPRESSOEFFECTOR_DEPENDENCIES, CUSTOMDATATYPE_INEXCLUDE_LIST)
);
// And compute the dirty-count of all of these.
if (list) {
Int32 count = list->GetObjectCount();
for (Int32 i=0; i < count; i++) {
BaseList2D* obj = list->ObjectFromIndex(doc, i);
if (obj) {
dcount += obj->GetDirty(DIRTYFLAGS_DATA);
}
}
}
}
// Add the dirty-count of all XPresso Tags.
dcount += _CountXPressoTagsDirty(op);
// Compare the dirty-counts.
if (dcount != m_d_dcount) {
op->SetDirty(DIRTYFLAGS_DATA);
m_d_dcount = dcount;
}
return true;
}
virtual Int32 _CountXPressoTagsDirty(BaseObject* op, DIRTYFLAGS flags=DIRTYFLAGS_ALL, HDIRTYFLAGS hflags=HDIRTYFLAGS_ALL) {
Int32 dcnt = 0;
// Iterate over all tags.
for (BaseTag* tag=op->GetFirstTag(); tag; tag=tag->GetNext()) {
// Filter XPresso Tags.
if (tag->IsInstanceOf(Texpresso)) {
dcnt += tag->GetDirty(flags) + tag->GetHDirty(hflags);
GvNodeMaster* master = static_cast<XPressoTag*>(tag)->GetNodeMaster();
if (master) dcnt += master->GetDirty(flags) + master->GetHDirty(hflags);;
}
}
return dcnt;
}
/**
* Contains execution information. Only valid from a call-stack level
* below `ModifyPoints()`.
*/
XPressoEffector_ExecInfo m_execInfo;
/**
* Keeps track of the dirty-count of all XPresso tags of the effector.
*/
Int32 m_x_dcount;
/**
* Keeps track of the dirty-count of all dependencies.
*/
Int32 m_d_dcount;
};
Bool RegisterXPressoEffector() {
menu::root().AddPlugin(IDS_MENU_EFFECTORS, ID_XPRESSOEFFECTOR);
niklasrosenstein::c4d::cleanup([] {
BaseTag::Free(g_preset_tag);
});
return RegisterEffectorPlugin(
ID_XPRESSOEFFECTOR,
GeLoadString(IDC_XPRESSOEFFECTOR_NAME),
OBJECT_MODIFIER | PLUGINFLAG_HIDEPLUGINMENU | OBJECT_CALL_ADDEXECUTION,
XPressoEffectorData::Alloc,
"Oxpressoeffector"_s,
raii::AutoBitmap("icons/Oxpressoeffector.tif"_s),
XPRESSOEFFECTOR_VERSION);
}
| 34.074434 | 127 | 0.596638 | [
"object",
"vector"
] |
09e6ef5881e42a6c8a93213356f81c33fd149dd9 | 72,568 | cpp | C++ | MaxCommon/hoa.process_tilde.cpp | CICM/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 71 | 2015-02-23T12:24:05.000Z | 2022-02-15T00:18:30.000Z | MaxCommon/hoa.process_tilde.cpp | pb5/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 13 | 2015-04-22T17:13:53.000Z | 2020-11-12T10:54:29.000Z | MaxCommon/hoa.process_tilde.cpp | pb5/HoaLibrary-Max | cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 8 | 2015-04-11T21:34:51.000Z | 2020-02-29T14:37:53.000Z | /*
// Copyright (c) 2012-2015 Eliott Paris, Julien Colafrancesco & Pierre Guillot, CICM, Universite Paris 8.
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*/
// based on dynamicdsp~ Copyright 2010 Alex Harker. All rights reserved.
/**
@file hoa.process~.cpp
@name hoa.process~
@realname hoa.process~
@type object
@module hoa
@author Julien Colafrancesco, Pierre Guillot, Eliott Paris.
@digest
patcher loader for multichannel processing.
@description
<o>hoa.process~</o> helps the modularization of patches for ambisonic or plane waves processing. <o>hoa.process~</o> is a kind of <o>poly~</o> object particulary suitable for multichannel ambisonic or plane wave processing. Create a patch/effect/operator, then parallelize it with the <o>hoa.process~</o>
@discussion
<o>hoa.process~</o> helps the modularization of patches for ambisonic or plane waves processing. <o>hoa.process~</o> is a kind of <o>poly~</o> object particulary suitable for multichannel ambisonic or plane wave processing. Create a patch/effect/operator, then parallelize it with the <o>hoa.process~</o>
@category 2d, 3d, Process, Utility, Ambisonics, Planewaves, Patching, MSP
@seealso hoa.in~, hoa.in, hoa.out, hoa.out~, hoa.thisprocess~, poly~, patcher
*/
#include "HoaCommon.max.h"
#include "HoaProcessSuite.h"
t_class *hoa_processor_class;
#define MAX_NUM_PATCHES 4096
#define MAX_ARGS 50
////////////////////////////// Structure for patch and related data //////////////////////////////
typedef struct _patchspace
{
t_patcher* the_patch;
struct _dspchain* the_dspchain;
t_symbol* patch_name_in;
char patch_name[256];
short patch_path;
short x_argc; // Arguments (stored in case of reload / update)
t_atom x_argv[MAX_ARGS];
double** out_ptrs; // Pointer to Audio Out Buffers
char patch_valid;
char patch_on;
} t_patchspace;
////////////////////////////////////// ins/outs ////////////////////////////////////////////////
typedef void *t_outvoid;
typedef struct _inout
{
t_object s_obj;
long s_index;
void* s_outlet;
} t_inout;
typedef struct _io_infos
{
long sig_ins;
long sig_outs;
long ins;
long outs;
long sig_ins_maxindex;
long sig_outs_maxindex;
long ins_maxindex;
long outs_maxindex;
long extra_sig_ins;
long extra_sig_outs;
long extra_ins;
long extra_outs;
long extra_sig_ins_maxindex;
long extra_sig_outs_maxindex;
long extra_ins_maxindex;
long extra_outs_maxindex;
} t_io_infos;
////////////////////////////////////// The hoa_processor structure //////////////////////////////////////
typedef struct _hoa_processor
{
t_pxobject x_obj;
t_patcher *parent_patch;
// Patch Data and Variables
t_patchspace *patch_space_ptrs[MAX_NUM_PATCHES];
long patch_spaces_allocated;
t_int32_atomic patch_is_loading;
long target_index;
long last_vec_size;
long last_samp_rate;
// IO Variables
long mode_default_numins;
long mode_default_numouts;
long instance_sig_ins;
long instance_sig_outs;
long instance_ins;
long instance_outs;
long extra_sig_ins;
long extra_sig_outs;
long extra_ins;
long extra_outs;
long declared_sig_ins;
long declared_sig_outs;
long declared_ins;
long declared_outs;
void **sig_ins;
void **sig_outs;
t_outvoid *in_table; // table of non-signal inlets
t_outvoid *out_table; // table of non-signal outlets
long num_proxies; // number of proxies
// Hoa stuff
Processor<Hoa2d, t_sample>::Harmonics* f_ambi2D;
Processor<Hoa3d, t_sample>::Harmonics* f_ambi3D;
ulong f_order;
t_symbol* f_mode;
e_hoa_object_type f_object_type;
} t_hoa_processor;
void *hoa_processor_new(t_symbol *s, short argc, t_atom *argv);
void hoa_processor_free(t_hoa_processor *x);
t_symbol* get_extra_comment(t_patcher* p, int extra_index, t_symbol* object_class);
void hoa_processor_assist(t_hoa_processor *x, void *b, long m, long a, char *s);
void hoa_processor_loadexit(t_hoa_processor *x, long replace_symbol_pointers, void *previous, void *previousindex);
t_hoa_err hoa_processor_loadpatch(t_hoa_processor *x, long index, t_symbol *patch_name_in, short argc, t_atom *argv);
void hoa_processor_bang(t_hoa_processor *x);
void hoa_processor_int(t_hoa_processor *x, long n);
void hoa_processor_float(t_hoa_processor *x, double f);
void hoa_processor_list(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv);
void hoa_processor_anything(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv);
void hoa_processor_target(t_hoa_processor *x, long target_index, long index, t_symbol *msg, short argc, t_atom *argv);
short hoa_processor_targetinlets(t_patcher *p, t_args_struct *args);
void hoa_processor_user_target(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv);
void hoa_processor_user_mute(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv);
void hoa_processor_mutemap(t_hoa_processor *x, long n);
short hoa_processor_send_mutechange(t_patcher *p, t_args_struct *args);
void hoa_processor_dsp64(t_hoa_processor *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags);
void hoa_processor_dsp_internal (t_patchspace *patch_space_ptrs, long vec_size, long samp_rate);
void hoa_processor_perform64(t_hoa_processor *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vec_size, long flags, void *userparam);
short hoa_processor_linkinlets(t_patcher *p, t_hoa_processor *x);
short hoa_processor_unlinkinlets(t_patcher *p, t_hoa_processor *x);
void hoa_processor_init_io_infos(t_io_infos* io_infos);
short hoa_processor_get_patch_io_context(t_patcher *p, t_io_infos* io_infos);
t_hoa_err hoa_processor_get_patch_filename_io_context(t_hoa_processor *x, t_symbol *patch_name_in, t_io_infos* io_infos);
void hoa_processor_dblclick(t_hoa_processor *x);
void hoa_processor_open(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv);
void hoa_processor_doopen(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv);
void hoa_processor_wclose(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv);
void hoa_processor_dowclose(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv);
short hoa_processor_patcher_descend(t_patcher *p, t_intmethod fn, void *arg, t_hoa_processor *x);
short hoa_processor_setsubassoc(t_patcher *p, t_hoa_processor *x);
void hoa_processor_pupdate(t_hoa_processor *x, void *b, t_patcher *p);
void *hoa_processor_subpatcher(t_hoa_processor *x, long index, void *arg);
void hoa_processor_parentpatcher(t_hoa_processor *x, t_patcher **parent);
void hoa_processor_init_patch_space (t_patchspace *patch_space_ptrs);
t_patchspace *hoa_processor_new_patch_space(t_hoa_processor *x,long index);
void hoa_processor_free_patch_and_dsp (t_hoa_processor *x, t_patchspace *patch_space_ptrs);
void *hoa_processor_query_declared_sigins(t_hoa_processor *x);
void *hoa_processor_query_declared_sigouts(t_hoa_processor *x);
void *hoa_processor_query_sigins(t_hoa_processor *x);
void *hoa_processor_query_outptrs_ptr(t_hoa_processor *x, long index);
void *hoa_processor_client_get_patch_on (t_hoa_processor *x, long index);
void hoa_processor_client_set_patch_on (t_hoa_processor *x, long index, long state);
void *hoa_processor_query_ambisonic_order(t_hoa_processor *x);
void *hoa_processor_query_mode(t_hoa_processor *x);
void *hoa_processor_query_is_2D(t_hoa_processor *x);
void *hoa_processor_query_number_of_instances(t_hoa_processor *x);
t_hoa_err hoa_processor_query_patcherargs(t_hoa_processor *x, long index, long *argc, t_atom **argv);
void hoa_processor_output_typed_message(void* outletptr, t_args_struct *args);
void* hoa_processor_query_io_index(t_hoa_processor *x, long patchIndex, t_object* io);
void hoa_processor_out_message(t_hoa_processor *x, t_args_struct *args);
t_hoa_err hoa_getinfos(t_hoa_processor* x, t_hoa_boxinfos* boxinfos);
// ========================================================================================================================================== //
// Main
// ========================================================================================================================================== //
#ifdef HOA_PACKED_LIB
int hoa_process_main(void)
#else
void ext_main(void *r)
#endif
{
t_class* c;
c = class_new("hoa.process~", (method)hoa_processor_new, (method)hoa_processor_free, sizeof(t_hoa_processor), NULL, A_GIMME, 0);
class_setname((char *)"hoa.process~", (char *)"hoa.process~");
class_setname((char *)"hoa.2d.process~", (char *)"hoa.process~");
class_setname((char *)"hoa.3d.process~", (char *)"hoa.process~");
hoa_initclass(c, (method)hoa_getinfos);
// @method signal @digest output signal in the corresponding <o>hoa.in~</o> object in the loaded patch.
// @description Output signal in the corresponding <o>hoa.in~</o> object in the loaded patches.
class_addmethod(c, (method)hoa_processor_dsp64, "dsp64", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_assist, "assist", A_CANT, 0);
// @method open @digest open a patcher instance for viewing.
// @description The word open, followed by a number, opens the specified instance of the patcher (depending on the process mode). You can view the activity of any instance of the patcher up to the number of loaded instances. With no arguments, the open message opens the instance that is currently the target (see the <m>target</m> message).
// @marg 0 @name instance-index @optional 1 @type int
class_addmethod(c, (method)hoa_processor_open, "open", A_GIMME, 0);
// @method wclose @digest close a numbered patcher instance's window.
// @description Closes the window for the numbered instance specified by the argument (depending on the process mode).
// @marg 0 @name instance-index @optional 1 @type int
class_addmethod(c, (method)hoa_processor_wclose, "wclose", A_GIMME, 0);
// @method (mouse) @digest double-click to open a display window to view loaded patch contents.
// @description Double-clicking on the <o>hoa.process~</o> opens a display window of the instance that is currently the target.
class_addmethod(c, (method)hoa_processor_dblclick, "dblclick", A_CANT, 0);
// @method target @digest target messages to a specific loaded instance.
// @description The hoa.process~ instance that will receive subsequent messages
// (other than messages specifically used by the hoa.process~ object itself) arriving at the hoa.process~ object's inlets.
// Targeted messages only works for <o>hoa.in</o> objects that have an <b>extra</b> attribute set.
// The target numbering/arguments depends on the current mode and the number of loaded instances.
// <ul>
// <li> In <m>planewaves</m> mode (2d/3d), the message <b>target 1</b> will target the first instance corresponding to the first channel.</li>
// <li> In 2d <m>harmonics</m> mode, target argument correspond to the harmonic index, the harmonics index go to <b>-order</b> to <b>order</b>.</li>
// <li> In 3d <m>harmonics</m> mode, the <m>target</m> message takes two arguments. First one is the ambisonic hdegree (between 0 and the <b>order</b>), the second one correspond to the harmonic index (from <b>-order</b> to <b>order</b>).</li>
// </ul>
// The message <b>target all</b> will target messages to all of the loaded instances.
// The message <b>target none</b> disable input to all instances.
// @marg 0 @name instance-index @optional 0 @type int/symbol
// @marg 1 @name instance-index-bis @optional 1 @type int
class_addmethod(c, (method)hoa_processor_user_target, "target", A_GIMME, 0);
// @method bang @digest Send a <m>bang</m> message to the patcher loaded into the <o>hoa.process~</o> object.
// @description Sends a <m>bang</m> to the patcher loaded into the <o>hoa.process~</o> object. The result of the message is determined by the loaded patcher.
class_addmethod(c, (method)hoa_processor_bang, "bang", 0);
// @method int @digest Send a <m>int</m> message to the patcher loaded into the <o>hoa.process~</o> object.
// @description Sends a <m>int</m> to the patcher loaded into the <o>hoa.process~</o> object. The result of the message is determined by the loaded patcher.
// @marg 0 @name number @optional 0 @type int
class_addmethod(c, (method)hoa_processor_int, "int", A_LONG, 0);
// @method float @digest Send a <m>float</m> message to the patcher loaded into the <o>hoa.process~</o> object.
// @description Sends a <m>float</m> to the patcher loaded into the <o>hoa.process~</o> object. The result of the message is determined by the loaded patcher.
// @marg 0 @name number @optional 0 @type float
class_addmethod(c, (method)hoa_processor_float, "float", A_FLOAT, 0);
// @method list @digest Send a <m>list</m> message to the patcher loaded into the <o>hoa.process~</o> object.
// @description Sends a <m>float</m> to the patcher loaded into the <o>hoa.process~</o> object. The result of the message is determined by the loaded patcher.
// @marg 0 @name message @optional 0 @type list
class_addmethod(c, (method)hoa_processor_list, "list", A_GIMME, 0);
// @method anything @digest Send a message to the patcher loaded into the <o>hoa.process~</o> object.
// @description Sends a message to the patcher loaded into the <o>hoa.process~</o> object. The result of the message is determined by the loaded patcher.
// @marg 0 @name message @optional 0 @type list
class_addmethod(c, (method)hoa_processor_anything, "anything", A_GIMME, 0);
// @method mute @digest Mute processing for a patcher instance.
// @description Turns off signal processing for the specified instance of a patcher loaded by the <o>hoa.process~</o> object and sends a bang message to the <o>hoa.thisprocess~</o> object for the specified instance.
// Mute target numbering works like <m>target</m> method (see the <m>target</m> message).
// Sending a 0 as the last argument turns the patcher instance on. The message mute all 1 mutes all instances, and mute all 0 turns on signal processing for all instances of the patcher.
// @marg 0 @name instance-index @optional 0 @type int
// @marg 1 @name on/off-flag @optional 0 @type int
class_addmethod(c, (method)hoa_processor_user_mute, "mute", A_GIMME, 0);
// @method mutemap @digest Report mutes out of a specified <o>hoa.process~</o> message outlet.
// @description Report voice mutes out of a specified <o>hoa.process~</o> message outlet
// @marg 0 @name outlet-number @optional 0 @type int
class_addmethod(c, (method)hoa_processor_mutemap, "mutemap", A_LONG, 0);
class_addmethod(c, (method)hoa_processor_pupdate, "pupdate", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_subpatcher, "subpatcher", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_parentpatcher, "parentpatcher", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_mode, "get_mode", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_is_2D, "is_2D", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_patcherargs, "get_patcherargs", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_number_of_instances, "get_number_of_instance", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_ambisonic_order, "get_ambisonic_order", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_declared_sigins, "get_declared_sigins", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_declared_sigouts, "get_declared_sigouts", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_sigins, "get_sigins", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_query_outptrs_ptr, "get_outptrs_ptr", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_client_get_patch_on, "get_patch_on", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_client_set_patch_on, "set_patch_on", A_CANT, 0);
class_addmethod(c, (method)hoa_processor_out_message, "out_message", A_CANT, 0); // receive a message from a hoa.out object
class_addmethod(c, (method)hoa_processor_query_io_index, "get_io_index", A_CANT, 0);
class_dspinit(c);
class_register(CLASS_BOX, c);
class_alias(c, gensym("hoa.2d.process~"));
class_alias(c, gensym("hoa.3d.process~"));
hoa_processor_class = c;
}
// ========================================================================================================================================== //
// Object Creation / Freeing / Assisstance
// ========================================================================================================================================== //
void *hoa_processor_new(t_symbol *s, short argc, t_atom *argv)
{
// @arg 0 @name decomposition-order/number-of-channels @optional 0 @type int @digest the ambisonic order or the number of channels.
// @description First argument is the ambisonic order or the number of channels depending on the third argument (process mode : harmonics/planewaves).
// In planewaves mode (2d/3d) the number of instances will be equal to the number of channel specified by this argument.
// In harmonics mode, the number of instances will be equal to the number of harmonics depending on the order of decomposition.
// In 2d it will be equal to (decomposition-order*2 + 1), in 2d to ((decomposition-order+1)*(decomposition-order+1))
// @arg 1 @name patcher-name @optional 0 @type symbol @digest Name of a patcher to be loaded.
// @description The second argument must specify the name of a patcher to be loaded which already exists and is in the Max search path.
// @arg 2 @name process-mode @optional 0 @type symbol @digest process mode.
// @description can be <b>harmonics</b>/<b>planewaves</b>. Use the <b>harmonics</b> mode to work in the Ambisonics domain, <b>planewaves</b> if your process is in the planewave domain.
// @arg 3 @name list-of-argument-values @optional 1 @type float/int/symbol @digest argument to send to the loaded patches.
// @description Argument to be sent to the loaded patches. These arguments can be retrieve by (#1, #2... patcher system) or/and with the help of the <o>hoa.thisprocess~</o> object.
// @arg 4 @name attribute-keys-and-list-of-argument-values @optional 1 @type float/int/symbol @digest attributes to send to the loaded patches.
// @description Attributes to be sent to the loaded patches. These arguments can be retrieve with the help of the <o>hoa.thisprocess~</o> object.
t_hoa_processor *x = (t_hoa_processor*)object_alloc(hoa_processor_class);
t_symbol *patch_name_entered = NULL;
t_symbol *tempsym;
long i;
int first_int = 1;
x->f_mode = hoa_sym_harmonics;
short ac = 0;
t_atom av[MAX_ARGS];
long number_of_instances_to_load = 0;
x->patch_spaces_allocated = 0;
x->target_index = 0;
x->last_vec_size = 64;
x->last_samp_rate = 44100;
x->in_table = x->out_table = 0;
x->patch_is_loading = 0;
x->declared_sig_ins = x->declared_ins = x->instance_ins = x->instance_sig_ins = x->extra_ins = x->extra_sig_ins = x->mode_default_numins = 0;
x->declared_sig_outs = x->declared_outs = x->instance_outs = x->instance_sig_outs = x->extra_outs = x->extra_sig_outs = x->mode_default_numouts = 0;
// check 2D or 3D context
x->f_object_type = HOA_OBJECT_2D;
if (s == gensym("hoa.3d.process~"))
x->f_object_type = HOA_OBJECT_3D;
/*
else if (s == gensym("hoa.plug~"))
object_error((t_object*)x, "hoa.plug~ is deprecated please take a look at the hoa.process~ object");
*/
// Check the order or the number of instances :
if (argc && atom_gettype(argv) == A_LONG)
{
first_int = atom_getlong(argv);
argc--; argv++;
}
// Check if there is a patch name given to load
if (argc && atom_gettype(argv) == A_SYM)
{
patch_name_entered = atom_getsym(argv);
argc--; argv++;
}
// Check the mode
if (argc && atom_gettype(argv) == A_SYM)
{
tempsym = atom_getsym(argv);
if (tempsym == hoa_sym_planewaves || tempsym == hoa_sym_harmonics)
{
x->f_mode = tempsym;
argc--; argv++;
}
}
// Get arguments to patch that is being loaded if there are any
if (argc)
{
ac = argc;
if (ac > MAX_ARGS)
ac = MAX_ARGS;
for (i = 0; i < ac; i++, argv++)
av[i] = *argv;
ac = i;
}
x->f_order = first_int;
x->f_ambi2D = new Processor<Hoa2d, t_sample>::Harmonics(x->f_order);
x->f_ambi3D = new Processor<Hoa3d, t_sample>::Harmonics(x->f_order);
// Initialise patcher symbol
object_obex_lookup(x, hoa_sym_pound_P, &x->parent_patch); // store reference to parent patcher
// load a single instance to query io informations
t_io_infos io_infos;
t_hoa_err loaded_patch_err = hoa_processor_get_patch_filename_io_context(x, patch_name_entered, &io_infos);
if (loaded_patch_err != HOA_ERR_NONE)
return x;
// default io config depends on object type (2d/3d) and mode :
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
x->mode_default_numins = x->mode_default_numouts = x->f_ambi2D->getNumberOfHarmonics();
else if (x->f_object_type == HOA_OBJECT_3D)
x->mode_default_numins = x->mode_default_numouts = x->f_ambi3D->getNumberOfHarmonics();
}
else if (x->f_mode == hoa_sym_planewaves)
{
x->mode_default_numins = x->mode_default_numouts = first_int;
}
// Set object io depending on contextual io of the current patcher
if (io_infos.sig_ins > 0)
x->instance_sig_ins = x->declared_sig_ins = x->mode_default_numins;
if (io_infos.sig_outs > 0)
x->instance_sig_outs = x->declared_sig_outs = x->mode_default_numouts;
if (io_infos.ins > 0)
x->instance_ins = x->declared_ins = x->mode_default_numins;
if (io_infos.outs > 0)
x->instance_outs = x->declared_outs = x->mode_default_numouts;
// --- add extra ins and outs (if necessary)
x->extra_sig_ins = io_infos.extra_sig_ins_maxindex;
x->extra_sig_outs = io_infos.extra_sig_outs_maxindex;
x->extra_ins = io_infos.extra_ins_maxindex;
x->extra_outs = io_infos.extra_outs_maxindex;
x->declared_sig_ins += x->extra_sig_ins;
x->declared_sig_outs += x->extra_sig_outs;
x->declared_ins += x->extra_ins;
x->declared_outs += x->extra_outs;
// --- Create signal in/out buffers and zero
x->num_proxies = max(x->instance_sig_ins, x->instance_ins) + max(x->extra_sig_ins, x->extra_ins);
x->declared_sig_ins = x->declared_ins = x->num_proxies;
x->sig_ins = (void **) malloc(x->declared_sig_ins * sizeof(void *));
x->sig_outs = (void **) malloc(x->declared_sig_outs * sizeof(void *));
for (i = 0; i < x->declared_sig_ins; i++)
x->sig_ins[i] = 0;
for (i = 0; i < x->declared_sig_outs; i++)
x->sig_outs[i] = 0;
// io schema :
// ins : instance in (mixed sig/ctrl) -- extra (mixed sig/ctrl)
// outs : instance sig outs -- extra sig -- instance ctrl outs -- extra ctrl
// Make non-signal inlets
if (x->declared_ins)
{
x->in_table = (t_outvoid *)t_getbytes(x->declared_ins * sizeof(t_outvoid));
for (i = 0; i < x->declared_ins; i++)
x->in_table[i] = outlet_new(0L, 0L); // make generic unowned inlets
}
// Make signal ins
dsp_setup((t_pxobject *) x, x->num_proxies);
x->x_obj.z_misc = Z_NO_INPLACE; // due to output zeroing!!
// Make non-signal instance and extra outlets
if (x->declared_outs)
{
x->out_table = (t_outvoid *) t_getbytes(x->declared_outs * sizeof(t_outvoid));
// non-signal extra outlets
if (x->extra_outs)
for (i = x->declared_outs - 1; i >= (x->declared_outs - x->extra_outs); i--)
x->out_table[i] = outlet_new((t_object *)x, 0);
// non-signal instance outlets
for (i = x->declared_outs - x->extra_outs - 1; i >= 0; i--)
x->out_table[i] = outlet_new((t_object *)x, 0);
}
// Make signal extra outlets
for (i = 0; i < x->declared_sig_outs; i++)
outlet_new((t_object *)x, "signal");
// Load patches and initialise all instances
if (patch_name_entered && loaded_patch_err == HOA_ERR_NONE)
{
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
number_of_instances_to_load = x->f_ambi2D->getNumberOfHarmonics();
else if (x->f_object_type == HOA_OBJECT_3D)
number_of_instances_to_load = x->f_ambi3D->getNumberOfHarmonics();
}
else if (x->f_mode == hoa_sym_planewaves)
{
number_of_instances_to_load = first_int;
}
for (i = 0; i < number_of_instances_to_load; i++)
{
hoa_processor_loadpatch(x, i, patch_name_entered, ac, av);
}
}
return (x);
}
t_hoa_err hoa_getinfos(t_hoa_processor* x, t_hoa_boxinfos* boxinfos)
{
boxinfos->object_type = x->f_object_type;
if (x->f_mode == hoa_sym_harmonics)
{
boxinfos->autoconnect_inputs = (long) max(x->instance_sig_ins, x->instance_ins);
boxinfos->autoconnect_outputs = (long) max(x->instance_sig_outs, x->instance_outs);
boxinfos->autoconnect_inputs_type = boxinfos->autoconnect_inputs ? HOA_CONNECT_TYPE_AMBISONICS : HOA_CONNECT_TYPE_STANDARD;
boxinfos->autoconnect_outputs_type = boxinfos->autoconnect_outputs ? HOA_CONNECT_TYPE_AMBISONICS : HOA_CONNECT_TYPE_STANDARD;
}
else if (x->f_mode == hoa_sym_planewaves)
{
boxinfos->autoconnect_inputs = (long) max(x->instance_sig_ins, x->instance_ins);
boxinfos->autoconnect_outputs = (long) max(x->instance_sig_outs, x->instance_outs);
boxinfos->autoconnect_inputs_type = boxinfos->autoconnect_inputs ? HOA_CONNECT_TYPE_PLANEWAVES : HOA_CONNECT_TYPE_STANDARD;
boxinfos->autoconnect_outputs_type = boxinfos->autoconnect_outputs ? HOA_CONNECT_TYPE_PLANEWAVES : HOA_CONNECT_TYPE_STANDARD;
}
return HOA_ERR_NONE;
}
void hoa_processor_free(t_hoa_processor *x)
{
t_patchspace *patch_space_ptr;
long i;
dsp_free((t_pxobject *)x);
// Free patches
for (i = 0; i < x->patch_spaces_allocated; i++)
{
patch_space_ptr = x->patch_space_ptrs[i];
hoa_processor_free_patch_and_dsp (x, patch_space_ptr);
if (patch_space_ptr)
freebytes((char *) patch_space_ptr, sizeof(t_patchspace));
}
if (x->declared_sig_ins)
free(x->sig_ins);
if (x->declared_sig_outs)
free(x->sig_outs);
for (i = 0; i < x->declared_ins; i++)
object_free((t_object*)x->in_table[i]);
if (x->in_table)
freebytes(x->in_table, x->declared_ins * sizeof(t_outvoid));
if (x->out_table)
freebytes(x->out_table, x->declared_outs * sizeof(t_outvoid));
delete x->f_ambi2D;
delete x->f_ambi3D;
}
t_symbol* get_extra_comment(t_patcher* p, int extra_index, t_symbol* object_class)
{
t_box *b;
t_object *io;
t_symbol* comment = hoa_sym_nothing;
int extra_index_exist = 0;
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (jbox_get_maxclass(b) == object_class)
{
io = jbox_get_object(b);
if (extra_index == object_attr_getlong(io, hoa_sym_extra))
{
extra_index_exist = 1;
comment = object_attr_getsym(io, hoa_sym_comment);
if (comment != hoa_sym_nothing)
break;
}
}
}
if (!extra_index_exist)
comment = gensym("does nothing");
return comment;
}
void hoa_processor_assist(t_hoa_processor *x, void *b, long m, long a, char *s)
{
long inlet = a + 1;
int extra_index = 0;
int is_extra_sig, is_extra_ctrl, is_instance_sig, is_instance_ctrl;
char sig_basis_text[50];
char ctrl_basis_text[50];
t_symbol* sig_extra_comment = hoa_sym_nothing;
t_symbol* ctrl_extra_comment = hoa_sym_nothing;
is_extra_sig = is_extra_ctrl = is_instance_sig = is_instance_ctrl = 0;
// check if "a" match an extra io + check if io is sig or/and ctrl
if ( m == ASSIST_INLET && (x->extra_ins || x->extra_sig_ins))
{
int max_instance = max(x->instance_ins, x->instance_sig_ins);
if (inlet > max_instance)
{
extra_index = inlet - max_instance;
if (inlet <= max_instance + x->extra_ins)
{
is_extra_ctrl = 1;
sprintf(ctrl_basis_text,"Extra %i", extra_index);
}
if (inlet <= max_instance + x->extra_sig_ins)
{
is_extra_sig = 1;
sprintf(sig_basis_text,"Extra %i", extra_index);
}
}
}
else if ( m == ASSIST_OUTLET && (x->extra_outs || x->extra_sig_outs))
{
if (inlet > x->instance_sig_outs && inlet <= x->declared_sig_outs)
{
is_extra_sig = 1;
extra_index = inlet - x->instance_sig_outs;
sprintf(sig_basis_text,"Extra %i", extra_index);
}
if ( inlet > x->declared_sig_outs + x->instance_outs)
{
is_extra_ctrl = 1;
extra_index = inlet - (x->declared_sig_outs + x->instance_outs);
sprintf(ctrl_basis_text,"Extra %i", extra_index);
}
}
// check if "a" match an instance io + check if io is sig or/and ctrl
if (!is_extra_ctrl || !is_extra_sig)
{
// instance in
if ( m == ASSIST_INLET && !is_extra_ctrl && (inlet <= x->instance_ins))
{
is_instance_ctrl = 1;
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
sprintf(ctrl_basis_text,"%s", x->f_ambi2D->getHarmonicName( a ).c_str());
else if (x->f_object_type == HOA_OBJECT_3D)
sprintf(ctrl_basis_text,"%s", x->f_ambi3D->getHarmonicName( a ).c_str());
}
else
{
sprintf(ctrl_basis_text,"Channel %ld", inlet);
}
}
// instance out
if ( m == ASSIST_OUTLET && !is_extra_ctrl && (inlet > x->declared_sig_outs))
{
is_instance_ctrl = 1;
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
sprintf(ctrl_basis_text,"%s", x->f_ambi2D->getHarmonicName( a - x->declared_sig_outs ).c_str());
else if (x->f_object_type == HOA_OBJECT_3D)
sprintf(ctrl_basis_text,"%s", x->f_ambi3D->getHarmonicName( a - x->declared_sig_outs ).c_str());
}
else
{
sprintf(ctrl_basis_text,"Channel %ld", inlet - x->declared_sig_outs);
}
}
// instance sig in
if ( m == ASSIST_INLET && !is_extra_sig && (inlet <= x->instance_sig_ins))
{
is_instance_sig = 1;
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
sprintf(sig_basis_text,"%s", x->f_ambi2D->getHarmonicName( a ).c_str());
else if (x->f_object_type == HOA_OBJECT_3D)
sprintf(sig_basis_text,"%s", x->f_ambi3D->getHarmonicName( a ).c_str());
}
else
{
sprintf(sig_basis_text,"Channel %ld", inlet);
}
}
// instance sig out
if ( m == ASSIST_OUTLET && !is_extra_sig && (inlet <= x->instance_sig_outs))
{
is_instance_sig = 1;
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
sprintf(sig_basis_text,"%s", x->f_ambi2D->getHarmonicName( a ).c_str());
else if (x->f_object_type == HOA_OBJECT_3D)
sprintf(sig_basis_text,"%s", x->f_ambi3D->getHarmonicName( a ).c_str());
}
else
{
sprintf(sig_basis_text,"Channel %ld", inlet);
}
}
}
// check if there is an extra comment
if (is_extra_ctrl)
{
ctrl_extra_comment = get_extra_comment(x->patch_space_ptrs[0]->the_patch, extra_index, (m == ASSIST_INLET) ? hoa_sym_in : hoa_sym_out);
// if extra doesn't match explicitly an inlet/outlet in the patch
if (ctrl_extra_comment == gensym("does nothing"))
is_extra_ctrl = 0;
}
if (is_extra_sig)
{
sig_extra_comment = get_extra_comment(x->patch_space_ptrs[0]->the_patch, extra_index, (m == ASSIST_INLET) ? hoa_sym_sigin : hoa_sym_sigout);
// if extra doesn't match explicitly an inlet/outlet in the patch
if (sig_extra_comment == gensym("does nothing"))
is_extra_sig = 0;
}
// enough, it's time to construct our assist string !
if ( (is_instance_sig && is_instance_ctrl) || (is_extra_sig && is_extra_ctrl) )
{
if (sig_extra_comment == hoa_sym_nothing && ctrl_extra_comment == hoa_sym_nothing)
sprintf(s,"(signal, messages) %s", sig_basis_text);
else if (sig_extra_comment == ctrl_extra_comment)
sprintf(s,"(signal, messages) %s : %s", sig_basis_text, sig_extra_comment->s_name);
else if (sig_extra_comment != hoa_sym_nothing && ctrl_extra_comment != hoa_sym_nothing)
sprintf(s,"(signal) %s : %s, (messages) %s : %s", sig_basis_text, sig_extra_comment->s_name, ctrl_basis_text, ctrl_extra_comment->s_name);
else if (sig_extra_comment != hoa_sym_nothing && ctrl_extra_comment == hoa_sym_nothing)
sprintf(s,"(signal) %s : %s, (messages) %s", sig_basis_text, sig_extra_comment->s_name, ctrl_basis_text);
else if (sig_extra_comment == hoa_sym_nothing && ctrl_extra_comment != hoa_sym_nothing)
sprintf(s,"(signal) %s, (messages) %s : %s", sig_basis_text, ctrl_basis_text, ctrl_extra_comment->s_name);
}
else if ( (is_instance_sig || is_extra_sig) && (!is_instance_ctrl && !is_extra_ctrl))
{
if (sig_extra_comment == hoa_sym_nothing)
sprintf(s,"(signal) %s", sig_basis_text);
else
sprintf(s,"%s", sig_extra_comment->s_name);
}
else if ( (is_instance_ctrl || is_extra_ctrl) && (!is_instance_sig && !is_extra_sig))
{
if (ctrl_extra_comment == hoa_sym_nothing)
sprintf(s,"(messages) %s", ctrl_basis_text);
else
sprintf(s,"%s", ctrl_extra_comment->s_name);
}
else
{
sprintf(s,"nothing here !");
}
/*
post("inlet %ld : instance_sig = %ld, instance_ctrl = %ld, extra_sig = %ld, extra_ctrl = %ld", inlet, is_instance_sig, is_instance_ctrl, is_extra_sig, is_extra_ctrl);
*/
}
// ========================================================================================================================================== //
// Patcher Loading / Deleting
// ========================================================================================================================================== //
void hoa_processor_loadexit(t_hoa_processor *x, long replace_symbol_pointers, void *previous, void *previousindex)
{
if (replace_symbol_pointers)
{
hoa_sym_HoaProcessor->s_thing = (struct object*)previous;
hoa_sym_HoaProcessorPatchIndex->s_thing = (struct object*)previousindex;
}
ATOMIC_DECREMENT_BARRIER(&x->patch_is_loading);
}
t_hoa_err hoa_processor_loadpatch(t_hoa_processor *x, long index, t_symbol *patch_name_in, short argc, t_atom *argv)
{
t_patchspace *patch_space_ptr = 0;
t_object *previous;
t_object *previousindex;
t_fourcc type;
t_fourcc filetypelist = 'JSON';
long patch_spaces_allocated = x->patch_spaces_allocated;
long harmonic_hdegree, harmonic_argument;
long i;
short patch_path;
short saveloadupdate;
char filename[MAX_FILENAME_CHARS];
char windowname[280];
t_patcher *p;
// Check that this object is not loading in another thread
if (ATOMIC_INCREMENT_BARRIER(&x->patch_is_loading) > 1)
{
object_error((t_object*)x, "patch is loading in another thread");
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FAIL;
}
// Find a free patch if no index is given
if (index < 0)
{
for (index = 0; index < patch_spaces_allocated; index++)
if (x->patch_space_ptrs[index]->the_patch == 0)
break;
}
// Check that the index is valid
if (index >= MAX_NUM_PATCHES)
{
object_error((t_object*)x, "max number of patcher loaded exceeded");
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FAIL;
}
// Create patchspaces up until the last allocated index (if necessary) and store the pointer
for (i = patch_spaces_allocated; i < index + 1; i++)
hoa_processor_new_patch_space (x, i);
patch_space_ptr = x->patch_space_ptrs[index];
// Free the old patch - the new patch is not yet valid, but we switch it on so it can be switched off at loadbang time
patch_space_ptr->patch_valid = 0;
hoa_processor_free_patch_and_dsp(x, patch_space_ptr);
hoa_processor_init_patch_space(patch_space_ptr);
patch_space_ptr->patch_on = 1;
// Bind to the loading symbols and store the old symbols
previous = hoa_sym_HoaProcessor->s_thing;
previousindex = hoa_sym_HoaProcessorPatchIndex->s_thing;
hoa_sym_HoaProcessor->s_thing = (t_object *) x;
hoa_sym_HoaProcessorPatchIndex->s_thing = (t_object *) (index + 1);
// Try to locate a file of the given name that is of the correct type
strncpy_zero(filename, patch_name_in->s_name, MAX_FILENAME_CHARS);
// if filetype does not exists
if (locatefile_extended(filename, &patch_path, &type, &filetypelist, 1))
{
object_error((t_object*)x, "patcher \"%s\" not found !", filename);
hoa_processor_loadexit(x, 1, previous, previousindex);
return HOA_ERR_FILE_NOT_FOUND;
}
// Check the number of rarguments (only up to 16 allowed right now)
if (argc > MAX_ARGS)
argc = MAX_ARGS;
// Load the patch (don't interrupt dsp)
saveloadupdate = dsp_setloadupdate(false);
p = (t_patcher*) intload(filename, patch_path, 0 , argc, argv, false);
dsp_setloadupdate(saveloadupdate);
// Check something has loaded
if (!p)
{
object_error((t_object*)x, "error loading %s", filename);
hoa_processor_loadexit(x, 1, previous, previousindex);
return HOA_ERR_FAIL;
}
// Check that it is a patcher that has loaded
if (!ispatcher((t_object*)p))
{
object_error((t_object*)x, "%s is not a patcher file", filename);
object_free((t_object *)p);
hoa_processor_loadexit(x, 1, previous, previousindex);
return HOA_ERR_FAIL;
}
// Change the window name to : "patchname [hdegree arg]" (if mode no or post)
if (x->f_mode == hoa_sym_harmonics)
{
if (x->f_object_type == HOA_OBJECT_2D)
{
harmonic_argument = x->f_ambi2D->getHarmonicOrder(index);
sprintf(windowname, "%s [%ld]", patch_name_in->s_name, harmonic_argument);
}
else if (x->f_object_type == HOA_OBJECT_3D)
{
harmonic_hdegree = x->f_ambi3D->getHarmonicDegree(index);
harmonic_argument = x->f_ambi3D->getHarmonicOrder(index);
sprintf(windowname, "%s [%ld %ld]", patch_name_in->s_name, harmonic_hdegree, harmonic_argument);
}
}
else
{
sprintf(windowname, "%s (%ld)", patch_name_in->s_name, index+1);
}
jpatcher_set_title(p, gensym(windowname));
// Set the relevant associations
hoa_processor_patcher_descend((t_patcher *)p, (t_intmethod) hoa_processor_setsubassoc, x, x);
// Link inlets and outlets
if (x->declared_ins)
hoa_processor_patcher_descend((t_patcher *)p, (t_intmethod) hoa_processor_linkinlets, x, x);
// Copy all the relevant data into the patch space
patch_space_ptr->the_patch = (t_patcher*)p;
patch_space_ptr->patch_name_in = patch_name_in;
strcpy(patch_space_ptr->patch_name, filename);
patch_space_ptr->patch_path = patch_path;
patch_space_ptr->x_argc = argc;
for (i = 0; i < argc; i++)
patch_space_ptr->x_argv[i] = argv[i];
// Compile the dspchain in case dsp is on
hoa_processor_dsp_internal (patch_space_ptr, x->last_vec_size, x->last_samp_rate);
// The patch is valid and ready to go
patch_space_ptr->patch_valid = 1;
// Return to previous state
hoa_processor_loadexit(x, 1, previous, previousindex);
//object_method(patch_space_ptr->the_patch, gensym("loadbang")); // useless (intload() func do it for us)
return HOA_ERR_NONE;
}
// ========================================================================================================================================== //
// Messages in passed on to the patcher via the "in" objects / Voice targeting
// ========================================================================================================================================== //
void hoa_processor_bang(t_hoa_processor *x)
{
long index = proxy_getinlet((t_object *)x);
long target_index = x->target_index;
if (index >= x->declared_ins || target_index == -1)
return;
if (target_index)
{
hoa_processor_target(x, target_index, index, hoa_sym_bang, 0, 0);
//post("hoa_processor_target target_index = %ld", target_index);
}
else
{
outlet_bang(x->in_table[index]);
//post("outlet_bang");
}
}
void hoa_processor_int(t_hoa_processor *x, long n)
{
long index = proxy_getinlet((t_object *)x); // proxy index
long target_index = x->target_index;
if (index >= x->declared_ins || target_index == -1)
return;
if (target_index)
{
t_atom n_atom;
atom_setlong (&n_atom, n);
hoa_processor_target(x, target_index, index, hoa_sym_int, 1, &n_atom);
}
else
outlet_int(x->in_table[index], n);
}
void hoa_processor_float(t_hoa_processor *x, double f)
{
long index = proxy_getinlet((t_object *)x); // proxy index
long target_index = x->target_index;
if (index >= x->declared_ins || target_index == -1)
return;
if (target_index)
{
t_atom f_atom;
atom_setfloat(&f_atom, f);
hoa_processor_target(x, target_index, index, hoa_sym_float, 1, &f_atom);
}
else
outlet_float(x->in_table[index], f);
}
void hoa_processor_list(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv)
{
long index = proxy_getinlet((t_object *)x); // proxy index
long target_index = x->target_index;
if (index >= x->declared_ins || target_index == -1)
return;
if (target_index)
hoa_processor_target(x, target_index, index, hoa_sym_list, argc, argv);
else
outlet_list(x->in_table[index], hoa_sym_list, argc, argv);
}
void hoa_processor_anything(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv)
{
long index = proxy_getinlet((t_object *)x); // proxy index
long target_index = x->target_index;
if (index >= x->declared_ins || target_index == -1)
return;
if (target_index)
hoa_processor_target(x, target_index, index, s, argc, argv);
else
outlet_anything(x->in_table[index], s, argc, argv);
}
void hoa_processor_target(t_hoa_processor *x, long target_index, long index, t_symbol *msg, short argc, t_atom *argv)
{
t_args_struct pass_args;
pass_args.msg = msg;
pass_args.argc = argc;
pass_args.argv = argv;
pass_args.index = index + 1;
if (target_index >= 1 && target_index <= x->patch_spaces_allocated)
{
t_patcher *p = x->patch_space_ptrs[target_index - 1]->the_patch;
if (x->patch_space_ptrs[target_index - 1]->patch_valid)
hoa_processor_patcher_descend(p, (t_intmethod) hoa_processor_targetinlets, &pass_args, x);
}
}
// - inlet and outlet linking using the in and out objects
short hoa_processor_targetinlets(t_patcher *p, t_args_struct *args)
{
t_box *b;
t_inout *io;
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (jbox_get_maxclass(b) == hoa_sym_in)
{
io = (t_inout *) jbox_get_object(b);
if (io->s_index == args->index)
hoa_processor_output_typed_message(io->s_obj.o_outlet, args);
}
}
return (0);
}
void hoa_processor_user_target(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv)
{
x->target_index = -1;
if (argc && argv)
{
if (atom_gettype(argv) == A_SYM && atom_getsym(argv) == gensym("all"))
{
x->target_index = 0;
}
else if (atom_gettype(argv) == A_SYM && atom_getsym(argv) == gensym("none"))
{
x->target_index = -1;
}
else if (atom_gettype(argv) == A_LONG)
{
if (x->f_mode == hoa_sym_harmonics)
{
long harm_degree, harm_order = 0;
if (x->f_object_type == HOA_OBJECT_2D)
{
harm_order = atom_getlong(argv);
if (abs(harm_order) <= x->f_ambi2D->getDecompositionOrder())
x->target_index = x->f_ambi2D->getHarmonicIndex(0, harm_order) + 1;
// bad target target none
if (x->target_index <= 0 || x->target_index > x->patch_spaces_allocated)
{
object_warn((t_object *)x, "target [%ld] doesn't match any patcher instance", harm_order);
x->target_index = -1;
}
}
else if (x->f_object_type == HOA_OBJECT_3D)
{
harm_degree = atom_getlong(argv);
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
harm_order = atom_getlong(argv+1);
if (harm_degree <= x->f_ambi3D->getDecompositionOrder() && abs(harm_order) <= harm_degree)
x->target_index = x->f_ambi3D->getHarmonicIndex(harm_degree, harm_order) + 1;
// bad target target none
if (x->target_index <= 0 || x->target_index > x->patch_spaces_allocated)
{
object_warn((t_object *)x, "target [%ld, %ld] doesn't match any patcher instance", harm_degree, harm_order);
x->target_index = -1;
}
}
}
else if (x->f_mode == hoa_sym_planewaves)
{
x->target_index = atom_getlong(argv);
// bad target target none
if (x->target_index <= 0 || x->target_index > x->patch_spaces_allocated)
{
object_warn((t_object *)x, "target (%ld) doesn't match any patcher instance", x->target_index);
x->target_index = -1;
}
}
}
}
}
void hoa_processor_user_mute(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv)
{
int state = 0;
int index = -1;
if (argc && argv)
{
if (atom_gettype(argv) == A_SYM && atom_getsym(argv) == gensym("all"))
{
index = 0;
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
state = atom_getlong(argv+1) != 0;
}
else if (atom_gettype(argv) == A_LONG)
{
if (x->f_mode == hoa_sym_harmonics)
{
long harm_degree, harm_order = 0;
if (x->f_object_type == HOA_OBJECT_2D)
{
harm_order = atom_getlong(argv);
if (abs(harm_order) <= x->f_ambi2D->getDecompositionOrder())
index = x->f_ambi2D->getHarmonicIndex(0, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "mute [%ld] doesn't match any patcher instance", harm_order);
index = -1;
}
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
state = atom_getlong(argv+1) != 0;
}
else if (x->f_object_type == HOA_OBJECT_3D)
{
harm_degree = Math<long>::clip(atom_getlong(argv), 0, x->f_ambi3D->getDecompositionOrder());
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
harm_order = atom_getlong(argv+1);
if (harm_degree <= x->f_ambi3D->getDecompositionOrder() && abs(harm_order) <= harm_degree)
index = x->f_ambi3D->getHarmonicIndex(harm_degree, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "target [%ld, %ld] doesn't match any patcher instance", harm_degree, harm_order);
index = -1;
}
if (argc > 2 && atom_gettype(argv+2) == A_LONG)
state = atom_getlong(argv+2) != 0;
}
}
else if (x->f_mode == hoa_sym_planewaves)
{
index = atom_getlong(argv);
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_warn((t_object *)x, "mute (%ld) doesn't match any patcher instance", x->target_index);
index = -1;
}
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
state = atom_getlong(argv+1) != 0;
}
}
}
// mute patch(es) and send bang to hoa.thisprocess~ object(s)
if (index == 0)
{
for (int i=0; i < x->patch_spaces_allocated; i++)
{
hoa_processor_client_set_patch_on(x, i+1, !state);
hoa_processor_patcher_descend(x->patch_space_ptrs[i]->the_patch, (t_intmethod)hoa_processor_send_mutechange, x, x);
}
}
else if (index > 0 && index <= x->patch_spaces_allocated)
{
hoa_processor_client_set_patch_on(x, index, !state);
hoa_processor_patcher_descend(x->patch_space_ptrs[index-1]->the_patch, (t_intmethod)hoa_processor_send_mutechange, x, x);
}
}
// - send a "mutechange" message to all hoa.thisprocess~ objects in the patch
short hoa_processor_send_mutechange(t_patcher *p, t_args_struct *args)
{
t_box *b;
t_object* thisprocess;
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (jbox_get_maxclass(b) == gensym("hoa.thisprocess~"))
{
thisprocess = (t_object *) jbox_get_object(b);
object_method(thisprocess, gensym("mutechange"));
}
}
return (0);
}
// report muted instance info as a list in a specied message outlet
void hoa_processor_mutemap(t_hoa_processor *x, long n)
{
int outlet_index = n;
if (outlet_index < 1 || outlet_index > x->declared_outs) return;
//t_atom list[x->patch_spaces_allocated];
t_atom *list = NULL;
list = (t_atom *)sysmem_newptr(sizeof(x->patch_spaces_allocated));
for (int i=0; i<x->patch_spaces_allocated; i++)
atom_setlong(list+i, !x->patch_space_ptrs[i]->patch_on);
outlet_list(x->out_table[outlet_index-1], NULL, x->patch_spaces_allocated, list);
}
void hoa_processor_out_message(t_hoa_processor *x, t_args_struct *args)
{
long index = args->index;
if (args->index > 0 && args->index <= x->declared_outs)
hoa_processor_output_typed_message(x->out_table[index-1], args);
}
void hoa_processor_output_typed_message(void* outletptr, t_args_struct *args)
{
if (outletptr)
{
if (args->msg == hoa_sym_bang)
outlet_bang(outletptr);
else if (args->msg == hoa_sym_int)
outlet_int(outletptr, atom_getlong(args->argv));
else if (args->msg == hoa_sym_float)
outlet_float(outletptr, atom_getfloat(args->argv));
else if (args->msg == hoa_sym_list)
outlet_list(outletptr, 0L, args->argc, args->argv);
else
outlet_anything (outletptr, args->msg, args->argc, args->argv);
}
}
// ========================================================================================================================================== //
// Perform and DSP Routines
// ========================================================================================================================================== //
void hoa_processor_perform64 (t_hoa_processor *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vec_size, long flags, void *userparam)
{
for (int i = 0; i < x->declared_sig_ins; i++)
x->sig_ins[i] = ins[i];
// Zero Outputs
for (int i = 0; i < x->declared_sig_outs; i++)
memset(outs[i], 0, sizeof(double) * vec_size);
if (x->x_obj.z_disabled)
return;
t_patchspace **patch_space_ptrs = x->patch_space_ptrs;
t_patchspace *next_patch_space_ptr = 0;
t_dspchain *next_dspchain = 0;
long patch_spaces_allocated = x->patch_spaces_allocated;
long index = 0;
for (int i = 0; i < patch_spaces_allocated; i++)
{
if (++index >= patch_spaces_allocated)
index -= patch_spaces_allocated;
next_patch_space_ptr = patch_space_ptrs[index];
next_dspchain = next_patch_space_ptr->the_dspchain;
if (next_patch_space_ptr->patch_valid && next_patch_space_ptr->patch_on && next_dspchain)
{
next_patch_space_ptr->out_ptrs = outs;
dspchain_tick(next_dspchain);
}
}
}
void hoa_processor_dsp64 (t_hoa_processor *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags)
{
t_patchspace *patch_space_ptr;
// Do internal dsp compile (for each valid patch)
for (int i = 0; i < x->patch_spaces_allocated; i++)
{
patch_space_ptr = x->patch_space_ptrs[i];
if (patch_space_ptr->patch_valid)
{
hoa_processor_dsp_internal(patch_space_ptr, maxvectorsize, (long)samplerate);
}
}
x->last_vec_size = maxvectorsize;
x->last_samp_rate = (long)samplerate;
object_method(dsp64, gensym("dsp_add64"), x, hoa_processor_perform64, 0, NULL);
}
void hoa_processor_dsp_internal (t_patchspace *patch_space_ptr, long vec_size, long samp_rate)
{
// Free the old dspchain
if (patch_space_ptr->the_dspchain)
object_free((t_object *)patch_space_ptr->the_dspchain);
// Recompile
patch_space_ptr->the_dspchain = dspchain_compile(patch_space_ptr->the_patch, vec_size, samp_rate);
}
// ========================================================================================================================================== //
// Patcher Link Inlets / Outlets
// ========================================================================================================================================== //
void hoa_processor_init_io_infos(t_io_infos* io_infos)
{
io_infos->sig_ins = 0;
io_infos->sig_outs = 0;
io_infos->ins = 0;
io_infos->outs = 0;
io_infos->sig_ins_maxindex = 0;
io_infos->sig_outs_maxindex = 0;
io_infos->ins_maxindex = 0;
io_infos->outs_maxindex = 0;
io_infos->extra_sig_ins = 0;
io_infos->extra_sig_outs = 0;
io_infos->extra_ins = 0;
io_infos->extra_outs = 0;
io_infos->extra_sig_ins_maxindex = 0;
io_infos->extra_sig_outs_maxindex = 0;
io_infos->extra_ins_maxindex = 0;
io_infos->extra_outs_maxindex = 0;
}
t_hoa_err hoa_processor_get_patch_filename_io_context(t_hoa_processor *x, t_symbol *patch_name_in, t_io_infos* io_infos)
{
t_fourcc type;
t_fourcc filetypelist = 'JSON';
short patch_path;
char filename[MAX_FILENAME_CHARS];
t_patcher *p;
hoa_processor_init_io_infos(io_infos);
if (!patch_name_in)
{
//object_warn((t_object*)x, "no patch name entered");
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FILE_NOT_FOUND;
}
// Check that this object is not loading in another thread
if (ATOMIC_INCREMENT_BARRIER(&x->patch_is_loading) > 1)
{
object_error((t_object*)x, "patch is loading in another thread");
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FAIL;
}
// Try to locate a file of the given name that is of the correct type
strncpy_zero(filename, patch_name_in->s_name, MAX_FILENAME_CHARS);
// if filetype does not exists
if (locatefile_extended(filename, &patch_path, &type, &filetypelist, 1))
{
object_error((t_object*)x, "patcher \"%s\" not found !", filename);
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FILE_NOT_FOUND;
}
// Load the patch
p = (t_patcher*) intload(filename, patch_path, 0, 0, NULL, false);
// Check something has loaded
if (!p)
{
object_error((t_object*)x, "error loading %s", filename);
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FAIL;
}
// Check that it is a patcher that has loaded
if (!ispatcher((t_object*)p))
{
object_error((t_object*)x, "%s is not a patcher file", filename);
object_free((t_object *)p);
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_FAIL;
}
// no error, so we can check our IO context
hoa_processor_get_patch_io_context(p, io_infos);
object_free((t_object *)p);
hoa_processor_loadexit(x, 0, 0, 0);
return HOA_ERR_NONE;
}
short hoa_processor_get_patch_io_context(t_patcher *p, t_io_infos* io_infos)
{
t_box *b;
t_object *io;
t_symbol* objclassname;
long extra;
hoa_processor_init_io_infos(io_infos);
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
objclassname = jbox_get_maxclass(b);
if (objclassname == hoa_sym_sigin || objclassname == hoa_sym_in ||
objclassname == hoa_sym_sigout || objclassname == hoa_sym_out)
{
extra = 0;
io = jbox_get_object(b);
extra = object_attr_getlong(io, hoa_sym_extra);
if (objclassname == hoa_sym_sigin)
{
if (extra > 0) io_infos->extra_sig_ins++;
else io_infos->sig_ins++;
io_infos->extra_sig_ins_maxindex = max(extra, io_infos->extra_sig_ins_maxindex);
}
else if (objclassname == hoa_sym_in)
{
if (extra > 0) io_infos->extra_ins++;
else io_infos->ins++;
io_infos->extra_ins_maxindex = max(extra, io_infos->extra_ins_maxindex);
}
else if (objclassname == hoa_sym_sigout)
{
if (extra > 0) io_infos->extra_sig_outs++;
else io_infos->sig_outs++;
io_infos->extra_sig_outs_maxindex = max(extra, io_infos->extra_sig_outs_maxindex);
}
else if (objclassname == hoa_sym_out)
{
if (extra > 0) io_infos->extra_outs++;
else io_infos->outs++;
io_infos->extra_outs_maxindex = max(extra, io_infos->extra_outs_maxindex);
}
}
}
return 0;
}
// - inlet linking and removal using hoa.in object
short hoa_processor_linkinlets(t_patcher *p, t_hoa_processor *x)
{
t_box *b;
t_inout *io;
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (jbox_get_maxclass(b) == hoa_sym_in)
{
io = (t_inout *) jbox_get_object(b);
if (io->s_index <= x->declared_ins)
outlet_add(x->in_table[io->s_index - 1], (struct inlet *)io->s_obj.o_outlet);
}
}
return 0;
}
short hoa_processor_unlinkinlets(t_patcher *p, t_hoa_processor *x)
{
t_box *b;
t_inout *io;
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (jbox_get_maxclass(b) == hoa_sym_in)
{
io = (t_inout *) jbox_get_object(b);
if (io->s_index <= x->declared_ins)
{
outlet_rm(x->in_table[io->s_index - 1], (struct inlet *)io->s_obj.o_outlet);
}
}
}
return (0);
}
// ========================================================================================================================================== //
// Patcher Window stuff
// ========================================================================================================================================== //
void hoa_processor_dblclick(t_hoa_processor *x)
{
for (int i = 0; i < x->patch_spaces_allocated; i++)
{
if (x->patch_space_ptrs[i]->the_patch)
{
// open the current target instance
hoa_processor_open(x, NULL, 0, NULL);
break;
}
}
}
void hoa_processor_open(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv)
{
long index = 0;
t_atom a;
if (argc && argv && atom_gettype(argv) == A_LONG)
{
if (x->f_mode == hoa_sym_harmonics)
{
long harm_degree, harm_order = 0;
if (x->f_object_type == HOA_OBJECT_2D)
{
harm_order = atom_getlong(argv);
if (abs(harm_order) <= x->f_ambi2D->getDecompositionOrder())
index = x->f_ambi2D->getHarmonicIndex(0, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "open [%ld] doesn't match any patcher instance", harm_order);
index = -1;
}
}
else if (x->f_object_type == HOA_OBJECT_3D)
{
harm_degree = atom_getlong(argv);
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
harm_order = atom_getlong(argv+1);
if (harm_degree <= x->f_ambi3D->getDecompositionOrder() && abs(harm_order) <= harm_degree)
index = x->f_ambi3D->getHarmonicIndex(harm_degree, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "open [%ld, %ld] doesn't match any patcher instance", harm_degree, harm_order);
index = -1;
}
}
}
else if (x->f_mode == hoa_sym_planewaves)
{
index = atom_getlong(argv);
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "no patcher instance (%ld)", index);
index = -1;
}
}
}
else
{
index = max<long>(x->target_index, 1);
}
atom_setlong (&a, index - 1);
if (index < 1 || index > x->patch_spaces_allocated) return;
if (!x->patch_space_ptrs[index - 1]->patch_valid) return;
defer(x,(method)hoa_processor_doopen, 0L, 1, &a);
}
void hoa_processor_doopen(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv)
{
long index = atom_getlong(argv);
if (x->patch_space_ptrs[index]->the_patch)
mess0((t_object *)x->patch_space_ptrs[index]->the_patch, hoa_sym_front); // this will always do the right thing
}
void hoa_processor_wclose(t_hoa_processor *x, t_symbol *msg, short argc, t_atom *argv)
{
long index = 0;
t_atom a;
if (argc && argv && atom_gettype(argv) == A_LONG)
{
if (x->f_mode == hoa_sym_harmonics)
{
long harm_degree, harm_order = 0;
if (x->f_object_type == HOA_OBJECT_2D)
{
harm_order = atom_getlong(argv);
if (abs(harm_order) <= x->f_ambi2D->getDecompositionOrder())
index = x->f_ambi2D->getHarmonicIndex(0, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "wclose [%ld] doesn't match any patcher instance", harm_order);
index = -1;
}
}
else if (x->f_object_type == HOA_OBJECT_3D)
{
harm_degree = atom_getlong(argv);
if (argc > 1 && atom_gettype(argv+1) == A_LONG)
harm_order = atom_getlong(argv+1);
if (harm_degree <= x->f_ambi3D->getDecompositionOrder() && abs(harm_order) <= harm_degree)
index = x->f_ambi3D->getHarmonicIndex(harm_degree, harm_order) + 1;
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "wclose [%ld, %ld] doesn't match any patcher instance", harm_degree, harm_order);
index = -1;
}
}
}
else if (x->f_mode == hoa_sym_planewaves)
{
index = atom_getlong(argv);
// bad target target none
if (index <= 0 || index > x->patch_spaces_allocated)
{
object_error((t_object *)x, "no patcher instance (%ld)", index);
index = -1;
}
}
}
else if (argc && argv && atom_gettype(argv) == A_SYM && atom_getsym(argv) == gensym("all"))
{
for (int i = 0; i < x->patch_spaces_allocated; i++)
{
atom_setlong (&a, i);
defer(x,(method)hoa_processor_dowclose, 0L, 1, &a);
}
return;
}
if (index < 1 || index > x->patch_spaces_allocated) return;
if (!x->patch_space_ptrs[index - 1]->patch_valid) return;
atom_setlong (&a, index - 1);
defer(x,(method)hoa_processor_dowclose, 0L, 1, &a);
}
void hoa_processor_dowclose(t_hoa_processor *x, t_symbol *s, short argc, t_atom *argv)
{
long index = atom_getlong(argv);
if (index < 0) return;
if (index >= x->patch_spaces_allocated) return;
if (!x->patch_space_ptrs[index]->patch_valid) return;
if (x->patch_space_ptrs[index]->the_patch)
object_method(x->patch_space_ptrs[index]->the_patch, gensym("wclose"), x);
}
// ========================================================================================================================================== //
// Patcher Utilities (these deal with various updating and necessary behind the scens state stuff)
// ========================================================================================================================================== //
short hoa_processor_patcher_descend(t_patcher *p, t_intmethod fn, void *arg, t_hoa_processor *x)
{
t_box *b;
t_patcher *p2;
long index;
t_object *assoc = NULL;
object_method(p, hoa_sym_getassoc, &assoc); // Avoid recursion into a poly / pfft / hoa.process~
if (assoc && (t_hoa_processor *) assoc != x)
return 0;
// CHANGED - DO NOT PASS x AS ARG
if ((*fn)(p, arg))
return (1);
for (b = jpatcher_get_firstobject(p); b; b = jbox_get_nextobject(b))
{
if (b)
{
index = 0;
while ((p2 = (t_patcher*)object_subpatcher(jbox_get_object(b), &index, arg)))
if (hoa_processor_patcher_descend(p2, fn, arg, x))
return 1;
}
}
return (0);
}
short hoa_processor_setsubassoc(t_patcher *p, t_hoa_processor *x)
{
t_object *assoc;
object_method(p, hoa_sym_getassoc, &assoc);
if (!assoc)
object_method(p, hoa_sym_setassoc, x);
object_method(p, hoa_sym_noedit, 1);
return 0;
}
void hoa_processor_pupdate(t_hoa_processor *x, void *b, t_patcher *p)
{
t_patchspace *patch_space_ptr;
// Reload the patcher when it's updated
for (int i = 0; i < x->patch_spaces_allocated; i++)
{
patch_space_ptr = x->patch_space_ptrs[i];
if (patch_space_ptr->the_patch == p)
hoa_processor_loadpatch(x, i, patch_space_ptr->patch_name_in, patch_space_ptr->x_argc, patch_space_ptr->x_argv);
}
}
void *hoa_processor_subpatcher(t_hoa_processor *x, long index, void *arg)
{
if (arg && (long) arg != 1)
if (!OB_INVALID(arg)) // arg might be good but not a valid object pointer
if (object_classname(arg) == hoa_sym_dspchain) // don't report subpatchers to dspchain
return 0;
if (index < x->patch_spaces_allocated)
if (x->patch_space_ptrs[index]->patch_valid) return x->patch_space_ptrs[index]->the_patch; // the indexed patcher
return 0;
}
void hoa_processor_parentpatcher(t_hoa_processor *x, t_patcher **parent)
{
*parent = x->parent_patch;
}
// ========================================================================================================================================== //
// Patchspace Utilities
// ========================================================================================================================================== //
// Make a new patchspace
t_patchspace *hoa_processor_new_patch_space (t_hoa_processor *x,long index)
{
t_patchspace *patch_space_ptr;
x->patch_space_ptrs[index] = patch_space_ptr = (t_patchspace *)t_getbytes(sizeof(t_patchspace));
hoa_processor_init_patch_space (patch_space_ptr);
x->patch_spaces_allocated++;
return patch_space_ptr;
}
// Initialise a patchspace
void hoa_processor_init_patch_space (t_patchspace *patch_space_ptr)
{
patch_space_ptr->the_patch = 0;
patch_space_ptr->patch_name_in = 0;
patch_space_ptr->patch_path = 0;
patch_space_ptr->patch_valid = 0;
patch_space_ptr->patch_on = 0;
patch_space_ptr->the_dspchain = 0;
patch_space_ptr->x_argc = 0;
patch_space_ptr->out_ptrs = 0;
}
// Free the patch and dspchain
void hoa_processor_free_patch_and_dsp (t_hoa_processor *x, t_patchspace *patch_space_ptr)
{
// free old patch and dspchain
if (patch_space_ptr->the_dspchain)
object_free((t_object *)patch_space_ptr->the_dspchain);
if (patch_space_ptr->the_patch)
{
if (x->declared_ins)
hoa_processor_patcher_descend(patch_space_ptr->the_patch, (t_intmethod) hoa_processor_unlinkinlets, x, x);
object_free((t_object *)patch_space_ptr->the_patch);
}
}
// ========================================================================================================================================== //
// Parent / Child Communication - Routines for owned objects to query the parent
// ========================================================================================================================================== //
// Note that objects wishing to query the parent hoa.process~ object should call the functions in hoa.process.h.
// These act as suitable wrappers to send the appropriate message to the parent object and returns values as appropriate
////////////////////////////////////////////////// Signal IO Queries //////////////////////////////////////////////////
void *hoa_processor_query_declared_sigins(t_hoa_processor *x)
{
return (void *) x->declared_sig_ins;
}
void *hoa_processor_query_declared_sigouts(t_hoa_processor *x)
{
return (void *) x->declared_sig_outs;
}
void *hoa_processor_query_sigins(t_hoa_processor *x)
{
return (void *) x->sig_ins;
}
void *hoa_processor_query_outptrs_ptr(t_hoa_processor *x, long index)
{
if (index <= x->patch_spaces_allocated)
return &x->patch_space_ptrs[index - 1]->out_ptrs;
else
return 0;
}
void* hoa_processor_query_io_index(t_hoa_processor *x, long patchIndex, t_object* io)
{
long io_index = -1;
long extra;
t_symbol* objclassname = object_classname(io);
if (objclassname == hoa_sym_in || (objclassname == hoa_sym_out) ||
(objclassname == hoa_sym_sigin) || (objclassname == hoa_sym_sigout))
{
extra = object_attr_getlong(io, hoa_sym_extra);
//post("query ins -- patchIndex = %ld, extra = %ld", patchIndex, extra);
if (objclassname == hoa_sym_in)
{
if ( extra > 0 && extra <= x->extra_ins)
{
if (x->instance_ins >= x->instance_sig_ins)
io_index = x->instance_ins + extra;
else if (x->instance_ins < x->instance_sig_ins)
io_index = x->instance_sig_ins + extra;
}
else
io_index = patchIndex;
if (io_index < 1 || io_index > x->declared_ins)
io_index = -1;
}
else if (objclassname == hoa_sym_out)
{
if ( extra > 0 && extra <= x->extra_outs)
io_index = x->instance_outs + extra;
else
io_index = patchIndex;
if (io_index < 1 || io_index > x->declared_outs)
io_index = -1;
}
else if(objclassname == hoa_sym_sigin)
{
if ( extra > 0 && extra <= x->extra_sig_ins)
{
if (x->instance_sig_ins >= x->instance_ins)
io_index = x->instance_sig_ins + extra;
else if (x->instance_sig_ins < x->instance_ins)
io_index = x->instance_ins + extra;
}
else
io_index = patchIndex;
}
else if(objclassname == hoa_sym_sigout)
{
if ( extra > 0 && extra <= x->extra_sig_outs)
{
io_index = x->instance_sig_outs + extra;
}
else
io_index = patchIndex;
if (io_index < 1 || io_index > x->declared_sig_outs)
io_index = -1;
}
//object_post((t_object*)io,"query ins -- io_index = %ld", io_index);
}
return (void*) io_index;
}
//////////////////////////////////////////////////// State Queries ////////////////////////////////////////////////////
void hoa_processor_client_set_patch_on (t_hoa_processor *x, long index, long state)
{
if (state) state = 1;
if (index <= x->patch_spaces_allocated)
{
x->patch_space_ptrs[index - 1]->patch_on = state;
}
}
void *hoa_processor_query_ambisonic_order(t_hoa_processor *x)
{
long order = x->f_ambi2D->getDecompositionOrder();
return (void *) order;
}
void *hoa_processor_query_mode(t_hoa_processor *x)
{
return (void *) x->f_mode;
}
void *hoa_processor_query_number_of_instances(t_hoa_processor *x)
{
return (void *) (x->patch_spaces_allocated);
}
void *hoa_processor_query_is_2D(t_hoa_processor *x)
{
return (void *) (x->f_object_type == HOA_OBJECT_2D);
}
t_hoa_err hoa_processor_query_patcherargs(t_hoa_processor *x, long index, long *argc, t_atom **argv)
{
argc[0] = 0;
argv[0] = NULL;
if (index > 0 && index <= x->patch_spaces_allocated)
{
long ac = x->patch_space_ptrs[index - 1]->x_argc;
argc[0] = ac;
argv[0] = (t_atom *) malloc(ac * sizeof(t_atom) );
for (int i = 0; i < ac; i++)
argv[0][i] = x->patch_space_ptrs[index - 1]->x_argv[i];
return HOA_ERR_NONE;
}
return HOA_ERR_OUT_OF_MEMORY;
}
void *hoa_processor_client_get_patch_on (t_hoa_processor *x, long index)
{
if (index <= x->patch_spaces_allocated)
return (void *) (long) x->patch_space_ptrs[index - 1]->patch_on;
return 0;
} | 34.45774 | 342 | 0.640613 | [
"object",
"3d"
] |
09ec83c8d7203a59113641a05f5b24fe69a47dff | 3,108 | hh | C++ | include/libport/weak-ptr.hh | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 3 | 2015-05-29T09:35:32.000Z | 2021-02-23T07:45:01.000Z | include/libport/weak-ptr.hh | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 2 | 2019-01-31T10:23:47.000Z | 2019-01-31T10:35:06.000Z | include/libport/weak-ptr.hh | jcbaillie/libport | b8192b177ae0ae63979c17ea7685a8617b03e11f | [
"BSD-3-Clause"
] | 7 | 2015-01-29T20:49:06.000Z | 2019-04-24T04:06:22.000Z | /*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef LIBPORT_WEAK_PTR_HH
# define LIBPORT_WEAK_PTR_HH
# include <libport/config.h>
# ifndef LIBPORT_NO_BOOST
# include <boost/weak_ptr.hpp>
namespace libport
{
/// A boost::weak_ptr wrapper.
///
/// Compared to its super type, this implementation provides
/// cast operators, and implicit constructors.
template <typename T>
class weak_ptr : public boost::weak_ptr<T>
{
public:
/// The parent class.
typedef boost::weak_ptr<T> super_type;
/// The type pointed to.
typedef T element_type;
using super_type::operator =;
/// \name Constructors & Destructor.
/// \{
/** \brief Construct a new reference to the value pointed to by \a other.
** The new reference shares the property of the object with \a other. */
template <typename U>
weak_ptr (const weak_ptr<U>& other);
/** \brief Copy constructor.
**
** Although the implementation is subsumed by the previous, more
** generic one, the C++ standard still mandates this specific
** signature. Otherwise, the compiler will provide a default
** implementation, which is of course wrong. Note that the
** same applies for the assignment operator. */
weak_ptr (const weak_ptr<T>& other);
/** \brief Construct a counted reference to a newly allocated object.
** The new reference takes the property of the object pointed to
** by \a p. If \a p is NULL, then the reference is invalid and
** must be \c reset () before use. */
weak_ptr ();
/** \brief Destroy a reference.
** The object pointed to is destroyed iff it is not referenced anymore. */
~weak_ptr ();
/// \}
/// \name Equality operators.
/// \{
/** \brief Reference comparison.
** Returns true if this points to \a p. */
bool operator== (const T* p) const;
/** \brief Reference comparison.
** Returns false if this points to \a p. */
bool operator!= (const T* p) const;
/// \}
/// \name Casts.
/// \{
/** \brief Cast the reference.
** Return a new reference, possibly throwing an exception if the
** dynamic_cast is invalid.
**/
template <typename U> weak_ptr<U> cast () const;
/** \brief Cast the reference (unsafe).
** Return a new reference, possibly a NULL reference if the
** dynamic_cast is invalid.
**/
template <typename U> weak_ptr<U> unsafe_cast () const;
/// \}
/** \brief Test fellowship.
** Return true if the reference points to an object which is
** really of the specified type.
**/
template <typename U> bool is_a () const;
};
/// Simple wrapper to spare the explicit instantiation parameters.
template <typename T>
weak_ptr<T>
make_weak_ptr(T* t);
}
# include <libport/weak-ptr.hxx>
# endif
#endif
| 27.75 | 79 | 0.648005 | [
"object"
] |
09f431a6032dc6a1408ad8cecd6ba774c05684ff | 44,865 | cpp | C++ | RobotRaconteurCore/src/HardwareTransport_win.cpp | robotraconteur/robotraconteur | ff997351761a687be364234684202e3348c4083c | [
"Apache-2.0"
] | 37 | 2019-01-31T06:05:17.000Z | 2022-03-21T06:56:18.000Z | RobotRaconteurCore/src/HardwareTransport_win.cpp | robotraconteur/robotraconteur | ff997351761a687be364234684202e3348c4083c | [
"Apache-2.0"
] | 14 | 2019-07-18T04:09:45.000Z | 2021-08-31T02:04:22.000Z | RobotRaconteurCore/src/HardwareTransport_win.cpp | robotraconteur/robotraconteur | ff997351761a687be364234684202e3348c4083c | [
"Apache-2.0"
] | 3 | 2018-11-23T22:03:22.000Z | 2021-11-02T10:03:39.000Z | // Copyright 2011-2020 Wason Technology, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifdef ROBOTRACONTEUR_CORE_USE_STDAFX
#include "stdafx.h"
#endif
#include "HardwareTransport_win_private.h"
#include "HardwareTransport_private.h"
#include <boost/foreach.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/locale.hpp>
#include <initguid.h>
#include <dbt.h>
// {E274FBA3-1510-4C58-B745-18564DDF78CB}
DEFINE_GUID(GUID_DEVINTERFACE_RobotRaconteurUSBDriver,
0xe274fba3, 0x1510, 0x4c58, 0xb7, 0x45, 0x18, 0x56, 0x4d, 0xdf, 0x78, 0xcb);
// {6F31E87A-198F-44AD-A546-C553C6334987}
DEFINE_GUID(GUID_DEVINTERFACE_RobotRaconteurPCIDriver,
0x6f31e87a, 0x198f, 0x44ad, 0xa5, 0x46, 0xc5, 0x53, 0xc6, 0x33, 0x49, 0x87);
// {01BA2F3B-105A-4CB1-87BD-1ECD6543C00C}
DEFINE_GUID(GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver,
0x1ba2f3b, 0x105a, 0x4cb1, 0x87, 0xbd, 0x1e, 0xcd, 0x65, 0x43, 0xc0, 0xc);
// {E0F04442-C2ED-4E63-9697-604BA38F461A}
DEFINE_GUID(GUID_PROPERTY_RobotRaconteurNodeID,
0xe0f04442, 0xc2ed, 0x4e63, 0x96, 0x97, 0x60, 0x4b, 0xa3, 0x8f, 0x46, 0x1a);
// {4798EB75-D914-43EC-89C8-5AD5CA44FD86}
DEFINE_GUID(GUID_PROPERTY_RobotRaconteurNodeName,
0x4798eb75, 0xd914, 0x43ec, 0x89, 0xc8, 0x5a, 0xd5, 0xca, 0x44, 0xfd, 0x86);
// {3F810FD2-2BCE-4552-98F3-A8AC220AD48D}
DEFINE_GUID(GUID_DEVINTERFACE_RobotRaconteurWinUsbDevice,
0x3f810fd2, 0x2bce, 0x4552, 0x98, 0xf3, 0xa8, 0xac, 0x22, 0xa, 0xd4, 0x8d);
// {25bb0b62-861a-4974-a1b8-18ed5495aa07}
DEFINE_GUID(GUID_RobotRaconteurBluetoothServiceClassID,
0x25bb0b62, 0x861a, 0x4974, 0xa1, 0xb8, 0x18, 0xed, 0x54, 0x95, 0xaa, 0x07);
#define USB_DIR_OUT 0
#define USB_DIR_IN 0x80
#define USB_TYPE_VENDOR (0x02 << 5)
#define USB_RECIP_INTERFACE 0x01
enum rr_usb_subpacket_notify
{
RR_USB_NOTIFICATION_NULL = 0,
RR_USB_NOTIFICATION_SOCKET_CLOSED = 1,
RR_USB_NOTIFICATION_PAUSE_REQUEST = 2,
RR_USB_NOTIFICATION_RESUME_REQUEST = 3
};
#define RR_USB_SUBPACKET_FLAG_COMMAND 0x01
#define RR_USB_SUBPACKET_FLAG_NOTIFICATION 0x02
#define VendorInterfaceRequest \
((USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE))
#define VendorInterfaceOutRequest \
((USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE))
enum rr_usb_control_requests
{
RR_USB_CONTROL_NULL = 0,
RR_USB_CONTROL_GET_INFO,
RR_USB_CONTROL_CONNECT_STREAM,
RR_USB_CONTROL_CLOSE_STREAM,
RR_USB_CONTROL_RESET_ALL_STREAM,
RR_USB_CONTROL_PAUSE_ALL_STREAM,
RR_USB_CONTROL_RESUME_ALL_STREAM,
RR_USB_CONTROL_SUPPORTED_PROTOCOLS,
RR_USB_CONTROL_CURRENT_PROTOCOL
};
#pragma pack(1)
struct subpacket_header
{
uint16_t len;
uint16_t flags;
int32_t id;
};
#pragma pack()
#define RR_USB_MAX_PACKET_SIZE 1024*16
namespace RobotRaconteur
{
SetupApi_Functions::SetupApi_Functions()
{
hLibModule = NULL;
}
bool SetupApi_Functions::LoadFunctions()
{
hLibModule = LoadLibraryW(L"setupapi.dll");
if (hLibModule == NULL)
{
return false;
}
SETUPAPI_FUNCTIONS_INIT(SETUPAPI_FUNCTIONS_PTR_INIT);
return true;
}
SetupApi_Functions::~SetupApi_Functions()
{
if (hLibModule != NULL)
{
FreeLibrary(hLibModule);
}
}
}
namespace RobotRaconteur
{
namespace detail
{
WinUsb_Functions::WinUsb_Functions()
{
hLibModule = NULL;
}
bool WinUsb_Functions::LoadFunctions()
{
hLibModule = LoadLibraryW(L"winusb.dll");
if (hLibModule == NULL) return false;
WINUSB_FUNCTIONS_INIT(WINUSB_FUNCTIONS_PTR_INIT);
WINUSB_ISOCH_FUNCTIONS_INIT(WINUSB_FUNCTIONS_PTR_INIT_NOERR);
return true;
}
WinUsb_Functions::~WinUsb_Functions()
{
if (hLibModule != NULL)
{
FreeLibrary(hLibModule);
}
}
// WinUsbDeviceManager
WinUsbDeviceManager::WinUsbDeviceManager(RR_SHARED_PTR<HardwareTransport> parent, RR_SHARED_PTR<SetupApi_Functions> setupapi_f)
: UsbDeviceManager(parent)
{
this->setupapi_f = setupapi_f;
}
WinUsbDeviceManager::~WinUsbDeviceManager()
{
}
bool WinUsbDeviceManager::InitUpdateDevices()
{
if (f)
{
return true;
}
else
{
RR_SHARED_PTR<WinUsb_Functions> f1 = RR_MAKE_SHARED<WinUsb_Functions>();
if (!f1->LoadFunctions())
{
return false;
}
f = f1;
}
return true;
}
static void SetupApi_Functions_SetupDiDestroyDeviceInfoList(RR_SHARED_PTR<SetupApi_Functions> f, HDEVINFO deviceInfo)
{
f->SetupDiDestroyDeviceInfoList(deviceInfo);
}
std::list<UsbDeviceManager_detected_device> WinUsbDeviceManager::GetDetectedDevicesPaths()
{
HDEVINFO deviceInfo;
RR_SHARED_PTR<void> deviceInfo_sp;
SP_DEVICE_INTERFACE_DATA interfaceData;
BOOL bResult;
std::list<UsbDeviceManager_detected_device> devices;
deviceInfo = setupapi_f->SetupDiGetClassDevsW(&GUID_DEVINTERFACE_RobotRaconteurWinUsbDevice,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfo == INVALID_HANDLE_VALUE) {
return devices;
}
deviceInfo_sp = RR_SHARED_PTR<void>(deviceInfo, boost::bind(&SetupApi_Functions_SetupDiDestroyDeviceInfoList, setupapi_f, RR_BOOST_PLACEHOLDERS(_1)));
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD i = 0;
while (true)
{
bResult = setupapi_f->SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
&GUID_DEVINTERFACE_RobotRaconteurWinUsbDevice,
i,
&interfaceData);
i++;
if (!bResult)
{
if (GetLastError() == ERROR_NO_MORE_ITEMS)
{
break;
}
else
{
continue;
}
}
DWORD requiredLength;
RR_SHARED_PTR <SP_DEVICE_INTERFACE_DETAIL_DATA_W> detailData;
//
// Get the size of the path string
// We expect to get a failure with insufficient buffer
//
bResult = setupapi_f->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
NULL,
0,
&requiredLength,
NULL);
if (FALSE == bResult && ERROR_INSUFFICIENT_BUFFER != GetLastError()) {
continue;
}
//
// Allocate temporary space for SetupDi structure
//
detailData.reset((PSP_DEVICE_INTERFACE_DETAIL_DATA_W)
LocalAlloc(LMEM_FIXED, requiredLength), LocalFree);
if (NULL == detailData)
{
continue;
}
detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
DWORD length = requiredLength;
//
// Get the interface's path string
//
bResult = setupapi_f->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
detailData.get(),
length,
&requiredLength,
NULL);
if (FALSE == bResult)
{
continue;
}
UsbDeviceManager_detected_device d;
d.path = std::wstring(detailData->DevicePath);
d.interface_ = 0;
devices.push_back(d);
}
return devices;
}
RR_SHARED_PTR<UsbDevice> WinUsbDeviceManager::CreateDevice(const UsbDeviceManager_detected_device& device)
{
return RR_MAKE_SHARED<WinUsbDevice>(RR_STATIC_POINTER_CAST<WinUsbDeviceManager>(shared_from_this()), f, device);
}
// WinUsbDevice_Handle
static void WinUsbDevice_winusb_free(RR_SHARED_PTR<WinUsb_Functions> f, void* hInterface)
{
f->WinUsb_Free(hInterface);
}
static UsbDeviceStatus WinUsbDevice_open_device(RR_BOOST_ASIO_IO_CONTEXT& _io_context, RR_SHARED_PTR<WinUsb_Functions>& f, const std::wstring& path, RR_SHARED_PTR<void>& dev_h)
{
HANDLE h1 = CreateFileW(path.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (h1 == INVALID_HANDLE_VALUE)
{
DWORD a = GetLastError();
if (GetLastError() == ERROR_ACCESS_DENIED)
{
return Busy;
}
return Error;
}
RR_SHARED_PTR<boost::asio::windows::stream_handle> device_handle1(new boost::asio::windows::stream_handle(_io_context, h1));
WINUSB_INTERFACE_HANDLE h2;
if (!f->WinUsb_Initialize(device_handle1->native_handle(), &h2))
{
return Error;
}
RR_SHARED_PTR<void> hInterface1(h2, boost::bind(&WinUsbDevice_winusb_free, f,RR_BOOST_PLACEHOLDERS(_1)));
RR_SHARED_PTR<WinUsbDevice_Handle> h = RR_MAKE_SHARED<WinUsbDevice_Handle>();
h->device_handle = device_handle1;
h->hInterface = hInterface1;
dev_h = h;
return Open;
}
WinUsbDevice_Handle::~WinUsbDevice_Handle()
{
hInterface.reset();
device_handle.reset();
}
//WinUsbDevice_Initialize
WinUsbDevice_Initialize::WinUsbDevice_Initialize(RR_SHARED_PTR<UsbDevice> parent, RR_SHARED_PTR<WinUsb_Functions> f, const UsbDeviceManager_detected_device& detected_device)
: UsbDevice_Initialize(parent, detected_device)
{
this->f = f;
}
UsbDeviceStatus WinUsbDevice_Initialize::OpenDevice(RR_SHARED_PTR<void>& dev_h)
{
return WinUsbDevice_open_device(GetNode()->GetThreadPool()->get_io_context(), f, detected_device.path, dev_h);
}
UsbDeviceStatus WinUsbDevice_Initialize::ReadInterfaceSettings(RR_SHARED_PTR<void> dev_h, RR_SHARED_PTR<UsbDevice_Settings>& settings)
{
RR_SHARED_PTR<WinUsbDevice_Handle> h = RR_STATIC_POINTER_CAST<WinUsbDevice_Handle>(dev_h);
UCHAR altSetting = 0;
if (!f->WinUsb_GetCurrentAlternateSetting(h->hInterface.get(), &altSetting))
{
return Error;
}
settings->interface_alt_setting = altSetting;
USB_INTERFACE_DESCRIPTOR d;
if (!f->WinUsb_QueryInterfaceSettings(h->hInterface.get(), settings->interface_alt_setting, &d))
{
return Error;
}
settings->interface_number = d.bInterfaceNumber;
settings->interface_num_endpoints = d.bNumEndpoints;
ULONG desc_buf_len = 64 * 1024;
ULONG desc_buf_read = 0;
boost::scoped_array<uint8_t> desc_buf(new uint8_t[desc_buf_len]);
if (!f->WinUsb_GetDescriptor(h->hInterface.get(), USB_CONFIGURATION_DESCRIPTOR_TYPE, settings->interface_number, 0, desc_buf.get(), desc_buf_len, &desc_buf_read))
{
return Error;
}
boost::asio::mutable_buffer desc(desc_buf.get(), desc_buf_read);
bool in_desired_interface = false;
bool cs_interface_found = false;
uint16_t num_protocols;
while (boost::asio::buffer_size(desc) >= 2)
{
USB_COMMON_DESCRIPTOR* c1 = RR_BOOST_ASIO_BUFFER_CAST(USB_COMMON_DESCRIPTOR*,desc);
if (c1->bLength > boost::asio::buffer_size(desc))
{
return Error;
}
if (c1->bDescriptorType == USB_INTERFACE_DESCRIPTOR_TYPE)
{
USB_INTERFACE_DESCRIPTOR* c2 = (USB_INTERFACE_DESCRIPTOR*)c1;
if (c2->bInterfaceNumber == settings->interface_number && c2->bAlternateSetting == settings->interface_alt_setting)
{
in_desired_interface = true;
}
else
{
in_desired_interface = false;
}
}
if (c1->bDescriptorType == USB_ENDPOINT_DESCRIPTOR_TYPE)
{
in_desired_interface = false;
}
if (in_desired_interface && c1->bDescriptorType == USB_CS_INTERFACE_DESCRIPTOR_TYPE)
{
robotraconteur_interface_common_descriptor* c3 = (robotraconteur_interface_common_descriptor*)c1;
if (c3->bDescriptorSubType == 0)
{
if (c3->bLength != sizeof(robotraconteur_interface_descriptor))
{
return Invalid;
}
robotraconteur_interface_descriptor* c4 = (robotraconteur_interface_descriptor*)c3;
if (memcmp(RR_USB_CS_INTERFACE_UUID_DETECT, c4->uuidRobotRaconteurDetect, sizeof(RR_USB_CS_INTERFACE_UUID_DETECT)) != 0)
{
return Invalid;
}
settings->string_lang_index = 0;
settings->string_nodeid_index = c4->iNodeID;
settings->string_nodename_index = c4->iNodeName;
num_protocols = c4->wNumProtocols;
cs_interface_found = true;
}
if (c3->bDescriptorSubType == 1)
{
if (c3->bLength < sizeof(robotraconteur_protocol_descriptor))
{
return Error;
}
robotraconteur_protocol_descriptor* c4 = (robotraconteur_protocol_descriptor*)c3;
settings->supported_protocols.push_back(c4->wRRProtocol);
}
}
desc = desc + c1->bLength;
}
if (!cs_interface_found)
{
return Invalid;
}
if (num_protocols != settings->supported_protocols.size())
{
return Invalid;
}
return Open;
}
UsbDeviceStatus WinUsbDevice_Initialize::ReadPipeSettings(RR_SHARED_PTR<void> dev_h, RR_SHARED_PTR<UsbDevice_Settings>& settings)
{
RR_SHARED_PTR<WinUsbDevice_Handle> h = RR_STATIC_POINTER_CAST<WinUsbDevice_Handle>(dev_h);
bool in_found = false;
bool out_found = false;
for (UCHAR i = 0; i < settings->interface_num_endpoints; i++)
{
//Bug with WinUsb WINUSB_PIPE_INFORMATION structure?
uint8_t d_pipe1[sizeof(WINUSB_PIPE_INFORMATION) * 2];
PWINUSB_PIPE_INFORMATION d_pipe = static_cast<PWINUSB_PIPE_INFORMATION>((void*)&d_pipe1);
if (f->WinUsb_QueryPipe(h->hInterface.get(), settings->interface_alt_setting, i, d_pipe))
{
if (d_pipe->PipeType == UsbdPipeTypeBulk && USB_ENDPOINT_DIRECTION_IN(d_pipe->PipeId) && !in_found)
{
in_found = true;
settings->in_pipe_id = d_pipe->PipeId;
settings->in_pipe_maxpacket = d_pipe->MaximumPacketSize;
if (RR_USB_MAX_PACKET_SIZE % settings->in_pipe_maxpacket == 0)
{
settings->in_pipe_buffer_size = RR_USB_MAX_PACKET_SIZE;
}
else
{
settings->in_pipe_buffer_size = ((RR_USB_MAX_PACKET_SIZE / settings->in_pipe_maxpacket) + 1) * settings->in_pipe_maxpacket;
}
}
if (d_pipe->PipeType == UsbdPipeTypeBulk && USB_ENDPOINT_DIRECTION_OUT(d_pipe->PipeId) && !out_found)
{
out_found = true;
settings->out_pipe_id = d_pipe->PipeId;
settings->out_pipe_maxpacket = d_pipe->MaximumPacketSize;
if (RR_USB_MAX_PACKET_SIZE % settings->out_pipe_maxpacket == 0)
{
settings->out_pipe_buffer_size = RR_USB_MAX_PACKET_SIZE;
}
else
{
settings->out_pipe_buffer_size = ((RR_USB_MAX_PACKET_SIZE / settings->in_pipe_maxpacket) + 1) * settings->out_pipe_maxpacket;
}
}
}
}
if (!in_found || !out_found)
{
return Error;
}
return Open;
}
static void WinUsbDevice_async_control_transfer(RR_BOOST_ASIO_IO_CONTEXT& _io_context, RR_SHARED_PTR<WinUsb_Functions> f, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler, RR_SHARED_PTR<void> dev_h = RR_SHARED_PTR<void>())
{
RR_SHARED_PTR<void> my_hInterface;
if (!dev_h)
{
RR_BOOST_ASIO_POST(_io_context,boost::bind(handler, boost::asio::error::broken_pipe, 0));
return;
}
RR_SHARED_PTR<WinUsbDevice_Handle> h = RR_STATIC_POINTER_CAST<WinUsbDevice_Handle>(dev_h);
my_hInterface = h->hInterface;
boost::asio::windows::overlapped_ptr overlapped(_io_context, handler);
DWORD bytes_transferred = 0;
WINUSB_SETUP_PACKET setup;
setup.RequestType = bmRequestType;
setup.Request = bRequest;
setup.Value = wValue;
setup.Index = wIndex;
setup.Length = (USHORT)boost::asio::buffer_size(buf);
BOOL ok = f->WinUsb_ControlTransfer(my_hInterface.get(), setup, RR_BOOST_ASIO_BUFFER_CAST(PUCHAR,buf), boost::asio::buffer_size(buf), &bytes_transferred, overlapped.get());
DWORD last_error = ::GetLastError();
if (!ok && last_error != ERROR_IO_PENDING
&& last_error != ERROR_MORE_DATA)
{
boost::system::error_code ec(last_error, boost::asio::error::system_category);
overlapped.complete(ec, 0);
}
else
{
overlapped.release();
}
}
void WinUsbDevice_Initialize::AsyncControlTransfer(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler, RR_SHARED_PTR<void> dev_h)
{
boost::mutex::scoped_lock lock(this_lock);
WinUsbDevice_async_control_transfer(GetNode()->GetThreadPool()->get_io_context(), f, bmRequestType, bRequest, wValue, wIndex, buf, handler, dev_h);
}
void WinUsbDevice_Initialize::AsyncControlTransferNoLock(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler, RR_SHARED_PTR<void> dev_h)
{
//boost::mutex::scoped_lock lock(this_lock);
WinUsbDevice_async_control_transfer(GetNode()->GetThreadPool()->get_io_context(), f, bmRequestType, bRequest, wValue, wIndex, buf, handler, dev_h);
}
//WinUsbDevice_Claim
WinUsbDevice_Claim::WinUsbDevice_Claim(RR_SHARED_PTR<UsbDevice> parent, RR_SHARED_PTR<WinUsb_Functions> f, const UsbDeviceManager_detected_device& detected_device)
:UsbDevice_Claim(parent, detected_device)
{
this->f = f;
}
void WinUsbDevice_Claim::AsyncControlTransfer(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler, RR_SHARED_PTR<void> dev_h)
{
boost::mutex::scoped_lock lock(this_lock);
if (!dev_h)
{
dev_h = device_handle;
}
WinUsbDevice_async_control_transfer(GetNode()->GetThreadPool()->get_io_context(), f, bmRequestType, bRequest, wValue, wIndex, buf, handler, dev_h);
}
void WinUsbDevice_Claim::AsyncControlTransferNoLock(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler, RR_SHARED_PTR<void> dev_h)
{
//boost::mutex::scoped_lock lock(this_lock);
if (!dev_h)
{
dev_h = device_handle;
}
WinUsbDevice_async_control_transfer(GetNode()->GetThreadPool()->get_io_context(), f, bmRequestType, bRequest, wValue, wIndex, buf, handler, dev_h);
}
void WinUsbDevice_Claim::AsyncReadPipe(uint8_t ep, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler)
{
boost::mutex::scoped_lock lock(this_lock);
AsyncReadPipeNoLock(ep, buf, handler);
}
void WinUsbDevice_Claim::AsyncReadPipeNoLock(uint8_t ep, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler)
{
if (status != Claimed || !device_handle)
{
RobotRaconteurNode::TryPostToThreadPool(node,boost::bind(handler, boost::asio::error::bad_descriptor, 0), true);
return;
}
RR_BOOST_ASIO_IO_CONTEXT& io = GetNode()->GetThreadPool()->get_io_context();
boost::asio::windows::overlapped_ptr overlapped(io, handler);
DWORD bytes_transferred = 0;
BOOL ok = f->WinUsb_ReadPipe(device_handle->hInterface.get(), ep, RR_BOOST_ASIO_BUFFER_CAST(PUCHAR,buf), boost::asio::buffer_size(buf), &bytes_transferred, overlapped.get());
DWORD last_error = ::GetLastError();
if (!ok && last_error != ERROR_IO_PENDING
&& last_error != ERROR_MORE_DATA)
{
boost::system::error_code ec(last_error, boost::asio::error::system_category);
overlapped.complete(ec, 0);
}
else
{
overlapped.release();
}
}
void WinUsbDevice_Claim::AsyncWritePipe(uint8_t ep, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler)
{
boost::mutex::scoped_lock lock(this_lock);
AsyncWritePipeNoLock(ep, buf, handler);
}
void WinUsbDevice_Claim::AsyncWritePipeNoLock(uint8_t ep, boost::asio::mutable_buffer& buf, boost::function< void(const boost::system::error_code&, size_t) > handler)
{
if (status != Claimed || !device_handle)
{
RobotRaconteurNode::TryPostToThreadPool(node, boost::bind(handler, boost::asio::error::bad_descriptor, 0), true);
return;
}
RR_BOOST_ASIO_IO_CONTEXT& io = GetNode()->GetThreadPool()->get_io_context();
boost::asio::windows::overlapped_ptr overlapped(io, handler);
DWORD bytes_transferred = 0;
BOOL ok = f->WinUsb_WritePipe(device_handle->hInterface.get(), ep, RR_BOOST_ASIO_BUFFER_CAST(PUCHAR,buf), boost::asio::buffer_size(buf), &bytes_transferred, overlapped.get());
DWORD last_error = ::GetLastError();
if (!ok && last_error != ERROR_IO_PENDING
&& last_error != ERROR_MORE_DATA)
{
boost::system::error_code ec(last_error, boost::asio::error::system_category);
overlapped.complete(ec, 0);
}
else
{
overlapped.release();
}
}
UsbDeviceStatus WinUsbDevice_Claim::ClaimDevice(RR_SHARED_PTR<void>& dev_h)
{
UsbDeviceStatus res= WinUsbDevice_open_device(GetNode()->GetThreadPool()->get_io_context(), f, detected_device.path, dev_h);
if (res != Open)
{
return res;
}
RR_SHARED_PTR<WinUsbDevice_Handle> h = RR_STATIC_POINTER_CAST<WinUsbDevice_Handle>(dev_h);
BOOL b_true = TRUE;
BOOL b_false = FALSE;
if (!f->WinUsb_SetPipePolicy(h->hInterface.get(), settings->in_pipe_id, RAW_IO, sizeof(b_true), &b_true)
/*|| !f->WinUsb_SetPipePolicy(hInterface1.get(), out_pipe_id, RAW_IO, sizeof(b_true), &b_true)*/
|| !f->WinUsb_SetPipePolicy(h->hInterface.get(), settings->in_pipe_id, ALLOW_PARTIAL_READS, sizeof(b_false), &b_false)
|| !f->WinUsb_SetPipePolicy(h->hInterface.get(), settings->out_pipe_id, SHORT_PACKET_TERMINATE, sizeof(b_true), &b_true)
|| !f->WinUsb_ResetPipe(h->hInterface.get(), settings->in_pipe_id) || !f->WinUsb_ResetPipe(h->hInterface.get(), settings->out_pipe_id))
{
return Error;
}
dev_h = h;
device_handle = h;
return Open;
}
void WinUsbDevice_Claim::ReleaseClaim()
{
if (!device_handle) return;
device_handle.reset();
}
void WinUsbDevice_Claim::DrawDownRequests(boost::function<void()> handler)
{
if (!device_handle) return;
f->WinUsb_AbortPipe(device_handle->hInterface.get(), settings->in_pipe_id);
f->WinUsb_AbortPipe(device_handle->hInterface.get(), settings->out_pipe_id);
RobotRaconteurNode::TryPostToThreadPool(node, handler, true);
}
void WinUsbDevice_Claim::ClearHalt(uint8_t ep)
{
boost::mutex::scoped_lock lock(this_lock);
if (!device_handle) return;
f->WinUsb_ResetPipe(device_handle->hInterface.get(), ep);
}
//WinUsbDevice
WinUsbDevice::WinUsbDevice(RR_SHARED_PTR<WinUsbDeviceManager> parent, RR_SHARED_PTR<WinUsb_Functions> f, const UsbDeviceManager_detected_device& device)
: UsbDevice(parent, device)
{
this->f = f;
}
WinUsbDevice::~WinUsbDevice()
{
}
RR_SHARED_PTR<UsbDevice_Initialize> WinUsbDevice::CreateInitialize()
{
return RR_MAKE_SHARED<WinUsbDevice_Initialize>(shared_from_this(), f, detected_device);
}
RR_SHARED_PTR<UsbDevice_Claim> WinUsbDevice::CreateClaim()
{
return RR_MAKE_SHARED<WinUsbDevice_Claim>(shared_from_this(), f, detected_device);
}
//WinsockBluetoothConnector
WinsockBluetoothConnector::WinsockBluetoothConnector(RR_SHARED_PTR<HardwareTransport> parent)
: BluetoothConnector(parent)
{
}
std::list<SOCKADDR_BTH> WinsockBluetoothConnector::GetDeviceAddresses()
{
std::list<SOCKADDR_BTH> o;
WSAQUERYSETW wsaq;
HANDLE hLookup;
union {
CHAR buf[5000];
double __unused; // ensure proper alignment
};
LPWSAQUERYSETW pwsaResults = (LPWSAQUERYSETW)buf;
DWORD dwSize = sizeof(buf);
ZeroMemory(&wsaq, sizeof(wsaq));
wsaq.dwSize = sizeof(wsaq);
wsaq.dwNameSpace = NS_BTH;
wsaq.lpcsaBuffer = NULL;
if (ERROR_SUCCESS != WSALookupServiceBeginW(&wsaq, LUP_CONTAINERS, &hLookup))
{
return o;
}
ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;
pwsaResults->lpBlob = NULL;
while (ERROR_SUCCESS == WSALookupServiceNextW(hLookup, LUP_RETURN_ADDR, &dwSize, pwsaResults))
{
if (pwsaResults->dwNumberOfCsAddrs != 1) continue;
SOCKADDR_BTH b = *((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr);
o.push_back(b);
dwSize = sizeof(buf);
}
WSALookupServiceEnd(hLookup);
return o;
}
std::list<BluetoothConnector<SOCKADDR_BTH, AF_BTH, BTHPROTO_RFCOMM>::device_info> WinsockBluetoothConnector::GetDeviceNodes(SOCKADDR_BTH addr)
{
std::list<device_info> o;
DWORD flags = LUP_FLUSHCACHE | LUP_RETURN_ALL | LUP_RES_SERVICE;
WSAQUERYSETW wsaq;
HANDLE hLookup;
union {
CHAR buf[5000];
double __unused; // ensure proper alignment
};
LPWSAQUERYSETW pwsaResults = (LPWSAQUERYSETW)buf;
DWORD dwSize = sizeof(buf);
ZeroMemory(&wsaq, sizeof(wsaq));
wsaq.dwSize = sizeof(wsaq);
wsaq.dwNameSpace = NS_BTH;
wsaq.lpcsaBuffer = NULL;
wchar_t address_str[40];
DWORD address_str_len = sizeof(address_str) / sizeof(wchar_t);
if (ERROR_SUCCESS != WSAAddressToStringW((LPSOCKADDR)&addr, sizeof(addr), NULL, address_str, &address_str_len))
{
return o;
}
GUID guid = GUID_RobotRaconteurBluetoothServiceClassID;
wsaq.lpszContext = address_str;
wsaq.lpServiceClassId = &guid;
if (ERROR_SUCCESS != WSALookupServiceBeginW(&wsaq, flags, &hLookup))
{
return o;
}
ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;
pwsaResults->lpBlob = NULL;
while (ERROR_SUCCESS == WSALookupServiceNextW(hLookup, flags, &dwSize, pwsaResults))
{
if (pwsaResults->dwNumberOfCsAddrs < 1) continue;
if (pwsaResults->lpcsaBuffer->iProtocol != BTHPROTO_RFCOMM) continue;
SOCKADDR_BTH b = *((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr);
boost::asio::mutable_buffer raw_record(pwsaResults->lpBlob->pBlobData, pwsaResults->lpBlob->cbSize);
device_info info;
info.addr = b;
if (!ReadSdpRecord(raw_record, info))
{
continue;
}
o.push_back(info);
dwSize = sizeof(buf);
}
WSALookupServiceEnd(hLookup);
return o;
}
//Device driver interface search
boost::optional<std::wstring> HardwareTransport_win_find_deviceinterface(RR_SHARED_PTR<void> f, const GUID* interface_guid, const NodeID& nodeid, boost::string_ref nodename)
{
if (!f)
{
return boost::optional<std::wstring>();
}
RR_SHARED_PTR<SetupApi_Functions> f1 = RR_STATIC_POINTER_CAST<SetupApi_Functions>(f);
HDEVINFO deviceInfo;
RR_SHARED_PTR<void> deviceInfo_sp;
SP_DEVICE_INTERFACE_DATA interfaceData;
BOOL bResult;
deviceInfo = f1->SetupDiGetClassDevsW(interface_guid,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfo == INVALID_HANDLE_VALUE) {
return boost::optional<std::wstring>();
}
deviceInfo_sp = RR_SHARED_PTR<void>(deviceInfo, boost::bind(&SetupApi_Functions_SetupDiDestroyDeviceInfoList, f1, RR_BOOST_PLACEHOLDERS(_1)));
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD i = 0;
while (true)
{
bResult = f1->SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
&GUID_DEVINTERFACE_RobotRaconteurUSBDriver,
i,
&interfaceData);
i++;
if (!bResult)
{
if (GetLastError() == ERROR_NO_MORE_ITEMS)
{
break;
}
else
{
continue;
}
}
wchar_t property_buffer[256];
memset(property_buffer, 0, sizeof(property_buffer));
DEVPROPKEY nodename_key;
nodename_key.fmtid = GUID_PROPERTY_RobotRaconteurNodeName;
nodename_key.pid = 2;
DEVPROPTYPE proptype;
bResult = f1->SetupDiGetDeviceInterfacePropertyW(deviceInfo,
&interfaceData,
&nodename_key,
&proptype,
(PBYTE)property_buffer,
sizeof(property_buffer),
NULL, 0);
if (FALSE == bResult)
{
continue;
}
if (proptype != DEVPROP_TYPE_STRING)
{
continue;
}
std::wstring nodename2(property_buffer);
memset(property_buffer, 0, sizeof(property_buffer));
DEVPROPKEY nodeid_key;
nodeid_key.fmtid = GUID_PROPERTY_RobotRaconteurNodeID;
nodeid_key.pid = 2;
DEVPROPTYPE proptype2;
bResult = f1->SetupDiGetDeviceInterfacePropertyW(deviceInfo,
&interfaceData,
&nodeid_key,
&proptype2,
(PBYTE)property_buffer,
sizeof(property_buffer),
NULL, 0);
if (FALSE == bResult)
{
continue;
}
if (proptype2 != DEVPROP_TYPE_STRING)
{
continue;
}
std::wstring nodeid2_str(property_buffer);
try
{
std::string nodeid2_str1 = boost::locale::conv::utf_to_utf<char>(nodeid2_str);
NodeID nodeid2(nodeid2_str1);
std::string nodename2_2 = boost::locale::conv::utf_to_utf<char>(nodename2);
if (!nodeid.IsAnyNode() && !nodename.empty())
{
if (nodeid != nodeid2 || nodename != nodename2_2)
{
continue;
}
}
else if (nodeid.IsAnyNode() && !nodename.empty())
{
if (nodename != nodename2_2)
{
continue;
}
}
else if (!nodeid.IsAnyNode() && nodename.empty())
{
if (nodename != nodename2_2)
{
continue;
}
}
else
{
continue;
}
//We have found a match if we made it this far...
DWORD requiredLength;
RR_SHARED_PTR <SP_DEVICE_INTERFACE_DETAIL_DATA_W> detailData;
//
// Get the size of the path string
// We expect to get a failure with insufficient buffer
//
bResult = f1->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
NULL,
0,
&requiredLength,
NULL);
if (FALSE == bResult && ERROR_INSUFFICIENT_BUFFER != GetLastError()) {
continue;
}
//
// Allocate temporary space for SetupDi structure
//
detailData.reset((PSP_DEVICE_INTERFACE_DETAIL_DATA_W)
LocalAlloc(LMEM_FIXED, requiredLength), LocalFree);
if (NULL == detailData)
{
continue;
}
detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
DWORD length = requiredLength;
//
// Get the interface's path string
//
bResult = f1->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
detailData.get(),
length,
&requiredLength,
NULL);
if (FALSE == bResult)
{
continue;
}
return std::wstring(detailData->DevicePath);
}
catch (std::exception&) {}
}
return boost::optional<std::wstring>();
}
boost::optional<std::wstring> HardwareTransport_win_find_usb(RR_SHARED_PTR<void> f, const NodeID& nodeid, boost::string_ref nodename)
{
return HardwareTransport_win_find_deviceinterface(f, &GUID_DEVINTERFACE_RobotRaconteurUSBDriver, nodeid, nodename);
}
boost::optional<std::wstring> HardwareTransport_win_find_pci(RR_SHARED_PTR<void> f, const NodeID& nodeid, boost::string_ref nodename)
{
return HardwareTransport_win_find_deviceinterface(f, &GUID_DEVINTERFACE_RobotRaconteurPCIDriver, nodeid, nodename);
}
boost::optional<std::wstring> HardwareTransport_win_find_bluetooth(RR_SHARED_PTR<void> f, const NodeID& nodeid, boost::string_ref nodename)
{
return HardwareTransport_win_find_deviceinterface(f, &GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver, nodeid, nodename);
}
HardwareTransport_win_discovery::HardwareTransport_win_discovery(RR_SHARED_PTR<HardwareTransport> parent, const std::vector<std::string>& schemes, RR_SHARED_PTR<WinUsbDeviceManager> usb, RR_SHARED_PTR<WinsockBluetoothConnector> bt, RR_SHARED_PTR<void> f_void)
: HardwareTransport_discovery(parent, schemes, usb, bt)
{
}
void HardwareTransport_win_discovery::Init()
{
HardwareTransport_discovery::Init();
running = true;
window_thread=boost::thread(boost::bind(&HardwareTransport_win_discovery::MessageWindowFunc, RR_STATIC_POINTER_CAST<HardwareTransport_win_discovery>(shared_from_this())));
}
void HardwareTransport_win_discovery::Close()
{
HardwareTransport_discovery::Close();
boost::thread t1;
{
boost::mutex::scoped_lock lock(this_lock);
running = false;
if (m_Wnd)
{
::PostMessageW(m_Wnd, WM_DESTROY, 0, 0);
}
t1.swap(window_thread);
}
if (t1.joinable())
{
t1.join();
}
}
std::vector<NodeDiscoveryInfo> HardwareTransport_win_discovery::GetDriverDevices()
{
std::vector<NodeDiscoveryInfo> v1=GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurUSBDriver, "rr+usb");
std::vector<NodeDiscoveryInfo> v2=GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurPCIDriver, "rr+pci");
std::vector<NodeDiscoveryInfo> v3=GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver, "rr+bluetooth");
std::vector<NodeDiscoveryInfo> o;
boost::range::copy(v1, std::back_inserter(o));
boost::range::copy(v2, std::back_inserter(o));
boost::range::copy(v3, std::back_inserter(o));
return o;
}
std::vector<NodeDiscoveryInfo> HardwareTransport_win_discovery::GetDriverDevices1(const GUID* guid, const std::string& scheme)
{
std::vector<NodeDiscoveryInfo> o;
try
{
RR_SHARED_PTR<RobotRaconteurNode> node = GetParent()->GetNode();
std::list<boost::tuple<NodeID, std::string> > usb_dev = HardwareTransport_win_find_deviceinterfaces(f, guid);
typedef boost::tuple<NodeID, std::string> e_type;
BOOST_FOREACH(e_type& e, usb_dev)
{
NodeDiscoveryInfo n;
n.NodeID = e.get<0>();
n.NodeName = e.get<1>();
NodeDiscoveryInfoURL n1;
n1.URL = scheme + ":///?nodeid=" + e.get<0>().ToString("D") + "&service=RobotRaconteurServiceIndex";
n1.LastAnnounceTime = node->NowNodeTime();
n.URLs.push_back(n1);
o.push_back(n);
}
}
catch (std::exception&) {}
return o;
}
//https://stackoverflow.com/questions/21369256/how-to-use-wndproc-as-a-class-function
LRESULT CALLBACK HardwareTransport_win_discovery::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
HardwareTransport_win_discovery* pThis;
if (msg == WM_NCCREATE)
{
pThis = static_cast<HardwareTransport_win_discovery*>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);
SetLastError(0);
if (!SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis)))
{
if (GetLastError() != 0)
return FALSE;
}
return TRUE;
}
else
{
pThis = reinterpret_cast<HardwareTransport_win_discovery*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
}
if (pThis)
{
switch (msg)
{
case WM_DEVICECHANGE:
switch (wParam)
{
case DBT_DEVICEARRIVAL:
case DBT_DEVICEREMOVECOMPLETE:
{
PDEV_BROADCAST_HDR dev_header = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (dev_header->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
PDEV_BROADCAST_DEVICEINTERFACE_W int_header = reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE_W>(lParam);
GUID g = int_header->dbcc_classguid;
pThis->OnDeviceChanged_win(g, wParam);
}
break;
}
case DBT_CUSTOMEVENT:
{
PDEV_BROADCAST_HDR dev_header = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (dev_header->dbch_devicetype == DBT_DEVTYP_HANDLE)
{
PDEV_BROADCAST_HANDLE int_header = reinterpret_cast<PDEV_BROADCAST_HANDLE>(lParam);
GUID g = int_header->dbch_eventguid;
pThis->OnBluetoothChanged_win(g, wParam, int_header->dbch_data);
}
}
default:
break;
}
return TRUE;
case WM_DESTROY:
return TRUE;
default:
//We don't care about most messages
break;
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
static BOOL DoRegisterDeviceInterfaceToHwnd(
const GUID* InterfaceClassGuid,
HWND hWnd,
HDEVNOTIFY *hDeviceNotify
)
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = *InterfaceClassGuid;
*hDeviceNotify = RegisterDeviceNotificationW(
hWnd, // events recipient
&NotificationFilter, // type of device
DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
);
if (NULL == *hDeviceNotify)
{
return FALSE;
}
return TRUE;
}
static BOOL DoRegisterBluetoothRadioToHwd(
RR_SHARED_PTR<void> f,
HWND hWnd,
RR_SHARED_PTR<void> &hDeviceNotify,
RR_SHARED_PTR<void>& hRadio
)
{
if (!f) return FALSE;
RR_SHARED_PTR<SetupApi_Functions> setupapi_f = RR_STATIC_POINTER_CAST<SetupApi_Functions>(f);
RR_SHARED_PTR<HANDLE> hRadio1;
HDEVINFO deviceInfo;
RR_SHARED_PTR<void> deviceInfo_sp;
SP_DEVICE_INTERFACE_DATA interfaceData;
BOOL bResult;
std::list<std::wstring> paths;
deviceInfo = setupapi_f->SetupDiGetClassDevsW(&GUID_BTHPORT_DEVICE_INTERFACE,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfo == INVALID_HANDLE_VALUE) {
return FALSE;
}
deviceInfo_sp = RR_SHARED_PTR<void>(deviceInfo_sp, setupapi_f->SetupDiDestroyDeviceInfoList);
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD i = 0;
bResult = setupapi_f->SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
&GUID_BTHPORT_DEVICE_INTERFACE,
i,
&interfaceData);
if (!bResult)
{
return FALSE;
}
DWORD requiredLength;
RR_SHARED_PTR <SP_DEVICE_INTERFACE_DETAIL_DATA_W> detailData;
//
// Get the size of the path string
// We expect to get a failure with insufficient buffer
//
bResult = setupapi_f->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
NULL,
0,
&requiredLength,
NULL);
if (FALSE == bResult && ERROR_INSUFFICIENT_BUFFER != GetLastError()) {
return FALSE;
}
//
// Allocate temporary space for SetupDi structure
//
detailData.reset((PSP_DEVICE_INTERFACE_DETAIL_DATA_W)
LocalAlloc(LMEM_FIXED, requiredLength), LocalFree);
if (NULL == detailData)
{
return FALSE;
}
detailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
DWORD length = requiredLength;
//
// Get the interface's path string
//
bResult = setupapi_f->SetupDiGetDeviceInterfaceDetailW(deviceInfo,
&interfaceData,
detailData.get(),
length,
&requiredLength,
NULL);
if (FALSE == bResult)
{
return FALSE;
}
HANDLE h=CreateFileW(detailData->DevicePath, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (h==INVALID_HANDLE_VALUE)
{
return false;
}
RR_SHARED_PTR<void> h_sp(h, CloseHandle);
DEV_BROADCAST_HANDLE NotificationFilter;
ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
NotificationFilter.dbch_size = sizeof(NotificationFilter);
NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE;
NotificationFilter.dbch_handle = h;
HDEVINFO hDeviceNotify1 = RegisterDeviceNotificationW(
hWnd, // events recipient
&NotificationFilter, // type of device
DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
);
if (!hDeviceNotify1) return FALSE;
hDeviceNotify.reset(hDeviceNotify1, &UnregisterDeviceNotification);
hRadio = h_sp;
return TRUE;
}
//Create a window to receive device change notification
HWND HardwareTransport_win_discovery::CreateMessageWindow()
{
static const wchar_t* class_name = L"ROBOTRACONTEUR_MESSAGE_WINDOW_CLASS";
WNDCLASSEXW wx = {};
wx.cbSize = sizeof(WNDCLASSEXW);
wx.lpfnWndProc = &HardwareTransport_win_discovery::WndProc; // function which will handle messages
wx.hInstance = NULL;
wx.lpszClassName = class_name;
if (!RegisterClassExW(&wx)) {
throw SystemResourceException("Could not initialize device update window");
}
HWND w=CreateWindowExW(0, class_name, L"rr_message_window", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, this);
if (!w)
{
throw SystemResourceException("Could not initialize device update window");
}
std::list<GUID> guids;
guids.push_back(GUID_DEVINTERFACE_RobotRaconteurUSBDriver);
guids.push_back(GUID_DEVINTERFACE_RobotRaconteurPCIDriver);
guids.push_back(GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver);
guids.push_back(GUID_DEVINTERFACE_RobotRaconteurWinUsbDevice);
guids.push_back(GUID_BTHPORT_DEVICE_INTERFACE);
BOOST_FOREACH(GUID& guid, guids)
{
HDEVNOTIFY hDeviceNotify;
if (!DoRegisterDeviceInterfaceToHwnd(&guid, w, &hDeviceNotify))
{
throw SystemResourceException("Could not initialize device update window");
}
this->hDeviceNotify.push_back(RR_SHARED_PTR<void>(hDeviceNotify, &UnregisterDeviceNotification));
}
RR_SHARED_PTR<void> bt_notify1;
RR_SHARED_PTR<void> bt_radio1;
if(DoRegisterBluetoothRadioToHwd(this->f, w, bt_notify1, bt_radio1))
{
hBtNotify.push_back(bt_notify1);
hBtNotify.push_back(bt_radio1);
}
return w;
}
void HardwareTransport_win_discovery::OnDeviceChanged_win(GUID guid, DWORD evt)
{
try
{
RR_SHARED_PTR<RobotRaconteurNode> n = GetParent()->GetNode();
RR_SHARED_PTR<ThreadPool> p = n->GetThreadPool();
if (IsEqualGUID(guid, GUID_BTHPORT_DEVICE_INTERFACE))
{
std::cout << "Got a refresh adapter notification" << std::endl;
hBtNotify.clear();
RR_SHARED_PTR<void> bt_notify1;
RR_SHARED_PTR<void> bt_radio1;
if (DoRegisterBluetoothRadioToHwd(this->f, m_Wnd, bt_notify1, bt_radio1))
{
hBtNotify.push_back(bt_notify1);
hBtNotify.push_back(bt_radio1);
}
return;
}
if (IsEqualGUID(guid, GUID_DEVINTERFACE_RobotRaconteurUSBDriver))
{
std::vector<NodeDiscoveryInfo> v1 = GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurUSBDriver, "rr+usb");
BOOST_FOREACH(NodeDiscoveryInfo& v2, v1)
{
n->NodeDetected(v2);
}
return;
}
if (IsEqualGUID(guid, GUID_DEVINTERFACE_RobotRaconteurPCIDriver))
{
std::vector<NodeDiscoveryInfo> v1 = GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurPCIDriver, "rr+pci");
BOOST_FOREACH(NodeDiscoveryInfo& v2, v1)
{
n->NodeDetected(v2);
}
return;
}
if (IsEqualGUID(guid, GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver))
{
std::vector<NodeDiscoveryInfo> v1 = GetDriverDevices1(&GUID_DEVINTERFACE_RobotRaconteurBluetoothDriver, "rr+bluetooth");
BOOST_FOREACH(NodeDiscoveryInfo& v2, v1)
{
n->NodeDetected(v2);
}
return;
}
if (IsEqualGUID(guid, GUID_DEVINTERFACE_RobotRaconteurWinUsbDevice))
{
GetUsbDevices(boost::bind(&HardwareTransport_win_discovery::OnDeviceChanged, shared_from_this(), RR_BOOST_PLACEHOLDERS(_1)));
return;
}
}
catch (std::exception&) {}
}
void HardwareTransport_win_discovery::OnBluetoothChanged_win(GUID guid, DWORD evt, PBYTE buf)
{
try
{
if (IsEqualGUID(guid, GUID_BLUETOOTH_RADIO_IN_RANGE))
{
SOCKADDR_BTH addr;
ZeroMemory(&addr, sizeof(addr));
addr.addressFamily = AF_BTH;
addr.btAddr = reinterpret_cast<PBTH_RADIO_IN_RANGE>(buf)->deviceInfo.address;
OnBluetoothChanged(addr);
return;
}
if (IsEqualGUID(guid, GUID_BLUETOOTH_RADIO_OUT_OF_RANGE))
{
SOCKADDR_BTH addr;
ZeroMemory(&addr, sizeof(addr));
addr.addressFamily = AF_BTH;
addr.btAddr = *reinterpret_cast<PBTH_ADDR>(buf);
return;
}
if (IsEqualGUID(guid, GUID_BLUETOOTH_HCI_EVENT))
{
SOCKADDR_BTH addr;
ZeroMemory(&addr, sizeof(addr));
addr.addressFamily = AF_BTH;
addr.btAddr = reinterpret_cast<PBTH_HCI_EVENT_INFO>(buf)->bthAddress;
OnBluetoothChanged(addr);
return;
}
}
catch (std::exception&) {}
}
void HardwareTransport_win_discovery::MessageWindowFunc()
{
try
{
boost::mutex::scoped_lock lock(this_lock);
if (!running) return;
m_Wnd = CreateMessageWindow();
MSG msg;
BOOL bRet;
while (true)
{
lock.unlock();
bRet = ::GetMessageW(&msg, m_Wnd, 0, 0);
lock.lock();
if (bRet == 0 || !running)
{
DestroyWindow(m_Wnd);
m_Wnd = NULL;
return;
}
if (bRet == -1)
{
throw SystemResourceException("Internal error in device update window");
}
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
catch (std::exception& err)
{
try
{
GetParent()->GetNode()->HandleException(&err);
}
catch (std::exception&) {}
return;
}
}
std::list<boost::tuple<NodeID, std::string> > HardwareTransport_win_find_deviceinterfaces(RR_SHARED_PTR<void> f, const GUID* interface_guid)
{
std::list<boost::tuple<NodeID, std::string> > o;
if (!f)
{
return o;
}
HDEVINFO deviceInfo;
RR_SHARED_PTR<void> deviceInfo_sp;
SP_DEVICE_INTERFACE_DATA interfaceData;
BOOL bResult;
RR_SHARED_PTR<SetupApi_Functions> f1 = RR_STATIC_POINTER_CAST<SetupApi_Functions>(f);
deviceInfo = f1->SetupDiGetClassDevsW(interface_guid,
NULL,
NULL,
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (deviceInfo == INVALID_HANDLE_VALUE) {
return o;
}
deviceInfo_sp = RR_SHARED_PTR<void>(deviceInfo_sp, f1->SetupDiDestroyDeviceInfoList);
interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
DWORD i = 0;
while (true)
{
bResult = f1->SetupDiEnumDeviceInterfaces(deviceInfo,
NULL,
&GUID_DEVINTERFACE_RobotRaconteurUSBDriver,
i,
&interfaceData);
i++;
if (!bResult)
{
if (GetLastError() == ERROR_NO_MORE_ITEMS)
{
break;
}
else
{
continue;
}
}
wchar_t property_buffer[256];
memset(property_buffer, 0, sizeof(property_buffer));
DEVPROPKEY nodename_key;
nodename_key.fmtid = GUID_PROPERTY_RobotRaconteurNodeName;
nodename_key.pid = 2;
DEVPROPTYPE proptype;
bResult = f1->SetupDiGetDeviceInterfacePropertyW(deviceInfo,
&interfaceData,
&nodename_key,
&proptype,
(PBYTE)property_buffer,
sizeof(property_buffer),
NULL, 0);
if (FALSE == bResult)
{
continue;
}
if (proptype != DEVPROP_TYPE_STRING)
{
continue;
}
std::wstring nodename2(property_buffer);
memset(property_buffer, 0, sizeof(property_buffer));
DEVPROPKEY nodeid_key;
nodeid_key.fmtid = GUID_PROPERTY_RobotRaconteurNodeID;
nodeid_key.pid = 2;
DEVPROPTYPE proptype2;
bResult = f1->SetupDiGetDeviceInterfacePropertyW(deviceInfo,
&interfaceData,
&nodeid_key,
&proptype2,
(PBYTE)property_buffer,
sizeof(property_buffer),
NULL, 0);
if (FALSE == bResult)
{
continue;
}
if (proptype2 != DEVPROP_TYPE_STRING)
{
continue;
}
std::wstring nodeid2_str(property_buffer);
try
{
std::string nodeid2_str1 = boost::locale::conv::utf_to_utf<char>(nodeid2_str);
NodeID nodeid2(nodeid2_str1);
std::string nodename2_2 = boost::locale::conv::utf_to_utf<char>(nodename2);
o.push_back(boost::make_tuple(nodeid2, nodename2_2));
}
catch (std::exception&) {}
}
return o;
}
}
} | 26.084302 | 356 | 0.745369 | [
"vector"
] |
09feb5724fc75011e5d1b07e05440b33df178abe | 8,231 | cpp | C++ | build/soccerwindow2-prefix/src/soccerwindow2-build/soccerwindow2_autogen/26NLMM5NFG/moc_main_window.cpp | temporaryforijcai/hfo-plus | b9f860c2cff48bea4a906609148710f9bea41792 | [
"MIT"
] | 1 | 2022-01-21T08:03:46.000Z | 2022-01-21T08:03:46.000Z | build/soccerwindow2-prefix/src/soccerwindow2-build/soccerwindow2_autogen/26NLMM5NFG/moc_main_window.cpp | temporaryforijcai/hfo-plus | b9f860c2cff48bea4a906609148710f9bea41792 | [
"MIT"
] | null | null | null | build/soccerwindow2-prefix/src/soccerwindow2-build/soccerwindow2_autogen/26NLMM5NFG/moc_main_window.cpp | temporaryforijcai/hfo-plus | b9f860c2cff48bea4a906609148710f9bea41792 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'main_window.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.7)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../soccerwindow2/src/qt4/main_window.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'main_window.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.7. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_MainWindow[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
47, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: signature, parameters, type, tag, flags
12, 11, 11, 11, 0x05,
// slots: signature, parameters, type, tag, flags
26, 11, 11, 11, 0x08,
36, 11, 11, 11, 0x08,
46, 11, 11, 11, 0x08,
62, 11, 11, 11, 0x08,
78, 11, 11, 11, 0x08,
88, 11, 11, 11, 0x08,
102, 11, 11, 11, 0x08,
119, 11, 11, 11, 0x08,
138, 11, 11, 11, 0x08,
158, 11, 11, 11, 0x08,
171, 11, 11, 11, 0x08,
185, 11, 11, 11, 0x08,
209, 201, 11, 11, 0x08,
235, 232, 11, 11, 0x08,
260, 11, 11, 11, 0x08,
292, 281, 11, 11, 0x08,
319, 11, 11, 11, 0x08,
335, 11, 11, 11, 0x08,
351, 11, 11, 11, 0x08,
369, 11, 11, 11, 0x08,
388, 11, 11, 11, 0x08,
411, 11, 11, 11, 0x08,
438, 430, 11, 11, 0x08,
456, 11, 11, 11, 0x08,
481, 11, 11, 11, 0x08,
505, 11, 11, 11, 0x08,
529, 11, 11, 11, 0x08,
552, 11, 11, 11, 0x08,
577, 232, 11, 11, 0x08,
601, 11, 11, 11, 0x08,
620, 11, 11, 11, 0x08,
638, 11, 11, 11, 0x08,
660, 11, 11, 11, 0x08,
668, 11, 11, 11, 0x08,
693, 688, 11, 11, 0x08,
713, 11, 11, 11, 0x08,
732, 11, 11, 11, 0x0a,
761, 755, 11, 11, 0x0a,
789, 11, 11, 11, 0x0a,
809, 805, 11, 11, 0x0a,
826, 805, 11, 11, 0x0a,
847, 805, 11, 11, 0x0a,
869, 755, 11, 11, 0x0a,
888, 11, 11, 11, 0x0a,
902, 11, 11, 11, 0x0a,
915, 11, 11, 11, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_MainWindow[] = {
"MainWindow\0\0viewUpdated()\0openRCG()\0"
"saveRCG()\0openDebugView()\0saveDebugView()\0"
"kickOff()\0setLiveMode()\0connectMonitor()\0"
"connectMonitorTo()\0disconnectMonitor()\0"
"killServer()\0startServer()\0restartServer()\0"
"command\0restartServer(QString)\0on\0"
"toggleDragMoveMode(bool)\0showLauncherDialog()\0"
"mode,point\0changePlayMode(int,QPoint)\0"
"toggleMenuBar()\0toggleToolBar()\0"
"toggleStatusBar()\0toggleFullScreen()\0"
"showPlayerTypeDialog()\0showDetailDialog()\0"
"checked\0changeStyle(bool)\0"
"showColorSettingDialog()\0"
"showFontSettingDialog()\0showMonitorMoveDialog()\0"
"showViewConfigDialog()\0showDebugMessageWindow()\0"
"toggleDebugServer(bool)\0startDebugServer()\0"
"stopDebugServer()\0showImageSaveDialog()\0"
"about()\0printShortcutKeys()\0size\0"
"resizeCanvas(QSize)\0saveImageAndQuit()\0"
"receiveMonitorPacket()\0point\0"
"updatePositionLabel(QPoint)\0dropBallThere()\0"
"pos\0dropBall(QPoint)\0freeKickLeft(QPoint)\0"
"freeKickRight(QPoint)\0movePlayer(QPoint)\0"
"moveObjects()\0yellowCard()\0redCard()\0"
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
MainWindow *_t = static_cast<MainWindow *>(_o);
switch (_id) {
case 0: _t->viewUpdated(); break;
case 1: _t->openRCG(); break;
case 2: _t->saveRCG(); break;
case 3: _t->openDebugView(); break;
case 4: _t->saveDebugView(); break;
case 5: _t->kickOff(); break;
case 6: _t->setLiveMode(); break;
case 7: _t->connectMonitor(); break;
case 8: _t->connectMonitorTo(); break;
case 9: _t->disconnectMonitor(); break;
case 10: _t->killServer(); break;
case 11: _t->startServer(); break;
case 12: _t->restartServer(); break;
case 13: _t->restartServer((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 14: _t->toggleDragMoveMode((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 15: _t->showLauncherDialog(); break;
case 16: _t->changePlayMode((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QPoint(*)>(_a[2]))); break;
case 17: _t->toggleMenuBar(); break;
case 18: _t->toggleToolBar(); break;
case 19: _t->toggleStatusBar(); break;
case 20: _t->toggleFullScreen(); break;
case 21: _t->showPlayerTypeDialog(); break;
case 22: _t->showDetailDialog(); break;
case 23: _t->changeStyle((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 24: _t->showColorSettingDialog(); break;
case 25: _t->showFontSettingDialog(); break;
case 26: _t->showMonitorMoveDialog(); break;
case 27: _t->showViewConfigDialog(); break;
case 28: _t->showDebugMessageWindow(); break;
case 29: _t->toggleDebugServer((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 30: _t->startDebugServer(); break;
case 31: _t->stopDebugServer(); break;
case 32: _t->showImageSaveDialog(); break;
case 33: _t->about(); break;
case 34: _t->printShortcutKeys(); break;
case 35: _t->resizeCanvas((*reinterpret_cast< const QSize(*)>(_a[1]))); break;
case 36: _t->saveImageAndQuit(); break;
case 37: _t->receiveMonitorPacket(); break;
case 38: _t->updatePositionLabel((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 39: _t->dropBallThere(); break;
case 40: _t->dropBall((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 41: _t->freeKickLeft((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 42: _t->freeKickRight((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 43: _t->movePlayer((*reinterpret_cast< const QPoint(*)>(_a[1]))); break;
case 44: _t->moveObjects(); break;
case 45: _t->yellowCard(); break;
case 46: _t->redCard(); break;
default: ;
}
}
}
const QMetaObjectExtraData MainWindow::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow,
qt_meta_data_MainWindow, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &MainWindow::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 47)
qt_static_metacall(this, _c, _id, _a);
_id -= 47;
}
return _id;
}
// SIGNAL 0
void MainWindow::viewUpdated()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}
QT_END_MOC_NAMESPACE
| 38.106481 | 125 | 0.585227 | [
"object"
] |
6708eef7de2e9539c5f88437eeddb3f29cccf4f5 | 17,635 | cpp | C++ | tests/MeshCostFunction.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | 1 | 2018-05-29T03:08:54.000Z | 2018-05-29T03:08:54.000Z | tests/MeshCostFunction.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | null | null | null | tests/MeshCostFunction.cpp | arpg/torch | 601ec64854008d97e39d2ca86ef4a93f79930967 | [
"Apache-2.0"
] | 1 | 2017-07-24T11:58:52.000Z | 2017-07-24T11:58:52.000Z | #include <gtest/gtest.h>
#include <torch/Torch.h>
namespace torch
{
namespace testing
{
TEST(MeshCostFunction, General)
{
std::shared_ptr<Scene> scene;
scene = std::make_shared<Scene>();
std::vector<Spectrum> albedos;
albedos.push_back(Spectrum::FromRGB(1, 1, 1));
albedos.push_back(Spectrum::FromRGB(1, 1, 1));
albedos.push_back(Spectrum::FromRGB(1, 1, 1));
std::vector<Point> vertices;
vertices.push_back(Point(0, 0, 0));
vertices.push_back(Point(0, 1, 0));
vertices.push_back(Point(1, 1, 0));
std::vector<Normal> normals;
normals.push_back(Normal(0, 0, -1));
normals.push_back(Normal(0, 0, -1));
normals.push_back(Normal(0, 0, -1));
std::vector<uint3> faces;
faces.push_back(make_uint3(0, 1, 2));
std::shared_ptr<Mesh> geometry;
geometry = scene->CreateMesh();
geometry->SetVertices(vertices);
geometry->SetNormals(normals);
geometry->SetFaces(faces);
std::shared_ptr<MatteMaterial> material;
material = scene->CreateMatteMaterial();
material->SetAlbedos(albedos);
std::shared_ptr<Primitive> primitive;
primitive = scene->CreatePrimitive();
primitive->SetGeometry(geometry);
primitive->SetMaterial(material);
primitive->SetPosition(0, 0, 1);
scene->Add(primitive);
std::shared_ptr<VoxelLight> light;
light = scene->CreateVoxelLight();
light->SetPosition(0, 0, -1);
light->SetDimensions(2, 2, 1);
light->SetVoxelSize(0.1);
light->SetRadiance(0.1, 0.1, 0.1);
light->SetRadiance(0, Spectrum::FromRGB(5, 5, 5));
scene->Add(light);
AlbedoBaker baker(scene);
// baker.SetSampleCount(10);
baker.SetSampleCount(128);
baker.Bake(material, geometry);
material->LoadAlbedos();
std::vector<Spectrum> new_colors;
material->GetAlbedos(new_colors);
for (const Spectrum& color : new_colors)
{
const Vector rgb = color.GetRGB();
std::cout << "Color: " << rgb.x << " " << rgb.y << " " << rgb.z << std::endl;
}
light->SetRadiance(0.1, 0.1, 0.1);
light->GetContext()->Compile();
MeshCostFunction* costFunction;
costFunction = new MeshCostFunction(light, geometry, material);
costFunction->SetMaxNeighborCount(3);
costFunction->SetMaxNeighborDistance(2.0f);
costFunction->SetSimilarityThreshold(0.0f);
costFunction->SetLightSampleCount(2048);
// costFunction->CreateJacobianMatrix();
// ASSERT_EQ(9, costFunction->GetResidualCount());
// float* parameters;
// LYNX_CHECK_CUDA(cudaMalloc(¶meters, sizeof(float) * 3 * light->GetVoxelCount()));
// lynx::Fill(parameters, 0.1, 3 * light->GetVoxelCount());
// float* residuals;
// LYNX_CHECK_CUDA(cudaMalloc(&residuals, sizeof(float) * 9));
// lynx::SetZeros(residuals, 9);
// float* gradient;
// LYNX_CHECK_CUDA(cudaMalloc(&gradient, sizeof(float) * 3 * light->GetVoxelCount()));
// lynx::SetZeros(gradient, 3 * light->GetVoxelCount());
// costFunction->Evaluate(¶meters, residuals, gradient);
// double cost = 0;
// for (size_t i = 0; i < 9; ++i)
// {
// const float value = lynx::Get(&residuals[i]);
// std::cout << "Residual " << i << ": " << value << std::endl;
// cost += value * value;
// }
// std::cout << std::endl;
// std::cout << "Cost: " << cost << std::endl;
// std::cout << std::endl;
// for (size_t i = 0; i < 3 * light->GetVoxelCount(); ++i)
// {
// std::cout << "Gradient " << i << ": " << lynx::Get(&gradient[i]) << std::endl;
// }
// std::cout << std::endl;
// std::cout << std::endl;
// lynx::Set(¶meters[0], 5);
// lynx::Set(¶meters[1], 5);
// lynx::Set(¶meters[2], 5);
// costFunction->Evaluate(¶meters, residuals, gradient);
// cost = 0;
// for (size_t i = 0; i < 9; ++i)
// {
// const float value = lynx::Get(&residuals[i]);
// std::cout << "Residual " << i << ": " << value << std::endl;
// cost += value * value;
// }
// std::cout << std::endl;
// std::cout << "Cost: " << cost << std::endl;
// std::cout << std::endl;
// for (size_t i = 0; i < 3 * light->GetVoxelCount(); ++i)
// {
// std::cout << "Gradient " << i << ": " << lynx::Get(&gradient[i]) << std::endl;
// }
optix::Buffer buffer = light->GetRadianceBuffer();
CUdeviceptr pointer = buffer->getDevicePointer(0);
float* values = reinterpret_cast<float*>(pointer);
lynx::Problem problem;
problem.AddParameterBlock(values, 3 * light->GetVoxelCount());
problem.SetLowerBound(values, 0.0f);
problem.AddResidualBlock(costFunction, nullptr, values);
// problem.CheckGradients();
lynx::Solver::Options options;
options.maxIterations = 10000;
options.minCostChangeRate = 1E-20;
lynx::Solver solver(&problem);
solver.Configure(options);
lynx::Solver::Summary summary;
solver.Solve(&summary);
std::cout << summary.BriefReport() << std::endl;
std::cout << std::endl;
for (size_t i = 0; i < light->GetVoxelCount(); ++i)
{
std::cout << "Voxel Value " << i << ": ";
std::cout << lynx::Get(values + 3 * i + 0) << " ";
std::cout << lynx::Get(values + 3 * i + 1) << " ";
std::cout << lynx::Get(values + 3 * i + 2) << std::endl;
}
std::cout << std::endl;
}
TEST(MeshCostFunction, Gradient)
{
std::vector<Spectrum> albedos;
std::vector<Point> vertices;
std::vector<Normal> normals;
std::vector<uint3> faces;
Spectrum albedo = Spectrum::FromRGB(0.8, 0.4, 0.4);
for (int x = -5; x < 5; ++x)
{
for (int y = -5; y < 5; ++y)
{
float xf = 0.5f * x;
float yf = 0.5f * y;
float zf = 2.0f - sqrtf(xf*xf + yf*yf) / 5.0;
Point p(xf, yf, zf);
Vector v = p - Point(0, 0, 5);
vertices.push_back(p);
normals.push_back(Normal(v));
albedos.push_back(albedo);
if (x < 4 && y < 4)
{
unsigned int c = (x + 5) * 11 + (y + 5);
unsigned int s = (x + 5) * 11 + (y + 6);
unsigned int e = (x + 6) * 11 + (y + 5);
unsigned int se = (x + 6) * 11 + (y + 6);
faces.push_back(make_uint3(c, s, se));
faces.push_back(make_uint3(c, se, e));
}
}
}
std::shared_ptr<Scene> scene;
scene = std::make_shared<Scene>();
std::shared_ptr<Mesh> geometry;
geometry = scene->CreateMesh();
geometry->SetVertices(vertices);
geometry->SetNormals(normals);
geometry->SetFaces(faces);
std::shared_ptr<MatteMaterial> material;
material = scene->CreateMatteMaterial();
material->SetAlbedos(albedos);
std::shared_ptr<Primitive> primitive;
primitive = scene->CreatePrimitive();
primitive->SetGeometry(geometry);
primitive->SetMaterial(material);
primitive->SetPosition(0, 0, 1);
scene->Add(primitive);
std::shared_ptr<VoxelLight> light;
light = scene->CreateVoxelLight();
light->SetPosition(0, 0, -2.5);
light->SetDimensions(2, 2, 1);
light->SetVoxelSize(2.0);
light->SetRadiance(0.50, 0.50, 0.50);
light->SetRadiance(0, Spectrum::FromRGB(10.3, 10.3, 10.3));
scene->Add(light);
AlbedoBaker baker(scene);
baker.SetSampleCount(10);
baker.Bake(material, geometry);
// light->SetRadiance(0, Spectrum::FromRGB(8.3, 8.3, 8.3));
light->GetContext()->Compile();
optix::Buffer buffer = light->GetRadianceBuffer();
CUdeviceptr pointer = buffer->getDevicePointer(0);
float* values = reinterpret_cast<float*>(pointer);
lynx::Problem problem;
problem.AddParameterBlock(values, 3 * light->GetVoxelCount());
problem.SetLowerBound(values, 0.0f);
MeshCostFunction* costFunction;
costFunction = new MeshCostFunction(light, geometry, material);
costFunction->SetMaxNeighborCount(5);
costFunction->SetMaxNeighborDistance(1.0f);
costFunction->SetSimilarityThreshold(0.0f);
costFunction->SetLightSampleCount(1000);
problem.AddResidualBlock(costFunction, nullptr, values);
problem.CheckGradients();
}
TEST(MeshCostFunction, Optimization)
{
std::vector<Spectrum> albedos;
std::vector<Point> vertices;
std::vector<Normal> normals;
std::vector<uint3> faces;
Spectrum albedo = Spectrum::FromRGB(0.8, 0.4, 0.4);
Spectrum albedo2 = Spectrum::FromRGB(0.4, 0.4, 0.8);
const float size = 5.0f;
const unsigned int resolution = 50;
const float stepSize = size / resolution;
const float origin = -size / 2.0;
for (unsigned int x = 0; x <= resolution; ++x)
{
for (unsigned int y = 0; y <= resolution; ++y)
{
float xf = origin + stepSize * x;
float yf = origin + stepSize * y;
float zf = 2.0f + sqrtf(xf*xf + yf*yf) / 5.0;
Point p(xf, yf, zf);
Vector n = p - Point(0, 0, 5);
vertices.push_back(p);
normals.push_back(Normal(n));
albedos.push_back((x < resolution / 2) ? albedo : albedo2);
if (x < resolution && y < resolution)
{
unsigned int c = (x + 0) * (resolution + 1) + (y + 0);
unsigned int s = (x + 0) * (resolution + 1) + (y + 1);
unsigned int e = (x + 1) * (resolution + 1) + (y + 0);
unsigned int se = (x + 1) * (resolution + 1) + (y + 1);
faces.push_back(make_uint3(c, s, se));
faces.push_back(make_uint3(c, se, e));
}
}
}
size_t ii = vertices.size();
vertices.push_back(Point(-0.5, -0.5, 0.8));
vertices.push_back(Point(-0.5, -1.5, 1.0));
vertices.push_back(Point(-1.5, -1.5, 1.0));
normals.push_back(Normal(0.0, 0.0, -1.0));
normals.push_back(Normal(0.0, 0.0, -1.0));
normals.push_back(Normal(0.0, 0.0, -1.0));
faces.push_back(make_uint3(ii + 0, ii + 1, ii + 2));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
ii = vertices.size();
std::shared_ptr<Scene> scene;
scene = std::make_shared<Scene>();
vertices.push_back(Point(-0.5, 0.2, 1.0));
vertices.push_back(Point(1.0, 0.0, 1.2));
vertices.push_back(Point(1.0, 1.0, 1.2));
normals.push_back(Normal(0.0, 0.0, -1.0));
normals.push_back(Normal(0.0, 0.0, -1.0));
normals.push_back(Normal(0.0, 0.0, -1.0));
faces.push_back(make_uint3(ii + 0, ii + 1, ii + 2));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
albedos.push_back(Spectrum::FromRGB(0.4, 0.8, 0.4));
std::shared_ptr<Mesh> geometry;
geometry = scene->CreateMesh();
geometry->SetVertices(vertices);
geometry->SetNormals(normals);
geometry->SetFaces(faces);
std::shared_ptr<MatteMaterial> material;
material = scene->CreateMatteMaterial();
material->SetAlbedos(albedos);
std::shared_ptr<Primitive> primitive;
primitive = scene->CreatePrimitive();
primitive->SetGeometry(geometry);
primitive->SetMaterial(material);
primitive->SetPosition(0, 0, 0);
scene->Add(primitive);
std::shared_ptr<VoxelLight> light;
light = scene->CreateVoxelLight();
light->SetPosition(0, 0, -3);
light->SetDimensions(9, 9, 9);
light->SetVoxelSize(1.0);
light->SetRadiance(1, 1, 1);
light->SetRadiance(0, Spectrum::FromRGB(100, 100, 100));
scene->Add(light);
std::shared_ptr<Camera> camera;
camera = scene->CreateCamera();
camera->SetPosition(0, 0, -2);
camera->SetImageSize(640, 480);
camera->SetFocalLength(320, 320);
camera->SetCenterPoint(320, 240);
camera->SetSampleCount(3);
Image image;
camera->CaptureAlbedo(image);
image.Save("image_01_groundtruth_albedo.png");
camera->CaptureLighting(image);
image.Save("image_02_groundtruth_lighting.png");
camera->Capture(image);
image.Save("image_03_render_with_groundtruth_lighting.png");
AlbedoBaker baker(scene);
baker.SetSampleCount(10);
baker.Bake(material, geometry);
material->LoadAlbedos();
// light->SetRadiance(0.01, 0.01, 0.01);
light->SetRadiance(0.001, 0.001, 0.001);
// light->SetRadiance(0, Spectrum::FromRGB(95, 95, 95));
light->GetContext()->Compile();
// light->SetRadiance(0, Spectrum::FromRGB(10, 10, 10));
// light->SetRadiance(24, Spectrum::FromRGB(100, 100, 100));
camera->CaptureAlbedo(image);
image.Save("image_04_initial_albedo.png");
camera->CaptureLighting(image);
image.Save("image_05_initial_lighting.png");
camera->Capture(image);
image.Save("image_06_render_with_initial_lighting.png");
material->GetAlbedos(albedos);
ShadingRemover remover2(geometry, material);
remover2.SetSampleCount(1000);
remover2.Remove();
camera->CaptureAlbedo(image);
image.Save("image_07_computed_albedos_with_initial_lighting.png");
material->SetAlbedos(albedos);
light->GetContext()->Compile();
optix::Buffer buffer = light->GetRadianceBuffer();
CUdeviceptr pointer = buffer->getDevicePointer(0);
float* values = reinterpret_cast<float*>(pointer);
// for (size_t i = 0; i < light->GetVoxelCount(); ++i)
// {
// std::cout << "Voxel Value " << i << ": ";
// std::cout << lynx::Get(values + 3 * i + 0) << " ";
// std::cout << lynx::Get(values + 3 * i + 1) << " ";
// std::cout << lynx::Get(values + 3 * i + 2) << std::endl;
// }
lynx::Problem problem;
problem.AddParameterBlock(values, 3 * light->GetVoxelCount());
problem.SetLowerBound(values, 0.0f);
MeshCostFunction* costFunction;
costFunction = new MeshCostFunction(light, geometry, material);
costFunction->SetMaxNeighborCount(25);
costFunction->SetMaxNeighborDistance(5.0f);
costFunction->SetSimilarityThreshold(0.0f);
costFunction->SetLightSampleCount(8196);
problem.AddResidualBlock(costFunction, nullptr, values);
// float cost;
// std::cout << "======== COST ========" << std::endl;
// std::cout << "======== COST ========" << std::endl;
// for (int i = 0; i < 1000; ++i)
// {
// lynx::Set(values + 0, 100.0f / (i / 1000.0f));
// lynx::Set(values + 1, 100.0f / (i / 1000.0f));
// lynx::Set(values + 2, 100.0f / (i / 1000.0f));
// problem.Evaluate(&cost, nullptr, nullptr);
// std::cout << cost << std::endl;
// }
// std::cout << "======== COST ========" << std::endl;
// std::cout << "======== COST ========" << std::endl;
// // VoxelActivationCostFunction* actFunction;
// // actFunction = new VoxelActivationCostFunction(light);
// // actFunction->SetBias(1.0);
// // actFunction->SetInnerScale(10.0);
// // actFunction->SetOuterScale(8.0);
// // problem.AddResidualBlock(actFunction, nullptr, values);
lynx::Solver::Options options;
options.maxIterations = 1000000;
options.minCostChangeRate = 1E-8;
options.verbose = true;
lynx::Solver solver(&problem);
solver.Configure(options);
lynx::Solver::Summary summary;
solver.Solve(&summary);
std::cout << summary.BriefReport() << std::endl;
std::cout << std::endl;
for (size_t i = 0; i < light->GetVoxelCount(); ++i)
{
printf("Voxel Value %04u: ", uint(i));
printf("%12.8f ", lynx::Get(values + 3 * i + 0));
printf("%12.8f ", lynx::Get(values + 3 * i + 1));
printf("%12.8f\n", lynx::Get(values + 3 * i + 2));
}
std::vector<Spectrum> rvalues(light->GetVoxelCount());
optix::Buffer radiance = light->GetRadianceBuffer();
Spectrum* device = reinterpret_cast<Spectrum*>(radiance->map());
std::copy(device, device + rvalues.size(), rvalues.data());
radiance->unmap();
light->SetRadiance(rvalues);
light->GetContext()->Compile();
// costFunction->ClearJacobian();
// solver.Solve(&summary);
// std::cout << summary.BriefReport() << std::endl;
// std::cout << std::endl;
// for (size_t i = 0; i < light->GetVoxelCount(); ++i)
// {
// printf("Voxel Value %04u: ", uint(i));
// printf("%12.8f ", lynx::Get(values + 3 * i + 0));
// printf("%12.8f ", lynx::Get(values + 3 * i + 1));
// printf("%12.8f\n", lynx::Get(values + 3 * i + 2));
// }
radiance = light->GetRadianceBuffer();
device = reinterpret_cast<Spectrum*>(radiance->map());
std::copy(device, device + rvalues.size(), rvalues.data());
radiance->unmap();
light->SetRadiance(rvalues);
camera->Capture(image);
image.Save("image_08_render_with_final_lighting_and_initial_albedos.png");
ShadingRemover remover(geometry, material);
remover.SetSampleCount(1000);
remover.Remove();
material->LoadAlbedos();
camera->CaptureAlbedo(image);
image.Save("image_09_computed_albedos_with_final_lighting.png");
const size_t floatCount = 640 * 480 * 3;
float* data = reinterpret_cast<float*>(image.GetData());
float max = 0;
for (size_t i = 0; i < floatCount; ++i)
{
if (data[i] > max) max = data[i];
}
for (size_t i = 0; i < floatCount; ++i)
{
data[i] /= max;
}
image.Save("image_10_scaled_albedos_with_final_lighting.png");
camera->CaptureLighting(image);
image.Save("image_11_final_lighting.png");
data = reinterpret_cast<float*>(image.GetData());
for (size_t i = 0; i < floatCount; ++i)
{
if (data[i] > max) max = data[i];
}
for (size_t i = 0; i < floatCount; ++i)
{
data[i] /= max;
}
image.Save("image_12_scaled_albedos_with_final_lighting.png");
camera->Capture(image);
image.Save("image_13_render_with_final_lighting_and_final_albedos.png");
// std::cout << std::endl;
// std::cout << std::endl;
// for (size_t i = 0; i < light->GetVoxelCount(); ++i)
// {
// const Vector rgb = rvalues[i].GetRGB();
// std::cout << rgb[0] << " ";
// std::cout << rgb[1] << " ";
// std::cout << rgb[2] << std::endl;
// }
// std::cout << std::endl;
// std::cout << std::endl;
// for (size_t i = 0; i < light->GetVoxelCount(); ++i)
// {
// printf("Voxel Value %04u: ", uint(i));
// printf("%12.8f ", lynx::Get(values + 3 * i + 0));
// printf("%12.8f ", lynx::Get(values + 3 * i + 1));
// printf("%12.8f\n", lynx::Get(values + 3 * i + 2));
// }
// ASSERT_TRUE(summary.solutionUsable && summary.finalCost < 1E-6);
}
} // namespace testing
} // namespace torch | 28.628247 | 90 | 0.62858 | [
"mesh",
"geometry",
"vector"
] |
e24dd5d911cb6a4a5a5524ab69d0fd51b05800bf | 10,245 | cpp | C++ | Firmware/PGR Telemetry Master/src/main.cpp | BOJIT/Greenpower-Datalogging-System | 7be925d2f3b5051376bcb11a48a87c1a57786016 | [
"MIT"
] | null | null | null | Firmware/PGR Telemetry Master/src/main.cpp | BOJIT/Greenpower-Datalogging-System | 7be925d2f3b5051376bcb11a48a87c1a57786016 | [
"MIT"
] | null | null | null | Firmware/PGR Telemetry Master/src/main.cpp | BOJIT/Greenpower-Datalogging-System | 7be925d2f3b5051376bcb11a48a87c1a57786016 | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "main.h"
#include <Wire.h>
#include "RTCLib.h"
#include <SPI.h>
#include <SD.h>
// this system uses a delimited text file system where data entries are separated by tabs (ASCII 009)
// define packet lengths for each variable
#define Voltage1_LEN 1
#define Voltage2_LEN 1
#define Current_LEN 1
#define RPM_LEN 2
#define Temp_LEN 2
#define GPSx_LEN 8
#define GPSy_LEN 8
#define Speed_LEN 8
#define Date_LEN 4
#define Time_LEN 4
// global pin definitions
#define RS485_State 5 // controls direction of data transfer on the RS485 Bus
#define Baud_Rate 9600
#define slave_timeout 200
#define Poll_Interval 500
#define Write_Interval 5000
// Master Address
const int Return_LEN = 32; // for now this number must be less than 60 to prevent a buffer overflow
// Text Arrays
const char Voltage[] = {86,111,108,116,97,103,101};
const char Current[] = {67,117,114,114,101,110,116};
const char Error[] = {45,45,45,45,45,69,82,82,79,82,33,45,45,45,45,45};
const char Problem[] = {45,45,45,45,80,82,79,66,76,69,77,33,45,45,45,45};
// global variables
uint8_t command_word = 0, LEN_1 = 0, LEN_2 = 0;
uint16_t Packet_LEN = 0;
unsigned long Prev_Poll;
unsigned long Prev_Write;
String filename;
// datalogging variables
uint8_t voltage1;
uint8_t voltage2;
uint8_t current;
uint16_t RPM;
uint16_t temperature;
double lattitde;
double longditude;
double speed;
uint32_t GPS_date;
uint32_t GPS_time;
union typeconv32to8 // setup a Union for type conversions (32 bit)
{
uint32_t LongVar;
uint8_t Bytes[4];
}
type32to8;
union typeconv64to8 // setup a Union for type conversions (64 bit)
{
double DoubleVar;
uint8_t Bytes[8];
}
type64to8;
RTC_DS1307 RTC; // create RTC object
// system states
typedef enum SYSTEM_STATE {
WORKING,
PROBLEM,
FATAL_ERROR
}
SystemState_t;
SystemState_t SystemState; // State Machine variable
File myFile; // create SD Object
void setup() {
//pinMode(LED_BUILTIN, OUTPUT); // debugging only
//digitalWrite(LED_BUILTIN, LOW);
// initialise RS485 Connection
pinMode(RS485_State, OUTPUT);
digitalWrite(RS485_State, LOW); // sets MAX485 to recieve data
delay(3000);
Serial.begin(Baud_Rate);
while (!SD.begin(4)) {
SystemState = FATAL_ERROR; // displays error message if SD is not inserted.
PollModule3();
}
PollModule3(); // grabs date from the GPS module
uint16_t year = GPS_date % 100;
uint8_t month = (GPS_date % 10000 - GPS_date %100)/100;
uint8_t day = (GPS_date - GPS_date % 10000)/10000;
uint8_t sec = (GPS_time % 10000)/100;
uint8_t min = (GPS_time % 1000000 - GPS_time % 10000)/10000;
uint8_t hour = (GPS_time - GPS_time % 1000000)/1000000;
RTC.begin();
// Check to see if the RTC is keeping time. If it is, load the time from your computer.
while (! RTC.isrunning()) {
SystemState = FATAL_ERROR; // displays error message if RTC is not responding.
PollModule3();
}
if(GPS_time != 0) {
RTC.adjust(DateTime(year, month, day, hour, min, sec));
}
DateTime now = RTC.now();
filename = String(now.day()) + "-" + String(now.month()) + "-" + String(now.year() - 2000) + ".TXT";
myFile = SD.open(filename, FILE_WRITE); // creates new text file with date string yy/mm/dd or accesses existing file
if (myFile) {
myFile.print("timeGPS");
myFile.write(9); // 'tab' in ASCII
myFile.print("RTC_Unix_Time");
myFile.write(9);
myFile.print("v1");
myFile.write(9);
myFile.print("v2");
myFile.write(9);
myFile.print("I");
myFile.write(9);
myFile.print("RPM");
myFile.write(9);
myFile.print("temp");
myFile.write(9);
myFile.print("lattitude");
myFile.write(9);
myFile.print("longditude");
myFile.write(9);
myFile.print("speed");
myFile.println();
myFile.close();
} else {
SystemState = FATAL_ERROR;
}
SystemState = WORKING;
}
void loop() {
if (millis() - Prev_Poll >= Poll_Interval) {
PollModule1();
delayMicroseconds(200);
PollModule2();
delayMicroseconds(200);
PollModule3();
delayMicroseconds(200);
Prev_Poll = millis();
}
SystemState = WORKING;
if (millis() - Prev_Write >= Write_Interval) {
myFile = SD.open(filename, FILE_WRITE); // creates new text file with date string yy/mm/dd or accesses existing file
DateTime now = RTC.now();
if (myFile) {
myFile.print(GPS_time/100);
myFile.write(9);
myFile.print(now.unixtime(), DEC);
myFile.write(9);
myFile.print(voltage1);
myFile.write(9);
myFile.print(voltage2);
myFile.write(9);
myFile.print(current);
myFile.write(9);
myFile.print(RPM);
myFile.write(9);
myFile.print(temperature);
myFile.write(9);
myFile.print(lattitde, 9);
myFile.write(9);
myFile.print(longditude, 9);
myFile.write(9);
myFile.print(speed, 4);
myFile.println();
myFile.close();
}
else {
SystemState = FATAL_ERROR;
}
Prev_Write = millis();
}
}
void PollModule1() {
digitalWrite(RS485_State, HIGH); // sets MAX485 to send data
Serial.write(0b00000001); // address write
Serial.write(0); // write out MSB (null)
Serial.write(0); // write out LSB (null)
Serial.flush(); // ensures tx buffer is empty before setting the MAX485 to listen
digitalWrite(RS485_State, LOW); // sets MAX485 to recieve data
Error_Routine();
}
void PollModule2() {
digitalWrite(RS485_State, HIGH); // sets MAX485 to send data
Serial.write(0b00000010); // address write
Serial.write(0); // write out MSB (null)
Serial.write(0); // write out LSB (null)
Serial.flush(); // ensures tx buffer is empty before setting the MAX485 to listen
digitalWrite(RS485_State, LOW); // sets MAX485 to recieve data
Error_Routine();
}
void PollModule3() {
digitalWrite(RS485_State, HIGH); // sets MAX485 to send data
Serial.write(0b00000011); // address write
Serial.write( (Return_LEN >> 8) ); // write out MSB
Serial.write(Return_LEN & 0xff); // write out LSB
LCD_Print(); // sends LCD bit array
Serial.flush(); // ensures tx buffer is empty before setting the MAX485 to listen
digitalWrite(RS485_State, LOW); // sets MAX485 to recieve data
Error_Routine();
}
void Error_Routine() {
bool status;
status = CheckResponse();
if(status == false) {
SystemState = PROBLEM;
}
delayMicroseconds(500);
}
int CheckResponse() {
unsigned long response_time = millis();
while(Serial.available() < 3) {
if (millis() - response_time >= slave_timeout) {
return false;
}
}
command_word = Serial.read(); // read first 3 command/length bits
LEN_1 = Serial.read();
LEN_2 = Serial.read();
Packet_LEN = LEN_1*256 + LEN_2; // combines LEN_1 and LEN_2
while(Serial.available() < LEN_2 ) {
// prevents the buffer being cleared before it is filled
}
ReadData(); // empties the current command from the serial buffer if no data is parsed
return true;
}
void ReadData() {
switch (command_word)
{
case 1: {
voltage1 = Serial.read();
voltage2 = Serial.read();
current = Serial.read();
for(;Packet_LEN > (Voltage1_LEN + Voltage2_LEN + Current_LEN); Packet_LEN--) {
Serial.read(); // reads any unused packet lengths (prevents buffer overflows)
}
}
break;
case 2: {
int highByte = Serial.read();
int lowByte = Serial.read();
RPM = highByte*256 + lowByte;
highByte = Serial.read();
lowByte = Serial.read();
temperature = highByte*256 + lowByte;
for(;Packet_LEN > (RPM_LEN + Temp_LEN); Packet_LEN--) {
Serial.read(); // reads any unused packet lengths (prevents buffer overflows)
}
}
break;
case 3: {
for (int i = 0; i < GPSy_LEN; i++) {
type64to8.Bytes[i] = Serial.read();
}
lattitde = type64to8.DoubleVar;
for (int i = 0; i < GPSx_LEN; i++) {
type64to8.Bytes[i] = Serial.read();
}
longditude = type64to8.DoubleVar;
for (int i = 0; i < Speed_LEN; i++) {
type64to8.Bytes[i] = Serial.read();
}
speed = type64to8.DoubleVar;
for (int i = 0; i < Date_LEN; i++) {
type32to8.Bytes[i] = Serial.read();
}
GPS_date = type32to8.LongVar;
for (int i = 0; i < Time_LEN; i++) {
type32to8.Bytes[i] = Serial.read();
}
GPS_time = type32to8.LongVar;
for(;Packet_LEN > (GPSx_LEN + GPSy_LEN + Speed_LEN + Date_LEN + Time_LEN); Packet_LEN--) {
Serial.read(); // reads any unused packet lengths (prevents buffer overflows)
}
}
break;
}
}
void LCD_Print() {
switch (SystemState)
{
case WORKING:
for (int i = 0; i < Return_LEN - 32; i++) { // shifts any leftover packets: room for extra expansion
Serial.write(83);
}
for (unsigned int i = 0; i < sizeof(Voltage)/sizeof(Voltage[0]); i++) {
Serial.write(Voltage[i]);
}
for (unsigned int i = 0; i < 16 - sizeof(Voltage)/sizeof(Voltage[0]); i++) {
Serial.write(32);
}
for (unsigned int i = 0; i < sizeof(Current)/sizeof(Current[0]); i++) {
Serial.write(Current[i]);
}
for (unsigned int i = 0; i < 16 - sizeof(Current)/sizeof(Current[0]); i++) {
Serial.write(32);
}
break;
case PROBLEM:
for (int i = 0; i < Return_LEN - 32; i++) { // shifts any leftover packets: room for extra expansion
Serial.write(85);
}
for (int i = 0; i < 16; i++) {
Serial.write(Problem[i]);
}
for (int i = 0; i < 16; i++) {
Serial.write(45);
}
break;
case FATAL_ERROR:
for (int i = 0; i < Return_LEN - 32; i++) { // shifts any leftover packets: room for extra expansion
Serial.write(85);
}
for (int i = 0; i < 16; i++) {
Serial.write(Error[i]);
}
for (int i = 0; i < 16; i++) {
Serial.write(45);
}
break;
}
} | 29.105114 | 123 | 0.615227 | [
"object"
] |
e253ff7c85add6ec552ccd2a35fc2b5615b7a6ae | 871 | cpp | C++ | src/quadrature/triangle_quadrature.cpp | annierhea/neon | 4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1 | [
"MIT"
] | null | null | null | src/quadrature/triangle_quadrature.cpp | annierhea/neon | 4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1 | [
"MIT"
] | null | null | null | src/quadrature/triangle_quadrature.cpp | annierhea/neon | 4eb51a06bda6bbf32c54fff8f39c9e02d429cfd1 | [
"MIT"
] | null | null | null |
#include "triangle_quadrature.hpp"
#include <algorithm>
namespace neon
{
triangle_quadrature::triangle_quadrature(point const p)
{
switch (p)
{
case point::one:
{
w = {1.0};
clist = {{0, 1.0 / 3.0, 1.0 / 3.0}};
break;
}
case point::three:
{
w = {1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0};
clist = {{0, 2.0 / 3.0, 1.0 / 6.0}, {1, 1.0 / 6.0, 2.0 / 3.0}, {2, 1.0 / 6.0, 1.0 / 6.0}};
break;
}
case point::four:
{
w = {-0.5625, 0.5208333333333333333333, 0.5208333333333333333333, 0.5208333333333333333333};
clist = {{0, 1.0 / 3.0, 1.0 / 3.0}, {1, 0.6, 0.2}, {2, 0.2, 0.6}, {3, 0.2, 0.2}};
break;
}
}
std::transform(begin(w), end(w), begin(w), [](auto const i) { return 0.5 * i; });
}
}
| 25.617647 | 104 | 0.437428 | [
"transform"
] |
e25625736301d19aa665f39e0daf335570331594 | 605 | cpp | C++ | Cube.cpp | PeterZhizhin/OpenGL3DShooter | 15e1160699c032307e82a965988f8c8550749b65 | [
"Apache-2.0"
] | null | null | null | Cube.cpp | PeterZhizhin/OpenGL3DShooter | 15e1160699c032307e82a965988f8c8550749b65 | [
"Apache-2.0"
] | 1 | 2015-07-07T15:29:06.000Z | 2015-07-07T15:29:06.000Z | Cube.cpp | PeterZhizhin/OpenGL3DShooter | 15e1160699c032307e82a965988f8c8550749b65 | [
"Apache-2.0"
] | null | null | null | #include "Cube.h"
#include <vector>
#include <iostream>
const std::vector<VertexData> Cube::getVertecies()
{
std::cout << "Creating vertecies" << std::endl;
std::vector<VertexData> result;
VertexData vertex;
result.reserve(3);
vertex.setVertex(-1.0f,-1.0f,0.0f);
vertex.print();
result.push_back(vertex);
vertex.setVertex(1.0f, -1.0f, 0.0f);
vertex.print();
result.push_back(vertex);
vertex.setVertex(0.0f,1.0f,0.0f);
vertex.print();
result.push_back(vertex);
std::cout << "Cube vertecies created" << std::endl;
return result;
}
Cube::Cube() : VertexArray(Cube::getVertecies())
{
}
| 18.333333 | 52 | 0.68595 | [
"vector"
] |
e25ea3d804e900b4e36b1a6d810ab3a794fce816 | 1,519 | cpp | C++ | hackerrank/components-in-graph.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 3 | 2020-06-25T21:04:02.000Z | 2021-05-12T03:33:19.000Z | hackerrank/components-in-graph.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | null | null | null | hackerrank/components-in-graph.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 1 | 2020-06-25T21:04:06.000Z | 2020-06-25T21:04:06.000Z | // Author: btjanaka (Bryon Tjanaka)
// Problem: (HackerRank) components-in-graph
// Title: Components in a Graph
// Link: https://www.hackerrank.com/challenges/components-in-graph/problem
// Idea: Use a union find to figure out which nodes get connected, then count
// the sizes of all the components.
// Difficulty: medium
// Tags: union-find
#include <bits/stdc++.h>
#define GET(x) scanf("%d", &x)
#define GED(x) scanf("%lf", &x)
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
struct UnionFind {
vector<int> parent, ranks, sizes;
UnionFind(int n) : parent(n), ranks(n, 0), sizes(n, 1) {
iota(parent.begin(), parent.end(), 0);
}
int find(int i) { return i == parent[i] ? i : (parent[i] = find(parent[i])); }
void join(int i, int j) {
int x = find(i), y = find(j);
if (x != y) {
if (ranks[x] > ranks[y]) {
sizes[x] += sizes[y];
parent[y] = x;
} else {
if (ranks[x] == ranks[y]) {
++ranks[y];
}
parent[x] = y;
sizes[y] += sizes[x];
}
}
}
};
int main() {
int n, n2;
GET(n);
n2 = 2 * n;
UnionFind uf(n2);
for (int e = 0; e < n; ++e) {
int i, j;
GET(i);
GET(j);
--i;
--j;
uf.join(i, j);
}
int mx = INT_MIN, mn = INT_MAX;
for (int i = 0; i < n2; ++i) {
if (uf.sizes[i] != 1 && uf.parent[i] == i) {
mx = max(mx, uf.sizes[i]);
mn = min(mn, uf.sizes[i]);
}
}
cout << mn << " " << mx << endl;
return 0;
}
| 22.671642 | 80 | 0.529954 | [
"vector"
] |
e2645a5f46209c59669a72ae9a1aad9c2075fb35 | 11,056 | cc | C++ | third_party/blink/renderer/core/paint/svg_paint_context.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/paint/svg_paint_context.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/paint/svg_paint_context.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2007, 2008 Rob Buis <buis@kde.org>
* Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
* Copyright (C) 2009 Google, Inc. All rights reserved.
* Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
* Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/paint/svg_paint_context.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_masker.h"
#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources.h"
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/core/paint/svg_mask_painter.h"
namespace blink {
SVGPaintContext::~SVGPaintContext() {
if (filter_) {
DCHECK(SVGResourcesCache::CachedResourcesForLayoutObject(object_));
DCHECK(
SVGResourcesCache::CachedResourcesForLayoutObject(object_)->Filter() ==
filter_);
DCHECK(filter_recording_context_);
SVGFilterPainter(*filter_).FinishEffect(object_,
*filter_recording_context_);
// Reset the paint info after the filter effect has been completed.
filter_paint_info_ = nullptr;
}
if (masker_) {
DCHECK(SVGResourcesCache::CachedResourcesForLayoutObject(object_));
DCHECK(
SVGResourcesCache::CachedResourcesForLayoutObject(object_)->Masker() ==
masker_);
SVGMaskPainter(*masker_).FinishEffect(object_, GetPaintInfo().context);
}
}
bool SVGPaintContext::ApplyClipMaskAndFilterIfNecessary() {
#if DCHECK_IS_ON()
DCHECK(!apply_clip_mask_and_filter_if_necessary_called_);
apply_clip_mask_and_filter_if_necessary_called_ = true;
#endif
// In SPv2 we should early exit once the paint property state has been
// applied, because all meta (non-drawing) display items are ignored in
// SPv2. However we can't simply omit them because there are still
// non-composited painting (e.g. SVG filters in particular) that rely on
// these meta display items.
ApplyPaintPropertyState();
// When rendering clip paths as masks, only geometric operations should be
// included so skip non-geometric operations such as compositing, masking, and
// filtering.
if (GetPaintInfo().IsRenderingClipPathAsMaskImage()) {
DCHECK(!object_.IsSVGRoot());
ApplyClipIfNecessary();
return true;
}
bool is_svg_root = object_.IsSVGRoot();
// Layer takes care of root opacity and blend mode.
if (is_svg_root) {
DCHECK(!(object_.IsTransparent() || object_.StyleRef().HasBlendMode()) ||
object_.HasLayer());
} else {
ApplyCompositingIfNecessary();
}
if (is_svg_root) {
DCHECK(!object_.StyleRef().ClipPath() || object_.HasLayer());
} else {
ApplyClipIfNecessary();
}
SVGResources* resources =
SVGResourcesCache::CachedResourcesForLayoutObject(object_);
if (!ApplyMaskIfNecessary(resources))
return false;
if (is_svg_root) {
DCHECK(!object_.StyleRef().HasFilter() || object_.HasLayer());
} else if (!ApplyFilterIfNecessary(resources)) {
return false;
}
if (!IsIsolationInstalled() &&
SVGLayoutSupport::IsIsolationRequired(&object_)) {
compositing_recorder_ = std::make_unique<CompositingRecorder>(
GetPaintInfo().context, object_, SkBlendMode::kSrcOver, 1);
}
return true;
}
void SVGPaintContext::ApplyPaintPropertyState() {
if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled())
return;
// SVGRoot works like normal CSS replaced element and its effects are
// applied as stacking context effect by PaintLayerPainter.
if (object_.IsSVGRoot())
return;
const auto* fragment = GetPaintInfo().FragmentToPaint(object_);
if (!fragment)
return;
const auto* properties = fragment->PaintProperties();
// MaskClip() implies Effect(), thus we don't need to check MaskClip().
if (!properties || (!properties->Effect() && !properties->ClipPathClip()))
return;
auto& paint_controller = GetPaintInfo().context.GetPaintController();
PropertyTreeState state = paint_controller.CurrentPaintChunkProperties();
if (const auto* effect = properties->Effect())
state.SetEffect(effect);
if (const auto* mask_clip = properties->MaskClip())
state.SetClip(mask_clip);
else if (const auto* clip_path_clip = properties->ClipPathClip())
state.SetClip(clip_path_clip);
scoped_paint_chunk_properties_.emplace(
paint_controller, state, object_,
DisplayItem::PaintPhaseToSVGEffectType(GetPaintInfo().phase));
}
void SVGPaintContext::ApplyCompositingIfNecessary() {
DCHECK(!GetPaintInfo().IsRenderingClipPathAsMaskImage());
const ComputedStyle& style = object_.StyleRef();
float opacity = style.Opacity();
BlendMode blend_mode = style.HasBlendMode() && object_.IsBlendingAllowed()
? style.GetBlendMode()
: BlendMode::kNormal;
if (opacity < 1 || blend_mode != BlendMode::kNormal) {
const FloatRect compositing_bounds =
object_.VisualRectInLocalSVGCoordinates();
compositing_recorder_ = std::make_unique<CompositingRecorder>(
GetPaintInfo().context, object_,
WebCoreCompositeToSkiaComposite(kCompositeSourceOver, blend_mode),
opacity, &compositing_bounds);
}
}
void SVGPaintContext::ApplyClipIfNecessary() {
if (object_.StyleRef().ClipPath())
clip_path_clipper_.emplace(GetPaintInfo().context, object_, LayoutPoint());
}
bool SVGPaintContext::ApplyMaskIfNecessary(SVGResources* resources) {
if (LayoutSVGResourceMasker* masker =
resources ? resources->Masker() : nullptr) {
if (!SVGMaskPainter(*masker).PrepareEffect(object_, GetPaintInfo().context))
return false;
masker_ = masker;
}
return true;
}
static bool HasReferenceFilterOnly(const ComputedStyle& style) {
if (!style.HasFilter())
return false;
const FilterOperations& operations = style.Filter();
if (operations.size() != 1)
return false;
return operations.at(0)->GetType() == FilterOperation::REFERENCE;
}
bool SVGPaintContext::ApplyFilterIfNecessary(SVGResources* resources) {
if (!resources)
return !HasReferenceFilterOnly(object_.StyleRef());
LayoutSVGResourceFilter* filter = resources->Filter();
if (!filter)
return true;
filter_recording_context_ =
std::make_unique<SVGFilterRecordingContext>(GetPaintInfo().context);
filter_ = filter;
GraphicsContext* filter_context = SVGFilterPainter(*filter).PrepareEffect(
object_, *filter_recording_context_);
if (!filter_context)
return false;
// Because the filter needs to cache its contents we replace the context
// during filtering with the filter's context.
filter_paint_info_ =
std::make_unique<PaintInfo>(*filter_context, paint_info_);
// Because we cache the filter contents and do not invalidate on paint
// invalidation rect changes, we need to paint the entire filter region
// so elements outside the initial paint (due to scrolling, etc) paint.
filter_paint_info_->cull_rect_.rect_ = LayoutRect::InfiniteIntRect();
return true;
}
bool SVGPaintContext::IsIsolationInstalled() const {
// In SPv175+ isolation is modeled by effect nodes, and will be applied by
// PaintArtifactCompositor or PaintChunksToCcLayer depends on compositing
// state.
if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled())
return true;
if (compositing_recorder_)
return true;
if (masker_ || filter_)
return true;
if (clip_path_clipper_ && clip_path_clipper_->IsIsolationInstalled())
return true;
return false;
}
void SVGPaintContext::PaintResourceSubtree(GraphicsContext& context,
const LayoutObject* item) {
DCHECK(item);
DCHECK(!item->NeedsLayout());
PaintInfo info(context, LayoutRect::InfiniteIntRect(),
PaintPhase::kForeground, kGlobalPaintNormalPhase,
kPaintLayerPaintingRenderingResourceSubtree);
item->Paint(info, IntPoint());
}
bool SVGPaintContext::PaintForLayoutObject(
const PaintInfo& paint_info,
const ComputedStyle& style,
const LayoutObject& layout_object,
LayoutSVGResourceMode resource_mode,
PaintFlags& flags,
const AffineTransform* additional_paint_server_transform) {
if (paint_info.IsRenderingClipPathAsMaskImage()) {
if (resource_mode == kApplyToStrokeMode)
return false;
flags.setColor(SK_ColorBLACK);
flags.setShader(nullptr);
return true;
}
SVGPaintServer paint_server = SVGPaintServer::RequestForLayoutObject(
layout_object, style, resource_mode);
if (!paint_server.IsValid())
return false;
if (additional_paint_server_transform && paint_server.IsTransformDependent())
paint_server.PrependTransform(*additional_paint_server_transform);
const SVGComputedStyle& svg_style = style.SvgStyle();
float alpha = resource_mode == kApplyToFillMode ? svg_style.FillOpacity()
: svg_style.StrokeOpacity();
paint_server.ApplyToPaintFlags(flags, alpha);
// We always set filter quality to 'low' here. This value will only have an
// effect for patterns, which are SkPictures, so using high-order filter
// should have little effect on the overall quality.
flags.setFilterQuality(kLow_SkFilterQuality);
// TODO(fs): The color filter can set when generating a picture for a mask -
// due to color-interpolation. We could also just apply the
// color-interpolation property from the the shape itself (which could mean
// the paintserver if it has it specified), since that would be more in line
// with the spec for color-interpolation. For now, just steal it from the GC
// though.
// Additionally, it's not really safe/guaranteed to be correct, as
// something down the flags pipe may want to farther tweak the color
// filter, which could yield incorrect results. (Consider just using
// saveLayer() w/ this color filter explicitly instead.)
flags.setColorFilter(sk_ref_sp(paint_info.context.GetColorFilter()));
return true;
}
} // namespace blink
| 38.124138 | 82 | 0.72974 | [
"shape"
] |
e265638c714213253694a4714f540b26ff06d5e1 | 8,494 | cpp | C++ | core/es/graphics/image/png/PngFileDecoder.cpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | null | null | null | core/es/graphics/image/png/PngFileDecoder.cpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | 1 | 2016-10-25T02:09:00.000Z | 2016-11-10T02:07:59.000Z | core/es/graphics/image/png/PngFileDecoder.cpp | eaglesakura/protoground | 2cd7eaf93eaab9a34619b7ded91d3a2b89e9d5d6 | [
"MIT"
] | null | null | null | #include "PngFileDecoder.h"
#include <png.h>
#include "es/internal/protoground-internal.hpp"
#include "es/graphics/image/IImageDecodeCallback.hpp"
#include "es/math/Math.hpp"
namespace es {
PngFileDecoder::PngFileDecoder() {
}
PngFileDecoder::~PngFileDecoder() {
}
namespace internal {
struct ImageBufferReader {
unsafe_array<uint8_t> preLoad;
sp<IAsset> asset;
bool readError = false;
/**
* バッファを読み出す
*/
bool loadBuffer(uint8_t *result, unsigned length) {
if (preLoad) {
// 読み込み可能な長さ分だけ読み込む
int read = std::min(preLoad.length, (int) length);
memcpy(result, preLoad.ptr, read);
// 読み込んだ分だけオフセットして、残りの長さを縮める
result += read;
preLoad += read;
length -= read;
}
// アセットから必要な長さを読み出す
if (length) {
unsafe_array<uint8_t> buffer = asset->read(length);
if (buffer.length < (int)length) {
// 容量が足りない!
memcpy(result, buffer.ptr, buffer.length);
readError = true;
return false;
} else {
assert(buffer.length == length);
// 十分な容量を読み込めた
memcpy(result, buffer.ptr, length);
}
}
return true;
}
};
}
static void pngReadBuffer(png_structp png, png_bytep result, png_size_t readSize) {
// eslog("PNG read request(%d bytes)", readSize);
internal::ImageBufferReader *reader = (internal::ImageBufferReader *) png_get_io_ptr(png);
if (!reader->loadBuffer((uint8_t *) result, (unsigned)readSize)) {
eslog("PNG BufferOver!!");
}
}
bool PngFileDecoder::load(std::shared_ptr<IAsset> asset, selection_ptr<IImageDecodeCallback> listener) {
IImageDecodeCallback::ImageInfo info;
info.dstPixelFormat = pixelConvert;
internal::ImageBufferReader reader;
reader.asset = asset;
reader.preLoad = unsafe_array<uint8_t>(readedBuffer.get(), readedBuffer.length());
struct PngData {
png_structp png = nullptr;
png_infop info = nullptr;
~PngData() {
png_destroy_read_struct(&png, &info, nullptr);
assert(!png);
assert(!info);
}
} data;
// PNG初期化
// TODO Error Handleを確定させる
// TODO 途中キャンセル時のメモリ管理
data.png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
assert(data.png);
data.info = png_create_info_struct(data.png);
assert(data.info);
if (setjmp(png_jmpbuf(data.png))) {
eslog("setjmp failed");
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_FormatError);
return false;
}
png_set_read_fn(data.png, (void *) (&reader), pngReadBuffer);
// info
png_read_info(data.png, data.info);
// 読み込みに必要なテンポラリを生成する
info.srcWidth = png_get_image_width(data.png, data.info);
info.srcHeight = png_get_image_height(data.png, data.info);
info.format = IImageDecodeCallback::ImageFormat_PNG;
int depth = png_get_bit_depth(data.png, data.info);
int rowBytes = png_get_rowbytes(data.png, data.info);
int perPixelBytes = rowBytes / info.srcWidth;
{
if (!info.srcWidth || !info.srcHeight) {
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_FormatError);
return false;
}
eslog("PNG [%d x %d] %d bits = %d bytes/pixel [row = %d bytes]", info.srcWidth, info.srcHeight, depth, perPixelBytes, rowBytes);
eslog("PNG read[%d] Once Lines", onceReadLines);
if (depth == 8) {
if (perPixelBytes == 3) {
info.srcPixelFormat = PixelFormat_RGB888;
} else if (perPixelBytes == 4) {
info.srcPixelFormat = PixelFormat_RGBA8888;
} else {
eslog("Not Support PNG depth bits...");
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_FormatError);
return false;
}
} else {
eslog("Not Support PNG depth bits...");
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_FormatError);
return false;
}
if (convertPot) {
info.dstWidth = toPowerOfTwo(info.srcWidth);
info.dstHeight = toPowerOfTwo(info.srcHeight);
} else {
info.dstWidth = info.srcWidth;
info.dstHeight = info.srcHeight;
}
// インフォメーションをコールバックする
listener->onImageInfoDecoded(&info);
}
// 一度に読み込む行数を確定する
int onceReadLines = std::min((int) info.srcHeight, (int) this->onceReadLines);
if (onceReadLines == 0) {
onceReadLines = info.srcHeight;
}
std::vector<uint8_t> readCacheBuffer;
ByteBuffer convertBuffer;
if (info.srcPixelFormat != this->pixelConvert) {
// 変換先の画素を生成する
convertBuffer = Pixel::createPixelBuffer(pixelConvert, Pixel::getPixelBytes(pixelConvert) * info.dstWidth * onceReadLines);
}
std::vector<void *> rowHeaders(onceReadLines);
if (convertBuffer.empty()) {
// 変換予定の無い場合は隙間設定をしながら取得する
util::valloc(&readCacheBuffer, perPixelBytes * info.dstWidth * onceReadLines, false);
for (int i = 0; i < onceReadLines; ++i) {
rowHeaders[i] = (void *) util::asPointer(readCacheBuffer, (perPixelBytes * info.dstWidth) * i);
}
} else {
// 変換予定の場合は隙間なくバッファを取得して変換用メモリも設定する
util::valloc(&readCacheBuffer, perPixelBytes * info.srcWidth * onceReadLines, false);
for (int i = 0; i < onceReadLines; ++i) {
rowHeaders[i] = (void *) util::asPointer(readCacheBuffer, (perPixelBytes * info.srcWidth) * i);
}
}
int lines = info.srcHeight;
while (lines) {
uint32_t reading = std::min((uint32_t) lines, (uint32_t) onceReadLines);
// eslog("PNG read[%d] Lines", reading);
png_read_rows(data.png, NULL, (png_bytepp) util::asPointer(rowHeaders), reading);
lines -= reading;
if (reader.readError) {
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_IOError);
return false;
} else if (listener->isImageDecodeCancel()) {
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_Canceled);
return false;
}
// バッファをリスナに伝える
if (convertBuffer.empty()) {
listener->onImageLineDecoded(&info, unsafe_array<uint8_t>(util::asPointer(readCacheBuffer), reading * rowBytes), reading);
} else {
// eslog("PNG Convert[%d] -> [%d]", info.srcPixelFormat, pixelConvert);
if (info.srcPixelFormat == PixelFormat_RGB888) {
Pixel::copyRGB888Pixels(
util::asPointer(readCacheBuffer),
pixelConvert, convertBuffer.get(),
info.srcWidth, reading, info.dstWidth
);
} else if (info.srcPixelFormat == PixelFormat_RGBA8888) {
Pixel::copyRGBA8888Pixels(
util::asPointer(readCacheBuffer),
pixelConvert, convertBuffer.get(),
info.srcWidth, reading, info.dstWidth
);
} else {
eslog("PNG Convert not support...");
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_FormatError);
return false;
}
listener->onImageLineDecoded(&info, unsafe_array<uint8_t>(convertBuffer.get(), perPixelBytes * info.dstWidth * reading), reading);
}
}
listener->onImageDecodeFinished(&info, IImageDecodeCallback::ImageDecodeResult_Success);
return true;
}
void PngFileDecoder::setReadedBuffer(const unsafe_array<uint8_t> &buffer) {
this->readedBuffer = Buffer::clone(buffer);
}
void PngFileDecoder::setOnceReadHeight(const unsigned heightPixels) {
this->onceReadLines = heightPixels;
}
void PngFileDecoder::setConvertPixelFormat(const PixelFormat_e format) {
this->pixelConvert = format;
}
void PngFileDecoder::setConvertPot(bool set) {
this->convertPot = set;
}
bool PngFileDecoder::isPngFile(const unsafe_array<uint8_t> &sign) {
if (png_sig_cmp(sign.ptr, 0, sign.length)) {
eslog("png_sig_cmp failed");
return false;
} else {
return true;
}
}
} | 33.840637 | 142 | 0.615493 | [
"vector"
] |
e292f3e0ee00bdf7857f22c7287e2171c410d568 | 3,472 | cc | C++ | chrome/browser/ui/search/search_model_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/search/search_model_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/search/search_model_unittest.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/search/search_model.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "chrome/browser/ui/search/search_model_observer.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/search/search_types.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
namespace {
class MockSearchModelObserver : public SearchModelObserver {
public:
MockSearchModelObserver();
~MockSearchModelObserver() override;
void ModelChanged(const SearchMode& old_mode,
const SearchMode& new_mode) override;
void VerifySearchModelStates(const SearchMode& expected_old_mode,
const SearchMode& expected_new_mode);
void VerifyNotificationCount(int expected_count);
private:
// How many times we've seen search model changed notifications.
int modelchanged_notification_count_;
SearchMode actual_old_mode_;
SearchMode actual_new_mode_;
DISALLOW_COPY_AND_ASSIGN(MockSearchModelObserver);
};
MockSearchModelObserver::MockSearchModelObserver()
: modelchanged_notification_count_(0) {
}
MockSearchModelObserver::~MockSearchModelObserver() {
}
void MockSearchModelObserver::ModelChanged(const SearchMode& old_mode,
const SearchMode& new_mode) {
actual_old_mode_ = old_mode;
actual_new_mode_ = new_mode;
modelchanged_notification_count_++;
}
void MockSearchModelObserver::VerifySearchModelStates(
const SearchMode& expected_old_mode,
const SearchMode& expected_new_mode) {
EXPECT_TRUE(actual_old_mode_ == expected_old_mode);
EXPECT_TRUE(actual_new_mode_ == expected_new_mode);
}
void MockSearchModelObserver::VerifyNotificationCount(int expected_count) {
EXPECT_EQ(modelchanged_notification_count_, expected_count);
}
} // namespace
class SearchModelTest : public ChromeRenderViewHostTestHarness {
public:
void SetUp() override;
void TearDown() override;
MockSearchModelObserver mock_observer;
SearchModel* model;
};
void SearchModelTest::SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
SearchTabHelper::CreateForWebContents(web_contents());
SearchTabHelper* search_tab_helper =
SearchTabHelper::FromWebContents(web_contents());
ASSERT_TRUE(search_tab_helper != NULL);
model = search_tab_helper->model();
model->AddObserver(&mock_observer);
}
void SearchModelTest::TearDown() {
model->RemoveObserver(&mock_observer);
ChromeRenderViewHostTestHarness::TearDown();
}
TEST_F(SearchModelTest, UpdateSearchModelMode) {
mock_observer.VerifyNotificationCount(0);
SearchMode search_mode(SearchMode::MODE_NTP, SearchMode::ORIGIN_NTP);
SearchMode expected_old_mode = model->mode();
SearchMode expected_new_mode = search_mode;
model->SetMode(search_mode);
mock_observer.VerifySearchModelStates(expected_old_mode, expected_new_mode);
mock_observer.VerifyNotificationCount(1);
search_mode.mode = SearchMode::MODE_SEARCH_SUGGESTIONS;
expected_old_mode = expected_new_mode;
expected_new_mode = search_mode;
model->SetMode(search_mode);
mock_observer.VerifySearchModelStates(expected_old_mode, expected_new_mode);
mock_observer.VerifyNotificationCount(2);
EXPECT_TRUE(model->mode() == expected_new_mode);
}
| 32.148148 | 78 | 0.78197 | [
"model"
] |
e297724bf2dff5361f914f249b88cfbc4f7a780e | 1,706 | hpp | C++ | src/libs/ast/factory.hpp | jdmclark/gorc | a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8 | [
"Apache-2.0"
] | 97 | 2015-02-24T05:09:24.000Z | 2022-01-23T12:08:22.000Z | src/libs/ast/factory.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 8 | 2015-03-27T23:03:23.000Z | 2020-12-21T02:34:33.000Z | src/libs/ast/factory.hpp | annnoo/gorc | 1889b4de6380c30af6c58a8af60ecd9c816db91d | [
"Apache-2.0"
] | 10 | 2016-03-24T14:32:50.000Z | 2021-11-13T02:38:53.000Z | #pragma once
#include "node.hpp"
#include <memory>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace gorc {
class ast_factory {
private:
class factory_factory {
public:
virtual ~factory_factory();
};
template <typename NodeT>
class factory_factory_impl : public factory_factory {
private:
std::vector<std::unique_ptr<NodeT>> nodes;
public:
template <typename ...ArgT>
NodeT* emplace(ArgT &&...args)
{
nodes.emplace_back(std::make_unique<NodeT>(std::forward<ArgT>(args)...));
return nodes.back().get();
}
};
std::unordered_map<std::type_index, std::unique_ptr<factory_factory>> factories;
template <typename NodeT>
factory_factory_impl<NodeT>& get_factory()
{
auto it = factories.find(typeid(NodeT));
if(it == factories.end()) {
it = factories.emplace(std::type_index(typeid(NodeT)),
std::make_unique<factory_factory_impl<NodeT>>()).first;
}
return *reinterpret_cast<factory_factory_impl<NodeT>*>(it->second.get());
}
public:
template <typename NodeT, typename ...ArgT>
NodeT* make(ArgT &&...args)
{
return get_factory<NodeT>().emplace(std::forward<ArgT>(args)...);
}
template <typename VariantT, typename NodeT, typename ...ArgT>
VariantT* make_var(ArgT &&...args)
{
return get_factory<VariantT>().emplace(make<NodeT>(std::forward<ArgT>(args)...));
}
};
}
| 27.967213 | 94 | 0.552169 | [
"vector"
] |
e29a7bce3518a6f0754787a10ecbf481ca34cfc3 | 10,572 | cc | C++ | content/renderer/browser_plugin/browser_plugin_bindings.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/browser_plugin/browser_plugin_bindings.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/browser_plugin/browser_plugin_bindings.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:23:37.000Z | 2020-11-04T07:23:37.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/browser_plugin/browser_plugin_bindings.h"
#include <cstdlib>
#include <string>
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "content/common/browser_plugin/browser_plugin_constants.h"
#include "content/public/renderer/v8_value_converter.h"
#include "content/renderer/browser_plugin/browser_plugin.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/web/WebBindings.h"
#include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebNode.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/npapi/bindings/npapi.h"
#include "v8/include/v8.h"
using blink::WebBindings;
using blink::WebElement;
using blink::WebDOMEvent;
using blink::WebDOMMessageEvent;
using blink::WebPluginContainer;
using blink::WebString;
namespace content {
namespace {
BrowserPluginBindings* GetBindings(NPObject* object) {
return static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(object)->
message_channel.get();
}
std::string StringFromNPVariant(const NPVariant& variant) {
if (!NPVARIANT_IS_STRING(variant))
return std::string();
const NPString& np_string = NPVARIANT_TO_STRING(variant);
return std::string(np_string.UTF8Characters, np_string.UTF8Length);
}
//------------------------------------------------------------------------------
// Implementations of NPClass functions. These are here to:
// - Implement src attribute.
//------------------------------------------------------------------------------
NPObject* BrowserPluginBindingsAllocate(NPP npp, NPClass* the_class) {
return new BrowserPluginBindings::BrowserPluginNPObject;
}
void BrowserPluginBindingsDeallocate(NPObject* object) {
BrowserPluginBindings::BrowserPluginNPObject* instance =
static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(object);
delete instance;
}
bool BrowserPluginBindingsHasMethod(NPObject* np_obj, NPIdentifier name) {
return false;
}
bool BrowserPluginBindingsInvokeDefault(NPObject* np_obj,
const NPVariant* args,
uint32 arg_count,
NPVariant* result) {
NOTIMPLEMENTED();
return false;
}
bool BrowserPluginBindingsHasProperty(NPObject* np_obj, NPIdentifier name) {
if (!np_obj)
return false;
BrowserPluginBindings* bindings = GetBindings(np_obj);
if (!bindings)
return false;
return bindings->HasProperty(name);
}
bool BrowserPluginBindingsGetProperty(NPObject* np_obj, NPIdentifier name,
NPVariant* result) {
if (!np_obj)
return false;
if (!result)
return false;
// All attributes from here on rely on the bindings, so retrieve it once and
// return on failure.
BrowserPluginBindings* bindings = GetBindings(np_obj);
if (!bindings)
return false;
return bindings->GetProperty(name, result);
}
bool BrowserPluginBindingsSetProperty(NPObject* np_obj, NPIdentifier name,
const NPVariant* variant) {
if (!np_obj)
return false;
if (!variant)
return false;
// All attributes from here on rely on the bindings, so retrieve it once and
// return on failure.
BrowserPluginBindings* bindings = GetBindings(np_obj);
if (!bindings)
return false;
if (variant->type == NPVariantType_Null)
return bindings->RemoveProperty(np_obj, name);
return bindings->SetProperty(np_obj, name, variant);
}
bool BrowserPluginBindingsEnumerate(NPObject *np_obj, NPIdentifier **value,
uint32_t *count) {
NOTIMPLEMENTED();
return true;
}
NPClass browser_plugin_message_class = {
NP_CLASS_STRUCT_VERSION,
&BrowserPluginBindingsAllocate,
&BrowserPluginBindingsDeallocate,
NULL,
&BrowserPluginBindingsHasMethod,
NULL,
&BrowserPluginBindingsInvokeDefault,
&BrowserPluginBindingsHasProperty,
&BrowserPluginBindingsGetProperty,
&BrowserPluginBindingsSetProperty,
NULL,
&BrowserPluginBindingsEnumerate,
};
} // namespace
// BrowserPluginPropertyBinding ------------------------------------------------
class BrowserPluginPropertyBinding {
public:
explicit BrowserPluginPropertyBinding(const char name[]) : name_(name) {}
virtual ~BrowserPluginPropertyBinding() {}
const std::string& name() const { return name_; }
bool MatchesName(NPIdentifier name) const {
return WebBindings::getStringIdentifier(name_.c_str()) == name;
}
virtual bool GetProperty(BrowserPluginBindings* bindings,
NPVariant* result) = 0;
virtual bool SetProperty(BrowserPluginBindings* bindings,
NPObject* np_obj,
const NPVariant* variant) = 0;
virtual void RemoveProperty(BrowserPluginBindings* bindings,
NPObject* np_obj) = 0;
// Updates the DOM Attribute value with the current property value.
void UpdateDOMAttribute(BrowserPluginBindings* bindings,
std::string new_value) {
bindings->instance()->UpdateDOMAttribute(name(), new_value);
}
private:
std::string name_;
DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBinding);
};
class BrowserPluginPropertyBindingAllowTransparency
: public BrowserPluginPropertyBinding {
public:
BrowserPluginPropertyBindingAllowTransparency()
: BrowserPluginPropertyBinding(
browser_plugin::kAttributeAllowTransparency) {
}
virtual bool GetProperty(BrowserPluginBindings* bindings,
NPVariant* result) OVERRIDE {
bool allow_transparency =
bindings->instance()->GetAllowTransparencyAttribute();
BOOLEAN_TO_NPVARIANT(allow_transparency, *result);
return true;
}
virtual bool SetProperty(BrowserPluginBindings* bindings,
NPObject* np_obj,
const NPVariant* variant) OVERRIDE {
std::string value = StringFromNPVariant(*variant);
if (!bindings->instance()->HasDOMAttribute(name())) {
UpdateDOMAttribute(bindings, value);
bindings->instance()->ParseAllowTransparencyAttribute();
} else {
UpdateDOMAttribute(bindings, value);
}
return true;
}
virtual void RemoveProperty(BrowserPluginBindings* bindings,
NPObject* np_obj) OVERRIDE {
bindings->instance()->RemoveDOMAttribute(name());
bindings->instance()->ParseAllowTransparencyAttribute();
}
private:
DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingAllowTransparency);
};
class BrowserPluginPropertyBindingContentWindow
: public BrowserPluginPropertyBinding {
public:
BrowserPluginPropertyBindingContentWindow()
: BrowserPluginPropertyBinding(browser_plugin::kAttributeContentWindow) {
}
virtual bool GetProperty(BrowserPluginBindings* bindings,
NPVariant* result) OVERRIDE {
NPObject* obj = bindings->instance()->GetContentWindow();
if (obj) {
result->type = NPVariantType_Object;
result->value.objectValue = WebBindings::retainObject(obj);
}
return true;
}
virtual bool SetProperty(BrowserPluginBindings* bindings,
NPObject* np_obj,
const NPVariant* variant) OVERRIDE {
return false;
}
virtual void RemoveProperty(BrowserPluginBindings* bindings,
NPObject* np_obj) OVERRIDE {}
private:
DISALLOW_COPY_AND_ASSIGN(BrowserPluginPropertyBindingContentWindow);
};
// BrowserPluginBindings ------------------------------------------------------
BrowserPluginBindings::BrowserPluginNPObject::BrowserPluginNPObject() {
}
BrowserPluginBindings::BrowserPluginNPObject::~BrowserPluginNPObject() {
}
BrowserPluginBindings::BrowserPluginBindings(BrowserPlugin* instance)
: instance_(instance),
np_object_(NULL),
weak_ptr_factory_(this) {
NPObject* obj =
WebBindings::createObject(instance->pluginNPP(),
&browser_plugin_message_class);
np_object_ = static_cast<BrowserPluginBindings::BrowserPluginNPObject*>(obj);
np_object_->message_channel = weak_ptr_factory_.GetWeakPtr();
property_bindings_.push_back(
new BrowserPluginPropertyBindingAllowTransparency);
property_bindings_.push_back(new BrowserPluginPropertyBindingContentWindow);
}
BrowserPluginBindings::~BrowserPluginBindings() {
WebBindings::releaseObject(np_object_);
}
bool BrowserPluginBindings::HasProperty(NPIdentifier name) const {
for (PropertyBindingList::const_iterator iter = property_bindings_.begin();
iter != property_bindings_.end();
++iter) {
if ((*iter)->MatchesName(name))
return true;
}
return false;
}
bool BrowserPluginBindings::SetProperty(NPObject* np_obj,
NPIdentifier name,
const NPVariant* variant) {
for (PropertyBindingList::iterator iter = property_bindings_.begin();
iter != property_bindings_.end();
++iter) {
if ((*iter)->MatchesName(name)) {
if ((*iter)->SetProperty(this, np_obj, variant)) {
return true;
}
break;
}
}
return false;
}
bool BrowserPluginBindings::RemoveProperty(NPObject* np_obj,
NPIdentifier name) {
for (PropertyBindingList::iterator iter = property_bindings_.begin();
iter != property_bindings_.end();
++iter) {
if ((*iter)->MatchesName(name)) {
(*iter)->RemoveProperty(this, np_obj);
return true;
}
}
return false;
}
bool BrowserPluginBindings::GetProperty(NPIdentifier name, NPVariant* result) {
for (PropertyBindingList::iterator iter = property_bindings_.begin();
iter != property_bindings_.end();
++iter) {
if ((*iter)->MatchesName(name))
return (*iter)->GetProperty(this, result);
}
return false;
}
} // namespace content
| 33.350158 | 80 | 0.687476 | [
"object"
] |
e2a0ca2531f7832ac8ea39fbe0d46d2bd8a294ba | 3,024 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter9Exercise13.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter9Exercise13.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter9Exercise13.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Class Rational Chapter9Exercise13.cpp
Bjarne Stroustrup "Programming: Principles and Practice Using C++"
COMMENT
Objective: Implement a class Rational representing a rational number.
Data members: Member functions: Overloaded operators: Helper Function:
numerator get_numerator() algebraic operations: valid_rational()
denomenator get_denominator() operator+ rational_simplification()
Invalid to_fraction() operator- least_common_denominator()
operator*
operator/
operator=
relational operators:
operator==
operator!=
operator<
operator>
extraction / insertion
operator<<
operator>>
Why would someone want to use class Rational?
To avoid rounding error (from algebraic operations) from floating point representation.
Input: -
Output: -
Author: Chris B. Kirov
Date: 30.03.2015
*/
#include <iostream>
#include "Chapter9Exercise13.h"
void test_function();
//=====================================================================================================================
int main()
{
try
{
test_function();
}
catch(Myrational::Rational::Invalid)
{
std::cerr <<"Exception caught!"<< std::endl;
}
}
//=====================================================================================================================
/*
Function: test_function();
Tests (not fully) the functions
related to class Rational.
*/
void test_function()
{
std::cout <<"Default constructor value: "<< Myrational::Rational() <<'\n';
std::cout <<"\nType a rational number in the form (numerator, denominator).\n>>";
Myrational::Rational r1;
std::cin >> r1;
std::cout <<"Object initialized to: "<< r1 <<'\n';
// toDouble()
Myrational::Rational r2(1,2);
double decimalrepresentation = r2.to_fraction();
std::cout <<"\nThe rational number: "<< r2 << " in floating point representation: " << decimalrepresentation <<'\n';
// assignment =
Myrational::Rational r3 = r2;
std::cout <<"\nInitialize new object using assignment: "<< r3 <<'\n';
// relational operators ==, !=
if (r3 == r2)
{
std::cout << "\nObjects equal.\n";
}
if (r3 != r2);
else
{
std::cout << "\nObjects NOT unequal.\n";
}
// relational operators <, >
if (r1 > r2)
{
std::cout << r1 << " > " << r2 <<'\n';
}
if (r1 < r3);
else
{
std::cout << r1 << " greater than " << r2 <<'\n';
}
// algebraic operations: +, -, *, /; rationalSimplification(), (indirectly)leastCommonDenominator()
Myrational::Rational r4(3, 4), r5(5, 6);
std::cout << r4 << " + " << r5 << " = " << r4 + r5 <<'\n';
std::cout << r4 << " - " << r5 << " = " << r4 - r5 <<'\n';
std::cout << r4 << " * " << r5 << " = " << r4 * r5 <<'\n';
std::cout << r4 << " / " << r5 << " = " << r4 / r5 <<'\n';
}
| 28.8 | 119 | 0.518849 | [
"object"
] |
e2acdf03f3c73cd0e669c7abc3eaac3f71ed37c2 | 1,127 | cpp | C++ | FGbTest.cpp | pichtj/groebner | 38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe | [
"MIT"
] | 2 | 2019-09-05T15:32:33.000Z | 2021-07-25T08:32:00.000Z | FGbTest.cpp | pichtj/groebner | 38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe | [
"MIT"
] | null | null | null | FGbTest.cpp | pichtj/groebner | 38e8fb8df9977ffa120ca21a35cac0b0ee3d5afe | [
"MIT"
] | 1 | 2018-02-20T16:34:55.000Z | 2018-02-20T16:34:55.000Z | #include <gtest/gtest.h>
#include <mpirxx.h>
#include "FGb.h"
#include "ImmutablePolynomial.h"
#include "CachedMonomial.h"
using namespace std;
TEST(FGbTest, FGb) {
use_abc_var_names in_this_scope;
FGbRunner<char, 4> runner;
typedef FGbRunner<char, 4>::P P;
typedef typename P::TermType T;
typedef typename P::MonomialType M;
T a = T(1, M::x(0));
T b = T(1, M::x(1));
T c = T(1, M::x(2));
P f1 = a*b*c;
P f2 = a*b - c;
P f3 = b*c - b;
vector<P> input = { f1, f2, f3 };
auto output = runner.fgb(input);
EXPECT_EQ(vector<P>({c, b}), output);
}
TEST(FGbTest, hcyclic3) {
use_abc_var_names in_this_scope;
FGbRunner<char, 4> runner;
typedef FGbRunner<char, 4>::P P;
typedef typename P::TermType T;
typedef typename P::MonomialType M;
T a = T(1, M::x(0));
T b = T(1, M::x(1));
T c = T(1, M::x(2));
T t = T(1, M::x(3));
vector<P> input = {
a + b + c,
a*b + a*c + b*c,
a*b*c - pow(t, 3)
};
auto output = runner.fgb(input);
EXPECT_EQ(vector<P>({a+b+c, pow(b, 2)+b*c+pow(c, 2), pow(c, 3)-pow(t, 3)}), output);
}
// vim:ruler:cindent:shiftwidth=2:expandtab:
| 20.125 | 86 | 0.589175 | [
"vector"
] |
e2b57d12b1e4d5eb497a59b871e801a7e7a6f93a | 8,915 | cpp | C++ | rubis_ws/src/rubis_pkg/src/fake_object_generator.cpp | rubis-lab/Autoware_NDT | b12dbd0100b7323c773f3cb399344986145702a4 | [
"MIT"
] | 2 | 2021-07-12T06:44:37.000Z | 2021-07-20T07:50:33.000Z | rubis_ws/src/rubis_pkg/src/fake_object_generator.cpp | rubis-lab/Autoware_NDT | b12dbd0100b7323c773f3cb399344986145702a4 | [
"MIT"
] | null | null | null | rubis_ws/src/rubis_pkg/src/fake_object_generator.cpp | rubis-lab/Autoware_NDT | b12dbd0100b7323c773f3cb399344986145702a4 | [
"MIT"
] | 3 | 2021-07-12T06:38:00.000Z | 2022-03-21T07:27:17.000Z | #include <iostream>
#include <algorithm>
#include <ros/ros.h>
#include <ros/time.h>
#include <std_msgs/Header.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Vector3.h>
#include <geometry_msgs/PolygonStamped.h>
#include <jsk_recognition_msgs/PolygonArray.h>
#include <geometry_msgs/Point32.h>
#include <autoware_msgs/DetectedObject.h>
#include <autoware_msgs/DetectedObjectArray.h>
static std::vector<std::string> type_names;
void init_type_names();
void create_fake_objects(std::vector< std::vector<double> >& object_list, autoware_msgs::DetectedObjectArray& object_array_msg, jsk_recognition_msgs::PolygonArray& polygon_array_msg);
void add_objects(std_msgs::Header& header, autoware_msgs::DetectedObjectArray& input_msg, autoware_msgs::DetectedObjectArray& output_msg);
std_msgs::Header create_header(int seq, std::string frame_id);
int main(int argc, char* argv[]){
init_type_names();
// Initialize
ros::init(argc, argv, "fake_object_generator");
ros::NodeHandle nh;
ros::Rate rate(10);
ros::Publisher object_array_pub;
ros::Publisher object_polygon_array_pub;
ros::Publisher person_polygon_array_pub;
object_array_pub = nh.advertise<autoware_msgs::DetectedObjectArray>("/detection/fusion_tools/objects", 10);
object_polygon_array_pub = nh.advertise<jsk_recognition_msgs::PolygonArray>("/fake_object_polygons", 10);
person_polygon_array_pub = nh.advertise<jsk_recognition_msgs::PolygonArray>("/fake_person_polygons", 10);
// Load Parameters
XmlRpc::XmlRpcValue xml_object_list;
nh.getParam("/fake_object_generator/object_list", xml_object_list);
std::vector< std::vector<double> > object_list;
for(int i=0; i<xml_object_list.size(); i++){
XmlRpc::XmlRpcValue xml_object = xml_object_list[i];
std::vector<double> object;
for(int j=0; j<xml_object.size(); j++)
object.push_back((double)(xml_object[j]));
object_list.push_back(object);
}
XmlRpc::XmlRpcValue xml_person_list;
nh.getParam("/fake_object_generator/person_list", xml_person_list);
std::vector< std::vector<double> > person_list;
for(int i=0; i<xml_person_list.size(); i++){
XmlRpc::XmlRpcValue xml_person = xml_person_list[i];
std::vector<double> person;
for(int j=0; j<xml_person.size(); j++)
person.push_back((double)(xml_person[j]));
person_list.push_back(person);
}
std::string frame_id = "/none";
nh.getParam("/fake_object_generator/frame_id", frame_id);
autoware_msgs::DetectedObjectArray object_array_msg;
jsk_recognition_msgs::PolygonArray object_polygon_array_msg;
create_fake_objects(object_list, object_array_msg, object_polygon_array_msg);
autoware_msgs::DetectedObjectArray person_array_msg;
jsk_recognition_msgs::PolygonArray person_polygon_array_msg;
create_fake_objects(person_list, person_array_msg, person_polygon_array_msg);
std::vector< std::vector<double> > empty_list;
autoware_msgs::DetectedObjectArray empty_array_msg;
jsk_recognition_msgs::PolygonArray empty_polygon_array_msg;
create_fake_objects(empty_list, empty_array_msg, empty_polygon_array_msg);
int seq = 0;
int object_flag, person_flag;
autoware_msgs::DetectedObjectArray final_object_msg;
while(ros::ok()){
nh.getParam("/fake_object_generator/object_flag", object_flag);
nh.getParam("/fake_object_generator/person_flag", person_flag);
std_msgs::Header header = create_header(seq, frame_id);
object_polygon_array_msg.header = header;
for(auto it = object_polygon_array_msg.polygons.begin(); it != object_polygon_array_msg.polygons.end(); ++it)
(*it).header = header;
person_polygon_array_msg.header = header;
for(auto it = person_polygon_array_msg.polygons.begin(); it != person_polygon_array_msg.polygons.end(); ++it)
(*it).header = header;
empty_polygon_array_msg.header = header;
// for(auto it = fake_polygon_array_msg.polygons.begin(); it != fake_polygon_array_msg.polygons.end(); ++it)
// (*it).header = header;
final_object_msg.header = header;
final_object_msg.objects.clear();
if(object_flag==1){
add_objects(header, object_array_msg, final_object_msg);
object_polygon_array_pub.publish(object_polygon_array_msg);
}
else{
object_polygon_array_pub.publish(empty_polygon_array_msg);
}
if(person_flag==1){
add_objects(header, person_array_msg, final_object_msg);
person_polygon_array_pub.publish(person_polygon_array_msg);
}
else{
person_polygon_array_pub.publish(empty_polygon_array_msg);
}
object_array_pub.publish(final_object_msg);
seq++;
rate.sleep();
}
return 0;
}
std_msgs::Header create_header(int seq, std::string frame_id){
std_msgs::Header header;
header.stamp = ros::Time::now();
header.seq = seq;
header.frame_id = frame_id;
return header;
}
void add_objects(std_msgs::Header& header, autoware_msgs::DetectedObjectArray& input_msg, autoware_msgs::DetectedObjectArray& output_msg){
for(auto it = input_msg.objects.begin(); it != input_msg.objects.end(); ++it){
(*it).header = header;
output_msg.objects.push_back(*it);
}
}
void create_fake_objects(std::vector< std::vector<double> >& object_list, autoware_msgs::DetectedObjectArray& object_array_msg, jsk_recognition_msgs::PolygonArray& polygon_array_msg){
static int object_id = 415;
for(auto itlist = object_list.begin(); itlist != object_list.end(); ++itlist){
std::vector<double> object = *itlist;
std::vector<double> x_vec;
std::vector<double> y_vec;
std::vector<double> z_vec;
std::vector<geometry_msgs::Point32> convex_hull_points;
autoware_msgs::DetectedObject object_msg;
geometry_msgs::PolygonStamped polygon_msg;
for(auto itobj = object.begin(); itobj != object.end(); ++itobj){
geometry_msgs::Point32 point;
int obj_idx = itobj - object.begin();
if(obj_idx%3 == 0)
x_vec.push_back(*itobj);
else if(obj_idx%3 == 1)
y_vec.push_back(*itobj);
else if(obj_idx%3 == 2){
z_vec.push_back(*itobj);
geometry_msgs::Point32 point;
point.x = x_vec[obj_idx/3];
point.y = y_vec[obj_idx/3];
point.z = z_vec[obj_idx/3];
convex_hull_points.push_back(point);
}
}
for(auto itconvex = convex_hull_points.begin(); itconvex != convex_hull_points.end(); ++itconvex){
geometry_msgs::Point32 point = *itconvex;
object_msg.convex_hull.polygon.points.push_back(*itconvex);
}
object_msg.id = object_id++;
// Pose
float max_x, min_x, max_y, min_y, max_z, min_z;
max_x = *std::max_element(x_vec.begin(), x_vec.end());
min_x = *std::min_element(x_vec.begin(), x_vec.end());
max_y = *std::max_element(y_vec.begin(), y_vec.end());
min_y = *std::min_element(y_vec.begin(), y_vec.end());
max_z = *std::max_element(z_vec.begin(), z_vec.end());
min_z = *std::min_element(z_vec.begin(), z_vec.end());
object_msg.pose.position.x = min_x + (max_x-min_x)/2.0;
object_msg.pose.position.y = min_y + (max_y-min_y)/2.0;
object_msg.pose.position.z = min_z + (max_z-min_z)/2.0;
object_msg.pose.orientation.x = 0.0132425152446;
object_msg.pose.orientation.y = 0.00564379347071;
object_msg.pose.orientation.z = -0.792667771434;
object_msg.pose.orientation.w = 0.609483869775;
// Dimension
object_msg.dimensions.x = (max_x-min_x)/2.0;
object_msg.dimensions.y = (max_y-min_y)/2.0;
object_msg.dimensions.z = (max_z-min_z)/2.0;
// Velocity
object_msg.velocity.linear.x = 0.5;
object_msg.velocity.linear.y = 0.5;
object_msg.velocity.linear.z = 0.5;
// Polygon
polygon_msg = object_msg.convex_hull;
// Create Msg
object_array_msg.objects.push_back(object_msg);
polygon_array_msg.polygons.push_back(polygon_msg);
}
}
void init_type_names(){
type_names.push_back(std::string("invalid"));
type_names.push_back(std::string("bool"));
type_names.push_back(std::string("int"));
type_names.push_back(std::string("double"));
type_names.push_back(std::string("string"));
type_names.push_back(std::string("data_time"));
type_names.push_back(std::string("base64"));
type_names.push_back(std::string("array"));
type_names.push_back(std::string("struct"));
}
| 39.100877 | 183 | 0.670107 | [
"object",
"vector"
] |
e2b82b1c260cdd1befd79a621b3bc6489290c6ae | 12,905 | cpp | C++ | transx/c_codes/test.cpp | IsaacChanghau/AmusingPythonCodes | 013ecaaafe62696866b47b0910e1db00cca9ea37 | [
"MIT"
] | 26 | 2018-01-30T09:02:39.000Z | 2021-12-09T05:14:53.000Z | test.cpp | davidie/TensorFlow-TransX | 41302d7a68d4880c1634b81c19639c72d4e3c65e | [
"MIT"
] | 1 | 2019-12-28T04:09:45.000Z | 2019-12-28T04:09:45.000Z | test.cpp | davidie/TensorFlow-TransX | 41302d7a68d4880c1634b81c19639c72d4e3c65e | [
"MIT"
] | 26 | 2017-09-29T08:59:35.000Z | 2021-11-15T03:23:02.000Z | #include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#include <vector>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
string inPath = "./wiki50k/";
extern "C"
void setInPath(char *path) {
int len = strlen(path);
inPath = "";
for (int i = 0; i < len; i++)
inPath = inPath + path[i];
printf("Input Files Path : %s\n", inPath.c_str());
}
int relationTotal;
int entityTotal;
int testTotal, tripleTotal, trainTotal, validTotal;
float l1_filter_tot = 0, l1_tot = 0, r1_tot = 0, r1_filter_tot = 0;
float l3_filter_tot = 0, l3_tot = 0, r3_tot = 0, r3_filter_tot = 0;
float l_filter_tot[6], r_filter_tot[6], l_tot[6], r_tot[6];
float l_filter_rank[6], r_filter_rank[6], l_rank[6], r_rank[6];
struct Triple {
int h, r, t, label;
};
struct cmp_head {
bool operator()(const Triple &a, const Triple &b) {
return (a.h < b.h)||(a.h == b.h && a.r < b.r)||(a.h == b.h && a.r == b.r && a.t < b.t);
}
};
Triple *testList, *tripleList;
Triple *classList;
int *flagList;
int tripleclassTotal;
int nntotal[5];
int *head_lef, *head_rig, *tail_lef, *tail_rig;
int *head_type, *tail_type;
extern "C"
void init() {
FILE *fin;
int tmp, h, r, t, label;
fin = fopen((inPath + "relation2id.txt").c_str(), "r");
tmp = fscanf(fin, "%d", &relationTotal);
fclose(fin);
fin = fopen((inPath + "entity2id.txt").c_str(), "r");
tmp = fscanf(fin, "%d", &entityTotal);
fclose(fin);
head_lef = (int *)calloc(relationTotal * 2, sizeof(int));
head_rig = (int *)calloc(relationTotal * 2, sizeof(int));
tail_lef = (int *)calloc(relationTotal * 2, sizeof(int));
tail_rig = (int *)calloc(relationTotal * 2, sizeof(int));
FILE* f_kb1 = fopen((inPath + "test2id_all.txt").c_str(), "r");
FILE* f_kb2 = fopen((inPath + "train2id.txt").c_str(), "r");
FILE* f_kb3 = fopen((inPath + "valid2id.txt").c_str(), "r");
tmp = fscanf(f_kb1, "%d", &testTotal);
tmp = fscanf(f_kb2, "%d", &trainTotal);
tmp = fscanf(f_kb3, "%d", &validTotal);
head_type = (int *)calloc((testTotal + trainTotal + validTotal) * 2, sizeof(int));
tail_type = (int *)calloc((testTotal + trainTotal + validTotal) * 2, sizeof(int));
tripleTotal = testTotal + trainTotal + validTotal;
testList = (Triple *)calloc(testTotal, sizeof(Triple));
tripleList = (Triple *)calloc(tripleTotal, sizeof(Triple));
for (int i = 0; i < testTotal; i++) {
tmp = fscanf(f_kb1, "%d", &label);
tmp = fscanf(f_kb1, "%d", &h);
tmp = fscanf(f_kb1, "%d", &t);
tmp = fscanf(f_kb1, "%d", &r);
label++;
nntotal[label]++;
testList[i].label = label;
testList[i].h = h;
testList[i].t = t;
testList[i].r = r;
tripleList[i].h = h;
tripleList[i].t = t;
tripleList[i].r = r;
}
for (int i = 0; i < trainTotal; i++) {
tmp = fscanf(f_kb2, "%d", &h);
tmp = fscanf(f_kb2, "%d", &t);
tmp = fscanf(f_kb2, "%d", &r);
tripleList[i + testTotal].h = h;
tripleList[i + testTotal].t = t;
tripleList[i + testTotal].r = r;
}
for (int i = 0; i < validTotal; i++) {
tmp = fscanf(f_kb3, "%d", &h);
tmp = fscanf(f_kb3, "%d", &t);
tmp = fscanf(f_kb3, "%d", &r);
tripleList[i + testTotal + trainTotal].h = h;
tripleList[i + testTotal + trainTotal].t = t;
tripleList[i + testTotal + trainTotal].r = r;
}
fclose(f_kb1);
fclose(f_kb2);
fclose(f_kb3);
sort(tripleList, tripleList + tripleTotal, cmp_head());
memset(l_filter_tot, 0, sizeof(l_filter_tot));
memset(r_filter_tot, 0, sizeof(r_filter_tot));
memset(l_tot, 0, sizeof(l_tot));
memset(r_tot, 0, sizeof(r_tot));
int total_lef = 0;
int total_rig = 0;
FILE* f_type = fopen((inPath + "type_constrain.txt").c_str(),"r");
tmp = fscanf(f_type, "%d", &tmp);
for (int i = 0; i < relationTotal; i++) {
int rel, tot;
tmp = fscanf(f_type, "%d%d", &rel, &tot);
head_lef[rel] = total_lef;
for (int j = 0; j < tot; j++) {
tmp = fscanf(f_type, "%d", &head_type[total_lef]);
total_lef++;
}
head_rig[rel] = total_lef;
sort(head_type + head_lef[rel], head_type + head_rig[rel]);
tmp = fscanf(f_type, "%d%d", &rel, &tot);
tail_lef[rel] = total_rig;
for (int j = 0; j < tot; j++) {
tmp = fscanf(f_type, "%d", &tail_type[total_rig]);
total_rig++;
}
tail_rig[rel] = total_rig;
sort(tail_type + tail_lef[rel], tail_type + tail_rig[rel]);
}
fclose(f_type);
}
bool find(int h, int t, int r) {
int lef = 0;
int rig = tripleTotal - 1;
int mid;
while (lef + 1 < rig) {
int mid = (lef + rig) >> 1;
if ((tripleList[mid]. h < h) || (tripleList[mid]. h == h && tripleList[mid]. r < r) || (tripleList[mid]. h == h && tripleList[mid]. r == r && tripleList[mid]. t < t)) lef = mid; else rig = mid;
}
if (tripleList[lef].h == h && tripleList[lef].r == r && tripleList[lef].t == t) return true;
if (tripleList[rig].h == h && tripleList[rig].r == r && tripleList[rig].t == t) return true;
return false;
}
extern "C"
int getEntityTotal() {
return entityTotal;
}
extern "C"
int getRelationTotal() {
return relationTotal;
}
extern "C"
int getTripleTotal() {
return tripleTotal;
}
extern "C"
int getTestTotal() {
return testTotal;
}
extern "C"
int getClassTotal() {
return tripleclassTotal;
}
extern "C"
void getClassBatch(int *ph, int *pt, int *pr, int *flag) {
for (int i = 0; i < tripleclassTotal; i++) {
ph[i] = classList[i].h;
pt[i] = classList[i].t;
pr[i] = classList[i].r;
flag[i] = flagList[i];
}
}
struct classTriple {
float res;
int flag;
};
struct classcmp {
bool operator()(const classTriple &a, const classTriple &b) {
return (a.res < b.res)||(a.res == b.res && a.flag > b.flag);
}
};
extern "C"
void getClassRes(float *con, int *flag) {
float posTot = 0;
float negTot = 0;
classTriple* res = (classTriple *)calloc(tripleclassTotal, sizeof(classTriple));
for (int i = 0; i < tripleclassTotal; i++) {
res[i].res = con[i];
res[i].flag = flag[i];
if (res[i].flag == 1) posTot++; else negTot++;
}
sort(res, res + tripleclassTotal, classcmp());
float posS = 0;
float negS = 0;
float mx;
for (int i = 0; i < tripleclassTotal; i++) {
if (res[i].flag == 1) posS++; else negS++;
float pre = (posS + negTot - negS)/(negTot+posTot);
if (pre > mx) mx = pre;
}
printf("%f\n", mx);
free(res);
}
int lastHead = 0;
int lastTail = 0;
extern "C"
void getHeadBatch(int *ph, int *pt, int *pr) {
for (int i = 0; i < entityTotal; i++) {
ph[i] = i;
pt[i] = testList[lastHead].t;
pr[i] = testList[lastHead].r;
}
}
extern "C"
void getTailBatch(int *ph, int *pt, int *pr) {
for (int i = 0; i < entityTotal; i++) {
ph[i] = testList[lastTail].h;
pt[i] = i;
pr[i] = testList[lastTail].r;
}
}
extern "C"
void testHead(float *con) {
int h = testList[lastHead].h;
int t = testList[lastHead].t;
int r = testList[lastHead].r;
int label = testList[lastHead].label;
float minimal = con[h];
printf("%f\n", minimal);
int l_s = 0;
int l_filter_s = 0;
int l_s_constrain = 0;
int l_filter_s_constrain = 0;
int type_head = head_lef[r];
for (int j = 0; j <= entityTotal; j++) {
float value = con[j];
if (j != h && value < minimal) {
l_s += 1;
if (not find(j, t, r))
l_filter_s += 1;
}
if (j != h) {
while (type_head < head_rig[r] && head_type[type_head] < j) type_head++;
if (type_head < head_rig[r] && head_type[type_head] == j) {
if (value < minimal) {
l_s_constrain += 1;
if (not find(j, t, r))
l_filter_s_constrain += 1;
}
}
}
}
if (l_filter_s < 10) l_filter_tot[0] += 1;
if (l_s < 10) l_tot[0] += 1;
if (l_filter_s < 3) l3_filter_tot += 1;
if (l_s < 3) l3_tot += 1;
if (l_filter_s < 1) l1_filter_tot += 1;
if (l_s < 1) l1_tot += 1;
if (l_filter_s < 10) l_filter_tot[label] += 1;
if (l_s < 10) l_tot[label] += 1;
l_filter_rank[label] += l_filter_s;
l_rank[label] += l_s;
if (l_filter_s_constrain < 10) l_filter_tot[5] += 1;
if (l_s_constrain < 10) l_tot[5] += 1;
l_filter_rank[5] += l_filter_s_constrain;
l_rank[5] += l_s_constrain;
l_filter_rank[0] += (l_filter_s+1);
l_rank[0] += (1+l_s);
lastHead++;
printf("l_filter_s: %d\n", l_filter_s);
printf("%f %f %f %f\n", l_tot[0] / lastHead, l_filter_tot[0] / lastHead, l_rank[0], l_filter_rank[0]);
}
extern "C"
void testTail(float *con) {
int h = testList[lastTail].h;
int t = testList[lastTail].t;
int r = testList[lastTail].r;
int label = testList[lastTail].label;
float minimal = con[t];
printf("%f\n", minimal);
int r_s = 0;
int r_filter_s = 0;
int r_s_constrain = 0;
int r_filter_s_constrain = 0;
int type_tail = tail_lef[r];
for (int j = 0; j <= entityTotal; j++) {
float value = con[j];
if (j != t && value < minimal) {
r_s += 1;
if (not find(h, j, r))
r_filter_s += 1;
}
if (j != t) {
while (type_tail < tail_rig[r] && tail_type[type_tail] < j) type_tail++;
if (type_tail < tail_rig[r] && tail_type[type_tail] == j) {
if (value < minimal) {
r_s_constrain += 1;
if (not find(h, j, r))
r_filter_s_constrain += 1;
}
}
}
}
if (r_filter_s < 10) r_filter_tot[0] += 1;
if (r_s < 10) r_tot[0] += 1;
if (r_filter_s < 3) r3_filter_tot += 1;
if (r_s < 3) r3_tot += 1;
if (r_filter_s < 1) r1_filter_tot += 1;
if (r_s < 1) r1_tot += 1;
if (r_filter_s < 10) r_filter_tot[label] += 1;
if (r_s < 10) r_tot[label] += 1;
r_filter_rank[label] += r_filter_s;
r_rank[label] += r_s;
if (r_filter_s_constrain < 10) r_filter_tot[5] += 1;
if (r_s_constrain < 10) r_tot[5] += 1;
r_filter_rank[5] += r_filter_s_constrain;
r_rank[5] += r_s_constrain;
r_filter_rank[0] += (1+r_filter_s);
r_rank[0] += (1+r_s);
lastTail++;
printf("r_filter_s: %d\n", r_filter_s);
printf("%f %f %f %f\n", r_tot[0] /lastTail, r_filter_tot[0] /lastTail, r_rank[0], r_filter_rank[0]);
}
extern "C"
void test() {
printf("results:\n");
for (int i = 0; i <=0; i++) {
printf("left %f %f %f %f \n", l_rank[i]/ testTotal, l_tot[i] / testTotal, l3_tot / testTotal, l1_tot / testTotal);
printf("left(filter) %f %f %f %f \n", l_filter_rank[i]/ testTotal, l_filter_tot[i] / testTotal, l3_filter_tot / testTotal, l1_filter_tot / testTotal);
printf("right %f %f %f %f \n", r_rank[i]/ testTotal, r_tot[i] / testTotal,r3_tot / testTotal,r1_tot / testTotal);
printf("right(filter) %f %f %f %f\n", r_filter_rank[i]/ testTotal, r_filter_tot[i] / testTotal,r3_filter_tot / testTotal,r1_filter_tot / testTotal);
}
printf("results (type constraints):\n");
for (int i = 5; i <=5; i++) {
printf("left %f %f %f %f \n", l_rank[i]/ testTotal, l_tot[i] / testTotal, l3_tot / testTotal, l1_tot / testTotal);
printf("left(filter) %f %f %f %f \n", l_filter_rank[i]/ testTotal, l_filter_tot[i] / testTotal, l3_filter_tot / testTotal, l1_filter_tot / testTotal);
printf("right %f %f %f %f \n", r_rank[i]/ testTotal, r_tot[i] / testTotal,r3_tot / testTotal,r1_tot / testTotal);
printf("right(filter) %f %f %f %f\n", r_filter_rank[i]/ testTotal, r_filter_tot[i] / testTotal,r3_filter_tot / testTotal,r1_filter_tot / testTotal);
}
for (int i = 1; i <= 4; i++) {
if (i == 1)
printf("results (1-1):\n");
if (i == 2)
printf("results (1-n):\n");
if (i == 3)
printf("results (n-1):\n");
if (i == 4)
printf("results (n-n):\n");
printf("left %f %f %f %f \n", l_rank[i]/ nntotal[i], l_tot[i] / nntotal[i], l3_tot / nntotal[i], l1_tot / nntotal[i]);
printf("left(filter) %f %f %f %f \n", l_filter_rank[i]/ nntotal[i], l_filter_tot[i] / nntotal[i], l3_filter_tot / nntotal[i], l1_filter_tot / nntotal[i]);
printf("right %f %f %f %f \n", r_rank[i]/ nntotal[i], r_tot[i] / nntotal[i],r3_tot / nntotal[i],r1_tot / nntotal[i]);
printf("right(filter) %f %f %f %f\n", r_filter_rank[i]/ nntotal[i], r_filter_tot[i] / nntotal[i],r3_filter_tot / nntotal[i],r1_filter_tot / nntotal[i]);
}
}
int main() {
init();
return 0;
}
| 31.785714 | 201 | 0.559706 | [
"vector"
] |
e2c0adf33fb656fd12d15b113e08c98e78c83bc4 | 370 | cpp | C++ | leetcode/215. Kth Largest Element in an Array/s4.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | 1 | 2021-02-09T11:38:51.000Z | 2021-02-09T11:38:51.000Z | leetcode/215. Kth Largest Element in an Array/s4.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | leetcode/215. Kth Largest Element in an Array/s4.cpp | contacttoakhil/LeetCode-1 | 9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c | [
"Fair"
] | null | null | null | // Author: github.com/lzl124631x
// Time: O(k + (N - k)logk)
// Space: O(k)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> q;
for (int n : nums) {
if (q.size() < k) q.push(n);
else if (q.top() < n) {
q.pop();
q.push(n);
}
}
return q.top();
}
}; | 21.764706 | 53 | 0.513514 | [
"vector"
] |
e2c704d36c3c1e17ace42519297d6a5a18456815 | 26,537 | hh | C++ | graph-tool-2.27/src/graph/graph_selectors.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/graph_selectors.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/graph_selectors.hh | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | // graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef GRAPH_SELECTORS_HH
#define GRAPH_SELECTORS_HH
#include <utility>
#include <type_traits>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/logical.hpp>
#include "graph_adaptor.hh"
#include "graph_properties.hh"
#include "graph.hh"
namespace graph_tool
{
// This file contain selector for degree types for different types of
// graphs. Namely, they will return the in degree, out degree, and total degree
// for both directed and undirected graphs. There is also an scalar selector,
// which will return a specific scalar property
// This file also contains selectors for in_edge iterators of graphs, which
// return an empty range for undirected graphs
namespace detail
{
struct no_weightS {};
template <class Weight>
struct get_weight_type
{
typedef typename boost::property_traits<typename std::remove_reference<Weight>::type>::value_type type;
};
template <>
struct get_weight_type<no_weightS&>
{
typedef size_t type;
};
template <>
struct get_weight_type<no_weightS>
{
typedef size_t type;
};
}
struct in_degreeS
{
typedef size_t value_type;
in_degreeS() {}
template <class Graph>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g) const
{
return in_degreeS::operator()(v, g, detail::no_weightS());
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, Weight&& weight) const
{
typedef typename std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>::type is_directed;
return get_in_degree(v, g, is_directed(), std::forward<Weight>(weight));
}
template <class Graph>
inline __attribute__((always_inline))
auto get_in_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::true_type,
detail::no_weightS) const
{
return in_degree(v, g);
}
template <class Graph, class Key, class Value>
inline __attribute__((always_inline))
auto get_in_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::true_type,
const ConstantPropertyMap<Value, Key>& weight) const
{
return in_degree(v, g) * weight.c;
}
template <class Graph, class Key, class Value>
inline __attribute__((always_inline))
auto get_in_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::true_type,
const UnityPropertyMap<Value, Key>&) const
{
return in_degree(v, g);
}
template <class Graph, class Weight>
auto get_in_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::true_type, Weight& weight) const
{
typedef typename boost::property_traits<Weight>::value_type val_t;
val_t d = val_t();
typename boost::graph_traits<Graph>::in_edge_iterator e, e_end;
for (std::tie(e, e_end) = in_edges(v, g); e != e_end; ++e)
d += get(weight, *e);
return d;
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto get_in_degree(const typename boost::graph_traits<Graph>::vertex_descriptor&,
const Graph&, std::false_type, Weight&&) const
{
return 0;
}
};
struct out_degreeS
{
typedef size_t value_type;
out_degreeS() {}
template <class Graph>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g) const
{
return out_degreeS::operator()(v, g, detail::no_weightS());
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, Weight&& weight) const
{
return get_out_degree(v, g, std::forward<Weight>(weight));
}
template <class Graph, class Key, class Value>
inline __attribute__((always_inline))
auto get_out_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g,
const ConstantPropertyMap<Value, Key>& weight) const
{
return out_degree(v, g) * weight.c;
}
template <class Graph, class Key, class Value>
inline __attribute__((always_inline))
auto get_out_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g,
const UnityPropertyMap<Value, Key>&) const
{
return out_degree(v, g);
}
template <class Graph, class Weight>
inline
auto get_out_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, const Weight& weight) const
{
typedef typename boost::property_traits<Weight>::value_type val_t;
val_t d = val_t();
typename boost::graph_traits<Graph>::out_edge_iterator e, e_end;
for (std::tie(e, e_end) = out_edges(v, g); e != e_end; ++e)
d += get(weight, *e);
return d;
}
template <class Graph>
inline __attribute__((always_inline))
auto get_out_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, detail::no_weightS) const
{
return out_degree(v, g);
}
};
struct total_degreeS
{
typedef size_t value_type;
total_degreeS() {}
template <class Graph>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g) const
{
return total_degreeS::operator()(v, g, detail::no_weightS());
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto operator()(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, Weight&& weight) const
{
typedef typename std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>::type is_directed;
return get_total_degree(v, g, is_directed(),
std::forward<Weight>(weight));
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto get_total_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::true_type,
Weight&& weight) const
{
return in_degreeS()(v, g, std::forward<Weight>(weight)) +
out_degreeS()(v, g, std::forward<Weight>(weight));
}
template <class Graph, class Weight>
inline __attribute__((always_inline))
auto get_total_degree(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g, std::false_type, Weight&& weight) const
{
return out_degreeS()(v, g, std::forward<Weight>(weight));
}
};
template <class PropertyMap>
struct scalarS
{
typedef typename boost::property_traits<PropertyMap>::value_type value_type;
scalarS() {}
scalarS(PropertyMap pmap): _pmap(pmap) {}
template <class Descriptor, class Graph>
inline __attribute__((always_inline))
auto operator()(const Descriptor& d, const Graph&) const
{
return get(_pmap, d);
}
PropertyMap _pmap;
};
struct get_degree_selector
{
typedef boost::mpl::map
<boost::mpl::pair<in_degreeS,
boost::mpl::int_<GraphInterface::IN_DEGREE> >,
boost::mpl::pair<out_degreeS,
boost::mpl::int_<GraphInterface::OUT_DEGREE> >,
boost::mpl::pair<total_degreeS,
boost::mpl::int_<GraphInterface::TOTAL_DEGREE> > >
degree_selector_index;
template <class Selector>
void operator()(Selector, int deg_index, boost::any& deg) const
{
if (boost::mpl::at<degree_selector_index, Selector>::type::value == deg_index)
deg = Selector();
}
};
struct get_scalar_selector
{
template <class PropertyMap>
void operator()(PropertyMap, boost::any prop, boost::any& sec, bool& found)
const
{
try
{
PropertyMap map = boost::any_cast<PropertyMap>(prop);
sec = scalarS<PropertyMap>(map);
found = true;
}
catch (boost::bad_any_cast&) {}
}
};
struct scalar_selector_type
{
template <class PropertyMap>
struct apply
{
typedef scalarS<PropertyMap> type;
};
};
struct selectors:
boost::mpl::vector<out_degreeS, in_degreeS, total_degreeS> {};
// retrieves the appropriate degree selector
boost::any degree_selector(GraphInterface::deg_t deg);
// helper types for in_edge_iteratorS
template <class Graph, class IsDirected>
struct get_in_edges
{
BOOST_MPL_ASSERT((std::is_same<IsDirected,std::true_type>));
BOOST_MPL_ASSERT((std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>));
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
typedef typename boost::graph_traits<Graph>::in_edge_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor v,
const Graph& g)
{
return in_edges(v, g);
}
};
template <class Graph>
struct get_in_edges<Graph,std::false_type>
{
BOOST_MPL_ASSERT((std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::undirected_tag>));
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
typedef typename boost::graph_traits<Graph>::out_edge_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor,
const Graph&)
{
return std::make_pair(type(), type());
}
};
// this in-edge iterator selector returns the in-edge range for directed graphs
// and an empty out-edge range for undirected graphs. The iterator type is given
// by in_edge_iteratorS<Graph>::type.
template <class Graph>
struct in_edge_iteratorS
{
typedef typename boost::graph_traits<Graph>::directed_category
directed_category;
typedef typename std::is_convertible<directed_category,
boost::directed_tag>::type is_directed;
typedef typename get_in_edges<Graph,is_directed>::type type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor v,
const Graph& g)
{
return get_in_edges<Graph,is_directed>::get_edges(v, g);
}
};
template <class Graph>
struct _all_edges_in_iteratorS
{
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef typename boost::graph_traits<Graph>::in_edge_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor v,
const Graph& g)
{
return _all_edges_in(v, g);
}
};
// out edges selector for completeness
template <class Graph>
struct out_edge_iteratorS
{
typedef typename boost::graph_traits<Graph>::out_edge_iterator type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor v,
const Graph& g)
{
return out_edges(v, g);
}
};
// this "all edges" iterator selector returns the in-edge + out-edge ranges for
// directed graphs and the out-edge range for undirected graphs. The
// iterator type is given by all_edges_iteratorS<Graph>::type.
template <class Graph>
struct all_edges_iteratorS
{
typedef typename Graph::all_edge_iterator type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type, type> get_edges(vertex_descriptor v, const Graph& g)
{
return all_edges(v, g);
}
};
// this "in or out" iterator selector returns the in-edge range for directed
// graphs and the out-edge range for undirected graphs. The iterator type is
// given by in_or_out_edges_iteratorS<Graph>::type
template <class Graph>
struct in_or_out_edge_iteratorS
: public std::conditional
<std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>::value,
in_edge_iteratorS<Graph>,
_all_edges_in_iteratorS<Graph>>::type
{};
// helper types for in_neighbor_iteratorS
template <class Graph, class IsDirected>
struct get_in_neighbors
{
BOOST_MPL_ASSERT((std::is_same<IsDirected,std::true_type>));
BOOST_MPL_ASSERT((std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>));
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
typedef typename boost::graph_traits<Graph>::in_neighbor_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_edges(vertex_descriptor v,
const Graph& g)
{
return in_neighbors(v, g);
}
};
template <class Graph>
struct get_in_neighbors<Graph,std::false_type>
{
BOOST_MPL_ASSERT((std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::undirected_tag>));
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
typedef typename boost::graph_traits<Graph>::out_neighbors_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_neighbors(vertex_descriptor,
const Graph&)
{
return make_pair(type(), type());
}
};
// this in-neighbor iterator selector returns the in-neighbor range for
// directed graphs and an empty out-neighbor range for undirected graphs. The
// iterator type is given by in_neighbor_iteratorS<Graph>::type.
template <class Graph>
struct in_neighbor_iteratorS
{
typedef typename boost::graph_traits<Graph>::directed_category
directed_category;
typedef typename std::is_convertible<directed_category,
boost::directed_tag>::type is_directed;
typedef typename get_in_edges<Graph,is_directed>::type type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type,type> get_neighbors(vertex_descriptor v,
const Graph& g)
{
return get_in_neighbors<Graph,is_directed>::get_neighbors(v, g);
}
};
template <class Graph>
struct _all_neighbors_in_iteratorS
{
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef typename boost::graph_traits<Graph>::in_edge_iterator type;
inline __attribute__((always_inline))
static std::pair<type,type> get_neighbors(vertex_descriptor v,
const Graph& g)
{
return _all_neighbors_ins(v, g);
}
};
// out edges selector for completeness
template <class Graph>
struct out_neighbor_iteratorS
{
typedef typename boost::graph_traits<Graph>::out_neighbors_iterator type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type,type> get_neighbors(vertex_descriptor v,
const Graph& g)
{
return out_neighbors(v, g);
}
};
// this "all neighbors" iterator selector returns the in-neighbors +
// out-neighbors ranges for directed graphs and the out-neighbors range for
// undirected graphs. The iterator type is given by
// all_neighbors_iteratorS<Graph>::type.
template <class Graph>
struct all_neighbors_iteratorS
{
typedef typename boost::graph_traits<Graph>::adjacency_iterator type;
typedef typename boost::graph_traits<Graph>::vertex_descriptor
vertex_descriptor;
inline __attribute__((always_inline))
static std::pair<type,type> get_neighbors(vertex_descriptor v,
const Graph& g)
{
return all_neighbors(v, g);
}
};
// this "in or out" iterator selector returns the in-neighbor range for
// directed graphs and the out-neighbor range for undirected graphs. The
// iterator type is given by in_or_adjacency_iteratorS<Graph>::type
template <class Graph>
struct in_or_out_neighbors_iteratorS
: public std::conditional
<std::is_convertible
<typename boost::graph_traits<Graph>::directed_category,
boost::directed_tag>::value,
in_neighbor_iteratorS<Graph>,
_all_neighbors_in_iteratorS<Graph>>::type
{};
// range adaptors
template <class Iter>
class IterRange
{
public:
explicit IterRange(std::pair<Iter, Iter>&& range)
: _range(std::forward<std::pair<Iter, Iter>>(range)) {}
const Iter& begin() { return _range.first; }
const Iter& end() { return _range.second; }
private:
std::pair<Iter, Iter> _range;
};
template <class Iter>
inline __attribute__((always_inline))
auto mk_range(std::pair<Iter, Iter>&& range)
{
return IterRange<Iter>(std::forward<std::pair<Iter, Iter>>(range));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto vertices_range(const Graph& g)
{
return mk_range(vertices(g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto edges_range(const Graph& g)
{
return mk_range(edges(g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto adjacent_vertices_range(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(adjacent_vertices(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto out_edges_range(typename out_edge_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(out_edge_iteratorS<Graph>::get_edges(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto out_neighbors_range(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(out_neighbors(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto in_edges_range(typename in_edge_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(in_edge_iteratorS<Graph>::get_edges(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto in_neighbors_range(typename boost::graph_traits<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(in_neighbors(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto all_edges_range(typename all_edges_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(all_edges(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto all_neighbors_range(typename all_neighbors_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(all_neighbors(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto in_or_out_edges_range(typename in_or_out_edge_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(in_or_out_edge_iteratorS<Graph>::get_edges(v, g));
}
template <class Graph>
inline __attribute__((always_inline)) __attribute__((flatten))
auto in_or_out_neighbors_range(typename in_or_out_edge_iteratorS<Graph>::vertex_descriptor v,
const Graph& g)
{
return mk_range(in_or_out_edge_iteratorS<Graph>::get_neighbors(v, g));
}
// useful type lists
struct degree_selectors:
boost::mpl::vector<in_degreeS, out_degreeS, total_degreeS> {};
struct vertex_properties:
property_map_types::apply<value_types,
GraphInterface::vertex_index_map_t>::type {};
struct writable_vertex_properties:
property_map_types::apply<value_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_properties:
property_map_types::apply<value_types,
GraphInterface::edge_index_map_t>::type {};
struct writable_edge_properties:
property_map_types::apply<value_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_scalar_properties:
property_map_types::apply<scalar_types,
GraphInterface::vertex_index_map_t>::type {};
struct writable_vertex_scalar_properties:
property_map_types::apply<scalar_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_integer_properties:
property_map_types::apply<integer_types,
GraphInterface::vertex_index_map_t>::type {};
struct vertex_floating_properties:
property_map_types::apply<floating_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_scalar_vector_properties:
property_map_types::apply<scalar_vector_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_integer_vector_properties:
property_map_types::apply<integer_vector_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_floating_vector_properties:
property_map_types::apply<floating_vector_types,
GraphInterface::vertex_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_scalar_properties:
property_map_types::apply<scalar_types,
GraphInterface::edge_index_map_t>::type {};
struct writable_edge_scalar_properties:
property_map_types::apply<scalar_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_integer_properties:
property_map_types::apply<integer_types,
GraphInterface::edge_index_map_t>::type {};
struct edge_floating_properties:
property_map_types::apply<floating_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_scalar_vector_properties:
property_map_types::apply<scalar_vector_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_integer_vector_properties:
property_map_types::apply<integer_vector_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct edge_floating_vector_properties:
property_map_types::apply<floating_vector_types,
GraphInterface::edge_index_map_t,
boost::mpl::bool_<false> >::type {};
struct vertex_scalar_selectors:
boost::mpl::transform<vertex_scalar_properties,
scalar_selector_type>::type {};
struct all_selectors:
boost::mpl::transform<vertex_properties,
scalar_selector_type,
boost::mpl::back_inserter<degree_selectors> >::type {};
struct scalar_selectors:
boost::mpl::transform<vertex_scalar_properties,
scalar_selector_type,
boost::mpl::back_inserter<degree_selectors> >::type {};
} //namespace graph_tool
#endif
| 34.508453 | 111 | 0.649734 | [
"vector",
"transform"
] |
e2c79f5494b07869238ddd9afbba460db2797093 | 3,309 | cpp | C++ | lib/cfganalyzer-2007-12-03/zchaff-src/cnf_stats.cpp | akiezun/hampi | de62cc822f927399ea0260be75185f723acf9839 | [
"MIT"
] | 1 | 2022-03-17T07:16:42.000Z | 2022-03-17T07:16:42.000Z | lib/cfganalyzer-2007-12-03/zchaff-src/cnf_stats.cpp | akiezun/hampi | de62cc822f927399ea0260be75185f723acf9839 | [
"MIT"
] | null | null | null | lib/cfganalyzer-2007-12-03/zchaff-src/cnf_stats.cpp | akiezun/hampi | de62cc822f927399ea0260be75185f723acf9839 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <set>
#include <vector>
#include <assert.h>
using namespace std;
const int MAX_WORD_LENGTH = 64;
const int MAX_LINE_LENGTH = 256000;
int main(int argc, char** argv) {
assert(argc == 2);
char * filename = argv[1];
int line_num = 0;
char line_buffer[MAX_LINE_LENGTH];
char word_buffer[MAX_WORD_LENGTH];
set<int> clause_vars;
set<int> clause_lits;
int num_cls = 0;
vector<bool> variables;
int var_num;
int cl_num;
ifstream inp(filename, ios::in);
if (!inp) {
cerr << "Can't open input file" << endl;
exit(1);
}
while (inp.getline(line_buffer, MAX_LINE_LENGTH)) {
++line_num;
if (line_buffer[0] == 'c') {
continue;
}
else if (line_buffer[0] == 'p') {
int arg = sscanf(line_buffer, "p cnf %d %d", &var_num, &cl_num);
if (arg < 2) {
cerr << "Unable to read number of variables and clauses"
<< "at line " << line_num << endl;
exit(3);
}
variables.resize(var_num + 1);
for (int i = 0; i < var_num + 1; ++i)
variables[i] = false;
} else { // Clause definition or continuation
char *lp = line_buffer;
do {
char *wp = word_buffer;
while (*lp && ((*lp == ' ') || (*lp == '\t'))) {
lp++;
}
while (*lp && (*lp != ' ') && (*lp != '\t') && (*lp != '\n')) {
*(wp++) = *(lp++);
}
*wp = '\0'; // terminate string
if (strlen(word_buffer) != 0) { // check if number is there
int var_idx = atoi(word_buffer);
int sign = 0;
if (var_idx != 0) {
if (var_idx < 0) {
var_idx = -var_idx;
sign = 1;
}
clause_vars.insert(var_idx);
clause_lits.insert((var_idx << 1) + sign);
} else {
// add this clause
if (clause_vars.size() != 0 &&
clause_vars.size() == clause_lits.size()) {
vector <int> temp;
for (set<int>::iterator itr = clause_lits.begin();
itr != clause_lits.end(); ++itr)
temp.push_back(*itr);
for (unsigned i = 0; i < temp.size(); ++i)
variables[temp[i]>>1] = true;
++num_cls;
} else {
cout << "Literals of both polarity at line "
<< line_num << ", clause skipped " << endl;
}
// it contain var of both polarity, so is automatically
// satisfied, just skip it
clause_lits.clear();
clause_vars.clear();
}
}
}
while (*lp);
}
}
if (!inp.eof()) {
cerr << "Input line " << line_num << " too long. Unable to continue..."
<< endl;
exit(2);
}
assert(clause_vars.size() == 0);
int num_vars = 0;
for (unsigned i = 0; i < variables.size(); ++i) {
if (variables[i])
++num_vars;
}
cout <<"Statistics of CNF file:\t\t" << filename << "\n"
<<" Claim:\t\t Cl: " << cl_num << "\t Var: " << var_num << "\n"
<<" Actual:\t Cl: " << num_cls << "\t Var: " << num_vars << endl;
return 0;
}
| 29.283186 | 77 | 0.481414 | [
"vector"
] |
e2c990adcc200718cf2f06fd2c36df5a0250366a | 16,213 | cxx | C++ | xp_comm_proj/draw/sup_draw.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 3 | 2020-08-03T08:52:20.000Z | 2021-04-10T11:55:49.000Z | xp_comm_proj/draw/sup_draw.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | null | null | null | xp_comm_proj/draw/sup_draw.cxx | avs/express-community | c699a68330d3b678b7e6bcea823e0891b874049c | [
"Apache-2.0"
] | 1 | 2021-06-08T18:16:45.000Z | 2021-06-08T18:16:45.000Z | //
// Super polyline editor for AVS/Express
//
// Provides more control and speed compared to Click Sketch.
//
// command:
// 0 no op
// 1 add point at the end of the polyline
// 2 add point between
// 3 move point
// 4 delete point
// 5 delete all points
// 6 translate the whole line
//
//
// Author: Mario Valle
// Date: 20-may-2000
//
#include <avs/util.h>
#include <avs/om.h>
#include <avs/om_type.h>
#include <avs/gd.h>
#include <malloc.h>
#include "sd_gen.h"
//
// Adapted interface to draw routines (the official definition lives in <gd/sw/swx.h>)
//
extern "C" void GD2d_draw_lines(GDstate *, int, short[], float[], float[]);
extern "C" void GD2d_draw_polyline(GDstate *, int, short[], float[], float[], int);
//
// Point list initial size (multiplied by INCREMENT every time overflows)
//
#define INITIAL_SIZE 50
#define INCREMENT 2
//
// Commands
//
#define CMD_INACTIVE 0
#define CMD_APPEND 1
#define CMD_INSERT 2
#define CMD_MOVE 3
#define CMD_DELETE 4
#define CMD_RESET 5
#define CMD_TRANSLATE 6
//
// Line types
//
#define LINE_OPEN 0
#define LINE_CLOSED 1
//
// Mouse sensitivity
//
#define TRESHOLD 2
//
// Distance measurement functions (defined in Distance.cxx)
//
extern float point_segment_squared_dist(short px, short py, short segstartx, short segstarty, short segendx, short segendy);
extern int find_nearest_segment(short *pt, int npt, short x, short y);
extern int find_nearest_point(short *pt, int npt, short x, short y);
//
// Enlarge the points list if needed
//
static void check_size(struct SuperDrawStatus *st)
{
if(st->npt >= st->len-1)
{
st->len *= INCREMENT;
st->pt = (short *)realloc(st->pt, st->len*sizeof(short)*2);
}
}
//
// Reads camera, view and object. Return 1 on error
//
int Draw_DrawMods_SuperDrawCore::setup_environment(struct SuperDrawStatus *st)
{
OMobj_id view_id, cam_id, obj_id, tmp_id;
//
// Get the view structure pointer
//
view_id = OMfind_subobj(*this, OMstr_to_name("view"), OM_OBJ_RD);
if (OMis_null_obj(view_id))
{
ERRerror("SuperDraw::setup_environment", 1, ERR_ORIG, "Can't get view\n");
return 1;
}
st->view = (GDview *)GDget_local(view_id, (OMpfi)GDview_init);
if (!st->view)
{
ERRerror("SuperDraw::setup_environment", 1, ERR_ORIG, "Can't get view information\n");
return 1;
}
if (!st->view->Winfo || !st->view->State)
{
//ERRerror("SuperDraw::setup_environment", 1, ERR_ORIG, "Winfo or State not initialized in view\n");
return 1;
}
//
// Get the camera
//
tmp_id = OMfind_subobj(*this, OMstr_to_name("camera"), OM_OBJ_RD);
if (OMis_null_obj(tmp_id))
return 1;
if (OMget_obj_val(tmp_id, &cam_id) != OM_STAT_SUCCESS)
{
ERRerror("SuperDraw::setup_environment", 1, ERR_ORIG, "Can't create output without camera\n");
return 1;
}
st->camera = (GDcamera *)GDget_local(cam_id, (OMpfi)GDcamera_create);
if (!st->camera)
{
ERRerror("SuperDraw::setup_environment", 1, ERR_ORIG, "Can't create output without camera\n");
return 1;
}
//
// The object is optional. If we don't have one the points
// are mapped back to the camera's space.
//
tmp_id = OMfind_subobj(*this, OMstr_to_name("obj"), OM_OBJ_RD);
if (OMis_null_obj(tmp_id))
st->object = NULL;
else if (OMget_obj_val(tmp_id, &obj_id) != OM_STAT_SUCCESS)
st->object = NULL;
else
st->object = (GDobject *)GDget_local(obj_id, (OMpfi)GDobject_create);
return 0;
}
//
// Output world coordinates points
//
void Draw_DrawMods_SuperDrawCore::output_points(struct SuperDrawStatus *st)
{
float mat[4][4], invmat[4][4];
int size;
float *points_arr;
//
// Open the line if the user ask for an open line and the line was closed
// and the number of points was >=4
//
if(st->is_closed && (!st->want_line_closed || st->npt < 4))
{
st->is_closed = false;
st->npt--;
}
//
// Close the line if the user so requested and the line was open
// and there is a sufficient number of points
//
else if(st->want_line_closed && !st->is_closed && st->npt > 2)
{
st->is_closed = true;
st->pt[st->npt*2+0] = st->pt[0];
st->pt[st->npt*2+1] = st->pt[1];
st->npt++;
check_size(st);
}
npoints = st->npt;
if(!st->npt)
{
points.set_array(OM_TYPE_FLOAT, NULL, 0, OM_SET_ARRAY_FREE);
npoints = 0;
}
else
{
points_arr = (float *)points.ret_array_ptr(OM_GET_ARRAY_WR, &size);
if(points_arr)
{
//
// Get the full matrix associated with the object. This
// includes the camera matrix and all object matricies
// including the object's.
//
GDmap_get_matrix(st->view, st->camera, st->object, &mat[0][0], 1);
//
// Take the inverse of the matrix and map the points
//
MATmat4_inverse(invmat, mat);
GDmap_ss_to_2dworld(st->camera, &invmat[0][0], st->npt, st->pt, points_arr);
ARRfree(points_arr);
}
}
}
//
// Map world coordinates points back to screen coordinates. Also syncronize the internal list of points
//
void Draw_DrawMods_SuperDrawCore::setup_pt(struct SuperDrawStatus *st)
{
float mat[4][4];
int size;
float *points_arr;
points_arr = (float *)points.ret_array_ptr(OM_GET_ARRAY_RD, &size);
if(points_arr)
{
if(size/2 >= st->len)
{
free((void *)st->pt);
st->len = size/2;
st->pt = (short *)malloc(sizeof(short)*2*size/2);
}
st->npt = size/2;
if(size)
{
float *points;
ALLOCN(points, float, st->npt*2, "can't alloc line buffer");
//
// Get the full matrix associated with the object. This
// includes the camera matrix and all object matricies
// including the object's.
//
GDmap_get_matrix(st->view, st->camera, st->object, &mat[0][0], 1);
//
// Multiply the coordinates for the transformation matrix
//
MATxform_verts2(st->npt, (Matr2*)points_arr, (Matr4*)mat, (Matr2*)points);
//
// Then correct the position back to screen coordinates.
// The first step is to correct the y positions which
// are from the windowing system which has 0,0 in the
// upper left to world space where 0,0 is in the center
// and xmax, ymax is in the upper left.
// While doing this we also transform the points from the -1,1 range
// back to their screen space values.
//
for(int i=0; i<st->npt; i++)
{
double xs = (points[2*i+0] + 1.0)*(st->camera->vp_xmax - st->camera->vp_xmin)/2. + st->camera->vp_xmin;
double ys = -((points[2*i+1] + 1.0)*(st->camera->vp_ymax - st->camera->vp_ymin)/2. - st->camera->vp_ymax + st->camera->vp_ymin);
st->pt[2*i+0] = (short)(xs + 0.5);
st->pt[2*i+1] = (short)(ys + 0.5);
}
// Free the temporary points array.
FREE(points);
}
ARRfree(points_arr);
}
else
{
st->npt = 0;
}
}
int
Draw_DrawMods_SuperDrawCore::OnInstance(OMevent_mask event_mask, int seq_num)
{
// local_ptr (OMXptr read write)
struct SuperDrawStatus *st;
st = (struct SuperDrawStatus *)malloc(sizeof(struct SuperDrawStatus));
if(!st) return 0;
OMset_ptr_val((OMobj_id)local_ptr, (void *)st, 0);
st->prev_state = 3;
st->npt = 0;
st->len = INITIAL_SIZE;
st->pt = (short *)malloc(sizeof(short)*2*INITIAL_SIZE);
st->is_closed = false;
st->want_line_closed = false;
st->must_update = false;
st->first_point = false;
// return 1 for success
return 1;
}
int
Draw_DrawMods_SuperDrawCore::OnDeinstance(OMevent_mask event_mask, int seq_num)
{
// local_ptr (OMXptr read write)
struct SuperDrawStatus *st;
OMget_ptr_val((OMobj_id)local_ptr, (void **)&st, 0);
if(!st) return 0;
free((void *)st->pt);
free((void *)st);
OMset_ptr_val((OMobj_id)local_ptr, (void *)0, 0);
// return 1 for success
return 1;
}
int
Draw_DrawMods_SuperDrawCore::OnDraw(OMevent_mask event_mask, int seq_num)
{
// x (OMXfloat read req)
// y (OMXfloat read req)
// state (OMXint read req notify)
// camera (GDcamera_templ read)
// obj (GDobject_templ read req notify)
// view (GDview_templ read req notify)
// command (OMXint read req notify)
// npoints (OMXint write)
// local_ptr (OMXptr read)
short lines[16];
int i, size, idx;
//
// Access the local status and check for correct initialization.
//
struct SuperDrawStatus *st;
OMget_ptr_val((OMobj_id)local_ptr, (void **)&st, 0);
if(!st || !st->pt) return 0;
//
// Get Camera, View and Object
//
if(setup_environment(st))
return 0;
//
// Record the line type requested by the user.
// The real setup is in output_points()
//
st->want_line_closed = ((int)line_type == LINE_CLOSED);
if(line_type.changed(seq_num))
{
output_points(st);
}
//
// Do nothing
//
if((int)command == CMD_INACTIVE) return 0;
//
// Read screen coordinates on button down
//
if((int)command != CMD_RESET && state == 1) setup_pt(st);
//
// Push start of rendering marker onto the stack so we can
// restore original attributes when we are done.
//
GDstack_push(st->view);
//
// Set the color to be used for drawing
//
float white[3];
float *colors_arr = (float *)colors.ret_array_ptr(OM_GET_ARRAY_RD, &size);
if(!colors_arr || size != 3)
{
white[0] = white[1] = white[2] = 1.0;
colors_arr = white;
}
GDstate_set_color(st->view, colors_arr);
//
// Tell GD to use the front buffer (ie. window) as the
// drawble. This allows our drawing to be visible even if
// we are in double buffer mode.
// Also set draw mode to XOR.
//
GDstate_set_drawable(st->view, 1);
GDstate_set_draw_mode(st->view, 1);
GDstate_set_line_width(st->view, ((int)width < 0) ? 0 : (int)width);
//
// Now execute the command
//
switch(command)
{
case CMD_INACTIVE:
// No-op
break;
case CMD_APPEND:
// Append point (only to an open line)
if(!st->is_closed)
{
switch(state)
{
case 1:
if(st->npt == 0)
{
st->npt = 1;
st->pt[0] = x;
st->pt[1] = y;
st->first_point = true;
st->must_update = true;
}
else
{
lines[0] = st->pt[st->npt*2-2];
lines[1] = st->pt[st->npt*2-1];
lines[2] = x;
lines[3] = y;
GD2d_draw_lines(st->view->State, 2, lines, NULL, NULL);
}
break;
case 2:
lines[0] = st->pt[st->npt*2-2];
lines[1] = st->pt[st->npt*2-1];
lines[2] = st->prev_x;
lines[3] = st->prev_y;
lines[4] = st->pt[st->npt*2-2];
lines[5] = st->pt[st->npt*2-1];
lines[6] = x;
lines[7] = y;
GD2d_draw_lines(st->view->State, 4, lines, NULL, NULL);
if(!(((st->prev_x - x) < TRESHOLD) && ((st->prev_x - x) > -TRESHOLD) &&
((st->prev_y - y) < TRESHOLD) && ((st->prev_y - y) > -TRESHOLD)))
st->first_point = false;
break;
case 3:
if(st->prev_state == 3) break;
if(st->first_point)
{
st->first_point = false;
}
else
{
lines[0] = st->pt[st->npt*2-2];
lines[1] = st->pt[st->npt*2-1];
lines[2] = st->prev_x;
lines[3] = st->prev_y;
GD2d_draw_lines(st->view->State, 2, lines, NULL, NULL);
st->pt[st->npt*2+0] = x;
st->pt[st->npt*2+1] = y;
st->npt++;
check_size(st);
st->must_update = true;
}
}
break;
}
// FALLTHROUGH
case CMD_INSERT:
// Add point between
if(st->npt < 2) break;
switch(state)
{
case 1:
st->prev_idx = find_nearest_segment(st->pt, st->npt, x, y);
st->npt++;
check_size(st);
for(i=st->npt-2; i > st->prev_idx; i--)
{
st->pt[2*i+2] = st->pt[2*i+0];
st->pt[2*i+3] = st->pt[2*i+1];
}
st->pt[2*st->prev_idx+2] = x;
st->pt[2*st->prev_idx+3] = y;
GD2d_draw_polyline(st->view->State, 3, &st->pt[2*st->prev_idx], NULL, NULL, 0);
break;
case 2:
GD2d_draw_polyline(st->view->State, 3, &st->pt[2*st->prev_idx], NULL, NULL, 0);
st->pt[2*st->prev_idx+2] = x;
st->pt[2*st->prev_idx+3] = y;
GD2d_draw_polyline(st->view->State, 3, &st->pt[2*st->prev_idx], NULL, NULL, 0);
break;
case 3:
if(st->prev_state == 3) break;
GD2d_draw_polyline(st->view->State, 3, &st->pt[2*st->prev_idx], NULL, NULL, 0);
st->pt[2*st->prev_idx+2] = x;
st->pt[2*st->prev_idx+3] = y;
st->must_update = true;
}
break;
case CMD_MOVE:
// Move point
if(st->npt == 0) break;
switch(state)
{
case 1:
st->prev_idx = find_nearest_point(st->pt, st->npt, x, y);
if(st->is_closed)
{
st->llen = 3;
if(st->prev_idx == 0 || st->prev_idx == st->npt-1)
{
st->l[0] = st->pt[2*st->npt-4];
st->l[1] = st->pt[2*st->npt-3];
st->l[2] = x;
st->l[3] = y;
st->l[4] = st->pt[2];
st->l[5] = st->pt[3];
}
else if(st->prev_idx == st->npt-2)
{
st->l[0] = st->pt[2*st->prev_idx-2];
st->l[1] = st->pt[2*st->prev_idx-1];
st->l[2] = x;
st->l[3] = y;
st->l[4] = st->pt[0];
st->l[5] = st->pt[1];
}
else
{
st->l[0] = st->pt[2*st->prev_idx-2];
st->l[1] = st->pt[2*st->prev_idx-1];
st->l[2] = x;
st->l[3] = y;
st->l[4] = st->pt[2*st->prev_idx+2];
st->l[5] = st->pt[2*st->prev_idx+3];
}
}
else
{
if(st->prev_idx == 0)
{
st->llen = 2;
st->l[0] = st->pt[2];
st->l[1] = st->pt[3];
st->l[2] = x;
st->l[3] = y;
}
else if(st->prev_idx == st->npt-1)
{
st->llen = 2;
st->l[0] = st->pt[2*st->npt-4];
st->l[1] = st->pt[2*st->npt-3];
st->l[2] = x;
st->l[3] = y;
}
else
{
st->llen = 3;
st->l[0] = st->pt[2*st->prev_idx-2];
st->l[1] = st->pt[2*st->prev_idx-1];
st->l[2] = x;
st->l[3] = y;
st->l[4] = st->pt[2*st->prev_idx+2];
st->l[5] = st->pt[2*st->prev_idx+3];
}
}
GD2d_draw_polyline(st->view->State, st->llen, st->l, NULL, NULL, 0);
break;
case 2:
GD2d_draw_polyline(st->view->State, st->llen, st->l, NULL, NULL, 0);
st->l[2] = x;
st->l[3] = y;
GD2d_draw_polyline(st->view->State, st->llen, st->l, NULL, NULL, 0);
break;
case 3:
if(st->prev_state == 3) break;
GD2d_draw_polyline(st->view->State, st->llen, st->l, NULL, NULL, 0);
st->pt[2*st->prev_idx+0] = x;
st->pt[2*st->prev_idx+1] = y;
if(st->is_closed)
{
if(st->prev_idx == 0)
{
st->pt[2*st->npt-2] = x;
st->pt[2*st->npt-1] = y;
}
else if(st->prev_idx == st->npt-1)
{
st->pt[0] = x;
st->pt[1] = y;
}
}
st->must_update = true;
break;
}
break;
case CMD_DELETE:
// Delete point
if(st->prev_state != 3 && state == 3 && st->npt > 0)
{
idx = find_nearest_point(st->pt, st->npt, x, y);
if(st->is_closed)
{
if(idx == 0 || idx == st->npt-1)
{
for(i=0; i < st->npt-1; i++)
{
st->pt[2*i+0] = st->pt[2*i+2];
st->pt[2*i+1] = st->pt[2*i+3];
}
st->pt[2*st->npt-4] = st->pt[0];
st->pt[2*st->npt-3] = st->pt[1];
}
else
{
for(i=idx; i < st->npt-1; i++)
{
st->pt[2*i+0] = st->pt[2*i+2];
st->pt[2*i+1] = st->pt[2*i+3];
}
}
}
else
{
for(i=idx; i < st->npt-1; i++)
{
st->pt[2*i+0] = st->pt[2*i+2];
st->pt[2*i+1] = st->pt[2*i+3];
}
}
// now make the change effective
st->npt--;
st->must_update = true;
}
break;
case CMD_RESET:
// delete all points (after asking confirmation)
if(!ERRsync_yesno_dialog(1, "Confirmation request", "Do you confirm the whole line deletion?")) break;
st->npt = 0;
command = CMD_INACTIVE;
st->is_closed = false;
st->must_update = true;
break;
case CMD_TRANSLATE:
// translate the whole line
switch(state)
{
case 1:
GD2d_draw_polyline(st->view->State, st->npt, st->pt, NULL, NULL, 0);
break;
case 2:
GD2d_draw_polyline(st->view->State, st->npt, st->pt, NULL, NULL, 0);
for(i=0; i < st->npt; i++)
{
st->pt[2*i+0] += (x - st->prev_x);
st->pt[2*i+1] += (y - st->prev_y);
}
GD2d_draw_polyline(st->view->State, st->npt, st->pt, NULL, NULL, 0);
break;
case 3:
if(st->prev_state == 3) break;
GD2d_draw_polyline(st->view->State, st->npt, st->pt, NULL, NULL, 0);
st->must_update = true;
break;
}
break;
default:
ERRverror("SuperDraw::OnDraw", ERR_ERROR, "Invalid command %d\n", (int)command);
break;
};
//
// Save current xy as prev_xy for erasure on other events
//
st->prev_x = x;
st->prev_y = y;
st->prev_state = state;
GDstack_pop(st->view);
//
// Update the output array
//
if(st->must_update)
{
output_points(st);
st->must_update = false;
}
// return 1 for success
return 1;
}
| 23.161429 | 132 | 0.599519 | [
"object",
"transform"
] |
e2d20ca1f4ae1c5477a0ffa5e2b33743944c1cba | 39,994 | cpp | C++ | MarkerFinderLib/MarkerFinderLib.cpp | hunsteve/RobotNavigation | 880b7b168a5267e740503011cef466216d7e5706 | [
"MIT"
] | 1 | 2017-09-13T23:04:23.000Z | 2017-09-13T23:04:23.000Z | MarkerFinderLib/MarkerFinderLib.cpp | hunsteve/RobotNavigation | 880b7b168a5267e740503011cef466216d7e5706 | [
"MIT"
] | null | null | null | MarkerFinderLib/MarkerFinderLib.cpp | hunsteve/RobotNavigation | 880b7b168a5267e740503011cef466216d7e5706 | [
"MIT"
] | null | null | null | // MarkerFinderLib.cpp : Defines the exported functions for the DLL application.
//
#include "MarkerFinderLib.h"
#include <list>
#include <queue>
#include <vector>
#include <math.h>
#include <iostream>
#include <fstream>
using namespace std;
MyShapeListElement *globalMarkerShapeList;
void create_image_list_N(MyImageListElement** element) {
if (element) {
(*element) = new MyImageListElement();
(*element)->next = NULL;
}
}
void add_image_list_item_N(MyImageListElement** element, MyImage image) {
if (element) {
MyImageListElement* newelement = new MyImageListElement();
newelement->image = image;
MyImageListElement* last = NULL;
MyImageListElement* current = *element;
while(current->next) {
last = current;
current = current->next;
}
newelement->next = current;
if (last) last->next = newelement;
else (*element) = newelement;
}
}
void delete_image_list_D(MyImageListElement* list) {
if (list) {
MyImageListElement* it = list;
while(it->next) {
MyImageListElement* now = it;
it = it->next;
delete now;
}
delete it;
}
}
void delete_contour_D(MyContourPoint* contour) {
if (contour) {
MyContourPoint* it = contour;
while(it->next) {
MyContourPoint* now = it;
it = it->next;
delete now;
}
delete it;
}
}
void delete_shape_list_D(MyShapeListElement* shapeList) {
if (shapeList) {
MyShapeListElement* it = shapeList;
while(it->next) {
MyShapeListElement* now = it;
it = it->next;
delete_contour_D(now->shape.contour);
delete now;
}
delete it;
}
}
void clone_contour_N(MyContourPoint* src, MyContourPoint** dest) {
if (src && dest) {
MyContourPoint* it = src;
MyContourPoint* it2 = (*dest) = new MyContourPoint();
while(it->next) {
it2->pos = it->pos;
it2->next = new MyContourPoint();
it2 = it2->next;
it = it->next;
}
it2->next = NULL;
}
}
void clone_shape_N(MyShape src, MyShape* dest) {
if (dest) {
(*dest).index = src.index;
(*dest).pos = src.pos;
(*dest).rot = src.rot;
(*dest).scale = src.scale;
clone_contour_N(src.contour,&((*dest).contour));
}
}
void clone_image_N(MyImage src, MyImage* dest) {
if (dest) {
dest->w = src.w;
dest->h = src.h;
dest->img = new uint[src.w * src.h];
for(int i = 0; i < src.w * src.h; ++i) {
dest->img[i] = src.img[i];
}
}
}
void delete_image_D(MyImage im) {
if (im.img) delete[] im.img;
}
void dilatation(MyImage im)
{
int w = im.w;
int h = im.h;
uint* img = im.img;
if (img) {
uint* ret = new uint[w * h];
for (int x = 1; x < w - 1; ++x)
{
for (int y = 1; y < h - 1; ++y)
{
bool match = false;
for (int dx = -1; dx <= 1; ++dx)
{
for (int dy = -1; dy <= 1; ++dy)
{
if (img[x + dx + (y + dy) * w]) match = true;
}
}
if (match) ret[x + y * w] = 1;
else ret[x + y * w] = 0;
}
}
for(int i = 0; i < w; ++i)
{
ret[i + 0 * w] = 0;
ret[i + (h-1) * w] = 0;
}
for(int i = 0; i < h; ++i)
{
ret[0 + i * w] = 0;
ret[w-1 + i * w] = 0;
}
for (int i = 0; i < w * h; ++i)
{
img[i] = ret[i];
}
delete[] ret;
}
}
void erosion(MyImage im)
{
int w = im.w;
int h = im.h;
uint* img = im.img;
if (img) {
uint* ret = new uint[w * h];
for (int x = 1; x < w - 1; ++x)
{
for (int y = 1; y < h - 1; ++y)
{
bool match = false;
for (int dx = -1; dx <= 1; ++dx)
{
for (int dy = -1; dy <= 1; ++dy)
{
if (!img[x + dx + (y + dy) * w]) match = true;
}
}
if (match) ret[x + y * w] = 0;
else ret[x + y * w] = 1;
}
}
for(int i = 0; i < w; ++i)
{
ret[i + 0 * w] = 0;
ret[i + (h-1) * w] = 0;
}
for(int i = 0; i < h; ++i)
{
ret[0 + i * w] = 0;
ret[w-1 + i * w] = 0;
}
for (int i = 0; i < w * h; ++i)
{
img[i] = ret[i];
}
delete[] ret;
}
}
void opening(MyImage im)
{
erosion(im);
dilatation(im);
}
void closing(MyImage im)
{
dilatation(im);
erosion(im);
}
void RGB2HSL (uint rgb, double* h, double* s, double* l)
{
double r = ((unsigned char*)&rgb)[2];
double g = ((unsigned char*)&rgb)[1];
double b = ((unsigned char*)&rgb)[0];
double v;
double m;
double vm;
double r2, g2, b2;
*h = 0; // default to black
*s = 0;
*l = 0;
v = max(r,g);
v = max(v,b);
m = min(r,g);
m = min(m,b);
*l = (m + v) / 2.0;
if (*l <= 0.0)
{
return;
}
vm = v - m;
*s = vm;
if (*s > 0.0)
{
*s /= (*l <= 0.5) ? (v + m ) : (2.0 - v - m) ;
}
else
{
return;
}
r2 = (v - r) / vm;
g2 = (v - g) / vm;
b2 = (v - b) / vm;
if (r == v)
{
*h = (g == m ? 5.0 + b2 : 1.0 - g2);
}
else if (g == v)
{
*h = (b == m ? 1.0 + r2 : 3.0 - b2);
}
else
{
*h = (r == m ? 3.0 + g2 : 5.0 - r2);
}
*h /= 6.0;
}
void substract(MyImage im1, MyImage im2)
{
if ((im1.w == im2.w) && (im1.h == im2.h) && im1.img && im2.img)
{
for (int i = 0; i < im1.w * im1.h; ++i)
{
if ((im1.img[i]) && (!im2.img[i])) im1.img[i] = 1;
else im1.img[i] = 0;
}
}
}
void contour(MyImage im)
{
MyImage im2;
clone_image_N(im,&im2);
dilatation(im);
substract(im, im2);
delete_image_D(im2);
}
void clear_blob(MyImage im, MyPoint point)
{
queue<MyPoint> pointQueue;
uint* img = im.img;
int xx = point.X;
int yy = point.Y;
int w = im.w;
int h = im.h;
if (img) {
pointQueue.push(MyPoint(xx, yy));
img[xx + yy * w] = 0;
while (!pointQueue.empty())
{
const MyPoint p = pointQueue.front();
const int& x = p.X;
const int& y = p.Y;
pointQueue.pop();
if ((x - 1 >= 0) && (img[x - 1 + y * w] != 0))
{
img[x - 1 + y * w] = 0;
pointQueue.push(MyPoint(x - 1, y));
}
if ((x + 1 < w) && (img[x + 1 + y * w] != 0))
{
img[x + 1 + y * w] = 0;
pointQueue.push(MyPoint(x + 1, y));
}
if ((y - 1 >= 0) && (img[x + (y - 1) * w] != 0))
{
img[x + (y - 1) * w] = 0;
pointQueue.push(MyPoint(x, y - 1));
}
if ((y + 1 < h) && (img[x + (y + 1) * w] != 0))
{
img[x + (y + 1) * w] = 0;
pointQueue.push(MyPoint(x, y + 1));
}
}
}
}
void segment_background_HSL(MyImage imFore, MyImage imBack, uint treshold)
{
uint* img = imFore.img;
int w = imFore.w;
int h = imFore.h;
uint* bg = imBack.img;
int bgw = imBack.w;
int bgh = imBack.h;
if (img && bg) {
int* dif = new int[w * h];
for(int i=0; i<w*h; ++i)
{
uint c1 = img[i];
uint c2 = bg[i];
double h1,s1,l1,h2,s2,l2;
RGB2HSL(c1, &h1, &s1, &l1);
RGB2HSL(c2, &h2, &s2, &l2);
int dh = (h1 - h2) *255.0;
int ds = (s1 - s2) *255.0;
int dl = (l1 - l2) *255.0;
dif[i] = (dh * dh + ds * ds);
}
for (int x = 1; x < w - 1; ++x)
{
for (int y = 1; y < h - 1; ++y)
{
uint diff = 0;
for (int dx = -1; dx <= 1; ++dx)
{
for (int dy = -1; dy <= 1; ++dy)
{
diff += dif[x + dx + (y + dy) * w];
}
}
if (diff < treshold) img[x + y * w] = 0;
else img[x + y * w] = 1;
}
}
delete[] dif;
}
}
void segment_background(MyImage imFore, MyImage imBack, uint treshold)
{
uint* img = imFore.img;
int w = imFore.w;
int h = imFore.h;
uint* bg = imBack.img;
int bgw = imBack.w;
int bgh = imBack.h;
if (img && bg) {
int* dif = new int[w * h];
for(int i=0; i<w*h; ++i)
{
uint c1 = img[i];
uint c2 = bg[i];
unsigned char a1 = ((unsigned char*)&c1)[3];
unsigned char r1 = ((unsigned char*)&c1)[2];
unsigned char g1 = ((unsigned char*)&c1)[1];
unsigned char b1 = ((unsigned char*)&c1)[0];
unsigned char a2 = ((unsigned char*)&c2)[3];
unsigned char r2 = ((unsigned char*)&c2)[2];
unsigned char g2 = ((unsigned char*)&c2)[1];
unsigned char b2 = ((unsigned char*)&c2)[0];
int dr = (r1 - r2);
int dg = (g1 - g2);
int db = (b1 - b2);
dif[i] = dr * dr + dg * dg + db * db;
}
for (int x = 1; x < w - 1; ++x)
{
for (int y = 1; y < h - 1; ++y)
{
uint diff = 0;
for (int dx = -1; dx <= 1; ++dx)
{
for (int dy = -1; dy <= 1; ++dy)
{
diff += dif[x + dx + (y + dy) * w];
}
}
if (diff < treshold) img[x + y * w] = 0;
else img[x + y * w] = 1;
}
}
delete[] dif;
}
}
void segment_kmeans(MyImage im, int levels)
{
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img) {
int* means = new int[levels * 4];
uint* ret = new uint[w * h];
//"veletlenszeru" besorolas
for (int i = 0; i < w * h; ++i)
{
ret[i] = i % levels;
}
int changed;
do
{
//nullazas
for (int j = 0; j < levels; ++j)
{
for (int i = 0; i < 4; ++i)
{
means[j * 4 + i] = 0;
}
}
//kozeppontok szamitasa a besorolasok alapjan
for (int i = 0; i < w * h - 7; i += 8)
{
uint j = ret[i];
uint c1 = img[i];
unsigned char a1 = ((unsigned char*)&c1)[3];
unsigned char r1 = ((unsigned char*)&c1)[2];
unsigned char g1 = ((unsigned char*)&c1)[1];
unsigned char b1 = ((unsigned char*)&c1)[0];
if (a1 == 0xFF)//ha alpha nem FF, akkor nem vesszuk figyelembe
{
means[j * 4 + 0] += r1;
means[j * 4 + 1] += g1;
means[j * 4 + 2] += b1;
means[j * 4 + 3]++;
}
}
//atlagolas osztasa
for (int j = 0; j < levels; ++j)
{
if (means[j * 4 + 3] != 0)
{
for (int i = 0; i < 3; ++i)
{
means[j * 4 + i] /= means[j * 4 + 3];
}
}
}
//pontok ujra besorolasa
changed = 0;
for (int i = 0; i < w * h; ++i)
{
uint minj = 0;
uint min = 0xFFFFFFFF;
for (int j = 0; j < levels; ++j)
{
uint c1 = img[i];
uint a1 = (c1 >> 24) % 256;
if (a1 == 0xFF)//csak akkor soroljuk be, ha FF az alpha ertek, amugy fixen levels lesz;
{
uint r1 = ((unsigned char*)&c1)[2] - means[j * 4 + 0];
uint g1 = ((unsigned char*)&c1)[1] - means[j * 4 + 1];
uint b1 = ((unsigned char*)&c1)[0] - means[j * 4 + 2];
uint dist = r1 * r1 + b1 * b1 + g1 * g1;
if (dist < min)
{
min = dist;
minj = j;
}
}
else minj = levels;
}
if (ret[i] != minj) changed++;
ret[i] = minj;
}
}
while (changed > w*h / 10);
for (int i = 0; i < w * h; ++i)
{
int j = (int)ret[i];
if (j < levels) img[i] = 0xFF000000 + 0x00010000 * means[j * 4 + 0] + 0x00000100 * means[j * 4 + 1] + 0x00000001 * means[j * 4 + 2];
else img[i] = 0x00000000;
}
delete[] ret;
delete[] means;
}
}
void binarize(MyImage im, uint color0, uint color1)
{
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img) {
uint cA, cB;
cA = cB = 0;
int j = 0;
while((cB == 0) && (j < w*h))
{
uint c = img[j];
uint a = (c >> 24) % 256;
if (a == 0xFF)
{
if (cA == 0) cA = c;
else if ((cB == 0)&&(cA != c)) cB = c;
}
++j;
}
if ((cA != 0) && (cB != 0))
{
uint rA0 = ((unsigned char*)&cA)[2] - ((unsigned char*)&color0)[2];
uint gA0 = ((unsigned char*)&cA)[1] - ((unsigned char*)&color0)[1];
uint bA0 = ((unsigned char*)&cA)[0] - ((unsigned char*)&color0)[0];
uint rB1 = ((unsigned char*)&cB)[2] - ((unsigned char*)&color1)[2];
uint gB1 = ((unsigned char*)&cB)[1] - ((unsigned char*)&color1)[1];
uint bB1 = ((unsigned char*)&cB)[0] - ((unsigned char*)&color1)[0];
uint rA1 = ((unsigned char*)&cA)[2] - ((unsigned char*)&color1)[2];
uint gA1 = ((unsigned char*)&cA)[1] - ((unsigned char*)&color1)[1];
uint bA1 = ((unsigned char*)&cA)[0] - ((unsigned char*)&color1)[0];
uint rB0 = ((unsigned char*)&cB)[2] - ((unsigned char*)&color0)[2];
uint gB0 = ((unsigned char*)&cB)[1] - ((unsigned char*)&color0)[1];
uint bB0 = ((unsigned char*)&cB)[0] - ((unsigned char*)&color0)[0];
uint distA0B1 = rA0 * rA0 + bA0 * bA0 + gA0 * gA0 + rB1 * rB1 + bB1 * bB1 + gB1 * gB1;
uint distA1B0 = rB0 * rB0 + bB0 * bB0 + gB0 * gB0 + rA1 * rA1 + bA1 * bA1 + gA1 * gA1;
if (distA0B1 < distA1B0)
{
for (int i = 0; i < w * h; ++i)
{
if (img[i] == cB) img[i] = 1;
else img[i] = 0;
}
}
else
{
for (int i = 0; i < w * h; ++i)
{
if (img[i] == cA) img[i] = 1;
else img[i] = 0;
}
}
}
else
{
for (int i = 0; i < w * h; ++i)
{
uint c = img[i];
uint a = (c >> 24) % 256;
if (a == 0xFF) img[i] = 1;
else img[i] = 0;
}
}
}
}
void binarize2(MyImage im, bool inverse) {
int w = im.w;
int h = im.h;
uint* img = im.img;
if (img) {
int* histogram = new int[256];
for(int i=0; i<256; ++i) histogram[i] = 1;
for(int i = 0; i < w * h; ++i)
{
uint c = img[i];
uint a = ((unsigned char*)&c)[3];
uint r = ((unsigned char*)&c)[2];
uint g = ((unsigned char*)&c)[1];
uint b = ((unsigned char*)&c)[0];
if (a == 0xFF) histogram[(r+g+b)/3]++;
}
int cA = 64;
int cB = 196;
for (int j = 0; j < 10; ++j)
{
int center = (cA + cB) / 2;
int halfA = 0;
for(int i=0; i < center; ++i)
{
halfA += histogram[i];
}
halfA /= 2;
cA = 0;
int sumA = 0;
while (sumA < halfA)
{
sumA += histogram[cA];
++cA;
}
--cA;
int halfB = 0;
for(int i=center; i < 256; ++i)
{
halfB += histogram[i];
}
halfB /= 2;
cB = center;
int sumB = 0;
while (sumB < halfB)
{
sumB += histogram[cB];
++cB;
}
--cB;
}
delete[] histogram;
int median = (cA + cB) / 2;
uint aa = 0;
uint bb = 1;
if (inverse) {
aa = 1;
bb = 0;
}
for(int i = 0; i < w * h; ++i)
{
uint c = img[i];
uint a = ((unsigned char*)&c)[3];
uint r = ((unsigned char*)&c)[2];
uint g = ((unsigned char*)&c)[1];
uint b = ((unsigned char*)&c)[0];
if (a == 0xFF)
{
if ((r+g+b)/3 < (uint)median) img[i] = aa;
else img[i] = bb;
}
else img[i] = bb;
}
}
}
void remove_outside(MyImage im, MyContourPoint* contour, uint clearColor)
{
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img && contour) {
int minX = w;
int minY = h;
int maxX = 0;
int maxY = 0;
MyContourPoint* currentContourPoint = contour;
while (currentContourPoint->next) {
MyPoint p = currentContourPoint->pos;
if (p.X > maxX) maxX = p.X;
if (p.X < minX) minX = p.X;
if (p.Y > maxY) maxY = p.Y;
if (p.Y < minY) minY = p.Y;
currentContourPoint = currentContourPoint->next;
}
if (minX < 2) minX = 2;
if (maxX > w-3) maxX = w-3;
if (minY < 2) minY = 2;
if (maxY > h-3) maxY = h-3;
uint* ret = new uint[w * h];
for (int i = 0; i < w * h; ++i) ret[i] = 0;
for (int y = minY-2; y < maxY+2; ++y)
{
for (int x = minX-2; x < maxX+2; ++x)
{
ret[x + y * w] = 1;
}
}
currentContourPoint = contour;
while (currentContourPoint->next) {
MyPoint p = currentContourPoint->pos;
ret[p.X + p.Y * w] = 0;
currentContourPoint = currentContourPoint->next;
}
MyImage im2 = {ret,w,h};
clear_blob(im2 ,MyPoint(minX-1,minY-1));
for (int i = 0; i < w * h; ++i)
{
if (!ret[i]) img[i] = clearColor;
}
delete[] ret;
}
}
void draw_line(MyImage im, MyPoint p1, MyPoint p2, uint color) {
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img) {
int dx = p2.X - p1.X;
int dy = p2.Y - p1.Y;
int adx = abs(dx);
int ady = abs(dy);
int ddx;
if (adx != 0) ddx = dx / adx;
else ddx = 0;
int ddy;
if (ady != 0) ddy = dy / ady;
else ddy = 0;
//if ((x >= 0)&&(x < im.w)&&(y >= 0)&&(y < im.h))
if (adx > ady) {
if (adx == 0) adx = 1;
for(int i=0; i <= adx; ++i)
{
img[p1.X + ddx * i + (p1.Y + (i * dy) / adx) * w] = color;
}
}
else {
if (ady == 0) ady = 1;
for(int i=0; i <= ady; ++i)
{
img[p1.X + (i * dx) / ady + (p1.Y + ddy * i) * w] = color;
}
}
}
}
void draw_shape_lines(MyImage im, MyContourPoint* contour, MyPoint pos, uint color) {
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img && contour) {
MyContourPoint* currentContourPoint = contour;
MyPoint last = currentContourPoint->pos;
last.X += pos.X;
last.Y += pos.Y;
while (currentContourPoint->next) {
MyPoint p = currentContourPoint->pos;
p.X += pos.X;
p.Y += pos.Y;
draw_line(im,p,last,color);
last = p;
currentContourPoint = currentContourPoint->next;
}
MyPoint p = contour->pos;
p.X += pos.X;
p.Y += pos.Y;
draw_line(im,p,last,color);
}
}
void draw_shape(MyImage im, MyContourPoint* contour, MyPoint pos, uint color) {
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img && contour) {
MyContourPoint* currentContourPoint = contour;
while (currentContourPoint->next) {
MyPoint p = currentContourPoint->pos;
int x = pos.X + p.X;
int y = pos.Y + p.Y;
if ((x >= 0)&&(x < im.w)&&(y >= 0)&&(y < im.h)) img[x + y * w] = color;
currentContourPoint = currentContourPoint->next;
}
}
}
void draw_shape_list(MyImage im, MyShapeListElement* shList) {
if (shList) {
MyShapeListElement* currentShapeList = shList;
while (currentShapeList->next) {
draw_shape(im, currentShapeList->shape.contour,currentShapeList->shape.pos,1);
currentShapeList = currentShapeList->next;
}
}
}
void real_contour_N(MyImage im, MyShapeListElement** shapeList)
{
uint* img = im.img;
int w = im.w;
int h = im.h;
if (img && shapeList)
{
vector<vector<MyPoint>> contours;
for (int x = 1; x < w - 1; ++x)
{
for (int y = 1; y < h - 1; ++y)
{
if (img[x + y * w] == 1)
{
vector<MyPoint> contour;
int x2 = x;
int y2 = y;
int phase = 7;
do
{
contour.push_back(MyPoint(x2, y2));
img[x2 + y2 * w]++;
int x20 = x2;
int y20 = y2;
int count = 0;
int x22 = x2;
int y22 = y2;
phase = (phase + 5) % 8;
do
{
switch (phase)
{
case 0:
x22 = x20 + 1;
y22 = y20 + 0;
break;
case 1:
x22 = x20 + 1;
y22 = y20 + 1;
break;
case 2:
x22 = x20 + 0;
y22 = y20 + 1;
break;
case 3:
x22 = x20 + -1;
y22 = y20 + 1;
break;
case 4:
x22 = x20 + -1;
y22 = y20 + 0;
break;
case 5:
x22 = x20 + -1;
y22 = y20 + -1;
break;
case 6:
x22 = x20 + 0;
y22 = y20 + -1;
break;
case 7:
x22 = x20 + 1;
y22 = y20 + -1;
break;
}
count++;
phase = (phase + 1) % 8;
if (x22 < 0) x22 = 0;
if (y22 < 0) y22 = 0;
if (x22 >= w) x22 = w-1;
if (y22 >= h) y22 = h-1;
}
while ((count < 8) && (img[x22 + y22 * w] == 0));
if (count < 8)
{
x2 = x22;
y2 = y22;
}
}
while (((x2 != x) || (y2 != y)) && (img[x2 + y2 * w] < 3));
contours.push_back(contour);
MyImage im2;
im2.img = img;
im2.w = w;
im2.h = h;
clear_blob(im2 ,MyPoint(x2,y2));
}
}
}
MyShapeListElement* shList = (*shapeList) = new MyShapeListElement();
for( vector<vector<MyPoint>>::iterator itcontour=contours.begin(); itcontour!=contours.end(); ++itcontour )
{
MyContourPoint* firstContourPoint;
MyContourPoint* contourPoint = firstContourPoint = new MyContourPoint();
for( vector<MyPoint>::iterator it=(*itcontour).begin(); it!=(*itcontour).end(); ++it )
{
contourPoint->pos = *it;
contourPoint->next = new MyContourPoint();
contourPoint = contourPoint->next;
}
contourPoint->next = NULL;
shList->shape.contour = firstContourPoint;
shList->next = new MyShapeListElement();
shList = shList->next;
}
shList->next = NULL;
draw_shape_list(im,*shapeList);
}
}
void to_complex_N(MyContourPoint* contour, MyComplexData* out)
{
if (contour && out) {
int length = 0;
MyContourPoint* cp = contour;
while(cp->next) {
++length;
cp = cp->next;
}
double* ret = new double[length * 2];
cp = contour;
for (int i = 0; i < length; ++i)
{
ret[2 * i] = cp->pos.X;
ret[2 * i + 1] = cp->pos.Y;
cp = cp->next;
}
out->data = ret;
out->length = length;
}
}
void to_contour_N(MyComplexData complexData, MyContourPoint** contour)
{
if (contour)
{
MyContourPoint* contourPoint = (*contour) = new MyContourPoint();
for( int i = 0; i < complexData.length; ++i )
{
contourPoint->pos = MyPoint((int)complexData.data[i*2],(int)complexData.data[i*2 + 1]);
contourPoint->next = new MyContourPoint();
contourPoint = contourPoint->next;
}
contourPoint->next = NULL;
}
}
void resample_N(MyComplexData src, int destCount, MyComplexData* dest)
{
if (dest) {
double* ret = new double[destCount * 2];
for (int i = 0; i < destCount; ++i)
{
double j = (double)i / destCount * src.length;
int k = (int)floor(j);
int l = (int)ceil(j);
if (k == l)
{
ret[2 * i] = src.data[2 * k];
ret[2 * i + 1] = src.data[2 * k + 1];
}
else
{
ret[2 * i] = src.data[(2 * k) % (2 * src.length)] * (1 - (j - floor(j))) + src.data[(2 * l) % (2 * src.length)] * (1 - (ceil(j) - j));
ret[2 * i + 1] = src.data[(2 * k + 1) % (2 * src.length)] * (1 - (j - floor(j))) + src.data[(2 * l + 1) % (2 * src.length)] * (1 - (ceil(j) - j));
}
}
dest->data = ret;
dest->length = destCount;
}
}
void FFT(MyComplexData indata, int sign)
{
uint n, mmax, m, j, istep, i;
double wtemp, wr, wpr, wpi, wi, theta, tempr, tempi;
double* data = indata.data;
if (data) {
int sampleCount = indata.length;
n = ((uint)sampleCount) << 1;
j = 0;
for (i = 0; i < n / 2; i += 2)
{
if (j > i)
{
tempr = data[j];
data[j] = data[i];
data[i] = tempr;
tempr = data[j + 1];
data[j + 1] = data[i + 1];
data[i + 1] = tempr;
if ((j / 2) < (n / 4))
{
tempr = data[(n - (i + 2))];
data[(n - (i + 2))] = data[(n - (j + 2))];
data[(n - (j + 2))] = tempr;
tempr = data[(n - (i + 2)) + 1];
data[(n - (i + 2)) + 1] = data[(n - (j + 2)) + 1];
data[(n - (j + 2)) + 1] = tempr;
}
}
m = n >> 1;
while (m >= 2 && j >= m)
{
j -= m;
m >>= 1;
}
j += m;
}
//end of the bit-reversed order algorithm
//Danielson-Lanzcos routine
mmax = 2;
while (n > mmax)
{
istep = mmax << 1;
theta = sign * (2 * PI / mmax);
wtemp = sin(0.5 * theta);
wpr = -2.0 * wtemp * wtemp;
wpi = sin(theta);
wr = 1.0;
wi = 0.0;
for (m = 1; m < mmax; m += 2)
{
for (i = m; i <= n; i += istep)
{
j = i + mmax;
tempr = wr * data[j - 1] - wi * data[j];
tempi = wr * data[j] + wi * data[j - 1];
data[j - 1] = data[i - 1] - tempr;
data[j] = data[i] - tempi;
data[i - 1] += tempr;
data[i] += tempi;
}
wr = (wtemp = wr) * wpr - wi * wpi + wr;
wi = wi * wpr + wtemp * wpi + wi;
}
mmax = istep;
}
if (sign < 0)
{
for (int i2 = 0; i2 < 2 * sampleCount; ++i2)
{
data[i2] *= (1.0 / sampleCount);
}
}
//end of the algorithm
}
}
//egy objektum normalizalasa; origoba tolas, meret normalizalas, fotengelyt fuggoleges allasba forditani (180 fokos elforgatas lehet!)
void normalize_shape(MyShape* shape)
{
if (shape) {
int sampleCount = SAMPLE_COUNT;
MyComplexData complexData, complexData2;
to_complex_N(shape->contour, &complexData);
//toroljuk a shape contourjat, mert ujat fog kapni
delete_contour_D(shape->contour);
resample_N(complexData, sampleCount, &complexData2);
//toroljuk a regi complex datat
delete[] complexData.data;
complexData = complexData2;
FFT(complexData, -1);
double* data = complexData.data;
//eltolas
shape->pos.X += (int)data[0];
shape->pos.Y += (int)data[1];
//invariancia eltolasra
data[0] = 0;
data[1] = 0;
//nagyitas
double scalearea = sqrt(data[2] * data[2] + data[3] * data[3]) / SCALE_MULT;
shape->scale *= scalearea;
//invariancia nagyitasra
for (int i2 = 0; i2 < sampleCount; ++i2)
{
data[2 * i2] *= 1 / scalearea;
data[2 * i2 + 1] *= 1 / scalearea;
}
//elforgatas
double ang1, ang2;
ang1 = atan2(data[2], data[3]);
ang2 = atan2(data[2 * sampleCount - 2], data[2 * sampleCount - 1]);
double fi1 = (ang1 + ang2) / 2;
double rotate = fi1;
double fi2 = (ang1 - ang2) / 2;
int n = (int)(fi2 * sampleCount / 2 / PI);
fi2 = n * 2 * PI / sampleCount;
shape->rot += fi1;
if (shape->rot > PI) shape->rot -= PI;
if (shape->rot < -PI) shape->rot += PI;
//invariancia elforgatasra
for (int i2 = 0; i2 < sampleCount; ++i2)
{
double angx = atan2(data[2 * i2], data[2 * i2 + 1]);
double c = sqrt(data[2 * i2] * data[2 * i2] + data[2 * i2 + 1] * data[2 * i2 + 1]);
data[2 * i2] = c * sin(angx - fi1 - i2 * fi2);
data[2 * i2 + 1] = c * cos(angx - fi1 - i2 * fi2);
}
//visszatrafo es kirajzolas
FFT(complexData, 1);
to_contour_N(complexData,&shape->contour);
delete[] complexData.data;
}
}
//a marker kepekbol normalizalt marker objektumokat keszit
void generate_marker_shapes_N(MyImageListElement* markers)
{
if (markers) {
MyImageListElement* currentMarker = markers;
MyShapeListElement* currentShape = globalMarkerShapeList = new MyShapeListElement();
int index = 0;
while (currentMarker->next)
{
MyImage im;
clone_image_N(currentMarker->image, &im);
//segment_kmeans(im, 2);
//binarize(im,0xFFFFFFFF,0xFF000000);
binarize2(im,true);
MyShapeListElement* markerContours;
real_contour_N(im, &markerContours);
MyShapeListElement* best = NULL;
int max = 0;
MyShapeListElement* currentMarkerShape = markerContours;
while (currentMarkerShape->next)
{
int length = 0;
MyContourPoint* cp = currentMarkerShape->shape.contour;
while(cp->next) {
++length;
cp = cp->next;
}
if (length > max)
{
max = length;
best = currentMarkerShape;
}
currentMarkerShape = currentMarkerShape->next;
}
MyShape bestShape;
clone_shape_N(best->shape,&bestShape);
delete_shape_list_D(markerContours);
normalize_shape(&bestShape);
bestShape.index = index;
bestShape.pos.X -= (im.w / 2);//kep kozepe az origo
bestShape.pos.Y -= (im.h / 2);
index++;
currentShape->shape = bestShape;
currentShape->next = new MyShapeListElement();
delete_image_D(im);
currentMarker = currentMarker->next;
currentShape = currentShape->next;
}
currentShape->next = NULL;
}
}
//normalizalt markerek es normalizalt alakzat, megkeresi a megfelelo markert. ha tureshataron kivul van mind, akkor -1 lesz az index
void match_shape(MyShape* shape, MyShapeListElement* markers) {
if (shape && markers) {
MyShape rotatedShape;
clone_shape_N(*shape,&rotatedShape);
int sampleCount = SAMPLE_COUNT;
MyComplexData complexData, complexData2;
to_complex_N(rotatedShape.contour, &complexData);
delete_contour_D(rotatedShape.contour);
resample_N(complexData, sampleCount, &complexData2);
delete[] complexData.data;
complexData = complexData2;
FFT(complexData, -1);
double* data = complexData.data;
for (int i2 = 0; i2 < sampleCount; ++i2)
{
double angx = atan2(data[2 * i2], data[2 * i2 + 1]);
double c = sqrt(data[2 * i2] * data[2 * i2] + data[2 * i2 + 1] * data[2 * i2 + 1]);
data[2 * i2] = c * sin(angx - PI - i2 * PI);
data[2 * i2 + 1] = c * cos(angx - PI - i2 * PI);
}
FFT(complexData, 1);
to_contour_N(complexData,&rotatedShape.contour);
delete[] complexData.data;
rotatedShape.rot += PI;
if (rotatedShape.rot > PI) rotatedShape.rot -= 2*PI;
MyShapeListElement* current = markers;
MyShapeListElement* best = NULL;
double maxdif = 256*256*256*64;
bool bestRotated = false;
while(current->next) {
MyContourPoint* currentCPshape = shape->contour;
MyContourPoint* currentCPshapeRot = rotatedShape.contour;
MyContourPoint* currentCPmarker = current->shape.contour;
double dist = 0;
double distRot = 0;
while(currentCPmarker->next && currentCPshapeRot->next && currentCPshape->next) {
dist += (currentCPmarker->pos.X - currentCPshape->pos.X) * (currentCPmarker->pos.X - currentCPshape->pos.X);
dist += (currentCPmarker->pos.Y - currentCPshape->pos.Y) * (currentCPmarker->pos.Y - currentCPshape->pos.Y);
distRot += (currentCPmarker->pos.X - currentCPshapeRot->pos.X) * (currentCPmarker->pos.X - currentCPshapeRot->pos.X);
distRot += (currentCPmarker->pos.Y - currentCPshapeRot->pos.Y) * (currentCPmarker->pos.Y - currentCPshapeRot->pos.Y);
currentCPmarker = currentCPmarker->next;
currentCPshapeRot = currentCPshapeRot->next;
currentCPshape = currentCPshape->next;
}
if (maxdif > dist) {
maxdif = dist;
best = current;
bestRotated = false;
}
if (maxdif > distRot) {
maxdif = distRot;
best = current;
bestRotated = true;
}
current = current->next;
}
if (bestRotated) {
delete_contour_D(shape->contour);
clone_shape_N(rotatedShape,shape);
delete_contour_D(rotatedShape.contour);
}
else {
delete_contour_D(rotatedShape.contour);
}
if (maxdif < TRESHOLD2) {
shape->index = best->shape.index;
shape->rot -= best->shape.rot;
if (shape->rot < -PI) shape->rot += 2*PI;
if (shape->rot > PI) shape->rot -= 2*PI;
shape->scale /= best->shape.scale;
shape->pos.X -= (int)((best->shape.pos.X * cos(-shape->rot) - best->shape.pos.Y * sin(-shape->rot)) * shape->scale);
shape->pos.Y -= (int)((best->shape.pos.X * sin(-shape->rot) + best->shape.pos.Y * cos(-shape->rot)) * shape->scale);
to_complex_N(shape->contour, &complexData);
delete_contour_D(shape->contour);
FFT(complexData, -1);
data = complexData.data;
int rotangn = (int)(-best->shape.rot * complexData.length / 2 / PI);
double rotang = rotangn * 2 * PI / complexData.length;
for (int i2 = 0; i2 < sampleCount; ++i2)
{
double angx = atan2(data[2 * i2], data[2 * i2 + 1]);
double c = sqrt(data[2 * i2] * data[2 * i2] + data[2 * i2 + 1] * data[2 * i2 + 1]);
data[2 * i2] = c * sin(angx - rotang - i2 * rotang);
data[2 * i2 + 1] = c * cos(angx - rotang - i2 * rotang);
}
FFT(complexData, 1);
to_contour_N(complexData,&(shape->contour));
delete[] complexData.data;
}
else {
shape->index = -1;
}
}
}
//megkeresi a megfeleleot, de nem konturt, hanem teruletet hasonlit ossze, kb 30-szor lassabb
void match_shape2(MyShape* shape, MyShapeListElement* markers) {
if (shape && markers) {
MyShape rotatedShape;
clone_shape_N(*shape,&rotatedShape);
int sampleCount = SAMPLE_COUNT;
MyComplexData complexData, complexData2;
to_complex_N(rotatedShape.contour, &complexData);
delete_contour_D(rotatedShape.contour);
resample_N(complexData, sampleCount, &complexData2);
delete[] complexData.data;
complexData = complexData2;
FFT(complexData, -1);
double* data = complexData.data;
for (int i2 = 0; i2 < sampleCount; ++i2)
{
double angx = atan2(data[2 * i2], data[2 * i2 + 1]);
double c = sqrt(data[2 * i2] * data[2 * i2] + data[2 * i2 + 1] * data[2 * i2 + 1]);
data[2 * i2] = c * sin(angx - PI - i2 * PI);
data[2 * i2 + 1] = c * cos(angx - PI - i2 * PI);
}
FFT(complexData, 1);
to_contour_N(complexData,&rotatedShape.contour);
delete[] complexData.data;
rotatedShape.rot += PI;
if (rotatedShape.rot > PI) rotatedShape.rot -= 2*PI;
MyImage imShape;
imShape.h = 100;
imShape.w = 100;
imShape.img = new uint[imShape.h * imShape.w];
MyImage imShapeRot;
imShapeRot.h = imShape.h;
imShapeRot.w = imShape.w;
imShapeRot.img = new uint[imShapeRot.h * imShapeRot.w];
for(int i=0; i < imShape.h*imShape.w; ++i) {
imShape.img[i] = 1;
imShapeRot.img[i] = 1;
}
draw_shape_lines(imShape,shape->contour,MyPoint(imShape.w / 2,imShape.h / 2),0);
draw_shape_lines(imShapeRot,rotatedShape.contour,MyPoint(imShapeRot.w / 2,imShapeRot.h / 2),0);
clear_blob(imShape,MyPoint(0,0));
clear_blob(imShape,MyPoint(imShape.w-1,0));
clear_blob(imShapeRot,MyPoint(0,0));
clear_blob(imShapeRot,MyPoint(imShapeRot.w-1,0));
MyShapeListElement* current = markers;
MyShapeListElement* best = NULL;
double maxdif = 256*256*256*64;
bool bestRotated = false;
while(current->next) {
MyImage imMarker;
imMarker.h = imShape.h;
imMarker.w = imShape.w;
imMarker.img = new uint[imMarker.h * imMarker.w];
for(int i=0; i < imMarker.h*imMarker.w; ++i) {
imMarker.img[i] = 1;
}
draw_shape_lines(imMarker,current->shape.contour,MyPoint(imMarker.w / 2,imMarker.h / 2),0);
clear_blob(imMarker,MyPoint(0,0));
clear_blob(imMarker,MyPoint(imMarker.w-1,0));
double dist = 0;
double distRot = 0;
for(int i=0; i < imMarker.h*imMarker.w; ++i) {
if (imMarker.img[i] != imShape.img[i]) ++dist;
if (imMarker.img[i] != imShapeRot.img[i]) ++distRot;
}
delete_image_D(imMarker);
if (maxdif > dist) {
maxdif = dist;
best = current;
bestRotated = false;
}
if (maxdif > distRot) {
maxdif = distRot;
best = current;
bestRotated = true;
}
current = current->next;
}
delete_image_D(imShape);
delete_image_D(imShapeRot);
if (bestRotated) {
delete_contour_D(shape->contour);
clone_shape_N(rotatedShape,shape);
delete_contour_D(rotatedShape.contour);
}
else {
delete_contour_D(rotatedShape.contour);
}
shape->index = best->shape.index;
shape->rot -= best->shape.rot;
if (shape->rot < -PI) shape->rot += 2*PI;
if (shape->rot > PI) shape->rot -= 2*PI;
shape->scale /= best->shape.scale;
shape->pos.X -= (int)((best->shape.pos.X * cos(-shape->rot) - best->shape.pos.Y * sin(-shape->rot)) * shape->scale);
shape->pos.Y -= (int)((best->shape.pos.X * sin(-shape->rot) + best->shape.pos.Y * cos(-shape->rot)) * shape->scale);
to_complex_N(shape->contour, &complexData);
delete_contour_D(shape->contour);
FFT(complexData, -1);
data = complexData.data;
int rotangn = (int)(-best->shape.rot * complexData.length / 2 / PI);
double rotang = rotangn * 2 * PI / complexData.length;
for (int i2 = 0; i2 < sampleCount; ++i2)
{
double angx = atan2(data[2 * i2], data[2 * i2 + 1]);
double c = sqrt(data[2 * i2] * data[2 * i2] + data[2 * i2 + 1] * data[2 * i2 + 1]);
data[2 * i2] = c * sin(angx - rotang - i2 * rotang);
data[2 * i2 + 1] = c * cos(angx - rotang - i2 * rotang);
}
FFT(complexData, 1);
to_contour_N(complexData,&(shape->contour));
delete[] complexData.data;
}
}
//elvegzi egy kepframere a teljes kepfeldolgozast, kamerakep, hatterkep, markerek listaja, es a visszakapott objektumlista)
void find_objects_N(MyImage foreground, MyImage background, MyShapeListElement** shapeList)
{
MyImage foreground2;
MyImage foregroundx;
MyImage backgroundx;
clone_image_N(foreground, &foregroundx);
clone_image_N(background, &backgroundx);
clone_image_N(foregroundx, &foreground2);
segment_background_HSL(foregroundx, backgroundx, TRESHOLD1);
closing(foregroundx);
opening(foregroundx);
MyShapeListElement* currentOutShapeElement;
(*shapeList) = currentOutShapeElement = new MyShapeListElement();
MyShapeListElement *currentShape;
MyShapeListElement *firstShape;
real_contour_N(foregroundx, &firstShape);
currentShape = firstShape;
while (currentShape->next)
{
//kivagjuk a konturon belul levo teruletet
MyImage foreground3;
clone_image_N(foreground2, &foreground3);
remove_outside(foreground3, currentShape->shape.contour, 0);
//segment_kmeans(foreground3, 2);
//binarize(foreground3,0xFFFFFFFF,0xFF000000);
binarize2(foreground3,true);
MyShapeListElement* markerContours;
real_contour_N(foreground3, &markerContours);
MyShapeListElement* best = NULL;
int max = 0;
delete_image_D(foreground3);
//maximalis hosszu kontur kivalasztasa (jo esetben csak 1 kontur van, a marker konturja)
MyShapeListElement* currentMarkerShape = markerContours;
while (currentMarkerShape->next)
{
int length = 0;
MyContourPoint* cp = currentMarkerShape->shape.contour;
while(cp->next) {
++length;
cp = cp->next;
}
if (length > max)
{
max = length;
best = currentMarkerShape;
}
currentMarkerShape = currentMarkerShape->next;
}
MyShape bestShape;
//ha megfelelo hosszu a kontur, csak akkor megyunk tovabb, amugy zajnak tekintjuk a markert, es a korulhatarolo kontur lesz amit megtalalunk
if (best && (max > MIN_CONTOUR_LENGTH)) {
clone_shape_N(best->shape,&bestShape);
normalize_shape(&bestShape);
match_shape(&bestShape, globalMarkerShapeList);
}
else {
clone_shape_N(currentShape->shape,&bestShape);
normalize_shape(&bestShape);
bestShape.index = -1;
}
currentOutShapeElement->shape = bestShape;
currentOutShapeElement->next = new MyShapeListElement();
currentOutShapeElement = currentOutShapeElement->next;
delete_shape_list_D(markerContours);
//kovetkezo kepet vesszuk
currentShape = currentShape->next;
}
delete_shape_list_D(firstShape);
currentOutShapeElement->next = NULL;
delete_image_D(foregroundx);
delete_image_D(backgroundx);
delete_image_D(foreground2);
}
MyImage readImage(char* filename, int w, int h) {
MyImage im;
im.w = w;
im.h = h;
im.img = new uint[im.w * im.h];
ifstream is;
is.open(filename, ios::binary );
is.read((char*)im.img,im.w * im.h * sizeof(uint));
is.close();
for(int i=0; i < im.w * im.h; ++i) {
uint c = im.img[i];
unsigned char r = ((unsigned char*)&c)[0];
unsigned char g = ((unsigned char*)&c)[1];
unsigned char b = ((unsigned char*)&c)[2];
unsigned char a = ((unsigned char*)&c)[3];
c = im.img[i] = a*0x01000000 + b*0x00010000 + g*0x00000100 + r;
}
return im;
}
void writeImage(char* filename, MyImage im) {
ofstream os;
os.open(filename, ofstream::binary);
os.write((char*)im.img,im.w * im.h * sizeof(uint));
os.close();
}
void writeImageRGB(char* filename, MyImage im) {
ofstream os;
os.open(filename, ofstream::binary);
char* iii = (char*)im.img;
for(int i=0; i < im.w * im.h; ++i) {
os.write(iii, 3 * sizeof(char));
iii += 4;
}
os.close();
} | 23.637116 | 151 | 0.53348 | [
"shape",
"vector"
] |
e2dc38be420622e1138ecf313395d43cbd80eaf0 | 12,486 | cpp | C++ | ds2/qt_demonsaw/model/client/client_upload_model.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 132 | 2017-03-22T03:46:38.000Z | 2022-03-08T15:08:16.000Z | ds2/qt_demonsaw/model/client/client_upload_model.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 4 | 2017-04-06T17:46:10.000Z | 2018-08-08T18:27:59.000Z | ds2/qt_demonsaw/model/client/client_upload_model.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 30 | 2017-03-26T22:38:17.000Z | 2021-11-21T20:50:17.000Z | //
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <QDesktopServices>
#include <QTimer>
#include <QUrl>
#include "client_upload_model.h"
#include "component/timer_component.h"
#include "component/timeout_component.h"
#include "component/io/file_component.h"
#include "component/router/router_component.h"
#include "component/transfer/upload_component.h"
#include "component/transfer/upload_thread_component.h"
#include "component/transfer/transfer_idle_component.h"
#include "resource/icon_provider.h"
#include "resource/resource.h"
#include "utility/io/file_util.h"
#include "window/client_window.h"
#include "window/window.h"
namespace eja
{
// Interface
void client_upload_model::init()
{
entity_table_model::init();
// Callback
add_callback(function_type::upload);
// Timer
m_timer = new QTimer(this);
m_timer->setInterval(1000);
connect(m_timer, &QTimer::timeout, [this]()
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector || upload_vector->empty())
return;
QModelIndex start = createIndex(0, column::time);
QModelIndex end = createIndex(upload_vector->size() - 1, column::max - 1);
emit dataChanged(start, end);
});
m_timer->start();
}
void client_upload_model::add(const entity::ptr entity)
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector || upload_vector->has(entity))
return;
// Timer
const auto timer = entity->get<timer_component>();
if (!timer)
return;
timer->start();
// Timeout
const auto timeout = entity->get<timeout_component>();
if (!timeout)
return;
timeout->start();
// Thread
const auto lambda = [this](const entity::ptr entity) { on_refresh(entity); };
const auto function = function::create(lambda);
const auto option = m_entity->get<client_option_component>();
const auto threads = option ? option->get_upload_threads() : 1;
const auto thread = upload_thread_component::create(threads);
thread->add(function);
entity->add(thread);
thread->start();
emit added(entity);
}
void client_upload_model::remove(const entity::ptr entity)
{
entity->shutdown();
emit removed(entity);
}
void client_upload_model::clear()
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return;
for (const auto& entity : upload_vector->copy())
{
const auto thread = entity->get<upload_thread_component>();
if (thread && thread->removeable())
{
entity->shutdown();
emit removed(entity);
}
}
}
void client_upload_model::on_clear(const entity::ptr entity)
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return;
for (const auto& entity : upload_vector->copy())
{
const auto thread = entity->get<upload_thread_component>();
if (thread && thread->running())
thread->stop();
entity->shutdown();
}
beginResetModel();
upload_vector->clear();
endResetModel();
set_status(client_statusbar::upload, upload_vector->size());
}
void client_upload_model::double_click(const QModelIndex& index)
{
if (!index.isValid())
return;
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return;
const size_t row = static_cast<size_t>(index.row());
const auto entity = upload_vector->get(row);
if (entity)
{
const auto file = entity->get<file_component>();
if (file)
{
const auto url = QUrl::fromLocalFile(QString::fromStdString(file->get_path()));
QDesktopServices::openUrl(url);
}
}
}
// Slot
void client_upload_model::on_add(const entity::ptr entity)
{
assert(thread::main());
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector || upload_vector->has(entity))
return;
{
auto_lock_ptr(upload_vector);
const auto row = upload_vector->size();
beginInsertRows(QModelIndex(), row, row);
upload_vector->add(entity);
endInsertRows();
}
set_status(client_statusbar::upload, upload_vector->size());
}
void client_upload_model::on_remove(const entity::ptr entity)
{
assert(thread::main());
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return;
{
auto_lock_ptr(upload_vector);
const auto row = upload_vector->get(entity);
if (row == type::npos)
return;
beginRemoveRows(QModelIndex(), row, row);
upload_vector->remove(row);
endRemoveRows();
}
set_status(client_statusbar::upload, upload_vector->size());
}
void client_upload_model::on_clear()
{
assert(thread::main());
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return;
beginResetModel();
upload_vector->clear();
endResetModel();
set_status(client_statusbar::upload, upload_vector->size());
}
// Utility
bool client_upload_model::empty() const
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
return !upload_vector || upload_vector->empty();
}
// Model
bool client_upload_model::removeRows(int row, int count, const QModelIndex& parent /*= QModelIndex()*/)
{
assert(thread::main());
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return false;
size_t status = 0;;
beginRemoveRows(QModelIndex(), row, (row + count - 1));
for (auto i = (row + count - 1); i >= row; --i)
{
const auto entity = upload_vector->get(i);
if (entity)
{
const auto thread = entity->get<upload_thread_component>();
if (thread && thread->removeable())
{
entity->shutdown();
status += upload_vector->remove(row);
}
}
}
endRemoveRows();
set_status(client_statusbar::upload, upload_vector->size());
return status > 0;
}
QVariant client_upload_model::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
const size_t row = static_cast<size_t>(index.row());
const size_t col = static_cast<size_t>(index.column());
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
if (!upload_vector)
return QVariant();
const auto entity = upload_vector->get(row);
if (!entity)
return QVariant();
switch (role)
{
case Qt::DisplayRole:
{
switch (col)
{
/*case column::time:
{
const auto time = entity->get<time_component>();
if (time)
return QString::fromStdString(time->str());
break;
}*/
case column::number:
{
const auto thread = entity->get<upload_thread_component>();
if (thread)
return QVariant::fromValue<uint>(thread->get_size());
break;
}
case column::status:
case column::file:
{
return QVariant::fromValue(entity);
}
case column::router:
{
const auto router = entity->get<router_component>();
if (router)
return QString::fromStdString(router->get_address());
break;
}
case column::version:
{
const auto router = entity->get<router_component>();
if (router)
return QString::fromStdString(router->get_version());
break;
}
case column::size:
{
const auto file = entity->get<file_component>();
if (file)
return QString::fromStdString(file_util::get_size(file->get_size()));
break;
}
case column::time:
{
const auto thread = entity->get<upload_thread_component>();
if (thread)
{
const auto transfer = entity->get<transfer_component>();
if (transfer && thread->running() && !transfer->done())
{
return QString::fromStdString(transfer->get_estimate());
}
else
{
const auto timer = entity->get<timer_component>();
if (timer)
return QString::fromStdString(timer->str());
}
}
break;
}
case column::speed:
{
const auto transfer = entity->get<transfer_component>();
if (transfer)
return QString::fromStdString(file_util::get_speed(transfer->get_speed()));
break;
}
case column::progress:
{
return QVariant::fromValue(entity);
}
}
break;
}
case Qt::UserRole:
{
switch (col)
{
/*case column::time:
{
const auto time = entity->get<time_component>();
if (time)
{
const auto file = entity->get<file_component>();
if (file)
return QString("%1%2").arg(time->elapsed()).arg(file->get_size());
return QVariant::fromValue<uint>(time->elapsed());
}
break;
}*/
case column::status:
{
const auto thread = entity->get<upload_thread_component>();
if (thread)
{
const auto status = static_cast<size_t>(thread->get_status());
return QVariant::fromValue<uint>(status);
}
break;
}
case column::file:
{
const auto file = entity->get<file_component>();
if (file)
return QString::fromStdString(file->get_name()).toLower();
break;
}
case column::router:
{
const auto router = entity->get<router_component>();
if (router)
return QString::fromStdString(router->get_address()).toLower();
break;
}
case column::size:
{
const auto file = entity->get<file_component>();
if (file)
return QVariant::fromValue<qulonglong>(file->get_size());
break;
}
case column::time:
{
const auto timer = entity->get<timer_component>();
if (timer)
return QVariant::fromValue<uint>(timer->elapsed());
break;
}
case column::speed:
{
const auto transfer = entity->get<transfer_component>();
if (transfer)
return QVariant::fromValue<uint>(transfer->get_speed());
break;
}
case column::progress:
{
const auto transfer = entity->get<transfer_component>();
if (transfer)
return QVariant::fromValue<double>(transfer->get_ratio());
break;
}
default:
{
return data(index, Qt::DisplayRole);
}
}
break;
}
case Qt::EditRole:
{
switch (col)
{
case column::file:
{
const auto file = entity->get<file_component>();
if (file)
return QString::fromStdString(file->get_name());
break;
}
}
break;
}
case Qt::TextAlignmentRole:
{
switch (col)
{
case column::number:
{
return static_cast<int>(Qt::AlignVCenter | Qt::AlignHCenter);
}
case column::size:
case column::time:
case column::speed:
{
return static_cast<int>(Qt::AlignVCenter | Qt::AlignRight);
}
}
break;
}
}
return QVariant();
}
int client_upload_model::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
return upload_vector ? upload_vector->size() : 0;
}
// Accessor
size_t client_upload_model::get_row(const entity::ptr entity) const
{
const auto upload_vector = m_entity->get<upload_entity_vector_component>();
return upload_vector ? upload_vector->get(entity) : type::npos;
}
}
| 24.339181 | 104 | 0.652971 | [
"model"
] |
e2dea264b3d220178434d9975a94f14c198542fe | 23,579 | cpp | C++ | SDDLViewerDlg.cpp | HiraokaHyperTools/SDDLViewer | 37def4b8cedf2d3398662dbcf9afe3929754a15e | [
"BSD-2-Clause"
] | 1 | 2021-06-25T09:58:02.000Z | 2021-06-25T09:58:02.000Z | SDDLViewerDlg.cpp | HiraokaHyperTools/SDDLViewer | 37def4b8cedf2d3398662dbcf9afe3929754a15e | [
"BSD-2-Clause"
] | null | null | null | SDDLViewerDlg.cpp | HiraokaHyperTools/SDDLViewer | 37def4b8cedf2d3398662dbcf9afe3929754a15e | [
"BSD-2-Clause"
] | null | null | null | // SDDLViewerDlg.cpp : implementation file
//
#include "Stdafx.h"
#include "SDDLViewer.h"
#include "SDDLViewerDlg.h"
#pragma comment(lib, "Version.lib")
#pragma comment(lib, "Aclui.lib")
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
BOOL OnInitDialog() {
CDialog::OnInitDialog();
CString strVer = _T("?");
{
HMODULE hMod = AfxGetResourceHandle();
HRSRC hVeri = FindResource(hMod, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
PVOID pvVeri = LockResource(LoadResource(hMod, hVeri));
DWORD cbVeri = SizeofResource(hMod, hVeri);
if (pvVeri != NULL && cbVeri != 0) {
VS_FIXEDFILEINFO *pffi = NULL;
UINT cb = 0;
if (VerQueryValue(pvVeri, _T("\\"), reinterpret_cast<LPVOID *>(&pffi), &cb)) {
if (pffi->dwSignature == 0xFEEF04BD) {
strVer.Format(_T("%u.%u.%u.%u")
, 0U +(WORD)(pffi->dwFileVersionMS >> 16)
, 0U +(WORD)(pffi->dwFileVersionMS >> 0)
, 0U +(WORD)(pffi->dwFileVersionLS >> 16)
, 0U +(WORD)(pffi->dwFileVersionLS >> 0)
);
}
}
}
}
{
CString text;
m_wndVer.GetWindowText(text);
text.Replace(_T("1.0"), strVer);
m_wndVer.SetWindowText(text);
}
return true;
}
protected:
DECLARE_MESSAGE_MAP()
public:
CStatic m_wndVer;
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_VER, m_wndVer);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CvDlg dialog
CvDlg::CvDlg(CWnd* pParent /*=NULL*/)
: CDialog(CvDlg::IDD, pParent)
, m_strSDDL(_T(""))
, m_objName(_T("npf"))
, m_dacl(true)
, m_sacl(FALSE)
, m_owner(FALSE)
, m_group(FALSE)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CvDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_SDDL, m_strSDDL);
DDX_Control(pDX, IDC_SE, m_wndSe);
DDX_Text(pDX, IDC_OBJNAME, m_objName);
DDX_Check(pDX, IDC_DACL, m_dacl);
DDX_Check(pDX, IDC_SACL, m_sacl);
DDX_Check(pDX, IDC_OWNER, m_owner);
DDX_Check(pDX, IDC_GROUP, m_group);
}
BEGIN_MESSAGE_MAP(CvDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_PASTE, &CvDlg::OnBnClickedPaste)
ON_BN_CLICKED(IDC_VIEW, &CvDlg::OnBnClickedView)
ON_BN_CLICKED(IDC_GET, &CvDlg::OnBnClickedGet)
ON_BN_CLICKED(IDC_COPY, &CvDlg::OnBnClickedCopy)
ON_BN_CLICKED(IDC_EDIT, &CvDlg::OnBnClickedEdit)
END_MESSAGE_MAP()
// CvDlg message handlers
BOOL CvDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
m_wndSe.SetItemData(m_wndSe.AddString(_T("FILE_OBJECT")), SE_FILE_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("SERVICE")), SE_SERVICE);
m_wndSe.SetItemData(m_wndSe.AddString(_T("PRINTER")), SE_PRINTER);
m_wndSe.SetItemData(m_wndSe.AddString(_T("REGISTRY_KEY")), SE_REGISTRY_KEY);
m_wndSe.SetItemData(m_wndSe.AddString(_T("LMSHARE")), SE_LMSHARE);
m_wndSe.SetItemData(m_wndSe.AddString(_T("KERNEL_OBJECT")), SE_KERNEL_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("WINDOW_OBJECT")), SE_WINDOW_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("DS_OBJECT")), SE_DS_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("DS_OBJECT_ALL")), SE_DS_OBJECT_ALL);
m_wndSe.SetItemData(m_wndSe.AddString(_T("PROVIDER_DEFINED_OBJECT")), SE_PROVIDER_DEFINED_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("WMIGUID_OBJECT")), SE_WMIGUID_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("REGISTRY_WOW64_32KEY")), SE_REGISTRY_WOW64_32KEY);
m_wndSe.SetCurSel(m_wndSe.FindString(-1, _T("SERVICE")));
UpdateData(false);
return TRUE; // return TRUE unless you set the focus to a control
}
void CvDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CvDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CvDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
class GMUt {
public:
static HGLOBAL Cap(LPCSTR psz) {
UINT cb = sizeof(char) * (strlen(psz) + 1);
HGLOBAL hMem = GlobalAlloc(GHND, cb);
if (hMem != NULL) {
PVOID pv = GlobalLock(hMem);
strcpy(reinterpret_cast<LPSTR>(pv), psz);
GlobalUnlock(hMem);
}
return hMem;
}
};
void CvDlg::OnBnClickedCopy() {
if (!UpdateData())
return;
if (OpenClipboard()) {
EmptyClipboard();
SetClipboardData(CF_TEXT, GMUt::Cap(CT2A(m_strSDDL)));
CloseClipboard();
}
}
void CvDlg::OnBnClickedPaste() {
if (!UpdateData())
return;
if (OpenClipboard()) {
HGLOBAL hMem = GetClipboardData(CF_TEXT);
LPVOID pv = GlobalLock(hMem);
if (pv != NULL) {
m_strSDDL = reinterpret_cast<LPCSTR>(pv);
GlobalUnlock(pv);
}
CloseClipboard();
UpdateData(false);
}
}
#define MAX_ACC 100U
class SUt {
public:
static BOOL ConvertSecurityDescriptorToStringSecurityDescriptor2(
PSECURITY_DESCRIPTOR SecurityDescriptor,
DWORD RequestedStringSDRevision,
SECURITY_INFORMATION SecurityInformation,
CString &StringSecurityDescriptor
) {
LPWSTR pcw = NULL;
if (ConvertSecurityDescriptorToStringSecurityDescriptor(SecurityDescriptor, RequestedStringSDRevision, SecurityInformation, &pcw, NULL)) {
StringSecurityDescriptor = pcw;
ATLVERIFY(NULL == LocalFree(pcw));
return true;
}
return false;
}
};
class CEaseSiAccess {
public:
CAtlArray<SI_ACCESS> m_access;
CAtlArray<CStringW> m_names;
void Add(ACCESS_MASK mask, CStringW name, DWORD flags) {
m_names.Add(name);
SI_ACCESS si;
si.pguid = NULL;
si.mask = mask;
si.pszName = const_cast<LPWSTR>(static_cast<LPCWSTR>(name));
si.dwFlags = flags;
m_access.Add(si);
}
};
class CSettype {
public:
CEaseSiAccess m_accEasy;
void SettypeKey() {
SetObjecttype(L"Key");
m_accEasy.Add(FILE_GENERIC_READ, L"Generic Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_WRITE , L"Generic Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_EXECUTE, L"Generic Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_CREATE_LINK, L"Create Link", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_CREATE_SUB_KEY, L"Create Subkey", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_ENUMERATE_SUB_KEYS, L"Enum Subkeys", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_EXECUTE, L"Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_NOTIFY, L"Notify", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_QUERY_VALUE, L"Query Value", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_READ, L"Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_SET_VALUE, L"Set Value", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WOW64_32KEY, L"WOW64 32Key", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WOW64_64KEY, L"WOW64 64Key", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WRITE, L"Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
}
void SettypeFile() {
SetObjecttype(L"File");
m_accEasy.Add(FILE_GENERIC_READ, L"Generic Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_WRITE , L"Generic Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_EXECUTE, L"Generic Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_DATA, L"Read Data; List Directory", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_DATA, L"Write Data; Add File", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_APPEND_DATA, L"Append Data; Add Subdir", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_EA, L"Read EA", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_EA, L"Write EA", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_EXECUTE, L"Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_TRAVERSE, L"Traverse", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_DELETE_CHILD, L"Delete Child", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_ATTRIBUTES, L"Read Atts", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_ATTRIBUTES, L"Write Atts", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
}
void SettypeService() {
SetObjecttype(L"Service");
m_accEasy.Add(STANDARD_RIGHTS_READ|SERVICE_QUERY_CONFIG|SERVICE_QUERY_STATUS|SERVICE_INTERROGATE|SERVICE_ENUMERATE_DEPENDENTS,
L"Generic Read", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_WRITE|SERVICE_CHANGE_CONFIG,
L"Generic Write", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_EXECUTE|SERVICE_START|SERVICE_STOP|SERVICE_PAUSE_CONTINUE|SERVICE_USER_DEFINED_CONTROL,
L"Generic Execute", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_QUERY_CONFIG, L"Query Config", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_CHANGE_CONFIG, L"Change Config", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_QUERY_STATUS, L"Query Status", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_ENUMERATE_DEPENDENTS, L"Enumerate Dependents", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_START, L"Start", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_STOP, L"Stop", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_PAUSE_CONTINUE, L"Pause Continue", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_INTERROGATE, L"Interrogate", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_USER_DEFINED_CONTROL, L"User Defined Control", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_START|SERVICE_STOP|SERVICE_PAUSE_CONTINUE|SERVICE_USER_DEFINED_CONTROL, L"Control (Start, stop, etc)", SI_ACCESS_GENERAL);
}
virtual void SetObjecttype(LPCWSTR pcw) PURE;
};
class CSI : public CSettype, public ISecurityInformation {
public:
ULONG m_life;
CStringW m_strObjectName;
CSI(): m_life(0) { }
virtual void SetObjecttype(LPCWSTR pcw) {
m_strObjectName = pcw;
}
// *** IUnknown methods ***
STDMETHOD(QueryInterface) (THIS_ REFIID riid, LPVOID * ppvObj) {
if (ppvObj == NULL)
return E_POINTER;
*ppvObj = NULL;
if (riid == IID_ISecurityInformation || riid == IID_IUnknown) {
*ppvObj = static_cast<ISecurityInformation *>(this);
}
else {
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
STDMETHOD_(ULONG,AddRef) (THIS) {
return ++m_life;
}
STDMETHOD_(ULONG,Release) (THIS) {
ULONG c = --m_life;
if (c == 0) {
delete this;
}
return c;
}
// *** ISecurityInformation methods ***
STDMETHOD(GetObjectInformation) (THIS_ PSI_OBJECT_INFO pObjectInfo ) {
SI_OBJECT_INFO &r = *pObjectInfo;
ZeroMemory(&r, sizeof(r));
r.dwFlags = 0
|SI_EDIT_ALL
|SI_ADVANCED
|SI_EDIT_PROPERTIES
|SI_EDIT_EFFECTIVE
|SI_NO_TREE_APPLY
|SI_NO_ACL_PROTECT
;
r.hInstance = GetModuleHandle(NULL);
r.pszObjectName = const_cast<LPWSTR>(static_cast<LPCWSTR>(m_strObjectName));
return S_OK;
}
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault ) PURE;
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor ) PURE;
class DCUt {
public:
template<typename IT, typename OT>
static void PutValue(OT &rOut, const IT &rIn) {
rOut = (OT)rIn;
if (rOut != rIn) throw std::domain_error("precision lost");
}
};
STDMETHOD(GetAccessRights) (THIS_ const GUID* pguidObjectType,
DWORD dwFlags, // SI_EDIT_AUDITS, SI_EDIT_PROPERTIES
PSI_ACCESS *ppAccess,
ULONG *pcAccesses,
ULONG *piDefaultAccess )
{
ATLASSERT(pguidObjectType == NULL || *pguidObjectType == GUID_NULL);
*ppAccess = m_accEasy.m_access.GetData();
DCUt::PutValue(*pcAccesses, m_accEasy.m_access.GetCount());
*piDefaultAccess = 0;
return S_OK;
}
STDMETHOD(MapGeneric) (THIS_ const GUID *pguidObjectType,
UCHAR *pAceFlags,
ACCESS_MASK *pMask)
{
return S_OK;
}
STDMETHOD(GetInheritTypes) (THIS_ PSI_INHERIT_TYPE *ppInheritTypes,
ULONG *pcInheritTypes )
{
if (ppInheritTypes == NULL || pcInheritTypes == NULL)
return E_POINTER;
*pcInheritTypes = 0;
return S_OK;
}
STDMETHOD(PropertySheetPageCallback)(THIS_ HWND hwnd, UINT uMsg, SI_PAGE_TYPE uPage )
{
return S_OK;
}
};
class CStrSI : public CSI {
public:
CString m_strSDDLOrg;
CString m_strSDDL;
CStrSI(CString strSDDL): m_strSDDLOrg(strSDDL), m_strSDDL(strSDDL) { }
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault )
{
if (ppSecurityDescriptor == NULL)
return E_POINTER;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(
fDefault ? m_strSDDLOrg : m_strSDDL, SDDL_REVISION_1, ppSecurityDescriptor, NULL
)) {
return S_OK;
}
int errc = GetLastError();
return HRESULT_FROM_WIN32(errc);
}
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor )
{
PSECURITY_DESCRIPTOR pSdRel = NULL;
int errc = 0;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(m_strSDDL, SDDL_REVISION_1, &pSdRel, NULL)) {
DWORD dwAbsoluteSDSize = 10000, dwDaclSize = 10000, dwSaclSize = 10000, dwOwnerSize = 10000, dwPrimaryGroupSize = 10000;
PSECURITY_DESCRIPTOR pSd = LocalAlloc(LPTR, 10000);
PACL pDacl = reinterpret_cast<PACL>(LocalAlloc(LPTR, 10000));
PACL pSacl = reinterpret_cast<PACL>(LocalAlloc(LPTR, 10000));
PSID pOwner = reinterpret_cast<PSID>(LocalAlloc(LPTR, 10000));
PSID pPrimaryGroup = reinterpret_cast<PSID>(LocalAlloc(LPTR, 10000));
SECURITY_INFORMATION fSi = 0;
if (MakeAbsoluteSD(pSdRel, pSd, &dwAbsoluteSDSize, pDacl, &dwDaclSize, pSacl, &dwSaclSize, pOwner, &dwOwnerSize, pPrimaryGroup, &dwPrimaryGroupSize)) {
if (SecurityInformation & OWNER_SECURITY_INFORMATION) {
PSID pOwner;
BOOL bDefaulted;
ATLVERIFY(GetSecurityDescriptorOwner(pSecurityDescriptor, &pOwner, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorOwner(pSd, pOwner, bDefaulted));
}
if (SecurityInformation & GROUP_SECURITY_INFORMATION) {
PSID pGroup;
BOOL bDefaulted;
ATLVERIFY(GetSecurityDescriptorGroup(pSecurityDescriptor, &pGroup, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorGroup(pSd, pGroup, bDefaulted));
}
if (SecurityInformation & DACL_SECURITY_INFORMATION) {
PACL pDacl;
BOOL bPresent, bDefaulted;
ATLVERIFY(GetSecurityDescriptorDacl(pSecurityDescriptor, &bPresent, &pDacl, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorDacl(pSd, bPresent, pDacl, bDefaulted));
}
if (SecurityInformation & SACL_SECURITY_INFORMATION) {
PACL pSacl;
BOOL bPresent, bDefaulted;
ATLVERIFY(GetSecurityDescriptorSacl(pSecurityDescriptor, &bPresent, &pSacl, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorSacl(pSd, bPresent, pSacl, bDefaulted));
}
LPWSTR pszSDDLNew = NULL;
if (ConvertSecurityDescriptorToStringSecurityDescriptor(
pSd, SDDL_REVISION_1, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION, &pszSDDLNew, NULL
)) {
m_strSDDL = pszSDDLNew;
LocalFree(pszSDDLNew);
ATLVERIFY(NULL == LocalFree(pSd));
ATLVERIFY(NULL == LocalFree(pDacl));
ATLVERIFY(NULL == LocalFree(pSacl));
ATLVERIFY(NULL == LocalFree(pOwner));
ATLVERIFY(NULL == LocalFree(pPrimaryGroup));
ATLVERIFY(NULL == LocalFree(pSdRel));
return S_OK;
}
else
errc = GetLastError();
}
ATLVERIFY(NULL == LocalFree(pSd));
ATLVERIFY(NULL == LocalFree(pDacl));
ATLVERIFY(NULL == LocalFree(pSacl));
ATLVERIFY(NULL == LocalFree(pOwner));
ATLVERIFY(NULL == LocalFree(pPrimaryGroup));
ATLVERIFY(NULL == LocalFree(pSdRel));
}
else
errc = GetLastError();
return HRESULT_FROM_WIN32(errc);
}
};
class CNamedSec {
public:
PSID psidOwner, psidGroup;
PACL pDacl, pSacl;
PSECURITY_DESCRIPTOR pSd;
CNamedSec() {
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
}
~CNamedSec() {
Clear();
}
void Clear() {
ATLVERIFY(NULL == LocalFree(pSd));
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
}
int Get(LPCTSTR psz, SE_OBJECT_TYPE se, SECURITY_INFORMATION sif) {
Clear();
return GetNamedSecurityInfo(psz, se, sif, &psidOwner, &psidGroup, &pDacl, &pSacl, &pSd);
}
PSECURITY_DESCRIPTOR Detach() {
PSECURITY_DESCRIPTOR p = pSd;
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
return p;
}
};
class CNamedSI : public CSI {
public:
CString m_objName;
SE_OBJECT_TYPE m_se;
SECURITY_INFORMATION m_sif;
CNamedSI() { }
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault )
{
if (ppSecurityDescriptor == NULL)
return E_POINTER;
CNamedSec sec;
int errc;
if (0 != (errc = sec.Get(m_objName, m_se, RequestedInformation))) {
return HRESULT_FROM_WIN32(errc);
}
*ppSecurityDescriptor = sec.Detach();
return S_OK;
}
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor )
{
if (pSecurityDescriptor == NULL)
return E_POINTER;
if (AfxMessageBox(_T("Really save changes?"), MB_ICONEXCLAMATION|MB_YESNO) != IDYES)
return E_ACCESSDENIED;
PSID psidOwner, psidGroup;
BOOL bOwnerDefaulted, bGroupDefaulted, bDaclPresent, bDaclDefaulted, bSaclPresent, bSaclDefaulted;
PACL pDacl, pSacl;
ATLVERIFY(GetSecurityDescriptorOwner(pSecurityDescriptor, &psidOwner, &bOwnerDefaulted));
ATLVERIFY(GetSecurityDescriptorGroup(pSecurityDescriptor, &psidGroup, &bGroupDefaulted));
ATLVERIFY(GetSecurityDescriptorDacl(pSecurityDescriptor, &bDaclPresent, &pDacl, &bDaclDefaulted));
ATLVERIFY(GetSecurityDescriptorSacl(pSecurityDescriptor, &bSaclPresent, &pSacl, &bSaclDefaulted));
int errc;
if (0 != (errc = SetNamedSecurityInfo(CT2W(m_objName), m_se, SecurityInformation, psidOwner, psidGroup, pDacl, pSacl))) {
return HRESULT_FROM_WIN32(errc);
}
return S_OK;
}
};
void CvDlg::OnBnClickedView() {
if (!UpdateData())
return;
CStrSI *pSi = new CStrSI(m_strSDDL);
CComPtr<ISecurityInformation> pSiif = pSi;
switch (m_wndSe.GetItemData(m_wndSe.GetCurSel())) {
case SE_SERVICE:
pSi->SettypeService(); break;
case SE_FILE_OBJECT:
case SE_LMSHARE:
pSi->SettypeFile(); break;
case SE_REGISTRY_KEY:
case SE_REGISTRY_WOW64_32KEY:
pSi->SettypeKey(); break;
}
if (EditSecurity(*this, pSiif)) {
m_strSDDL = pSi->m_strSDDL;
UpdateData(false);
}
}
class EUt {
public:
static CString Format(int errc) {
PVOID pv = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, errc, 0, reinterpret_cast<LPWSTR>(&pv), 0, NULL);
CString s = reinterpret_cast<LPCTSTR>(pv);
ATLVERIFY(NULL == LocalFree(pv));
return s;
}
};
void CvDlg::OnBnClickedGet() {
if (!UpdateData())
return;
SE_OBJECT_TYPE se = (SE_OBJECT_TYPE)m_wndSe.GetItemData(m_wndSe.GetCurSel());
SECURITY_INFORMATION sif = 0
|(m_dacl ? DACL_SECURITY_INFORMATION : 0)
|(m_group ? GROUP_SECURITY_INFORMATION : 0)
|(m_owner ? OWNER_SECURITY_INFORMATION : 0)
|(m_sacl ? SACL_SECURITY_INFORMATION : 0)
;
int errc;
CNamedSec sec;
if (0 != (errc = sec.Get(m_objName, se, sif))) {
CString strMsg;
strMsg.Format(_T("GetNamedSecurityInfo failed.\n\n%s"), EUt::Format(errc));
AfxMessageBox(strMsg);
return;
}
if (SUt::ConvertSecurityDescriptorToStringSecurityDescriptor2(sec.pSd, SDDL_REVISION_1, sif, m_strSDDL)) {
UpdateData(false);
}
}
void CvDlg::OnBnClickedEdit() {
if (!UpdateData())
return;
SE_OBJECT_TYPE se = (SE_OBJECT_TYPE)m_wndSe.GetItemData(m_wndSe.GetCurSel());
SECURITY_INFORMATION sif = 0
|(m_dacl ? DACL_SECURITY_INFORMATION : 0)
|(m_group ? GROUP_SECURITY_INFORMATION : 0)
|(m_owner ? OWNER_SECURITY_INFORMATION : 0)
|(m_sacl ? SACL_SECURITY_INFORMATION : 0)
;
CNamedSI *pSi = new CNamedSI();
CComPtr<ISecurityInformation> pSiif = pSi;
pSi->m_objName = m_objName;
pSi->m_se = se;
pSi->m_sif = sif;
switch (m_wndSe.GetItemData(m_wndSe.GetCurSel())) {
case SE_SERVICE: pSi->SettypeService(); break;
default: AfxMessageBox(_T("Only NT Service edit for now."), MB_ICONEXCLAMATION); return;
}
pSi->m_strObjectName = m_objName;
if (!EditSecurity(*this, pSiif))
return;
return;
}
| 30.307198 | 160 | 0.741083 | [
"model"
] |
e2e5ed899a5faf29533e9b3b526de7db1f2643ea | 2,865 | cpp | C++ | TAO/tests/Bug_1495_Regression/Server_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tests/Bug_1495_Regression/Server_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tests/Bug_1495_Regression/Server_Task.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | /**
* @file Server_Task.cpp
* @author Will Otte <wotte@dre.vanderbilt.edu>
*
* $Id: Server_Task.cpp 84563 2009-02-23 08:13:54Z johnnyw $
*
* Implements the Server_Task class which acts as the process colocated
* corba server for Bug_1495_Regression test.
*/
#include "Server_Task.h"
#include "ace/OS_NS_unistd.h"
#include "test_i.h"
#include "ace/Manual_Event.h"
Server_Task::Server_Task (const ACE_TCHAR *output,
CORBA::ORB_ptr sorb,
ACE_Manual_Event &me,
ACE_Thread_Manager *thr_mgr)
: ACE_Task_Base (thr_mgr),
output_ (output),
me_ (me),
sorb_ (CORBA::ORB::_duplicate (sorb))
{
}
int
Server_Task::svc (void)
{
try
{
CORBA::Object_var poa_object =
sorb_->resolve_initial_references ("RootPOA");
if (CORBA::is_nil (poa_object.in ()))
{
ACE_ERROR ((LM_ERROR,
" (%P|%t) Unable to initialize the POA\n"));
return 1;
}
PortableServer::POA_var root_poa =
PortableServer::POA::_narrow (poa_object.in ());
PortableServer::POAManager_var poa_manager =
root_poa->the_POAManager ();
poa_manager->activate ();
Bug1495_i *server_impl = 0;
ACE_NEW_RETURN (server_impl,
Bug1495_i (sorb_.in ()),
0);
PortableServer::ServantBase_var owner_transfer (server_impl);
PortableServer::ObjectId_var id =
root_poa->activate_object (server_impl);
CORBA::Object_var object = root_poa->id_to_reference (id.in ());
Bug1495_Regression::Bug1495_var bug1495 =
Bug1495_Regression::Bug1495::_narrow (object.in ());
CORBA::String_var ior = sorb_->object_to_string (bug1495.in ());
if (output_ != 0)
{
FILE *output_file = ACE_OS::fopen (output_, "w");
if (output_file == 0)
{
ACE_ERROR ((LM_ERROR,
"Cannot open output file for writing the "
"thread server IOR: %s", output_));
return 1;
}
ACE_OS::fprintf (output_file, "%s", ior.in ());
ACE_OS::fclose (output_file);
}
// sleep for a few seconds and hope the remote server picks up the
// ior.
ACE_OS::sleep (5);
// Signal the manual event to wake the main thread up.
me_.signal ();
// The ORB will run for 15 seconds and shut down.
ACE_Time_Value tv (15, 0);
sorb_->run (tv);
ACE_DEBUG ((LM_DEBUG,
"Event loop finished for the thread server.\n"));
root_poa->destroy (1, 1);
sorb_->destroy ();
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("Caught an exception in server task: ");
return 1;
}
return 0;
}
| 25.353982 | 72 | 0.572775 | [
"object"
] |
e2efed27f77f0cc5ecc6976caddddd1321ede5ad | 1,607 | hpp | C++ | Viewer/ecflowUI/src/VLimiterAttr.hpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | 11 | 2020-08-07T14:42:45.000Z | 2021-10-21T01:59:59.000Z | Viewer/ecflowUI/src/VLimiterAttr.hpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 10 | 2020-08-07T14:36:27.000Z | 2022-02-22T06:51:24.000Z | Viewer/ecflowUI/src/VLimiterAttr.hpp | CoollRock/ecflow | db61dddc84d3d2c7dd6af95fd799d717c6bc2a6d | [
"Apache-2.0"
] | 6 | 2020-08-07T14:34:38.000Z | 2022-01-10T12:06:27.000Z | //============================================================================
// Copyright 2017 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#ifndef VLIMITERATTR_HPP
#define VLIMITERATTR_HPP
#include "VAttribute.hpp"
#include "VAttributeType.hpp"
#include <QStringList>
#include <string>
#include <vector>
class AttributeFilter;
class VAttributeType;
class VNode;
class InLimit;
class VLimiterAttrType : public VAttributeType
{
public:
explicit VLimiterAttrType();
QString toolTip(QStringList d) const override;
QString definition(QStringList d) const override;
void encode(const InLimit&,QStringList&) const;
void scan(VNode* vnode,std::vector<VAttribute*>& vec);
int totalNum(VNode* vnode);
private:
enum DataIndex {TypeIndex=0,NameIndex=1,PathIndex=2,TokenIndex=3,
SubmissionIndex=4, FamiliesIndex=5};
};
class VLimiterAttr : public VAttribute
{
public:
VLimiterAttr(VNode *parent,const InLimit&,int index);
VAttributeType* type() const override;
QStringList data(bool firstLine) const override;
std::string strName() const override;
static void scan(VNode* vnode,std::vector<VAttribute*>& vec);
};
#endif // VLIMITERATTR_HPP
| 28.192982 | 79 | 0.670193 | [
"vector"
] |
e2f25ec9960e493c3afb5b422b66bf0cd3eecc0b | 32,720 | cpp | C++ | src/demo/PandoraPillarExperiment.cpp | KCL-Planning/strategic-tactical-pandora | aa609af26a59e756b25212fa57fa72be937766e7 | [
"BSD-2-Clause"
] | 2 | 2019-01-27T05:17:06.000Z | 2020-10-06T15:25:31.000Z | src/demo/PandoraPillarExperiment.cpp | KCL-Planning/strategic-tactical-pandora | aa609af26a59e756b25212fa57fa72be937766e7 | [
"BSD-2-Clause"
] | null | null | null | src/demo/PandoraPillarExperiment.cpp | KCL-Planning/strategic-tactical-pandora | aa609af26a59e756b25212fa57fa72be937766e7 | [
"BSD-2-Clause"
] | null | null | null | #include "PandoraPillarExperiment.h"
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>
#define _USE_MATH_DEFINES
#include <math.h>
#ifndef _WIN32
#include <ros/ros.h>
#endif
#include <glm/gtc/matrix_transform.hpp>
#include <GL/glew.h>
#include "../core/loaders/targa.h"
#include "../core/entities/camera/Camera.h"
#include "../shapes/terrain.h"
#include "../shapes/Water.h"
#include "../shapes/Tree.h"
#include "../shapes/sphere.h"
#include "../shapes/Piramid.h"
#include "../shapes/Cube.h"
#include "../shapes/SkyBox.h"
#include "../core/light/PointLight.h"
#include "../core/light/Light.h"
#include "../core/light/DirectedLight.h"
#include "../core/scene/frustum/Frustum.h"
#include "../core/scene/SceneLeafLight.h"
#include "../core/scene/SceneLeafModel.h"
#include "../core/scene/SceneManager.h"
#include "../core/scene/SceneNode.h"
#include "../core/scene/SkyBoxLeaf.h"
#include "../core/scene/portal/Region.h"
#include "../shapes/terrain.h"
#include "../core/scene/Material.h"
#include "../core/shaders/TerrainShader.h"
#include "../core/shaders/BasicShadowShader.h"
#include "../core/shaders/WaterShader.h"
#include "../core/shaders/SkyBoxShader.h"
#include "../core/shaders/ShadowShader.h"
#include "../core/shaders/AnimatedShadowShader.h"
#include "../core/shaders/LineShader.h"
#include "../core/shaders/MergeFBOShader.h"
#include "../core/animation/LinearAnimation.h"
#include "../core/animation/BouncingBox.h"
#include "../core/entities/WavingWater.h"
#include "pandora/AUV.h"
#include "pandora/Propeller.h"
#ifndef _WIN32
#include "pandora/ontology/OctomapBuilder.h"
#endif
#include "../core/collision/ConvexPolygon.h"
#include "../core/entities/Lever.h"
#include "../core/entities/Bridge.h"
#include "../core/scene/frustum/SphereCheck.h"
#include "../core/entities/camera/DynamicCamera.h"
#include "../core/entities/camera/FreeMovingCamera.h"
#include "../core/entities/behaviours/RotateBehaviour.h"
#include "../core/loaders/WavefrontLoader.h"
#include "../core/loaders/AssimpLoader.h"
#include "../core/texture/Texture.h"
#include "../core/texture/TargaTexture.h"
#include "../core/loaders/PortalLevelFormatLoader.h"
#include "flat/Wall.h"
#include "../core/models/AnimatedModel.h"
#include "shooter/ArmedPlayer.h"
#ifndef _WIN32
#include "pandora/gui/PlanVisualiser.h"
#include "pandora/gui/WaypointLabeler.h"
#include "pandora/gui/BillBoard.h"
#endif
#include "../core/loaders/AssimpLoader.h"
#include "../core/entities/behaviours/HoverBehaviour.h"
#include "../core/entities/behaviours/MoveBehaviour.h"
#include "../core/entities/HeightMap.h"
#include "pandora/ontology/ValveGoal.h"
#include "pandora/ontology/InspectionPoint.h"
#ifndef _WIN32
// ROS stuff.
#include "pandora/ontology/Ontology.h"
//#include "pandora/ontology/HWUOntology.h"
#include "pandora/ontology/Pose.h"
#include "pandora/controllers/ActionController.h"
// Test the RRT code.
#include "pandora/RRT.h"
#include "pandora/sensors/Sonar.h"
#include "pandora/sensors/SliceSonar.h"
#include "pandora/sensors/Odometry.h"
#include "pandora/controllers/FollowWaypointController.h"
//#include "pandora/controllers/ObserveController.h"
#endif
// GUI stuff.
#include "../core/gui/themes/MyGUITheme.h"
#include "../core/gui/fonts/TexturedFont.h"
#include "pandora/gui/PlanLine.h"
#include "pandora/structures/ValvePanel.h"
#include "pandora/structures/Valve.h"
#include "pandora/structures/Pillar.h"
// Volumetric light.
#include "volumetric/LightVolumeShape.h"
#include "volumetric/ShadowVolumeShader.h"
// Sea life.
#include "pandora/models/Shark.h"
#include "pandora/models/Seal.h"
#include "pandora/models/UnderWaterVolcano.h"
#include "pandora/level/MissionSite.h"
#include "../core/gui/themes/MyGUITheme.h"
#include "../core/gui/Label.h"
#include "../core/gui/Container.h"
#include "../core/gui/GUIManager.h"
#include "../core/gui/fonts/TexturedFont.h"
#include "gui_demo/FPSLabel.h"
#include "pandora/shaders/CausticShader.h"
#include "pandora/shaders/CausticTerrainShader.h"
#include "pandora/shaders/CausticTexture.h"
#include "pandora/gui/ActionLabel.h"
PandoraPillarExperiment::PandoraPillarExperiment(SceneManager& scene_manager)
#ifndef _WIN32
: scene_manager_(&scene_manager), ros_node_(NULL)
#else
: scene_manager_(&scene_manager)
#endif
{
srand (time(NULL));
}
bool PandoraPillarExperiment::init(int argc, char** argv)//, bool use_hwu_ontology)
{
#ifndef _WIN32
ros::init(argc, argv, "PlannerVisualisation");
ros_node_ = new ros::NodeHandle();
#endif
pillars_enabled_ = true;
unsigned int nr_pillars = 3;
unsigned int seed = time(NULL);
float min_distance = 10.0f;
float area_size = 40.0f;
for (unsigned int i = 1; i < argc; ++i)
{
std::string param(argv[i]);
std::string name = param;
std::string value;
std::size_t splitter = param.find('=');
if (splitter != std::string::npos)
{
name = param.substr(0, splitter);
value = param.substr(splitter + 1);
std::cout << name << "==" << value << std::endl;
}
if (param == "--no-pillars")
{
pillars_enabled_ = false;
std::cout << "Pillars are disabled." << std::endl;
}
else if (name == "--seed")
{
seed = ::atoi(value.c_str());
std::cout << "Random generator initalised with seed: " << value << std::endl;
}
else if (name == "--npillars")
{
nr_pillars = ::atoi(value.c_str());
std::cout << "Number of pillars is " << nr_pillars << "." << std::endl;
}
else if (name == "--min-distance")
{
min_distance = ::atof(value.c_str());
std::cout << "The minimal distance between pillars and AUVs is " << min_distance << "." << std::endl;
}
else if (name == "--area-size")
{
area_size = ::atof(value.c_str());
std::cout << "The size of the area is now " << area_size << "." << std::endl;
}
else
{
if (name == "--help" || name == "-h")
{
std::cout << "Welcome weary traveler, stay a while and listen." << std::endl;
}
else
{
std::cout << "Unknown option: " << param << "." << std::endl;
}
std::cout << "Usage: ./bin/visualiser " << std::endl;
std::cout << "\t--no-pillars default=false // To disconnect the inspection points from the pillars. Pillars can still be detected." << std::endl;
std::cout << "\t--seed={int} default=time(null) // This sets the seed for the random generator. I give you my pledge that pillars will be set in the same location given the same seed." << std::endl;
std::cout << "\t--npillars={int} default=3 // Sets the number of pillars that need to be generated." << std::endl;
std::cout << "\t--min-distance={float} default=10.0 // Sets the minimal distance between objects." << std::endl;
std::cout << "\t--area-size={float} default=40.0 // Sets the dimensions of the area of operation." << std::endl;
exit(1);
}
}
glEnable(GL_DEPTH_TEST);
glClearColor(0.2, 0.2, 0.4, 1.0f);
terrain_ = new Terrain();
terrain_->createRandomHeightmap(65, -2.0f, 2.0f);
terrain_node_ = new HeightMap(terrain_->getWidth(), terrain_->getWidth(), terrain_->getVertices()[1].x - terrain_->getVertices()[0].x, terrain_->getHeights(), *scene_manager_, &scene_manager_->getRoot(), glm::mat4(1.0f), OBSTACLE, "terrain");
MissionSite* mission_site = new MissionSite(*scene_manager_, terrain_node_, glm::mat4(1.0f));
Texture* water_texture = TargaTexture::loadTexture("data/textures/waterbubble.tga");
Texture* grass_texture = TargaTexture::loadTexture("data/textures/grass.tga");
Texture* height_texture = TargaTexture::loadTexture("data/textures/underwater_height.tga");
// Initialise a terrain to render.
MaterialLightProperty* terrain_ambient = new MaterialLightProperty(0.7f, 0.7f, 0.7f, 1.0f);
MaterialLightProperty* terrain_diffuse = new MaterialLightProperty(0.8f, 0.8f, 0.8f, 1.0f);
MaterialLightProperty* terrain_specular = new MaterialLightProperty(0.0f, 0.0f, 0.0f, 1.0f);
MaterialLightProperty* terrain_emmisive = new MaterialLightProperty(0.5f, 0.5f, 0.5f, 1.0f);
terrain_material_ = new Material(*terrain_ambient, *terrain_diffuse, *terrain_specular, *terrain_emmisive);
terrain_material_->add1DTexture(*height_texture);
terrain_material_->add2DTexture(*grass_texture);
SceneLeafModel* terrain_leaf_node = new SceneLeafModel(*terrain_node_, NULL, *terrain_, *terrain_material_, CausticTerrainShader::getShader(), false, false);
// The AUV.
auv1_ = new AUV(terrain_node_, glm::translate(glm::mat4(1.0), glm::vec3(4.2f, 3.0f, -3.0f)), *scene_manager_, *grass_texture, "auv0");
scene_manager_->addUpdateableEntity(*auv1_);
auv2_ = new AUV(terrain_node_, glm::translate(glm::mat4(1.0), glm::vec3(-12.2f, 3.0f, 19.0f)), *scene_manager_, *grass_texture, "auv1");
scene_manager_->addUpdateableEntity(*auv2_);
Texture* pillar_texture = TargaTexture::loadTexture("data/models/Pandora/misc/damaged_beacon.tga");
srand (seed);
for (unsigned int i = 0; i < nr_pillars; ++i)
{
bool valid_pillar_location = false;
glm::vec3 pillar_location;
while (!valid_pillar_location)
{
pillar_location.x = ((float)rand() / (float)RAND_MAX) * area_size - area_size / 2.0f;
pillar_location.y = -1.0f;
pillar_location.z = ((float)rand() / (float)RAND_MAX) * area_size - area_size / 2.0f;
// Check that this location is not too close to other pillars and not too close to the auvs.
valid_pillar_location = true;
for (std::vector<Pillar*>::const_iterator ci = mission_site->getPillars().begin(); ci != mission_site->getPillars().end(); ++ci)
{
Pillar* existing_pillar = *ci;
if (glm::distance(existing_pillar->getLocalLocation(), pillar_location) < min_distance)
{
valid_pillar_location = false;
break;
}
}
/*
if (glm::distance(pillar_location, auv1_->getLocalLocation()) < min_distance ||
glm::distance(pillar_location, auv2_->getLocalLocation()) < min_distance)
{
valid_pillar_location = false;
}
*/
}
//Pillar* pillar = new Pillar(i, *mission_site, *scene_manager_, mission_site, glm::translate(glm::mat4(1.0f), pillar_location), "data/models/Pandora/Pillar.plf", *pillar_texture);
std::stringstream pillar_name_ss;
pillar_name_ss << "Pillar" << i;
Pillar* pillar = new Pillar(pillar_name_ss.str(), *mission_site, *scene_manager_, mission_site, glm::translate(glm::mat4(1.0f), pillar_location), "data/models/Pandora/misc/damaged_beacon.plf", *pillar_texture);
mission_site->addPillar(*pillar);
Sphere* sphere = new Sphere(10, 10, 0.1);
SceneNode* sphere_node = new SceneNode(*scene_manager_, terrain_node_, glm::translate(glm::mat4(1.0f), pillar_location));
SceneLeafModel* sphere_model = new SceneLeafModel(*sphere_node, NULL, *sphere, *terrain_material_, BasicShadowShader::getShader(), false, false, OBJECT, ShadowRenderer::NO_SHADOW);
}
#ifndef _WIN32
octomap_ = new OctomapBuilder(*ros_node_, *auv1_, *auv2_);
ontology_ = new Ontology(*ros_node_, *octomap_);
ontology_->addAUV(*auv1_);
ontology_->addAUV(*auv2_);
#endif
for (std::vector<Pillar*>::const_iterator ci = mission_site->getPillars().begin(); ci != mission_site->getPillars().end(); ++ci)
{
InspectionPoint* ip = new InspectionPoint(Pose((*ci)->getLocalLocation().x, 5.0f, (*ci)->getLocalLocation().z - 1.0f, 0, 0), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip);
InspectionPoint* ip2 = new InspectionPoint(Pose((*ci)->getLocalLocation().x - 1.0f, 5.0f, (*ci)->getLocalLocation().z, 0, 90), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip2);
InspectionPoint* ip3 = new InspectionPoint(Pose((*ci)->getLocalLocation().x, 5.0f, (*ci)->getLocalLocation().z + 1.0f, 0, 180), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip3);
InspectionPoint* ip4 = new InspectionPoint(Pose((*ci)->getLocalLocation().x + 1.0f, 5.0f, (*ci)->getLocalLocation().z, 0, 270), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip4);
InspectionPoint* ip5 = new InspectionPoint(Pose((*ci)->getLocalLocation().x, 10.0f, (*ci)->getLocalLocation().z - 1.0f, 0, 0), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip5);
InspectionPoint* ip6 = new InspectionPoint(Pose((*ci)->getLocalLocation().x - 1.0f, 10.0f, (*ci)->getLocalLocation().z, 0, 90), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip6);
InspectionPoint* ip7 = new InspectionPoint(Pose((*ci)->getLocalLocation().x, 10.0f, (*ci)->getLocalLocation().z + 1.0f, 0, 180), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip7);
InspectionPoint* ip8 = new InspectionPoint(Pose((*ci)->getLocalLocation().x + 1.0f, 10.0f, (*ci)->getLocalLocation().z, 0, 270), pillars_enabled_ ? *ci : NULL);
mission_site->addInspectionPoint(*ip8);
if (pillars_enabled_)
{
(*ci)->addInspectionPoint(*ip);
(*ci)->addInspectionPoint(*ip2);
(*ci)->addInspectionPoint(*ip3);
(*ci)->addInspectionPoint(*ip4);
(*ci)->addInspectionPoint(*ip5);
(*ci)->addInspectionPoint(*ip6);
(*ci)->addInspectionPoint(*ip7);
(*ci)->addInspectionPoint(*ip8);
}
}
#ifndef _WIN32
//ontology_->addValvePanel(*value_panel_);
//ontology_->addValveGoal(*valve, vg);
// Make sure to call this AFTER all the properties have been set for each mission site!
ontology_->addMissionSite(*mission_site);
MaterialLightProperty* ambient = new MaterialLightProperty(0, 0, 0, 0);
MaterialLightProperty* diffuse = new MaterialLightProperty(0, 0, 0, 0);
MaterialLightProperty* specular = new MaterialLightProperty(0, 0, 0, 0);
MaterialLightProperty* emmisive = new MaterialLightProperty(0, 0, 1, 0.1f);
Material* material = new Material(*ambient, *diffuse, *specular, *emmisive);
std::vector<Entity*> entities;
entities.push_back(auv1_);
entities.push_back(auv2_);
rrt_ = new RRT(*ros_node_, *scene_manager_, entities, *terrain_node_, *octomap_, *ontology_, *material);
ontology_->initialise(*rrt_);
//WaypointLabeler* wl = new WaypointLabeler(*scene_manager_, *rrt_, *terrain_node_);
// Setup the GUI.
theme_ = new MyGUITheme();
//planning_gui_ = new PlanningGUI(*theme, *auv_, *rrt_);
Texture* font_texture = TargaTexture::loadTexture("data/textures/fonts/test_font.tga");
font_ = new TexturedFont(*font_texture);
// Setup the GUI for the FPS.
GUIManager& gui_manager = GUIManager::getInstance();
Container* fps_container = new Container(*theme_, font_->clone(), 10, 10, 120, 20, false);
Label* fps_label = new Label(*theme_, 120, 15, "", 12);
fps_container->addElement(*fps_label, 0, -10);
fps_label_ = new FPSLabel(*fps_label);
planning_msgs::ActionDispatch action;
Container* status_container = new Container(*theme_, font_->clone(), 300, 10, 400, 40, false);
status_label_ = new ActionLabel(*theme_, font_->clone(), glm::vec4(1.0f, 0.0f, 0.0f, 0.5f), 400, 30, "All systems go", action);
status_container->addElement(*status_label_, 0, -10);
gui_manager.addFrame(*fps_container);
// gui_manager.addFrame(*status_container);
// Initialise the action controller that will receive all the messages from the planner.
FollowWaypointController* controller1 = new FollowWaypointController(*scene_manager_, *auv1_, *rrt_);
action_controller1_ = new ActionController(*scene_manager_, *ros_node_, *auv1_, *terrain_node_, *controller1, *ontology_, status_label_);
FollowWaypointController* controller2 = new FollowWaypointController(*scene_manager_, *auv2_, *rrt_);
action_controller2_ = new ActionController(*scene_manager_, *ros_node_, *auv2_, *terrain_node_, *controller2, *ontology_, status_label_);
// Setup the ROS odometry class.
auv_odometry1_ = new Odometry(*auv1_);
auv_odometry2_ = new Odometry(*auv2_);
#endif
/*
// Test under water vulcanos.
std::vector<glm::vec3> under_water_volcano_locations;
for (unsigned int i = 0; i < 50; ++i)
{
float x = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX) - 0.5f) * 200.0f;
float z = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX) - 0.5f) * 200.0f;
float uwv_height = terrain_->getHeight(x, z);
under_water_volcano_locations.push_back(glm::vec3(x, uwv_height, z));
}
UnderWaterVolcano* under_Water_volcano = new UnderWaterVolcano(*scene_manager_, terrain_node_, glm::mat4(1.0f), under_water_volcano_locations);
scene_manager_->addUpdateableEntity(*under_Water_volcano);
*/
// Create a node that ignores the rotation.
stable_platform1_ = new SceneNode(*scene_manager_, &auv1_->getAUVNode(), glm::mat4(1.0f));
stable_platform1_->ignoreRotations(true);
stable_platform2_ = new SceneNode(*scene_manager_, &auv2_->getAUVNode(), glm::mat4(1.0f));
stable_platform2_->ignoreRotations(true);
// Add some lighting.
{
// AUV1
PointLight* point_light = new PointLight(*scene_manager_, 34, glm::vec3(0.6f, 0.6f, 0.6f), glm::vec3(0.9f, 0.9f, 0.9f), glm::vec3(0.2f, 0.2f, 0.2f), 1.0f, 0.3f, 0.15f, 0.1f, 10.0f);
SceneNode* light_node = new SceneNode(*scene_manager_, &auv1_->getAUVModel(), glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -1.25f)));
SceneLeafLight* light_leaf = new SceneLeafLight(*light_node, NULL, *point_light);
volumetric_light_point_ = new PointLight(*scene_manager_, 34, glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(0.9f, 0.9f, 0.9f), glm::vec3(0.2f, 0.2f, 0.2f), 1.0f, 0.3f, 0.15f, 0.1f, 10.0f, 128, GL_NONE, GL_NONE, GL_NONE);
volumetric_light_leaf_ = new SceneLeafLight(*light_node, NULL, *volumetric_light_point_);
LightVolumeShape* lvs = new LightVolumeShape(*scene_manager_, *volumetric_light_point_);
light_volume_leaf_ = new SceneLeafModel(*light_node, NULL, *lvs, *terrain_material_, ShadowVolumeShader::getShader(), false, true, COLLISION, ShadowRenderer::NO_SHADOW);
lvs->setLeafNode(*light_volume_leaf_);
}
{
// AUV2
PointLight* point_light = new PointLight(*scene_manager_, 34, glm::vec3(0.6f, 0.6f, 0.6f), glm::vec3(0.9f, 0.9f, 0.9f), glm::vec3(0.2f, 0.2f, 0.2f), 1.0f, 0.3f, 0.15f, 0.1f, 10.0f);
SceneNode* light_node = new SceneNode(*scene_manager_, &auv2_->getAUVModel(), glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -1.25f)));
SceneLeafLight* light_leaf = new SceneLeafLight(*light_node, NULL, *point_light);
volumetric_light_point2_ = new PointLight(*scene_manager_, 34, glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(0.9f, 0.9f, 0.9f), glm::vec3(0.2f, 0.2f, 0.2f), 1.0f, 0.3f, 0.15f, 0.1f, 10.0f, 128, GL_NONE, GL_NONE, GL_NONE);
volumetric_light_leaf2_ = new SceneLeafLight(*light_node, NULL, *volumetric_light_point2_);
LightVolumeShape* lvs = new LightVolumeShape(*scene_manager_, *volumetric_light_point2_);
light_volume_leaf2_ = new SceneLeafModel(*light_node, NULL, *lvs, *terrain_material_, ShadowVolumeShader::getShader(), false, true, COLLISION, ShadowRenderer::NO_SHADOW);
lvs->setLeafNode(*light_volume_leaf2_);
}
#ifndef _WIN32
sonar1_ = new Sonar(*ros_node_, *scene_manager_, &auv1_->getAUVModel(), *auv1_, auv1_->getName(), glm::translate(glm::mat4(1.0f), glm::vec3(0.00f, 0.0f, -2.25f)), 0.1f, 60.0f, 30.0f);
sonar2_ = new Sonar(*ros_node_, *scene_manager_, &auv2_->getAUVModel(), *auv2_, auv2_->getName(), glm::translate(glm::mat4(1.0f), glm::vec3(0.00f, 0.0f, -2.25f)), 0.1f, 60.0f, 30.0f);
#endif
//SliceSonar* slice_sonar = new SliceSonar(*ros_node_, *scene_manager_, 9, &auv_->getAUVNode(), glm::translate(glm::mat4(1.0f), glm::vec3(0.00f, 0.0f, -2.25f)), 0.1f, 60.0f, 30.0f);
//sonar_odometry_ = new Odometry(*slice_sonar);
// Add the camera system.
camera_node_ = new DynamicCamera(*auv1_, *scene_manager_, stable_platform1_, glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 1.0f, 2.0f)), 90.0f, 1024, 768, 0.1f, 300.0f);
scene_manager_->addUpdateableEntity(*camera_node_);
std::vector<glm::vec2> uv_mapping;
uv_mapping.push_back(glm::vec2(0.75f, 1.0f));
uv_mapping.push_back(glm::vec2(1.0f, 1.0f));
uv_mapping.push_back(glm::vec2(0.75f, 0.75f));
uv_mapping.push_back(glm::vec2(1.0f, 0.75f));
BillBoard* bb_auv1 = new BillBoard(*theme_, *font_, *auv1_, *camera_node_, glm::vec3(0, 1, 0), 50, 50, uv_mapping);
bb_auv1->setVisible(false);
gui_manager.addFrame(*bb_auv1);
auv1_->setBillBoard(*bb_auv1);
BillBoard* bb_auv2 = new BillBoard(*theme_, *font_, *auv2_, *camera_node_, glm::vec3(0, 1, 0), 50, 50, uv_mapping);
bb_auv2->setVisible(false);
gui_manager.addFrame(*bb_auv2);
auv2_->setBillBoard(*bb_auv2);
DirectedLight* sun = new DirectedLight(*scene_manager_, glm::vec3(0, 0, 0), glm::vec3(0, 0, 0), glm::vec3(0, 0, 0), 1.01, 0.15, 0.01);
SceneNode* sun_node = new SceneNode(*scene_manager_, terrain_node_, glm::rotate(glm::translate(glm::mat4(1.0f), glm::vec3(0, 20, 0)), -90.0f, glm::vec3(1, 0, 0)));
SceneLeafLight* light_leaf = new SceneLeafLight(*sun_node, NULL, *sun);
caustic_texture_ = new CausticTexture();
CausticShader::initialiseSun(*sun, *caustic_texture_);
CausticTerrainShader::initialiseSun(*sun, *caustic_texture_);
PlanVisualiser* pv1 = new PlanVisualiser(*ros_node_, *auv1_, *ontology_, *terrain_node_, *scene_manager_, *theme_, *font_, *camera_node_);
action_controller1_->addListener(*pv1);
action_controller2_->addListener(*pv1);
PlanVisualiser* pv2 = new PlanVisualiser(*ros_node_, *auv2_, *ontology_, *terrain_node_, *scene_manager_, *theme_, *font_, *camera_node_);
action_controller1_->addListener(*pv2);
action_controller2_->addListener(*pv2);
#ifdef _WIN32
//pl_ = new PlanLine(*theme, *font, 200, 30, 650, 150);
#else
pl_ = new PlanLine(*ros_node_, *theme_, *font_, 200, 30, 200, 650);
action_controller1_->addListener(*pl_);
action_controller2_->addListener(*pl_);
// Create some shapes to denote the inspection points.
std::vector<InspectionPoint*> inspection_points;
if (ontology_->getInspectionPoints(inspection_points))
{
for (std::vector<InspectionPoint*>::const_iterator ci = inspection_points.begin(); ci != inspection_points.end(); ++ci)
{
const InspectionPoint* ip = *ci;
std::cout << ip->getPose().x_ << " " << ip->getPose().y_ << " " << ip->getPose().z_ << std::endl;
Sphere* sphere = new Sphere(10, 10, 0.1);
SceneNode* sphere_node = new SceneNode(*scene_manager_, terrain_node_, glm::translate(glm::mat4(1.0f), glm::vec3(ip->getPose().x_, ip->getPose().y_, ip->getPose().z_)));
SceneLeafModel* sphere_model = new SceneLeafModel(*sphere_node, NULL, *sphere, *terrain_material_, BasicShadowShader::getShader(), false, false, OBJECT, ShadowRenderer::NO_SHADOW);
}
}
#endif
shadow_renderer_ = new ShadowRenderer(*scene_manager_, 512, GL_BACK, GL_NONE, GL_NONE);
// Create a seperate framebuffer for the post processing.
post_processing_texture_ = new Texture(GL_TEXTURE_2D);
//glGenTextures(1, &texture_id_);
glBindTexture(GL_TEXTURE_2D, post_processing_texture_->getTextureId());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 1024, 768, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glGenFramebuffers(1, &fbo_id_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_id_);
// Attach the rgb texture to it.
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, post_processing_texture_->getTextureId(), 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Test! :)
//BillBoard* bb_auv1 = new BillBoard(*theme_, font_->clone(), *auv1_, *camera_node_, glm::vec3(0, 1, 0), 50, 30, theme_->getMaximiseTexture());
//BillBoard* bb_auv2 = new BillBoard(*theme_, font_->clone(), *auv2_, *camera_node_, glm::vec3(0, 1, 0), 50, 30, theme_->getMaximiseTexture());
//gui_manager.addFrame(*bb_auv1);
//gui_manager.addFrame(*bb_auv2);
return true;
}
bool PandoraPillarExperiment::postInit()
{
return true;
}
GLuint PandoraPillarExperiment::postProcess(Texture& color_texture, Texture& depth_texture, float dt)
{
GLuint merged_frame_buffer = 0;
fps_label_->frameRendered();
if (auv1_->isLightOn() || auv2_->isLightOn())
{
// Render the scene from the camera's point of view, we use this depth texture to cull the light such that it does not shine through
// solid objects.
shadow_renderer_->render(*camera_node_);
glm::vec3 camera_location = camera_node_->getLocation();
glm::mat4 view_matrix = camera_node_->getViewMatrix();
glm::mat4 perspective_matrix = camera_node_->getPerspectiveMatrix();
std::vector<const SceneLeafLight*> active_lights;
if (auv1_->isLightOn())
{
active_lights.push_back(volumetric_light_leaf_);
volumetric_light_point_->preRender(volumetric_light_leaf_->getParent()->getCompleteTransformation());
}
if (auv2_->isLightOn())
{
volumetric_light_point2_->preRender(volumetric_light_leaf2_->getParent()->getCompleteTransformation());
}
glClearColor(0.0, 0.0, 0.0, 0.0f);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_id_);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_DEPTH_CLAMP);
// Enable additive blending.
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
ShadowVolumeShader& shader = ShadowVolumeShader::getShader();
if (auv1_->isLightOn())
{
// Render the light volume in this frame buffer.
shader.initialise(*light_volume_leaf_, view_matrix, light_volume_leaf_->getParent()->getCompleteTransformation(), perspective_matrix, *volumetric_light_leaf_, camera_node_->getNearPlane(), camera_node_->getFarPlane(), shadow_renderer_->getTexture());
light_volume_leaf_->draw(view_matrix, perspective_matrix, active_lights, NULL);
}
if (auv2_->isLightOn())
{
// For the second light.
active_lights.clear();
active_lights.push_back(volumetric_light_leaf2_);
// Render the shadow from the light's perspective.
// Render the light volume in this frame buffer.
shader.initialise(*light_volume_leaf2_, view_matrix, light_volume_leaf2_->getParent()->getCompleteTransformation(), perspective_matrix, *volumetric_light_leaf2_, camera_node_->getNearPlane(), camera_node_->getFarPlane(), shadow_renderer_->getTexture());
light_volume_leaf2_->draw(view_matrix, perspective_matrix, active_lights, NULL);
}
//ss_ << "end...";
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_CLAMP);
// Merge the images of the volumetric light step with the main image.
MergeFBOShader& merge_shader = MergeFBOShader::getShader();
merge_shader.postProcess(color_texture, *post_processing_texture_, dt);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glClearColor(0.2, 0.2, 0.4, 1.0f);
merged_frame_buffer = merge_shader.getFrameBufferId() ;
}
// Draw any additional GUI elements.
return merged_frame_buffer;
}
void PandoraPillarExperiment::tick(float dt)
{
caustic_texture_->update(dt);
ros::spinOnce();
// Publish the odometry information of the UAV.
auv_odometry1_->update(dt);
auv_odometry2_->update(dt);
// Update the actions.
action_controller1_->update(dt);
action_controller2_->update(dt);
// Update ROS.
ros::spinOnce();
Frustum frustum1(sonar1_->getPerspectiveMatrix() * sonar1_->getViewMatrix());
Frustum frustum2(sonar2_->getPerspectiveMatrix() * sonar2_->getViewMatrix());
if (pillars_enabled_)
{
//Frustum frustum(camera_node_->getPerspectiveMatrix() * camera_node_->getViewMatrix());
std::stringstream ss;
ss << "Visible pillars ";
for (std::vector<MissionSite*>::const_iterator ci = ontology_->getMissionSites().begin(); ci != ontology_->getMissionSites().end(); ++ci)
{
MissionSite* mission_site = *ci;
for (std::vector<Pillar*>::const_iterator ci = mission_site->getPillars().begin(); ci != mission_site->getPillars().end(); ++ci)
{
Pillar* pillar = *ci;
if (pillar->getFrustumChecker().isInsideFrustum(frustum1) && !pillar->hasBeenObserved())
{
std::vector<glm::vec2> uv_mapping;
uv_mapping.push_back(glm::vec2(0.75f, 1.0f));
uv_mapping.push_back(glm::vec2(1.0f, 1.0f));
uv_mapping.push_back(glm::vec2(0.75f, 0.75f));
uv_mapping.push_back(glm::vec2(1.0f, 0.75f));
auv1_->setBillBoardUVs(uv_mapping);
}
else if (pillar->getFrustumChecker().isInsideFrustum(frustum2) && !pillar->hasBeenObserved())
{
//SceneNode* dummy_node = new SceneNode(*scene_manager_, NULL, glm::translate(glm::mat4(1.0f), auv2_->getGlobalLocation()));
std::vector<glm::vec2> uv_mapping;
uv_mapping.push_back(glm::vec2(0.75f, 1.0f));
uv_mapping.push_back(glm::vec2(1.0f, 1.0f));
uv_mapping.push_back(glm::vec2(0.75f, 0.75f));
uv_mapping.push_back(glm::vec2(1.0f, 0.75f));
//BillBoard* bb = new BillBoard(*theme_, *font_, *dummy_node, *camera_node_, glm::vec3(0, 1, 0), 50, 50, uv_mapping);
//GUIManager& gui_manager = GUIManager::getInstance();
//gui_manager.addFrame(*bb);
//auv2_->setBillBoard(*bb);
auv2_->setBillBoardUVs(uv_mapping);
}
if (pillar->getFrustumChecker().isInsideFrustum(frustum1) ||
pillar->getFrustumChecker().isInsideFrustum(frustum2))
{
pillar->setObserved();
ss << pillar->getName() << " ";
}
}
}
//status_label_->setLabel(ss.str());
}
else
{
//status_label_->setLabel("Pillar detection disabled");
}
if (glfwGetKey('1') == GLFW_PRESS)
{
camera_node_->setTargetToFollow(*auv1_, stable_platform1_);
}
if (glfwGetKey('2') == GLFW_PRESS)
{
camera_node_->setTargetToFollow(*auv2_, stable_platform2_);
}
if (glfwGetKey('Z') == GLFW_PRESS)
{
std::cout << "Create an RRT" << std::endl;
std::vector<glm::vec3> begin;
begin.push_back(auv1_->getGlobalLocation());
//begin.push_back(auv2_->getGlobalLocation());
std::vector<bool> connectivity(2, false);
std::set<Waypoint*> waypoints;
/*
for (std::vector<MissionSite*>::const_iterator ci = ontology_->getMissionSites().begin(); ci != ontology_->getMissionSites().end(); ++ci)
{
MissionSite* mission_site = *ci;
for (std::vector<Pillar*>::const_iterator ci = mission_site->getPillars().begin(); ci != mission_site->getPillars().end(); ++ci)
{
Pillar* pillar = *ci;
for (std::vector<InspectionPoint*>::const_iterator ci = pillar->getInspectionPoint().begin(); ci != pillar->getInspectionPoint().end(); ++ci)
{
InspectionPoint* inspection_point = *ci;
std::stringstream ss;
ss << "wp_inspectionpoint" << inspection_point->getId();
Waypoint* waypoint = new Waypoint(ss.str(), inspection_point->getVisiblePoint(), connectivity);
waypoints.insert(waypoint);
}
}
}
*/
std::vector<bool> resultsz(2, false);
waypoints.insert(new Waypoint("test", auv1_->getLocalLocation() + glm::vec3(0.0f, 0.0f, -8.0f), resultsz));
rrt_->createRRT(begin, waypoints, -100, 100, -20, 20, -100, 100);
for (std::vector<Waypoint*>::const_iterator ci = rrt_->getPoints().begin(); ci != rrt_->getPoints().end(); ++ci)
{
std::cout << "p: (" << (*ci)->position_.x << ", " << (*ci)->position_.y << ", " << (*ci)->position_.z << ")" << std::endl;
}
}
if (glfwGetKey('Q') == GLFW_PRESS)
{
rrt_->setVisible(false);
}
if (glfwGetKey('W') == GLFW_PRESS)
{
rrt_->setVisible(true);
}
}
void PandoraPillarExperiment::onResize(int width, int height)
{
camera_node_->onResize(width, height);
glBindTexture(GL_TEXTURE_2D, post_processing_texture_->getTextureId());
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_id_);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, post_processing_texture_->getTextureId(), 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
MergeFBOShader& merge_shader = MergeFBOShader::getShader();
merge_shader.onResize(width, height);
}
| 41.734694 | 257 | 0.696608 | [
"render",
"object",
"vector",
"solid"
] |
e2fcb5b65b4206d13487bf9ef9394bcf13feb1c2 | 18,717 | cpp | C++ | GUI/mainwindow.cpp | beldmitr/i4004 | f090bc91acbf88be119d72a80301cdcf57a8c159 | [
"MIT"
] | 7 | 2017-04-07T01:17:26.000Z | 2021-11-02T06:08:45.000Z | GUI/mainwindow.cpp | beldmitr/i4004 | f090bc91acbf88be119d72a80301cdcf57a8c159 | [
"MIT"
] | null | null | null | GUI/mainwindow.cpp | beldmitr/i4004 | f090bc91acbf88be119d72a80301cdcf57a8c159 | [
"MIT"
] | 1 | 2018-12-13T10:47:08.000Z | 2018-12-13T10:47:08.000Z | #include "mainwindow.h"
void MainWindow::createActions()
{
// Actions File
actNew = std::shared_ptr<QAction>(new QAction(tr("&New"), this));
actNew->setIcon(QIcon(":/Resources/icons/new.png"));
actNew->setShortcut(QKeySequence::New);
connect(actNew.get(), &QAction::triggered, [=](){
this->editorSubWindow->newFile();
});
actOpen = std::shared_ptr<QAction>(new QAction(tr("&Open"), this));
actOpen->setIcon(QIcon(":/Resources/icons/open.png"));
actOpen->setShortcut(QKeySequence::Open);
connect(actOpen.get(), &QAction::triggered, this, [=](){
this->editorSubWindow->openFile();
});
actSave = std::shared_ptr<QAction>(new QAction(tr("&Save"), this));
actSave->setIcon(QIcon(":/Resources/icons/save.png"));
actSave->setShortcut(QKeySequence::Save);
connect(actSave.get(), &QAction::triggered, [=](){
this->editorSubWindow->saveFile();
});
actSaveAs = std::shared_ptr<QAction>(new QAction(tr("Save As..."), this));
actSaveAs->setIcon(QIcon(":/Resources/icons/saveas.png"));
actSaveAs->setShortcut(QKeySequence::SaveAs);
connect(actSaveAs.get(), &QAction::triggered, [=](){
this->editorSubWindow->saveAsFile();
});
actExit = std::shared_ptr<QAction>(new QAction(tr("E&xit"), this));
actExit->setIcon(QIcon(":/Resources/icons/exit.png"));
actExit->setShortcut(tr("Ctrl+Q"));
connect(actExit.get(), &QAction::triggered, [=](){
QMainWindow::close();
});
// Actions Edit
actUndo = std::shared_ptr<QAction>(new QAction(tr("Undo"), this));
actUndo->setIcon(QIcon(":/Resources/icons/undo.png"));
actUndo->setShortcut(QKeySequence::Undo);
connect(actUndo.get(), &QAction::triggered, [=](){
this->editorSubWindow->undoEdit();
});
actRedo = std::shared_ptr<QAction>(new QAction(tr("Redo"), this));
actRedo->setIcon(QIcon(":/Resources/icons/redo.png"));
actRedo->setShortcut(QKeySequence::Redo);
connect(actRedo.get(), &QAction::triggered, [=](){
this->editorSubWindow->redoEdit();
});
actCut = std::shared_ptr<QAction>(new QAction(tr("Cut"), this));
actCut->setIcon(QIcon(":/Resources/icons/cut.png"));
actCut->setShortcut(QKeySequence::Cut);
connect(actCut.get(), &QAction::triggered, [=](){
this->editorSubWindow->cutEdit();
});
actCopy = std::shared_ptr<QAction>(new QAction(tr("Copy"), this));
actCopy->setIcon(QIcon(":/Resources/icons/copy.png"));
actCopy->setShortcut(QKeySequence::Copy);
connect(actCopy.get(), &QAction::triggered, [=](){
this->editorSubWindow->copyEdit();
});
actPaste = std::shared_ptr<QAction>(new QAction(tr("Paste"), this));
actPaste->setIcon(QIcon(":/Resources/icons/paste.png"));
actPaste->setShortcut(QKeySequence::Paste);
connect(actPaste.get(), &QAction::triggered, [=](){
this->editorSubWindow->pasteEdit();
});
actDelete = std::shared_ptr<QAction>(new QAction(tr("Delete"), this));
actDelete->setIcon(QIcon(":/Resources/icons/delete.png"));
actDelete->setShortcut(QKeySequence::Delete);
connect(actDelete.get(), &QAction::triggered, [=](){
this->editorSubWindow->deleteEdit();
});
actSelectAll = std::shared_ptr<QAction>(new QAction(tr("Select All"), this));
actSelectAll->setIcon(QIcon(":/Resources/icons/selectall.png"));
actSelectAll->setShortcut(QKeySequence::SelectAll);
connect(actSelectAll.get(), &QAction::triggered, [=](){
this->editorSubWindow->selectAllEdit();
});
// Actions Build
actCompile = std::shared_ptr<QAction>(new QAction(tr("Compile"), this));
actCompile->setIcon(QIcon(":/Resources/icons/compile.png"));
actCompile->setShortcut(tr("Ctrl+B"));
connect(actCompile.get(), &QAction::triggered, [=](){
buildCode();
});
// Actions Debug
actionGroup = std::make_shared<QActionGroup>(this);
actVerySlow = std::shared_ptr<QAction>(new QAction(tr("Very Slow"), this));
actVerySlow->setCheckable(true);
actionGroup->addAction(actVerySlow.get());
connect(actVerySlow.get(), &QAction::triggered, [=](){
simulator->setDelay(2000);
});
actSlow = std::shared_ptr<QAction>(new QAction(tr("Slow"), this));
actSlow->setCheckable(true);
actionGroup->addAction(actSlow.get());
connect(actSlow.get(), &QAction::triggered, [=](){
simulator->setDelay(1000);
});
actNormal = std::shared_ptr<QAction>(new QAction(tr("Normal"), this));
actNormal->setCheckable(true);
actNormal->setChecked(true);
actionGroup->addAction(actNormal.get());
connect(actNormal.get(), &QAction::triggered, [=](){
simulator->setDelay(50);
});
actFast = std::shared_ptr<QAction>(new QAction(tr("Fast"), this));
actFast->setCheckable(true);
actionGroup->addAction(actFast.get());
connect(actFast.get(), &QAction::triggered, [=](){
simulator->setDelay(25);
});
actVeryFast = std::shared_ptr<QAction>(new QAction(tr("Very Fast"), this));
actVeryFast->setCheckable(true);
actionGroup->addAction(actVeryFast.get());
connect(actVeryFast.get(), &QAction::triggered, [=](){
simulator->setDelay(10);
});
actPlay = std::shared_ptr<QAction>(new QAction(tr("Play"), this));
actPlay->setIcon(QIcon(":/Resources/icons/debug_resume.png"));
actPlay->setShortcut(tr("F5"));
connect(actPlay.get(), &QAction::triggered, [=](){
simulator->play();
});
actStep = std::shared_ptr<QAction>(new QAction(tr("Step"), this));
actStep->setIcon(QIcon(":/Resources/icons/debug_step_over.png"));
actStep->setShortcut(tr("F10"));
connect(actStep.get(), &QAction::triggered, [=](){
simulator->step();
});
actStop = std::shared_ptr<QAction>(new QAction(tr("Stop"), this));
actStop->setIcon(QIcon(":/Resources/icons/debug_stop.png"));
actStop->setShortcut(tr("Escape"));
connect(actStop.get(), &QAction::triggered, [=](){
simulator->stop();
});
actReset = std::shared_ptr<QAction>(new QAction(tr("Reset"), this));
actReset->setIcon(QIcon(":/Resources/icons/debug_restart.png"));
actReset->setShortcut(tr("Ctrl+Backspace"));
connect(actReset.get(), &QAction::triggered, [=](){
simulator->reset();
});
}
void MainWindow::createMenu()
{
// Create main menu
mainMenu = std::shared_ptr<QMenuBar>(new QMenuBar);
this->setMenuBar(mainMenu.get());
// Create menu File
menuFile = std::shared_ptr<QMenu>(mainMenu->addMenu("File"));
menuFile->addAction(actNew.get());
menuFile->addAction(actOpen.get());
menuFile->addSeparator();
menuFile->addAction(actSave.get());
menuFile->addAction(actSaveAs.get());
menuFile->addSeparator();
menuFile->addAction(actExit.get());
// Create menu Edit
menuEdit = std::shared_ptr<QMenu>(mainMenu->addMenu("Edit"));
menuEdit->addAction(actUndo.get());
menuEdit->addAction(actRedo.get());
menuEdit->addSeparator();
menuEdit->addAction(actCut.get());
menuEdit->addAction(actCopy.get());
menuEdit->addAction(actPaste.get());
menuEdit->addAction(actDelete.get());
menuEdit->addSeparator();
menuEdit->addAction(actSelectAll.get());
// Create menu Build
menuBuild = std::shared_ptr<QMenu>(mainMenu->addMenu("Build"));
menuBuild->addAction(actCompile.get());
menuBuild->addSeparator();
speedMenu = std::make_shared<QMenu>("Play speed");
menuBuild->addMenu(speedMenu.get());
speedMenu->addAction(actVerySlow.get());
speedMenu->addAction(actSlow.get());
speedMenu->addAction(actNormal.get());
speedMenu->addAction(actFast.get());
speedMenu->addAction(actVeryFast.get());
menuBuild->addAction(actPlay.get());
menuBuild->addAction(actStop.get());
menuBuild->addAction(actStep.get());
menuBuild->addAction(actReset.get());
// Create menu Windows
menuWindows = std::shared_ptr<QMenu>(mainMenu->addMenu("Windows"));
nextWindow = std::shared_ptr<QAction>(new QAction("Next window", this));
nextWindow->setShortcut(tr("Ctrl+]"));
connect(nextWindow.get(), SIGNAL(triggered(bool)), mdi.get(), SLOT(activateNextSubWindow()));
menuWindows->addAction(nextWindow.get());
prevWindow = std::shared_ptr<QAction>(new QAction("Previous window", this));
prevWindow->setShortcut(tr("Ctrl+["));
connect(prevWindow.get(), SIGNAL(triggered(bool)), mdi.get(), SLOT(activatePreviousSubWindow()));
menuWindows->addAction(prevWindow.get());
menuWindows->addSeparator();
for(int i = 0; i < mdi->subWindowList().length(); i++)
{
QMdiSubWindow* w = mdi->subWindowList().at(i);
QAction* act = new QAction(w->windowTitle(), this);
QIcon ico = w->windowIcon();
act->setIcon(ico);
if (i < 9)
{
std::string shortcut = QString("Ctrl+"+ QString::number(i+1)).toStdString();
act->setShortcut(tr(shortcut.c_str()));
}
listWindowsMenuBtn.push_back(act);
connect(act, SIGNAL(triggered(bool)), w, SLOT(show()));
connect(act, SIGNAL(triggered(bool)), w, SLOT(setFocus()));
menuWindows->addAction(act);
}
menuWindows->addSeparator();
minimizeAll = std::shared_ptr<QAction>(new QAction("Minimize all", this));
minimizeAll->setShortcut(tr("Ctrl+M"));
for(QMdiSubWindow* w : mdi->subWindowList())
{
connect(minimizeAll.get(), SIGNAL(triggered(bool)), w, SLOT(showMinimized()));
}
menuWindows->addAction(minimizeAll.get());
showWindows = std::shared_ptr<QAction>(new QAction("Show windows", this));
showWindows->setShortcut(tr("Ctrl+Shift+M"));
for(QMdiSubWindow* w : mdi->subWindowList())
{
connect(showWindows.get(), SIGNAL(triggered(bool)), w, SLOT(showNormal()));
}
menuWindows->addAction(showWindows.get());
}
void MainWindow::createToolbars()
{
toolBarMinimize = std::shared_ptr<QToolBar>(new QToolBar("Minimize"));
for(QMdiSubWindow* w : mdi->subWindowList())
{
QIcon ico = w->windowIcon();
QString title = w->windowTitle();
QAction* act = new QAction(ico, title, this);
listWindowsToolbarBtn.push_back(act);
act->setToolTip("Show " + title);
connect(act, SIGNAL(triggered(bool)), w, SLOT(show()));
connect(act, SIGNAL(triggered(bool)), w, SLOT(setFocus()));
toolBarMinimize->addAction(act);
}
toolBarMinimize->setFloatable(false);
toolBarMinimize->setMovable(false);
toolBarFile = std::shared_ptr<QToolBar>(new QToolBar("File"));
toolBarFile->addAction(actNew.get());
toolBarFile->addAction(actOpen.get());
toolBarFile->addAction(actSave.get());
toolBarEdit = std::shared_ptr<QToolBar>(new QToolBar("Edit"));
toolBarEdit->addAction(actUndo.get());
toolBarEdit->addAction(actRedo.get());
toolBarEdit->addSeparator();
toolBarEdit->addAction(actCut.get());
toolBarEdit->addAction(actCopy.get());
toolBarEdit->addAction(actPaste.get());
toolBarEdit->addAction(actDelete.get());
toolBarEdit->addSeparator();
toolBarEdit->addAction(actSelectAll.get());
toolBarBuild = std::shared_ptr<QToolBar>(new QToolBar("Build"));
toolBarBuild->addAction(actCompile.get());
toolBarBuild->addSeparator();
toolBarBuild->addAction(actPlay.get());
toolBarBuild->addAction(actStop.get());
toolBarBuild->addAction(actStep.get());
toolBarBuild->addAction(actReset.get());
this->addToolBar(toolBarFile.get());
this->addToolBar(toolBarEdit.get());
this->addToolBar(toolBarBuild.get());
this->addToolBar(Qt::LeftToolBarArea, toolBarMinimize.get());
}
void MainWindow::createSubWindows()
{
editorSubWindow = std::shared_ptr<EditorSubWindow>(new EditorSubWindow(mdi.get()));
mdi->addSubWindow(editorSubWindow.get(), Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
debuggerSubWindow = std::shared_ptr<DebuggerSubWindow>(new DebuggerSubWindow(mdi.get(), compiler, simulator));
mdi->addSubWindow(debuggerSubWindow.get(), Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
ledSubWindow = std::shared_ptr<LEDSubWindow>(new LEDSubWindow(mdi.get(), simulator));
mdi->addSubWindow(ledSubWindow.get(), Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
buttonSubWindow = std::shared_ptr<ButtonSubWindow>(new ButtonSubWindow(mdi.get(), simulator));
mdi->addSubWindow(buttonSubWindow.get(), Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
mdi->setActiveSubWindow(editorSubWindow.get()); // Editor window is activated (focused) by default
debuggerSubWindow->setWindowState(Qt::WindowMinimized);
ledSubWindow->setWindowState(Qt::WindowMinimized);
buttonSubWindow->setWindowState(Qt::WindowMinimized);
}
void MainWindow::createDocks()
{
this->setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
this->setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
this->setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
this->setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
dockResult = std::shared_ptr<QDockWidget>(new QDockWidget("Output"));
dockResult->setFeatures(QDockWidget::NoDockWidgetFeatures);
lstResult = std::shared_ptr<QListWidget>(new QListWidget);
dockResult->setWidget(lstResult.get());
this->addDockWidget(Qt::BottomDockWidgetArea, dockResult.get());
dockResult->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
dockDRam = std::shared_ptr<QDockWidget>(new QDockWidget("Data RAM"));
dockDRam->setFeatures(QDockWidget::NoDockWidgetFeatures);
dramWidget = std::shared_ptr<DataRamWidget>(new DataRamWidget(simulator));
dockDRam->setWidget(dramWidget.get());
this->addDockWidget(Qt::BottomDockWidgetArea, dockDRam.get());
dockDRam->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
dockRom = std::shared_ptr<QDockWidget>(new QDockWidget("ROM"));
dockRom->setFeatures(QDockWidget::NoDockWidgetFeatures);
romWidget = std::shared_ptr<RomWidget>(new RomWidget(simulator));
dockRom->setWidget(romWidget.get());
this->addDockWidget(Qt::BottomDockWidgetArea, dockRom.get());
dockRom->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
this->tabifyDockWidget(dockResult.get(), dockRom.get());
this->tabifyDockWidget(dockRom.get(), dockDRam.get());
this->dockResult->raise();
dockCpuWidget = std::shared_ptr<QDockWidget>(new QDockWidget("CPU"));
dockCpuWidget->setFeatures(QDockWidget::NoDockWidgetFeatures);
cpuWidget = std::shared_ptr<CpuWidget>(new CpuWidget(simulator));
dockCpuWidget->setWidget(cpuWidget.get());
this->addDockWidget(Qt::BottomDockWidgetArea, dockCpuWidget.get());
connect(compiler, SIGNAL(onCompiled()), this, SLOT(handleCompiled()));
}
MainWindow::MainWindow(Compiler& compiler, Simulator &simulator, QWidget *parent)
: QMainWindow(parent)
{
this->compiler = &compiler;
this->simulator = &simulator;
this->setWindowState(Qt::WindowMaximized);
// create components
mdi = std::shared_ptr<QMdiArea>(new QMdiArea);
// mdi->tileSubWindows();
// mdi->cascadeSubWindows();
mdi->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
mdi->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
createActions();
createDocks();
createSubWindows();
createToolbars();
createMenu();
statusLabel = std::shared_ptr<QLabel>(new QLabel("Line: 1\t"));
statusBar = std::shared_ptr<QStatusBar>(new QStatusBar);
statusBar->setStyleSheet("background-color: lightgray");
statusBar->addPermanentWidget(statusLabel.get());
// set widgets
this->setCentralWidget(mdi.get());
this->setStatusBar(statusBar.get());
connect(this->compiler, SIGNAL(onCompiled()), this, SLOT(handleBuildCode()));
connect(this->compiler, SIGNAL(onCompiledError()), this, SLOT(handleCompiledError()));
connect(this->simulator, SIGNAL(onEvalCommand(QString)), this, SLOT(handleEvalCommand(const QString&)));
connect(editorSubWindow.get(), SIGNAL(onCursorPosChanged(unsigned)), this, SLOT(handleCursorPosChanged(unsigned)));
}
MainWindow::~MainWindow()
{
for (QAction* a : listWindowsMenuBtn)
{
delete(a);
}
for (QAction* a : listWindowsToolbarBtn)
{
delete(a);
}
}
void MainWindow::createOutputFilename()
{
outputname = filename;
outputname = outputname.split(".").first();
outputname.append(".bin");
}
void MainWindow::buildCode()
{
this->editorSubWindow->saveFile();
this->actCompile->setDisabled(true);
simulator->stop();
simulator->reset();
lstResult->clear();
filename = this->editorSubWindow->getFilename();
QtConcurrent::run([=](){
compiler->compile(filename.toStdString());
});
}
void MainWindow::closeEvent(QCloseEvent* event)
{
bool isPlaying = this->simulator->getIsPlaying();
this->simulator->stop();
QString msg = tr("Please, don't forget to save your changes.\n\nDo you want to exit?");
QMessageBox::StandardButton btn = QMessageBox::question(this, tr("Exit"), msg);
if (btn == QMessageBox::Yes)
{
event->accept();
}
else
{
event->ignore();
if (isPlaying)
{
this->simulator->play();
}
}
}
void MainWindow::handleCompiledError()
{
this->actCompile->setDisabled(false);
}
void MainWindow::handleBuildCode()
{
std::vector<std::shared_ptr<CompilerError>> errors = this->compiler->getErrors();
if (errors.empty())
{
lstResult->addItem(QString(tr("Compiled successfully")));
}
else
{
for (const std::shared_ptr<CompilerError> e : errors)
{
QString msg;
msg.append("Line ").append(QString::number(e->row));
msg.append(": ")
.append(QString(e->message.c_str()));
lstResult->addItem(msg);
}
}
this->actCompile->setDisabled(false);
return;
}
void MainWindow::handleCompiled()
{
dockResult->raise();
if (compiler->getErrors().empty())
{
this->actPlay->setEnabled(true);
this->actStep->setEnabled(true);
}
else
{
this->actPlay->setEnabled(false);
this->actStep->setEnabled(false);
}
}
void MainWindow::handleCursorPosChanged(unsigned line)
{
statusLabel->setText("Line: " + QString::number(line) + "\t");
}
void MainWindow::handleEvalCommand(const QString &msg)
{
this->lstResult->addItem(msg);
}
| 34.854749 | 131 | 0.665064 | [
"vector"
] |
c3b3be5cd2adc4088e9ecd430f15c3160699246a | 5,697 | cpp | C++ | src/projects/geometry_shader_normal_viewer/src/main.cpp | computersarecool/opengl_examples | 658196529420dcdded5436ef4a118cb4a3bc9b2c | [
"MIT"
] | 8 | 2020-01-09T13:19:12.000Z | 2022-02-10T02:44:21.000Z | src/projects/geometry_shader_normal_viewer/src/main.cpp | computersarecool/opengl_examples | 658196529420dcdded5436ef4a118cb4a3bc9b2c | [
"MIT"
] | null | null | null | src/projects/geometry_shader_normal_viewer/src/main.cpp | computersarecool/opengl_examples | 658196529420dcdded5436ef4a118cb4a3bc9b2c | [
"MIT"
] | 1 | 2021-03-16T03:54:39.000Z | 2021-03-16T03:54:39.000Z | // This is a cube geometry shader which converts faces to lines to show normals
#include <memory>
#include <vector>
#include "glm/glm/gtc/matrix_transform.hpp"
#include "base_app.h"
#include "glsl_program.h"
#include "camera.h"
// Cube
const GLfloat cube_vertices[] {
// Positions // Normals
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f
};
class GeometryShaderExample : public Application
{
private:
GLuint m_vao{ 0 };
GLuint m_vbo{ 0 };
glm::mat4 m_model_matrix{ glm::mat4{1.0f } };
Camera m_camera{ glm::vec3{0, 0, 5} };
const GLuint m_num_vertices{ 36 };
const GLfloat m_normal_length{ 0.5f};
const glm::vec3 m_world_up{ glm::vec3{ 0, 1, 0 } };
const GLfloat m_rotation_rate{ 0.001f };
const std::vector<GLfloat> m_clear_color{ 0.2f, 0.0f, 0.2f, 1.0f };
std::unique_ptr<GlslProgram> m_shader;
std::unique_ptr<GlslProgram> m_normal_shader;
void set_info() override
{
Application::set_info();
m_info.title = "Geometry shader example";
}
void setup() override
{
// Create shaders
m_shader = std::make_unique<GlslProgram>(GlslProgram::Format().vertex("../assets/shaders/cube.vert").fragment("../assets/shaders/cube.frag"));
m_normal_shader = std::make_unique<GlslProgram>(GlslProgram::Format().vertex("../assets/shaders/normal_viewer.vert").fragment("../assets/shaders/normal_viewer.frag").geometry("../assets/shaders/normal_viewer.geom"));
// Cube position vertex attribute parameters
const GLuint elements_per_face{ 6 };
const GLuint position_index{ 0 };
const GLuint position_size{ 3 };
const GLenum position_type{ GL_FLOAT };
const GLboolean position_normalize{ GL_FALSE };
const GLuint position_offset_in_buffer{ 0 };
// Normal position vertex attribute parameters
const GLuint normal_index{ 1 };
const GLuint normal_size{ 3 };
const GLenum normal_type{ GL_FLOAT };
const GLboolean normal_normalize{ GL_FALSE };
const GLuint normal_offset_in_buffer{ sizeof(GLfloat) * position_size };
// Cube vertex buffer attributes
const GLuint binding_index{ 0 };
const GLuint offset{ 0 };
const GLuint element_stride{ sizeof(GLfloat) * elements_per_face };
// Setup the cube VBO and its data store
const GLuint flags{ 0 };
glCreateBuffers(1, &m_vbo);
glNamedBufferStorage(m_vbo, sizeof(cube_vertices), cube_vertices, flags);
// Setup and bind a VAO
glCreateVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
// Set attributes in the VAO
glEnableVertexArrayAttrib(m_vao, position_index);
glEnableVertexArrayAttrib(m_vao, normal_index);
glVertexArrayAttribFormat(m_vao, position_index, position_size, position_type, position_normalize, position_offset_in_buffer);
glVertexArrayAttribFormat(m_vao, normal_index, normal_size, normal_type, normal_normalize, normal_offset_in_buffer);
glVertexArrayAttribBinding(m_vao, position_index, binding_index);
glVertexArrayAttribBinding(m_vao, normal_index, binding_index);
glVertexArrayVertexBuffer(m_vao, binding_index, m_vbo, offset, element_stride);
// Turn on depth test
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
void render(double current_time) override
{
// Set OpenGL state
glViewport(0, 0, m_info.window_width, m_info.window_height);
glClearBufferfv(GL_COLOR, 0, m_clear_color.data());
glClearBufferfi(GL_DEPTH_STENCIL, 0, 1.0f, 0);
// Update uniforms
m_model_matrix = glm::rotate(m_model_matrix, m_rotation_rate, m_world_up);
// Set uniforms for normals
m_normal_shader->use();
m_normal_shader->uniform("u_model_view_matrix", m_camera.get_view_matrix() * m_model_matrix);
m_normal_shader->uniform("u_projection_matrix", m_camera.get_proj_matrix());
m_normal_shader->uniform("u_normal_length", m_normal_length);
glDrawArrays(GL_TRIANGLES, 0, m_num_vertices);
// Set uniforms for faces
m_shader->use();
m_shader->uniform("u_model_view_matrix", m_camera.get_view_matrix() * m_model_matrix);
m_shader->uniform("u_projection_matrix", m_camera.get_proj_matrix());
glDrawArrays(GL_TRIANGLES, 0, m_num_vertices);
};
};
int main(int argc, char* argv[])
{
std::unique_ptr<Application> app{ new GeometryShaderExample };
app->run();
} | 34.113772 | 218 | 0.654555 | [
"geometry",
"render",
"vector"
] |
c3b6658cc2c44cfaa361af6799e6e373019cb2a1 | 3,335 | hpp | C++ | include/MIPTPFrame.hpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | 1 | 2018-07-29T17:53:50.000Z | 2018-07-29T17:53:50.000Z | include/MIPTPFrame.hpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | include/MIPTPFrame.hpp | SaivNator/MIPTP_cpp | c830b875c47cad742f0e0ed07649e9322865b02e | [
"MIT"
] | null | null | null | //MIPTPFrame.hpp
//Author: Sivert Andresen Cubedo
#pragma once
#ifndef MIPTPFrame_HEADER
#define MIPTPFrame_HEADER
//C++
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <utility>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <bitset>
//Local
#include "AddressTypes.hpp"
/*
packet layout:
header is always 48 bits long.
<packet type : 2 bits> <padding bits : 2 bits> <dest port : 14 bits> <source port: 14 bits> <packet sequence number : 16 bits> <data>
packet type :
Can be :
00 : connect request
01 : connect reply
10 : data transmission
11 : sack
*/
class MIPTPFrame
{
public:
/*
const
*/
static const std::size_t FRAME_HEADER_SIZE = 6; //in byte
static const std::size_t FRAME_MAX_SIZE = 1496; //in byte
static const std::size_t FRAME_MAX_MSG_SIZE = FRAME_MAX_SIZE - FRAME_HEADER_SIZE; //in byte
enum Packet_Type
{
request = 0b00,
reply = 0b01,
data = 0b10,
sack = 0b11
};
/*
Constructor.
*/
MIPTPFrame();
/*
Constructor.
Parameters:
buf
size
*/
MIPTPFrame(char* buf, std::size_t size);
/*
Set packet type.
Parameters:
type int where the first 2 bits are relevant
Return:
void
*/
void setType(int type);
/*
Set padding bits.
Parameters:
padding int where the first 2 bits are relevant
Return:
void
*/
void setPadding(int padding);
/*
Set dest port.
Parameters:
dest
Return:
void
*/
void setDest(Port dest);
/*
Set source port.
Parameters:
source
Return:
void
*/
void setSource(Port source);
/*
Set sequence number.
Parameters:
num num where the first 16 bits are relevant
Return:
void
*/
void setSequenceNumber(int seq);
/*
Set msg size.
Parameters:
size
Return:
void
*/
void setMsgSize(std::size_t size);
/*
Set msg.
Parameters:
Return:
void
*/
void setMsg(const char* buf, std::size_t size);
/*
Set total size of frame.
Parameters:
size
Return:
void
*/
void setSize(std::size_t size);
/*
Get type.
Parameters:
Return:
type int where the 2 first bits are relevant
*/
int getType();
/*
Get padding.
Parameters:
Return:
padding int where the first 2 bits are relevant
*/
int getPadding();
/*
Get dest port.
Parameters:
Return:
dest
*/
Port getDest();
/*
Get source port.
Parameters:
Return:
source
*/
Port getSource();
/*
Get sequence number.
Parameters:
Return:
sequence number
*/
int getSequenceNumber();
/*
Get msg size.
Parameters:
Return:
size in bytes
*/
std::size_t getMsgSize();
/*
Get msg.
Parameters:
Return:
msg as raw pointer to msg
*/
char* getMsg();
/*
Get total size of frame (in bytes).
Parameters:
Return:
size
*/
std::size_t getSize();
/*
Get raw buffer.
Parameters:
Return:
pointer to raw data of frame
*/
char* getData();
/*
Exchanges underlying container with other frame.
Parameters:
other ref to frame the swap
Return:
void
*/
void swap(MIPTPFrame & other);
/*
Calculate padding.
Parameters:
size
Return
padding int where the first 2 bits are relevant
*/
static int calcPadding(std::size_t size);
/*
To string (for testing).
Parameters:
Return:
string
*/
std::string toString();
private:
std::vector<char> m_data; //must be 6 byte or bigger
};
#endif // !MIPTPFrame_HEADER
| 14.191489 | 134 | 0.668066 | [
"vector"
] |
c3b685539a5be5df99c48e85dfa40e896288d3d3 | 1,800 | cpp | C++ | Train/Sheet/Sheet-B/base/40-60/41-50/43.Strategic Defense Initiative.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Train/Sheet/Sheet-B/base/40-60/41-50/43.Strategic Defense Initiative.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Train/Sheet/Sheet-B/base/40-60/41-50/43.Strategic Defense Initiative.cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void file() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
}
/* Finds longest strictly increasing subsequence. O(n log k) algorithm. */
void find_lis(vector<int> &a, vector<int> &b) {
vector<int> p(a.size());
int u, v;
if (a.empty())
return;
b.push_back(0);
for (size_t i = 1; i < a.size(); i++) {
// If next element a[i] is greater than last element of
// current longest subsequence a[b.back()], just push it at back of "b" and continue
if (a[b.back()] < a[i]) {
p[i] = b.back();
b.push_back(i);
continue;
}
// Binary search to find the smallest element referenced by b which is just bigger than a[i]
// Note : Binary search is performed on b (and not a).
// Size of b is always <=k and hence contributes O(log k) to complexity.
for (u = 0, v = b.size() - 1; u < v;) {
int c = (u + v) / 2;
if (a[b[c]] < a[i])
u = c + 1;
else
v = c;
}
// Update b if new value is smaller then previously referenced value
if (a[i] < a[b[u]]) {
if (u > 0)
p[i] = b[u - 1];
b[u] = i;
}
}
for (u = b.size(), v = b.back(); u--; v = p[v])
b[u] = v;
}
int main() {
file();
vector<int> v;
int t, x;
scanf("%d\n\n", &t);
while (t--) {
v.clear();
string s;
while (getline(cin, s) && s != "") {
stringstream ss(s);
ss >> x;
v.push_back(x);
}
// int a[] = { 1, 9, 3, 8, 11, 4, 5, 6, 4, 19, 7, 1, 7 };
// vector<int> seq(a, a + sizeof(a) / sizeof(a[0])); // seq : Input Vector
vector<int> lis; // lis : Vector containing indexes of longest subsequence
find_lis(v, lis);
printf("Max hits: %d\n", (int)(lis).size());
//Printing actual output
for (size_t i = 0; i < lis.size(); i++)
printf("%d\n", v[lis[i]]);
if (t)
printf("\n");
}
return 0;
}
| 22.78481 | 94 | 0.551111 | [
"vector"
] |
c3b933fc38391b2a5915f9bed395f16a4e10eff4 | 539 | cpp | C++ | Source/Engine/ING/Source/ING/Scripting/Method/OuternalMethod/OuternalMethod.cpp | ING-Game-Devs/ing-engine | 7379e96433f47c005fb677cb303686e628d41bfe | [
"MIT"
] | 12 | 2022-01-17T13:25:03.000Z | 2022-03-19T08:53:56.000Z | Source/Engine/ING/Source/ING/Scripting/Method/OuternalMethod/OuternalMethod.cpp | ING-Game-Devs/ing | 829611b16a324d1ba0f8fbbd5fdc418e2b9d6aa4 | [
"MIT"
] | null | null | null | Source/Engine/ING/Source/ING/Scripting/Method/OuternalMethod/OuternalMethod.cpp | ING-Game-Devs/ing | 829611b16a324d1ba0f8fbbd5fdc418e2b9d6aa4 | [
"MIT"
] | 7 | 2022-01-21T03:50:09.000Z | 2022-03-25T14:30:29.000Z |
/**
* Include Header
*/
#include "OuternalMethod.h"
namespace ING {
namespace Scripting {
/**
* Constructors And Destructor
*/
IOuternalMethod::IOuternalMethod(IContext* context, IMethodContainer* container) :
IMethod(context, container)
{
}
IOuternalMethod::~IOuternalMethod()
{
}
/**
* Release Method
*/
void IOuternalMethod::Release() {
IMethod::Release();
}
/**
* Methods
*/
void* IOuternalMethod::Execute(void* object, void** params) {
return 0;
}
}
} | 9.625 | 84 | 0.604824 | [
"object"
] |
c3bd4d759c47828da9990c4d668d3e4f0589340e | 5,018 | cpp | C++ | keychain_win/secmodlib/src/SecureModuleWrapper.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 29 | 2018-03-21T09:21:18.000Z | 2020-09-22T16:31:03.000Z | keychain_win/secmodlib/src/SecureModuleWrapper.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 119 | 2018-03-16T14:02:04.000Z | 2019-04-16T21:16:32.000Z | keychain_win/secmodlib/src/SecureModuleWrapper.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 3 | 2018-03-21T15:00:16.000Z | 2019-12-25T09:03:58.000Z |
#include "SecureModuleWrapper.h"
#include "NamedPipeServer.h"
#include <keychain_lib/secmod_parser_cmd.hpp>
#include <sddl.h>
#include <algorithm>
#pragma comment(lib, "advapi32.lib")
namespace sm_cmd = keychain_app::secmod_commands;
SecurityManager _secman;
SecureModuleWrapper::~SecureModuleWrapper()
{
//TODO: need implementation
}
std::string SecureModuleWrapper::exec_cmd(const std::string& json_cmd) const
{
sm_cmd::secmod_parser_f parser;
auto etype = parser(json_cmd);
int unlock_time = 0;
switch (etype)
{
case sm_cmd::events_te::sign_trx:
{
auto cmd = parser.params<sm_cmd::events_te::sign_trx>();
unlock_time = cmd.unlock_time;
}
break;
case sm_cmd::events_te::unlock:
{
auto cmd = parser.params<sm_cmd::events_te::unlock>();
unlock_time = cmd.unlock_time;
}
break;
}
keychain_app::byte_seq_t result_pass;
result_pass.reserve(512);
HANDLE hPipe;
char buffer[1024];
DWORD dwRead;
#if 0
HANDLE transactionPipe;
auto& log = logger_singleton::instance();
BOOST_LOG_SEV(log.lg, info) << "Send to pipe:"+ json_cmd;
//initializing security attributes
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;
//creating DACL
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
L"D:(D;OICI;GA;;;BG)(D;OICI;GA;;;AN)(A;OICI;GRGWGX;;;AU)(A;OICI;GA;;;BA)",
SDDL_REVISION_1,
&(sa.lpSecurityDescriptor),
NULL
))
FC_LIGHT_THROW_EXCEPTION(fc_light::password_input_exception,
"Can't receive password: ConvertStringSecurityDescriptorToSecurityDescriptor error");
transactionPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\transpipe"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
9000 * 16,
9000 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
&sa);
DWORD writtenSize;
DWORD lastErrror;
DisconnectNamedPipe(transactionPipe);
_secman.CreateSecureDesktop(unlock_time);
while (transactionPipe != INVALID_HANDLE_VALUE) {
DWORD dwWritten;
if (ConnectNamedPipe(transactionPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
std::string trans = json_cmd;
BOOST_LOG_SEV(log.lg, info) << "Send to pipe: (hardcode)" + trans;
trans.push_back('\0');
WriteFile(transactionPipe,
trans.c_str(),
trans.length(), // = length of string + terminating '\0' !!!
&dwWritten,
NULL);
BOOST_LOG_SEV(log.lg, info) << "Error code: " << GetLastError();
CloseHandle(transactionPipe);
DisconnectNamedPipe(transactionPipe);
break;
}
//lastErrror = GetLastError();
//throw std::runtime_error("Error: can't write pipe transaction");
}
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\keychainpass"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
1,
1024 * 16,
1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
&sa);
std::vector<wchar_t> password(256, 0x00);
if (hPipe == INVALID_HANDLE_VALUE)
FC_LIGHT_THROW_EXCEPTION(fc_light::password_input_exception,"Can't receive password: INVALID_HANDLE_VALUE");
constexpr int MAX_WAIT_TIME = 1000;
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
buffer[dwRead] = '\0';
LPWSTR pDescrOut = NULL;
DATA_BLOB DataOut;
DataOut.cbData = sizeof(buffer) - 1;
DataOut.pbData = (BYTE*)buffer;
DATA_BLOB DataVerify;
if (CryptUnprotectData(
&DataOut,
&pDescrOut,
NULL, // Optional entropy
NULL, // Reserved
NULL, // Optional PromptStruct
CRYPTPROTECT_LOCAL_MACHINE,
&DataVerify))
{
//here is decrypted password
//printf("The decrypted data is: %s\n", DataVerify.pbData);
result_pass.resize(DataVerify.cbData);
std::strncpy(result_pass.data(), (char*)DataVerify.pbData, result_pass.size());
std::string resPass(result_pass.data());
if (resPass.find("cancel_pass_enterance") != -1) {
result_pass.resize(0);
}
//printf("The description of the data was: %S\n", pDescrOut);
}
else {
DWORD lastError = GetLastError();
}
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
}
#endif
std::string result;
result_pass = { 'b', 'l', 'a', 'n', 'k' };
sm_cmd::secmod_resonse_common response;
if (result_pass.empty())
{
response.etype = sm_cmd::response_te::null;
result = fc_light::json::to_pretty_string(response);
}
else
{
response.etype = sm_cmd::response_te::password;
response.params = result_pass;
result = fc_light::json::to_pretty_string(response);
}
return result;
} | 30.228916 | 168 | 0.662615 | [
"vector"
] |
c3c1d4f52c057a755992b0e2dd0e92b910ad19e2 | 2,029 | cpp | C++ | problems/uva/uva988.cpp | phogbinh/cp | 41a86550e14571c8f54bbec9579060647e77209c | [
"MIT"
] | null | null | null | problems/uva/uva988.cpp | phogbinh/cp | 41a86550e14571c8f54bbec9579060647e77209c | [
"MIT"
] | null | null | null | problems/uva/uva988.cpp | phogbinh/cp | 41a86550e14571c8f54bbec9579060647e77209c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
enum {UNVISITED = 0, VISITED};
#define LOCAL
#define MAX_V 100050
#define DUMP_INT 0
int V;
vector<vii> AL; // [A]djacency [L]ist
vi topoR; // [t]opological order [R]eversed
int visited[MAX_V];
int cnt[MAX_V];
void dfs(int u)
{
visited[u] = VISITED;
for (int i = 0; i < (int)AL[u].size(); ++i)
{
ii vw = AL[u][i];
if (visited[ vw.first ] == UNVISITED) dfs(vw.first);
}
topoR.push_back( u );
}
void work()
{
topoR.clear();
memset(visited, UNVISITED, sizeof visited);
memset(cnt, 0, sizeof cnt);
AL.assign( V, vii() );
for (int u = 0; u < V; ++u)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i)
{
int v;
scanf("%d", &v);
AL[ u ].push_back( ii(v, DUMP_INT) );
}
}
// for (int u = 0; u < V; ++u)
// {
// printf("u: %d, #edges: %d\n", u, (int)AL[u].size());
// for (int i = 0; i < (int)AL[u].size(); ++i)
// {
// ii vw = AL[u][i];
// printf("edge - v: %d, weight: %d\n", vw.first, vw.second);
// }
// }
dfs(0);
// printf("Topo: ");
// for (int i = (int)topoR.size() - 1; i >= 0; --i)
// {
// printf("%d ", topoR[i]);
// }
// printf("\n");
cnt[0] = 1;
for (int i = (int)topoR.size() - 1; i >= 0; --i)
{
int u = topoR[i];
for (int i = 0; i < (int)AL[u].size(); ++i)
{
ii vw = AL[u][i];
cnt[ vw.first ] += cnt[u];
}
}
int ret = 0;
for (int u = 0; u < V; ++u)
{
if (AL[u].size()==0) ret += cnt[u];
}
printf("%d\n", ret);
}
int main()
{
#ifdef LOCAL
freopen("in3", "r", stdin);
freopen("myout", "w", stdout);
#endif
int count = 0;
while (scanf("%d", &V) != EOF)
{
if (count != 0) printf("\n");
work();
++count;
}
return 0;
}
| 20.29 | 72 | 0.437161 | [
"vector"
] |
c3cdff46355cb57fc7756f3810de23636d521ee8 | 387 | cpp | C++ | samples/use_precompiled_headers/src/s0.cpp | Dylan95/dcg_build_system | 98febea3fdeef21be5847d5573032314d02ae843 | [
"MIT"
] | 1 | 2016-11-04T17:16:20.000Z | 2016-11-04T17:16:20.000Z | samples/use_precompiled_headers/src/s0.cpp | Dylan95/dcg_build_system | 98febea3fdeef21be5847d5573032314d02ae843 | [
"MIT"
] | null | null | null | samples/use_precompiled_headers/src/s0.cpp | Dylan95/dcg_build_system | 98febea3fdeef21be5847d5573032314d02ae843 | [
"MIT"
] | null | null | null | //a precompiled header that is meant to be used specifically for s0.cpp
#include "s0_pch.hpp"
//this was already included in the precompiled header.
//including it again won't cause any problem. the include gaurd will have already
//been defined, so including it again will have no effect whatsoever.
#include <vector>
using namespace std;
int main(){
vector<int> v;
return 0;
}
| 22.764706 | 82 | 0.751938 | [
"vector"
] |
c3d03d27f58731549c14e9107eba2d61d92b416a | 8,543 | cc | C++ | osp/impl/quic/quic_connection_factory_impl.cc | gtalis/openscreen | 9b28b9695df98d310c2271eaa65d20cc6d224203 | [
"BSD-3-Clause"
] | 1 | 2020-09-22T05:59:36.000Z | 2020-09-22T05:59:36.000Z | osp/impl/quic/quic_connection_factory_impl.cc | gtalis/openscreen | 9b28b9695df98d310c2271eaa65d20cc6d224203 | [
"BSD-3-Clause"
] | null | null | null | osp/impl/quic/quic_connection_factory_impl.cc | gtalis/openscreen | 9b28b9695df98d310c2271eaa65d20cc6d224203 | [
"BSD-3-Clause"
] | 1 | 2022-02-03T11:05:44.000Z | 2022-02-03T11:05:44.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "osp/impl/quic/quic_connection_factory_impl.h"
#include <algorithm>
#include <memory>
#include "osp/impl/quic/quic_connection_impl.h"
#include "platform/api/task_runner.h"
#include "platform/api/time.h"
#include "platform/base/error.h"
#include "third_party/chromium_quic/src/base/location.h"
#include "third_party/chromium_quic/src/base/task_runner.h"
#include "third_party/chromium_quic/src/net/third_party/quic/core/quic_constants.h"
#include "third_party/chromium_quic/src/net/third_party/quic/platform/impl/quic_chromium_clock.h"
#include "util/osp_logging.h"
#include "util/trace_logging.h"
namespace openscreen {
namespace osp {
class QuicTaskRunner final : public ::base::TaskRunner {
public:
explicit QuicTaskRunner(openscreen::TaskRunner* task_runner);
~QuicTaskRunner() override;
void RunTasks();
// base::TaskRunner overrides.
bool PostDelayedTask(const ::base::Location& whence,
::base::OnceClosure task,
::base::TimeDelta delay) override;
bool RunsTasksInCurrentSequence() const override;
private:
openscreen::TaskRunner* const task_runner_;
};
QuicTaskRunner::QuicTaskRunner(openscreen::TaskRunner* task_runner)
: task_runner_(task_runner) {}
QuicTaskRunner::~QuicTaskRunner() = default;
void QuicTaskRunner::RunTasks() {}
bool QuicTaskRunner::PostDelayedTask(const ::base::Location& whence,
::base::OnceClosure task,
::base::TimeDelta delay) {
Clock::duration wait = Clock::duration(delay.InMilliseconds());
task_runner_->PostTaskWithDelay(
[closure = std::move(task)]() mutable { std::move(closure).Run(); },
wait);
return true;
}
bool QuicTaskRunner::RunsTasksInCurrentSequence() const {
return true;
}
QuicConnectionFactoryImpl::QuicConnectionFactoryImpl(TaskRunner* task_runner)
: task_runner_(task_runner) {
quic_task_runner_ = ::base::MakeRefCounted<QuicTaskRunner>(task_runner);
alarm_factory_ = std::make_unique<::net::QuicChromiumAlarmFactory>(
quic_task_runner_.get(), ::quic::QuicChromiumClock::GetInstance());
::quic::QuartcFactoryConfig factory_config;
factory_config.alarm_factory = alarm_factory_.get();
factory_config.clock = ::quic::QuicChromiumClock::GetInstance();
quartc_factory_ = std::make_unique<::quic::QuartcFactory>(factory_config);
}
QuicConnectionFactoryImpl::~QuicConnectionFactoryImpl() {
OSP_DCHECK(connections_.empty());
}
void QuicConnectionFactoryImpl::SetServerDelegate(
ServerDelegate* delegate,
const std::vector<IPEndpoint>& endpoints) {
OSP_DCHECK(!delegate != !server_delegate_);
server_delegate_ = delegate;
sockets_.reserve(sockets_.size() + endpoints.size());
for (const auto& endpoint : endpoints) {
// TODO(mfoltz): Need to notify the caller and/or ServerDelegate if socket
// create/bind errors occur. Maybe return an Error immediately, and undo
// partial progress (i.e. "unwatch" all the sockets and call
// sockets_.clear() to close the sockets)?
auto create_result = UdpSocket::Create(task_runner_, this, endpoint);
if (!create_result) {
OSP_LOG_ERROR << "failed to create socket (for " << endpoint
<< "): " << create_result.error().message();
continue;
}
std::unique_ptr<UdpSocket> server_socket = std::move(create_result.value());
server_socket->Bind();
sockets_.emplace_back(std::move(server_socket));
}
}
void QuicConnectionFactoryImpl::OnRead(UdpSocket* socket,
ErrorOr<UdpPacket> packet_or_error) {
TRACE_SCOPED(TraceCategory::kQuic, "QuicConnectionFactoryImpl::OnRead");
if (packet_or_error.is_error()) {
return;
}
UdpPacket packet = std::move(packet_or_error.value());
// Ensure that |packet.socket| is one of the instances owned by
// QuicConnectionFactoryImpl.
auto packet_ptr = &packet;
OSP_DCHECK(std::find_if(sockets_.begin(), sockets_.end(),
[packet_ptr](const std::unique_ptr<UdpSocket>& s) {
return s.get() == packet_ptr->socket();
}) != sockets_.end());
// TODO(btolsch): We will need to rethink this both for ICE and connection
// migration support.
auto conn_it = connections_.find(packet.source());
if (conn_it == connections_.end()) {
if (server_delegate_) {
OSP_VLOG << __func__ << ": spawning connection from " << packet.source();
auto transport =
std::make_unique<UdpTransport>(packet.socket(), packet.source());
::quic::QuartcSessionConfig session_config;
session_config.perspective = ::quic::Perspective::IS_SERVER;
session_config.packet_transport = transport.get();
auto result = std::make_unique<QuicConnectionImpl>(
this, server_delegate_->NextConnectionDelegate(packet.source()),
std::move(transport),
quartc_factory_->CreateQuartcSession(session_config));
auto* result_ptr = result.get();
connections_.emplace(packet.source(),
OpenConnection{result_ptr, packet.socket()});
server_delegate_->OnIncomingConnection(std::move(result));
result_ptr->OnRead(socket, std::move(packet));
}
} else {
OSP_VLOG << __func__ << ": data for existing connection from "
<< packet.source();
conn_it->second.connection->OnRead(socket, std::move(packet));
}
}
std::unique_ptr<QuicConnection> QuicConnectionFactoryImpl::Connect(
const IPEndpoint& endpoint,
QuicConnection::Delegate* connection_delegate) {
auto create_result = UdpSocket::Create(task_runner_, this, endpoint);
if (!create_result) {
OSP_LOG_ERROR << "failed to create socket: "
<< create_result.error().message();
// TODO(mfoltz): This method should return ErrorOr<uni_ptr<QuicConnection>>.
return nullptr;
}
std::unique_ptr<UdpSocket> socket = std::move(create_result.value());
auto transport = std::make_unique<UdpTransport>(socket.get(), endpoint);
::quic::QuartcSessionConfig session_config;
session_config.perspective = ::quic::Perspective::IS_CLIENT;
// TODO(btolsch): Proper server id. Does this go in the QUIC server name
// parameter?
session_config.unique_remote_server_id = "turtle";
session_config.packet_transport = transport.get();
auto result = std::make_unique<QuicConnectionImpl>(
this, connection_delegate, std::move(transport),
quartc_factory_->CreateQuartcSession(session_config));
// TODO(btolsch): This presents a problem for multihomed receivers, which may
// register as a different endpoint in their response. I think QUIC is
// already tolerant of this via connection IDs but this hasn't been tested
// (and even so, those aren't necessarily stable either).
connections_.emplace(endpoint, OpenConnection{result.get(), socket.get()});
sockets_.emplace_back(std::move(socket));
return result;
}
void QuicConnectionFactoryImpl::OnConnectionClosed(QuicConnection* connection) {
auto entry = std::find_if(
connections_.begin(), connections_.end(),
[connection](const decltype(connections_)::value_type& entry) {
return entry.second.connection == connection;
});
OSP_DCHECK(entry != connections_.end());
UdpSocket* const socket = entry->second.socket;
connections_.erase(entry);
// If none of the remaining |connections_| reference the socket, close/destroy
// it.
if (std::find_if(connections_.begin(), connections_.end(),
[socket](const decltype(connections_)::value_type& entry) {
return entry.second.socket == socket;
}) == connections_.end()) {
auto socket_it =
std::find_if(sockets_.begin(), sockets_.end(),
[socket](const std::unique_ptr<UdpSocket>& s) {
return s.get() == socket;
});
OSP_DCHECK(socket_it != sockets_.end());
sockets_.erase(socket_it);
}
}
void QuicConnectionFactoryImpl::OnError(UdpSocket* socket, Error error) {
OSP_LOG_ERROR << "failed to configure socket " << error.message();
}
void QuicConnectionFactoryImpl::OnSendError(UdpSocket* socket, Error error) {
// TODO(crbug.com/openscreen/67): Implement this method.
OSP_UNIMPLEMENTED();
}
} // namespace osp
} // namespace openscreen
| 39.009132 | 97 | 0.692614 | [
"vector"
] |
c3d4f7d8ac2c3a817e85c9ba31fb334dca9c1aa6 | 1,225 | cpp | C++ | tests/test_mpi.cpp | kingang1986/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 312 | 2015-03-16T15:29:38.000Z | 2021-09-16T22:48:41.000Z | tests/test_mpi.cpp | zuiwufenghua/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 19 | 2015-03-17T16:20:19.000Z | 2015-10-03T03:34:09.000Z | tests/test_mpi.cpp | zuiwufenghua/purine2 | e53447da173e83fb62bae8cf50bde17f75723203 | [
"BSD-2-Clause"
] | 108 | 2015-03-16T07:07:30.000Z | 2021-08-22T07:32:13.000Z | // Copyright Lin Min 2014
#include "catch/catch.hpp"
#include <vector>
#include "operations/include/random.hpp"
#include "operations/operation.hpp"
#include "operations/include/mpi.hpp"
#include "dispatch/op_template.hpp"
#include "dispatch/graph_template.hpp"
#include "dispatch/runnable.hpp"
#include "dispatch/blob.hpp"
using namespace purine;
using namespace std;
typedef vector<Blob*> B;
TEST_CASE("TestMPI", "[MPI][Thread]") {
Runnable g;
SECTION("Isend and Irecv") {
int rank = current_rank();
Blob* src = g.create("src", 0, -1, {1, 3, 10, 10});
Blob* dest = g.create("dest", 1, -1, {1, 3, 10, 10});
Op<Constant>* c = g.create<Constant>("constant", 0, -1, "main",
Constant::param_tuple(1.));
Op<Isend>* send = g.create<Isend>("send", 0, -1, "main",
Isend::param_tuple(0, dest->rank()));
Op<Irecv>* recv = g.create<Irecv>("recv", 1, -1, "main",
Irecv::param_tuple(0, src->rank()));
// connect
*c >> B{ src };
B{ src } >> *send;
*recv >> B{ dest };
// run
g.run();
Tensor* t = dest->tensor();
if (current_rank() == 1) {
for (int i = 0; i < t->size().count(); ++i) {
REQUIRE(t->cpu_data()[i] == 1.);
}
}
}
}
| 28.488372 | 67 | 0.582857 | [
"vector"
] |
c3d5f1258b20ddc16d83a19f34466b9d3729c7fc | 3,175 | hh | C++ | Original Geant4 code/include/ExN03DetectorConstruction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | null | null | null | Original Geant4 code/include/ExN03DetectorConstruction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | null | null | null | Original Geant4 code/include/ExN03DetectorConstruction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | 1 | 2018-04-09T00:10:04.000Z | 2018-04-09T00:10:04.000Z | // This code implementation is the intellectual property of
// the GEANT4 collaboration.
//
// By copying, distributing or modifying the Program (or any work
// based on the Program) you indicate your acceptance of this statement,
// and all its terms.
//
// $Id: ExN03DetectorConstruction.hh,v 1.1.10.1 1999/12/07 20:47:28 gunter Exp $
// GEANT4 tag $Name: geant4-01-00 $
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
#ifndef ExN03DetectorConstruction_h
#define ExN03DetectorConstruction_h 1
#include "G4VTouchable.hh"
#include "G4TouchableHistory.hh"
#include "G4VUserDetectorConstruction.hh"
#include "globals.hh"
class G4Box;
class G4LogicalVolume;
class G4VPhysicalVolume;
class G4Material;
class ExN03DetectorMessenger;
class ExN03PixelSD;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
class ExN03DetectorConstruction : public G4VUserDetectorConstruction
{
public:
ExN03DetectorConstruction();
~ExN03DetectorConstruction();
public:
void PrintPixelParameters();
void SetPixelThickness(G4double);
void SetPixelMaterial(G4String);
void SetCeramicMaterial(G4String);
G4VPhysicalVolume* Construct();
void UpdateGeometry();
public:
// void PrintCalorParameters();
G4double GetWorldSizeX() {return WorldSizeX;};
G4double GetWorldSizeY() {return WorldSizeY;};
G4double GetWorldSizeZ() {return WorldSizeZ;};
G4double GetMatrixThickness() {return MatrixThickness;};
G4double GetMatrixSizeY() {return MatrixSizeY;};
G4double GetMatrixSizeX() {return MatrixSizeX;};
G4double GetPixelThickness() {return PixelThickness;};
G4double GetPixelSizeY() {return PixelSizeY;};
G4double GetPixelSizeX() {return PixelSizeX;};
const G4VPhysicalVolume* GetphysiWorld() {return physiWorld;};
const G4VPhysicalVolume* GetphysiMatrix() {return physiMatrix;};
private:
#include "ExN03DetectorParameterDef.hh"
G4Box* solidWorld; //pointer to the solid World
G4LogicalVolume* logicWorld; //pointer to the logical World
G4VPhysicalVolume* physiWorld; //pointer to the physical World
G4Box* solidMatrix; //pointer to the solid Matrix
G4LogicalVolume* logicMatrix; //pointer to the logical Matrix
G4VPhysicalVolume* physiMatrix; //pointer to the physical Matrix
G4Box* solidPixel; //pointer to the solid Pixel
G4LogicalVolume* logicPixel;
G4VPhysicalVolume* physiPixel;
G4Material* PixelMaterial;
G4Material* CeramicMaterial;
G4Material* defaultMaterial;
ExN03DetectorMessenger* detectorMessenger; //pointer to the Messenger
ExN03PixelSD* pixelSD; //pointer to the sensitive detector
private:
void DefineMaterials();
// void ComputePixelParameters();
G4VPhysicalVolume* ConstructPixel();
};
#endif
| 29.12844 | 80 | 0.672126 | [
"solid"
] |
c3d725481f7e55bb0670f58a56796e08e51729b7 | 173 | cpp | C++ | rotate_array.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | rotate_array.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | 1 | 2020-12-17T07:54:03.000Z | 2020-12-17T08:00:22.000Z | rotate_array.cpp | spencercjh/sync-leetcode-today-problem-cpp-example | 178a974e5848e3a620f4565170b459d50ecfdd6b | [
"Apache-2.0"
] | null | null | null | /**
* https://leetcode-cn.com/problems/rotate-array/
*
* @author spencercjh
*/
class RotateArray {
public:
void rotate(vector<int>& nums, int k) {
}
}
| 13.307692 | 49 | 0.589595 | [
"vector"
] |
c3d80f3a32d15d5d92492365fe48693dffeb4caa | 1,359 | cc | C++ | Tools/GenCC.cc | zhmz90/Lan | d7bb1b38ecb5a082276efaafdadca8d9700fbc27 | [
"MIT"
] | null | null | null | Tools/GenCC.cc | zhmz90/Lan | d7bb1b38ecb5a082276efaafdadca8d9700fbc27 | [
"MIT"
] | null | null | null | Tools/GenCC.cc | zhmz90/Lan | d7bb1b38ecb5a082276efaafdadca8d9700fbc27 | [
"MIT"
] | null | null | null | // copyright 2017 Lanting Guo
/** GenCC is to be used to generate a cc file which will be consistent
with google-cpp-style guide.
*/
#include <ctime>
#include <iostream>
#include <string>
#include <fstream>
using string = std::string;
string getYear() {
time_t t = time(0);
struct tm now;
localtime_r(&t, &now);
return std::to_string(now.tm_year + 1900);
}
string getCopyright() {
return "/* Copyright " + getYear() + " Lanting Guo" + " */\n"
+ "/**\n\n\n*/\n";
}
string getHeaders() {
return R"(#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <unordered_map>
#include <memory>
using std::string;
using std::vector;
using std::endl;
using std::cin;
using std::shared_ptr;
using std::make_shared;
)";
}
string getMain() {
return R"(int main(int argc, char *argv[]) {
Solution solu;
return 0;
})";
}
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Please input a file name" << "\n";
exit(0);
}
if (argc > 2) {
std::cout << "Do you want to generate multiple files?\n";
std::cout << "Sorry, only one file one time.";
exit(0);
}
std::ofstream cc;
cc.open(argv[1]);
cc << getCopyright();
cc << "\n";
cc << getHeaders();
cc << "\n\n\n";
cc << getMain();
cc << '\n';
cc.close();
return 0;
}
| 18.364865 | 70 | 0.607064 | [
"vector"
] |
c3daa4724b8e7664ce9ea1eb1e1df558db3c6f3b | 2,612 | hpp | C++ | ThirdParty-mod/java2cpp/android/hardware/SensorListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/hardware/SensorListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/hardware/SensorListener.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.hardware.SensorListener
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_DECL
#define J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
#include <java/lang/Object.hpp>
namespace j2cpp {
namespace android { namespace hardware {
class SensorListener;
class SensorListener
: public object<SensorListener>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit SensorListener(jobject jobj)
: object<SensorListener>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
void onSensorChanged(jint, local_ref< array<jfloat,1> > const&);
void onAccuracyChanged(jint, jint);
}; //class SensorListener
} //namespace hardware
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_IMPL
#define J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_IMPL
namespace j2cpp {
android::hardware::SensorListener::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
void android::hardware::SensorListener::onSensorChanged(jint a0, local_ref< array<jfloat,1> > const &a1)
{
return call_method<
android::hardware::SensorListener::J2CPP_CLASS_NAME,
android::hardware::SensorListener::J2CPP_METHOD_NAME(0),
android::hardware::SensorListener::J2CPP_METHOD_SIGNATURE(0),
void
>(get_jobject(), a0, a1);
}
void android::hardware::SensorListener::onAccuracyChanged(jint a0, jint a1)
{
return call_method<
android::hardware::SensorListener::J2CPP_CLASS_NAME,
android::hardware::SensorListener::J2CPP_METHOD_NAME(1),
android::hardware::SensorListener::J2CPP_METHOD_SIGNATURE(1),
void
>(get_jobject(), a0, a1);
}
J2CPP_DEFINE_CLASS(android::hardware::SensorListener,"android/hardware/SensorListener")
J2CPP_DEFINE_METHOD(android::hardware::SensorListener,0,"onSensorChanged","(I[F)V")
J2CPP_DEFINE_METHOD(android::hardware::SensorListener,1,"onAccuracyChanged","(II)V")
} //namespace j2cpp
#endif //J2CPP_ANDROID_HARDWARE_SENSORLISTENER_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 26.653061 | 105 | 0.705972 | [
"object"
] |
c3e3cc70e10a3897004ecf294eafd603ce9e32fd | 1,231 | cc | C++ | 2021/d4s1.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | 2021/d4s1.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | 2021/d4s1.cc | danielrayali/adventofcode | 29bfd54013a4ba832b7c846d2770eb03692d67de | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> Split(string& input) {
vector<string> values;
ssize_t prev = 0, cur = 0;
for (int i = 0; i < 5; ++i) {
cur = input.find_first_of(' ', prev);
if (cur != std::string::npos) {
values.push_back(input.substr(cur, (cur - prev)));
} else {
values.push_back(input.substr(cur));
}
prev = cur;
}
return values;
}
class BingoBoard {
public:
BingoBoard(std::ifstream& input) {
string line;
for (int i = 0; i < 5; ++i) {
getline(input, line);
vector<string> values = Split(line);
board_.push_back({});
for (auto value : values) {
board_.back().push_back(atoi(value.c_str()));
}
}
}
void Print() {
for (auto line : board_) {
for (auto value : line) {
cout << value << " ";
}
cout << endl;
}
}
private:
vector<vector<int>> board_;
};
int main(int argc, char* argv[]) {
ifstream input("d4s1.txt");
BingoBoard bingo_board(input);
bingo_board.Print();
return 0;
} | 23.226415 | 62 | 0.502031 | [
"vector"
] |
c3ec9dc6e9cf0cf05758aac78c9cd6c420511727 | 1,008 | cpp | C++ | aws-cpp-sdk-appflow/source/model/DescribeConnectorResult.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-appflow/source/model/DescribeConnectorResult.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-appflow/source/model/DescribeConnectorResult.cpp | truthiswill/aws-sdk-cpp | 6e854b6a8bc7945f150c3a11551196bda341962a | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appflow/model/DescribeConnectorResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Appflow::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeConnectorResult::DescribeConnectorResult()
{
}
DescribeConnectorResult::DescribeConnectorResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DescribeConnectorResult& DescribeConnectorResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("connectorConfiguration"))
{
m_connectorConfiguration = jsonValue.GetObject("connectorConfiguration");
}
return *this;
}
| 24.585366 | 114 | 0.77381 | [
"model"
] |
c3fb1b352b3e95546ac4e7daec395409d3ca25ae | 2,450 | cpp | C++ | main.cpp | MattiaSarti/neural-network-in-cpp | 4839ccbb68dea6068fc92c29e24ead0a236b5133 | [
"MIT"
] | null | null | null | main.cpp | MattiaSarti/neural-network-in-cpp | 4839ccbb68dea6068fc92c29e24ead0a236b5133 | [
"MIT"
] | null | null | null | main.cpp | MattiaSarti/neural-network-in-cpp | 4839ccbb68dea6068fc92c29e24ead0a236b5133 | [
"MIT"
] | null | null | null | /*
Script loading the training and validation sets from the file system,
training the model on the training set and evaluating it before and after
training on the validation set, saving results to the file system.
*/
#include "common.hpp"
#include "load_dataset.hpp"
#include "model.hpp"
// architecture hyperparameters:
const auto ACTIVATION_FUNCTIONS_NAME = "leakyReLU";
const std::vector<uint> N_NEURONS_IN_LAYERS = {2, 8, 8, 6, 4};
// training hyperparameters:
const float LEARNING_RATE = 0.0001;
const uint N_EPOCHS = 500;
// display options:
const bool VERBOSE = false;
int main() {
// loading training and validation sets:
std::vector<Tensor1D*> training_samples;
std::vector<Tensor1D*> training_labels;
loadDataset("training_set.csv", &training_samples, &training_labels);
std::cout << "training set loaded ✓" << std::endl;
std::vector<Tensor1D*> validation_samples;
std::vector<Tensor1D*> validation_labels;
loadDataset("validation_set.csv", &validation_samples, &validation_labels);
std::cout << "validation set loaded ✓" << std::endl;
std::cout << "- - - - - - - - - - - -" << std::endl;
// asserting that the number of neurons of first layer equals the number
// of features that samples in the dataset have:
assert(N_NEURONS_IN_LAYERS.front() == validation_samples.front()->size());
// initializing the model:
FullyConnectedNeuralNetwork model(N_NEURONS_IN_LAYERS,
ACTIVATION_FUNCTIONS_NAME);
std::cout << "model initialized ✓" << std::endl;
std::cout << "- - - - - - - - - - - -" << std::endl;
// evaluating the model on the validation set before training:
std::string results_path = "validation_set_predictions_before_training.csv";
model.evaluate(validation_samples, validation_labels, results_path,
VERBOSE);
std::cout << "- - - - - - - - - - - -" << std::endl;
// training the model on the training set:
model.train(training_samples, training_labels, LEARNING_RATE, N_EPOCHS,
VERBOSE);
std::cout << "- - - - - - - - - - - -" << std::endl;
// evaluating the model on the validation set after training:
results_path = "validation_set_predictions_after_training.csv";
model.evaluate(validation_samples, validation_labels, results_path,
VERBOSE);
std::cout << "- - - - - - - - - - - -" << std::endl;
return 0;
}
| 33.561644 | 80 | 0.657959 | [
"vector",
"model"
] |
c3fe5487aa72d1de75d93a30b6409f20de2631a5 | 1,067 | cc | C++ | src/base/util/ranges/functional_unittest.cc | huanyifan/naiveproxy | f7691d7020a7f0c2de4e25e363f8766dfc46466f | [
"BSD-3-Clause"
] | null | null | null | src/base/util/ranges/functional_unittest.cc | huanyifan/naiveproxy | f7691d7020a7f0c2de4e25e363f8766dfc46466f | [
"BSD-3-Clause"
] | null | null | null | src/base/util/ranges/functional_unittest.cc | huanyifan/naiveproxy | f7691d7020a7f0c2de4e25e363f8766dfc46466f | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/util/ranges/functional.h"
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
namespace util {
TEST(RangesTest, Identity) {
static constexpr identity id;
std::vector<int> v;
EXPECT_EQ(&v, &id(v));
constexpr int arr = {0};
static_assert(arr == id(arr), "");
}
TEST(RangesTest, Invoke) {
struct S {
int data_member = 123;
int member_function() { return 42; }
};
S s;
EXPECT_EQ(123, invoke(&S::data_member, s));
EXPECT_EQ(42, invoke(&S::member_function, s));
auto add_functor = [](int i, int j) { return i + j; };
EXPECT_EQ(3, invoke(add_functor, 1, 2));
}
TEST(RangesTest, EqualTo) {
ranges::equal_to eq;
EXPECT_TRUE(eq(0, 0));
EXPECT_FALSE(eq(0, 1));
EXPECT_FALSE(eq(1, 0));
}
TEST(RangesTest, Less) {
ranges::less lt;
EXPECT_FALSE(lt(0, 0));
EXPECT_TRUE(lt(0, 1));
EXPECT_FALSE(lt(1, 0));
}
} // namespace util
| 20.132075 | 73 | 0.656982 | [
"vector"
] |
7f067d639ce0820ed7344601cbc2258c7053f329 | 6,238 | hpp | C++ | boost/range_run_storage/algorithm/first_last.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 11 | 2015-02-21T11:23:44.000Z | 2021-08-15T03:39:29.000Z | boost/range_run_storage/algorithm/first_last.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | null | null | null | boost/range_run_storage/algorithm/first_last.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 3 | 2015-05-09T02:25:42.000Z | 2019-11-02T13:39:29.000Z | ///////////////////////////////////////////////////////////////////////////////
/// \file first_last.hpp
/// Returns the first and last runs and values from an \c InfiniteRangeRunStorage
//
// Copyright 2006 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_RANGE_RUN_STORAGE_ALGORITHM_FIRST_LAST_EAN_10_26_2006_HPP
#define BOOST_RANGE_RUN_STORAGE_ALGORITHM_FIRST_LAST_EAN_10_26_2006_HPP
#include <utility>
#include <boost/assert.hpp>
#include <boost/range_run_storage/concepts.hpp>
#include <boost/range_run_storage/utility/run_cast.hpp>
namespace boost { namespace range_run_storage
{
namespace seq = sequence;
namespace rrs = range_run_storage;
namespace detail
{
template<typename Offset>
struct std_pair_run
{
typedef std::pair<Offset, Offset> type;
};
}
/// \brief Returns the first run of an \c InfiniteRangeRunStorage.
///
/// Returns the first \c Run of an \c InfiniteRangeRunStorage. If there are
/// no runs in the \c InfinteRangeRunStorage, an empty run is returned.
/// Complexity is O(1).
///
/// \param[in] s The \c InfiniteRangeRunStorage.
/// \return A \c Run which has the same offset and end offset as the
/// first run in the \c InfiniteRangeRunStorage if one exists, or
/// and empty run if one doesn't.
/// \pre \c In is a model of \c InfiniteRangeRunStorage.
template<typename In>
typename detail::std_pair_run<
typename concepts::InfiniteRangeRunStorage<In const>::offset_type
>::type
first_run(In const &s)
{
typedef typename concepts::InfiniteRangeRunStorage<In const>::offset_type offset_type;
typedef typename concepts::InfiniteRangeRunStorage<In const>::cursor cursor_type;
typedef std::pair<offset_type, offset_type> run_type;
run_type run(rrs::run_cast<run_type>(rrs::pre_run(s)));
if(!rrs::empty(run))
{
return run;
}
cursor_type begin(seq::begin(s)), end(seq::end(s));
if(begin != end)
{
return rrs::run_cast<run_type>(rrs::runs(s)(*begin));
}
// could be empty
return rrs::run_cast<run_type>(rrs::post_run(s));
}
/// \brief Returns the value of the first run of an \c InfiniteRangeRunStorage.
///
/// Returns the value of the first \c Run of an \c InfiniteRangeRunStorage.
/// Complexity is O(1).
///
/// \param[in] s The \c InfiniteRangeRunStorage.
/// \return The value of the first run in the \c InfiniteRangeRunStorage.
/// \pre \c In is a model of \c InfiniteRangeRunStorage.
/// \pre \c s contains at least one run.
template<typename In>
typename concepts::InfiniteRangeRunStorage<In const>::reference
first_value(In const &s)
{
typedef typename concepts::InfiniteRangeRunStorage<In const>::cursor cursor_type;
if(!rrs::empty(rrs::pre_run(s)))
{
return rrs::pre_value(s);
}
cursor_type begin(seq::begin(s)), end(seq::end(s));
if(begin != end)
{
return seq::elements(s)(*begin);
}
BOOST_ASSERT(!rrs::empty(rrs::post_run(s)));
return rrs::post_value(s);
}
/// \brief Returns the last run of an \c InfiniteRangeRunStorage.
///
/// Returns the last \c Run of an \c InfiniteRangeRunStorage. If there are
/// no runs in the \c InfinteRangeRunStorage, an empty run is returned.
/// Complexity is O(1).
///
/// \param[in] s The \c InfiniteRangeRunStorage.
/// \return A \c Run which has the same offset and end offset as the
/// last run in the \c InfiniteRangeRunStorage if one exists, or
/// and empty run if one doesn't.
/// \pre \c In is a model of \c InfiniteRangeRunStorage.
/// \pre <tt>InfiniteRangeRunStorage<In const>::cursor</tt> is a model of
/// \c BidirectionalIterator.
template<typename In>
typename detail::std_pair_run<
typename concepts::InfiniteRangeRunStorage<In const>::offset_type
>::type
last_run(In const &s)
{
typedef typename concepts::InfiniteRangeRunStorage<In const>::offset_type offset_type;
typedef typename concepts::InfiniteRangeRunStorage<In const>::cursor cursor_type;
typedef std::pair<offset_type, offset_type> run_type;
run_type run(rrs::run_cast<run_type>(rrs::post_run(s)));
if(!rrs::empty(run))
{
return run;
}
cursor_type begin(seq::begin(s)), end(seq::end(s));
if(begin != end)
{
--end;
return rrs::run_cast<run_type>(rrs::runs(s)(*end));
}
// could be empty
return rrs::run_cast<run_type>(rrs::pre_run(s));
}
/// \brief Returns the value of the last \c Run of an \c InfiniteRangeRunStorage.
///
/// Returns the value of the last \c Run of an \c InfiniteRangeRunStorage.
/// Complexity is O(1).
///
/// \param[in] s The \c InfiniteRangeRunStorage.
/// \return The value of the last run in the \c InfiniteRangeRunStorage.
/// \pre \c In is a model of \c InfiniteRangeRunStorage.
/// \pre \c s contains at least one run.
/// \pre <tt>InfiniteRangeRunStorage<In const>::cursor</tt> is a model of
/// \c BidirectionalIterator.
template<typename In>
typename concepts::InfiniteRangeRunStorage<In const>::reference
last_value(In const &s)
{
typedef typename concepts::InfiniteRangeRunStorage<In const>::cursor cursor_type;
if(!rrs::empty(rrs::post_run(s)))
{
return rrs::post_value(s);
}
cursor_type begin(seq::begin(s)), end(seq::end(s));
if(begin != end)
{
--end;
return seq::elements(s)(*end);
}
BOOST_ASSERT(!rrs::empty(rrs::pre_run(s)));
return rrs::pre_value(s);
}
}}
#endif
| 35.850575 | 95 | 0.606925 | [
"model"
] |
7f0ec676398a500465efe245339bc871ce4852a3 | 2,737 | cpp | C++ | android/apps/framePlayer/src/main/cpp/PlayerWindow.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 272 | 2021-01-07T03:06:08.000Z | 2022-03-25T03:54:07.000Z | android/apps/framePlayer/src/main/cpp/PlayerWindow.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 1,021 | 2020-12-12T02:33:32.000Z | 2022-03-31T23:36:37.000Z | android/apps/framePlayer/src/main/cpp/PlayerWindow.cpp | Darlingnotin/Antisocial_VR | f1debafb784ed5a63a40fe9b80790fbaccfedfce | [
"Apache-2.0"
] | 77 | 2020-12-15T06:59:34.000Z | 2022-03-23T22:18:04.000Z | //
// Created by Bradley Austin Davis on 2018/10/21
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "PlayerWindow.h"
#include <QtCore/QFileInfo>
#include <QtGui/QImageReader>
#include <QtQml/QQmlContext>
#include <QtQuick/QQuickItem>
#include <gpu/Frame.h>
#include <gpu/FrameIO.h>
PlayerWindow::PlayerWindow() {
setFlags(Qt::MSWindowsOwnDC | Qt::Window | Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowTitleHint);
setSurfaceType(QSurface::OpenGLSurface);
create();
showFullScreen();
// Make sure the window has been created by processing events
QCoreApplication::processEvents();
// Start the rendering thread
_renderThread.initialize(this, &_surface);
// Start the UI
_surface.resize(size());
connect(&_surface, &hifi::qml::OffscreenSurface::rootContextCreated, this, [](QQmlContext* context){
context->setContextProperty("FRAMES_FOLDER", "file:assets:/frames");
});
_surface.load("qrc:///qml/main.qml");
// Connect the UI handler
QObject::connect(_surface.getRootItem(), SIGNAL(loadFile(QString)),
this, SLOT(loadFile(QString))
);
// Turn on UI input events
installEventFilter(&_surface);
}
PlayerWindow::~PlayerWindow() {
}
// static const char* FRAME_FILE = "assets:/frames/20190110_1635.json";
static void textureLoader(const std::string& filename, const gpu::TexturePointer& texture, uint16_t layer) {
QImage image;
QImageReader(filename.c_str()).read(&image);
if (layer > 0) {
return;
}
texture->assignStoredMip(0, image.byteCount(), image.constBits());
}
void PlayerWindow::loadFile(QString filename) {
QString realFilename = QUrl(filename).toLocalFile();
if (QFileInfo(realFilename).exists()) {
auto frame = gpu::readFrame(realFilename.toStdString(), _renderThread._externalTexture, &textureLoader);
_surface.pause();
_renderThread.submitFrame(frame);
}
}
void PlayerWindow::touchEvent(QTouchEvent* event) {
// Super basic input handling when the 3D scene is active.... tap with two finders to return to the
// QML UI
static size_t touches = 0;
switch (event->type()) {
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
touches = std::max<size_t>(touches, event->touchPoints().size());
break;
case QEvent::TouchEnd:
if (touches >= 2) {
_renderThread.submitFrame(nullptr);
_surface.resume();
}
touches = 0;
break;
default:
break;
}
}
| 29.75 | 112 | 0.659116 | [
"3d"
] |
7f122fdd80b8849a944369210cb26762c4996e9f | 32,983 | cpp | C++ | coast/foundation/base/cuteTest/AnythingConstructorsTest.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/foundation/base/cuteTest/AnythingConstructorsTest.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/foundation/base/cuteTest/AnythingConstructorsTest.cpp | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* Copyright (c) 2015, David Tran, Faculty of Computer Science,
* University of Applied Sciences Rapperswil (HSR),
* 8640 Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#include "AnythingConstructorsTest.h"
#include "IFAObject.h"
#include "Tracer.h"
AnythingConstructorsTest::AnythingConstructorsTest() : fString("A String"), fLong(5L), fBool(true), fDouble(7.125), fDouble2(8.1), fFloat(-24.490123456789), fNull(Anything()) {
StartTrace(AnythingConstructorsTest.setUp);
}
void AnythingConstructorsTest::runAllTests(cute::suite &s) {
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, DefaultConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, IntConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, LongConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, FloatConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, DoubleConstr0Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, DoubleConstr1Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, CharStarConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, CharStarLongConstr0Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, CharStarLongConstr1Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, CharStarLongConstr2Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, CharStarLongConstr3Test));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, StringConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, VoidStarLenConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, EmptyVoidStarLenConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, IFAObjectStarConstrTest));
s.push_back(CUTE_SMEMFUN(AnythingConstructorsTest, AnythingConstrTest));
}
class DummyIFAObj: public IFAObject {
public:
DummyIFAObj(const char *) {
}
/*! @copydoc IFAObject::Clone(Allocator *) */
IFAObject *Clone(Allocator *a) const {
return new (a) DummyIFAObj("dummy");
}
};
void AnythingConstructorsTest::DefaultConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
Anything anyHlp;
ASSERT( fNull.GetType() == AnyNullType );
ASSERT_EQUAL( fNull.IsNull(), true );
ASSERT_EQUAL( fNull.IsNull(), true );
ASSERT( fNull.IsNull() == bool(1) );
ASSERT( fNull.GetSize() == bool(0) );
ASSERT( fNull == anyHlp );
ASSERT( !(fNull != anyHlp) );
ASSERT( fNull.IsEqual(anyHlp) );
ASSERT( String("") == fNull.AsCharPtr() );
ASSERT( String("Default") == fNull.AsCharPtr("Default") );
ASSERT( fNull.AsCharPtr(0) == NULL );
ASSERT_EQUAL( fNull.AsLong(), 0L );
ASSERT_EQUAL( fNull.AsLong(1234), 1234L );
ASSERT_EQUAL( fNull.AsBool(), false );
ASSERT_EQUAL( fNull.AsBool(true), true );
ASSERT( fNull.AsBool() == 0 );
ASSERT( fNull.AsDouble() == 0 );
ASSERT_EQUAL( fNull.AsDouble(2.3), 2.3 );
ASSERT( fNull.AsIFAObject() == NULL );
DummyIFAObj testObj("testObj");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( fNull.AsIFAObject(&testObj) == &testObj );
ASSERT_EQUAL( (fNull.AsString()).Length(), 0L );
ASSERT( (fNull.AsString()).Capacity() >= (fNull.AsString()).Length() );
ASSERT( fNull.AsString() == "" );
ASSERT( fNull.AsString("Default") == "Default" );
ASSERT( fNull.Contains("testSlot") == false );
ASSERT_LESS( fNull.FindValue("testSlot"), 0L );
// Does it survive?
fNull.Remove(-1L);
fNull.Remove(0L);
fNull.Remove(1L);
ASSERT_LESS( fNull.FindIndex("testSlots"), 0L );
ASSERT( fNull.IsDefined("testSlots") == false );
ASSERT( fNull.SlotName(0) == NULL );
//ASSERT( fNull.At(-1L) == NULL ); // ABORT ???? Anything.cpp:1358
ASSERT( fNull.At(0L) == NULL );
ASSERT( fNull.At(1L) == NULL );
//ASSERT( fNull[-1L] == NULL ); // ABORT ???? Anything.cpp:1358
ASSERT( fNull[0L] == NULL );
ASSERT( fNull[1L] == NULL );
}
void AnythingConstructorsTest::IntConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
Anything anyHlp = fBool;
ASSERT( fBool.GetType() == AnyLongType );
ASSERT_EQUAL( fBool.IsNull(), false );
ASSERT_EQUAL( fBool.IsNull(), false );
ASSERT( fBool.IsNull() == 0 );
ASSERT_EQUAL( fBool.GetSize(), 1L );
ASSERT( fBool == anyHlp );
ASSERT( !(fBool != anyHlp) );
ASSERT( fBool.IsEqual(anyHlp) );
ASSERT_EQUAL( fBool.AsBool(), true );
ASSERT_EQUAL( fBool.AsBool(false), true );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( fBool.AsIFAObject(&testObj) == &testObj );
ASSERT( fBool.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( fBool.AsIFAObject() == NULL );
ASSERT_EQUAL( (fBool.AsString()).Length(), 1L );
ASSERT( (fBool.AsString()).Capacity() >= (fBool.AsString()).Length() );
ASSERT_EQUAL( fBool.Contains("testSlot"), false );
ASSERT_LESS( fBool.FindValue("testSlot"), 0L );
// Does it survive?
fBool.Remove(-1L);
fBool.Remove(0L);
fBool.Remove(1L);
ASSERT_LESS( fBool.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( fBool.IsDefined("testSlots"), false );
ASSERT( fBool.SlotName(0) == NULL );
ASSERT_EQUAL( (fBool.At(0L)).AsBool(false), false );
ASSERT( fBool.At(1L) == NULL );
ASSERT( fBool[1L] == NULL );
}
void AnythingConstructorsTest::LongConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
Anything anyHlp = fLong;
ASSERT( fLong.GetType() == AnyLongType );
ASSERT_EQUAL( fLong.IsNull(), false );
ASSERT( fLong.IsNull() == 0 );
ASSERT_EQUAL( fLong.GetSize(), 1L );
ASSERT( fLong == anyHlp );
ASSERT( !(fLong != anyHlp) );
ASSERT( fLong.IsEqual(anyHlp) );
ASSERT( String("5") == fLong.AsCharPtr() );
ASSERT( String("5") == fLong.AsCharPtr("Default") );
ASSERT_EQUAL( fLong.AsCharPtr(0), "5");
ASSERT_EQUAL( fLong.AsLong(), 5L );
ASSERT_EQUAL( fLong.AsLong(1234), 5L );
ASSERT_EQUAL( fLong.AsBool(), true );
ASSERT_EQUAL( fLong.AsBool(false), true );
ASSERT( fLong.AsBool() == 1 );
ASSERT( fLong.AsDouble() == (double)5 );
ASSERT( fLong.AsDouble(2.3) == (double)5 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( fLong.AsIFAObject(&testObj) == &testObj );
ASSERT( fLong.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( fLong.AsIFAObject() == NULL );
ASSERT_EQUAL( (fLong.AsString()).Length(), 1L );
ASSERT( (fLong.AsString()).Capacity() >= (fLong.AsString()).Length() );
ASSERT( fLong.AsString() == "5" );
ASSERT( fLong.AsString("Default") == "5" );
ASSERT_EQUAL( fLong.Contains("testSlot"), false );
ASSERT_LESS( fLong.FindValue("testSlot"), 0L );
// Does it survive?
ASSERT_EQUAL( fLong.GetType(), AnyLongType );
fLong.Remove(-1L);
ASSERT_EQUAL( fLong.GetType(), AnyLongType );
fLong.Remove(0L);
ASSERT_EQUAL( fLong.GetType(), AnyNullType );
fLong.Remove(1L);
ASSERT_LESS( fLong.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( fLong.IsDefined("testSlots"), false );
ASSERT( fLong.SlotName(0) == NULL );
ASSERT( fLong.At(-1L) == fLong.At(0L) );
ASSERT_EQUAL( fLong.GetType(), AnyArrayType );
ASSERT_EQUAL( fLong[0L].GetType(), AnyNullType );
ASSERT_EQUAL( (fLong.At(0L)).AsLong(-1L), -1L );
ASSERT( fLong.At(1L) == NULL );
ASSERT_EQUAL( fLong[0L].AsCharPtr(""), "");
ASSERT( fLong[1L] == NULL );
}
void AnythingConstructorsTest::DoubleConstr0Test() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
// fDouble = 7.125; there is an exact binary representation
Anything anyHlp = fDouble;
ASSERT( fDouble.GetType() == AnyDoubleType );
ASSERT_EQUAL( fDouble.IsNull(), false );
ASSERT_EQUAL( fDouble.IsNull(), false );
ASSERT( fDouble.IsNull() == 0 );
ASSERT_EQUAL( fDouble.GetSize(), 1L );
ASSERT( fDouble == anyHlp );
ASSERT( !(fDouble != anyHlp) );
ASSERT( fDouble.IsEqual(anyHlp) );
ASSERT_EQUAL( "7.125", fDouble.AsCharPtr() );
ASSERT_EQUAL( "7.125", fDouble.AsCharPtr("Default") );
ASSERT_EQUAL( fDouble.AsCharPtr(0), "7.125");
ASSERT_EQUAL( fDouble.AsLong(), 7L );
ASSERT_EQUAL( fDouble.AsLong(1234), 7L );
ASSERT_EQUAL( fDouble.AsBool(), false );
ASSERT_EQUAL( fDouble.AsBool(false), false );
ASSERT( fDouble.AsBool() == 0 );
ASSERT_EQUAL( fDouble.AsDouble(), 7.125 );
ASSERT_EQUAL( fDouble.AsDouble(2.3), 7.125 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( fDouble.AsIFAObject(&testObj) == &testObj );
ASSERT( fDouble.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( fDouble.AsIFAObject() == NULL );
ASSERT_EQUAL( 5L, fDouble.AsString().Length() );
ASSERT( (fDouble.AsString()).Capacity() >= (fDouble.AsString()).Length() );
ASSERT_EQUAL( "7.125", fDouble.AsString() );
ASSERT_EQUAL( "7.125", fDouble.AsString("Default") );
ASSERT_EQUAL( fDouble.Contains("testSlot"), false );
ASSERT_LESS( fDouble.FindValue("testSlot"), 0L );
// Does it survive?
fDouble.Remove(-1L);
fDouble.Remove(0L);
fDouble.Remove(1L);
ASSERT_LESS( fDouble.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( fDouble.IsDefined("testSlots"), false );
ASSERT( fDouble.SlotName(0) == NULL );
ASSERT( fDouble.At(-1L) == fDouble.At(0L) );
ASSERT_EQUAL( (fDouble.At(0L)).AsLong(1), 1L );
ASSERT( fDouble.At(1L) == NULL );
ASSERT_EQUAL( fDouble[0L].AsCharPtr(""), "");
ASSERT( fDouble[1L] == NULL );
}
void AnythingConstructorsTest::DoubleConstr1Test() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
// fDouble2 = 8.1; there is no exact binary representation
Anything anyHlp = fDouble2;
ASSERT( fDouble2.GetType() == AnyDoubleType );
ASSERT_EQUAL( fDouble2.IsNull(), false );
ASSERT_EQUAL( fDouble2.IsNull(), false );
ASSERT( fDouble2.IsNull() == 0 );
ASSERT_EQUAL( fDouble2.GetSize(), 1L );
ASSERT( fDouble2 == anyHlp );
ASSERT( !(fDouble2 != anyHlp) );
ASSERT( fDouble2.IsEqual(anyHlp) );
ASSERT_EQUAL( "8.1", fDouble2.AsString().SubString(0, 6) );
ASSERT_EQUAL( "8.1", fDouble2.AsString() );
ASSERT_EQUAL( "8.1", fDouble2.AsString("Default") );
ASSERT_EQUAL( 8L, fDouble2.AsLong() );
ASSERT_EQUAL( 8L, fDouble2.AsLong(1234) );
ASSERT( !fDouble2.AsBool() );
ASSERT( fDouble2.AsBool(true) );
ASSERT_EQUAL_DELTA( 8.1, fDouble2.AsDouble(), 0.1 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simplest IFAObject that can be instantiated
ASSERT( fDouble2.AsIFAObject(&testObj) == &testObj );
ASSERT( fDouble2.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( fDouble2.AsIFAObject() == NULL );
ASSERT_EQUAL( fDouble2.Contains("testSlot"), false );
ASSERT_LESS( fDouble2.FindValue("testSlot"), 0L );
// Does it survive?
fDouble2.Remove(-1L);
fDouble2.Remove(0L);
fDouble2.Remove(1L);
ASSERT_LESS( fDouble2.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( fDouble2.IsDefined("testSlots"), false );
ASSERT( fDouble2.SlotName(0) == NULL );
ASSERT( fDouble2.At(-1L) == fDouble2.At(0L) );
ASSERT_EQUAL( (fDouble2.At(0L)).AsLong(-2), -2L );
ASSERT( fDouble2.At(1L) == NULL );
ASSERT( fDouble2[1L] == NULL );
}
void AnythingConstructorsTest::FloatConstrTest() // Test if the dafault constructor generates an anything-object with good reactions.
{
// The method called now are assumed to work correctly (they are being tested later on).
Anything anyHlp = fFloat;
ASSERT( fFloat.GetType() == AnyDoubleType );
ASSERT_EQUAL( fFloat.IsNull(), false );
ASSERT_EQUAL( fFloat.IsNull(), false );
ASSERT( fFloat.IsNull() == 0 );
ASSERT_EQUAL( fFloat.GetSize(), 1L );
ASSERT( fFloat == anyHlp );
ASSERT( !(fFloat != anyHlp) );
ASSERT( fFloat.IsEqual(anyHlp) );
// here we use 14 significant digits
fFloat = -24.490123456789;
double testDouble = -24.490123456789;
ASSERT_EQUAL_DELTA( testDouble, fFloat.AsDouble(0), 0.000000000001 );
ASSERT_EQUAL( "-24.4901234567", fFloat.AsString().SubString(0, 14) );
ASSERT_EQUAL( "-24.490123456789", fFloat.AsString() );
ASSERT_EQUAL( -24L, fFloat.AsLong() );
ASSERT_EQUAL( -24L, fFloat.AsLong(1234) );
ASSERT( !fFloat.AsBool() );
ASSERT( fFloat.AsBool(true) );
ASSERT_EQUAL( 0, fFloat.AsBool() );
ASSERT_EQUAL_DELTA( (double) - 24.4901, fFloat.AsDouble(), 0.0001 );
ASSERT( fFloat.AsDouble(2.3) == (double) - 24.490123456789 );
ASSERT( fFloat.AsDouble(2.3) != (double) - 24.4901 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( fFloat.AsIFAObject(&testObj) == &testObj );
ASSERT( fFloat.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( fFloat.AsIFAObject() == NULL );
ASSERT_EQUAL( 16, fFloat.AsString().Length() );
ASSERT_EQUAL( "-24.490123456789", fFloat.AsString("Default") );
ASSERT( !fFloat.Contains("testSlot") );
ASSERT_LESS( fFloat.FindValue("testSlot"), 0L );
// Does it survive?
fFloat.Remove(-1L);
fFloat.Remove(0L);
fFloat.Remove(1L);
ASSERT_LESS( fFloat.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( fFloat.IsDefined("testSlots"), false );
ASSERT( fFloat.SlotName(0) == NULL );
ASSERT( fFloat.At(-1L) == fFloat.At(0L) );
ASSERT( (fFloat.At(0L)).AsLong(3L) == 3L );
ASSERT( fFloat.At(1L) == NULL );
ASSERT( fFloat[1L] == NULL );
Anything anyTest = -24.51;
ASSERT( anyTest.AsLong() == -24L );
}
void AnythingConstructorsTest::CharStarConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
char charStarTest[50] = { 0 };
memcpy(charStarTest, "A String", strlen("A String"));
Anything anyCharStar(charStarTest), anyHlp = fString;
ASSERT( anyCharStar.GetType() == AnyCharPtrType );
ASSERT_EQUAL( anyCharStar.IsNull(), false );
ASSERT_EQUAL( anyCharStar.IsNull(), false );
ASSERT( anyCharStar.IsNull() == 0 );
ASSERT_EQUAL( anyCharStar.GetSize(), 1L );
ASSERT( anyCharStar == anyHlp );
ASSERT( !(anyCharStar != anyHlp) );
ASSERT( anyCharStar.IsEqual(anyHlp) );
ASSERT( String("A String") == anyCharStar.AsCharPtr() );
ASSERT( String("A String") == anyCharStar.AsCharPtr("Default") );
ASSERT_EQUAL( anyCharStar.AsCharPtr(0), "A String");
ASSERT_EQUAL( anyCharStar.AsLong(), 0L );
ASSERT_EQUAL( anyCharStar.AsLong(1234), 1234L );
ASSERT_EQUAL ( 1234L, anyCharStar.AsLong(1234) );
ASSERT_EQUAL( anyCharStar.AsBool(), false );
ASSERT_EQUAL( anyCharStar.AsBool(true), true );
ASSERT( anyCharStar.AsBool() == 0 );
ASSERT( anyCharStar.AsDouble() == (double)0 );
ASSERT( anyCharStar.AsDouble(2.3) == (double)2.3 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( anyCharStar.AsIFAObject(&testObj) == &testObj );
ASSERT( anyCharStar.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( anyCharStar.AsIFAObject() == NULL );
ASSERT( (anyCharStar.AsString()).Length() == (long)strlen("A String") );
ASSERT( (anyCharStar.AsString()).Capacity() >= (anyCharStar.AsString()).Length() );
ASSERT( anyCharStar.AsString() == "A String" );
ASSERT( anyCharStar.AsString("Default") == "A String" );
ASSERT_EQUAL( anyCharStar.Contains("testSlot"), false );
ASSERT_LESS( anyCharStar.FindValue("testSlot"), 0L );
// Does it survive?
anyCharStar.Remove(-1L);
anyCharStar.Remove(0L);
anyCharStar.Remove(1L);
ASSERT_LESS( anyCharStar.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyCharStar.IsDefined("testSlots"), false );
ASSERT( anyCharStar.SlotName(0) == NULL );
ASSERT( anyCharStar.At(-1L) == anyCharStar.At(0L) );
ASSERT( (anyCharStar.At(0L)).AsLong() == 0 );
ASSERT( anyCharStar.At(1L) == NULL );
ASSERT_EQUAL( anyCharStar[0L].AsCharPtr(""), "" );
ASSERT( anyCharStar[1L] == NULL );
}
void AnythingConstructorsTest::CharStarLongConstr0Test() {
Anything anyStringLen("abcdefgh", 8L), anyHlp;
anyHlp = anyStringLen;
ASSERT( anyStringLen.GetType() == AnyCharPtrType );
ASSERT_EQUAL( anyStringLen.IsNull(), false );
ASSERT_EQUAL( anyStringLen.IsNull(), false );
ASSERT( anyStringLen.IsNull() == 0 );
ASSERT_EQUAL( anyStringLen.GetSize(), 1L );
ASSERT( anyStringLen == anyHlp );
ASSERT( !(anyStringLen != anyHlp) );
ASSERT( anyStringLen.IsEqual(anyHlp) );
ASSERT( String("abcdefgh") == anyStringLen.AsCharPtr() );
ASSERT( String("abcdefgh") == anyStringLen.AsCharPtr("Default") );
ASSERT_EQUAL( anyStringLen.AsCharPtr(0), "abcdefgh");
ASSERT_EQUAL( anyStringLen.AsLong(), 0L );
ASSERT_EQUAL( anyStringLen.AsLong(1234), 1234L );
ASSERT_EQUAL( anyStringLen.AsBool(), false );
ASSERT_EQUAL( anyStringLen.AsBool(true), true );
ASSERT( anyStringLen.AsBool() == 0 );
ASSERT( anyStringLen.AsDouble() == (double)0 );
ASSERT( anyStringLen.AsDouble(2.3) == (double)2.3 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( anyStringLen.AsIFAObject(&testObj) == &testObj );
ASSERT( anyStringLen.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( anyStringLen.AsIFAObject() == NULL );
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen("abcdefgh") );
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen(anyStringLen.AsCharPtr(0)) );
ASSERT( (anyStringLen.AsString()).Capacity() >= (anyStringLen.AsString(0)).Length() );
ASSERT( anyStringLen.AsString() == "abcdefgh" );
ASSERT( anyStringLen.AsString("Default") == "abcdefgh" );
ASSERT_EQUAL( anyStringLen.Contains("testSlot"), false );
ASSERT_LESS( anyStringLen.FindValue("testSlot"), 0L );
// Does it survive?
anyStringLen.Remove(-1L);
anyStringLen.Remove(0L);
anyStringLen.Remove(1L);
ASSERT_LESS( anyStringLen.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyStringLen.IsDefined("testSlots"), false );
ASSERT( anyStringLen.SlotName(0) == NULL );
ASSERT( anyStringLen.At(-1L) == anyStringLen.At(0L) );
ASSERT( (anyStringLen.At(0L)).AsLong() == 0 );
ASSERT( anyStringLen.At(1L) == NULL );
ASSERT_EQUAL( anyStringLen[0L].AsCharPtr(""), "");
ASSERT( anyStringLen[1L] == NULL );
}
void AnythingConstructorsTest::CharStarLongConstr1Test() {
Anything anyStringLen("abcdefgh", 4L), anyHlp;
anyHlp = anyStringLen;
ASSERT( anyStringLen.GetType() == AnyCharPtrType );
ASSERT_EQUAL( anyStringLen.IsNull(), false );
ASSERT_EQUAL( anyStringLen.IsNull(), false );
ASSERT( anyStringLen.IsNull() == 0 );
ASSERT_EQUAL( anyStringLen.GetSize(), 1L );
ASSERT( anyStringLen == anyHlp );
ASSERT( !(anyStringLen != anyHlp) );
ASSERT( anyStringLen.IsEqual(anyHlp) );
ASSERT( String("abcd") == anyStringLen.AsCharPtr() );
ASSERT( String("abcd") == anyStringLen.AsCharPtr("Default") );
ASSERT_EQUAL( anyStringLen.AsCharPtr(0), "abcd");
ASSERT_EQUAL( anyStringLen.AsLong(), 0L );
ASSERT_EQUAL( anyStringLen.AsLong(1234), 1234L );
ASSERT_EQUAL( anyStringLen.AsBool(), false );
ASSERT_EQUAL( anyStringLen.AsBool(true), true );
ASSERT( anyStringLen.AsBool() == 0 );
ASSERT( anyStringLen.AsDouble() == (double)0 );
ASSERT( anyStringLen.AsDouble(2.3) == (double)2.3 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( anyStringLen.AsIFAObject(&testObj) == &testObj );
ASSERT( anyStringLen.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( anyStringLen.AsIFAObject() == NULL );
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen("abcd") );
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen(anyStringLen.AsCharPtr(0)) );
ASSERT( (anyStringLen.AsString()).Capacity() >= (anyStringLen.AsString(0)).Length() );
ASSERT( anyStringLen.AsString() == "abcd" );
ASSERT( anyStringLen.AsString("Default") == "abcd" );
ASSERT_EQUAL( anyStringLen.Contains("testSlot"), false );
ASSERT_LESS( anyStringLen.FindValue("testSlot"), 0L );
// Does it survive?
anyStringLen.Remove(-1L);
anyStringLen.Remove(0L);
anyStringLen.Remove(1L);
ASSERT_LESS( anyStringLen.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyStringLen.IsDefined("testSlots"), false );
ASSERT( anyStringLen.SlotName(0) == NULL );
ASSERT( anyStringLen.At(-1L) == anyStringLen.At(0L) );
ASSERT( (anyStringLen.At(0L)).AsLong() == 0 );
ASSERT( anyStringLen.At(1L) == NULL );
ASSERT_EQUAL( anyStringLen[0L].AsCharPtr(""), "");
ASSERT( anyStringLen[1L] == NULL );
}
void AnythingConstructorsTest::CharStarLongConstr2Test() {
// Frage: Ist der Inhalt gleich wegen Zufall oder wird festgestellt, dass strlen("abcdefgh") < 10 ist?
#define TSTSTR "abcdefgh"
Anything anyStringLen(TSTSTR, 10L);
// PT: this is not nice: constructor will read past the end of the string,
// it might crash!
long l = anyStringLen.AsString().Length();
ASSERT( l == (long)strlen(TSTSTR) ); // this would also be a reasonable assertion
// ASSERT_EQUAL( 10, l ); // semantic change, above is correct!
// ASSERT( (anyStringLen.AsString()).Length() == (long)strlen(anyStringLen.AsCharPtr(0)) );
// the above would be reasonable also
ASSERT_EQUAL( anyStringLen.AsCharPtr(0), "abcdefgh");
}
void AnythingConstructorsTest::CharStarLongConstr3Test() {
// negative Werte bedeuten "Ich kenne die Laenge nicht" --> Die Laenge wird die Laenge der Zeichenkette
Anything anyStringLen("abcdefgh", -3L);
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen("abcdefgh") );
ASSERT( (anyStringLen.AsString()).Length() == (long)strlen(anyStringLen.AsCharPtr(0)) );
ASSERT( anyStringLen.AsString() == "abcdefgh" );
ASSERT( (anyStringLen.AsString()).Length() <= (anyStringLen.AsString()).Capacity() );
}
void AnythingConstructorsTest::StringConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
String stringTest = "A String";
Anything anyString(stringTest), anyHlp = fString;
ASSERT( anyString.GetType() == AnyCharPtrType );
ASSERT_EQUAL( anyString.IsNull(), false );
ASSERT_EQUAL( anyString.IsNull(), false );
ASSERT( anyString.IsNull() == 0 );
ASSERT_EQUAL( anyString.GetSize(), 1L );
ASSERT( anyString.AsString() == anyHlp.AsString() );
ASSERT( !(anyString.AsString() != anyHlp.AsString()) );
ASSERT( anyString.IsEqual(anyHlp) );
ASSERT_EQUAL( anyString.AsCharPtr(0), "A String");
ASSERT_EQUAL( anyString.AsCharPtr("Default"), "A String");
ASSERT( anyString.AsLong() == 0L );
ASSERT_EQUAL( anyString.AsLong(1234), 1234L );
ASSERT_EQUAL( anyString.AsBool(), false );
ASSERT_EQUAL( anyString.AsBool(true), true );
ASSERT( anyString.AsBool() == 0 );
ASSERT( anyString.AsDouble() == (double)0 );
ASSERT( anyString.AsDouble(2.3) == (double)2.3 );
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( anyString.AsIFAObject(&testObj) == &testObj );
ASSERT( anyString.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( anyString.AsIFAObject() == NULL );
ASSERT( (anyString.AsString()).Length() == (long)strlen("A String") );
ASSERT( (anyString.AsString()).Capacity() >= (anyString.AsString()).Length() );
ASSERT( anyString.AsString() == "A String" );
ASSERT( anyString.AsString("Default") == "A String" );
String stringHlp;
stringHlp = anyString.AsString();
ASSERT( stringHlp == "A String" );
stringHlp = String(anyString.AsString());
ASSERT( stringHlp == "A String" );
ASSERT_EQUAL( anyString.Contains("testSlot"), false );
ASSERT_LESS( anyString.FindValue("testSlot"), 0L );
// Does it survive?
anyString.Remove(-1L);
anyString.Remove(0L);
anyString.Remove(1L);
ASSERT_LESS( anyString.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyString.IsDefined("testSlots"), false );
ASSERT( anyString.SlotName(0) == NULL );
ASSERT( anyString.At(-1L) == anyString.At(0L) );
ASSERT( (anyString.At(0L)).AsLong() == 0L );
ASSERT( anyString.At(1L) == NULL );
ASSERT_EQUAL( anyString[0L].AsCharPtr(""), "");
ASSERT( anyString[1L] == NULL );
String voidstr((void *) "abc\0ef", 5); // string with 0 byte included
Anything avoidstr(voidstr);
ASSERT(avoidstr.GetType() == AnyCharPtrType);
ASSERT(avoidstr.AsString() == voidstr); // does it remain the same
ASSERT_EQUAL(voidstr.Length(), avoidstr.AsString().Length());
}
void AnythingConstructorsTest::EmptyVoidStarLenConstrTest() {
char test[10];
memset(test, '\0', 10);
Anything anyTest((void *) 0, 10);
ASSERT( anyTest.GetType() == AnyVoidBufType );
ASSERT_EQUAL( anyTest.IsNull(), false );
ASSERT_EQUAL( anyTest.GetSize(), 1L );
ASSERT( anyTest.AsCharPtr(0) != 0 );
ASSERT_EQUAL( (const char *) test, anyTest.AsCharPtr());
Anything anyTest1((void *) test, 0); // we do not allocate something
ASSERT( anyTest1.GetType() == AnyVoidBufType );
ASSERT_EQUAL( anyTest1.IsNull(), false );
ASSERT_EQUAL( anyTest1.GetSize(), 1L );
ASSERT( anyTest1.AsCharPtr(0) == 0 );
test[0] = '1';
test[5] = '6';
Anything anyTest2((void *) test, 10);
ASSERT( anyTest2.GetType() == AnyVoidBufType );
ASSERT_EQUAL( anyTest2.IsNull(), false );
ASSERT_EQUAL( anyTest2.GetSize(), 1L );
ASSERT( anyTest2.AsCharPtr(0) != 0 );
ASSERT_EQUAL( (const char *) test, anyTest2.AsCharPtr());
}
void AnythingConstructorsTest::VoidStarLenConstrTest() {
typedef long arrValueType;
arrValueType arrTest[5] = { 0, 1, 2, 3, 4 };
Anything anyTest((void *) arrTest, static_cast<long>(sizeof(arrTest)));
size_t _byteLengthOfArray = sizeof(arrTest);
long _elementsInArray = _byteLengthOfArray/sizeof(arrValueType);
Anything anyHlp = anyTest;
ASSERT( anyTest.GetType() == AnyVoidBufType );
ASSERT_EQUAL( anyTest.IsNull(), false );
ASSERT_EQUAL( anyTest.IsNull(), false );
ASSERT( anyTest.IsNull() == 0 );
ASSERT_EQUAL( anyTest.GetSize(), 1L );
ASSERT( anyTest == anyHlp );
ASSERT( !(anyTest != anyHlp) );
ASSERT( anyTest.IsEqual(anyHlp) );
ASSERT_EQUAL( (const char *) arrTest, anyTest.AsCharPtr());
// AsCharPtr returns the address of the buffer of the binary any
ASSERT( anyTest.AsLong() != 0 ); // address of the buffer (also)
ASSERT_EQUAL((long) anyTest.AsCharPtr(0), anyTest.AsLong());
ASSERT_EQUAL( anyTest.AsBool(), false );
ASSERT_EQUAL( anyTest.AsBool(false), false );
ASSERT( anyTest.AsDouble() == (double)0 );
ASSERT_EQUAL( anyTest.AsDouble(2.3), 2.3 );
DummyIFAObj testObj("Test");
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
ASSERT( anyTest.AsIFAObject(&testObj) == &testObj );
ASSERT( anyTest.AsIFAObject() == NULL );
ASSERT_EQUAL( (long)sizeof(arrTest), (anyTest.AsString()).Length() );
ASSERT( (anyTest.AsString()).Capacity() >= (anyTest.AsString()).Length() );
ASSERT( anyTest.AsString() == String( (void *)arrTest, (long)sizeof(arrTest) ) );
ASSERT( anyTest.AsString("Default") == String( (void *)arrTest, (long)sizeof(arrTest) ) );
long i;
for (i = 0; i < _elementsInArray; i++) {
ASSERT ( ( (long *)((const char *)anyTest.AsString()) )[i] == i );
ASSERT ( ( (long *)((const char *)anyTest.At(0L).AsString()) )[i] == i );
ASSERT ( ( (long *)((const char *)anyTest[0L].AsString()) )[i] == i );
ASSERT ( ( (long *)(anyTest.AsCharPtr()) )[i] == i );
ASSERT ( ( (long *)(anyTest.At(0L).AsCharPtr()) )[i] == i );
ASSERT ( ( (long *)((const char *)anyTest[0L].AsString()) )[i] == i );
}
ASSERT_EQUAL( anyTest.Contains("testSlot"), false );
ASSERT_LESS( anyTest.FindValue("testSlot"), 0L );
// Does it survive?
ASSERT_EQUAL(_byteLengthOfArray, anyTest[0L].AsString().Length());
ASSERT_EQUAL("", anyTest[0L].AsString());
anyTest.Remove(-1L);
ASSERT_EQUAL(1, anyTest.GetSize());
anyTest.Remove(0L);
ASSERT_EQUAL(0, anyTest.GetSize());
anyTest.Remove(1L);
ASSERT_EQUAL(0, anyTest.GetSize());
ASSERT_LESS( anyTest.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyTest.IsDefined("testSlots"), false );
ASSERT( anyTest.SlotName(0) == NULL );
ASSERT( anyTest.At(-1L) == anyTest.At(0L) );
ASSERT_EQUAL( (anyTest.At(0L)).AsLong(-1L), -1L );
ASSERT( anyTest.At(1L) == NULL );
ASSERT_EQUAL( anyTest[0L].AsCharPtr(""), (const char *)arrTest);
ASSERT( anyTest[1L] == NULL );
}
void AnythingConstructorsTest::IFAObjectStarConstrTest() {
// Test if the dafault constructor generates an anything-object with good reactions.
// The method called now are assumed to work correctly (they are being tested later on).
DummyIFAObj testObj("Test"), testObjDummy("TestObjDummy");
String testAdr;
testAdr << (long) &testObj; // the address of the object for comparison
// We use a DummyIFAObj, it is the simples IFAObject that can be instantiated
Anything anyIFAObj(&testObj), anyHlp = anyIFAObj;
ASSERT( anyIFAObj.GetType() == AnyObjectType );
ASSERT_EQUAL( anyIFAObj.IsNull(), false );
ASSERT_EQUAL( anyIFAObj.IsNull(), false );
ASSERT( anyIFAObj.IsNull() == 0 );
ASSERT_EQUAL( anyIFAObj.GetSize(), 1L );
ASSERT( anyIFAObj == anyHlp );
ASSERT( !(anyIFAObj != anyHlp) );
ASSERT( anyIFAObj.IsEqual(anyHlp) );
ASSERT( String("IFAObject") == anyIFAObj.AsCharPtr() ); // Ist es OK ????
ASSERT( String("IFAObject") == anyIFAObj.AsCharPtr("Default") );
ASSERT_EQUAL( anyIFAObj.AsCharPtr(0), "IFAObject");
ASSERT( anyIFAObj.AsLong() != 0L ); // address of object
ASSERT( anyIFAObj.AsLong(1234) != 1234L );
ASSERT_EQUAL( anyIFAObj.AsBool(), false );
ASSERT_EQUAL( anyIFAObj.AsBool(false), false );
ASSERT( anyIFAObj.AsDouble() == (double)0 );
ASSERT_EQUAL( anyIFAObj.AsDouble(2.3), 2.3 );
ASSERT( anyIFAObj.AsIFAObject(&testObj) == &testObj );
ASSERT( anyIFAObj.AsIFAObject(&testObj) != &testObjDummy );
ASSERT( anyIFAObj.AsIFAObject() == &testObj );
// PT: somewhat inconsistent, AsString returns the address, AsCharPtr the type
// PS: now it is consistent so the testcases fail
ASSERT( String("IFAObject") == anyIFAObj.AsString() ); // Ist es OK ????
ASSERT( (anyIFAObj.AsString()).Capacity() >= (anyIFAObj.AsString()).Length() );
ASSERT( (anyIFAObj.At(0L)).AsLong() == (long)&testObj );
// returns the address
ASSERT( anyIFAObj.At(1L) == NULL );
ASSERT_EQUAL( anyIFAObj[0L].AsCharPtr(), "IFAObject");
ASSERT_EQUAL( anyIFAObj.Contains("testSlot"), false );
ASSERT_LESS( anyIFAObj.FindValue("testSlot"), 0L );
// Does it survive?
anyIFAObj.Remove(-1L);
ASSERT_EQUAL( anyIFAObj.At(-1L).GetType(), AnyObjectType );
ASSERT( (anyIFAObj.At(0L)).AsLong() == (long)&testObj );
ASSERT( anyIFAObj.At(1L) == NULL );
// PT: Probably this statement switches to an ArrayImpl
ASSERT_EQUAL(anyIFAObj.GetSize(), 2 );
ASSERT(anyIFAObj[0L].AsIFAObject() == &testObj );
ASSERT( anyIFAObj[1L] == NULL );
//ASSERT( anyIFAObj[0L].AsString() == testAdr );
ASSERT_EQUAL( "IFAObject", anyIFAObj[0L].AsCharPtr() );
anyIFAObj.Remove(1L);
ASSERT_LESS( anyIFAObj.FindIndex("testSlots"), 0L );
ASSERT_EQUAL( anyIFAObj.IsDefined("testSlots"), false );
ASSERT( anyIFAObj.SlotName(0) == NULL );
ASSERT( anyIFAObj[1L] == NULL );
anyIFAObj.Remove(0L);
ASSERT_EQUAL( (anyIFAObj.At(0L)).AsLong(), 0L );
ASSERT_EQUAL( anyIFAObj[0L].GetType(), AnyNullType );
}
void AnythingConstructorsTest::AnythingConstrTest() {
Anything any0;
Anything anyTest0(any0);
anyTest0.IsEqual(any0);
any0.IsEqual(anyTest0);
Anything any1(0L);
Anything anyTest1(any1);
anyTest1.IsEqual(any1);
any1.IsEqual(anyTest1);
Anything any2(true);
Anything anyTest2(any2);
anyTest2.IsEqual(any2);
any2.IsEqual(anyTest2);
Anything any3((long) 2);
Anything anyTest3(any3);
anyTest3.IsEqual(any3);
any3.IsEqual(anyTest3);
Anything any4((float) 4.1);
Anything anyTest4(any4);
anyTest4.IsEqual(any4);
any4.IsEqual(anyTest4);
Anything any5((double) 5.2);
Anything anyTest5(any5);
anyTest5.IsEqual(any5);
any5.IsEqual(anyTest5);
Anything any6("0123456789");
Anything anyTest6(any6);
anyTest6.IsEqual(any6);
any6.IsEqual(anyTest6);
Anything any7("abcdefgh", 8);
Anything anyTest7(any7);
anyTest7.IsEqual(any7);
any7.IsEqual(anyTest7);
Anything any8(String("Anything Test"));
Anything anyTest8(any8);
anyTest8.IsEqual(any8);
any8.IsEqual(anyTest8);
long buf[5] = { 0, 1, 2, 3, 4 };
Anything any9((void *) &buf[0], (long) sizeof(buf));
Anything anyTest9(any9);
anyTest9.IsEqual(any9);
any9.IsEqual(anyTest9);
DummyIFAObj testObj("Test");
// We use a DummyIFAObj, it is the simplest IFAObject that can be instantiated
Anything any10(&testObj);
Anything anyTest10(any10);
anyTest10.IsEqual(any10);
any10.IsEqual(anyTest10);
}
| 38.531542 | 176 | 0.70694 | [
"object"
] |
7f14a48e5c08487ef58ff6c73ef0286712057826 | 4,659 | cpp | C++ | include/cinolib/geometry/segment.cpp | bbrrck/cinolib | c7cceefd041646e1e1113339e681e212a9bba7e7 | [
"MIT"
] | 1 | 2019-06-22T00:23:45.000Z | 2019-06-22T00:23:45.000Z | include/cinolib/geometry/segment.cpp | snowfox1939/cinolib | 6017d9dd7461e7008df8198563d63526db3ed86a | [
"MIT"
] | null | null | null | include/cinolib/geometry/segment.cpp | snowfox1939/cinolib | 6017d9dd7461e7008df8198563d63526db3ed86a | [
"MIT"
] | null | null | null | /********************************************************************************
* This file is part of CinoLib *
* Copyright(C) 2016: Marco Livesu *
* *
* The MIT License *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *
* IN THE SOFTWARE. *
* *
* Author(s): *
* *
* Marco Livesu (marco.livesu@gmail.com) *
* http://pers.ge.imati.cnr.it/livesu/ *
* *
* Italian National Research Council (CNR) *
* Institute for Applied Mathematics and Information Technologies (IMATI) *
* Via de Marini, 6 *
* 16149 Genoa, *
* Italy *
*********************************************************************************/
#include <cinolib/geometry/segment.h>
namespace cinolib
{
CINO_INLINE
std::ostream & operator<<(std::ostream & in, const Segment & s)
{
in << s.first << "\t" << s.second << "\n";
return in;
}
CINO_INLINE
Segment::Segment(const vec3d & P0, const vec3d & P1)
{
first = P0;
second = P1;
}
CINO_INLINE
double Segment::operator[](const vec3d & p) const
{
return dist_to_point(p);
}
CINO_INLINE
vec3d Segment::project_onto(const vec3d &p) const
{
vec3d v = second - first;
vec3d w = p - first;
float cos_wv = w.dot(v);
float cos_vv = v.dot(v);
if (cos_wv <= 0.0) return first;
if (cos_vv <= cos_wv) return second;
float b = cos_wv / cos_vv;
vec3d Pb = first + v*b;
return Pb;
}
CINO_INLINE
double Segment::dist_to_point(const vec3d & p) const
{
return p.dist(project_onto(p));
}
CINO_INLINE
bool Segment::is_in_between(const vec3d &p) const
{
vec3d v = second - first;
vec3d w = p - first;
float cos_wv = w.dot(v);
float cos_vv = v.dot(v);
if (cos_wv <= 0.0) return false;
if (cos_vv <= cos_wv) return false;
return true;
}
CINO_INLINE
std::vector<Plane> Segment::to_planes() const
{
vec3d d = dir();
vec3d n0(-d.y(), d.x(), 0);
vec3d n1(-d.z(), 0, d.x());
vec3d n2( 0, -d.z(), d.y());
std::vector<Plane> planes;
if (n0.length() > 0) planes.push_back(Plane(first, n0));
if (n1.length() > 0) planes.push_back(Plane(first, n1));
if (n2.length() > 0) if (planes.size() < 2) planes.push_back(Plane(first, n2));
assert(planes.size() == 2);
return planes;
}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::
CINO_INLINE
vec3d Segment::dir() const
{
vec3d d = first-second;
d.normalize();
return d;
}
}
| 35.030075 | 83 | 0.451599 | [
"geometry",
"vector"
] |
7f17df71b65a3eb7ef12f5cc902a158d799b339e | 1,140 | cpp | C++ | May2016/highways.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | May2016/highways.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | May2016/highways.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | //http://www.spoj.com/problems/HIGHWAYS/
#include <cstdio>
#include <queue>
using namespace std;
struct edge {
int v;
int w;
};
bool operator <( edge a, edge b ) {
return a.w < b.w;
}
#define INF 10000000
int dist[ 1000001 ];
void dijkstra( vector< edge > graph[], int N, int S, int T ) {
int i;
for ( i = 0; i <= N; ++i ) {
dist[ i ] = INF;
}
priority_queue< edge > q;
q.push( ( edge ) { S, 0 } );
dist[ S ] = 0;
while ( !q.empty() ) {
edge p = q.top();
q.pop();
for ( i = 0; i < graph[ p.v ].size(); ++i ) {
edge k = graph[ p.v ][ i ];
if ( dist[ p.v ] + k.w < dist[ k.v ] ) {
dist[ k.v ] = dist[ p.v ] + k.w;
q.push( k );
}
}
}
if ( dist[ T ] != INF ) {
printf( "%d\n", dist[ T ] );
}
else {
printf( "NONE\n" );
}
}
int main() {
int t, N, m, s, T;
int u, v, w, i;
scanf( "%d", &t );
while ( t > 0 ) {
scanf( "%d%d%d%d", &N, &m, &s, &T );
vector< edge > graph[ N + 1 ];
for ( i = 0; i < m; ++i ) {
scanf( "%d%d%d", &u, &v, &w );
graph[ u ].push_back( ( edge ) { v, w } );
graph[ v ].push_back( ( edge ) { u, w } );
}
dijkstra( graph, N, s, T );
--t;
}
return 0;
} | 19.655172 | 62 | 0.463158 | [
"vector"
] |
7f19ba322c5c1657004c3d3cfade3e8540d44c4f | 6,301 | cpp | C++ | src/CurvatureJetFit.cpp | Yusheng-cai/InstantaneousInterface | 42ec7c825c6424f0339b2443077bb3505819cde6 | [
"MIT"
] | null | null | null | src/CurvatureJetFit.cpp | Yusheng-cai/InstantaneousInterface | 42ec7c825c6424f0339b2443077bb3505819cde6 | [
"MIT"
] | null | null | null | src/CurvatureJetFit.cpp | Yusheng-cai/InstantaneousInterface | 42ec7c825c6424f0339b2443077bb3505819cde6 | [
"MIT"
] | null | null | null | #include "CurvatureJetFit.h"
namespace CurvatureRegistry
{
registry<CurvatureJetFit> registerJet("jetfit");
}
CurvatureJetFit::CurvatureJetFit(CurvatureInput& input)
:Curvature(input)
{
foundnumneighrs_ = input.pack.ReadNumber("neighbors", ParameterPack::KeyType::Optional, numneighbors_);
input.pack.ReadNumber("degree", ParameterPack::KeyType::Optional, degree_);
input.pack.ReadNumber("MongeCoefficient", ParameterPack::KeyType::Optional, MongeCoefficient_);
outputs_.registerOutputFunc("neighborIndices", [this](std::string name) -> void {this -> printNeighbors(name);});
outputs_.registerOutputFunc("coefficients", [this](std::string name) -> void {this -> printCoefficientPerVertex(name);});
outputs_.registerOutputFunc("PCAeigenvector", [this](std::string name) -> void {this -> printPCAeigenvector(name);});
numpoints_ = (degree_ + 1)*(degree_+2)/2;
}
void CurvatureJetFit::printPCAeigenvector(std::string name)
{
std::ofstream ofs_;
ofs_.open(name);
for (int i=0;i<PCAeigenvector_.size();i++)
{
for (int j=0;j<3;j++)
{
for (int k=0;k<3;k++)
{
ofs_ << PCAeigenvector_[i][j][k] << " ";
}
}
ofs_ << "\n";
}
ofs_.close();
}
void CurvatureJetFit::calculate(Mesh& mesh)
{
initialize(mesh);
mesh.findVertexNeighbors();
const auto& VertexNeighbors_ = mesh.getNeighborIndices();
const auto& vertices = mesh.getvertices();
CurvaturePerVertex_.resize(vertices.size());
avgCurvaturePerVertex_.resize(vertices.size() ,0.0);
GaussCurvaturePerVertex_.resize(vertices.size(),0.0);
principalDir1_.resize(vertices.size());
principalDir2_.resize(vertices.size());
if (foundnumneighrs_)
{
std::cout << "Using number of vertices." << std::endl;
Graph::getNearbyIndicesNVertexAway(VertexNeighbors_,numneighbors_,NeighborIndicesNVertex_);
}
else
{
std::cout << "Using number of neighbors." << std::endl;
Graph::getNNearbyIndices(VertexNeighbors_,numpoints_-1,NeighborIndicesNVertex_);
}
coefficientsPerVertex_.resize(vertices.size());
PCAeigenvector_.resize(vertices.size());
#pragma omp parallel
{
MongeViaJetFitting jetfitterLocal;
#pragma omp for
for (int i=0;i<NeighborIndicesNVertex_.size();i++)
{
std::vector<Dpoint> vec;
Real3 thisPos = vertices[i].position_;
Real3 thisNormal = vertices[i].normals_;
Dpoint point(thisPos[0], thisPos[1], thisPos[2]);
vec.push_back(point);
for (int j=0;j<NeighborIndicesNVertex_[i].size();j++)
{
int neighborIndex = NeighborIndicesNVertex_[i][j];
Real3 vertpos = vertices[neighborIndex].position_;
Dpoint point(vertpos[0], vertpos[1], vertpos[2]);
vec.push_back(point);
}
ASSERT((vec.size() >= numpoints_), "The neighbors for indices " << i << " " << vec.size() << " is not enough for fitting for degree " << degree_ <<\
" which has to be at least " << numpoints_);
auto mform = jetfitterLocal(vec.begin(), vec.end(), degree_, MongeCoefficient_);
for (int j=0;j<3;j++)
{
for (int k=0;k<3;k++)
{
PCAeigenvector_[i][j][k] = jetfitterLocal.pca_basis(j).second[k];
}
}
DVector norm(-thisNormal[0], -thisNormal[1], -thisNormal[2]);
mform.comply_wrt_given_normal(norm);
#ifdef MY_DEBUG
std::cout << "Origin = " << mform.origin() << std::endl;
std::cout << "Position1 = " << vec_[0] << std::endl;
std::cout << "vertex position = " << vertices[i].position_[0] << " " << vertices[i].position_[1] << " " << vertices[i].position_[2] << std::endl;
#endif
std::vector<Real> coeff;
for (int i=0;i<mform.coefficients().size();i++)
{
coeff.push_back(mform.coefficients()[i]);
}
coefficientsPerVertex_[i] = coeff;
CurvaturePerVertex_[i][0] = mform.principal_curvatures(0);
CurvaturePerVertex_[i][1] = mform.principal_curvatures(1);
DVector vec1 = mform.maximal_principal_direction();
DVector vec2 = mform.minimal_principal_direction();
Real3 v;
Real3 v2;
for (int j=0;j<3;j++)
{
v[j] = vec1[j];
v2[j] = vec2[j];
}
principalDir1_[i] = v;
principalDir2_[i] = v2;
}
#pragma omp for
for (int i=0;i<CurvaturePerVertex_.size();i++)
{
Real avg=0.0;
Real gauss = 1.0;
for (int j=0;j<2;j++)
{
gauss *= CurvaturePerVertex_[i][j];
avg += CurvaturePerVertex_[i][j]/2.0;
}
avgCurvaturePerVertex_[i] = avg;
GaussCurvaturePerVertex_[i] = gauss;
}
}
}
void CurvatureJetFit::printNeighbors(std::string name)
{
std::ofstream ofs_;
ofs_.open(name);
for (int i=0;i<NeighborIndicesNVertex_.size();i++)
{
int neighborsize = NeighborIndicesNVertex_[i].size();
// print self first
ofs_ << i << " ";
for (int j=0;j<neighborsize;j++)
{
ofs_ << NeighborIndicesNVertex_[i][j] << " ";
}
ofs_ << "\n";
}
ofs_.close();
}
void CurvatureJetFit::printCoefficientPerVertex(std::string name)
{
std::ofstream ofs_;
ofs_.open(name);
ofs_ << "# ";
for (int i=0;i<coefficientsPerVertex_[0].size();i++)
{
ofs_ << "coefficient" << i+1 << " ";
}
ofs_ << "\n";
for (int i=0;i<coefficientsPerVertex_.size();i++)
{
int sizePerVertex = coefficientsPerVertex_[i].size();
for (int j=0;j<sizePerVertex;j++)
{
if (j != sizePerVertex-1)
{
ofs_ << coefficientsPerVertex_[i][j] << " ";
}
else
{
ofs_ << coefficientsPerVertex_[i][j] << "\n";
}
}
}
ofs_.close();
} | 31.039409 | 160 | 0.556102 | [
"mesh",
"vector"
] |
7f1a218c7d539607d308d4e06af4b35d82fca601 | 1,346 | cpp | C++ | C++/problems/0181_maximum_distance_closest_person.cpp | raulhsant/algorithms | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | [
"MIT"
] | 6 | 2019-03-20T22:23:26.000Z | 2020-08-28T03:10:27.000Z | C++/problems/0181_maximum_distance_closest_person.cpp | raulhsant/algorithms | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | [
"MIT"
] | 15 | 2019-10-13T20:53:53.000Z | 2022-03-31T02:01:35.000Z | C++/problems/0181_maximum_distance_closest_person.cpp | raulhsant/algorithms | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | [
"MIT"
] | 3 | 2019-03-11T10:57:46.000Z | 2020-02-26T21:13:21.000Z | // Problem Statement
// You are given an array representing a row of seats where seats[i] = 1
// represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
// There is at least one empty seat, and at least one person sitting.
// Alex wants to sit in the seat such that the distance between him and the
// closest person to him is maximized.
// Return that maximum distance to the closest person.
#include "0181_maximum_distance_closest_person.hpp"
#include <bits/stdc++.h>
using namespace std;
int Solution::maxDistToClosest(vector<int>& seats){
int tam = seats.size(),result=0;
vector<int> left(tam,-1), right(tam,tam);
for(int i=0;i<tam;i++){
if(seats[i]==1){
left[i]=i;
}else if(i>0){
left[i] = left[i-1];
}
}
for(int i=tam-1;i>=0;i--){
if(seats[i]==1){
right[i]=i;
}else if(i<tam-1){
right[i] = right[i+1];
}
}
for(int i=0;i<tam;i++){
int distLeft = INT_MAX,distRight = INT_MAX;
if(left[i]!=-1){
distLeft = i-left[i];
}
if(right[i]!=tam){
distRight = right[i]-i;
}
result = max(result,min(distLeft,distRight));
}
return result;
} | 26.392157 | 115 | 0.557207 | [
"vector"
] |
7f1d4a83409d1dce08d6be0f46e672a82564ce53 | 2,428 | cpp | C++ | src/MandelApp.cpp | mhhollomon/mandel | 9c5658b5b5433d80474e13930a69cedf3574e802 | [
"MIT"
] | null | null | null | src/MandelApp.cpp | mhhollomon/mandel | 9c5658b5b5433d80474e13930a69cedf3574e802 | [
"MIT"
] | null | null | null | src/MandelApp.cpp | mhhollomon/mandel | 9c5658b5b5433d80474e13930a69cedf3574e802 | [
"MIT"
] | null | null | null | #include "MandelWin.hpp"
#include "MandelApp.hpp"
#include <gtkmm.h>
MandelApp::MandelApp(int& argc, char**& argv,
const Glib::ustring& application_id,
Gio::ApplicationFlags flags)
: Gtk::Application(application_id, flags),
clopts_{parse_commandline(argc, argv)}
{
Glib::set_application_name("Mandel");
}
Glib::RefPtr<MandelApp> MandelApp::create( int& argc, char**& argv,
const Glib::ustring& application_id,
Gio::ApplicationFlags flags)
{
return Glib::RefPtr<MandelApp>(new MandelApp(argc, argv, application_id, flags));
}
void MandelApp::on_startup() {
//Call the base class's implementation:
Gtk::Application::on_startup();
_create_menubar();
}
void MandelApp::on_activate() {
_create_window();
}
void MandelApp::_create_window() {
auto win = new MandelWin(clopts_);
//Make sure that the application runs for as long this window is still open:
add_window(*win);
//Delete the window when it is hidden.
//That's enough for this simple example.
win->signal_hide().connect(sigc::bind<Gtk::Window*>(
sigc::mem_fun(*this, &MandelApp::on_window_hide), win));
win->show_all();
}
void MandelApp::on_menu_file_quit() {
std::vector<Gtk::Window*> windows = get_windows();
if (windows.size() > 0)
windows[0]->hide(); // In this simple case, we know there is only one window.
}
void MandelApp::on_window_hide(Gtk::Window* window) {
delete window;
}
//
// ###############################################
// Menu Bar
// ##############################################
const char* ui_info =
"<interface>"
" <menu id='menubar'>"
" <submenu>"
" <attribute name='label' translatable='yes'>_File</attribute>"
" <section>"
" <item>"
" <attribute name='label' translatable='yes'>_Quit</attribute>"
" <attribute name='action'>app.quit</attribute>"
" <attribute name='accel'><Primary>q</attribute>"
" </item>"
" </section>"
" </submenu>"
" </menu>"
"</interface>";
void MandelApp::_create_menubar() {
add_action("quit", sigc::mem_fun(*this, &MandelApp::on_menu_file_quit));
builder_ = Gtk::Builder::create();
builder_->add_from_string(ui_info);
auto object = builder_->get_object("menubar");
auto gmenu = Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
set_menubar(gmenu);
}
| 26.681319 | 85 | 0.613262 | [
"object",
"vector"
] |
7f20904c5386f13857990873f4fb5df3339f8bad | 4,344 | cpp | C++ | libs/graph_parallel/test/distributed_async_bfs_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | 1 | 2021-09-03T10:22:04.000Z | 2021-09-03T10:22:04.000Z | libs/graph_parallel/test/distributed_async_bfs_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | libs/graph_parallel/test/distributed_async_bfs_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2011-2012 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Nick Edmonds
// Simple asyncrhonous BFS implementation, of course you could also
// use async_breadth_first_search from
// boost/graph/distributed/breadth_first_searc.hpp
#include <am++/am++.hpp>
#include <am++/mpi_transport.hpp>
#include <boost/graph/use_mpi.hpp>
#include <boost/graph/distributed/compressed_sparse_row_graph.hpp>
#include <boost/property_map/parallel/distributed_property_map.hpp>
#include <boost/graph/small_world_generator.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/test/minimal.hpp>
#include <boost/lexical_cast.hpp>
#define COALESCED_SIZE 4096
using namespace boost;
typedef boost::graph_traits<compressed_sparse_row_graph<directedS,
no_property, no_property, no_property,
distributedS<> > >::vertex_descriptor Vertex;
typedef std::pair<Vertex, std::size_t> bfs_distance_data;
template <typename Graph, typename DistanceMap>
struct async_bfs_handler {
typedef amplusplus::basic_coalesced_message_type<bfs_distance_data, async_bfs_handler>
async_bfs_message_type;
typedef typename property_traits<DistanceMap>::value_type distance_type;
async_bfs_handler() {}
async_bfs_handler(Graph& g, DistanceMap& dist, async_bfs_message_type& msg)
: g(&g), distance(&dist), bfs_msg(&msg) {}
void operator() (int /* source */, const bfs_distance_data& data)
{
typename graph_traits<Graph>::vertex_descriptor v = data.first;
/* volatile */ distance_type old_dist;
distance_type new_dist = data.second;
do {
old_dist = get(*distance, v);
if (new_dist >= old_dist) return;
} while (!exchange(*distance, v, old_dist, new_dist));
// TODO: Explore all out edges of v
BGL_FORALL_ADJ_T(v, u, *g, Graph) {
bfs_msg->send(std::make_pair(u, new_dist + 1), get(get(vertex_owner, *g), u));
}
}
protected:
Graph* g;
DistanceMap* distance;
async_bfs_message_type* bfs_msg;
};
int test_main(int argc, char* argv[])
{
amplusplus::environment env = amplusplus::mpi_environment(argc, argv, true);
amplusplus::transport trans = env.create_transport();
int num_threads = 1;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "--threads")
num_threads = boost::lexical_cast<int>( argv[i+1] );
}
typedef compressed_sparse_row_graph<directedS, no_property, no_property, no_property,
distributedS<> >
Digraph;
// Build a Watts-Strogatz graph to test with
typedef small_world_iterator<minstd_rand, Digraph> SWIter;
int n = 100, k = 4;
double prob = 0.05;
minstd_rand gen;
gen.seed(1);
Digraph g(edges_are_unsorted, SWIter(gen, n, k, prob), SWIter(), n, trans);
// Distance map
std::vector<std::size_t> distanceS(num_vertices(g), std::numeric_limits<std::size_t>::max());
typedef iterator_property_map<std::vector<std::size_t>::iterator,
property_map<Digraph, vertex_index_t>::type>
DistanceMap;
DistanceMap distance(distanceS.begin(), get(vertex_index, g));
// Messages
amplusplus::register_mpi_datatype<bfs_distance_data>();
typedef async_bfs_handler<Digraph, DistanceMap> Handler;
typedef amplusplus::basic_coalesced_message_type<bfs_distance_data, Handler>
async_bfs_message_type;
async_bfs_message_type async_bfs_msg(amplusplus::basic_coalesced_message_type_gen(COALESCED_SIZE), trans);
//
// TODO: Add addressing to message type
//
async_bfs_msg.set_handler(Handler(g, distance, async_bfs_msg));
// Single threaded since we'd have to fork inside the coalesced messages
{
amplusplus::scoped_epoch epoch(trans);
async_bfs_msg.send(std::make_pair(vertex(0, g), 0), get(get(vertex_owner, g), vertex(0, g)));
}
int visited = 0;
BGL_FORALL_VERTICES(v, g, Digraph) {
if (get(distance, v) < std::numeric_limits<std::size_t>::max())
++visited;
}
std::cerr << trans.rank() << ": visited " << visited << " vertices of " << num_vertices(g) << std::endl;
return 0;
}
| 32.661654 | 108 | 0.707643 | [
"vector"
] |
7f213b32747176698592b89f29f43af5deb73af9 | 952 | cpp | C++ | test/source/test_low_discr_seq_n.cpp | luk036/lds-cpp | d48f7c7b2848dd7dfa523b1da81a48801670717c | [
"Unlicense"
] | null | null | null | test/source/test_low_discr_seq_n.cpp | luk036/lds-cpp | d48f7c7b2848dd7dfa523b1da81a48801670717c | [
"Unlicense"
] | null | null | null | test/source/test_low_discr_seq_n.cpp | luk036/lds-cpp | d48f7c7b2848dd7dfa523b1da81a48801670717c | [
"Unlicense"
] | null | null | null | #include <doctest/doctest.h> // for Approx, ResultBuilder, TestCase
#include <gsl/span> // for span
#include <lds/low_discr_seq_n.hpp> // for cylin_n, halton_n, sphere3, sphere_n
#include <vector> // for vector
TEST_CASE("sphere3") {
unsigned base[] = {2, 3, 5, 7};
auto sp3gen = lds::sphere3(base);
auto [x1, x2, x3, x4] = sp3gen();
CHECK(x1 == doctest::Approx(0.8966646826));
}
TEST_CASE("halton_n") {
unsigned base[] = {2, 3, 5, 7};
auto hgen = lds::halton_n(base);
auto res = hgen();
CHECK(res[0] == doctest::Approx(0.5));
}
TEST_CASE("cylin_n") {
unsigned base[] = {2, 3, 5, 7};
auto cygen = lds::cylin_n(base);
auto res = cygen();
CHECK(res[0] == doctest::Approx(0.5896942325));
}
TEST_CASE("sphere_n") {
unsigned base[] = {2, 3, 5, 7};
auto spgen = lds::sphere_n(base);
auto res = spgen();
CHECK(res[0] == doctest::Approx(0.6092711237));
}
| 28 | 79 | 0.581933 | [
"vector"
] |
7f23ee5d6d84335ad36da8fef4b5498ed843f80a | 25,075 | cpp | C++ | metaCode/LUTCode2/Source.cpp | chenjiunfeng/openMaelstrom | 6dc6ffe3501f056eb83d1d6306d2ac5ec754c192 | [
"MIT"
] | 45 | 2019-11-07T13:51:50.000Z | 2022-02-11T01:51:14.000Z | metaCode/LUTCode2/Source.cpp | chenjiunfeng/openMaelstrom | 6dc6ffe3501f056eb83d1d6306d2ac5ec754c192 | [
"MIT"
] | 2 | 2020-03-06T20:25:02.000Z | 2021-02-07T21:45:39.000Z | metaCode/LUTCode2/Source.cpp | chenjiunfeng/openMaelstrom | 6dc6ffe3501f056eb83d1d6306d2ac5ec754c192 | [
"MIT"
] | 10 | 2019-08-22T09:11:23.000Z | 2022-02-07T07:04:55.000Z | #include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <tuple>
#include <utility/include_all.h>
#include <utility/iterator.h>
#include <utility/math.h>
#include <utility/unit_math.h>
#include <vector>
auto generateHexGrid(float h, float r, bool center = true, float scale = 1.0f) {
float H = h * kernelSize();
auto gen_position = [&](auto r, int32_t i, int32_t j, int32_t k) {
float4 initial{ 2.0f * i + ((j + k) % 2), sqrt(3.f) * (j + 1.0f / 3.0f * (k % 2)), 2.0f * sqrt(6.0f) / 3.0f * k, h / r };
return initial * r;
};
int32_t requiredSlices_x = (int32_t)math::ceilf(scale * H / r);
int32_t requiredSlices_y = (int32_t)math::ceilf(scale * H / (sqrt(3.0f) * r));
int32_t requiredSlices_z = (int32_t)math::ceilf(scale * H / r * 3.0f / (sqrt(6.0f) * 2.0f));
std::vector<float4> positions;
for (int32_t x_it = -requiredSlices_x; x_it <= requiredSlices_x; x_it++)
for (int32_t y_it = -requiredSlices_y; y_it <= requiredSlices_y; y_it++)
for (int32_t z_it = -requiredSlices_z; z_it <= requiredSlices_z; z_it++)
if (center || (!center && (x_it != 0 || y_it != 0 || z_it != 0)))
positions.push_back(gen_position(r, x_it, y_it, z_it));
return positions;
}
#define CALC_CONSTANTS
#ifdef CALC_CONSTANTS
constexpr auto volume = 1.f;
auto radius = powf(volume, 1.f / 3.f) * PI4O3_1;
auto h = support_from_volume(volume);
auto H = h * kernelSize();
auto getPacking() {
int32_t it = 0;
auto spacing = math::brentsMethod(
[&](auto r) {
auto positions = generateHexGrid(h, r, true, 1.0f);
auto positionsL = generateHexGrid(h, r, true, 2.0f);
float error = 0.0f;
for (const auto& pos : positions) {
float density = -1.0f;
for (const auto& posL : positionsL)
density += volume * spline4_kernel(posL, pos);
error += density;
}
std::cout << r << "[" << it++ << "] -> " << error << std::endl;
return error;
},
radius * 0.75f, radius * 8.0f, 1e-5f, 100);
return spacing;
}
auto spacing = getPacking();
#else
constexpr auto H = 0x1.2487b0p+1f;
constexpr auto h = 0x1.407358p+0f;
constexpr auto r = 0x1.e8ec8ap-3f;
constexpr auto V = 0x1.000000p+0f;
constexpr auto s = 0x1.1ece3cp-1f;
#endif
constexpr auto lutSize = 1024;
constexpr auto integralSize = 16*1024;
template<typename C>
auto generateLUT(C&& func) {
float4 c{ 0.f,0.f,0.f,h };
using res_t = double;// decltype(func(c, std::declval<float4>()));
std::array<res_t, lutSize> LUT;
float dd = 2.f * H / ((float)lutSize - 1);
for (auto di = 0; di < lutSize; ++di) {
auto n = integralSize;
double dh = H / ((double)n);
double d = H - dd * (double)(di);
res_t integral = vector_t<double, math::dimension_v<res_t>>::zero();
#pragma omp parallel for reduction(+ : integral)
for (auto ni = 0; ni < n; ++ni) {
double xl = dh * (double)ni;
double xh = dh * (double)ni + dh;
float4 p{ (float) xl + 0.5f * (float)dh, 0.f, 0.f, h };
double hl = math::clamp(xl - d, 0.f, 2.f * xl);
double hh = math::clamp(xh - d, 0.f, 2.f * xh);
double Vl = CUDART_PI_F * hl * hl / 3.f * (3.f * xl - hl);
double Vh = CUDART_PI_F * hh * hh / 3.f * (3.f * xh - hh);
double dV = Vh - Vl;
integral += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d) / H));
}
LUT[di] = integral;
}
std::reverse(LUT.begin(), LUT.end());
return LUT;
}
constexpr float t = 0.0001f;
template<typename C>
auto gradientLUT(C&& func) {
float4 c{ 0.f,0.f,0.f,h };
using res_t = double;// decltype(func(c, std::declval<float4>()));
std::array<res_t, lutSize> LUT;
double dd = 2.f * H / ((double)lutSize - 1);
for (auto di = 0; di < lutSize; ++di) {
constexpr auto n = integralSize;
double dh = H / ((double)n);
double d = H - dd * (double)(di);
res_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();
#pragma omp parallel for reduction(+ : integralp)
for (auto ni = 0; ni < n; ++ni) {
double xl = dh * (double)ni;
double xh = dh * (double)ni + dh;
float4 p{ (float) xl + 0.5f * (float) dh, 0.f, 0.f, h };
double hl = math::clamp(xl - d + t, 0., 2. * xl);
double hh = math::clamp(xh - d + t, 0., 2. * xh);
double Vl = CUDART_PI * hl * hl / 3. * (3. * xl - hl);
double Vh = CUDART_PI * hh * hh / 3. * (3. * xh - hh);
double dV = Vh - Vl;
integralp += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d - t) / H));
}
res_t integraln = vector_t<double, math::dimension_v<res_t>>::zero();
#pragma omp parallel for reduction(+ : integraln)
for (auto ni = 0; ni < n; ++ni) {
double xl = dh * (double)ni;
double xh = dh * (double)ni + dh;
float4 p{ (float)xl + 0.5f * (float)dh , 0.f, 0.f, h };
double hl = math::clamp(xl - d - t, 0., 2. * xl);
double hh = math::clamp(xh - d - t, 0., 2. * xh);
double Vl = CUDART_PI_F * hl * hl / 3. * (3. * xl - hl);
double Vh = CUDART_PI_F * hh * hh / 3. * (3. * xh - hh);
double dV = Vh - Vl;
integraln += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d + t) / H));
}
LUT[di] = (integralp - integraln) / (2.0 * t);
}
std::reverse(LUT.begin(), LUT.end());
return LUT;
}
template<typename T>
auto lookup (const std::array<T, lutSize> LUT, float x) {
auto xRel = ((x + H) / (2.f * H)) * ((float)lutSize - 1.f);
auto xL = math::floorf(xRel);
auto xH = math::ceilf(xRel);
auto xD = xRel - xL;
int32_t xLi = math::clamp(static_cast<int32_t>(xL), 0, lutSize - 1);
int32_t xHi = math::clamp(static_cast<int32_t>(xH), 0, lutSize - 1);
auto lL = LUT[xLi];
auto lH = LUT[xHi];
return lL * xD + (1.f - xD) * lH;
};
#include <config/config.h>
#include <fstream>
#ifdef _WIN32
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#endif
auto writeLUT(const std::string& name, const std::string& type, const std::array<double, lutSize>& LUT) {
fs::path bin_dir(sourceDirectory);
auto file = bin_dir / "cfg" / name;
file.replace_extension("lut");
if (fs::exists(file)) {
if (fs::exists(__FILE__)) {
auto input_ts = fs::last_write_time(__FILE__);
auto output_ts = fs::last_write_time(file);
if (input_ts <= output_ts) {
return;
}
}
}
std::cout << "Writing " << file.string() << std::endl;
std::ofstream output(file.string());
//output << "std::vector<" << type << "> " << name << "{ ";
int32_t ctr = 0;
for (auto v : LUT) {
output << std::scientific << std::setprecision(std::numeric_limits<float>::digits10 + 1)
<< static_cast<float>(v) << " ";
}
//output << "};" << std::endl;
output.close();
}
auto sphericalGradientIntegral(const std::function<double(float4, float4, float)>& func, int32_t phiSlices, int32_t thetaSlices, int32_t radiusSteps) {
float4 c{ 0.f,0.f,0.f,h };
using res_t = double;
std::array<res_t, lutSize> LUT;
double dd = 2.f * H / ((double)lutSize - 1);
for (auto di = 0; di < lutSize; ++di) {
auto n = radiusSteps;
double dh = H / ((double)n);
double d = H - dd * (double)(di);
double dTheta = (2.0 * CUDART_PI) / (double)thetaSlices;
double dPhi = (CUDART_PI) / (double)phiSlices;
res_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();
#pragma omp parallel for
for (auto iR = 0; iR < radiusSteps; ++iR) {
double xl = dh * (double)iR;
double xh = dh * (double)iR + dh;
float r = (float) xl + 0.5f * (float)dh;
double Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;
double Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;
double dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;
res_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iTheta = 0.0; iTheta < 2.0 * CUDART_PI; iTheta += dTheta) {
res_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iPhi = 0.0; iPhi < CUDART_PI; iPhi += dPhi) {
double theta = iTheta + dTheta * 0.5;
double phi = iPhi + dPhi * 0.5;
double x = r * cos(theta) * sin(phi);
double y = r * sin(theta) * sin(phi);
double z = r * cos(phi);
if (x < d + t)
continue;
float4 p{ (float)x, (float)y, (float)z, h };
phiSum += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, d + t));
}
thetaSum += phiSum;
}
integralp += thetaSum;
}
res_t integraln = vector_t<double, math::dimension_v<res_t>>::zero();
#pragma omp parallel for
for (auto iR = 0; iR < radiusSteps; ++iR) {
double xl = dh * (double)iR;
double xh = dh * (double)iR + dh;
float r = (float)xl + 0.5f * (float)dh;
double Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;
double Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;
double dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;
res_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iTheta = 0.0; iTheta < 2.0 * CUDART_PI; iTheta += dTheta) {
res_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iPhi = 0.0; iPhi < CUDART_PI; iPhi += dPhi) {
double theta = iTheta + dTheta * 0.5;
double phi = iPhi + dPhi * 0.5;
double x = r * cos(theta) * sin(phi);
double y = r * sin(theta) * sin(phi);
double z = r * cos(phi);
if (x < d - t)
continue;
float4 p{ (float)x, (float)y, (float)z, h };
phiSum += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, d - t));
}
thetaSum += phiSum;
}
integraln += thetaSum;
}
LUT[di] = (integralp - integraln) / (2.0 * t);
}
std::reverse(LUT.begin(), LUT.end());
return LUT;
}
void progressBar(int32_t frame, int32_t frameTarget, float progress) {
std::ios cout_state(nullptr);
cout_state.copyfmt(std::cout);
static auto startOverall = std::chrono::high_resolution_clock::now();
static auto startFrame = startOverall;
static auto lastTime = startOverall;
static int32_t lastFrame = frame;
//if (frame != lastFrame) {
// lastFrame = frame;
if(frame == 0)
startFrame = std::chrono::high_resolution_clock::now();
//}
auto now = std::chrono::high_resolution_clock::now();
lastTime = now;
int barWidth = 128;
std::cout << "Generating " << std::setw(4) << frame;
if (frameTarget != -1)
std::cout << "/" << std::setw(4) << frameTarget;
std::cout << " [";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << std::setw(3) << int(progress * 100.0) << " ";
auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(now - startFrame);
if (dur.count() < 100 || progress < 1e-3f) {
std::cout << " ---/---s ";
}
else {
auto totalTime = ((float)std::chrono::duration_cast<std::chrono::microseconds>(now - startFrame).count()) / 1000.f / 1000.f;
std::cout << std::fixed << std::setprecision(0) << " " << std::setw(3) << totalTime << "/" << std::setw(3) << (totalTime / progress) << "s ";
}
std::cout << "\r";
std::cout.flush();
std::cout.copyfmt(cout_state);
}
auto sphericalIntegral(const std::function<double(float4, float4, float)>& func, int32_t phiSlices, int32_t thetaSlices, int32_t radiusSteps) {
float4 c{ 0.f,0.f,0.f,h };
using res_t = double;
std::array<res_t, lutSize> LUT;
double dd = 2.f * H / ((double)lutSize - 1);
//std::vector<double> thetaSum(thetaSlices);
//std::vector<double> phiSum(phiSlices);
for (auto di = 0; di < lutSize; ++di) {
progressBar(di, lutSize, (double)di / (double)lutSize);
auto n = radiusSteps;
double dh = H / ((double)n);
double d = -H + dd * (double)(di);
double dTheta = (2.0 * CUDART_PI) / (double)thetaSlices;
double dPhi = (CUDART_PI) / (double)phiSlices;
res_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();
double dVSum = 0.0;
#pragma omp parallel for
for (auto iR = 0; iR < radiusSteps; ++iR) {
double xl = dh * (double)iR;
double xh = dh * (double)iR + dh;
float r = (float)xl + 0.5f * (float)dh;
double Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;
double Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;
double dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;
res_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iTheta = 0; iTheta < thetaSlices; iTheta++) {
res_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();
for (auto iPhi = 0; iPhi < phiSlices; iPhi++) {
double theta = ((double)iTheta) * dTheta;// +dTheta * 0.5;
double phi = ((double)iPhi) * dPhi;// +dPhi * 0.5;
double x = r * cos(theta) * sin(phi);
double y = r * sin(theta) * sin(phi);
double z = r * cos(phi);
if (x < d)
phiSum += 0.0;
else {
float4 p{ (float)x, (float)y, (float)z, h };
phiSum += math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (x - d) / (1.0 * H)));
}
}
//std::sort(phiSum.begin(), phiSum.end());
thetaSum += phiSum;
}
//std::sort(thetaSum.begin(), thetaSum.end());
//integralp += dV * std::reduce(thetaSum.begin(), thetaSum.end());
integralp += dV * thetaSum;
}
LUT[di] = integralp;
//break;
}
std::cout << std::endl;
//std::reverse(LUT.begin(), LUT.end());
return LUT;
}
auto approximateGradient(const std::array<double, lutSize>& LUT, const std::array<double, lutSize>& vLUT) {
std::array<double, lutSize> gLUT;
for (auto& e : gLUT) e = 0.0;
for (int32_t i = 0; i < lutSize - 1; ++i) {
auto vi1 = 1.f; //vLUT[i + 1];
auto vi = 1.f; //vLUT[i];
vi1 = vi1 < 1e-5f ? vi : vi1;
gLUT[i] = (LUT[i + 1] / vi1 - LUT[i] / vi) / (2.0 * H / (double)lutSize) * vi;
}
gLUT[lutSize - 1] = gLUT[lutSize - 2];
return gLUT;
}
auto smoothLUT(const std::array<double, lutSize>& LUT) {
std::array<double, lutSize> gLUT;
gLUT = LUT;
for (int32_t i = 1; i < lutSize - 1; ++i) {
if(LUT[i-1] < LUT[i])
gLUT[i] = (LUT[i - 1] + LUT[i + 1])*0.5;
}
return gLUT;
}
#include <omp.h>
int main(int32_t argc, char** argv) {
omp_set_num_threads(12);
#ifdef CALC_CONSTANTS
std::ios cout_state(nullptr);
cout_state.copyfmt(std::cout);
std::cout << std::hexfloat << "H = " << H << std::endl;
std::cout << std::hexfloat << "h = " << h << std::endl;
std::cout << std::hexfloat << "radius = " << radius << std::endl;
std::cout << std::hexfloat << "volume = " << volume << std::endl;
std::cout << std::hexfloat << "spacing = " << spacing << std::endl;
std::cout.copyfmt(cout_state);
std::cout << "H = " << H << std::endl;
std::cout << "h = " << h << std::endl;
std::cout << "radius = " << radius << std::endl;
std::cout << "volume = " << volume << std::endl;
std::cout << "spacing = " << spacing << std::endl;
std::cout.copyfmt(cout_state);
#endif
std::cout << "Running LUT generation code." << std::endl;
//#ifdef WIN32
// HWND console = GetConsoleWindow();
// RECT _r;
// GetWindowRect(console, &_r);
// MoveWindow(console, 0, 0, 1920, 1200, TRUE);
//#endif
//std::cout << "H = " << H << std::endl;
//std::cout << "h = " << h << std::endl;
//std::cout << "radius = " << r << std::endl;
//std::cout << "volume = " << V << std::endl;
//std::cout << "spacing = " << s << std::endl;
//std::cout << "Spherical Integral: " << << std::endl;
//std::cout << "Analytical: " << CUDART_PI * 4.0 / 3.0 * H * H * H << std::endl;
//std::array densityLUT = sphericalIntegral([](float4 c, float4 p, float d) {return kernel(c, p); }, 128, 128, 128);
//std::cout << "Generated density LUT" << std::endl;
float dFactor = 0.f;// 0.f;// 1.5f;
std::array densityLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * kernel(c, p); });
writeLUT("density", "float", densityLUT);
auto lookup = [&](auto x) {
float xRel = ((x + 1.f) / 2.f)* ((float)lutSize - 1.f);
auto xL = math::floorf(xRel);
auto xH = math::ceilf(xRel);
auto xD = xRel - xL;
int32_t xLi = math::clamp(static_cast<int32_t>(xL), 0, lutSize - 1);
int32_t xHi = math::clamp(static_cast<int32_t>(xH), 0, lutSize - 1);
auto lL = densityLUT[xLi];
auto lH = densityLUT[xHi];
auto val = lL * xD + (1.f - xD) * lH;
return val;
};
auto findX = [&](auto x) {
float f = -1.f;
int32_t n = 8;
for (int32_t n = 1; n < 11; ++n) {
auto fx = lookup(f);
//std::cout << "Starting at " << f << " : " << fx << " with dx = " << powf(0.5f, (float)n) << std::endl;
while (n % 2 == 1 ? fx > x + 0.001f : fx < x - 0.001f){
f += (n % 2 == 1 ? 1.f : -1.f) * powf(0.5f, (float)n);
fx = lookup(f);
//std::cout << f << " -> " << fx << std::endl;
}
}
//std::cout << f << " - " << lookup(f) << " <-> " << x << std::endl;
return f;
};
std::array<double, lutSize> offsetLUT;
for (int32_t i = 0; i < lutSize; ++i) {
float f = (float) i / (float)lutSize;
offsetLUT[i] = /*0.24509788f*/ -0.f* findX(f);
}
//std::reverse(offsetLUT.begin(), offsetLUT.end());
writeLUT("offsetLUT", "float", offsetLUT);
//findX(0.5f);
std::array spline2LUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * (1.f + dFactor * d) * math::dot3(gradient(c, p), gradient(c, p)); });
writeLUT("spline2", "float", spline2LUT);
std::array spikyLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * PressureKernel<kernel_kind::spline4>::value(c,p); });
writeLUT("spiky", "float", spikyLUT);
std::array splineLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * kernel(c, p); });
writeLUT("spline", "float", splineLUT);
std::array cohesionLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * Kernel<kernel_kind::cohesion>::value(c, p).x; });
for (int32_t i = 1; i < cohesionLUT.size(); ++i) {
cohesionLUT[i] = abs(cohesionLUT[i]) < 1e-12 ? cohesionLUT[i - 1] : cohesionLUT[i];
}
writeLUT("cohesion", "float", cohesionLUT);
std::array adhesionLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * Kernel<kernel_kind::adhesion>::value(c, p).x; });
for (int32_t i = 1; i < adhesionLUT.size(); ++i) {
adhesionLUT[i] = abs(adhesionLUT[i]) < 1e-12 ? adhesionLUT[i - 1] : adhesionLUT[i];
}
writeLUT("adhesion", "float", adhesionLUT);
std::array volumeLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d); });
//for (auto& v : volumeLUT)
// v = 1.f;
writeLUT("volume", "float", volumeLUT);
////std::cout << adhesion0 << std::endl;
//std::array spikyGradientLUT = generateLUT([&](float4 c, float4 p, float d) {
// return -((1.f + dFactor * d) * SpikyKernel<kernel_kind::spline4>::gradient(c, p).x); });
std::array spikyGradientLUT = approximateGradient(spikyLUT, volumeLUT);
for (int32_t i = 1; i < spikyGradientLUT.size(); ++i) {
//spikyGradientLUT[i] = fabsf(spikyGradientLUT[i]) < 1e-12f ? spikyGradientLUT[i - 1] : spikyGradientLUT[i];
}
//std::array spikyGradientLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f) * SpikyKernel<kernel_kind::spline4>::gradient(c, p).x ; });
//for (auto& v : spikyGradientLUT)
//v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);
writeLUT("spikyGradient", "float", spikyGradientLUT);
std::array splineGradientLUT = approximateGradient(splineLUT, volumeLUT);
for (int32_t i = 1; i < splineGradientLUT.size(); ++i) {
//splineGradientLUT[i] = fabsf(splineGradientLUT[i]) < 1e-12f ? splineGradientLUT[i - 1] : splineGradientLUT[i];
}
//std::array splineGradientLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f ) * gradient(c, p).x; });
//for (auto& v : splineGradientLUT)
// v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);
writeLUT("splineGradient", "float", splineGradientLUT);
//std::array densityLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return kernel(c, p); }, 127, 127, 127);
auto chi = [&](auto d) {
return 1.f + dFactor * d;
//return math::clamp(1.0 / lookup(densityLUT, -d * HforV1) + d,1.0,4.0);
};
//densityLUT = smoothLUT(densityLUT);
//std::cout << "Generated density LUT" << std::endl;
//writeLUT("density", "float", densityLUT);
//std::array splineLUTN = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * kernel(c, p); }, 127, 127, 127);
//splineLUTN = smoothLUT(splineLUTN);
//std::cout << "Generated spline LUT" << std::endl;
//writeLUT("splinePolar", "float", splineLUTN);
//std::array splineGradientLUTN = approximateGradient(splineLUTN);
//std::cout << "Generated spline Gradient LUT" << std::endl;
//writeLUT("splineGradientPolar", "float", splineGradientLUTN);
//std::array spikyLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * SpikyKernel<kernel_kind::spline4>::value(c, p); }, 128, 128, 128);
//spikyLUT = smoothLUT(spikyLUT);
//std::cout << "Generated spiky LUT" << std::endl;
//writeLUT("spiky", "float", spikyLUT);
//std::array spikyGradientLUT = approximateGradient(spikyLUT);
//std::cout << "Generated spiky Gradient LUT" << std::endl;
//writeLUT("spikyGradient", "float", spikyGradientLUT);
//std::array cohesionLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * Kernel<kernel_kind::cohesion>::value(c, p).x; }, 128, 128, 128);
//std::cout << "Generated cohesion LUT" << std::endl;
//writeLUT("cohesion", "float", cohesionLUT);
//std::array adhesionLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * Kernel<kernel_kind::adhesion>::value(c, p).x; }, 128, 128, 128);
//auto adhesion0 = lookup(adhesionLUT, -HforV1);
//for (auto& v : adhesionLUT)
// v /= adhesion0;
//std::cout << "Generated adhesion LUT" << std::endl;
//writeLUT("adhesion", "float", adhesionLUT);
//std::array volumeLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return 1.0; }, 128, 128, 128);
//std::cout << "Generated volume LUT" << std::endl;
//writeLUT("volume", "float", volumeLUT);
//float dh = 0.001f;
//float4 dx{ dh,0.f,0.f,0.f };
//float4 dy{ 0.f,dh,0.f,0.f };
//float4 dz{ 0.f,0.f,dh,0.f };
//std::array spikyLUT = generateLUT([&](float4 c, float4 p) { return SpikyKernel<kernel_kind::spline4>::value(c, p); });
//std::array splineLUT = generateLUT([&](float4 c, float4 p) { return kernel(c, p); });
//std::array cohesionLUT = generateLUT([&](float4 c, float4 p) { return Kernel<kernel_kind::cohesion>::value(c, p).x; });
//std::array adhesionLUT = generateLUT([&](float4 c, float4 p) { return Kernel<kernel_kind::adhesion>::value(c, p).x; });
//std::array spikyGradientLUT = gradientLUT([&](float4 c, float4 p) { return SpikyKernel<kernel_kind::spline4>::value(c, p); });
//std::array splineGradientLUT = gradientLUT([&](float4 c, float4 p) { return kernel(c, p); });
//std::array volumeLUT = gradientLUT([&](float4 c, float4 p) { return 1.f; });
//for (int32_t i = 0; i < lutSize; ++i) {
// std::cout << i << "\t" << splineLUT[i] << " - " << splineLUT2[i] << " -> " << splineLUT[i] / splineLUT2[i] << std::endl;
//}
//for (float x = -H; x <= H; x += H / 16.f) {
// std::cout << x << "\t" << lookup(splineLUT, x) << " @ " << lookup(splineLUT2, x) << std::endl;
//}
//for (float x = -H; x <= H; x += H / 16.f) {
// std::cout << x << "\t" << lookup(splineLUT, x) << " @ " << lookup(splineGradientLUT, x) << " -> " << lookup(splineLUT, x + dh) << " : " << lookup(splineLUT, x) + dh * lookup(splineGradientLUT, x) << std::endl;
//}
//for (auto& v : splineGradientLUT)
// v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);
//for (auto& v : spikyGradientLUT)
// v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);
//for (auto& v : cohesionLUT)
// v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);
////std::cout << adhesion0 << std::endl;
//auto x0 = lookup(splineLUT, 0.0f);
//auto xp = lookup(splineLUT, 0.0f + t);
//auto xn = lookup(splineLUT, 0.0f - t);
//auto xnum = (xp - xn) / (2.f * t);
//auto xint = lookup(splineGradientLUT, 0.f);
//std::cout << x0 << " -> " << xp << std::endl;
//std::cout << xnum << " <-> " << xint << std::endl;
//float evalP = 0.f * H;
//std::cout << "Spherical integral" << std::endl;
//std::cout << "Kernel: " << lookup(splineLUT, evalP) << std::endl;
//std::cout << "Gradient: " << lookup(splineGradientLUT, evalP) << std::endl;
//float4 c{ 0.f,0.f,0.f,h };
//double sumd = 0.0;
//double4 gradSumd{ 0.0,0.0,0.0,0.0 };
//double volume = 0.f;
//constexpr auto trapz = 512;
//constexpr auto dt = 2.0 * (double) H / ((double)trapz);
//constexpr auto dV = dt * dt * dt;
//auto trapH = support_from_volume(dV);
//for (int32_t xi = -trapz / 2; xi <= trapz / 2; ++xi) {
// for (int32_t yi = -trapz / 2; yi <= trapz / 2; ++yi) {
// for (int32_t zi = -trapz / 2; zi <= trapz / 2; ++zi) {
// float4 p{ (float)dt * (float)xi, (float)dt * (float)yi, (float)dt * (float)zi, h };
// if (p.x > evalP)
// continue;
// sumd += (double) kernel(c, p) * dV;
// gradSumd += math::castTo<double4>(gradient(c, p)) * dV;
// volume += kernel(c, p) > 0.f ? dV : 0.f;
// }
// }
//}
//std::cout << "Trapz" << std::endl;
//std::cout << "Kernel: " << sumd << std::endl;
//std::cout << "Gradient: " << gradSumd << std::endl;
//getchar();
} | 39.426101 | 213 | 0.601157 | [
"vector"
] |
7f27ed12ce94017531315d9cd9d5a1d009186a30 | 85,138 | cpp | C++ | src/DumpNAL.cpp | MMT-TLVassociation/DumpTS | c884656196b29790064bb09ad455a6f7470431a8 | [
"MIT"
] | 1 | 2021-12-22T05:25:56.000Z | 2021-12-22T05:25:56.000Z | src/DumpNAL.cpp | MMT-TLVassociation/DumpTS | c884656196b29790064bb09ad455a6f7470431a8 | [
"MIT"
] | null | null | null | src/DumpNAL.cpp | MMT-TLVassociation/DumpTS | c884656196b29790064bb09ad455a6f7470431a8 | [
"MIT"
] | 1 | 2022-02-08T01:18:29.000Z | 2022-02-08T01:18:29.000Z | /*
MIT License
Copyright (c) 2021 Ravin.Wang(wangf1978@hotmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "platcomm.h"
#include "nal_com.h"
#include "NAL.h"
#include "nal_parser.h"
#include "DataUtil.h"
#include "h264_video.h"
#include "h265_video.h"
#include "h266_video.h"
#include "mediaobjprint.h"
#include "DumpTS.h"
#include <unordered_map>
using namespace std;
extern map<std::string, std::string, CaseInsensitiveComparator> g_params;
int ShowNUs()
{
INALContext* pNALContext = nullptr;
uint8_t pBuf[2048] = { 0 };
const int read_unit_size = 2048;
FILE* rfp = NULL;
int iRet = RET_CODE_SUCCESS;
int64_t file_size = 0;
auto iter_srcfmt = g_params.find("srcfmt");
if (iter_srcfmt == g_params.end())
return RET_CODE_ERROR_NOTIMPL;
NAL_CODING coding = NAL_CODING_UNKNOWN;
if (iter_srcfmt->second.compare("h264") == 0)
coding = NAL_CODING_AVC;
else if (iter_srcfmt->second.compare("h265") == 0)
coding = NAL_CODING_HEVC;
else if (iter_srcfmt->second.compare("h266") == 0)
coding = NAL_CODING_VVC;
else
return RET_CODE_ERROR_NOTIMPL;
int options = 0;
std::string& strShowNU = g_params["showNU"];
std::vector<std::string> strShowNUOptions;
splitstr(strShowNU.c_str(), ",;.:", strShowNUOptions);
if (strShowNUOptions.size() == 0)
options = NAL_ENUM_OPTION_ALL;
else
{
for (auto& sopt : strShowNUOptions)
{
if (MBCSICMP(sopt.c_str(), "au") == 0)
options |= NAL_ENUM_OPTION_AU;
if (MBCSICMP(sopt.c_str(), "nu") == 0)
options |= NAL_ENUM_OPTION_NU;
if (MBCSICMP(sopt.c_str(), "seimsg") == 0 || MBCSICMP(sopt.c_str(), "seimessage") == 0)
options |= NAL_ENUM_OPTION_SEI_MSG;
if (MBCSICMP(sopt.c_str(), "seipayload") == 0)
options |= NAL_ENUM_OPTION_SEI_PAYLOAD;
}
}
int top = GetTopRecordCount();
CNALParser NALParser(coding);
IUnknown* pMSECtx = nullptr;
if (AMP_FAILED(NALParser.GetContext(&pMSECtx)) ||
FAILED(pMSECtx->QueryInterface(IID_INALContext, (void**)&pNALContext)))
{
AMP_SAFERELEASE(pMSECtx);
printf("Failed to get the %s NAL context.\n", NAL_CODING_NAME(coding));
return RET_CODE_ERROR_NOTIMPL;
}
AMP_SAFERELEASE(pMSECtx);
class CNALEnumerator : public CComUnknown, public INALEnumerator
{
public:
CNALEnumerator(INALContext* pNALCtx) : m_pNALContext(pNALCtx) {
if (m_pNALContext)
m_pNALContext->AddRef();
m_coding = m_pNALContext->GetNALCoding();
}
virtual ~CNALEnumerator() {
AMP_SAFERELEASE(m_pNALContext);
}
DECLARE_IUNKNOWN
HRESULT NonDelegatingQueryInterface(REFIID uuid, void** ppvObj)
{
if (ppvObj == NULL)
return E_POINTER;
if (uuid == IID_INALEnumerator)
return GetCOMInterface((INALEnumerator*)this, ppvObj);
return CComUnknown::NonDelegatingQueryInterface(uuid, ppvObj);
}
public:
RET_CODE EnumNewVSEQ(IUnknown* pCtx) { return RET_CODE_SUCCESS; }
RET_CODE EnumNewCVS(IUnknown* pCtx, int8_t represent_nal_unit_type){return RET_CODE_SUCCESS;}
RET_CODE EnumNALAUBegin(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf, int picture_slice_type)
{
printf("Access-Unit#%" PRIu64 "\n", m_AUCount);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALUnitBegin(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
uint8_t nal_unit_type = m_coding == NAL_CODING_AVC ? (pEBSPNUBuf[0] & 0x1F):(m_coding == NAL_CODING_HEVC? ((pEBSPNUBuf[0] >> 1) & 0x3F):0);
printf("\tNAL Unit %s -- %s, len: %zu\n",
m_coding == NAL_CODING_AVC? avc_nal_unit_type_names[nal_unit_type]:(m_coding == NAL_CODING_HEVC? hevc_nal_unit_type_names[nal_unit_type]:"Unknown"),
m_coding == NAL_CODING_AVC? avc_nal_unit_type_descs[nal_unit_type]:(m_coding == NAL_CODING_HEVC? hevc_nal_unit_type_descs[nal_unit_type]:"Unknown"), cbEBSPNUBuf);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIMessageBegin(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf)
{
printf("\t\tSEI message\n");
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIPayloadBegin(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf)
{
printf("\t\t\tSEI payload %s, length: %zu\n", sei_payload_type_names[payload_type], cbRBSPPayloadBuf);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIPayloadEnd(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALSEIMessageEnd(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALUnitEnd(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
m_NUCount++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALAUEnd(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf)
{
m_AUCount++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALError(IUnknown* pCtx, uint64_t stream_offset, int error_code)
{
printf("Hitting error {error_code: %d}.\n", error_code);
return RET_CODE_SUCCESS;
}
INALContext* m_pNALContext = nullptr;
uint64_t m_AUCount = 0;
uint64_t m_NUCount = 0;
NAL_CODING m_coding = NAL_CODING_UNKNOWN;
}NALEnumerator(pNALContext);
errno_t errn = fopen_s(&rfp, g_params["input"].c_str(), "rb");
if (errn != 0 || rfp == NULL)
{
printf("Failed to open the file: %s {errno: %d}.\n", g_params["input"].c_str(), errn);
goto done;
}
// Get file size
_fseeki64(rfp, 0, SEEK_END);
file_size = _ftelli64(rfp);
_fseeki64(rfp, 0, SEEK_SET);
NALEnumerator.AddRef();
NALParser.SetEnumerator((IUnknown*)(&NALEnumerator), options);
do
{
int read_size = read_unit_size;
if ((read_size = (int)fread(pBuf, 1, read_unit_size, rfp)) <= 0)
{
iRet = RET_CODE_IO_READ_ERROR;
break;
}
iRet = NALParser.ProcessInput(pBuf, read_size);
if (AMP_FAILED(iRet))
break;
iRet = NALParser.ProcessOutput();
if (iRet == RET_CODE_ABORT)
break;
} while (!feof(rfp));
if (feof(rfp))
iRet = NALParser.ProcessOutput(true);
done:
if (rfp != nullptr)
fclose(rfp);
if (pNALContext)
{
pNALContext->Release();
pNALContext = nullptr;
}
return iRet;
}
int PrintHRDFromAVCSPS(H264_NU sps_nu)
{
if (!sps_nu || sps_nu->ptr_seq_parameter_set_rbsp == nullptr)
return RET_CODE_INVALID_PARAMETER;
uint64_t BitRates[32] = { 0 };
uint64_t CpbSize[32] = { 0 };
bool bUseConcludedValues[2] = { true, true };
if (sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->vcl_hrd_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->vcl_hrd_parameters)
{
printf("Type-I HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->vcl_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\tSchedSelIdx#%d:\n", SchedSelIdx);
BitRates[SchedSelIdx] = ((uint64_t)hrd_parameters->bit_rate_value_minus1[SchedSelIdx] + 1) * (uint64_t)1ULL<<(6 + hrd_parameters->bit_rate_scale);
CpbSize[SchedSelIdx] = ((uint64_t)hrd_parameters->cpb_size_value_minus1[SchedSelIdx] + 1)*(uint64_t)1ULL << (4 + hrd_parameters->cpb_size_scale);
printf("\t\tthe maximum input bit rate for the CPB: %" PRIu64 "bps/%sbps \n",
BitRates[SchedSelIdx], GetHumanReadNumber(BitRates[SchedSelIdx]).c_str());
printf("\t\tthe CPB size: %" PRIu64 "b/%sb \n",
CpbSize[SchedSelIdx], GetHumanReadNumber(CpbSize[SchedSelIdx]).c_str());
printf("\t\t%s mode\n", hrd_parameters->cbr_flag[SchedSelIdx]?"CBR":"VBR");
}
}
if (sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->nal_hrd_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->nal_hrd_parameters)
{
printf("Type-II HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->nal_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\tSchedSelIdx#%d:\n", SchedSelIdx);
BitRates[SchedSelIdx] = ((uint64_t)hrd_parameters->bit_rate_value_minus1[SchedSelIdx] + 1) * (uint64_t)1ULL << (6 + hrd_parameters->bit_rate_scale);
CpbSize[SchedSelIdx] = ((uint64_t)hrd_parameters->cpb_size_value_minus1[SchedSelIdx] + 1)*(uint64_t)1ULL << (4 + hrd_parameters->cpb_size_scale);
printf("\t\tthe maximum input bit rate for the CPB: %" PRIu64 "bps/%sbps \n",
BitRates[SchedSelIdx], GetHumanReadNumber(BitRates[SchedSelIdx]).c_str());
printf("\t\tthe CPB size: %" PRIu64 "b/%sb \n",
CpbSize[SchedSelIdx], GetHumanReadNumber(CpbSize[SchedSelIdx]).c_str());
printf("\t\t%s mode\n", hrd_parameters->cbr_flag[SchedSelIdx] ? "CBR" : "VBR");
}
}
return RET_CODE_SUCCESS;
}
int PrintHRDFromHEVCSPS(H265_NU sps_nu)
{
if (!sps_nu || sps_nu->ptr_seq_parameter_set_rbsp == nullptr)
return RET_CODE_INVALID_PARAMETER;
uint64_t BitRates[32] = { 0 };
uint64_t CpbSize[32] = { 0 };
bool bUseConcludedValues[2] = { true, true };
if (sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->vui_hrd_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->m_commonInfPresentFlag &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->vcl_hrd_parameters_present_flag)
{
printf("Type-I HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters;
for (uint8_t i = 0; i <= hrd_parameters->m_maxNumSubLayersMinus1; i++)
{
printf("\tSublayer#%d:\n", i);
auto sub_layer_hrd_parameters = hrd_parameters->sub_layer_infos[i]->ptr_vcl_sub_layer_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->sub_layer_infos[i]->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\t\tSchedSelIdx#%d:\n", SchedSelIdx);
BitRates[SchedSelIdx] = ((uint64_t)sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->bit_rate_value_minus1 + 1) << (6 + hrd_parameters->bit_rate_scale);
CpbSize[SchedSelIdx] = ((uint64_t)sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->cpb_size_value_minus1 + 1) << (4 + hrd_parameters->cpb_size_scale);
printf("\t\t\tthe maximum input bit rate for the CPB: %" PRIu64 "bps/%sbps \n",
BitRates[SchedSelIdx], GetHumanReadNumber(BitRates[SchedSelIdx]).c_str());
printf("\t\t\tthe CPB size: %" PRIu64 "b/%sb \n",
CpbSize[SchedSelIdx], GetHumanReadNumber(CpbSize[SchedSelIdx]).c_str());
printf("\t\t\t%s mode\n", sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->cbr_flag ? "CBR" : "VBR");
}
}
}
if (sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->vui_hrd_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->m_commonInfPresentFlag &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->nal_hrd_parameters_present_flag)
{
printf("Type-II HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters;
for (uint8_t i = 0; i <= hrd_parameters->m_maxNumSubLayersMinus1; i++)
{
printf("\tSublayer#%d:\n", i);
auto sub_layer_hrd_parameters = hrd_parameters->sub_layer_infos[i]->ptr_nal_sub_layer_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->sub_layer_infos[i]->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\t\tSchedSelIdx#%d:\n", SchedSelIdx);
BitRates[SchedSelIdx] = ((uint64_t)sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->bit_rate_value_minus1 + 1) << (6 + hrd_parameters->bit_rate_scale);
CpbSize[SchedSelIdx] = ((uint64_t)sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->cpb_size_value_minus1 + 1) << (4 + hrd_parameters->cpb_size_scale);
printf("\t\t\tthe maximum input bit rate for the CPB: %" PRIu64 "bps/%sbps \n",
BitRates[SchedSelIdx], GetHumanReadNumber(BitRates[SchedSelIdx]).c_str());
printf("\t\t\tthe CPB size: %" PRIu64 "b/%sb \n",
CpbSize[SchedSelIdx], GetHumanReadNumber(CpbSize[SchedSelIdx]).c_str());
printf("\t\t\t%s mode\n", sub_layer_hrd_parameters->sub_layer_hrd_parameters[SchedSelIdx]->cbr_flag ? "CBR" : "VBR");
}
}
}
return RET_CODE_SUCCESS;
}
int PrintHRDFromSEIPayloadBufferingPeriod(IUnknown* pCtx, uint8_t* pSEIPayload, size_t cbSEIPayload)
{
int iRet = RET_CODE_SUCCESS;
if (pSEIPayload == nullptr || cbSEIPayload == 0 || pCtx == nullptr)
return RET_CODE_INVALID_PARAMETER;
INALContext* pNALCtx = nullptr;
if (FAILED(pCtx->QueryInterface(IID_INALContext, (void**)&pNALCtx)))
return RET_CODE_INVALID_PARAMETER;
AMBst bst = nullptr;
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::BUFFERING_PERIOD* pBufPeriod = new
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::BUFFERING_PERIOD((int)cbSEIPayload, pNALCtx);
NAL_CODING coding = pNALCtx->GetNALCoding();
if (pBufPeriod != nullptr)
bst = AMBst_CreateFromBuffer(pSEIPayload, (int)cbSEIPayload);
if (pBufPeriod == nullptr || bst == nullptr)
{
iRet = RET_CODE_OUTOFMEMORY;
goto done;
}
if (AMP_FAILED(iRet = pBufPeriod->Map(bst)))
{
printf("Failed to unpack the SEI payload: buffering period.\n");
goto done;
}
if (coding == NAL_CODING_AVC)
{
H264_NU sps_nu;
INALAVCContext* pNALAVCCtx = nullptr;
if (SUCCEEDED(pCtx->QueryInterface(IID_INALAVCContext, (void**)&pNALAVCCtx)))
{
sps_nu = pNALAVCCtx->GetAVCSPS(pBufPeriod->bp_seq_parameter_set_id);
pNALAVCCtx->Release();
pNALAVCCtx = nullptr;
}
if (sps_nu &&
sps_nu->ptr_seq_parameter_set_rbsp != nullptr &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters)
{
auto vui_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters;
if (vui_parameters->vcl_hrd_parameters_present_flag)
{
printf("Type-I HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->vcl_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\tSchedSelIdx#%d:\n", SchedSelIdx);
printf("\t\tinitial_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_delay);
printf("\t\tinitial_cpb_removal_delay_offset: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_offset);
}
}
if (vui_parameters->nal_hrd_parameters_present_flag)
{
printf("Type-II HRD:\n");
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->nal_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
printf("\tSchedSelIdx#%d:\n", SchedSelIdx);
printf("\t\tinitial_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_delay);
printf("\t\tinitial_cpb_removal_delay_offset: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_offset);
}
}
}
}
else if (coding == NAL_CODING_HEVC)
{
H265_NU sps_nu;
INALHEVCContext* pNALHEVCCtx = nullptr;
if (SUCCEEDED(pCtx->QueryInterface(IID_INALHEVCContext, (void**)&pNALHEVCCtx)))
{
sps_nu = pNALHEVCCtx->GetHEVCSPS(pBufPeriod->bp_seq_parameter_set_id);
pNALHEVCCtx->Release();
pNALHEVCCtx = nullptr;
}
if (pBufPeriod->irap_cpb_params_present_flag)
{
printf("\tcpb_delay_offset: %" PRIu32 "\n", pBufPeriod->cpb_delay_offset);
printf("\tdpb_delay_offset: %" PRIu32 "\n", pBufPeriod->dpb_delay_offset);
}
printf("\tconcatenation_flag: %d\n", (int)pBufPeriod->concatenation_flag);
printf("\tau_cpb_removal_delay_delta: %" PRId64"\n", (int64_t)pBufPeriod->au_cpb_removal_delay_delta_minus1 + 1);
bool sub_pic_hrd_params_present_flag = false;
bool NalHrdBpPresentFlag = false;
bool VclHrdBpPresentFlag = false;
uint8_t au_cpb_removal_delay_length_minus1 = 0;
uint8_t dpb_output_delay_length_minus1 = 0;
uint8_t initial_cpb_removal_delay_length_minus1 = 0;
if (sps_nu &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters)
{
sub_pic_hrd_params_present_flag = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->sub_pic_hrd_params_present_flag;
au_cpb_removal_delay_length_minus1 = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->au_cpb_removal_delay_length_minus1;
dpb_output_delay_length_minus1 = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->dpb_output_delay_length_minus1;
initial_cpb_removal_delay_length_minus1 = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->initial_cpb_removal_delay_length_minus1;
NalHrdBpPresentFlag = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->nal_hrd_parameters_present_flag ? true : false;
VclHrdBpPresentFlag = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->vcl_hrd_parameters_present_flag ? true : false;
}
if (NalHrdBpPresentFlag)
{
auto pSubLayer0Info = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->sub_layer_infos[0];
size_t CpbCnt = pSubLayer0Info != NULL ? pSubLayer0Info->cpb_cnt_minus1 : 0;
for (size_t i = 0; i <= CpbCnt; i++)
{
printf("\tNAL CPB#%zu\n", i);
printf("\t\tinitial_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[i].initial_cpb_removal_delay);
printf("\t\tinitial_cpb_removal_offset: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[i].initial_cpb_removal_offset);
if (sub_pic_hrd_params_present_flag || pBufPeriod->irap_cpb_params_present_flag)
{
printf("\t\tinitial_alt_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[i].initial_alt_cpb_removal_delay);
printf("\t\tinitial_alt_cpb_removal_offset: %" PRIu32 "\n", pBufPeriod->nal_initial_cpb_removal_info[i].initial_alt_cpb_removal_offset);
}
}
}
if (VclHrdBpPresentFlag)
{
auto pSubLayer0Info = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters->hrd_parameters->sub_layer_infos[0];
size_t CpbCnt = pSubLayer0Info != NULL ? pSubLayer0Info->cpb_cnt_minus1 : 0;
for (size_t i = 0; i <= CpbCnt; i++)
{
printf("\tNAL CPB#%zu\n", i);
printf("\t\tinitial_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[i].initial_cpb_removal_delay);
printf("\t\tinitial_cpb_removal_offset: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[i].initial_cpb_removal_offset);
if (sub_pic_hrd_params_present_flag || pBufPeriod->irap_cpb_params_present_flag)
{
printf("\t\tinitial_alt_cpb_removal_delay: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[i].initial_alt_cpb_removal_delay);
printf("\t\tinitial_alt_cpb_removal_offset: %" PRIu32 "\n", pBufPeriod->vcl_initial_cpb_removal_info[i].initial_alt_cpb_removal_offset);
}
}
}
}
else if (coding == NAL_CODING_VVC)
{
}
done:
if (bst)
AMBst_Destroy(bst);
AMP_SAFEDEL(pBufPeriod);
AMP_SAFERELEASE(pNALCtx);
return iRet;
}
int PrintHRDFromSEIPayloadPicTiming(IUnknown* pCtx, uint8_t* pSEIPayload, size_t cbSEIPayload)
{
int iRet = RET_CODE_SUCCESS;
if (pSEIPayload == nullptr || cbSEIPayload == 0 || pCtx == nullptr)
return RET_CODE_INVALID_PARAMETER;
INALContext* pNALCtx = nullptr;
if (FAILED(pCtx->QueryInterface(IID_INALContext, (void**)&pNALCtx)))
return RET_CODE_INVALID_PARAMETER;
NAL_CODING coding = pNALCtx->GetNALCoding();
AMBst bst = nullptr;
bst = AMBst_CreateFromBuffer(pSEIPayload, (int)cbSEIPayload);
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H264* pPicTiming = nullptr;
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H265* pPicTimingH265 = nullptr;
if (bst == nullptr)
{
iRet = RET_CODE_OUTOFMEMORY;
goto done;
}
printf("Picture Timing(payloadLength: %zu):\n", cbSEIPayload);
//print_mem(pSEIPayload, (int)cbSEIPayload, 4);
if (coding == NAL_CODING_AVC)
{
pPicTiming = new BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H264((int)cbSEIPayload, pNALCtx);
if (AMP_FAILED(iRet = pPicTiming->Map(bst)))
{
printf("Failed to unpack the SEI payload: pic_timing.\n");
goto done;
}
printf("\tcpb_removal_delay: %" PRIu32 "\n", pPicTiming->cpb_removal_delay);
printf("\tdpb_output_delay: %" PRIu32 "\n", pPicTiming->dpb_output_delay);
if (pPicTiming->pic_struct_present_flag)
printf("\tpic_struct: %d (%s)\n", pPicTiming->pic_struct, PIC_STRUCT_MEANING(pPicTiming->pic_struct));
int NumClockTS = 0;
if (pPicTiming->pic_struct >= 0 && pPicTiming->pic_struct <= 2)
NumClockTS = 1;
else if (pPicTiming->pic_struct == 3 || pPicTiming->pic_struct == 4 || pPicTiming->pic_struct == 7)
NumClockTS = 2;
else if (pPicTiming->pic_struct == 5 || pPicTiming->pic_struct == 6 || pPicTiming->pic_struct == 8)
NumClockTS = 3;
for (int i = 0; i < NumClockTS; i++)
{
printf("\tClockTS#%d:\n", i);
printf("\t\tclock_timestamp_flag: %d\n", (int)pPicTiming->ClockTS[i].clock_timestamp_flag);
if (pPicTiming->ClockTS[i].clock_timestamp_flag)
{
printf("\t\tct_type: %d(%s)\n", (int)pPicTiming->ClockTS[i].ct_type,
pPicTiming->ClockTS[i].ct_type == 0?"progressive":(
pPicTiming->ClockTS[i].ct_type == 1?"interlaced":(
pPicTiming->ClockTS[i].ct_type == 2?"unknown":"")));
printf("\t\tnuit_field_based_flag: %d\n", (int)pPicTiming->ClockTS[i].nuit_field_based_flag);
printf("\t\tcounting_type: %d\n", (int)pPicTiming->ClockTS[i].counting_type);
printf("\t\tfull_timestamp_flag: %d\n", (int)pPicTiming->ClockTS[i].full_timestamp_flag);
printf("\t\tdiscontinuity_flag: %d\n", (int)pPicTiming->ClockTS[i].discontinuity_flag);
printf("\t\tcnt_dropped_flag: %d\n", (int)pPicTiming->ClockTS[i].cnt_dropped_flag);
printf("\t\ttime code: %s\n", pPicTiming->ClockTS[i].GetTimeCode().c_str());
if (pPicTiming->ClockTS[i].time_offset_length > 0)
printf("\t\ttime offset: %" PRId64 "\n", pPicTiming->ClockTS[i].time_offset);
}
}
}
else if (coding == NAL_CODING_HEVC)
{
pPicTimingH265 = new BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H265((int)cbSEIPayload, pNALCtx);
if (AMP_FAILED(iRet = pPicTimingH265->Map(bst)))
{
printf("Failed to unpack the SEI payload: pic_timing.\n");
goto done;
}
if (pPicTimingH265->frame_field_info_present_flag)
{
printf("\tpic_struct: %d (%s)\n", pPicTimingH265->pic_struct, pic_struct_names[pPicTimingH265->pic_struct]);
printf("\tsource_scan_type: %d (%s)\n", pPicTimingH265->source_scan_type,
pPicTimingH265->source_scan_type == 0 ? "Interlaced":(
pPicTimingH265->source_scan_type == 1 ? "Progressive" : (
pPicTimingH265->source_scan_type == 2 ? "Unspecified" : "")));
printf("\tduplicate_flag: %d\n", pPicTimingH265->duplicate_flag);
}
if (pPicTimingH265->CpbDpbDelaysPresentFlag)
{
printf("\tau_cpb_removal_delay: %" PRIu64 "\n", pPicTimingH265->au_cpb_removal_delay_minus1 + 1);
printf("\tpic_dpb_output_delay: %" PRIu64 "\n", pPicTimingH265->pic_dpb_output_delay);
if (pPicTimingH265->sub_pic_hrd_params_present_flag)
{
printf("\tpic_dpb_output_du_delay: %" PRIu64 "\n", pPicTimingH265->pic_dpb_output_du_delay);
if (pPicTimingH265->sub_pic_cpb_params_in_pic_timing_sei_flag)
{
printf("\tnum_decoding_units: %" PRIu64 "\n", pPicTimingH265->num_decoding_units_minus1 + 1);
printf("\tdu_common_cpb_removal_delay_flag: %d\n", (int)pPicTimingH265->du_common_cpb_removal_delay_flag);
if (pPicTimingH265->du_common_cpb_removal_delay_flag)
{
printf("\tdu_common_cpb_removal_delay_increment: %" PRIu64 "\n", pPicTimingH265->du_common_cpb_removal_delay_increment_minus1 + 1);
}
for (size_t i = 0; i <= (size_t)pPicTimingH265->num_decoding_units_minus1; i++)
{
printf("\tdu#%zu:\n", i);
printf("\t\tnum_nalus_in_du: %" PRIu64 "\n", pPicTimingH265->dus[i].num_nalus_in_du_minus1 + 1);
if (!pPicTimingH265->du_common_cpb_removal_delay_flag && i < pPicTimingH265->num_decoding_units_minus1)
{
printf("\t\tdu_cpb_removal_delay_increment: %" PRIu64 "\n", pPicTimingH265->dus[i].du_cpb_removal_delay_increment_minus1 + 1);
}
}
}
}
}
}
else
{
// TODO...
}
done:
if (bst)
AMBst_Destroy(bst);
AMP_SAFEDEL(pPicTiming);
AMP_SAFEDEL(pPicTimingH265);
AMP_SAFERELEASE(pNALCtx);
return iRet;
}
void PrintAVCSPSRoughInfo(H264_NU sps_nu)
{
if (!sps_nu || sps_nu->ptr_seq_parameter_set_rbsp == nullptr)
return;
auto& sps_seq = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data;
printf("A new H.264 sequence(seq_parameter_set_id:%d):\n", sps_seq.seq_parameter_set_id);
printf("\tAVC Profile: %s\n", get_h264_profile_name(sps_seq.GetH264Profile()));
printf("\tAVC Level: %s\n", get_h264_level_name(sps_seq.GetH264Level()));
printf("\tChroma: %s\n", chroma_format_idc_names[sps_seq.chroma_format_idc]);
printf("\tScan type: %s\n", sps_seq.frame_mbs_only_flag?"Progressive":"Interlaced");
uint8_t SubWidthC = (sps_seq.chroma_format_idc == 1 || sps_seq.chroma_format_idc == 2) ? 2 : (sps_seq.chroma_format_idc == 3 && sps_seq.separate_colour_plane_flag == 0 ? 1 : 0);
uint8_t SubHeightC = (sps_seq.chroma_format_idc == 2 || (sps_seq.chroma_format_idc == 3 && sps_seq.separate_colour_plane_flag == 0)) ? 1 : (sps_seq.chroma_format_idc == 1 ? 2 : 0);
uint16_t PicWidthInMbs = sps_seq.pic_width_in_mbs_minus1 + 1;
uint32_t PicWidthInSamplesL = PicWidthInMbs * 16;
//uint32_t PicWidthInSamplesC = PicWidthInMbs * MbWidthC;
uint16_t PicHeightInMapUnits = sps_seq.pic_height_in_map_units_minus1 + 1;
uint32_t PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits;
uint16_t FrameHeightInMbs = (2 - sps_seq.frame_mbs_only_flag) * PicHeightInMapUnits;
uint8_t ChromaArrayType = sps_seq.separate_colour_plane_flag == 0 ? sps_seq.chroma_format_idc : 0;
uint8_t CropUnitX = ChromaArrayType == 0 ? 1 : SubWidthC;
uint8_t CropUnitY = ChromaArrayType == 0 ? (2 - sps_seq.frame_mbs_only_flag) : SubHeightC * (2 - sps_seq.frame_mbs_only_flag);
uint32_t frame_buffer_width = PicWidthInSamplesL, frame_buffer_height = FrameHeightInMbs * 16;
uint32_t display_width = frame_buffer_width, display_height = frame_buffer_height;
if (sps_seq.frame_cropping_flag)
{
uint32_t crop_unit_x = 0, crop_unit_y = 0;
if (0 == sps_seq.chroma_format_idc) // monochrome
{
crop_unit_x = 1;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
else if (1 == sps_seq.chroma_format_idc) // 4:2:0
{
crop_unit_x = 2;
crop_unit_y = 2 * (2 - sps_seq.frame_mbs_only_flag);
}
else if (2 == sps_seq.chroma_format_idc) // 4:2:2
{
crop_unit_x = 2;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
else if (3 == sps_seq.chroma_format_idc)
{
crop_unit_x = 1;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
display_width -= crop_unit_x * (sps_seq.frame_crop_left_offset + sps_seq.frame_crop_right_offset);
display_height -= crop_unit_y * (sps_seq.frame_crop_top_offset + sps_seq.frame_crop_bottom_offset);
}
printf("\tCoded Frame resolution: %" PRIu32 "x%" PRIu32 "\n", frame_buffer_width, frame_buffer_height);
printf("\tDisplay resolution: %" PRIu32 "x%" PRIu32 "\n", display_width, display_height);
if (sps_seq.vui_parameters_present_flag && sps_seq.vui_parameters)
{
auto vui_parameters = sps_seq.vui_parameters;
if (vui_parameters->aspect_ratio_info_present_flag)
{
if (vui_parameters->aspect_ratio_idc == 0xFF)
printf("\tSample Aspect-Ratio: %" PRIu16 "x%" PRIu16 "\n", vui_parameters->sar_width, vui_parameters->sar_height);
else
printf("\tSample Aspect-Ratio: %s\n", sample_aspect_ratio_descs[vui_parameters->aspect_ratio_idc]);
}
if (vui_parameters->video_signal_type_present_flag && vui_parameters->colour_description_present_flag)
{
printf("\tColour Primaries: %d(%s)\n", vui_parameters->colour_primaries, vui_colour_primaries_names[vui_parameters->colour_primaries]);
printf("\tTransfer Characteristics: %d(%s)\n", vui_parameters->transfer_characteristics, vui_transfer_characteristics_names[vui_parameters->transfer_characteristics]);
printf("\tMatrix Coeffs: %d(%s)\n", vui_parameters->matrix_coeffs, vui_matrix_coeffs_descs[vui_parameters->matrix_coeffs]);
}
uint32_t units_field_based_flag = 1; // For H264, default value is 1
if (vui_parameters->timing_info_present_flag)
{
if (vui_parameters->time_scale > 0)
{
float frame_rate = (float)vui_parameters->time_scale / (vui_parameters->num_units_in_tick * (units_field_based_flag + 1));
printf("\tFrame-Rate: %f fps\n", frame_rate);
}
}
}
return;
}
void PrintHEVCSPSRoughInfo(H265_NU sps_nu)
{
if (!sps_nu || sps_nu->ptr_seq_parameter_set_rbsp == nullptr)
return;
auto sps_seq = sps_nu->ptr_seq_parameter_set_rbsp;
if (sps_seq == nullptr ||
sps_seq->profile_tier_level == nullptr ||
!sps_seq->profile_tier_level->general_profile_level.profile_present_flag)
return;
const char* szProfileName = get_hevc_profile_name(sps_seq->profile_tier_level->GetHEVCProfile());
printf("A new H.265 sequence(seq_parameter_set_id:%d):\n", sps_seq->sps_seq_parameter_set_id);
printf("\tHEVC Profile: %s\n", szProfileName);
printf("\tTiger: %s\n", sps_seq->profile_tier_level->general_profile_level.tier_flag?"High":"Main");
if (sps_seq->profile_tier_level->general_profile_level.level_present_flag)
printf("\tLevel %d.%d\n", (int)(sps_seq->profile_tier_level->general_profile_level.level_idc / 30), (int)(sps_seq->profile_tier_level->general_profile_level.level_idc % 30 / 3));
printf("\tChroma: %s\n", chroma_format_idc_names[sps_seq->chroma_format_idc]);
if (sps_seq->vui_parameters_present_flag &&
sps_seq->vui_parameters)
printf("\tScan type: %s\n", sps_seq->vui_parameters->field_seq_flag ? "Interlaced" : "Progressive");
uint32_t display_width = sps_seq->pic_width_in_luma_samples, display_height = sps_seq->pic_height_in_luma_samples;
if (sps_seq->conformance_window_flag)
{
uint32_t sub_width_c = ((1 == sps_seq->chroma_format_idc) || (2 == sps_seq->chroma_format_idc)) && (0 == sps_seq->separate_colour_plane_flag) ? 2 : 1;
uint32_t sub_height_c = (1 == sps_seq->chroma_format_idc) && (0 == sps_seq->separate_colour_plane_flag) ? 2 : 1;
display_width -= sub_width_c * (sps_seq->conf_win_left_offset + sps_seq->conf_win_right_offset);
display_height = sub_height_c * (sps_seq->conf_win_top_offset + sps_seq->conf_win_bottom_offset);
}
printf("\tCoded Frame resolution: %" PRIu32 "x%" PRIu32 "\n", sps_seq->pic_width_in_luma_samples, sps_seq->pic_height_in_luma_samples);
printf("\tDisplay resolution: %" PRIu32 "x%" PRIu32 "\n", display_width, display_height);
if (sps_seq->vui_parameters_present_flag && sps_seq->vui_parameters)
{
auto vui_parameters = sps_seq->vui_parameters;
if (vui_parameters->aspect_ratio_info_present_flag)
{
if (vui_parameters->aspect_ratio_idc == 0xFF)
printf("\tSample Aspect-Ratio: %" PRIu16 "x%" PRIu16 "\n", vui_parameters->sar_width, vui_parameters->sar_height);
else
printf("\tSample Aspect-Ratio: %s\n", sample_aspect_ratio_descs[vui_parameters->aspect_ratio_idc]);
}
if (vui_parameters->video_signal_type_present_flag && vui_parameters->colour_description_present_flag)
{
printf("\tColour Primaries: %d(%s)\n", vui_parameters->colour_primaries, vui_colour_primaries_names[vui_parameters->colour_primaries]);
printf("\tTransfer Characteristics: %d(%s)\n", vui_parameters->transfer_characteristics, vui_transfer_characteristics_names[vui_parameters->transfer_characteristics]);
printf("\tMatrix Coeffs: %d(%s)\n", vui_parameters->matrix_coeffs, vui_matrix_coeffs_descs[vui_parameters->matrix_coeffs]);
}
uint32_t units_field_based_flag = 1; // For H264, default value is 1
if (vui_parameters->vui_timing_info_present_flag)
{
if (vui_parameters->vui_time_scale > 0)
{
float frame_rate = (float)vui_parameters->vui_time_scale / (vui_parameters->vui_num_units_in_tick * (vui_parameters->field_seq_flag + 1));
printf("\tFrame-Rate: %f fps\n", frame_rate);
}
}
}
return;
}
int GetStreamInfoFromSPS(NAL_CODING coding, uint8_t* pAnnexBBuf, size_t cbAnnexBBuf, STREAM_INFO& stm_info)
{
INALContext* pNALContext = nullptr;
int iRet = RET_CODE_ERROR;
if (cbAnnexBBuf >= INT64_MAX)
return RET_CODE_BUFFER_OVERFLOW;
CNALParser NALParser(coding);
IUnknown* pMSECtx = nullptr;
if (AMP_FAILED(NALParser.GetContext(&pMSECtx)) ||
FAILED(pMSECtx->QueryInterface(IID_INALContext, (void**)&pNALContext)))
{
AMP_SAFERELEASE(pMSECtx);
printf("Failed to get the %s NAL context.\n", NAL_CODING_NAME(coding));
return RET_CODE_ERROR_NOTIMPL;
}
AMP_SAFERELEASE(pMSECtx);
if (coding == NAL_CODING_AVC)
pNALContext->SetNUFilters({ BST::H264Video::SPS_NUT });
else if (coding == NAL_CODING_HEVC)
pNALContext->SetNUFilters({ BST::H265Video::VPS_NUT, BST::H265Video::SPS_NUT });
else if (coding == NAL_CODING_VVC)
pNALContext->SetNUFilters({ BST::H266Video::VPS_NUT, BST::H266Video::SPS_NUT });
class CNALEnumerator : public CComUnknown, public INALEnumerator
{
public:
CNALEnumerator(INALContext* pNALCtx) : m_pNALContext(pNALCtx) {
if (m_pNALContext)
m_pNALContext->AddRef();
m_coding = m_pNALContext->GetNALCoding();
if (m_coding == NAL_CODING_AVC)
m_pNALContext->QueryInterface(IID_INALAVCContext, (void**)&m_pNALAVCContext);
else if (m_coding == NAL_CODING_HEVC)
m_pNALContext->QueryInterface(IID_INALHEVCContext, (void**)&m_pNALHEVCContext);
}
virtual ~CNALEnumerator() {
AMP_SAFERELEASE(m_pNALAVCContext);
AMP_SAFERELEASE(m_pNALHEVCContext);
AMP_SAFERELEASE(m_pNALContext);
}
DECLARE_IUNKNOWN
HRESULT NonDelegatingQueryInterface(REFIID uuid, void** ppvObj)
{
if (ppvObj == NULL)
return E_POINTER;
if (uuid == IID_INALEnumerator)
return GetCOMInterface((INALEnumerator*)this, ppvObj);
return CComUnknown::NonDelegatingQueryInterface(uuid, ppvObj);
}
public:
RET_CODE EnumNewVSEQ(IUnknown* pCtx) { return RET_CODE_SUCCESS; }
RET_CODE EnumNewCVS(IUnknown* pCtx, int8_t represent_nal_unit_type) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALAUBegin(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf, int picture_slice_type) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALUnitBegin(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
int iRet = RET_CODE_SUCCESS;
uint8_t nal_unit_type = 0xFF;
AMBst bst = AMBst_CreateFromBuffer(pEBSPNUBuf, (int)cbEBSPNUBuf);
if (m_coding == NAL_CODING_AVC)
{
nal_unit_type = (pEBSPNUBuf[0] & 0x1F);
if (nal_unit_type == BST::H264Video::SPS_NUT || nal_unit_type == BST::H264Video::PPS_NUT)
{
H264_NU nu = m_pNALAVCContext->CreateAVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s parameter set {error: %d}.\n", avc_nal_unit_type_descs[nal_unit_type], iRet);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H264Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_spsid = nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id;
m_pNALAVCContext->UpdateAVCSPS(nu);
}
else if (nal_unit_type == BST::H264Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALAVCContext->UpdateAVCPPS(nu);
}
}
}
else if (m_coding == NAL_CODING_HEVC)
{
nal_unit_type = ((pEBSPNUBuf[0] >> 1) & 0x3F);
if (nal_unit_type == BST::H265Video::VPS_NUT || nal_unit_type == BST::H265Video::SPS_NUT || nal_unit_type == BST::H265Video::PPS_NUT)
{
H265_NU nu = m_pNALHEVCContext->CreateHEVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s.\n", hevc_nal_unit_type_names[nal_unit_type]);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H265Video::VPS_NUT)
{
if (memcmp(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCVPS(nu);
}
else if (nal_unit_type == BST::H265Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_spsid = nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id;
m_pNALHEVCContext->UpdateHEVCSPS(nu);
}
else if (nal_unit_type == BST::H265Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCPPS(nu);
}
}
}
done:
if (bst)
AMBst_Destroy(bst);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIMessageBegin(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALSEIPayloadBegin(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALSEIPayloadEnd(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALSEIMessageEnd(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALUnitEnd(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
m_NUCount++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALAUEnd(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALError(IUnknown* pCtx, uint64_t stream_offset, int error_code)
{
printf("Hitting error {error_code: %d}.\n", error_code);
return RET_CODE_SUCCESS;
}
int16_t GetSPSID() { return m_spsid; }
INALContext* m_pNALContext = nullptr;
INALAVCContext* m_pNALAVCContext = nullptr;
INALHEVCContext* m_pNALHEVCContext = nullptr;
uint64_t m_NUCount = 0;
NAL_CODING m_coding = NAL_CODING_UNKNOWN;
AMSHA1_RET prev_sps_sha1_ret[32] = { {0} };
AMSHA1_RET prev_vps_sha1_ret[32] = { {0} };
// H.264, there may be 256 pps at maximum; H.265/266: there may be 64 pps at maximum
AMSHA1_RET prev_pps_sha1_ret[256] = { {0} };
int16_t m_spsid = -1;
}NALEnumerator(pNALContext);
NALEnumerator.AddRef();
NALParser.SetEnumerator((IUnknown*)(&NALEnumerator), NAL_ENUM_OPTION_NU);
uint8_t* p = pAnnexBBuf;
int64_t cbLeft = (int64_t)cbAnnexBBuf;
INALAVCContext* pNALAVCContext = nullptr;
INALHEVCContext* pNALHEVCContext = nullptr;
if (coding == NAL_CODING_AVC)
{
if (FAILED(pNALContext->QueryInterface(IID_INALAVCContext, (void**)&pNALAVCContext)))
{
iRet = RET_CODE_ERROR_NOTIMPL;
goto done;
}
}
else if (coding == NAL_CODING_HEVC)
{
if (FAILED(pNALContext->QueryInterface(IID_INALHEVCContext, (void**)&pNALHEVCContext)))
{
iRet = RET_CODE_ERROR_NOTIMPL;
goto done;
}
}
while (cbLeft > 0)
{
int64_t cbSubmit = AMP_MIN(cbLeft, 2048);
if (AMP_SUCCEEDED(NALParser.ProcessInput(p, (size_t)cbSubmit)))
{
NALParser.ProcessOutput(cbLeft <= 2048 ? true : false);
if (coding == NAL_CODING_AVC)
{
int16_t sps_id = NALEnumerator.GetSPSID();
if (sps_id >= 0 && sps_id <= UINT8_MAX)
{
auto sps_nu = pNALAVCContext->GetAVCSPS((uint8_t)sps_id);
if (sps_nu &&
sps_nu->ptr_seq_parameter_set_rbsp)
{
auto& sps_seq = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data;
stm_info.video_info.profile = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.GetH264Profile();
stm_info.video_info.tier = -1;
stm_info.video_info.level = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.GetH264Level();
uint8_t SubWidthC = (sps_seq.chroma_format_idc == 1 || sps_seq.chroma_format_idc == 2) ? 2 : (sps_seq.chroma_format_idc == 3 && sps_seq.separate_colour_plane_flag == 0 ? 1 : 0);
uint8_t SubHeightC = (sps_seq.chroma_format_idc == 2 || (sps_seq.chroma_format_idc == 3 && sps_seq.separate_colour_plane_flag == 0)) ? 1 : (sps_seq.chroma_format_idc == 1 ? 2 : 0);
uint16_t PicWidthInMbs = sps_seq.pic_width_in_mbs_minus1 + 1;
uint32_t PicWidthInSamplesL = PicWidthInMbs * 16;
//uint32_t PicWidthInSamplesC = PicWidthInMbs * MbWidthC;
uint16_t PicHeightInMapUnits = sps_seq.pic_height_in_map_units_minus1 + 1;
uint32_t PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits;
uint16_t FrameHeightInMbs = (2 - sps_seq.frame_mbs_only_flag) * PicHeightInMapUnits;
uint8_t ChromaArrayType = sps_seq.separate_colour_plane_flag == 0 ? sps_seq.chroma_format_idc : 0;
uint8_t CropUnitX = ChromaArrayType == 0 ? 1 : SubWidthC;
uint8_t CropUnitY = ChromaArrayType == 0 ? (2 - sps_seq.frame_mbs_only_flag) : SubHeightC * (2 - sps_seq.frame_mbs_only_flag);
uint32_t frame_buffer_width = PicWidthInSamplesL, frame_buffer_height = FrameHeightInMbs * 16;
uint32_t display_width = frame_buffer_width, display_height = frame_buffer_height;
if (sps_seq.frame_cropping_flag)
{
uint32_t crop_unit_x = 0, crop_unit_y = 0;
if (0 == sps_seq.chroma_format_idc) // monochrome
{
crop_unit_x = 1;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
else if (1 == sps_seq.chroma_format_idc) // 4:2:0
{
crop_unit_x = 2;
crop_unit_y = 2 * (2 - sps_seq.frame_mbs_only_flag);
}
else if (2 == sps_seq.chroma_format_idc) // 4:2:2
{
crop_unit_x = 2;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
else if (3 == sps_seq.chroma_format_idc)
{
crop_unit_x = 1;
crop_unit_y = 2 - sps_seq.frame_mbs_only_flag;
}
display_width -= crop_unit_x * (sps_seq.frame_crop_left_offset + sps_seq.frame_crop_right_offset);
display_height -= crop_unit_y * (sps_seq.frame_crop_top_offset + sps_seq.frame_crop_bottom_offset);
}
stm_info.video_info.video_width = display_width;
stm_info.video_info.video_height = display_height;
if (sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters)
{
auto vui_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters;
if (vui_parameters->nal_hrd_parameters_present_flag &&
vui_parameters->nal_hrd_parameters)
{
stm_info.video_info.bitrate = (vui_parameters->nal_hrd_parameters->bit_rate_value_minus1[0] + 1) << (vui_parameters->nal_hrd_parameters->bit_rate_scale + 6);
}
else if (vui_parameters->vcl_hrd_parameters_present_flag &&
vui_parameters->vcl_hrd_parameters)
{
stm_info.video_info.bitrate = (vui_parameters->vcl_hrd_parameters->bit_rate_value_minus1[0] + 1) << (vui_parameters->vcl_hrd_parameters->bit_rate_scale + 6);
}
if (vui_parameters->aspect_ratio_info_present_flag)
{
uint16_t SAR_N = 0, SAR_D = 0;
if (vui_parameters->aspect_ratio_idc == 0xFF)
{
SAR_N = vui_parameters->sar_width;
SAR_D = vui_parameters->sar_height;
}
else if (vui_parameters->aspect_ratio_idc >= 0 && vui_parameters->aspect_ratio_idc < sizeof(sample_aspect_ratios) / sizeof(sample_aspect_ratios[0]))
{
SAR_N = std::get<0>(sample_aspect_ratios[vui_parameters->aspect_ratio_idc]);
SAR_D = std::get<1>(sample_aspect_ratios[vui_parameters->aspect_ratio_idc]);
}
if (SAR_N != 0 && SAR_D != 0)
{
float diff_4_3 = fabs(((float)SAR_N*display_width) / ((float)SAR_D*display_height) - 4.0f / 3.0f);
float diff_16_9 = fabs(((float)SAR_N*display_width) / ((float)SAR_D*display_height) - 16.0f / 9.0f);
stm_info.video_info.aspect_ratio_numerator = diff_4_3 < diff_16_9 ? 4 : 16;
stm_info.video_info.aspect_ratio_denominator = diff_4_3 < diff_16_9 ? 3 : 9;
}
}
if (vui_parameters->video_signal_type_present_flag && vui_parameters->colour_description_present_flag)
{
stm_info.video_info.transfer_characteristics = vui_parameters->transfer_characteristics;
stm_info.video_info.colour_primaries = vui_parameters->colour_primaries;
}
stm_info.video_info.chroma_format_idc = sps_seq.chroma_format_idc;
if (vui_parameters->timing_info_present_flag && vui_parameters->fixed_frame_rate_flag)
{
uint64_t GCD = gcd((uint64_t)vui_parameters->num_units_in_tick * 2, vui_parameters->time_scale);
stm_info.video_info.framerate_numerator = (uint32_t)(vui_parameters->time_scale / GCD);
stm_info.video_info.framerate_denominator = (uint32_t)((uint64_t)vui_parameters->num_units_in_tick * 2 / GCD);
}
}
iRet = RET_CODE_SUCCESS;
break;
}
}
}
else if (coding == NAL_CODING_HEVC)
{
int16_t sps_id = NALEnumerator.GetSPSID();
if (sps_id >= 0 && sps_id <= UINT8_MAX)
{
auto sps_nu = pNALHEVCContext->GetHEVCSPS((uint8_t)sps_id);
if (sps_nu &&
sps_nu->ptr_seq_parameter_set_rbsp)
{
auto sps_seq = sps_nu->ptr_seq_parameter_set_rbsp;
stm_info.video_info.profile = BST::H265Video::HEVC_PROFILE_UNKNOWN;
stm_info.video_info.tier = BST::H265Video::HEVC_TIER_UNKNOWN;
if (sps_seq->profile_tier_level)
{
if (sps_seq->profile_tier_level->general_profile_level.profile_present_flag)
{
stm_info.video_info.profile = sps_seq->profile_tier_level->GetHEVCProfile();
stm_info.video_info.tier = sps_seq->profile_tier_level->general_profile_level.tier_flag;
}
stm_info.video_info.level = sps_seq->profile_tier_level->general_profile_level.level_idc;
}
uint32_t display_width = sps_seq->pic_width_in_luma_samples, display_height = sps_seq->pic_height_in_luma_samples;
if (sps_seq->conformance_window_flag)
{
uint32_t sub_width_c = ((1 == sps_seq->chroma_format_idc) || (2 == sps_seq->chroma_format_idc)) && (0 == sps_seq->separate_colour_plane_flag) ? 2 : 1;
uint32_t sub_height_c = (1 == sps_seq->chroma_format_idc) && (0 == sps_seq->separate_colour_plane_flag) ? 2 : 1;
display_width -= sub_width_c * (sps_seq->conf_win_left_offset + sps_seq->conf_win_right_offset);
display_height = sub_height_c * (sps_seq->conf_win_top_offset + sps_seq->conf_win_bottom_offset);
}
stm_info.video_info.video_width = display_width;
stm_info.video_info.video_height = display_height;
if (sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters_present_flag &&
sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters)
{
auto vui_parameters = sps_nu->ptr_seq_parameter_set_rbsp->vui_parameters;
if (vui_parameters->vui_hrd_parameters_present_flag &&
vui_parameters->hrd_parameters &&
vui_parameters->hrd_parameters->m_commonInfPresentFlag &&
vui_parameters->hrd_parameters->sub_layer_infos)
{
if (vui_parameters->hrd_parameters->nal_hrd_parameters_present_flag)
{
auto ptr_nal_sub_layer_hrd_parameters = vui_parameters->hrd_parameters->sub_layer_infos[0]->ptr_nal_sub_layer_hrd_parameters;
stm_info.video_info.bitrate =
(ptr_nal_sub_layer_hrd_parameters->sub_layer_hrd_parameters[0]->bit_rate_value_minus1 + 1) << (vui_parameters->hrd_parameters->bit_rate_scale + 6);
}
else if (vui_parameters->hrd_parameters->vcl_hrd_parameters_present_flag)
{
auto ptr_vcl_sub_layer_hrd_parameters = vui_parameters->hrd_parameters->sub_layer_infos[0]->ptr_vcl_sub_layer_hrd_parameters;
stm_info.video_info.bitrate =
(ptr_vcl_sub_layer_hrd_parameters->sub_layer_hrd_parameters[0]->bit_rate_value_minus1 + 1) << (vui_parameters->hrd_parameters->bit_rate_scale + 6);
}
}
if (vui_parameters->aspect_ratio_info_present_flag)
{
uint16_t SAR_N = 0, SAR_D = 0;
if (vui_parameters->aspect_ratio_idc == 0xFF)
{
SAR_N = vui_parameters->sar_width;
SAR_D = vui_parameters->sar_height;
}
else if (vui_parameters->aspect_ratio_idc >= 0 && vui_parameters->aspect_ratio_idc < sizeof(sample_aspect_ratios) / sizeof(sample_aspect_ratios[0]))
{
SAR_N = std::get<0>(sample_aspect_ratios[vui_parameters->aspect_ratio_idc]);
SAR_D = std::get<1>(sample_aspect_ratios[vui_parameters->aspect_ratio_idc]);
}
if (SAR_N != 0 && SAR_D != 0)
{
float diff_4_3 = fabs(((float)SAR_N*display_width) / ((float)SAR_D*display_height) - 4.0f / 3.0f);
float diff_16_9 = fabs(((float)SAR_N*display_width) / ((float)SAR_D*display_height) - 16.0f / 9.0f);
stm_info.video_info.aspect_ratio_numerator = diff_4_3 < diff_16_9 ? 4 : 16;
stm_info.video_info.aspect_ratio_denominator = diff_4_3 < diff_16_9 ? 3 : 9;
}
}
if (vui_parameters->video_signal_type_present_flag && vui_parameters->colour_description_present_flag)
{
stm_info.video_info.transfer_characteristics = vui_parameters->transfer_characteristics;
stm_info.video_info.colour_primaries = vui_parameters->colour_primaries;
}
stm_info.video_info.chroma_format_idc = sps_seq->chroma_format_idc;
if (vui_parameters->vui_timing_info_present_flag)
{
uint64_t GCD = gcd((uint64_t)vui_parameters->vui_num_units_in_tick * (1ULL + vui_parameters->field_seq_flag), vui_parameters->vui_time_scale);
stm_info.video_info.framerate_numerator = (uint32_t)(vui_parameters->vui_time_scale / GCD);
stm_info.video_info.framerate_denominator = (uint32_t)((uint64_t)vui_parameters->vui_num_units_in_tick * (1ULL + vui_parameters->field_seq_flag) / GCD);
}
}
iRet = RET_CODE_SUCCESS;
break;
}
}
}
cbLeft -= cbSubmit;
p += cbSubmit;
}
else
break;
}
done:
if (pNALAVCContext)
{
pNALAVCContext->Release();
pNALAVCContext = nullptr;
}
if (pNALHEVCContext)
{
pNALHEVCContext->Release();
pNALHEVCContext = nullptr;
}
if (pNALContext)
{
pNALContext->Release();
pNALContext = nullptr;
}
return iRet;
}
/*
1: VPS
2: SPS
3: PPS
12: HRD
81: rough VPS
82: rough SPS
*/
int ShowNALObj(int object_type)
{
INALContext* pNALContext = nullptr;
uint8_t pBuf[2048] = { 0 };
const int read_unit_size = 2048;
FILE* rfp = NULL;
int iRet = RET_CODE_SUCCESS;
int64_t file_size = 0;
auto iter_srcfmt = g_params.find("srcfmt");
if (iter_srcfmt == g_params.end())
return RET_CODE_ERROR_NOTIMPL;
NAL_CODING coding = NAL_CODING_UNKNOWN;
if (iter_srcfmt->second.compare("h264") == 0)
coding = NAL_CODING_AVC;
else if (iter_srcfmt->second.compare("h265") == 0)
coding = NAL_CODING_HEVC;
else if (iter_srcfmt->second.compare("h266") == 0)
coding = NAL_CODING_VVC;
else
{
printf("Only support H.264/265/266 at present.\n");
return RET_CODE_ERROR_NOTIMPL;
}
int top = GetTopRecordCount();
CNALParser NALParser(coding);
IUnknown* pMSECtx = nullptr;
if (AMP_FAILED(NALParser.GetContext(&pMSECtx)) ||
FAILED(pMSECtx->QueryInterface(IID_INALContext, (void**)&pNALContext)))
{
AMP_SAFERELEASE(pMSECtx);
printf("Failed to get the %s NAL context.\n", NAL_CODING_NAME(coding));
return RET_CODE_ERROR_NOTIMPL;
}
AMP_SAFERELEASE(pMSECtx);
if (coding == NAL_CODING_AVC)
{
if (object_type == 1)
{
printf("No VPS object in H.264 stream.\n");
return RET_CODE_INVALID_PARAMETER;
}
else if (object_type == 2 || object_type == 82)
pNALContext->SetNUFilters({ BST::H264Video::SPS_NUT });
else if (object_type == 3)
pNALContext->SetNUFilters({ BST::H264Video::SPS_NUT, BST::H264Video::PPS_NUT });
}
else if (coding == NAL_CODING_HEVC)
{
if (object_type == 1 || object_type == 81)
pNALContext->SetNUFilters({ BST::H265Video::VPS_NUT });
else if (object_type == 2 || object_type == 82)
pNALContext->SetNUFilters({ BST::H265Video::VPS_NUT, BST::H265Video::SPS_NUT });
else if (object_type == 3)
pNALContext->SetNUFilters({ BST::H265Video::VPS_NUT, BST::H265Video::SPS_NUT, BST::H265Video::PPS_NUT });
}
else if (coding == NAL_CODING_VVC)
{
if (object_type == 1 || object_type == 81)
pNALContext->SetNUFilters({ BST::H266Video::VPS_NUT });
else if (object_type == 2 || object_type == 82)
pNALContext->SetNUFilters({ BST::H266Video::VPS_NUT, BST::H266Video::SPS_NUT });
else if (object_type == 3)
pNALContext->SetNUFilters({ BST::H266Video::VPS_NUT, BST::H266Video::SPS_NUT, BST::H266Video::PPS_NUT });
}
class CNALEnumerator : public CComUnknown, public INALEnumerator
{
public:
CNALEnumerator(INALContext* pNALCtx, int objType) : m_pNALContext(pNALCtx), object_type(objType) {
m_coding = m_pNALContext->GetNALCoding();
if (m_pNALContext)
m_pNALContext->AddRef();
if (m_coding == NAL_CODING_AVC)
m_pNALContext->QueryInterface(IID_INALAVCContext, (void**)&m_pNALAVCContext);
else if (m_coding == NAL_CODING_HEVC)
m_pNALContext->QueryInterface(IID_INALHEVCContext, (void**)&m_pNALHEVCContext);
}
virtual ~CNALEnumerator() {
AMP_SAFERELEASE(m_pNALAVCContext);
AMP_SAFERELEASE(m_pNALHEVCContext);
AMP_SAFERELEASE(m_pNALContext);
}
DECLARE_IUNKNOWN
HRESULT NonDelegatingQueryInterface(REFIID uuid, void** ppvObj)
{
if (ppvObj == NULL)
return E_POINTER;
if (uuid == IID_INALEnumerator)
return GetCOMInterface((INALEnumerator*)this, ppvObj);
return CComUnknown::NonDelegatingQueryInterface(uuid, ppvObj);
}
RET_CODE EnumNewVSEQ(IUnknown* pCtx) { return RET_CODE_SUCCESS; }
RET_CODE EnumNewCVS(IUnknown* pCtx, int8_t represent_nal_unit_type) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALAUBegin(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf, int picture_slice_type){return RET_CODE_SUCCESS;}
RET_CODE EnumNALUnitBegin(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
int iRet = RET_CODE_SUCCESS;
uint8_t nal_unit_type = 0xFF;
AMBst bst = AMBst_CreateFromBuffer(pEBSPNUBuf, (int)cbEBSPNUBuf);
if (m_coding == NAL_CODING_AVC)
{
nal_unit_type = (pEBSPNUBuf[0] & 0x1F);
if (nal_unit_type == BST::H264Video::SPS_NUT || nal_unit_type == BST::H264Video::PPS_NUT)
{
H264_NU nu = m_pNALAVCContext->CreateAVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s parameter set {error: %d}.\n", avc_nal_unit_type_descs[nal_unit_type], iRet);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H264Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALAVCContext->UpdateAVCSPS(nu);
if (object_type == 2)
PrintMediaObject(nu.get());
else if (object_type == 82)
PrintAVCSPSRoughInfo(nu);
else if (object_type == 12)
PrintHRDFromAVCSPS(nu);
}
else if (nal_unit_type == BST::H264Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALAVCContext->UpdateAVCPPS(nu);
if (object_type == 3)
PrintMediaObject(nu.get());
}
}
}
else if (m_coding == NAL_CODING_HEVC)
{
nal_unit_type = ((pEBSPNUBuf[0] >> 1) & 0x3F);
if (nal_unit_type == BST::H265Video::VPS_NUT || nal_unit_type == BST::H265Video::SPS_NUT || nal_unit_type == BST::H265Video::PPS_NUT)
{
H265_NU nu = m_pNALHEVCContext->CreateHEVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s.\n", hevc_nal_unit_type_names[nal_unit_type]);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H265Video::VPS_NUT)
{
if (memcmp(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCVPS(nu);
if (object_type == 1)
PrintMediaObject(nu.get());
}
else if (nal_unit_type == BST::H265Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCSPS(nu);
if (object_type == 2)
PrintMediaObject(nu.get());
else if (object_type == 82)
PrintHEVCSPSRoughInfo(nu);
else if (object_type == 12)
PrintHRDFromHEVCSPS(nu);
}
else if (nal_unit_type == BST::H265Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCPPS(nu);
if (object_type == 3)
PrintMediaObject(nu.get());
}
}
}
done:
if (bst)
AMBst_Destroy(bst);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIMessageBegin(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALSEIPayloadBegin(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf)
{
if (payload_type == SEI_PAYLOAD_BUFFERING_PERIOD)
{
if (object_type == 12)
{
// Try to activate SPS
if (cbRBSPPayloadBuf > 0)
{
AMBst bst = AMBst_CreateFromBuffer(pRBSPSEIPayloadBuf, (int)cbRBSPPayloadBuf);
try
{
uint64_t bp_seq_parameter_set_id = AMBst_Get_ue(bst);
if (bp_seq_parameter_set_id >= 0 && bp_seq_parameter_set_id <= 15)
{
if (m_coding == NAL_CODING_HEVC && m_pNALHEVCContext)
m_pNALHEVCContext->ActivateSPS((int8_t)bp_seq_parameter_set_id);
else if (m_coding == NAL_CODING_AVC && m_pNALAVCContext)
m_pNALAVCContext->ActivateSPS((int8_t)bp_seq_parameter_set_id);
}
}
catch (...)
{
}
}
PrintHRDFromSEIPayloadBufferingPeriod(pCtx, pRBSPSEIPayloadBuf, cbRBSPPayloadBuf);
}
}
else if (payload_type == SEI_PAYLOAD_PIC_TIMING)
{
if (object_type == 12)
PrintHRDFromSEIPayloadPicTiming(pCtx, pRBSPSEIPayloadBuf, cbRBSPPayloadBuf);
}
else if (payload_type == SEI_PAYLOAD_ACTIVE_PARAMETER_SETS && m_coding == NAL_CODING_HEVC && m_pNALHEVCContext)
{
if (object_type == 12 && cbRBSPPayloadBuf > 0)
{
AMBst bst = AMBst_CreateFromBuffer(pRBSPSEIPayloadBuf, (int)cbRBSPPayloadBuf);
try
{
AMBst_SkipBits(bst, 6);
uint64_t num_sps_ids_minus1 = AMBst_Get_ue(bst);
uint64_t active_seq_parameter_set_id0 = AMBst_Get_ue(bst);
if (active_seq_parameter_set_id0 >= 0 && active_seq_parameter_set_id0 <= 15)
{
m_pNALHEVCContext->ActivateSPS((int8_t)active_seq_parameter_set_id0);
}
}
catch (...)
{
}
AMBst_Destroy(bst);
}
}
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIPayloadEnd(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALSEIMessageEnd(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALUnitEnd(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
m_NUCount++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALAUEnd(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf){return RET_CODE_SUCCESS;}
RET_CODE EnumNALError(IUnknown* pCtx, uint64_t stream_offset, int error_code)
{
printf("Hitting error {error_code: %d}.\n", error_code);
return RET_CODE_SUCCESS;
}
INALContext* m_pNALContext = nullptr;
INALAVCContext* m_pNALAVCContext = nullptr;
INALHEVCContext* m_pNALHEVCContext = nullptr;
uint64_t m_NUCount = 0;
NAL_CODING m_coding = NAL_CODING_UNKNOWN;
AMSHA1_RET prev_sps_sha1_ret[32] = { {0} };
AMSHA1_RET prev_vps_sha1_ret[32] = { {0} };
// H.264, there may be 256 pps at maximum; H.265/266: there may be 64 pps at maximum
AMSHA1_RET prev_pps_sha1_ret[256] = { {0} };
int object_type = -1;
}NALEnumerator(pNALContext, object_type);
errno_t errn = fopen_s(&rfp, g_params["input"].c_str(), "rb");
if (errn != 0 || rfp == NULL)
{
printf("Failed to open the file: %s {errno: %d}.\n", g_params["input"].c_str(), errn);
goto done;
}
// Get file size
_fseeki64(rfp, 0, SEEK_END);
file_size = _ftelli64(rfp);
_fseeki64(rfp, 0, SEEK_SET);
NALEnumerator.AddRef();
NALParser.SetEnumerator((IUnknown*)(&NALEnumerator), object_type == 12?NAL_ENUM_OPTION_ALL:NAL_ENUM_OPTION_NU);
do
{
int read_size = read_unit_size;
if ((read_size = (int)fread(pBuf, 1, read_unit_size, rfp)) <= 0)
{
iRet = RET_CODE_IO_READ_ERROR;
break;
}
iRet = NALParser.ProcessInput(pBuf, read_size);
if (AMP_FAILED(iRet))
break;
iRet = NALParser.ProcessOutput();
if (iRet == RET_CODE_ABORT)
break;
} while (!feof(rfp));
if (feof(rfp))
iRet = NALParser.ProcessOutput(true);
done:
if (rfp != nullptr)
fclose(rfp);
if (pNALContext)
{
pNALContext->Release();
pNALContext = nullptr;
}
return iRet;
}
int ShowVPS()
{
return ShowNALObj(1);
}
int ShowSPS()
{
return ShowNALObj(2);
}
int ShowNALInfo()
{
return ShowNALObj(82);
}
int ShowPPS()
{
return ShowNALObj(3);
}
int ShowHRD()
{
return ShowNALObj(12);
}
// At present, only support Type-II HRD
int RunH264HRD()
{
INALContext* pNALContext = nullptr;
uint8_t pBuf[2048] = { 0 };
const int read_unit_size = 2048;
FILE* rfp = NULL;
int iRet = RET_CODE_SUCCESS;
int64_t file_size = 0;
auto iter_srcfmt = g_params.find("srcfmt");
if (iter_srcfmt == g_params.end())
return RET_CODE_ERROR_NOTIMPL;
NAL_CODING coding = NAL_CODING_UNKNOWN;
if (iter_srcfmt->second.compare("h264") == 0)
coding = NAL_CODING_AVC;
else if (iter_srcfmt->second.compare("h265") == 0)
coding = NAL_CODING_HEVC;
else if (iter_srcfmt->second.compare("h266") == 0)
coding = NAL_CODING_VVC;
else
{
printf("Only support H.264/265/266 at present.\n");
return RET_CODE_ERROR_NOTIMPL;
}
int top = GetTopRecordCount();
CNALParser NALParser(coding);
IUnknown* pMSECtx = nullptr;
if (AMP_FAILED(NALParser.GetContext(&pMSECtx)) ||
FAILED(pMSECtx->QueryInterface(IID_INALContext, (void**)&pNALContext)))
{
AMP_SAFERELEASE(pMSECtx);
printf("Failed to get the %s NAL context.\n", NAL_CODING_NAME(coding));
return RET_CODE_ERROR_NOTIMPL;
}
AMP_SAFERELEASE(pMSECtx);
class CHRDRunner : public CComUnknown, public INALEnumerator
{
public:
CHRDRunner(INALContext* pNALCtx) : m_pNALContext(pNALCtx) {
if (m_pNALContext)
m_pNALContext->AddRef();
m_coding = m_pNALContext->GetNALCoding();
if (m_coding == NAL_CODING_AVC)
m_pNALContext->QueryInterface(IID_INALAVCContext, (void**)&m_pNALAVCContext);
else if (m_coding == NAL_CODING_HEVC)
m_pNALContext->QueryInterface(IID_INALHEVCContext, (void**)&m_pNALHEVCContext);
}
virtual ~CHRDRunner() {
AMP_SAFERELEASE(m_pNALAVCContext);
AMP_SAFERELEASE(m_pNALHEVCContext);
AMP_SAFERELEASE(m_pNALContext);
}
DECLARE_IUNKNOWN
HRESULT NonDelegatingQueryInterface(REFIID uuid, void** ppvObj)
{
if (ppvObj == NULL)
return E_POINTER;
if (uuid == IID_INALEnumerator)
return GetCOMInterface((INALEnumerator*)this, ppvObj);
return CComUnknown::NonDelegatingQueryInterface(uuid, ppvObj);
}
public:
RET_CODE EnumNewVSEQ(IUnknown* pCtx) { return RET_CODE_SUCCESS; }
RET_CODE EnumNewCVS(IUnknown* pCtx, int8_t represent_nal_unit_type) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALAUBegin(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf, int picture_slice_type)
{
bHaveSEIBufferingPeriod = false;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALUnitBegin(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
int iRet = RET_CODE_SUCCESS;
uint8_t nal_unit_type = 0xFF;
AMBst bst = AMBst_CreateFromBuffer(pEBSPNUBuf, (int)cbEBSPNUBuf);
if (m_coding == NAL_CODING_AVC)
{
nal_unit_type = (pEBSPNUBuf[0] & 0x1F);
if (nal_unit_type == BST::H264Video::SPS_NUT || nal_unit_type == BST::H264Video::PPS_NUT)
{
H264_NU nu = m_pNALAVCContext->CreateAVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s parameter set {error: %d}.\n", avc_nal_unit_type_descs[nal_unit_type], iRet);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H264Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALAVCContext->UpdateAVCSPS(nu);
}
else if (nal_unit_type == BST::H264Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALAVCContext->UpdateAVCPPS(nu);
}
}
}
else if (m_coding == NAL_CODING_HEVC)
{
nal_unit_type = ((pEBSPNUBuf[0] >> 1) & 0x3F);
if (nal_unit_type == BST::H265Video::VPS_NUT || nal_unit_type == BST::H265Video::SPS_NUT || nal_unit_type == BST::H265Video::PPS_NUT)
{
H265_NU nu = m_pNALHEVCContext->CreateHEVCNU();
if (AMP_FAILED(iRet = nu->Map(bst)))
{
printf("Failed to unpack %s.\n", hevc_nal_unit_type_names[nal_unit_type]);
goto done;
}
// Check whether the buffer is the same with previous one or not
AMSHA1_RET sha1_ret = { 0 };
AMSHA1 sha1_handle = AM_SHA1_Init(pEBSPNUBuf, (int)cbEBSPNUBuf);
AM_SHA1_Finalize(sha1_handle);
AM_SHA1_GetHash(sha1_handle, sha1_ret);
AM_SHA1_Uninit(sha1_handle);
if (nal_unit_type == BST::H265Video::VPS_NUT)
{
if (memcmp(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_vps_sha1_ret[nu->ptr_video_parameter_set_rbsp->vps_video_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCVPS(nu);
}
else if (nal_unit_type == BST::H265Video::SPS_NUT)
{
if (memcmp(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_sps_sha1_ret[nu->ptr_seq_parameter_set_rbsp->sps_seq_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCSPS(nu);
}
else if (nal_unit_type == BST::H265Video::PPS_NUT)
{
if (memcmp(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET)) == 0)
goto done;
else
memcpy(prev_pps_sha1_ret[nu->ptr_pic_parameter_set_rbsp->pps_pic_parameter_set_id], sha1_ret, sizeof(AMSHA1_RET));
m_pNALHEVCContext->UpdateHEVCPPS(nu);
}
}
}
done:
if (bst)
AMBst_Destroy(bst);
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIMessageBegin(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALSEIPayloadBegin(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf)
{
if (payload_type == SEI_PAYLOAD_BUFFERING_PERIOD)
{
BeginBufferPeriod(pCtx, pRBSPSEIPayloadBuf, cbRBSPPayloadBuf);
}
else if (payload_type == SEI_PAYLOAD_PIC_TIMING)
{
BeginPicTiming(pCtx, pRBSPSEIPayloadBuf, cbRBSPPayloadBuf);
}
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALSEIPayloadEnd(IUnknown* pCtx, uint32_t payload_type, uint8_t* pRBSPSEIPayloadBuf, size_t cbRBSPPayloadBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALSEIMessageEnd(IUnknown* pCtx, uint8_t* pRBSPSEIMsgRBSPBuf, size_t cbRBSPSEIMsgBuf) { return RET_CODE_SUCCESS; }
RET_CODE EnumNALUnitEnd(IUnknown* pCtx, uint8_t* pEBSPNUBuf, size_t cbEBSPNUBuf)
{
m_NUCount++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALAUEnd(IUnknown* pCtx, uint8_t* pEBSPAUBuf, size_t cbEBSPAUBuf)
{
uint64_t t_ai_earliest = UINT64_MAX;
/*
Update the t_a_f
The final arrival time for access unit n is derived by
*/
uint64_t t_a_f = UINT64_MAX;
// Assume going into the CPB buffer now
if (HRD_AU_n == 0)
{
HRD_AU_t_ai.push_back(0);
HRD_AU_t_r_n.push_back(active_initial_cpb_removal_delay);
}
else if (HRD_AU_n != UINT32_MAX)
{
if (active_cbr_flag == 1)
{
/*
If cbr_flag[ SchedSelIdx ] is equal to 1, the initial arrival time for access unit n,
is equal to the final arrival time (which is derived below) of access unit n-1, i.e.,
*/
HRD_AU_t_ai.push_back(HRD_AU_t_af.back());
}
else
{
/*
Otherwise (cbr_flag[ SchedSelIdx ] is equal to 0), the initial arrival time for access unit n is derived by
*/
assert(HRD_AU_t_r.size() == (uint64_t)HRD_AU_n + 1);
if (HRD_AU_n_of_buffering_period == 0)
{
if (HRD_AU_t_r.back() > active_initial_cpb_removal_delay)
t_ai_earliest = HRD_AU_t_r.back() - active_initial_cpb_removal_delay;
else
t_ai_earliest = 0;
}
else
{
if (HRD_AU_t_r.back() > ((uint64_t)active_initial_cpb_removal_delay + active_initial_cpb_removal_delay_offset))
t_ai_earliest = HRD_AU_t_r.back() - ((uint64_t)active_initial_cpb_removal_delay + active_initial_cpb_removal_delay_offset);
else
t_ai_earliest = 0;
}
uint64_t t_ai = AMP_MAX(HRD_AU_t_af.back(), t_ai_earliest);
HRD_AU_t_ai.push_back(t_ai);
}
}
assert(HRD_AU_n == HRD_AU_t_af.size());
t_a_f = HRD_AU_t_ai.back() + cbEBSPAUBuf * 8ULL * 90000 / active_bitrate;
HRD_AU_t_af.push_back(t_a_f);
int64_t delta_t_g_90 = -1LL;
if (HRD_AU_t_r.back() < HRD_AU_t_af.back())
{
printf("\t!!!!!!!!CPB will underflow.\n");
}
else if (HRD_AU_n > 0)
{
delta_t_g_90 = HRD_AU_t_r.back() - HRD_AU_t_af[HRD_AU_n - 1];
//if (!active_cbr_flag)
//{
// if (active_initial_cpb_removal_delay > delta_t_g_90)
// printf("assert happened!!!\n");
//}
//else
//{
// //
//}
}
printf("[AU#%05" PRIu32 "] -- initial arrive time: %" PRIu64 "(%" PRIu64 ".%03" PRIu64 "ms), final arrive time: %" PRIu64 "(%" PRIu64 ".%03" PRIu64 "ms), CPB removal time: %" PRIu64 "(%" PRIu64 ".%03" PRIu64 "ms), delta_t_g_90: %" PRId64 "\n",
HRD_AU_n,
HRD_AU_t_ai.back(), HRD_AU_t_ai.back()/90, HRD_AU_t_ai.back() * 100 / 9 % 1000,
HRD_AU_t_af.back(), HRD_AU_t_af.back()/90, HRD_AU_t_af.back() * 100 / 9 % 1000,
HRD_AU_t_r.back(), HRD_AU_t_r.back()/90 , HRD_AU_t_r.back() * 100 / 9 % 1000,
delta_t_g_90);
HRD_AU_n++;
HRD_AU_n_of_buffering_period++;
return RET_CODE_SUCCESS;
}
RET_CODE EnumNALError(IUnknown* pCtx, uint64_t stream_offset, int error_code)
{
printf("Hitting error {error_code: %d}.\n", error_code);
return RET_CODE_SUCCESS;
}
int BeginBufferPeriod(IUnknown* pCtx, uint8_t* pSEIPayload, size_t cbSEIPayload)
{
int iRet = RET_CODE_SUCCESS;
uint32_t sel_initial_cpb_removal_delay = UINT32_MAX;
uint32_t sel_initial_cpb_removal_delay_offset = UINT32_MAX;
if (pSEIPayload == nullptr || cbSEIPayload == 0 || pCtx == nullptr)
return RET_CODE_INVALID_PARAMETER;
INALContext* pNALCtx = nullptr;
if (FAILED(pCtx->QueryInterface(IID_INALContext, (void**)&pNALCtx)))
return RET_CODE_INVALID_PARAMETER;
AMBst bst = nullptr;
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::BUFFERING_PERIOD* pBufPeriod = new
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::BUFFERING_PERIOD((int)cbSEIPayload, pNALCtx);
NAL_CODING coding = pNALCtx->GetNALCoding();
if (pBufPeriod != nullptr)
bst = AMBst_CreateFromBuffer(pSEIPayload, (int)cbSEIPayload);
if (pBufPeriod == nullptr || bst == nullptr)
{
iRet = RET_CODE_OUTOFMEMORY;
goto done;
}
if (AMP_FAILED(iRet = pBufPeriod->Map(bst)))
{
printf("Failed to unpack the SEI payload: buffering period.\n");
goto done;
}
if (coding == NAL_CODING_AVC)
{
H264_NU sps_nu;
INALAVCContext* pNALAVCCtx = nullptr;
if (SUCCEEDED(pNALCtx->QueryInterface(IID_INALAVCContext, (void**)&pNALAVCCtx)))
{
sps_nu = pNALAVCCtx->GetAVCSPS(pBufPeriod->bp_seq_parameter_set_id);
active_sps = sps_nu;
pNALAVCCtx->Release();
pNALAVCCtx = nullptr;
}
if (sps_nu &&
sps_nu->ptr_seq_parameter_set_rbsp != nullptr &&
sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters)
{
auto vui_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters;
if (vui_parameters->vcl_hrd_parameters_present_flag)
{
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->vcl_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
if (active_HRD_type == 1 && active_SchedSelIdx == SchedSelIdx)
{
sel_initial_cpb_removal_delay = pBufPeriod->vcl_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_delay;
sel_initial_cpb_removal_delay_offset = pBufPeriod->vcl_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_offset;
active_cbr_flag = hrd_parameters->cbr_flag[SchedSelIdx];
active_bitrate = ((uint64_t)hrd_parameters->bit_rate_value_minus1[SchedSelIdx] + 1) * (uint64_t)1ULL << (6 + hrd_parameters->bit_rate_scale);
active_cpb_size = ((uint64_t)hrd_parameters->cpb_size_value_minus1[SchedSelIdx] + 1)*(uint64_t)1ULL << (4 + hrd_parameters->cpb_size_scale);
break;
}
}
}
if (vui_parameters->nal_hrd_parameters_present_flag)
{
auto hrd_parameters = sps_nu->ptr_seq_parameter_set_rbsp->seq_parameter_set_data.vui_parameters->nal_hrd_parameters;
for (uint8_t SchedSelIdx = 0; SchedSelIdx <= hrd_parameters->cpb_cnt_minus1; SchedSelIdx++)
{
if (active_HRD_type == 2 && active_SchedSelIdx == SchedSelIdx)
{
sel_initial_cpb_removal_delay = pBufPeriod->nal_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_delay;
sel_initial_cpb_removal_delay_offset = pBufPeriod->nal_initial_cpb_removal_info[SchedSelIdx].initial_cpb_removal_offset;
active_cbr_flag = hrd_parameters->cbr_flag[SchedSelIdx];
active_bitrate = ((uint64_t)hrd_parameters->bit_rate_value_minus1[SchedSelIdx] + 1) * (uint64_t)1ULL << (6 + hrd_parameters->bit_rate_scale);
active_cpb_size = ((uint64_t)hrd_parameters->cpb_size_value_minus1[SchedSelIdx] + 1)*(uint64_t)1ULL << (4 + hrd_parameters->cpb_size_scale);
break;
}
}
}
if (vui_parameters->timing_info_present_flag)
HRD_t_c = vui_parameters->num_units_in_tick * 90000ULL / vui_parameters->time_scale;
active_low_delay_hrd_flag = vui_parameters->low_delay_hrd_flag;
printf("New buffering period(initial_cpb_removal_delay:%" PRIu32 " initial_cpb_removal_delay_offset:%" PRIu32 ")\n",
sel_initial_cpb_removal_delay, sel_initial_cpb_removal_delay_offset);
}
}
else if (coding == NAL_CODING_HEVC)
{
}
else if (coding == NAL_CODING_VVC)
{
}
// Initialize the HRD
if (bHRDInited == false)
{
HRD_AU_n = 0;
HRD_AU_t_ai.clear();
HRD_AU_t_r_n.clear();
active_initial_cpb_removal_delay = sel_initial_cpb_removal_delay;
active_initial_cpb_removal_delay_offset = sel_initial_cpb_removal_delay_offset;
bHRDInited = true;
}
HRD_AU_n_of_buffering_period = 0;
bHaveSEIBufferingPeriod = true;
done:
if (bst)
AMBst_Destroy(bst);
AMP_SAFEDEL(pBufPeriod);
AMP_SAFERELEASE(pNALCtx);
return iRet;
}
int BeginPicTiming(IUnknown* pCtx, uint8_t* pSEIPayload, size_t cbSEIPayload)
{
int iRet = RET_CODE_SUCCESS;
if (pSEIPayload == nullptr || cbSEIPayload == 0 || pCtx == nullptr)
return RET_CODE_INVALID_PARAMETER;
INALContext* pNALCtx = nullptr;
if (FAILED(pCtx->QueryInterface(IID_INALContext, (void**)&pNALCtx)))
return RET_CODE_INVALID_PARAMETER;
NAL_CODING coding = pNALCtx->GetNALCoding();
AMBst bst = nullptr;
bst = AMBst_CreateFromBuffer(pSEIPayload, (int)cbSEIPayload);
BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H264* pPicTiming = nullptr;
if (bst == nullptr)
{
iRet = RET_CODE_OUTOFMEMORY;
goto done;
}
if (coding == NAL_CODING_AVC)
{
pPicTiming = new BST::SEI_RBSP::SEI_MESSAGE::SEI_PAYLOAD::PIC_TIMING_H264((int)cbSEIPayload, pNALCtx);
if (AMP_FAILED(iRet = pPicTiming->Map(bst)))
{
printf("Failed to unpack the SEI payload: buffering period.\n");
goto done;
}
uint64_t t_r_n = UINT64_MAX;
if (HRD_AU_n > 0)
{
if (bHaveSEIBufferingPeriod)
{
/*
When an access unit n is the first access unit of a buffering period that does not initialize the HRD,
the nominal removal time of the access unit from the CPB is specified by
*/
if (HRD_AU_previous_t_r_n != UINT64_MAX && HRD_t_c != UINT64_MAX)
{
t_r_n = HRD_AU_previous_t_r_n + HRD_t_c * pPicTiming->cpb_removal_delay;
HRD_AU_t_r_n.push_back(t_r_n);
HRD_AU_previous_t_r_n = t_r_n;
}
}
else
{
/*
The nominal removal time tr,n(n) of an access unit n that is not the first access unit of a buffering period is given by
*/
t_r_n = HRD_AU_previous_t_r_n + HRD_t_c * pPicTiming->cpb_removal_delay;
HRD_AU_t_r_n.push_back(t_r_n);
}
}
else
{
t_r_n = active_initial_cpb_removal_delay;
HRD_AU_previous_t_r_n = t_r_n;
}
if (active_low_delay_hrd_flag == 0 || t_r_n >= HRD_AU_t_af[HRD_AU_n])
{
/*
If low_delay_hrd_flag is equal to 0 or tr,n( n ) >= taf( n ), the removal time of access unit n is specified by
*/
HRD_AU_t_r.push_back(t_r_n);
}
else
{
uint64_t t_r = t_r_n + (HRD_AU_t_af[HRD_AU_n] - t_r_n + HRD_t_c - 1) / HRD_t_c * HRD_t_c;
HRD_AU_t_r.push_back(t_r);
}
}
done:
if (bst)
AMBst_Destroy(bst);
AMP_SAFEDEL(pPicTiming);
AMP_SAFERELEASE(pNALCtx);
return iRet;
}
INALContext* m_pNALContext = nullptr;
INALAVCContext* m_pNALAVCContext = nullptr;
INALHEVCContext* m_pNALHEVCContext = nullptr;
uint64_t m_NUCount = 0;
NAL_CODING m_coding = NAL_CODING_UNKNOWN;
AMSHA1_RET prev_sps_sha1_ret[32] = { {0} };
AMSHA1_RET prev_vps_sha1_ret[32] = { {0} };
// H.264, there may be 256 pps at maximum; H.265/266: there may be 64 pps at maximum
AMSHA1_RET prev_pps_sha1_ret[256] = { {0} };
H264_NU active_sps;
uint32_t active_HRD_type = 2; // At present, only support HDR type-II
uint32_t active_SchedSelIdx = 0; // At present, always using the first one
uint32_t active_initial_cpb_removal_delay = UINT32_MAX;
uint32_t active_initial_cpb_removal_delay_offset = UINT32_MAX;
uint32_t active_cbr_flag = UINT32_MAX;
uint32_t active_low_delay_hrd_flag = UINT32_MAX;
uint64_t active_bitrate = UINT64_MAX;
uint64_t active_cpb_size = 0;
// For HRD analyzing
bool bHRDInited = false;
uint32_t HRD_AU_n = UINT32_MAX;
uint32_t HRD_AU_n_of_buffering_period = UINT32_MAX;
std::vector<uint64_t> HRD_AU_t_ai;
std::vector<uint64_t> HRD_AU_t_af;
std::vector<uint64_t> HRD_AU_t_r_n;
std::vector<uint64_t> HRD_AU_t_r;
bool bHaveSEIBufferingPeriod = false;
uint64_t HRD_AU_previous_t_r_n = UINT64_MAX;
uint64_t HRD_t_c = UINT64_MAX;
}HRDRunner(pNALContext);
errno_t errn = fopen_s(&rfp, g_params["input"].c_str(), "rb");
if (errn != 0 || rfp == NULL)
{
printf("Failed to open the file: %s {errno: %d}.\n", g_params["input"].c_str(), errn);
goto done;
}
// Get file size
_fseeki64(rfp, 0, SEEK_END);
file_size = _ftelli64(rfp);
_fseeki64(rfp, 0, SEEK_SET);
HRDRunner.AddRef();
NALParser.SetEnumerator((IUnknown*)(&HRDRunner), NAL_ENUM_OPTION_ALL);
do
{
int read_size = read_unit_size;
if ((read_size = (int)fread(pBuf, 1, read_unit_size, rfp)) <= 0)
{
iRet = RET_CODE_IO_READ_ERROR;
break;
}
iRet = NALParser.ProcessInput(pBuf, read_size);
if (AMP_FAILED(iRet))
break;
iRet = NALParser.ProcessOutput();
if (iRet == RET_CODE_ABORT)
break;
} while (!feof(rfp));
if (feof(rfp))
iRet = NALParser.ProcessOutput(true);
done:
if (rfp != nullptr)
fclose(rfp);
if (pNALContext)
{
pNALContext->Release();
pNALContext = nullptr;
}
return iRet;
}
| 36.936226 | 247 | 0.720019 | [
"object",
"vector"
] |
b52b1d42418b8f1b6e7988c6d492780c1ab5e533 | 2,440 | hh | C++ | src/structured-interface/input_state.hh | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | 1 | 2020-12-09T13:55:07.000Z | 2020-12-09T13:55:07.000Z | src/structured-interface/input_state.hh | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | 1 | 2019-09-29T09:02:03.000Z | 2019-09-29T09:02:03.000Z | src/structured-interface/input_state.hh | project-arcana/structured-interface | 56054310e08a3ae98f8065a90b454e23a36d60d9 | [
"MIT"
] | null | null | null | #pragma once
#include <clean-core/vector.hh>
#include <typed-geometry/tg-lean.hh>
#include <structured-interface/handles.hh>
namespace si
{
/// a helper struct that contains the input state of an element_tree
/// used for answering user-space queries such as "is_hovered" or "was_clicked"
/// (without querying into the element_tree directly)
///
/// TODO: is_hovered during record can be optimized by tracking the hover stack
struct input_state
{
element_handle direct_hover_last;
element_handle direct_hover_curr;
element_handle focus_last;
element_handle focus_curr;
// hover stack
// NOTE: topmost element is first
// NOTE: currently ignores detached, i.e. follows the recorded ui structure
cc::vector<element_handle> hovers_last;
cc::vector<element_handle> hovers_curr;
// TODO: invalid pressed when released outside?
element_handle pressed_last;
element_handle pressed_curr;
bool is_drag = false; // TODO: also a timed component?
element_handle clicked_curr; // no last
// NOTE: in some mergers, this doesn't make much sense
tg::pos2 mouse_pos;
tg::vec2 mouse_delta;
tg::vec2 scroll_delta;
// sets "last" to "curr" and "curr" to empty
void on_next_update();
// common queries
public:
bool was_clicked(element_handle id) const { return clicked_curr == id; }
bool is_hovered(element_handle id) const { return hovers_curr.contains(id); }
bool is_hover_entered(element_handle id) const { return hovers_curr.contains(id) && !hovers_last.contains(id); }
bool is_hover_left(element_handle id) const { return !hovers_curr.contains(id) && hovers_last.contains(id); }
bool is_direct_hovered(element_handle id) const { return direct_hover_curr == id; }
bool is_direct_hover_entered(element_handle id) const { return direct_hover_curr == id && direct_hover_last != id; }
bool is_direct_hover_left(element_handle id) const { return direct_hover_curr != id && direct_hover_last == id; }
bool is_pressed(element_handle id) const { return pressed_curr == id; }
bool is_focused(element_handle id) const { return focus_curr == id; }
bool is_focus_gained(element_handle id) const { return focus_curr == id && focus_last != id; }
bool is_focus_lost(element_handle id) const { return focus_curr != id && focus_last == id; }
bool is_dragged(element_handle id) const { return pressed_curr == id && is_drag; }
};
}
| 40 | 120 | 0.729098 | [
"geometry",
"vector"
] |
b52bf4fd8c5faf00f9b23114a80633e8ec71385d | 2,114 | cpp | C++ | database.cpp | guilhermota/Projeto_Robotica | 9a7e30332dd161b50e5b352f10c7319865ac5f7e | [
"MIT"
] | null | null | null | database.cpp | guilhermota/Projeto_Robotica | 9a7e30332dd161b50e5b352f10c7319865ac5f7e | [
"MIT"
] | null | null | null | database.cpp | guilhermota/Projeto_Robotica | 9a7e30332dd161b50e5b352f10c7319865ac5f7e | [
"MIT"
] | null | null | null | #include "database.h"
/**
* @brief database::database
* Abre conexão com o banco de dados
*/
database::database(QString hostname, QString dbname, QString username, QString password)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(hostname);
db.setPort(3307);
db.setDatabaseName(dbname);
db.setUserName(username);
db.setPassword(password);
db.open();
isOpen = db.isOpen();
if(isOpen){
qDebug() << "Conected to database;";
} else{
qDebug() << db.driverName();
qDebug() << db.lastError();
}
}
database::~database(){}
/**
* @brief database::retrieveFaces
* Executa query que busca os usuarios cadastrados, seus nomes e o diretorio de suas imagens
*/
bool database::retrieveFaces(std::vector<std::string> *path, std::vector<std::string> *names, std::vector<int> *labels)
{
QSqlQuery query;
bool ok = query.exec("select a.nome, b.path, a.id_usuario "
"from usuarios a, imagens b, usuarios_has_imagens c "
"where a.id_usuario = c.usuarios_id_usuario "
"and b.id_imagem = c.imagens_id_imagem;");
//qDebug() << query.lastError().text();
if(ok){
//qDebug() << query.isSelect();
}
while(query.next()){
//qDebug() << "name: " << query.value(0).toString() << " path: " << query.value(1).toString();
path->push_back(query.value(1).toString().toStdString());
names->push_back(query.value(0).toString().toStdString());
labels->push_back(query.value(2).toInt());
}
return true;
}
/**
* @brief database::isConnected
* Retorna se a conexão está aberta ou não
*/
bool database::isConnected(){
return isOpen;
}
/**
* @brief database::uploadImagem
* Envia imagem ao servidor
*/
void database::uploadImagem(QByteArray imagem, int id)
{
/*QHttp
http->setHost(siteURLEdit->text());
QByteArray ba;
QBuffer buffer( &ba );
buffer.open( QBuffer::ReadWrite );
originalPixmap.save( &buffer , "PNG" );
http->post("/wp-content/plugins/wp-shotcam.php",ba);
*/
}
| 26.425 | 119 | 0.620624 | [
"vector"
] |
b5303e04729687253a0088c61bae0e17b2928a83 | 1,064 | cpp | C++ | Leetcode/Hashing/make-two-arrays-equal-by-reversing-sub-arrays.cpp | susantabiswas/competitive_coding | 49163ecdc81b68f5c1bd90988cc0dfac34ad5a31 | [
"MIT"
] | 2 | 2021-04-29T14:44:17.000Z | 2021-10-01T17:33:22.000Z | Leetcode/Hashing/make-two-arrays-equal-by-reversing-sub-arrays.cpp | adibyte95/competitive_coding | a6f084d71644606c21840875bad78d99f678a89d | [
"MIT"
] | null | null | null | Leetcode/Hashing/make-two-arrays-equal-by-reversing-sub-arrays.cpp | adibyte95/competitive_coding | a6f084d71644606c21840875bad78d99f678a89d | [
"MIT"
] | 1 | 2021-10-01T17:33:29.000Z | 2021-10-01T17:33:29.000Z | /*
https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/
Since reversal can be done any number of times, so in base case if we have 2 elements,
we can reverse them. So we only need to ensure that both are having same element frequency,
since in worst case we can always reverse 2 elements to get what is required.
TC: O(N), SC: O(N)
*/
class Solution {
public:
bool canBeEqual(vector<int>& target, vector<int>& arr) {
if(target.size() != arr.size())
return false;
// find the frequency map of target
unordered_map<int, int> freq;
for(const int& num : target)
freq[num] += 1;
// check if the second array has the same set of element frequencies
for(const int& num: arr) {
if(freq.count(num)) {
--freq[num];
if(freq[num] == 0)
freq.erase(num);
}
else
return false;
}
return freq.empty();
}
};
| 30.4 | 96 | 0.548872 | [
"vector"
] |
b5331bb509dffc83ee05d0747c8da6f0eff88940 | 10,865 | hpp | C++ | include/AudioEngine.hpp | Dinahmoe/dm-audioengine | c6b4712ee889e5e15125f86d73bfaad7f6d73088 | [
"BSD-3-Clause"
] | null | null | null | include/AudioEngine.hpp | Dinahmoe/dm-audioengine | c6b4712ee889e5e15125f86d73bfaad7f6d73088 | [
"BSD-3-Clause"
] | null | null | null | include/AudioEngine.hpp | Dinahmoe/dm-audioengine | c6b4712ee889e5e15125f86d73bfaad7f6d73088 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015, Dinahmoe. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*!
* \file AudioEngine.hpp
*
* \author Alessandro Saccoia
* \date 7/19/12
* \deprecated This class shouldn't be necessary anymore
*
* This class inherits both by AudioDriver and AudioEngine. deprecated.
*/
#ifndef __AudioEngine_hpp
#define __AudioEngine_hpp
#include <memory>
#include <functional>
#include <list>
#include <fstream>
#include "AudioContext.hpp"
#include "DmDictionary.h"
#include "NullMutex.hpp"
#include "TimeProvider.hpp"
#include "RingBuffer.hpp"
#include "AudioEngineConfig.hpp"
#if DMF_USES_OFFLINE_RENDERING
#include "AudioDriver_audiofile.hpp"
#else
#if DMF_USES_EXTERNAL_AUDIO
#include "AudioDriver_external.hpp"
#else
#ifdef DM_PLATFORM_OSX
#include "AudioDriver_osx.hpp"
#elif DM_PLATFORM_ANDROID
#include "AudioDriver_android.hpp"
#elif DM_PLATFORM_IOS
#include "AudioDriver_ios.hpp"
#elif DM_PLATFORM_LINUX
#include "AudioDriver_alsa.hpp"
#endif
#endif
#endif
namespace dinahmoe {
namespace audioengine {
template <bool IS_REALTIME>
struct MutexChooser {
typedef dinahmoe::synchro::NullMutex MUTEX_T;
};
template <>
struct MutexChooser<true> {
typedef std::mutex MUTEX_T;
};
template <class AUDIODRIVER_T>
class AudioEngine :
public AUDIODRIVER_T,
public AudioContext,
public synchro::TimeProvider {
public:
// factory method
AudioEngine(DmDictionary& params);
~AudioEngine();
void start();
void stop();
dm_time_seconds getCurrentTime();
dm_time_seconds getLatency();
private:
int cb(int channelsIn_, float** inPlaceInputBuffer,
int channelsOut_, float** inPlaceOutputBuffer,
int numberOfFrames);
RingBuffer<float>* m_inputRingBuffers;
RingBuffer<float>* m_outputRingBuffers;
float** m_inputBuffer;
float** m_outputBuffer;
size_t m_ringBufferSize;
#ifdef AE_PROFILE
typedef struct AeProfilingStruct_ {
std::chrono::system_clock::time_point start;
std::chrono::system_clock::time_point end;
unsigned long long sample;
} AeProfilingStruct;
bool m_createProfile;
std::chrono::system_clock::time_point m_startTime;
std::string m_profilingFilePath;
std::vector<AeProfilingStruct> m_profilingList;
typename std::vector<AeProfilingStruct>::iterator profit;
unsigned long long m_currentSampleNumber;
#endif
};
template <class AUDIODRIVER_T>
AudioEngine<AUDIODRIVER_T>::AudioEngine(DmDictionary& params) :
AUDIODRIVER_T(params,
[&](int channelsIn_, float** inPlaceInputBuffer,
int channelsOut_, float** inPlaceOutputBuffer, int nsamples) {
return this->AudioEngine<AUDIODRIVER_T>::cb(channelsIn_, inPlaceInputBuffer, channelsOut_, inPlaceOutputBuffer, nsamples);
}
),
AudioContext(((AUDIODRIVER_T*)this)->sampleRate(), ((AUDIODRIVER_T*)this)->outputChannels(), ((AUDIODRIVER_T*)this)->bufferSize(), AUDIODRIVER_T::IS_REALTIME),
m_ringBufferSize(0) {
if (AUDIODRIVER_T::inputChannels()) {
m_inputBuffer = new float*[AUDIODRIVER_T::inputChannels()];
m_inputRingBuffers = new RingBuffer<float>[AUDIODRIVER_T::inputChannels()];
}
if (AUDIODRIVER_T::outputChannels()) {
m_outputBuffer = new float*[AUDIODRIVER_T::outputChannels()];
m_outputRingBuffers = new RingBuffer<float>[AUDIODRIVER_T::outputChannels()];
}
// compute a good ring buffer size
size_t ringBuffersSize = (AUDIODRIVER_T::sampleRate()/2 > AUDIODRIVER_T::bufferSize()*3) ? AUDIODRIVER_T::sampleRate()/2 : AUDIODRIVER_T::bufferSize() * 3;
for (int i = 0; i < AUDIODRIVER_T::inputChannels(); ++i) {
m_inputRingBuffers[i].resize(ringBuffersSize);
m_inputRingBuffers[i].zero(AUDIODRIVER_T::bufferSize());
m_inputBuffer[i] = new float[AUDIODRIVER_T::sampleRate()/2];
}
for (int i = 0; i < AUDIODRIVER_T::outputChannels(); ++i) {
m_outputRingBuffers[i].resize(ringBuffersSize);
m_outputRingBuffers[i].zero(AUDIODRIVER_T::bufferSize());
m_outputBuffer[i] = new float[AUDIODRIVER_T::sampleRate()/2];
}
m_ringBufferSize = AUDIODRIVER_T::bufferSize();
#ifdef AE_PROFILE
m_createProfile = params.keyExists("profilingFilePath");
m_currentSampleNumber = 0;
if (m_createProfile) {
m_profilingFilePath = params.getStringValue("profilingFilePath");
m_profilingList.resize(100000);
profit = m_profilingList.begin();
}
m_startTime = std::chrono::system_clock::now();
#endif
}
template <class AUDIODRIVER_T>
AudioEngine<AUDIODRIVER_T>::~AudioEngine() {
dmaf_log(Log::Debug, "Initialization: Deleting AudioEngine");
#ifdef AE_PROFILE
if (m_createProfile) {
std::ofstream osout(m_profilingFilePath);
for (auto itl = m_profilingList.begin(); itl != profit; ++itl) {
osout << itl->sample
<< " " << std::chrono::duration_cast<std::chrono::microseconds>(itl->start - m_startTime).count()
<< " " << std::chrono::duration_cast<std::chrono::microseconds>(itl->end - m_startTime).count()
<< " " << std::chrono::duration_cast<std::chrono::microseconds>(itl->end - itl->start).count()
<< std::endl;
}
osout
<< std::endl
<< std::endl
<< "MATLAB"
<< std::endl;
osout << "TIMES = zeros(" << m_profilingList.size() << ",1);" << std::endl;
osout << "DURATIONS = zeros(" << m_profilingList.size() << ",1);" << std::endl;
int count = 1;
for (auto itl = m_profilingList.begin(); itl != profit; ++itl) {
osout << "TIMES(" << count << ") = " << ((double)itl->sample) / AudioContext::getSampleRate() << ";" << std::endl;
osout << "DURATIONS(" << count << ") = " << std::chrono::duration_cast<std::chrono::microseconds>(itl->end - itl->start).count() << ";" << std::endl;
++count;
}
osout.close();
}
#endif
for (int i = 0; i < AUDIODRIVER_T::inputChannels(); ++i) {
delete [] m_inputBuffer[i];
}
for (int i = 0; i < AUDIODRIVER_T::outputChannels(); ++i) {
delete [] m_outputBuffer[i];
}
if (AUDIODRIVER_T::inputChannels()) {
delete [] m_inputBuffer;
delete [] m_inputRingBuffers;
}
if (AUDIODRIVER_T::outputChannels()) {
delete [] m_outputBuffer;
delete [] m_outputRingBuffers;
}
}
template <class AUDIODRIVER_T>
void AudioEngine<AUDIODRIVER_T>::start() {
dmaf_log(Log::Debug, "Initialization: AudioEngine::startRendering");
((AudioContext*)this)->start();
((AUDIODRIVER_T*)this)->startRendering();
}
template <class AUDIODRIVER_T>
void AudioEngine<AUDIODRIVER_T>::stop() {
((AudioContext*)this)->stop();
((AUDIODRIVER_T*)this)->stopRendering();
// clean things up
((AudioContext*)this)->stopAllSourceNodes();
((AudioContext*)this)->updateInternalState();
dmaf_log(Log::Debug, "Initialization: AudioEngine::stopRendering");
}
template <class AUDIODRIVER_T>
int AudioEngine<AUDIODRIVER_T>::cb(int channelsIn_, float** inPlaceInputBuffer,
int channelsOut_, float** inPlaceOutputBuffer,
int numberOfFrames) {
m_ringBufferSize += numberOfFrames;
for (int i = 0; i < channelsIn_; ++i) {
m_inputRingBuffers[i].write(inPlaceInputBuffer[i], numberOfFrames);
}
while (m_ringBufferSize >= AudioContext::getBufferSize()) {
if (channelsIn_) {
for (int i = 0; i < channelsIn_; ++i) {
m_inputRingBuffers[i].read(m_inputBuffer[i], AudioContext::getBufferSize(), true);
}
}
// notify (asynchronously) the listeners
this->TimeProvider::Notify();
#ifdef AE_PROFILE
std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
#endif
((AudioContext*)this)->audioCallback(m_inputBuffer, channelsIn_, m_outputBuffer, channelsOut_, AudioContext::getBufferSize());
if (channelsOut_) {
for (int i = 0; i < channelsOut_; ++i) {
m_outputRingBuffers[i].write(m_outputBuffer[i], AudioContext::getBufferSize());
}
}
#ifdef AE_PROFILE
profit->start = start;
profit->end = std::chrono::system_clock::now();
profit->sample = m_currentSampleNumber;
m_currentSampleNumber += numberOfFrames;
++profit;
#endif
m_ringBufferSize -= AudioContext::getBufferSize();
}
if (channelsOut_) {
for (int i = 0; i < channelsOut_; ++i) {
m_outputRingBuffers[i].read(inPlaceOutputBuffer[i], numberOfFrames, true);
}
}
return numberOfFrames;
}
template <class AUDIODRIVER_T>
dm_time_seconds AudioEngine<AUDIODRIVER_T>::getLatency() {
return (((AudioContext*)this)->getBufferSize() * dm_time_seconds(AUDIODRIVER_T::IS_REALTIME? 5 : 0) / getSampleRate());
}
template <class AUDIODRIVER_T>
dm_time_seconds AudioEngine<AUDIODRIVER_T>::getCurrentTime() {
return ((AudioContext*)this)->getCurrentTime();
}
#if DMF_USES_OFFLINE_RENDERING
typedef audioengine::AudioEngine<audiodriver::AudioDriver_audiofile> AudioEngineT;
#else
#if DMF_USES_EXTERNAL_AUDIO
typedef audioengine::AudioEngine<audiodriver::AudioDriver_external> AudioEngineT;
#else
#if DM_PLATFORM_OSX
typedef audioengine::AudioEngine<audiodriver::AudioDriver_osx> AudioEngineT;
#elif DM_PLATFORM_ANDROID
typedef audioengine::AudioEngine<audiodriver::AudioDriver_android> AudioEngineT;
#elif DM_PLATFORM_IOS
typedef audioengine::AudioEngine<audiodriver::AudioDriver_ios> AudioEngineT;
#elif DM_PLATFORM_LINUX
typedef audioengine::AudioEngine<audiodriver::AudioDriver_alsa> AudioEngineT;
#endif
#endif
#endif
} // audioengine
} // dinahmoe
#endif // __AudioEngine_hpp
| 34.492063 | 161 | 0.71468 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.