void GLSL::compileShader(const std::string & filePath, GLuint id) { //Vertex and fragment shaders are successfully compiled. //Now time to link them together into a program. //Get a program object. _programID = glCreateProgram(); //load shader code std::ifstream vertexFile(filePath); if (vertexFile.fail()) { fatalError("Failed to open " + filePath); } std::string fileContent = ""; std::string line; while (std::getline(vertexFile, line)) { fileContent += line + "\n"; } vertexFile.close(); const char* contentsPtr = fileContent.c_str(); glShaderSource(id, 1, &contentsPtr, nullptr); glCompileShader(id); //error checking of shader code GLint success = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &success); GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<char> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); // Exit with failure. glDeleteShader(id); // Don't leak the shader. std::printf("%s\n", &(errorLog[0])); //Provide the infolog in whatever manor you deem best. fatalError("Shader "+ filePath+" failed to compile!"); }
void GLSProgram::compileShader(const std::string& filePath, GLuint id) { std::ifstream vertexFile(filePath); if (vertexFile.fail()) { perror(filePath.c_str()); fatalError("Failed to open " + filePath); } std::string fileContents = ""; std::string line; while (std::getline(vertexFile, line)) { // Will concat each line together with a new line and put it into fileContents fileContents += line + "\n"; } vertexFile.close(); const char* contentsPtr = fileContents.c_str(); glShaderSource(id, 1, &contentsPtr, nullptr); glCompileShader(id); GLint success = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength incledes the NULL charater std::vector<char> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); //Provide the infolog in whatever manor you deem best. //Exit with failure. glDeleteShader(id); //Don't leak the shader std::printf("%s\n", &(errorLog[0])); fatalError("Shader " + filePath + " failed to compile!"); } }
void GLSLProgram :: compileShader(const std::string&FilePath,GLuint id) { std::ifstream vertexFile(FilePath); if(vertexFile.fail()) { perror(FilePath.c_str()); fatalError("failed to open "+ FilePath); } //reading all data from file into one string variable, this very string variable will be compiled by opengl std:: string fileContents = ""; std:: string line; while(std::getline(vertexFile,line)) //reading vertexfile and adding the whole line to string line variable { fileContents +=line +"\n"; //appending string file contents with line and adding new line at end since getLine() doesn't add new line } vertexFile.close(); const char * contentsPointer = fileContents.c_str(); glShaderSource(id, //passing shader id 1, //stands for number of string, in our case we've put all text in 1 string &contentsPointer, //pointer to c string of the vertex file, opengl wants an array of c string nullptr); //wants the pointer array of integers, length of each string.. but since we have only 1 string so passing null glCompileShader(id); //finally passing the shader id for compilation //error checking for shader compilation GLint success = 0; glGetShaderiv(id,GL_COMPILE_STATUS,&success); //returns true if compiled if(success == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); //the max length includes null character std::vector<char> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); //provides info log in whatever manner we want //exit with failure glDeleteShader(id); std::printf("%s\n",&(errorLog[0])); //address of 1st element of error, that's like saying we want this to be interpreted as sting fatalError("shader"+FilePath+" failed to compile"); } }
void GLSLProgram::compileShader(const std::string& filepath, GLuint id) { std::ifstream vertexFile(filepath); if (vertexFile.fail()) { std::printf("ERROR: Failed to open %s\n", filepath); } std::string fileContents = ""; std::string line; while (std::getline(vertexFile, line)) { fileContents += line + "\n"; } vertexFile.close(); const char* contentsPtr = fileContents.c_str(); glShaderSource(id, 1, &contentsPtr, nullptr); glCompileShader(id); GLint success = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); //We don't need the shader anymore. glDeleteShader(id); std::printf("%s", &errorLog[0]); std::printf("Shader failed to compile: %s", filepath); return; } }
void GLSLProgram::compileShader(const std::string& filePath, GLuint id) { //Read in the vertex shader into a string and create shader std::ifstream vertexFile(filePath); if (vertexFile.fail()) { perror(filePath.c_str()); fatalError("Failed to open " + filePath); } std::string fileContents = ""; std::string line; while (std::getline(vertexFile, line)) { fileContents += line + "\n"; } vertexFile.close(); const char* contentPtr = fileContents.c_str(); glShaderSource(id, 1, &contentPtr, nullptr); glCompileShader(id); //Check if the shader compiled properly GLint success = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the null termination std::vector<char> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); //Show error log fatalError("Shader " + filePath + " failed to compile!\n"); std::printf("%s\n", &errorLog[0]); //Exit glDeleteShader(id); } }
void plan(KoulesSetup& ks, double maxTime, const std::string& outputFile) { if (ks.solve(maxTime)) { std::ofstream out(outputFile.c_str()); oc::PathControl path(ks.getSolutionPath()); path.interpolate(); if (!path.check()) OMPL_ERROR("Path is invalid"); writeParams(out); path.printAsMatrix(out); if (!ks.haveExactSolutionPath()) OMPL_INFORM("Solution is approximate. Distance to actual goal is %g", ks.getProblemDefinition()->getSolutionDifference()); OMPL_INFORM("Output saved in %s", outputFile.c_str()); } #if 0 // Get the planner data, save the ship's (x,y) coordinates to one file and // the edge information to another file. This can be used for debugging // purposes; plotting the tree of states might give you some idea of // a planner's strategy. ob::PlannerData pd(ks.getSpaceInformation()); ks.getPlannerData(pd); std::ofstream vertexFile((outputFile + "-vertices").c_str()), edgeFile((outputFile + "-edges").c_str()); double* coords; unsigned numVerts = pd.numVertices(); std::vector<unsigned int> edgeList; for (unsigned int i = 0; i < numVerts; ++i) { coords = pd.getVertex(i).getState()->as<KoulesStateSpace::StateType>()->values; vertexFile << coords[0] << ' ' << coords[1] << '\n'; pd.getEdges(i, edgeList); for (unsigned int j = 0; j < edgeList.size(); ++j) edgeFile << i << ' ' << edgeList[j] << '\n'; } #endif }
bool Engine::StaticCollisionMesh::LoadMeshDataFromFile(const char* i_path, HWND i_WindowHandle) { bool wereThereErrors = false; DWORD usage = 0; // Our code will only ever write to the buffer usage |= D3DUSAGE_WRITEONLY; MeshData currentMesh; if (!fileExists(i_path)) { MessageBox(i_WindowHandle, "Failed to Load Mesh File", "File not found", MB_OK | MB_ICONERROR); return false; } std::ifstream vertexFile(i_path, std::ifstream::binary); vertexFile.seekg(0, vertexFile.end); long size = static_cast<long>(vertexFile.tellg()); vertexFile.seekg(0); //Allocate space for file char* buffer = new char[size]; vertexFile.read(buffer, size); currentMesh.m_numberOfVertices = m_numberOfVertices= (reinterpret_cast<uint32_t*>(buffer))[0]; currentMesh.m_vertexDataStart = reinterpret_cast<size_t*>(buffer + sizeof(uint32_t)); if (m_numberOfVertices == 0) m_vertices = nullptr; else m_vertices = new Vector3[m_numberOfVertices]; //Save vertex and index count m_numberOfVertices = currentMesh.m_numberOfVertices; memcpy(m_vertices, currentMesh.m_vertexDataStart, sizeof(sVertex)*currentMesh.m_numberOfVertices); return true; }
void GLSLProgram::compileShader(const std::string& filePath, GLuint id) { std::ifstream vertexFile(filePath); if (vertexFile.fail()) { perror(filePath.c_str()); fatalError("Failed to open " + filePath); } std::string fileContents = ""; std::string line; while (std::getline(vertexFile, line)) { fileContents += line + "\n"; } vertexFile.close(); const char* contentsPtr = fileContents.c_str(); glShaderSource(id, 1, &contentsPtr, nullptr); glCompileShader(id); GLint isCompiled = 0; glGetShaderiv(id, GL_COMPILE_STATUS, &isCompiled); if (isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength); std::vector<GLchar> errorLog(maxLength); glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]); glDeleteShader(id); std::printf("%s\n", &errorLog[0]); fatalError("Shader" + filePath + " failed to compile."); } }
void TulipGraphSave::operator()(const Graph& graph, const std::string nodeFile ) const { std::map<int,int> idToParentId; edge_iterator ei, ei_end; for( boost::tie(ei, ei_end) = boost::edges(graph); ei != ei_end; ++ei ) { idToParentId[boost::target(*ei, graph)] = boost::source(*ei, graph); } std::ofstream vertexFile(nodeFile.c_str()); vertex_iterator vi, vi_end; vertexFile << ID << GRAPH_SEPARATOR << PARENT_ID << GRAPH_SEPARATOR << LABEL << GRAPH_SEPARATOR << LEVEL << GRAPH_SEPARATOR << CARDINALITY << GRAPH_SEPARATOR << POSITION << "\n"; // writes header for ( boost::tie(vi, vi_end) = boost::vertices(graph); vi != vi_end; ++vi ) { int vertex = *vi; vertexFile << graph[vertex].index << GRAPH_SEPARATOR //-1 means the vertex doesn't have any parent. << ((idToParentId.count(graph[vertex].index) > 0) ? idToParentId[graph[vertex].index] : -1) << GRAPH_SEPARATOR << graph[vertex].getLabel() << GRAPH_SEPARATOR << graph[vertex].level << GRAPH_SEPARATOR << graph[vertex].variable.cardinality() << GRAPH_SEPARATOR << graph[vertex].position << std::endl; } vertexFile.close(); }
/** * @brief Load shaders. * @param aVertexShaderFilename Name of vertex shader. * @param aFragmentShaderFilename Name of fragment shader. */ void PCShaderSurface::LoadShaders(HashString const &aVertexShaderFilename, HashString const &aFragmentShaderFilename) { mVertexShaderFileName = aVertexShaderFilename; mFragmentShaderFileName = aFragmentShaderFilename; HashString shaderKey = aVertexShaderFilename + aFragmentShaderFilename; if(GetManager()->ShaderDataExists(shaderKey)) { mProgramID = GetManager()->GetShaderData(shaderKey).mProgramID; return; } std::ifstream vertexFile(Common::RelativePath("Shaders", aVertexShaderFilename.ToCharArray()).c_str()); std::ifstream fragmentFile(Common::RelativePath("Shaders", aFragmentShaderFilename.ToCharArray()).c_str()); if(vertexFile.is_open() && fragmentFile.is_open()) { GLenum program = glCreateProgram(); GLenum vertexShader = glCreateShader(GL_VERTEX_SHADER); GLenum fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); GLint didCompile = 0; GLint isLinked = 0; HashString vertexFileContents = std::string((std::istreambuf_iterator<char>(vertexFile)), std::istreambuf_iterator<char>()); const char* vertexContents = vertexFileContents.ToCharArray(); // Compile glShaderSource(vertexShader, 1, &vertexContents, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &didCompile); if(didCompile == GL_FALSE) { DebugLogPrint("VERTEX SHADER %s READ:\n%s\n", aVertexShaderFilename.ToCharArray(), vertexContents); GLint maxLength = 0; glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<char> infoLog(maxLength); glGetShaderInfoLog(vertexShader, maxLength, &maxLength, &infoLog[0]); DebugLogPrint("GLERROR %s: %s\n", aVertexShaderFilename.ToCharArray(), &infoLog[0]); //We don't need the shader anymore. glDeleteShader(vertexShader); } HashString fragmentFileContents = std::string((std::istreambuf_iterator<char>(fragmentFile)), std::istreambuf_iterator<char>()); const char* fragmentContents = fragmentFileContents.ToCharArray(); glShaderSource(fragmentShader, 1, &fragmentContents, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &didCompile); if(didCompile == GL_FALSE) { DebugLogPrint("FRAGMENT SHADER %s READ:\n%s\n", aFragmentShaderFilename.ToCharArray(), fragmentContents); GLint maxLength = 0; glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<char> infoLog(maxLength); glGetShaderInfoLog(fragmentShader, maxLength, &maxLength, &infoLog[0]); DebugLogPrint("GLERROR %s: %s\n", aFragmentShaderFilename.ToCharArray(), &infoLog[0]); //We don't need the shader anymore. glDeleteShader(fragmentShader); } // Linking glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &isLinked); if(isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]); //We don't need the program anymore. glDeleteProgram(program); //Don't leak shaders either. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); DebugLogPrint("GL LINK ERROR: %s\n", &infoLog[0]); } GetManager()->AddShaderPairing(shaderKey, ShaderData(program, vertexShader, fragmentShader, vertexContents, fragmentContents)); mProgramID = program; } else { DebugLogPrint("No shader with name %s or %s found\n", aVertexShaderFilename.ToCharArray(), aFragmentShaderFilename.ToCharArray()); assert(!"Shader file not found."); } }
bool DXShader::Load(const String& vertexFileName, const String& pixelFileName) { HRESULT hr = S_OK; String vertexFile("data/shaders/dx/"); vertexFile.Append(vertexFileName); // create vertex shader void* vBuffer = nullptr; unsigned vSize = load_binary_file(&vBuffer, vertexFile.Data()); hr = _Device->CreateVertexShader(vBuffer, vSize, NULL, &vertexShader); if(FAILED(hr)) { delete[] vBuffer; LOG_ISSUE("DIRECTX ERROR: %s - failed to load vertex shader: %s", hresult_text(hr).Data(), vertexFileName.Data()); return false; } // create input layout const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC particleVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC* inputLayoutDesc = (layoutType == 0) ? basicVertexLayoutDesc : particleVertexLayoutDesc; unsigned inputDescSize = (layoutType == 0) ? ARRAYSIZE(basicVertexLayoutDesc) : ARRAYSIZE(particleVertexLayoutDesc); hr = _Device->CreateInputLayout(inputLayoutDesc, inputDescSize, vBuffer, vSize, &inputLayout); delete[] vBuffer; if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create input layout " "for vertex shader: %s", hresult_text(hr).Data(), vertexFileName.Data()); return false; } // create pixel shader String pixelFile("shaders/dx/"); pixelFile.Append(pixelFileName); void* psBuffer = nullptr; unsigned psSize = load_binary_file(&psBuffer, pixelFile.Data()); hr = _Device->CreatePixelShader(psBuffer, psSize, NULL, &pixelShader); delete[] psBuffer; if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to load pixel shader: %s", hresult_text(hr).Data(), pixelFileName.Data()); return false; } // initialize constants numVertexConstants = 3; vertexConstants[0].name = "model"; vertexConstants[0].type = ShaderConstant::MAT4X4; vertexConstants[1].name = "view"; vertexConstants[1].type = ShaderConstant::MAT4X4; vertexConstants[2].name = "projection"; vertexConstants[2].type = ShaderConstant::MAT4X4; numPixelConstants = 1; pixelConstants[0].name = "color"; pixelConstants[0].type = ShaderConstant::VEC4; int count = 0; for(int i = 0; i < numVertexConstants; i++) { vertexConstants[i].location = count; count += vertexConstants[i].GetSize(); } count = 0; for(int i = 0; i < numPixelConstants; i++) { pixelConstants[i].location = count; count += pixelConstants[i].GetSize(); } // create constant buffers int vertexConstantBufferSize = 0; for(int i = 0; i < numVertexConstants; i++) vertexConstantBufferSize += vertexConstants[i].GetSize(); D3D11_BUFFER_DESC constantBufferDesc = {0}; constantBufferDesc.ByteWidth = sizeof(float) * vertexConstantBufferSize; constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; _Device->CreateBuffer(&constantBufferDesc, nullptr, &vertCB); if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create constant buffer " "for shaders: %s and %s", hresult_text(hr).Data(), vertexFileName.Data(), pixelFileName.Data()); return false; } int pixelConstantBufferSize = 0; for(int i = 0; i < numPixelConstants; i++) pixelConstantBufferSize += pixelConstants[i].GetSize(); D3D11_BUFFER_DESC pixelCBDesc = {0}; pixelCBDesc.ByteWidth = sizeof(float) * pixelConstantBufferSize; pixelCBDesc.Usage = D3D11_USAGE_DYNAMIC; pixelCBDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pixelCBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; _Device->CreateBuffer(&pixelCBDesc, nullptr, &pixelCB); if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create pixel constant buffer " "for shaders: %s and %s", hresult_text(hr).Data(), vertexFileName.Data(), pixelFileName.Data()); return false; } return true; }
/** BN vertex file: see SINGLE format. * BN distribution file: see above. */ void BayesGraphLoad::operator()( std::shared_ptr<Graph> graph, const std::string labPosFileName, const std::string vertexFileName, const std::string distributionFileName, const std::string cndDataFileName, const std::string dataFileName ) const { BOOST_LOG_TRIVIAL(trace) << "begin loading label..." << std::endl; LabPosMap labPosMap = readLabPos(labPosFileName); BOOST_LOG_TRIVIAL(trace) << "end loading label..." << std::endl; std::ifstream vertexFile(vertexFileName.c_str()), distributionFile(distributionFileName.c_str()), dataFile(dataFileName.c_str()); CSVIterator<std::string> vertexLine(vertexFile); ++vertexLine; // skips header. BOOST_LOG_TRIVIAL(trace) << "begin loading vertices\n"; for( ; vertexLine != CSVIterator<std::string>(); ++vertexLine ) { size_t id = boost::lexical_cast<size_t>( (*vertexLine)[0] ); int level = boost::lexical_cast<int>( (*vertexLine)[2] ); int cardinality = boost::lexical_cast<int>( (*vertexLine)[3] ); // printf("id: %lu, level: %d, card: %d, label: %s, pos: %d", id, level, cardinality, label.c_str(), position); std::string label = labPosMap[id].first; int position = labPosMap[id].second; create_graph_node( graph, cardinality, label, position, level ); } Graph& graphRef = *graph; BOOST_LOG_TRIVIAL(trace) << "end loading vertices: " << boost::num_vertices(graphRef) << "\n\n"; BOOST_LOG_TRIVIAL(trace) << "begin loading dist\n"; CSVIterator<std::string> distributionLine(distributionFile); while ( distributionLine != CSVIterator<std::string>() ) { plVariablesConjunction variables; // holds child variables plComputableObjectList jointDistri; size_t latentId = boost::lexical_cast<size_t>( (*distributionLine)[BN_LATENT_ID] ); size_t nbrChildren = boost::lexical_cast<size_t>( (*distributionLine)[NBR_CHILDREN] ); Node& latentNode = graphRef[ latentId ]; ++distributionLine; // reads next line. std::vector< plProbValue > probValuesZ; for ( size_t latentVal = 0; latentVal < latentNode.variable.cardinality(); ++latentVal) { // loads probability table for the latent var probValuesZ.push_back( boost::lexical_cast<plProbValue>( (*distributionLine)[latentVal] ) ); } const plProbTable probTabZ(latentNode.variable, probValuesZ); ++distributionLine; for ( size_t child = 0; child < nbrChildren; ++child ) { size_t childId = boost::lexical_cast<size_t>( (*distributionLine)[BN_LATENT_ID] ); ++distributionLine; Node& childNode = graphRef[ childId ]; variables ^= childNode.variable; plDistributionTable distTab_Xi_Z ( childNode.variable, latentNode.variable ); for ( size_t latentVal = 0; latentVal < latentNode.variable.cardinality(); ++latentVal ) { std::vector< plProbValue > probValuesXiZ_vals; for ( size_t childVal = 0; childVal < childNode.variable.cardinality(); ++childVal ) { probValuesXiZ_vals.push_back( boost::lexical_cast<plProbValue>( (*distributionLine)[childVal] ) ); } distTab_Xi_Z.push( plProbTable( childNode.variable, probValuesXiZ_vals), (int)latentVal ); ++distributionLine; } jointDistri *= distTab_Xi_Z; // adds the conditional table to result boost::add_edge( latentId, childId, graphRef ); } auto jd = ( probTabZ * jointDistri ); ++distributionLine; latentNode.set_joint_distribution( plJointDistribution(latentNode.variable ^ variables, probTabZ * jointDistri) ); } distributionFile.close(); vertexFile.close(); set_data(*graph, cndDataFileName, dataFileName); }
/** vertex file: see SINGLE format. * distribution file: see above. */ void BayesGraphSave::operator()( const Graph& graph, const std::string vertexFileName, const std::string distFileName ) const { std::ofstream distFile(distFileName.c_str()), vertexFile(vertexFileName.c_str()); vertex_iterator vi, vi_end; Label2Index label2Index; vertexFile << ID << GRAPH_SEPARATOR << LATENT << GRAPH_SEPARATOR << LEVEL << GRAPH_SEPARATOR << CARDINALITY << GRAPH_SEPARATOR << "label" << "\n"; // writes header BOOST_LOG_TRIVIAL(trace) << "saving vertices...\n"; for ( boost::tie(vi, vi_end) = boost::vertices(graph); vi != vi_end; ++vi ) { int vertex = *vi; vertexFile << graph[vertex].index << GRAPH_SEPARATOR << !(graph[vertex].is_leaf()) << GRAPH_SEPARATOR << graph[vertex].level << GRAPH_SEPARATOR << graph[vertex].variable.cardinality() << GRAPH_SEPARATOR << graph[vertex].getLabel() << std::endl; label2Index[graph[vertex].getLabel()] = graph[vertex].index; } vertexFile.close(); BOOST_LOG_TRIVIAL(trace) << "saving joint distribution...\n"; for ( boost::tie(vi, vi_end) = boost::vertices(graph); vi != vi_end; ++vi ) { const Node& node = graph[*vi]; if ( !node.is_leaf() ) { auto latentVar = node.variable; // plJointDistribution distribution = node.jointDistribution; // plVariablesConjunction all_variables = distribution.get_variables(); // all variables (latent variable and its children) plVariablesConjunction childVars = node.get_children_variables(); // child childVars // for (size_t i = 1; i < all_variables.size(); ++i) // childVars ^= all_variables[i]; // initializes child conjunction. // plSymbol latentVar = all_variables[0]; // latent variable distFile << node.index << GRAPH_SEPARATOR << childVars.size() << std::endl; // plComputableObjectList objLists = distribution.get_computable_object_list(); // plComputableObject probTableZ = objLists.get_distribution_over(latentVar); // distribution table for the latent variable auto probTableZ = node.marginalDist; int val; for ( val = 0; val < latentVar.cardinality() - 1 ; ++val ) { distFile << std::fixed << std::setprecision(30) << probTableZ->compute( plValues().add(latentVar, val) ) << GRAPH_SEPARATOR; // P(latentVar = val) } distFile << std::fixed << std::setprecision(15) << probTableZ->compute( plValues().add(latentVar, val) ) << std::endl; // writes last probability value for ( size_t i = 0; i < childVars.size(); ++i ) { plSymbol varX = childVars[ i ]; // retrieves the child variable distFile << label2Index[varX.name()] << std::endl; // writes child variable's id. auto distTableXZ = node.cndChildrenDists.at(i); //objLists.get_distribution_over(varX); // conditional distribution P(X_i | Z) // plDistributionTable& distTableXZ = // static_cast<plDistributionTable&>( compTableXZ ); // casting P(X_i | Z) to derived class for ( val = 0; val < latentVar.cardinality(); ++val ) { int childVal; for ( childVal = 0; childVal < varX.cardinality() - 1; ++childVal ) { // for each value x of the child variable distFile << std::fixed << std::setprecision(15) << distTableXZ->compute( plValues().add(latentVar, val).add(varX, childVal) ) << GRAPH_SEPARATOR; // p(X_i = childVal | Z = val) } distFile << std::fixed << std::setprecision(15) << distTableXZ->compute( plValues().add(latentVar, val).add(varX, childVal) ) << std::endl; } } distFile << std::endl; // breaks the line, moves to the next latent variable. } } distFile.close(); }
bool Engine::Mesh::LoadMeshDataFromFile(const char* i_path, HWND i_WindowHandle, IDirect3DDevice9* i_D3DDevice, IDirect3DVertexDeclaration9* i_VertexDeclaration, D3DVERTEXELEMENT9* i_vertexElements) { bool wereThereErrors = false; DWORD usage = 0; // Our code will only ever write to the buffer usage |= D3DUSAGE_WRITEONLY; MeshData currentMesh; if (!fileExists(i_path)) { MessageBox(i_WindowHandle, "Failed to Load Mesh File", "File not found", MB_OK | MB_ICONERROR); return false; } std::ifstream vertexFile(i_path, std::ifstream::binary); vertexFile.seekg(0, vertexFile.end); long size = static_cast<long>(vertexFile.tellg()); vertexFile.seekg(0); //Allocate space for file char* buffer = new char[size]; vertexFile.read(buffer, size); currentMesh.m_numberOfVertices = reinterpret_cast<uint32_t*>(buffer)[0]; currentMesh.m_numberOfIndices = reinterpret_cast<uint32_t*>(buffer)[1]; currentMesh.m_vertexDataStart = reinterpret_cast<size_t*>(buffer + 2 * sizeof(uint32_t)); currentMesh.m_indexDataStart = reinterpret_cast<size_t*>(buffer + 2 * sizeof(uint32_t)+currentMesh.m_numberOfVertices*sizeof(sVertex)); //Save vertex and index count m_VertexCount = currentMesh.m_numberOfVertices; m_IndexCount = currentMesh.m_numberOfIndices; // Initialize the vertex format HRESULT result = i_D3DDevice->CreateVertexDeclaration(i_vertexElements, &i_VertexDeclaration); if (SUCCEEDED(result)) { result = i_D3DDevice->SetVertexDeclaration(i_VertexDeclaration); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to set the vertex declaration", "No Vertex Declaration", MB_OK | MB_ICONERROR); return false; } } else { MessageBox(i_WindowHandle, "DirectX failed to create a Direct3D9 vertex declaration", "No Vertex Declaration", MB_OK | MB_ICONERROR); return false; } // Create a vertex buffer for the cube { const unsigned int bufferSize = currentMesh.m_numberOfVertices * sizeof(sVertex); // We will define our own vertex format const DWORD useSeparateVertexDeclaration = 0; // Place the vertex buffer into memory that Direct3D thinks is the most appropriate const D3DPOOL useDefaultPool = D3DPOOL_DEFAULT; HANDLE* const notUsed = NULL; result = i_D3DDevice->CreateVertexBuffer(bufferSize, usage, useSeparateVertexDeclaration, useDefaultPool, &m_BufferData.m_VertexBuffer, notUsed); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to create a vertex buffer", "No Vertex Buffer", MB_OK | MB_ICONERROR); return false; } } // Fill the vertex buffer with the rectangle's vertices { // Before the vertex buffer can be changed it must be "locked" sVertex* vertexData; { const unsigned int lockEntireBuffer = 0; const DWORD useDefaultLockingBehavior = 0; result = m_BufferData.m_VertexBuffer->Lock(lockEntireBuffer, lockEntireBuffer, reinterpret_cast<void**>(&vertexData), useDefaultLockingBehavior); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to lock the vertex buffer", "No Vertex Buffer", MB_OK | MB_ICONERROR); return false; } } // Fill the buffer { memcpy(vertexData, currentMesh.m_vertexDataStart, sizeof(sVertex)*currentMesh.m_numberOfVertices); // The buffer must be "unlocked" before it can be used { result = m_BufferData.m_VertexBuffer->Unlock(); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to unlock the vertex buffer", "No Vertex Buffer", MB_OK | MB_ICONERROR); return false; } } } } // Create an index buffer { // We'll use 32-bit indices in this class to keep things simple D3DFORMAT format = D3DFMT_INDEX32; unsigned int bufferLength; { bufferLength = currentMesh.m_numberOfIndices * sizeof(uint32_t); } D3DPOOL useDefaultPool = D3DPOOL_DEFAULT; HANDLE* notUsed = NULL; HRESULT result = i_D3DDevice->CreateIndexBuffer(bufferLength, usage, format, useDefaultPool, &m_BufferData.m_IndexBuffer, notUsed); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to create an index buffer", "No Index Buffer", MB_OK | MB_ICONERROR); return false; } } // Fill the index buffer with the rectangle's triangles' indices { // Before the index buffer can be changed it must be "locked" uint32_t* indices; { const unsigned int lockEntireBuffer = 0; const DWORD useDefaultLockingBehavior = 0; const HRESULT result = m_BufferData.m_IndexBuffer->Lock(lockEntireBuffer, lockEntireBuffer, reinterpret_cast<void**>(&indices), useDefaultLockingBehavior); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to lock the index buffer", "No Index Buffer", MB_OK | MB_ICONERROR); return false; } } // Fill the buffer { memcpy(indices, currentMesh.m_indexDataStart, sizeof(uint32_t)*currentMesh.m_numberOfIndices); } // The buffer must be "unlocked" before it can be used { const HRESULT result = m_BufferData.m_IndexBuffer->Unlock(); if (FAILED(result)) { MessageBox(i_WindowHandle, "DirectX failed to unlock the index buffer", "No Index Buffer", MB_OK | MB_ICONERROR); return false; } } } return true; }