void dirjob_ret (struct dirjob *job, int err) { int ret = 0; int refcnt = 0; struct dirjob *parent = NULL; pthread_spin_lock (&job->lock); { refcnt = --job->refcnt; job->ret = (job->ret || err); } pthread_spin_unlock (&job->lock); if (refcnt == 0) { ret = job->ret; if (ret) terr ("Failed: %s (%d)\n", job->dirname, ret); else tdbg ("Finished: %s\n", job->dirname); parent = job->parent; if (parent) dirjob_ret (parent, ret); dirjob_free (job); job = NULL; } }
void CreateWaterMesh(unsigned int size, Mesh& outM) { //Just create a flat terrain and let it do the math. Terrain terr(Vector2u(size, size)); std::vector<WaterVertex> verts; std::vector<unsigned int> indices; { Array2D<float> heightmap(size, size, 0.0f); terr.SetHeightmap(heightmap); terr.GenerateTrianglesFull<WaterVertex>( verts, indices, [](WaterVertex& v) { return &v.Pos; }, [](WaterVertex& v) { return &v.TexCoord; }); } //Convert the terrain vertices into water vertices. float invSize = 1.0f / (float)size; for (unsigned int i = 0; i < verts.size(); ++i) { verts[i].Pos = Vector3f(verts[i].Pos.x * invSize, verts[i].Pos.y * invSize, verts[i].Pos.z); } //Upload the mesh data into vertex/index buffers. outM.SetVertexData(verts, Mesh::BUF_STATIC, WaterVertex::GetVertexAttributes()); outM.SetIndexData(indices, Mesh::BUF_STATIC); }
void CreateWaterMesh(unsigned int size, Vector3f scle, Mesh& outM) { Vector3f offset(size * -0.5f, size * -0.5f, 0.0f); Array2D<float> terrainHeight(size, size, 0.0f); //Just create a flat terrain and let it do the math. Terrain terr(Vector2u(size, size)); terr.SetHeightmap(terrainHeight); std::vector<WaterVertex> verts; std::vector<unsigned int> indices; terr.GenerateTrianglesFull<WaterVertex>(verts, indices, [](WaterVertex& v) { return &v.Pos; }, [](WaterVertex& v) { return &v.TexCoord; }); //Convert the terrain vertices into water vertices. for (unsigned int i = 0; i < verts.size(); ++i) { verts[i].Pos = verts[i].Pos.ComponentProduct(scle) + offset; } //Upload the mesh data into vertex/index buffers. outM.SubMeshes.push_back(MeshData(false, PT_TRIANGLE_LIST)); MeshData& mDat = outM.SubMeshes[0]; mDat.SetVertexData(verts, MeshData::BUF_STATIC, WaterVertex::GetVertexAttributes()); mDat.SetIndexData(indices, MeshData::BUF_STATIC); }
int main(void) { akari::Terrain terr(10, 10, 0); akari::Camera camera; akari::InfoUI info_ui; akari::Bitmap bitmap_mgr; //file open/save dialog OPENFILENAME ofn ; wchar_t szFile[260]; ZeroMemory(&ofn , sizeof(ofn)); ofn.lStructSize = sizeof (ofn); ofn.hwndOwner = NULL; ofn.lpstrFile = szFile; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = L"Bitmap File\0*.bmp\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir= NULL; ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST; //init size int width, height; scanf("%d %d", &width, &height); terr.Reset(width, height, 0); //temp input managing bool is_rotating_ = false; bool is_rotating_pressing_ = false; int running = GL_TRUE; // Initialize GLFW if( !glfwInit() ) { exit( EXIT_FAILURE ); } // Open an OpenGL window if( !glfwOpenWindow( WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) ) { glfwTerminate(); exit( EXIT_FAILURE ); } Init(); // Main loop while( running ) { // OpenGL rendering goes here... glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glLoadIdentity(); camera.Update(); if(is_rotating_) { glRotatef(glfwGetTime() * 75, 0, 1, 0); } terr.Update(camera.GetEye(),camera.GetLookAt()); terr.Draw(0, is_rotating_); info_ui.DrawHelp(); info_ui.DrawTerrainInfo(terr); info_ui.DrawAxis(); info_ui.DrawCameraInfo(camera); info_ui.DrawIsRotating(is_rotating_); glFlush(); // Swap front and back rendering buffers glfwSwapBuffers(); // Check if ESC key was pressed or window was closed running = !glfwGetKey( GLFW_KEY_ESC ) && glfwGetWindowParam( GLFW_OPENED ); if(glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT)) { terr.Click(); } if(glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT)) { terr.RightClick(); } if(!is_rotating_pressing_ && glfwGetKey('M') == GLFW_PRESS) { is_rotating_ = !is_rotating_; is_rotating_pressing_ = true; } if(glfwGetKey('M') == GLFW_RELEASE) { is_rotating_pressing_ = false; } //File Open if(glfwGetKey('O') == GLFW_PRESS) { if(GetOpenFileName(&ofn)) { bitmap_mgr.ImportBMP(terr, ofn.lpstrFile); MessageBox ( NULL , ofn.lpstrFile , L"Open File" , MB_OK); } } if(glfwGetKey('P') == GLFW_PRESS) { if(GetSaveFileName(&ofn)) { bitmap_mgr.ExportBMP(terr, ofn.lpstrFile); MessageBox ( NULL , ofn.lpstrFile , L"Saved." , MB_OK); } } if(glfwGetKey('[') == GLFW_PRESS) { if(GetSaveFileName(&ofn)) { bitmap_mgr.ExportBMPForSimcity(terr, ofn.lpstrFile); MessageBox(NULL, ofn.lpstrFile, L"Saved for simcity.", MB_OK); } } } // Close window and terminate GLFW glfwTerminate(); // Exit program exit( EXIT_SUCCESS ); return 0; }
int xworker_do_crawl (struct xwork *xwork, struct dirjob *job) { DIR *dirp = NULL; int ret = -1; int boff; int plen; struct dirent *result; char dbuf[512]; char *path = NULL; struct dirjob *cjob = NULL; struct stat statbuf = {0,}; char gfid_path[4096] = {0,}; plen = strlen (job->dirname) + 256 + 2; path = alloca (plen); tdbg ("Entering: %s\n", job->dirname); dirp = sys_opendir (job->dirname); if (!dirp) { terr ("opendir failed on %s (%s)\n", job->dirname, strerror (errno)); goto out; } boff = sprintf (path, "%s/", job->dirname); for (;;) { ret = readdir_r (dirp, (struct dirent *)dbuf, &result); if (ret) { err ("readdir_r(%s): %s\n", job->dirname, strerror (errno)); goto out; } if (!result) /* EOF */ break; if (result->d_ino == 0) continue; if (skip_name (job->dirname, result->d_name)) continue; /* It is sure that, children and grandchildren of .glusterfs * are directories, just add them to global queue. */ if (skip_stat (job, result->d_name)) { strncpy (path + boff, result->d_name, (plen-boff)); cjob = dirjob_new (path, job); if (!cjob) { err ("dirjob_new(%s): %s\n", path, strerror (errno)); ret = -1; goto out; } xwork_addcrawl (xwork, cjob); continue; } strcpy (gfid_path, slavemnt); strcat (gfid_path, "/.gfid/"); strcat (gfid_path, result->d_name); ret = lstat (gfid_path, &statbuf); if (ret && errno == ENOENT) { out ("%s\n", result->d_name); BUMP (skipped_gfids); } if (ret && errno != ENOENT) { err ("stat on slave failed(%s): %s\n", gfid_path, strerror (errno)); goto out; } } ret = 0; out: if (dirp) sys_closedir (dirp); return ret; }
//[[Rcpp::export]] Rcpp::List nnmf(const mat & A, const unsigned int k, mat W, mat H, umat Wm, umat Hm, const vec & alpha, const vec & beta, const unsigned int max_iter, const double rel_tol, const int n_threads, const int verbose, const bool show_warning, const unsigned int inner_max_iter, const double inner_rel_tol, const int method, unsigned int trace) { /****************************************************************************************************** * Non-negative Matrix Factorization(NNMF) using alternating scheme * ---------------------------------------------------------------- * Description: * Decompose matrix A such that * A = W H * Arguments: * A : Matrix to be decomposed * W, H : Initial matrices of W and H, where ncol(W) = nrow(H) = k. # of rows/columns of W/H could be 0 * Wm, Hm : Masks of W and H, s.t. masked entries are no-updated and fixed to initial values * alpha : [L2, angle, L1] regularization on W (non-masked entries) * beta : [L2, angle, L1] regularization on H (non-masked entries) * max_iter : Maximum number of iteration * rel_tol : Relative tolerance between two successive iterations, = |e2-e1|/avg(e1, e2) * n_threads : Number of threads (openMP) * verbose : Either 0 = no any tracking, 1 == progression bar, 2 == print iteration info * show_warning : If to show warning if targeted `tol` is not reached * inner_max_iter : Maximum number of iterations passed to each inner W or H matrix updating loop * inner_rel_tol : Relative tolerance passed to inner W or H matrix updating loop, = |e2-e1|/avg(e1, e2) * method : Integer of 1, 2, 3 or 4, which encodes methods * : 1 = sequential coordinate-wise minimization using square loss * : 2 = Lee's multiplicative update with square loss, which is re-scaled gradient descent * : 3 = sequentially quadratic approximated minimization with KL-divergence * : 4 = Lee's multiplicative update with KL-divergence, which is re-scaled gradient descent * trace : A positive integer, error will be checked very 'trace' iterations. Computing WH can be very expansive, * : so one may not want to check error A-WH every single iteration * Return: * A list (Rcpp::List) of * W, H : resulting W and H matrices * mse_error : a vector of mean square error (divided by number of non-missings) * mkl_error : a vector (length = number of iterations) of mean KL-distance * target_error : a vector of loss (0.5*mse or mkl), plus constraints * average_epoch : a vector of average epochs (one complete swap over W and H) * Author: * Eric Xihui Lin <*****@*****.**> * Version: * 2015-12-11 ******************************************************************************************************/ unsigned int n = A.n_rows; unsigned int m = A.n_cols; //int k = H.n_rows; // decomposition rank k unsigned int N_non_missing = n*m; if (trace < 1) trace = 1; unsigned int err_len = (unsigned int)std::ceil(double(max_iter)/double(trace)) + 1; vec mse_err(err_len), mkl_err(err_len), terr(err_len), ave_epoch(err_len); // check progression bool show_progress = false; if (verbose == 1) show_progress = true; Progress prgrss(max_iter, show_progress); double rel_err = rel_tol + 1; double terr_last = 1e99; uvec non_missing; bool any_missing = !A.is_finite(); if (any_missing) { non_missing = find_finite(A); N_non_missing = non_missing.n_elem; mkl_err.fill(mean((A.elem(non_missing)+TINY_NUM) % log(A.elem(non_missing)+TINY_NUM) - A.elem(non_missing))); } else mkl_err.fill(mean(mean((A+TINY_NUM) % log(A+TINY_NUM) - A))); // fixed part in KL-dist, mean(A log(A) - A) if (Wm.empty()) Wm.resize(0, n); else inplace_trans(Wm); if (Hm.empty()) Hm.resize(0, m); if (W.empty()) { W.randu(k, n); W *= 0.01; if (!Wm.empty()) W.elem(find(Wm > 0)).fill(0.0); } else inplace_trans(W); if (H.empty()) { H.randu(k, m); H *= 0.01; if (!Hm.empty()) H.elem(find(Hm > 0)).fill(0.0); } if (verbose == 2) { Rprintf("\n%10s | %10s | %10s | %10s | %10s\n", "Iteration", "MSE", "MKL", "Target", "Rel. Err."); Rprintf("--------------------------------------------------------------\n"); } int total_raw_iter = 0; unsigned int i = 0; unsigned int i_e = 0; // index for error checking for(; i < max_iter && std::abs(rel_err) > rel_tol; i++) { Rcpp::checkUserInterrupt(); prgrss.increment(); if (any_missing) { // update W total_raw_iter += update_with_missing(W, H, A.t(), Wm, alpha, inner_max_iter, inner_rel_tol, n_threads, method); // update H total_raw_iter += update_with_missing(H, W, A, Hm, beta, inner_max_iter, inner_rel_tol, n_threads, method); if (i % trace == 0) { const mat & Ahat = W.t()*H; mse_err(i_e) = mean(square((A - Ahat).eval().elem(non_missing))); mkl_err(i_e) += mean((-(A+TINY_NUM) % log(Ahat+TINY_NUM) + Ahat).eval().elem(non_missing)); } } else { // update W total_raw_iter += update(W, H, A.t(), Wm, alpha, inner_max_iter, inner_rel_tol, n_threads, method); // update H total_raw_iter += update(H, W, A, Hm, beta, inner_max_iter, inner_rel_tol, n_threads, method); if (i % trace == 0) { const mat & Ahat = W.t()*H; mse_err(i_e) = mean(mean(square((A - Ahat)))); mkl_err(i_e) += mean(mean(-(A+TINY_NUM) % log(Ahat+TINY_NUM) + Ahat)); } } if (i % trace == 0) { ave_epoch(i_e) = double(total_raw_iter)/(n+m); if (method < 3) // mse based terr(i_e) = 0.5*mse_err(i_e); else // KL based terr(i_e) = mkl_err(i_e); add_penalty(i_e, terr, W, H, N_non_missing, alpha, beta); rel_err = 2*(terr_last - terr(i_e)) / (terr_last + terr(i_e) + TINY_NUM ); terr_last = terr(i_e); if (verbose == 2) Rprintf("%10d | %10.4f | %10.4f | %10.4f | %10.g\n", i+1, mse_err(i_e), mkl_err(i_e), terr(i_e), rel_err); total_raw_iter = 0; // reset to 0 ++i_e; } } // compute error of the last iteration if ((i-1) % trace != 0) { if (any_missing) { const mat & Ahat = W.t()*H; mse_err(i_e) = mean(square((A - Ahat).eval().elem(non_missing))); mkl_err(i_e) += mean((-(A+TINY_NUM) % log(Ahat+TINY_NUM) + Ahat).eval().elem(non_missing)); } else { const mat & Ahat = W.t()*H; mse_err(i_e) = mean(mean(square((A - Ahat)))); mkl_err(i_e) += mean(mean(-(A+TINY_NUM) % log(Ahat+TINY_NUM) + Ahat)); } ave_epoch(i_e) = double(total_raw_iter)/(n+m); if (method < 3) // mse based terr(i_e) = 0.5*mse_err(i_e); else // KL based terr(i_e) = mkl_err(i_e); add_penalty(i_e, terr, W, H, N_non_missing, alpha, beta); rel_err = 2*(terr_last - terr(i_e)) / (terr_last + terr(i_e) + TINY_NUM ); terr_last = terr(i_e); if (verbose == 2) Rprintf("%10d | %10.4f | %10.4f | %10.4f | %10.g\n", i+1, mse_err(i_e), mkl_err(i_e), terr(i_e), rel_err); ++i_e; } if (verbose == 2) { Rprintf("--------------------------------------------------------------\n"); Rprintf("%10s | %10s | %10s | %10s | %10s\n\n", "Iteration", "MSE", "MKL", "Target", "Rel. Err."); } if (i_e < err_len) { mse_err.resize(i_e); mkl_err.resize(i_e); terr.resize(i_e); ave_epoch.resize(i_e); } if (show_warning && rel_err > rel_tol) Rcpp::warning("Target tolerance not reached. Try a larger max.iter."); return Rcpp::List::create( Rcpp::Named("W") = W.t(), Rcpp::Named("H") = H, Rcpp::Named("mse_error") = mse_err, Rcpp::Named("mkl_error") = mkl_err, Rcpp::Named("target_error") = terr, Rcpp::Named("average_epoch") = ave_epoch, Rcpp::Named("n_iteration") = i ); }
int main(int argc, char ** argv[]) { Display display(800, 600, "TSBK07 Level of Detail on Terrain"); Basic_Shader base_shader("./shaders/space"); Phong_Shader phong("./shaders/phong"); Texture texture("./textures/dirt.tga"); Camera camera(glm::vec3(0, 1, 0), 70.0f, display.GetAspectRation(), 0.01f, 1000.0f); Terrain terr("./textures/terrain2.jpg", "./textures/terrain2.jpg"); Skybox sky; sky.SkyboxInit("./textures/skybox/", "back.jpg", "front.jpg", "left.jpg", "right.jpg", "top.jpg", "bottom.jpg"); Transform transform; Keyboard keyboard; Mouse mouse; float counter = 0.0f; Mesh monkey("./models/monkey3.obj"); Mesh box("./models/box.obj"); std::cout << "init complete" << std::endl; bool wireframe = true; bool lock = false; while (!display.IsClosed()) { display.Clear(1, 0, 1, 1); SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { display.HandleEvent(e); } if (e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP) { mouse.HandleEvent(e, camera); } } const Uint8* currentKeyStates = SDL_GetKeyboardState(NULL); keyboard.HandleEvent(currentKeyStates, camera); sky.Draw(transform, camera); if (currentKeyStates[SDL_SCANCODE_B]) { lock = !lock; } if (currentKeyStates[SDL_SCANCODE_F]) { wireframe = !wireframe; } terr.Draw(transform, camera, lock, wireframe); display.Update(); counter += 0.001f; } return 0; }