//==================================================================================== bool IniFile::writeValue(const AnsiStr& section, const AnsiStr& variable, const AnsiStr& strValue) { AnsiStr strLine, strToAdd; strToAdd = variable; strToAdd += "="; strToAdd += strValue; int startPos = hasSection(section); if(startPos >= 0) { //Record file pos for(int i=startPos+1; i < (int)m_content.size(); i++) { strLine = m_content[i]; //If it is a comment then ignore if(strLine.firstChar() == '#') continue; //Is it another section? if((strLine.firstChar() == L'[')&&(strLine.lastChar() == L']')) { m_content.insert(m_content.begin() + i, strToAdd); return true; } else { //Check Variable for(int iChar=0; iChar < strLine.length(); iChar++) { if(strLine[iChar] == L'=') { strLine = strLine.substr(0, iChar); AnsiStr varUpperCased = variable; varUpperCased.toUpper(); if( strLine.toUpper() == varUpperCased ) { //Write it here m_content[i] = strToAdd; return true; } else break; } } } } //Not Written m_content.push_back(strToAdd); } else { //Add it if not found anywhere strLine = AnsiStr("[") + section + AnsiStr("]"); m_content.push_back(strLine); m_content.push_back(strToAdd); } return true; }
bool IniFile::readIntArrayU32(const AnsiStr& section, const AnsiStr& variable, int ctExpected, std::vector<U32>& arrayInt) { AnsiStr strVal; if(readValue(section, variable, strVal)) { int pos; int iComp = 0; AnsiStr strTemp; if(strVal.firstChar() == '(') strVal = strVal.substr(1); else return false; while(strVal.lfind(',', pos)) { strTemp = strVal.substr(0, pos); strVal = strVal.substr(pos + 1); strVal.removeStartEndSpaces(); arrayInt.push_back(atoi(strTemp.ptr())); iComp++; } if(strVal.length() >= 1) { if(strVal.lastChar() == ')') { strTemp = strVal.substr(0, strVal.length() - 1); strTemp.removeStartEndSpaces(); if(strTemp.length() > 0) arrayInt.push_back(atoi(strTemp.ptr())); } } } return ((int)arrayInt.size() == ctExpected); }
VolMesh* VolMeshSamples::CreateTruthCube(int nx, int ny, int nz, double cellsize) { if(nx < 2 || ny < 2 || nz < 2) { LogError("Invalid input param to create a truth cube"); return NULL; } vector< vec3d > vertices; vector< vec4u32 > elements; vec3d start = vec3d(- (double)(nx)/2.0, 0, - (double)(nz)/2.0) * (cellsize); //add all nodes for(int i=0; i < nx; i++) { for(int j=0; j < ny; j++) { for(int k=0; k < nz; k++) { vec3d v = start + vec3d(i, j, k) * cellsize; vertices.push_back(v); } } } //corner defs enum CellCorners {LBN = 0, LBF = 1, LTN = 2, LTF = 3, RBN = 4, RBF = 5, RTN = 6, RTF = 7}; U32 cn[8]; //add all elements for(int i=0; i < nx-1; i++) { for(int j=0; j < ny-1; j++) { for(int k=0; k < nz-1; k++) { //collect cell nodes cn[LBN] = i * ny * nz + j * nz + k; cn[LBF] = i * ny * nz + j * nz + k + 1; cn[LTN] = i * ny * nz + (j+1) * nz + k; cn[LTF] = i * ny * nz + (j+1) * nz + k + 1; cn[RBN] = (i+1) * ny * nz + j * nz + k; cn[RBF] = (i+1) * ny * nz + j * nz + k + 1; cn[RTN] = (i+1) * ny * nz + (j+1) * nz + k; cn[RTF] = (i+1) * ny * nz + (j+1) * nz + k + 1; //add elements elements.push_back(vec4u32(cn[LBN], cn[LTN], cn[RBN], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LBF], cn[RBN])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LTF], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[RBN], cn[LBF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LBF], cn[LTF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LTF], cn[RTF], cn[RBF])); } } } //build the final mesh vector<double> vFlatVertices; vector<U32> vFlatElements; FlattenVec3<double>(vertices, vFlatVertices); FlattenVec4<U32>(elements, vFlatElements); AnsiStr strName = printToAStr("truthcube_%dx%dx%d", nx, ny, nz); VolMesh* cube = new VolMesh(vFlatVertices, vFlatElements); cube->setName(strName.cptr()); return cube; }
bool SGHeaders::updateHeaderLine(const AnsiStr& title, const AnsiStr& strInfo) { return updateHeaderLine(getHeaderId(title.cptr()), strInfo); }
int main(int argc, char* argv[]) { cout << "Cutting tets" << endl; // prints !!!Hello World!!! //Initialize app glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); glutCreateWindow("OpenGL Framework"); glutDisplayFunc(draw); glutReshapeFunc(def_resize); glutMouseFunc(MousePress); glutPassiveMotionFunc(MousePassiveMove); glutMotionFunc(MouseMove); glutMouseWheelFunc(MouseWheel); glutKeyboardFunc(NormalKey); glutSpecialFunc(SpecialKey); glutCloseFunc(closeApp); glutIdleFunc(timestep); //Setup Shading Environment static const GLfloat lightColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; static const GLfloat lightPos[4] = { 0.0f, 9.0f, 0.0f, 1.0f }; //Setup Light0 Position and Color glLightfv(GL_LIGHT0, GL_AMBIENT, lightColor); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor); glLightfv(GL_LIGHT0, GL_SPECULAR, lightColor); glLightfv(GL_LIGHT0, GL_POSITION, lightPos); //Turn on Light 0 glEnable(GL_LIGHT0); //Enable Lighting glEnable(GL_LIGHTING); //Enable features we want to use from OpenGL glShadeModel(GL_SMOOTH); glEnable(GL_POLYGON_SMOOTH); glEnable(GL_LINE_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_STENCIL_TEST); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); //glClearColor(0.45f, 0.45f, 0.45f, 1.0f); glClearColor(1.0, 1.0, 1.0, 1.0); //Compiling shaders GLenum err = glewInit(); if (err != GLEW_OK) { //Problem: glewInit failed, something is seriously wrong. fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(1); } //Build Shaders for drawing the mesh AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strShaderRoot = strRoot + "data/shaders/"; //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Ground and Room TheSceneGraph::Instance().addFloor(32, 32, 0.5f); TheSceneGraph::Instance().addSceneBox(AABB(vec3f(-10, -10, -16), vec3f(10, 10, 16))); glutMainLoop(); return 0; }
VolMesh* VolMeshSamples::CreateEggShell(int hseg, int vseg, double radius, double shelltickness) { if(hseg <= 0 || vseg <= 0) { LogErrorArg2("Invalid eggshell segments param: %u, %u", hseg, vseg); return NULL; } if(shelltickness >= radius) { LogErrorArg2("Invalid eggshell radius and thickness params: %.3f, %.3f", radius, shelltickness); return NULL; } vector< vec3d > vertices; vector< vec4u32 > elements; float vSegInv = 1.0f / (float)vseg; float hSegInv = 1.0f / (float)hseg; //Loop Over for(int v=0; v<vseg+1; v++) { double p = DEGTORAD(v * vSegInv * 180.0); for(int h=0; h<hseg; h++) { double o = DEGTORAD(h * hSegInv * 360.0); //vertex vec3d v1; v1.x = radius * sin(p) * sin(o); v1.z = radius * sin(p) * cos(o); v1.y = radius * cos(p); //Add Vertex vertices.push_back(v1); } } //layer 2 U32 layeroffset = vertices.size(); radius -= shelltickness; for(int v=0; v<vseg+1; v++) { double p = DEGTORAD(v * vSegInv * 180.0); for(int h=0; h<hseg; h++) { double o = DEGTORAD(h * hSegInv * 360.0); //vertex vec3d v1; v1.x = radius * sin(p) * sin(o); v1.z = radius * sin(p) * cos(o); v1.y = radius * cos(p); //Add Vertex vertices.push_back(v1); } } //Indices enum CellCorners {LBN = 0, LBF = 1, LTN = 2, LTF = 3, RBN = 4, RBF = 5, RTN = 6, RTF = 7}; U32 cn[8]; //Add all elements for(int v=0; v<vseg; v++) { for(int h=0; h<hseg; h++) { //top cn[LTN] = h + v*hseg; cn[LTF] = cn[LTN] + 1; cn[RTN] = h + (v+1)*hseg; cn[RTF] = cn[RTN] + 1; if(h == hseg-1) { cn[LTF] = v*hseg; cn[RTF] = (v+1)*hseg; } //bottom cn[LBN] = layeroffset + h + v*hseg; cn[LBF] = layeroffset + cn[LTN] + 1; cn[RBN] = layeroffset + h + (v+1)*hseg; cn[RBF] = layeroffset + cn[RTN] + 1; if(h == hseg-1) { cn[LBF] = layeroffset + v*hseg; cn[RBF] = layeroffset + (v+1)*hseg; } //add elements elements.push_back(vec4u32(cn[LBN], cn[LTN], cn[RBN], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LBF], cn[RBN])); elements.push_back(vec4u32(cn[RTN], cn[LTN], cn[LTF], cn[LBF])); elements.push_back(vec4u32(cn[RTN], cn[RBN], cn[LBF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LBF], cn[LTF], cn[RBF])); elements.push_back(vec4u32(cn[RTN], cn[LTF], cn[RTF], cn[RBF])); } } //remove slivers U32 i = 0; while(i < elements.size()) { //fetch vertices vec4u32 e = elements[i]; vec3d v[4]; for(U32 j=0; j < COUNT_CELL_NODES; j++) v[j] = vertices[e[j]]; if(VolMesh::ComputeCellVolume(v) < 0.0001) elements.erase(elements.begin() + i); else i++; } //build the final mesh vector<double> vFlatVertices; vector<U32> vFlatElements; FlattenVec3<double>(vertices, vFlatVertices); FlattenVec4<U32>(elements, vFlatElements); AnsiStr strName = printToAStr("eggshell_h%d_v%d", hseg, vseg); VolMesh* eggshell = new VolMesh(vFlatVertices, vFlatElements); eggshell->setName(strName.cptr()); return eggshell; }
bool VolMeshIO::convertMatlabTextToVega(const AnsiStr& strNodesFP, const AnsiStr& strFacesFP, const AnsiStr& strCellsFP) { // node: node coordinates (in mm) // face: surface triangles; the last column is the surface ID, // 1-scalp, 2-CSF, 3-gray matter, 4-white matter // elem: tetrahedral elements; the last column is the region ID, // 1-scalp and skull layer, 2-CSF, 3-gray matter, 4-white matter if(!FileExists(strNodesFP) || !FileExists(strCellsFP)) { LogError("Invalid input file!"); return false; } vector<vec3d> nodes; ifstream fpNodes(strNodesFP.cptr()); if (!fpNodes.is_open()) return false; //read nodes U32 ctLine = 0; char chrLine[1024]; while (!fpNodes.eof()) { fpNodes.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(',', tokens); if(ctTokens < 2) continue; vec3d v; v.x = atof(tokens[0].cptr()); v.y = atof(tokens[1].cptr()); v.z = atof(tokens[2].cptr()); nodes.push_back(v); } ctLine++; } fpNodes.close(); vector< vector<U32> > vBrainSegmentCells; vBrainSegmentCells.resize(4); //read cells ifstream fpCells(strCellsFP.cptr()); if (!fpCells.is_open()) return false; U32 ctExpectedTokens = 5; vector<U32> vConvTokens; vConvTokens.resize(ctExpectedTokens); while (!fpCells.eof()) { fpCells.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(',', tokens); if(ctTokens < 2) continue; for(U32 i=0; i < ctExpectedTokens; i++) vConvTokens[i] = atoi(tokens[i].cptr()); U32 idxSegment = vConvTokens.back() - 1; for(U32 i=0; i < ctExpectedTokens - 1; i++) vBrainSegmentCells[idxSegment].push_back(vConvTokens[i] - 1); } } fpCells.close(); //export brain segments enum BrainSegment {bsSkull = 1, bsCSF = 2, bsGrayMatter = 3, bsWhiteMatter = 4}; string arrSegmentTitles[4] = {"skull", "csf", "graymatter", "whitematter"}; AnsiStr strRoot = ExtractFilePath(strNodesFP); //export segments for(U32 i=0; i < 4; i++) { vector<U32> vFlatCells(vBrainSegmentCells[i].begin(), vBrainSegmentCells[i].end()); vector<vec3d> vFinalNodes; vFinalNodes.reserve(nodes.size()); map<U32, U32> mapSegmentNodes; //Make a unique set of nodes for(U32 j=0; j < vFlatCells.size(); j++) { //if not found in cache the add it if(mapSegmentNodes.find(vFlatCells[j]) == mapSegmentNodes.end()) { vFinalNodes.push_back(nodes[vFlatCells[j] ]); U32 idxNewNode = vFinalNodes.size() - 1; mapSegmentNodes[ vFlatCells[j] ] = idxNewNode; } //convert to the new node index vFlatCells[j] = mapSegmentNodes[ vFlatCells[j] ]; } //clear the map mapSegmentNodes.clear(); vector<double> vFlatNodes; FlattenVec3<double>(vFinalNodes, vFlatNodes); VolMesh* pvm = new VolMesh(vFlatNodes, vFlatCells); pvm->setVerbose(true); // quatd q; // q.fromAxisAngle(vec3d(0, 0, 1), 90.0); // rotatemesh(pvm, q); //aabb // AABB box1(vec3f(0.0f, 0.0f, 0.0f), vec3f(4.0f, 4.0f, 4.0f)); // fitmesh(pvm, box1); //aabb AABB box2(vec3f(-2.0f, 0.0f, -2.0f), vec3f(2.0f, 4.0f, 2.0f)); fitmesh(pvm, box2); AnsiStr strFP = strRoot + AnsiStr(arrSegmentTitles[i].c_str()) + AnsiStr(".veg"); if(writeVega(pvm, strFP)) { LogInfoArg2("Saved segment %s to %s", arrSegmentTitles[i].c_str(), strFP.cptr()); } SAFE_DELETE(pvm); } return true; }
//Read Program from file and then compile it int ComputeDevice::addProgramFromFile(const AnsiStr& strFP, bool tryLoadBinary) { if(!m_bReady) return -1; if(!PS::FILESTRINGUTILS::FileExists(strFP)) { LogErrorArg1("File does not exist! Path: %s", strFP.cptr()); return -1; } std::ifstream fp; fp.open(strFP.cptr(), std::ios::binary); if(!fp.is_open()) return -1; //Compute Source File Checksum for bin compatibility and future storage LogInfoArg1("Computing source file MD5 checksum for %s", strFP.cptr()); string checkSumOrg = ComputeCheckSum(strFP.cptr()); LogInfoArg1("Computed checksum is %s", checkSumOrg.c_str()); if(tryLoadBinary) { string checkSumLoaded; ComputeProgram* lpProgram = NULL; if(LoadSourceCheckSum(strFP.cptr(), checkSumLoaded)) { if(checkSumOrg == checkSumLoaded) { LogInfo("Checksums matched. Attempting to load ptx binfile."); string strBinFile = string(strFP.cptr()) + ".ptx"; std::ifstream binFile; binFile.open(strBinFile.c_str(), std::ios::binary); if(binFile.is_open()) { size_t size; binFile.seekg(0, std::ios::end); size = binFile.tellg(); binFile.seekg(0, std::ios::beg); U8* buf = new U8[size]; binFile.read((char*)buf, size); binFile.close(); lpProgram = loadPtxBinary(buf, size); if(lpProgram) LogInfoArg1("Kernels loaded from binfile at: %s", strBinFile.c_str()); else LogErrorArg1("An error occured while trying to load ptx binfile from: %s", strBinFile.c_str()); SAFE_DELETE(buf); } } } if(lpProgram) { //Add loaded to list m_lstPrograms.push_back(lpProgram); return ((int)m_lstPrograms.size() - 1); } } //From Source Code LogInfo("Compiling and storing bin file along with the computed md5 checksum for future loads."); size_t size; fp.seekg(0, std::ios::end); size = fp.tellg(); fp.seekg(0, std::ios::beg); char * buf = new char[size+1]; //Read file content fp.read(buf, size); buf[size] = '\0'; string strCode = string(buf); SAFE_DELETE(buf); fp.close(); //Save Binary int id = addProgram(strCode.c_str()); if(isProgramIndex(id)) { string strBinFile = string(strFP.cptr()) + ".ptx"; storePtxBinary(m_lstPrograms[id], strBinFile.c_str()); SaveSourceCheckSum(strFP.cptr(), checkSumOrg); } return id; }
//================================================================== int ListFilesInDir(std::vector<AnsiStr>& lstFiles, const char* pDir, const char* pExtensions, bool storeWithPath) { AnsiStr strDir; AnsiStr strResolvedDir; lstFiles.resize(0); if(pDir == NULL) strResolvedDir = ps::dir::ExtractFilePath(ps::dir::GetExePath()); else strResolvedDir = AnsiStr(pDir); if(pExtensions != NULL) strDir = printToAStr("%s/*.%s", strResolvedDir.ptr(), pExtensions); else strDir = printToAStr("%s/*.*", strResolvedDir.ptr()); #ifdef PS_OS_WINDOWS WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; DWideStr wstrDir = toWideString(strDir); hFind = FindFirstFile(wstrDir.ptr(), &ffd); if(hFind == INVALID_HANDLE_VALUE) return 0; AnsiStr temp; do { if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { if (storeWithPath) { temp = strResolvedDir + "\\"; temp += AnsiStr(ffd.cFileName); lstFiles.push_back(temp); } else { temp = AnsiStr(ffd.cFileName); lstFiles.push_back(temp); } } }while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else DIR* dirFile = opendir( strResolvedDir.cptr() ); if ( dirFile ) { struct dirent* hFile; string strExt = "." + string(pExtensions); while (( hFile = readdir( dirFile )) != NULL ) { if ( !strcmp( hFile->d_name, "." )) continue; if ( !strcmp( hFile->d_name, ".." )) continue; // in linux hidden files all start with '.' if (hFile->d_name[0] == '.' ) continue; // dirFile.name is the name of the file. Do whatever string comparison // you want here. Something like: if ( strstr( hFile->d_name, strExt.c_str())) { if(storeWithPath) lstFiles.push_back(strResolvedDir + "//" + AnsiStr(hFile->d_name)); else lstFiles.push_back(AnsiStr(hFile->d_name)); printf("Found file %s", hFile->d_name); } } closedir( dirFile ); } #endif return (int)lstFiles.size(); }
bool VolMeshIO::readVega(VolMesh* vm, const AnsiStr& strPath) { if ((vm == NULL) || !FileExists(strPath)) return false; char chrLine[1024]; ifstream fpIn(strPath.cptr()); if (!fpIn.is_open()) return false; vector<double> vertices; vector<U32> elements; U32 ctLine = 0; U32 idxVertex = 0; U32 ctVertices = 0; U32 ctVertexStep = 0; U32 idxElement = 0; U32 ctElements = 0; U32 ctElementStep = 0; enum READMODE { modeReadHeader, modeReadVertex, modeReadElements, modeReadMaterial, modeReadRegion }; READMODE mode = modeReadHeader; READMODE prevMode = mode; while (!fpIn.eof()) { fpIn.getline(chrLine, 1024); AnsiStr strLine(chrLine); strLine.trim(); strLine.removeStartEndSpaces(); if (strLine.length() == 0) continue; if (strLine.firstChar() == '#') continue; if (strLine.firstChar() == '*') { vector<AnsiStr> tokens; strLine.decompose(' ', tokens); if (tokens[0] == "*VERTICES") mode = modeReadVertex; else if (tokens[0] == "*ELEMENTS") mode = modeReadElements; else if (tokens[0] == "*MATERIAL") mode = modeReadMaterial; else if (tokens[0] == "*REGION") mode = modeReadRegion; continue; } else if(strLine == "TETS") continue; //count tokens { vector<AnsiStr> tokens; int ctTokens = strLine.decompose(' ', tokens); if(ctTokens < 2) continue; } if (prevMode != mode) { if (mode == modeReadVertex && idxVertex == 0) { sscanf(strLine.cptr(), "%u %u", &ctVertices, &ctVertexStep); if (ctVertices <= 0 || ctVertexStep != 3) { fpIn.close(); return false; } vertices.reserve(ctVertices * ctVertexStep); prevMode = mode; continue; } else if (mode == modeReadElements && idxElement == 0) { sscanf(strLine.cptr(), "%u %u", &ctElements, &ctElementStep); if (ctElements <= 0 || ctElementStep != 4) { fpIn.close(); return false; } elements.reserve(ctElements * ctElementStep); prevMode = mode; continue; } } if (mode == modeReadVertex) { vec3d v; vector<AnsiStr> arrWords; int ctWords = strLine.decompose(' ', arrWords); if (ctWords >= 4) { U32 row = atoi(arrWords[0].cptr()) - 1; assert(row == idxVertex); v.x = atof(arrWords[1].cptr()); v.y = atof(arrWords[2].cptr()); v.z = atof(arrWords[3].cptr()); } //add vertex to the array vertices.push_back(v.x); vertices.push_back(v.y); vertices.push_back(v.z); idxVertex++; } else if (mode == modeReadElements) { vec4u32 e; vector<AnsiStr> arrWords; int ctWords = strLine.decompose(' ', arrWords); if (ctWords >= 5) { U32 row = atoi(arrWords[0].cptr()) - 1; assert(row == idxElement); e.x = atoi(arrWords[1].cptr()) - 1; e.y = atoi(arrWords[2].cptr()) - 1; e.z = atoi(arrWords[3].cptr()) - 1; e.w = atoi(arrWords[4].cptr()) - 1; } //add element to the array elements.push_back(e.x); elements.push_back(e.y); elements.push_back(e.z); elements.push_back(e.w); idxElement++; } prevMode = mode; ctLine++; } fpIn.close(); //check read amount if((vertices.size() / ctVertexStep) != ctVertices) return false; if((elements.size() / ctElementStep) != ctElements) return false; //setup mesh vm->cleanup(); vm->setName(ExtractFileTitleOnly(strPath).cptr()); return vm->setup(vertices, elements); }
int main(int argc, char* argv[]) { int ctThreads = tbb::task_scheduler_init::default_num_threads(); tbb::task_scheduler_init init(ctThreads); cout << "started tbb with " << ctThreads << " threads." << endl; //parser g_parser.addSwitch("--disjoint", "-d", "converts splitted part to disjoint meshes", "0"); g_parser.addSwitch("--ringscalpel", "-r", "If the switch presents then the ring scalpel will be used"); g_parser.addSwitch("--verbose", "-v", "prints detailed description."); g_parser.addSwitch("--input", "-i", "[filepath] set input file in vega format", "internal"); //g_parser.addSwitch("--example", "-e", "[one, two, cube, eggshell] set an internal example", "two"); //g_parser.addSwitch("--gizmo", "-g", "loads a file to set gizmo location and orientation", "gizmo.ini"); if(g_parser.parse(argc, argv) < 0) exit(0); //file path g_strIniFilePath = AnsiStr(g_parser.value("input").c_str()); if(FileExists(g_strIniFilePath)) vloginfo("input file: %s.", g_strIniFilePath.cptr()); else { vlogerror("Unable to find input filepath: [%s]", g_strIniFilePath.cptr()); exit(1); } //GLFW LIB g_lpWindow = NULL; glfwSetErrorCallback(error_callback); if (!glfwInit()) { vlogerror("Failed to init glfw"); exit(EXIT_FAILURE); } /* glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); */ g_lpWindow = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "tetcutter - Pourya Shirazian", NULL, NULL); if (!g_lpWindow) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_lpWindow); glfwSwapInterval(1); glfwSetKeyCallback(g_lpWindow, key_callback); glfwSetCursorPosCallback(g_lpWindow, mouse_motion_callback); glfwSetMouseButtonCallback(g_lpWindow, mouse_button_callback); glfwSetScrollCallback(g_lpWindow, scroll_callback); //init gl def_initgl(); //Build Shaders for drawing the mesh IniFile ini(g_strIniFilePath, IniFile::fmRead); AnsiStr strRoot = ini.readString("system", "data"); AnsiStr strShaderRoot = strRoot + "shaders/"; AnsiStr strTextureRoot = strRoot + "textures/"; AnsiStr strFontsRoot = strRoot + "fonts/"; //convert mesh // AnsiStr strNodesFP = strRoot + AnsiStr("data/meshes/matlab/nodes.txt"); // AnsiStr strFacesFP = strRoot + AnsiStr("data/meshes/matlab/faces.txt"); // AnsiStr strCellsFP = strRoot + AnsiStr("data/meshes/matlab/cells.txt"); // VolMeshIO::convertMatlabTextToVega(strNodesFP, strFacesFP, strCellsFP); //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Load Textures TheTexManager::Instance().add(strTextureRoot + "wood.png"); TheTexManager::Instance().add(strTextureRoot + "spin.png"); TheTexManager::Instance().add(strTextureRoot + "icefloor.png"); // TheTexManager::Instance().add(strTextureRoot + "rendermask.png"); // TheTexManager::Instance().add(strTextureRoot + "maskalpha.png"); // TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png"); vloginfo("Floor show is set to: [%d]", ini.readBool("visible", "floor")); //Ground and Room SGQuad* floor = new SGQuad(16.0f, 16.0f, TheTexManager::Instance().get("icefloor")); floor->setName("floor"); floor->transform()->translate(vec3f(0, -0.1f, 0)); floor->transform()->rotate(vec3f(1.0f, 0.0f, 0.0f), 90.0f); floor->setVisible(ini.readBool("visible", "floor")); TheEngine::Instance().add(floor); //Create Scalpel g_lpScalpel = new AvatarScalpel(); g_lpScalpel->setVisible(false); g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin")); g_lpRing->setVisible(false); TheEngine::Instance().add(g_lpScalpel); TheEngine::Instance().add(g_lpRing); if(g_parser.value_to_int("ringscalpel") == 1) { g_lpAvatar = g_lpRing; g_lpRing->setVisible(true); } else { g_lpAvatar = g_lpScalpel; g_lpScalpel->setVisible(true); } g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(cutFinished); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); TheGizmoManager::Instance().readConfig(g_strIniFilePath); //setup engine TheEngine::Instance().readConfig(g_strIniFilePath); TheEngine::Instance().headers()->addHeaderLine("cell", "info"); TheEngine::Instance().print(); //reset cuttable mesh resetMesh(); //mainloop while (!glfwWindowShouldClose(g_lpWindow)) { //setup projection matrix int width = DEFAULT_WIDTH; int height = DEFAULT_HEIGHT; glfwGetFramebufferSize(g_lpWindow, &width, &height); def_resize(width, height); //draw frame draw(); timestep(); glfwSwapBuffers(g_lpWindow); glfwPollEvents(); } //destroy window glfwDestroyWindow(g_lpWindow); glfwTerminate(); exit(EXIT_SUCCESS); return 0; }
bool resetMesh() { //remove it from scenegraph TheEngine::Instance().remove(g_lpTissue); SAFE_DELETE(g_lpTissue); if(!FileExists(g_strIniFilePath)) { vlogerror("ini file not exists! [%s]", g_strIniFilePath.c_str()); return false; } vloginfo("reading model config from ini file: [%s]", g_strIniFilePath.c_str()); IniFile ini(g_strIniFilePath, IniFile::fmRead); AnsiStr mdl_type = ini.readString("model", "type"); AnsiStr mdl_name = ini.readString("model", "name"); VolMesh* temp = NULL; //loading internal model if(mdl_type == "internal") { int pos = -1; if(mdl_name == "one") temp = VolMeshSamples::CreateOneTetra(); else if(mdl_name == "two") temp = VolMeshSamples::CreateTwoTetra(); else if(mdl_name.lfindstr(AnsiStr("cube"), pos)) { U32 nx, ny, nz = 0; sscanf(mdl_name.cptr(), "cube_%u_%u_%u", &nx, &ny, &nz); temp = VolMeshSamples::CreateTruthCube(nx, ny, nz, 0.2); } else if(mdl_name.lfindstr(AnsiStr("eggshell"), pos)) { U32 nx, ny; //float radius, thickness; sscanf(mdl_name.cptr(), "eggshell_%u_%u", &nx, &ny); temp = VolMeshSamples::CreateEggShell(nx, ny); } else temp = VolMeshSamples::CreateOneTetra(); } else if(mdl_type == "file") { temp = new VolMesh(); temp->setFlagFilterOutFlatCells(false); temp->setVerbose(g_parser.value_to_int("verbose")); if(!FileExists(mdl_name)) { AnsiStr data_root_path = ini.readString("system", "data"); mdl_name = data_root_path + "meshes/veg/" + mdl_name; vloginfo("resolved model name to [%s]", mdl_name.cptr()); } vloginfo("Begin to read vega file from: %s", mdl_name.cptr()); bool res = VolMeshIO::readVega(temp, mdl_name); if(!res) vlogerror("Unable to load mesh from: %s", mdl_name.cptr()); } vloginfo("Loaded mesh to temp"); g_lpTissue = new CuttableMesh(*temp); g_lpTissue->setFlagSplitMeshAfterCut(true); g_lpTissue->setFlagDrawNodes(true); g_lpTissue->setFlagDrawWireFrame(false); g_lpTissue->setFlagDrawSweepSurf(ini.readBool("visible", "sweepsurf")); g_lpTissue->setColor(Color::skin()); g_lpTissue->setVerbose(g_parser.value_to_int("verbose") != 0); g_lpTissue->syncRender(); SAFE_DELETE(temp); TheEngine::Instance().add(g_lpTissue); if(g_parser.value_to_int("ringscalpel") == 1) g_lpRing->setTissue(g_lpTissue); else g_lpScalpel->setTissue(g_lpTissue); //print stats VolMeshStats::printAllStats(g_lpTissue); vloginfo("mesh load completed"); }
void normal_key(unsigned char key, int x, int y) { key = tolower(key); switch(key) { case('/'): { g_lpTissue->setFlagDrawSweepSurf(!g_lpTissue->getFlagDrawSweepSurf()); vloginfo("Draw sweep surf set to: %d", g_lpTissue->getFlagDrawSweepSurf()); } break; case('a'): { if(!g_lpTissue) return; U32 i = g_lpTissue->getElemToShow(); if(g_lpTissue->isCellIndex(i)) g_lpTissue->setElemToShow(--i); else g_lpTissue->setElemToShow(0); if(g_lpTissue->isCellIndex(i)) { const CELL& cell = g_lpTissue->const_cellAt(i); AnsiStr strInfo = printToAStr("cell [%u], nodes [%u, %u, %u, %u]", i, cell.nodes[0], cell.nodes[1], cell.nodes[2], cell.nodes[3]); TheEngine::Instance().headers()->updateHeaderLine("cell", strInfo); } } break; case('d'): { if(!g_lpTissue) return; U32 i = g_lpTissue->getElemToShow(); if(g_lpTissue->isCellIndex(i)) g_lpTissue->setElemToShow(++i); else g_lpTissue->setElemToShow(0); if(g_lpTissue->isCellIndex(i)) { const CELL& cell = g_lpTissue->const_cellAt(i); AnsiStr strInfo = printToAStr("cell [%u], nodes [%u, %u, %u, %u]", i, cell.nodes[0], cell.nodes[1], cell.nodes[2], cell.nodes[3]); TheEngine::Instance().headers()->updateHeaderLine("cell", strInfo); } } break; case('e'): { if(!g_lpTissue) return; U32 ctElems = g_lpTissue->countCells(); U32 idxElem = -1; printf("Insert element index to show: [0:%u]\n", ctElems-1); scanf("%u", &idxElem); if(g_lpTissue->isCellIndex(idxElem)) g_lpTissue->setElemToShow(idxElem); else g_lpTissue->setElemToShow(); } break; case('g'):{ TheGizmoManager::Instance().setType(gtTranslate); } break; case('h'):{ bool flag = !TheEngine::Instance().get("headers")->isVisible(); TheEngine::Instance().get("headers")->setVisible(flag); vloginfo("Set headers draw to %s", flag ? "show" : "hide"); break; } case('s'):{ TheGizmoManager::Instance().setType(gtScale); break; } case('r'):{ TheGizmoManager::Instance().setType(gtRotate); break; } case ('t'): { if (g_lpAvatar == g_lpScalpel) { g_lpAvatar = g_lpRing; g_lpScalpel->setVisible(false); } else { g_lpAvatar = g_lpScalpel; g_lpRing->setVisible(false); } g_lpAvatar->setVisible(true); g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(cutFinished); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); break; } case('.'):{ if(g_lpTissue) g_lpTissue->setFlagDrawWireFrame(!g_lpTissue->getFlagDrawWireFrame()); vloginfo("Wireframe mode is %d", g_lpTissue->getFlagDrawWireFrame()); break; } case('x'):{ TheGizmoManager::Instance().setAxis(axisX); } break; case('y'):{ TheGizmoManager::Instance().setAxis(axisY); } break; case('z'):{ TheGizmoManager::Instance().setAxis(axisZ); } break; case('m'): { bool flag = !TheEngine::Instance().get("rendermask")->isVisible(); TheEngine::Instance().get("rendermask")->setVisible(flag); vloginfo("Set rendermask to %s", flag ? "show" : "hide"); break; } break; case('p'): { TheEngine::Instance().print(); } break; case('['):{ TheEngine::Instance().camera().incrZoomLevel(0.5f); } break; case(']'):{ TheEngine::Instance().camera().incrZoomLevel(-0.5f); } break; case('w'):{ AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strOutput = strRoot + "data/output/"; AnsiStr strVegOutput = strOutput + printToAStr("%s_cuts%d.veg", g_lpTissue->name().c_str(), g_lpTissue->countCompletedCuts()); AnsiStr strObjOutput = strOutput + printToAStr("%s_cuts%d.obj", g_lpTissue->name().c_str(), g_lpTissue->countCompletedCuts()); vloginfo("Attempt to store at %s. Make sure all the required directories are present!", strVegOutput.cptr()); if(VolMeshIO::writeVega(g_lpTissue, strVegOutput)) vloginfo("Stored the mesh at: %s", strVegOutput.cptr()); vloginfo("Attempt to store at %s. Make sure all the required directories are present!", strObjOutput.cptr()); if(VolMeshIO::writeObj(g_lpTissue, strObjOutput)) vloginfo("Stored the mesh at: %s", strObjOutput.cptr()); } break; } //Update Screen // glutPostRedisplay(); }
int Run_SphereDistKernel() { AnsiStr strFP = ExtractOneLevelUp(ExtractFilePath(GetExePath())); strFP += AnsiStr("/PS_OpenCLKernels/SphereDist.cl"); ComputeDevice* lpGPU = new ComputeDevice(ComputeDevice::dtGPU); lpGPU->printInfo(); int prgID = lpGPU->addProgramFromFile(strFP.cptr()); assert(prgID >= 0); ComputeKernel* lpKernel = lpGPU->addKernel(prgID, "distSphere"); //Input Pos float* arrPosX = new float[DATA_SIZE]; float* arrPosY = new float[DATA_SIZE]; float* arrPosZ = new float[DATA_SIZE]; //Output Dist float* arrDist = new float[DATA_SIZE]; //Number of correct results returned unsigned int correct; cl_mem inMemPosX; cl_mem inMemPosY; cl_mem inMemPosZ; cl_mem outMemDist; // Fill the vector with random float values U32 count = DATA_SIZE; for (U32 i = 0; i < count; i++) { arrPosX[i] = rand() / (float) RAND_MAX; arrPosY[i] = rand() / (float) RAND_MAX; arrPosZ[i] = rand() / (float) RAND_MAX; } // Create the device memory vectors inMemPosX = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); inMemPosY = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); inMemPosZ = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memReadOnly); outMemDist = lpGPU->createMemBuffer(sizeof(float) * count, PS::CL::memWriteOnly); // Transfer the input vector into device memory. //PosX if (!lpGPU->enqueueWriteBuffer(inMemPosX, sizeof(float) * count, arrPosX)) return -1; //PosY if (!lpGPU->enqueueWriteBuffer(inMemPosY, sizeof(float) * count, arrPosY)) return -1; //PosZ if (!lpGPU->enqueueWriteBuffer(inMemPosZ, sizeof(float) * count, arrPosZ)) return -1; // Set the arguments to the compute kernel lpKernel->setArg(0, sizeof(cl_mem), &inMemPosX); lpKernel->setArg(1, sizeof(cl_mem), &inMemPosY); lpKernel->setArg(2, sizeof(cl_mem), &inMemPosZ); lpKernel->setArg(3, sizeof(cl_mem), &outMemDist); lpKernel->setArg(4, sizeof(U32), &count); size_t local; size_t global; // Get the maximum work group size for executing the kernel on the device cl_int err = clGetKernelWorkGroupInfo(lpKernel->getKernel(), lpGPU->getDevice(), CL_KERNEL_WORK_GROUP_SIZE, sizeof(local), &local, NULL); if (err != CL_SUCCESS) { cerr << "Error: Failed to retrieve kernel work group info! " << err << endl; exit(1); } // Execute the kernel over the vector using the // maximum number of work group items for this device global = count; err = clEnqueueNDRangeKernel(lpGPU->getCommandQ(), lpKernel->getKernel(), 1, NULL, &global, &local, 0, NULL, NULL); if (err) { cerr << "Error: Failed to execute kernel!" << endl; return EXIT_FAILURE; } // Wait for all commands to complete lpGPU->finishAllCommands(); // Read back the results from the device to verify the output if (!lpGPU->enqueueReadBuffer(outMemDist, sizeof(float) * count, arrDist)) { return -1; } // Validate our results // correct = 0; float current; float v; for (U32 i = 0; i < count; i++) { current = arrDist[i]; v = arrPosX[i] * arrPosX[i] + arrPosY[i] * arrPosY[i] + arrPosZ[i] * arrPosZ[i]; if (FLOAT_EQ(current, v)) correct++; } // Print a brief summary detailing the results cout << "Computed " << correct << "/" << count << " correct values" << endl; cout << "Computed " << 100.f * (float) correct / (float) count << "% correct values" << endl; // Shutdown and cleanup SAFE_DELETE_ARRAY(arrPosX); SAFE_DELETE_ARRAY(arrPosY); SAFE_DELETE_ARRAY(arrPosZ); SAFE_DELETE_ARRAY(arrDist); clReleaseMemObject(inMemPosX); clReleaseMemObject(inMemPosY); clReleaseMemObject(inMemPosZ); clReleaseMemObject(outMemDist); SAFE_DELETE(lpGPU); return 1; }
int main(int argc, char* argv[]) { cout << "Cutting tets" << endl; g_parser.add_option("input", "[filepath] set input file in vega format", Value(AnsiStr("internal"))); g_parser.add_toggle("ringscalpel", "If the switch presents then the ring scalpel will be used"); g_parser.add_option("example", "[one, two, cube, eggshell] set an internal example", Value(AnsiStr("two"))); g_parser.add_option("gizmo", "loads a file to set gizmo location and orientation", Value(AnsiStr("gizmo.ini"))); if (g_parser.parse(argc, argv) < 0) exit(0); //file path g_strFilePath = ExtractFilePath(GetExePath()) + g_parser.value<AnsiStr>("input"); if (FileExists(g_strFilePath)) LogInfoArg1("input file: %s.", g_strFilePath.cptr()); else g_strFilePath = ""; //Initialize app glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); glutCreateWindow("SoftRigidDynamics - Pourya Shirazian"); glutDisplayFunc(draw); glutReshapeFunc(def_resize); glutMouseFunc(MousePress); glutPassiveMotionFunc(MousePassiveMove); glutMotionFunc(MouseMove); glutMouseWheelFunc(MouseWheel); glutKeyboardFunc(NormalKey); glutSpecialFunc(SpecialKey); glutCloseFunc(closeApp); glutIdleFunc(timestep); def_initgl(); //Build Shaders for drawing the mesh AnsiStr strRoot = ExtractOneLevelUp(ExtractFilePath(GetExePath())); AnsiStr strShaderRoot = strRoot + "data/shaders/"; AnsiStr strMeshRoot = strRoot + "data/meshes/"; AnsiStr strTextureRoot = strRoot + "data/textures/"; AnsiStr strLeftPial = strMeshRoot + "brain/pial_Full_obj/lh.pial.obj"; AnsiStr strRightPial = strMeshRoot + "brain/pial_Full_obj/rh.pial.obj"; //Load Shaders TheShaderManager::Instance().addFromFolder(strShaderRoot.cptr()); //Load Textures TheTexManager::Instance().add(strTextureRoot + "wood.png"); TheTexManager::Instance().add(strTextureRoot + "rendermask.png"); TheTexManager::Instance().add(strTextureRoot + "maskalpha.png"); TheTexManager::Instance().add(strTextureRoot + "maskalphafilled.png"); TheTexManager::Instance().add(strTextureRoot + "spin.png"); //Ground and Room //TheSceneGraph::Instance().addFloor(32, 32, 0.5f); TheSceneGraph::Instance().addSceneBox(AABB(vec3f(-10, -10, -16), vec3f(10, 10, 16))); //floor Geometry g; g.addCube(vec3f(-8, -2.0, -8), vec3f(8, -1.8, 8)); g.addPerVertexColor(vec4f(0.5, 0.5, 0.5, 1)); SGBulletRigidMesh* floor = new SGBulletRigidMesh(); floor->setup(g, 0.0); floor->setName("floor"); TheSceneGraph::Instance().addRigidBody(floor); //create rigid bodies /* Geometry g1; g1.addCube(vec3f(0.0, 0.0, 0.0), 1.0); g1.addPerVertexColor(vec4f(0, 0, 1, 1)); for(int i=0; i < 8; i ++) { for(int j=0; j < 8; j++) { g1.colors().clear(); float r = RandRangeT<float>(0.0, 1.0); float g = RandRangeT<float>(0.0, 1.0); float b = RandRangeT<float>(0.0, 1.0); g1.addPerVertexColor(vec4f(r, g, b, 1.0f)); SGBulletRigidMesh* acube = new SGBulletRigidMesh(); acube->transform()->setTranslate(vec3f(i-3, 10.0, j-3)); acube->setup(g1, 1.0); TheSceneGraph::Instance().addRigidBody(acube); } } */ //Scalpel g_lpScalpel = new AvatarScalpel(); g_lpRing = new AvatarRing(TheTexManager::Instance().get("spin")); TheSceneGraph::Instance().add(g_lpScalpel); TheSceneGraph::Instance().add(g_lpRing); if(g_parser.value<int>("ringscalpel")) { g_lpAvatar = g_lpRing; g_lpScalpel->setVisible(false); } else { g_lpAvatar = g_lpScalpel; g_lpRing->setVisible(false); } g_lpAvatar->setTissue(g_lpTissue); g_lpAvatar->setOnCutFinishedEventHandler(finishedcut); TheGizmoManager::Instance().setFocusedNode(g_lpAvatar); //load gizmo manager file AnsiStr strGizmoFP = g_parser.value<AnsiStr>("gizmo"); TheGizmoManager::Instance().readConfig(strGizmoFP); resetMesh(); //render mask // SGRenderMask* renderMask = new SGRenderMask(TheTexManager::Instance().get("maskalpha")); // renderMask->setName("rendermask"); // TheSceneGraph::Instance().add(renderMask); glutMainLoop(); return 0; }