int main( int argc, char *argv[] ) { glutInit( &argc, argv ); glutInitWindowPosition( 200, 200 ); glutInitWindowSize( 800, 500 ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); glutCreateWindow("World of Awesome"); glutReshapeFunc( ReshapeGL ); glutDisplayFunc( Draw ); glutKeyboardFunc( keyboard ); glutMouseFunc( mouse ); glutMotionFunc( mouseMove ); glutPassiveMotionFunc( passiveMove ); glutTimerFunc(TIMER_DELAY, tock, 0); g_width = g_height = 200; #ifdef _WIN32 GLenum err = glewInit(); if (GLEW_OK != err) { std::cerr << "Error initializing glew! " << glewGetErrorString(err) << std::endl; return 1; } #endif #ifdef __APPLE__ glutSetCursor(GLUT_CURSOR_NONE); #endif backShade = glm::vec3(0.2,0.5,0.9); Initialize(); //test the openGL version getGLversion(); //install the shader if (!InstallShader(textFileRead((char *)"shaders/vert.glsl"), textFileRead((char *)"shaders/frag.glsl"))) { printf("Error installing shader!\n"); return 0; } InitGeom(); g_shadeType = PHONG; g_pitch = 0; g_yaw = M_PI / 2; float tx = cos(g_pitch)*cos(g_yaw); float ty = sin(g_pitch); float tz = cos(g_pitch)*cos(M_PI/2 - g_yaw); eye = glm::vec3(0, 2.5, 0); target = eye + glm::vec3(tx, ty, tz); sunDir = normalize(vec3(-0.2, -1.0, 0.0)); sunShade = glm::vec3(1.0, 1.0, 0.9); glutMainLoop(); return 0; }
void TempoMap::setRelTempo(qreal val) { _relTempo = val; normalize(); }
void ProjectConfig::setScriptFile(const string &scriptFile) { _scriptFile = scriptFile; normalize(); }
int ACE_Svc_Conf_Lexer::yylex (YYSTYPE* ace_yylval, ACE_Svc_Conf_Param* param) { #if defined (ACE_USES_WCHAR) bool look_for_bom = false; ACE_Encoding_Converter_Factory::Encoding_Hint hint = ACE_Encoding_Converter_Factory::ACE_NONE; #endif /* ACE_USES_WCHAR */ if (param->buffer == 0) { #if defined (ACE_USES_WCHAR) look_for_bom = true; #endif /* ACE_USES_WCHAR */ ACE_NEW_RETURN (param->buffer, ace_yy_buffer_state, -1); } int token = ACE_NO_STATE; do { if (param->buffer->need_more_) { #if defined (ACE_USES_WCHAR) size_t skip_bytes = 0; #endif /* ACE_USES_WCHAR */ param->buffer->need_more_ = false; size_t amount = input (param, param->buffer->input_ + param->buffer->size_, normalize (ACE_YY_BUF_SIZE - param->buffer->size_)); if (amount == 0) { param->buffer->eof_ = true; #if defined (ACE_USES_WCHAR) skip_bytes = param->buffer->size_; #endif /* ACE_USES_WCHAR */ } else { #if defined (ACE_USES_WCHAR) if (look_for_bom) { size_t read_more = 0; look_for_bom = false; hint = locate_bom (param->buffer->input_, amount, read_more); if (read_more != 0) { input (param, param->buffer->input_ + amount, read_more); ACE_OS::memmove (param->buffer->input_, param->buffer->input_ + read_more, amount); } } skip_bytes = param->buffer->size_; #endif /* ACE_USES_WCHAR */ param->buffer->size_ += amount; } #if defined (ACE_USES_WCHAR) if (!convert_to_utf8 (param, skip_bytes, hint)) { ace_yyerror (++param->yyerrno, param->yylineno, ACE_TEXT ("Unable to convert input stream to UTF-8")); return ACE_NO_STATE; } #endif /* ACE_USES_WCHAR */ } token = scan (ace_yylval, param); } while (token == ACE_NO_STATE && param->buffer->need_more_); return token; }
void TimeSigMap::del(int tick) { erase(tick); normalize(); }
void TessMeshApp::Update(){ App::Update(); mesh->Update(); meshShaderProgram->use(); GLuint m = meshShaderProgram->uniform("model"); glUniformMatrix4fv(m, 1, GL_FALSE, glm::value_ptr(mesh->modelMatrix)); GLuint v = meshShaderProgram->uniform("view"); glUniformMatrix4fv(v, 1, GL_FALSE, glm::value_ptr(camera.view)); GLuint p = meshShaderProgram->uniform("projection"); glUniformMatrix4fv(p, 1, GL_FALSE, glm::value_ptr(camera.projection)); meshShaderProgram->disable(); mouseShaderProgram->use(); m = mouseShaderProgram->uniform("model"); glUniformMatrix4fv(m, 1, GL_FALSE, glm::value_ptr(mesh->modelMatrix)); v = mouseShaderProgram->uniform("view"); glUniformMatrix4fv(v, 1, GL_FALSE, glm::value_ptr(camera.view)); p = mouseShaderProgram->uniform("projection"); glUniformMatrix4fv(p, 1, GL_FALSE, glm::value_ptr(camera.projection)); // cursor { vec2 mouse = mouse_cursor; vec3 view = normalize( camera.camera_look_at - camera.camera_position ); vec3 h = normalize(cross(view, camera.camera_up)); vec3 v = normalize(cross(h, view)); float rad = radians(camera.field_of_view); float vLength = tanf(rad /2.0f) * camera.near_clip; float hLength = vLength * camera.aspect; v *= vLength; h *= hLength; mouse.x -= window_width/2; mouse.y = window_height - mouse.y - window_height/2; mouse.x /= window_width/2; mouse.y /= window_height/2; vec3 pos = camera.camera_position + view * (float)camera.near_clip + h*mouse.x + v*mouse.y; GLuint mousePosition = mouseShaderProgram->uniform("mousePosition"); glUniform3fv(mousePosition, 1, value_ptr(pos)); } mouseShaderProgram->disable(); }
int main(int argc, char* argv[]) { // welcome message std::cout<<"*********************************************************************************"<<std::endl; std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl; std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl; std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl; std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl; std::cout<<"* The retina model still have the following properties:"<<std::endl; std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl; std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl; std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl; std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl; std::cout<<"* for more information, reer to the following papers :"<<std::endl; std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl; std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl; std::cout<<"* => reports comments/remarks at [email protected]"<<std::endl; std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl; std::cout<<"*********************************************************************************"<<std::endl; std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl; std::cout<<"*********************************************************************************"<<std::endl; std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl; std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl; std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl; std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl; std::cout<<"*********************************************************************************"<<std::endl; // basic input arguments checking if (argc<2) { help("bad number of parameter"); return -1; } bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing std::string inputImageName=argv[1]; ////////////////////////////////////////////////////////////////////////////// // checking input media type (still image, video file, live video acquisition) std::cout<<"RetinaDemo: processing image "<<inputImageName<<std::endl; // image processing case // declare the retina input buffer... that will be fed differently in regard of the input media inputImage = cv::imread(inputImageName, -1); // load image in RGB mode std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl; if (!inputImage.total()) { help("could not load image, program end"); return -1; } // rescale between 0 and 1 normalize(inputImage, inputImage, 0.0, 1.0, cv::NORM_MINMAX); cv::Mat gammaTransformedImage; cv::pow(inputImage, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5) imshow("EXR image original image, 16bits=>8bits linear rescaling ", inputImage); imshow("EXR image with basic processing : 16bits=>8bits with gamma correction", gammaTransformedImage); if (inputImage.empty()) { help("Input image could not be loaded, aborting"); return -1; } ////////////////////////////////////////////////////////////////////////////// // Program start in a try/catch safety context (Retina may throw errors) try { /* create a retina instance with default parameters setup, uncomment the initialisation you wanna test * -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) */ if (useLogSampling) { retina = cv::createRetina(inputImage.size(),true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : retina = cv::createRetina(inputImage.size()); // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" retina->write("RetinaDefaultParameters.xml"); // desactivate Magnocellular pathway processing (motion information extraction) since it is not usefull here retina->activateMovingContoursProcessing(false); // declare retina output buffers cv::Mat retinaOutput_parvo; ///////////////////////////////////////////// // prepare displays and interactions histogramClippingValue=0; // default value... updated with interface slider //inputRescaleMat = inputImage; //outputRescaleMat = imageInputRescaled; cv::namedWindow("Retina input image (with cut edges histogram for basic pixels error avoidance)",1); cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat); cv::namedWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", 1); colorSaturationFactor=3; cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors); retinaHcellsGain=40; cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams); localAdaptation_photoreceptors=197; localAdaptation_Gcells=190; cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams); cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams); ///////////////////////////////////////////// // apply default parameters of user interaction variables rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100); retina->setColorSaturation(true,(float)colorSaturationFactor); callBack_updateRetinaParams(1,NULL); // first call for default parameters setup // processing loop with stop condition bool continueProcessing=true; while(continueProcessing) { // run retina filter retina->run(imageInputRescaled); // Retrieve and display retina output retina->getParvo(retinaOutput_parvo); cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0); cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo); cv::waitKey(10); } }catch(cv::Exception e) { std::cerr<<"Error using Retina : "<<e.what()<<std::endl; } // Program end message std::cout<<"Retina demo end"<<std::endl; return 0; }
void parse_ccom(char *cmd, struct chatroom *room, struct pork_acct *acct, int priv) { struct aim_chat *ccon = room->data; struct aim_priv *a_priv = acct->data; dlist_t *temp; char sn[MAXSNLEN+1]; char msg[MAXSNLEN+1024]; char *pmsg = msg; cmd[strcspn(cmd,"/")] = '\0'; if(!strncasecmp(cmd, "op ", 3) && (priv >= FULLOPS)) { cmd += 3; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_op(sn, room)) return; ccon->oparray = dlist_add_tail(ccon->oparray, xstrdup(sn)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been opped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } else if(!strncasecmp(cmd, "deop ", 5) && (priv >= FULLOPS)) { cmd += 5; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (!check_if_op(sn, room)) return; if (temp = dlist_find(ccon->oparray, sn, (void*)strcmp)) { free(temp->data); ccon->oparray = dlist_remove(ccon->oparray, temp); if (ccon->chatsends > 1) { sprintf(msg, "%s has been deopped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "defullop ", 7) && (priv >= DOWNERS)) { cmd += 9; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (temp = dlist_find(ccon->fullops, sn, (void*)strcmp)) { free(temp->data); ccon->fullops = dlist_remove(ccon->fullops, temp); if (ccon->chatsends > 1) { sprintf(msg, "%s has been defullopped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "fullop ", 7) && (priv >= FULLOPS)) { cmd += 7; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_fullop(sn, room)) return; ccon->fullops = dlist_add_tail(ccon->fullops, xstrdup(sn)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been fullopped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } else if(!strncasecmp(cmd, "halfop ", 7) && (priv > HALFOPS)) { cmd += 7; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_halfop(sn, room)) return; ccon->halfops = dlist_add_tail(ccon->halfops, xstrdup(sn)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been halfopped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } else if(!strncasecmp(cmd, "dehalfop ", 9) && (priv > HALFOPS)) { cmd += 9; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (!check_if_halfop(sn, room)) return; if (temp = dlist_find(ccon->halfops, sn, (void*)strcmp)) { free(temp->data); ccon->halfops = dlist_remove(ccon->halfops, temp); if (ccon->chatsends > 1) { sprintf(msg, "%s has been dehalfopped.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "kick ", 5)) { cmd += 5; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_imm(sn, room)) return; if (ccon->chatsends > 1) { snprintf(msg, MAXSNLEN+127, "kicking %s.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } if ((temp = dlist_find(ccon->banlist, sn, (void*)strcmp)) != NULL) { free(temp->data); ccon->banlist = dlist_remove(ccon->banlist, temp); } aim_chat_ban(&a_priv->aim_session, ccon->conn, sn); aim_chat_unban(&a_priv->aim_session, ccon->conn, sn); } else if(!strncasecmp(cmd, "ban ", 4) && (priv > HALFOPS)) { cmd += 4; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_imm(sn, room)) return; if (ccon->chatsends > 1) { snprintf(msg, MAXSNLEN+127, "banning %s.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } if (!dlist_find(ccon->banlist, sn, (void*)strcmp)) ccon->banlist = dlist_add_tail(ccon->banlist, xstrdup(sn)); aim_chat_ban(&a_priv->aim_session, ccon->conn, sn); } else if(!strncasecmp(cmd, "unban ", 6) && (priv > HALFOPS)) { cmd += 6; if (!aim_snvalid(cmd)) return; if (ccon->chatsends > 1) { snprintf(msg, MAXSNLEN+127, "unbanning %s.", cmd); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } if ((temp = dlist_find(ccon->banlist, cmd, (void*)strcmp)) != NULL) { free(temp->data); ccon->banlist = dlist_remove(ccon->banlist, temp); } aim_chat_unban(&a_priv->aim_session, ccon->conn, cmd); } else if(!strncasecmp(cmd, "pause ", 6) && (priv >= FULLOPS)) { cmd += 6; banpause = atoi(cmd); if (banpause < 0) banpause = 0; sprintf(msg, "autoban pause set to %g microseconds.", banpause); if (ccon->chatsends > 1) aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } else if(!strncasecmp(cmd, "help", 4) && ccon->chatsends) { char commands[MAXMSGLEN+1]; strcpy(commands, "commands are: !status, !kick, !imm"); if (priv > HALFOPS) strcat(commands,", !unimm, !ban, !unban, !ab, !unab, !aw, !unaw, !halfop, !dehalfop, !bj"); if (priv > OPS) strcat(commands,", !ak, !unak, !op, !deop, !fullop, !save, !load"); if (priv > FULLOPS) strcat(commands,", !defullop"); strcat(commands, "."); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, commands, strlen(commands), "us-ascii", "en"); } else if(!strncasecmp(cmd, "imm ", 4)) { cmd += 4; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_imm(sn, room)) return; ccon->immlist = dlist_add_tail(ccon->immlist, xstrdup(sn)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been immed.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } else if(!strncasecmp(cmd, "unimm ", 6) && (priv > HALFOPS)) { cmd += 6; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (!check_if_imm(sn, room)) return; if (temp = dlist_find(ccon->immlist, sn, (void*)strcmp)) { free(temp->data); ccon->immlist = dlist_remove(ccon->immlist, temp); if (ccon->chatsends > 1) { sprintf(msg, "%s has been unimmed.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "ak ", 3) && (priv > OPS)) { cmd += 3; if (!aim_snvalid(cmd)) return; if (check_if_ak(cmd, room)) return; normalize(sn, cmd, strlen(cmd) + 1); ccon->akarray = dlist_add_tail(ccon->akarray, xstrdup(cmd)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been autokicked.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } check_akusers_in_room(room); } else if(!strncasecmp(cmd, "ab ", 3) && (priv > HALFOPS)) { cmd += 3; if (!aim_snvalid(cmd)) return; if (check_if_ab(cmd, room)) return; normalize(sn, cmd, strlen(cmd) + 1); ccon->abarray = dlist_add_tail(ccon->abarray, xstrdup(cmd)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been autobanned.", sn); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } check_abusers_in_room(room); } else if(!strncasecmp(cmd, "aw ", 3) && (priv > HALFOPS)) { cmd += 3; if (check_if_aw(cmd, room)) return; ccon->awarray = dlist_add_tail(ccon->awarray, xstrdup(cmd)); if (ccon->chatsends > 1) { sprintf(msg, "%s has been autoworded.", cmd); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } else if(!strncasecmp(cmd, "unak ", 5) && (priv > OPS)) { cmd += 5; if (!aim_snvalid(cmd)) return; if (!check_if_ak(cmd, room)) return; if (temp = dlist_find(ccon->akarray, cmd, (void*)strcmp)) { free(temp->data); ccon->akarray = dlist_remove(ccon->akarray, temp); if (0) { //ccon->chatsends > 1) { sprintf(msg, "%s has been unautokicked.", cmd); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "unab ", 5) && (priv > HALFOPS)) { cmd += 5; if (!aim_snvalid(cmd)) return; if (!check_if_ab(cmd, room)) return; if (temp = dlist_find(ccon->abarray, cmd, (void*)strcmp)) { free(temp->data); ccon->abarray = dlist_remove(ccon->abarray, temp); if (0) { //ccon->chatsends > 1) { sprintf(msg, "%s has been unautobanned.", cmd); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "unaw ", 5) && (priv > HALFOPS)) { cmd += 5; if (!check_if_aw(cmd, room)) return; if (temp = dlist_find(ccon->awarray, cmd, (void*)strcmp)) { free(temp->data); ccon->awarray = dlist_remove(ccon->awarray, temp); if (ccon->chatsends > 1) { snprintf(msg, 1024, "%s has been unautoworded.", cmd); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "status ", 7) && ccon->chatsends) { strcpy(msg, ""); cmd += 7; if (!aim_snvalid(cmd)) return; partial_nick(cmd, sn, room); if (check_if_fullop(sn, room)) { sprintf(msg, "%s is a full op.", sn); } else if (check_if_op(sn, room)) { sprintf(msg, "%s is an op.", sn); } else if (check_if_halfop(sn, room)) { sprintf(msg, "%s is a half op", sn); if (check_if_imm(sn, room)) strcat(msg, " and immune"); strcat(msg, "."); } else if (check_if_imm(sn, room)) { sprintf(msg, "%s is immune.", sn); } if (strlen(msg)) aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, pmsg, strlen(msg), "us-ascii", "en"); } else if(!strncasecmp(cmd, "chatsends ", 10) && (priv >= FULLOPS)) { int chatsends; cmd += 10; chatsends = atoi(cmd); if ((chatsends >= 0) && (chatsends <= 2)) { ccon->chatsends = chatsends; if (ccon->chatsends > 1) { sprintf(msg, "chatsends now set to %d.", ccon->chatsends); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, msg, strlen(msg), "us-ascii", "en"); } } } else if(!strncasecmp(cmd, "save", 4) && (priv >= FULLOPS)) { if (!write_room(ccon)) { screen_err_msg("unable to save config for room %s.\n", ccon->title); } } else if(!strncasecmp(cmd, "load ", 5) && (priv >= FULLOPS)) { if (!read_room(ccon, &cmd[5])) { screen_err_msg("unable to load config for room %s.\n", &cmd[5]); } } else if(!strncasecmp(cmd, "bj", 2) && (priv > HALFOPS)) { ccon->banjoin = !ccon->banjoin; if (ccon->chatsends > 1) { sprintf(msg, "banjoin: %s.", ccon->banjoin?"on":"off"); aim_chat_send_im(&a_priv->aim_session, ccon->conn, 0, msg, strlen(msg), "us-ascii", "en"); } } }
// int main(int argc, char *argv[]) int APIENTRY WinMain(HINSTANCE hCurrentInst, HINSTANCE hPreviousInst,LPSTR lpszCmdLine, int nCmdShow) { SpringNetwork cloth = SpringNetworkCreateRectangular(17, 17, 1.0f); for (auto &v : cloth.X) v.z -= 1.75f; // put cloth object at 0,0,-1.5 region, view/camera will be at origin. cloth.gravity = float3(0, -10.0f, 0); // normally i perfer z-up for any environment or "world" space. cloth.dt = 0.033f; // speed it up a bit (regardless of fps, each frame advances cloth 1/30th of a second instead of just 1/60th). GLWin glwin("TestCloth sample"); glwin.keyboardfunc = OnKeyboard; InitTex(); // just initializes a checkerboard default texture int selection = 0; // index of currently selected point while (glwin.WindowUp()) { int point_to_unpin = -1; // if we temporarily move pin a point, we have to unpin it later after simulation. if (!glwin.MouseState) // on mouse drag { float3 v = glwin.MouseVector; // assumes camera at 0,0,0 looking down -z axis selection = std::max_element(cloth.X.begin(), cloth.X.end(), [&v](const float3&a, const float3&b)->bool{return dot(v, normalize(a)) < dot(v, normalize(b)); })- cloth.X.begin(); } else { if (!cloth.PointStatusSet(selection, -1)) cloth.PointStatusSet((point_to_unpin = selection), 1); const float3 &v = glwin.MouseVector; cloth.X[selection] = v * (dot(v, cloth.X[selection]) / dot(v, v) *(1.0f + glwin.mousewheel*0.1f)); } cloth.Simulate(); if(point_to_unpin >=0) cloth.PointStatusSet(point_to_unpin, 0); glPushAttrib(GL_ALL_ATTRIB_BITS); glViewport(0, 0, glwin.res.x,glwin.res.y); // Set up the viewport glClearColor(0.1f, 0.1f, 0.15f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01, 10); glMatrixMode(GL_MODELVIEW); glPushMatrix(); gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); glEnable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glPointSize(3); glBegin(GL_POINTS); for (unsigned int i = 0; i < cloth.X.size(); i++ ) glColor3f((i==selection)?1.0f:0 , 1, 0.5f), glVertex3fv(cloth.X[i]); glEnd(); if (g_wireframe) { glBegin(GL_LINES); SpringNetworkDrawSprings(&cloth, [](const float3 &a, const float3 &b, const float3 &c){glColor3fv(c); glVertex3fv(a); glVertex3fv(b); }); glColor3f(1, 0, 0); glEnd(); } else { glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1., 1. / (float)0x10000); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glColor3f(0.5f, 0.5f, 0.5f); glBegin(GL_QUADS); for (auto const & q: cloth.quads) { for (int c = 0; c <4; c++) glTexCoord2f(q[c]%17/16.0f,q[c]/17/16.0f),glNormal3fv(cloth.N[q[c]]), glVertex3fv(cloth.X[q[c]]); } glEnd(); } // Restore state glPopMatrix(); //should be currently in modelview mode glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glMatrixMode(GL_MODELVIEW); glwin.PrintString({ 0, 0 }, "Press ESC to quit. w toggles wireframe. "); glwin.PrintString({ 0, 1 }, "Use left mouse motion and wheel to move points."); glwin.PrintString({ 0, 2 }, "(w)ireframe %s vert selected %d", ((g_wireframe) ? "ON " : "OFF"), selection); # ifdef _DEBUG glwin.PrintString({ 2, -1 }, "Running DEBUG Version. Performance may be SLoooow.", 2, -1); # endif glwin.SwapBuffers(); } std::cout << "\n"; return 0; }
void Point3::normalizeXY() { m_z = 0; normalize(); }
void myKeyHandler(unsigned char ch, int x, int y) { int i; static int subdiv=0; struct point_t *slice; struct point_t *linecur; struct point_t *cur; struct point_t *new_points; struct slice_t *cur_slice,*cur2_slice; struct point_t *cur2; struct point_t points[5]; double a,b,c; GLfloat v1[3],v2[3],v3[3]; double deginc; // struct slice_t *cur_slice; switch(ch) { case 'q': endSubdiv(0); break; case 'z': mode=(~mode)&1; printf("%s\n",mode?"3D mode":"2D mode"); switch(mode) { case 0: resetCamera(); break; case 1: reset3DCamera(); break; } break; case 'k': /* test phong stuff */ cur_slice = slices; cur2_slice = slices->n; //while(cur_slice!=NULL) { cur = cur_slice->line; cur2 = cur2_slice->line; //while(cur->n!=NULL) { /* right vertex */ add_vec(&(cur->nx),&(cur->n->nx),&(points[0].nx)); normalize(&(points[0].nx)); sub_vec(&(cur->n->x),&(cur->x),v1); v1[0] /= 2; v1[1] /= 2; v1[2] /= 2; add_vec(&(cur->x),v1,&(points[0].x)); /* top vertex */ add_vec(&(cur->nx),&(cur2->nx),&(points[1].nx)); normalize(&(points[1].nx)); sub_vec(&(cur2->x),&(cur->x),v1); v1[0] /= 2; v1[1] /= 2; v1[2] /= 2; add_vec(&(cur->x),v1,&(points[1].x)); /* left vertex */ add_vec(&(cur2->nx),&(cur2->n->nx),&(points[2].nx)); normalize(&(points[2].nx)); sub_vec(&(cur2->n->x),&(cur2->x),v1); v1[0] /= 2; v1[1] /= 2; v1[2] /= 2; add_vec(&(cur2->x),v1,&(points[2].x)); /* bottom vertex */ add_vec(&(cur2->n->nx),&(cur->n->nx),&(points[3].nx)); normalize(&(points[3].nx)); sub_vec(&(cur->n->x),&(cur2->n->x),v1); v1[0] /= 2; v1[1] /= 2; v1[2] /= 2; add_vec(&(cur2->n->x),v1,&(points[3].x)); /* center vertex */ add_vec(&(points[0].nx),&(points[1].nx),v1); add_vec(&(points[2].nx),&(points[3].nx),v2); add_vec(v1,v2,&(points[4].nx)); normalize(&(points[4].nx)); sub_vec(&(points[3].x),&(cur2->n->x),v1); sub_vec(&(points[2].x),&(cur2->n->x),v2); add_vec(v1,v2,v3); normalize(v3); a=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]); b=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2]); c=sqrt(a*a+b*b); v3[0] *= c; v3[1] *= c; v3[2] *= c; add_vec(&(cur2->n->x),v3,&(points[4].x)); printf("v2[0]=%f,v2[1]=%f,v2[2]=%f\nv3[0]=%f,v3[1]=%f,v3[2]=%f\n",v2[0],v2[1],v2[2],v3[0],v3[1],v3[2]); for(i=0; i<5; i++) printf("points[%d]->x=%f,points[%d]->y=%f,points[%d]->z=%f\n", i,points[i].x,i,points[i].y,i,points[i].z); printf("cur->x=%f,cur->y=%f,cur->z=%f\ncur->n->x=%f,cur->n->y=%f,cur->n->z=%f\n", cur->x,cur->y,cur->z,cur->n->x,cur->n->y,cur->n->z); printf("cur2->x=%f,cur2->y=%f,cur2->z=%f\ncur2->n->x=%f,cur2->n->y=%f,cur2->n->z=%f\n", cur2->x,cur2->y,cur2->z,cur2->n->x,cur2->n->y,cur2->n->z); cur = cur->n; cur2 = cur2->n; } cur_slice = cur_slice->n; cur2_slice = cur2_slice->n != NULL ? cur2_slice->n : slices; /* circle around */ } break; case 'n': normals=(~normals)&1; printf("Normal mode %s\n",normals?"on":"off"); break; case 'e': solid=(~solid)&1; printf("%s\n",solid?"Solid mode":"Wireframe mode"); switch(solid) { case 0: glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); break; case 1: glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); break; } break; case 'r': faces=(~faces)&1; printf("%s\n",faces?"Faces mode":"Control points mode"); break; case 'w': /* calculate initial 3d object */ if(num<5) printf("There must be at least 5 control points.\n"); else if(!mode) { mode=(~mode)&1; printf("%s\n",mode?"3D mode":"2D mode"); switch(mode) { case 0: resetCamera(); break; case 1: reset3DCamera(); break; } freeModel(); subdiv_v = 0; subdiv_h = NUMSLICES; /* the radius of the circle for each of the points is x */ for(i=0;i<subdiv_h;i++) { ALLOC_POINT(slice); cur=slice; linecur=line; while(linecur!=NULL) { cur->z = linecur->x*sin(DEGINC*i); cur->x = linecur->x*cos(DEGINC*i); cur->y = linecur->y; linecur = linecur->n; if(linecur!=NULL) { ALLOC_POINT(cur->n); cur = cur->n; } } addSlice(slice); } } recompute_normals(); break; case 's': /* horizontal subdivision */ if(!mode || slices==NULL) break; /* backup the original slice */ new_points = duplicate_slice(slices->line); freeModel(); subdiv_h<<=1; subdiv++; printf("Horizontal subdivision level %d\n",subdiv); deginc = 2*M_PI/subdiv_h; for(i=0;i<subdiv_h;i++) { ALLOC_POINT(slice); cur=slice; linecur=new_points; while(linecur!=NULL) { cur->z = linecur->x*sin(deginc*i); cur->x = linecur->x*cos(deginc*i); cur->y = linecur->y; linecur = linecur->n; if(linecur!=NULL) { ALLOC_POINT(cur->n); cur = cur->n; } } addSlice(slice); } recompute_normals(); break; case 'a': /* vertical subdivision */ if(!mode || slices==NULL) break; cur_slice=slices; subdiv_v++; printf("Vertical subdivision level %d\n",subdiv_v); linecur = cur_slice->line; /* calc the first point */ cur = new_points = calc_point(linecur,linecur,linecur->n,linecur->n->n); /* calc middle and last points */ while(linecur->n->n!=NULL) { if(linecur->n->n->n!=NULL) /* middle points */ cur->n = calc_point(linecur,linecur->n,linecur->n->n,linecur->n->n->n); else cur->n = calc_point(linecur,linecur->n,linecur->n->n,linecur->n->n); cur = cur->n; linecur = linecur->n; } interleave(cur_slice->line,new_points); new_points = duplicate_slice(cur_slice->line); deginc = 2*M_PI/subdiv_h; freeModel(); for(i=0;i<subdiv_h;i++) { ALLOC_POINT(slice); cur=slice; linecur=new_points; while(linecur!=NULL) { cur->z = linecur->x*sin(deginc*i); cur->x = linecur->x*cos(deginc*i); cur->y = linecur->y; linecur = linecur->n; if(linecur!=NULL) { ALLOC_POINT(cur->n); cur = cur->n; } } addSlice(slice); } recompute_normals(); break; case 'd': shading=(~shading)&1; printf("%s shading\n",shading?"Phong":"Gouraud"); break; case '<': if(mode) { glMatrixMode(GL_MODELVIEW); glRotatef(1,0.0,1.0,0.0); } break; case '>': if(mode) { glMatrixMode(GL_MODELVIEW); glRotatef(-1,0.0,1.0,0.0); } break; default: /* Unrecognized keypress */ return; } glutPostRedisplay(); return; }
Model::Model(const std::string &filename, const Vector &off) : bbtop({0,0,0}), bbbottom({0,0,0}) { FILE *f = fopen(filename.c_str(), "r"); int verts, faces; fscanf(f, "# %d %d\n", &verts, &faces); for (int i = 0; i < verts; ++i) { float x,y,z; fscanf(f, "v %f %f %f\n", &x, &y, &z); x += off.x; y += off.y; z += off.z; if (i == 0 || x > bbtop.x) { bbtop.x = x; } if (i == 0 || y > bbtop.y) { bbtop.y = y; } if (i == 0 || z > bbtop.z) { bbtop.z = z; } if (i == 0 || x < bbbottom.x) { bbbottom.x = x; } if (i == 0 || y < bbbottom.y) { bbbottom.y = y; } if (i == 0 || z < bbbottom.z) { bbbottom.z = z; } _vertices.push_back({x,y,z}); } for (int i = 0; i < faces; ++i) { int x,y,z; fscanf(f, "f %d %d %d\n", &x, &y, &z); x--; y--; z--; //Based on https://www.opengl.org/wiki/Calculating_a_Surface_Normal Vector norm; Vector v1 = _vertices[x]; Vector v2 = _vertices[y]; Vector v3 = _vertices[z]; Vector u = v2 - v3; Vector v = v1 - v3; norm = normalize(cross(v,u)); _faces.push_back({x,y,z, norm}); } fclose(f); mat_ambient[0] = 0.7; mat_ambient[1] = 0.7; mat_ambient[2] = 0.7; mat_diffuse[0] = 0; mat_diffuse[1] = 0; mat_diffuse[2] = 1; mat_specular[0] = 1; mat_specular[1] = 1; mat_specular[2] = 1; mat_shineness = 30; reflectance = 0.5; transparency = 0.5; }
void LLDrawPoolTree::renderTree(BOOL selecting) { LLGLState normalize(GL_NORMALIZE, TRUE); // Bind the texture for this tree. LLViewerImage::bindTexture(mTexturep,sDiffTex); if (mTexturep) { if (mTexturep->getClampS()) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); } if (mTexturep->getClampT()) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } } U32 indices_drawn = 0; glMatrixMode(GL_MODELVIEW); for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace *face = *iter; LLDrawable *drawablep = face->getDrawable(); if (drawablep->isDead() || face->mVertexBuffer.isNull()) { continue; } face->mVertexBuffer->setBuffer(LLDrawPoolTree::VERTEX_DATA_MASK); U32* indicesp = (U32*) face->mVertexBuffer->getIndicesPointer(); // Render each of the trees LLVOTree *treep = (LLVOTree *)drawablep->getVObj().get(); LLColor4U color(255,255,255,255); if (!selecting || treep->mGLName != 0) { if (selecting) { S32 name = treep->mGLName; color = LLColor4U((U8)(name >> 16), (U8)(name >> 8), (U8)name, 255); } glPushMatrix(); // Translate to tree base HACK - adjustment in Z plants tree underground const LLVector3 &pos_agent = treep->getPositionAgent(); glTranslatef(pos_agent.mV[VX], pos_agent.mV[VY], pos_agent.mV[VZ] - 0.1f); // Rotate to tree position F32 angle_radians, x, y, z; treep->getRotation().getAngleAxis(&angle_radians, &x, &y, &z); glRotatef(angle_radians * RAD_TO_DEG, x, y, z); // Rotate and bend for current trunk/wind // Note that trunk stiffness controls the amount of bend at the trunk as // opposed to the crown of the tree // glRotatef(90.f, 0, 0, 1); const F32 TRUNK_STIFF = 22.f; glRotatef(treep->mTrunkBend.magVec()*TRUNK_STIFF, treep->mTrunkBend.mV[VX], treep->mTrunkBend.mV[VY], 0); F32 radius = treep->getScale().magVec()*0.5f; radius *= 0.1f; glScalef(radius, radius, radius); const F32 THRESH_ANGLE_FOR_BILLBOARD = 15.f; const F32 BLEND_RANGE_FOR_BILLBOARD = 3.f; F32 droop = treep->mDroop + 25.f*(1.f - treep->mTrunkBend.magVec()); S32 stop_depth = 0; F32 app_angle = treep->getAppAngle()*LLVOTree::sTreeFactor; F32 alpha = 1.0; S32 trunk_LOD = 0; for (S32 j = 0; j < 4; j++) { if (app_angle > LLVOTree::sLODAngles[j]) { trunk_LOD = j; break; } } if (app_angle < (THRESH_ANGLE_FOR_BILLBOARD - BLEND_RANGE_FOR_BILLBOARD)) { // // Draw only the billboard // // Only the billboard, can use closer to normal alpha func. stop_depth = -1; LLFacePool::LLOverrideFaceColor clr(this, color); indices_drawn += treep->drawBranchPipeline(indicesp, trunk_LOD, stop_depth, treep->mDepth, treep->mTrunkDepth, 1.0, treep->mTwist, droop, treep->mBranches, alpha); } else // if (app_angle > (THRESH_ANGLE_FOR_BILLBOARD + BLEND_RANGE_FOR_BILLBOARD)) { // // Draw only the full geometry tree // //stop_depth = (app_angle < THRESH_ANGLE_FOR_RECURSION_REDUCTION); LLFacePool::LLOverrideFaceColor clr(this, color); indices_drawn += treep->drawBranchPipeline(indicesp, trunk_LOD, stop_depth, treep->mDepth, treep->mTrunkDepth, 1.0, treep->mTwist, droop, treep->mBranches, alpha); } glPopMatrix(); } } if (mTexturep) { if (mTexturep->getClampS()) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); } if (mTexturep->getClampT()) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } } addIndicesDrawn(indices_drawn); }
LineRenderable::LineRenderable(const LineSymbol* symbol, const VirtualPath& virtual_path, bool closed) : Renderable(symbol->getColor()) , line_width(0.001f * symbol->getLineWidth()) { Q_ASSERT(virtual_path.size() >= 2); float half_line_width = (color_priority < 0) ? 0.0f : 0.5f * line_width; switch (symbol->getCapStyle()) { case LineSymbol::FlatCap: cap_style = Qt::FlatCap; break; case LineSymbol::RoundCap: cap_style = Qt::RoundCap; break; case LineSymbol::SquareCap: cap_style = Qt::SquareCap; break; case LineSymbol::PointedCap: cap_style = Qt::FlatCap; break; } switch (symbol->getJoinStyle()) { case LineSymbol::BevelJoin: join_style = Qt::BevelJoin; break; case LineSymbol::MiterJoin: join_style = Qt::MiterJoin; break; case LineSymbol::RoundJoin: join_style = Qt::RoundJoin; break; } auto& flags = virtual_path.coords.flags; auto& coords = virtual_path.coords; bool has_curve = false; bool hole = false; bool gap = false; QPainterPath first_subpath; auto i = virtual_path.first_index; path.moveTo(coords[i]); extent = QRectF(coords[i].x(), coords[i].y(), 0.0001f, 0.0001f); extentIncludeCap(i, half_line_width, false, symbol, virtual_path); for (++i; i <= virtual_path.last_index; ++i) { if (gap) { if (flags[i].isHolePoint()) { gap = false; hole = true; } else if (flags[i].isGapPoint()) { gap = false; if (first_subpath.isEmpty() && closed) { first_subpath = path; path = QPainterPath(); } path.moveTo(coords[i]); extentIncludeCap(i, half_line_width, false, symbol, virtual_path); } continue; } if (hole) { Q_ASSERT(!flags[i].isHolePoint() && "Two hole points in a row!"); if (first_subpath.isEmpty() && closed) { first_subpath = path; path = QPainterPath(); } path.moveTo(coords[i]); extentIncludeCap(i, half_line_width, false, symbol, virtual_path); hole = false; continue; } if (flags[i-1].isCurveStart()) { Q_ASSERT(i < virtual_path.last_index-1); has_curve = true; path.cubicTo(coords[i], coords[i+1], coords[i+2]); i += 2; } else path.lineTo(coords[i]); if (flags[i].isHolePoint()) hole = true; else if (flags[i].isGapPoint()) gap = true; if ((i < virtual_path.last_index && !hole && !gap) || (i == virtual_path.last_index && closed)) extentIncludeJoin(i, half_line_width, symbol, virtual_path); else extentIncludeCap(i, half_line_width, true, symbol, virtual_path); } if (closed) { if (first_subpath.isEmpty()) path.closeSubpath(); else path.connectPath(first_subpath); } // If we do not have the path coords, but there was a curve, calculate path coords. if (has_curve) { // This happens for point symbols with curved lines in them. const auto& path_coords = virtual_path.path_coords; Q_ASSERT(path_coords.front().param == 0.0); Q_ASSERT(path_coords.back().param == 0.0); for (auto i = path_coords.size()-1; i > 0; --i) { if (path_coords[i].param != 0.0) { const auto& pos = path_coords[i].pos; auto to_coord = pos - path_coords[i-1].pos; auto to_next = path_coords[i+1].pos - pos; to_coord.normalize(); to_next.normalize(); auto right = (to_coord + to_next).perpRight(); right.setLength(half_line_width); rectInclude(extent, pos + right); rectInclude(extent, pos - right); } } } Q_ASSERT(extent.right() < 999999); // assert if bogus values are returned }
void Rectangle::Subdivide(float patchSize) { if (mPatches == nullptr) { mPatches = new std::vector< Patch* >(); // Calculate the number of patches along one axis float distance_i = _a.DistanceTo(_b); float dimension_i = distance_i / patchSize; int size_i = int(dimension_i); float remainder_i = dimension_i - size_i; if (remainder_i > 0) { ++size_i; } // Calculate the number of patches along the other axis float distance_j = _a.DistanceTo(_d); float dimension_j = distance_j / patchSize; int size_j = int(dimension_j); float remainder_j = dimension_j - size_j; if (remainder_j > 0) { ++size_j; } // Create a two-dimensional vector to hold points std::vector< std::vector<Point*> > points(size_i + 1, std::vector<Point*>(size_j + 1, (Point*)nullptr)); Vector AB(_b, _a); Vector AD(_d, _a); float len_AB = _b.DistanceTo(_a); float len_AD = _d.DistanceTo(_a); normalize(AB); normalize(AD); Point *p1; // Create the starting point p1 = new Point(_a); // Loop in AD direction for (int j = 0; j <= size_j; ++j) { // add p1 to the list points.at(0).at(j) = p1; Point *p2 = p1; // Loop in AB direction for (int i = 0; i < size_i; ++i) { Point *p3; // Check boundary if (i == size_i - 1) { p3 = new Point(scalarMultiply(AB, len_AB).Translate(*p1)); } else { p3 = new Point(scalarMultiply(AB, patchSize).Translate(*p2)); } // add p3 to the list points.at(i+1).at(j) = p3; // Update p2 p2 = p3; } // Update p1 if (j == size_j - 1) { p1 = new Point(scalarMultiply(AD, len_AD).Translate(_a)); } else { p1 = new Point(scalarMultiply(AD, patchSize).Translate(*p1)); } } // Create the patches // Loop in AD direction for (int j = 0; j < size_j; ++j) { // Loop in AB direction for (int i = 0; i < size_i; ++i) { Point *A = points.at(i).at(j); Point *B = points.at(i+1).at(j); Point *C = points.at(i+1).at(j+1); Point *D = points.at(i).at(j+1); // Create the patch Patch *p = new Patch(A, B, C, D, GetColor(), emission); mPatches->push_back(p); } } } }
static inline int LL98 (double psi[], const int two_nmin, const int two_nmax, void *params, double (*X) (const double, const void *), double (*Y) (const double, const void *), double (*Z) (const double, const void *), void (*normalize) (double *, const double, const int, const void *)) /* This is the generic LL98 recurssion strategy common to the 3j and 6j calculations. */ { int nmax_idx = (two_nmax - two_nmin) / 2; int ndim = nmax_idx + 1, nminus_idx = 0, nplus_idx = nmax_idx, i; bool iter_up = true, iter_down = true; double y; double nmin = two_nmin / 2.0, nmax = two_nmax / 2.0; double rs[ndim]; if (ndim == 1) /* Only a single value is possible, requires special handling. */ { psi[0] = 1.0; normalize (psi, nmin, nmax_idx, params); return __SUCCESS; } /* Iterate LL98 Eq. 3 from nmin upwards unless the first term is undefined. */ y = Y (nmin, params); if (fabs (y) > __SMALL) { rs[0] = -X (nmin, params) / y; for (i = 1; i <= nmax_idx; i++) { double n, denom; if (rs[i - 1] > 1.0) { nminus_idx = i - 1; break; } n = nmin + i; denom = Y (n, params) + Z (n, params) * rs[i - 1]; if (fabs (denom) > __SMALL) rs[i] = -X (n, params) / denom; else { nminus_idx = i - 1; break; } } /* Generate psi(n_minus-k)/psi(n_minus) == Psi_minus(n) using LL98 Eq. 5'. */ if (nminus_idx > 0) { psi[nminus_idx - 1] = rs[nminus_idx - 1]; for (i = nminus_idx - 2; i >= 0; i--) psi[i] = psi[i + 1] * rs[i]; } } else { /* If Y is zero there are two possibilities: a) X != 0. In this case, first term s(nmin) is infinity because psi(nmin + 1) = 0. However, psi(nmin) is not nescessarily 0 in this case though. This implies we're actually in the classically allowed region at nmin, and so we can later use the 3 term recursion to iterate up from nmin. b) X = 0. In this case the first term is undefined, and we're unable to iterate upwards from nmin using either the 2 or 3 term recursions. */ nminus_idx = 0; if (fabs (X (nmin, params)) < __SMALL) iter_up = false; } /* Iterate LL98 Eq. 2 from nmax downwards, unless the first term is undefined. */ y = Y (nmax, params); if (fabs (y) > __SMALL) { rs[nmax_idx] = -Z (nmax, params) / y; for (i = nmax_idx - 1; i > nminus_idx; i--) { double n, denom; if (rs[i + 1] > 1.0) { nplus_idx = i + 1; break; } n = nmin + i; denom = Y (n, params) + X (n, params) * rs[i + 1]; if (fabs (denom) > __SMALL) rs[i] = -Z (n, params) / denom; else { nplus_idx = i + 1; break; } } /* Generate psi(n_plus+k)/psi(n_plus) == Psi_plus(n) using LL98 Eq. 4'. */ if (nplus_idx < nmax_idx) { psi[nplus_idx + 1] = rs[nplus_idx + 1]; for (i = nplus_idx + 2; i <= nmax_idx; i++) psi[i] = psi[i - 1] * rs[i]; } } else { /* If Y is zero there are two possibilities: a) Z != 0. In this case, first term r(nmax) is infinity because psi(nmax - 1) = 0. However, psi(nmax) is not nescessarily 0 in this case though. This implies we're actually in the classically allowed region at nmax, and so we can later use the 3 term recursion to iterate up from nmin. b) Z = 0. In this case the first term is undefined, and we're unable to iterate upwards from nmin using either the 2 or 3 term recursions. */ nplus_idx = nmax_idx; if (fabs (Z (nmax, params)) < __SMALL) iter_down = false; } /* Iterate in the classical region using three term recursion LL98 Eq. 1. */ if (iter_up) /* Iterate upwards from nminus, chosing nc = nplus. */ { double a; int iter_up_start_idx; /* Note that this initialization stuff can't be done inside the logic of iterating LL98 Eq. 3 above, since it can potentially be clobbered during the subsequent iteration of LL98 Eq. 4 if that section was also to contain initialization logic for iterating downwards in the classical region below. Really, tempting though it is, don't move this earlier. */ if (nminus_idx < 2) { psi[0] = 1.0; psi[1] = -Y (nmin, params) / X (nmin, params); /* Since psi(nmin - 1) = 0 */ iter_up_start_idx = 2; } else { psi[nminus_idx] = 1.0; iter_up_start_idx = nminus_idx + 1; } for (i = iter_up_start_idx; i <= nplus_idx; i++) { double nn = nmin - 1.0 + i; /* n - 1 */ psi[i] = -(Y (nn, params) * psi[i - 1] + Z (nn, params) * psi[i - 2]) / X (nn, params); } /* Since we choose nc=nplus, Psi_plus(nc)=1, and we multiply Psi_minus(nmin...nplus) by Psi_plus(nc)/Psi_minus(nc) == 1/Psi_minus(n_plus) to give us Psi_plus(nmin...nplus). */ a = 1.0 / psi[nplus_idx]; for (i = 0; i <= nplus_idx; i++) psi[i] *= a; normalize (psi, nmin, nmax_idx, params); return __SUCCESS; } if (iter_down) /* Iterate downwards from nplus, chosing nc = nminus. */ { double a; int iter_down_start_idx; /* Note that this initialization stuff could be done inside the logic of iterating LL98 Eq. 2 above. However following that design leads to some rather obscure corner cases and errors, so it's cleaner to do it here. Really, don't move it. */ if (nplus_idx > nmax_idx - 2) { psi[nplus_idx] = 1.0; psi[nplus_idx - 1] = -Y (nmax, params) / Z (nmax, params); iter_down_start_idx = nplus_idx - 2; } else { psi[nplus_idx] = 1.0; iter_down_start_idx = nplus_idx - 1; } for (i = iter_down_start_idx; i >= nminus_idx; i--) { double nn = nmin + 1.0 + i; /* n + 1 */ psi[i] = -(X (nn, params) * psi[i + 2] + Y (nn, params) * psi[i + 1]) / Z (nn, params); } /* Since we choose nc=nminus, Psi_minus(nc)=1, and we multiply Psi_plus(nminus...nmax) by Psi_minus(nc)/Psi_plus(nc) == 1/Psi_plus(n_plus) to give us Psi_minus(nminus...nmax). */ a = 1.0 / psi[nminus_idx]; for (i = nmax_idx; i >= nminus_idx; i--) psi[i] *= a; normalize (psi, nmin, nmax_idx, params); return __SUCCESS; } fprintf (stderr, "LL98: Could not iterate in either direction\n"); return __FAILURE; }
Distance3f distance_trianglef(const float3 p, const float3* poly) { const float3 normal = normalize(cross(poly[1]-poly[0], poly[2]-poly[0])); // Degenerate triangle if (normal.x != normal.x) { // Hack to safely fail if triangle is degenerate float max_d = length2(poly[1]-poly[0]); float3 a = poly[1]; float3 b = poly[0]; if (length2(poly[2]-poly[1]) > max_d) { max_d = length2(poly[2]-poly[1]); a = poly[2]; b = poly[1]; } if (length2(poly[2]-poly[0]) > max_d) { // No need to reset max_d a = poly[2]; b = poly[0]; } return distance_line3(p, a, b); } const float proj_dist = dot((p - poly[0]), normal); const float3 proj_pnt = p - (normal * proj_dist); float dist = fabs(proj_dist); int drop_dim = 0; float drop_dim_val = fabs(normal.x); if (fabs(normal.y) > drop_dim_val) { drop_dim = 1; drop_dim_val = fabs(normal.y); } if (fabs(normal.z) > drop_dim_val) { drop_dim = 2; drop_dim_val = fabs(normal.z); } float2 poly_proj[3]; float2 proj_proj_pnt; #ifdef OPEN_CL for (int i = 0; i < 3; ++i) { if (drop_dim == 0) { poly_proj[i] = poly[i].yz; } else if (drop_dim == 1) { poly_proj[i] = poly[i].xz; } else { poly_proj[i] = poly[i].xy; } } if (drop_dim == 0) { proj_proj_pnt = proj_pnt.yz; } else if (drop_dim == 1) { proj_proj_pnt = proj_pnt.xz; } else { proj_proj_pnt = proj_pnt.xy; } #else for (int i = 0; i < 3; ++i) { if (drop_dim == 0) { poly_proj[i] = make_float2(poly[i].y, poly[i].z); } else if (drop_dim == 1) { poly_proj[i] = make_float2(poly[i].x, poly[i].z); } else { poly_proj[i] = make_float2(poly[i].x, poly[i].y); } } if (drop_dim == 0) { proj_proj_pnt = make_float2(proj_pnt.y, proj_pnt.z); } else if (drop_dim == 1) { proj_proj_pnt = make_float2(proj_pnt.x, proj_pnt.z); } else { proj_proj_pnt = make_float2(proj_pnt.x, proj_pnt.y); } #endif float2 poly_shift[3]; for (int i = 0; i < 3; ++i) { poly_shift[i] = poly_proj[i] - proj_proj_pnt; } bool test_val; bool first_time = true; bool inside = true; for (int i = 0; i < 3; ++i) { float2 v = poly_shift[i]; float2 vn = poly_shift[(i+1) % 3]; float area = vn.x*v.y - v.x*vn.y; // actually is twice area if (first_time) { test_val = area > 0; first_time = false; } else { if (test_val != area > 0) { inside = false; break; } } } if (inside) { // nan! /* assert(dist == dist); */ // dist is set at start of function to be proj distance Distance3f d = { dist, proj_pnt }; return d; } else { bool unset = true; Distance3f best; for (int i = 0; i < 3; ++i) { if (unset) { best = distance_line3(p, poly[i], poly[(i+1)%3]); unset = false; } else { Distance3f dist = distance_line3(p, poly[i], poly[(i+1)%3]); best = min_pair3f(best, dist); } } // nan! /* assert(best.d == best.d) { */ return best; } }
static unsigned int ray_color(const point3 e, double t, const point3 d, idx_stack *stk, const rectangular_node rectangulars, const sphere_node spheres, const light_node lights, color object_color, int bounces_left) { rectangular_node hit_rec = NULL, light_hit_rec = NULL; sphere_node hit_sphere = NULL, light_hit_sphere = NULL; double diffuse, specular; point3 l, _l, r, rr; object_fill fill; color reflection_part; color refraction_part; /* might be a reflection ray, so check how many times we've bounced */ if (bounces_left == 0) { SET_COLOR(object_color, 0.0, 0.0, 0.0); return 0; } /* check for intersection with a sphere or a rectangular */ intersection ip= ray_hit_object(e, d, t, MAX_DISTANCE, rectangulars, &hit_rec, spheres, &hit_sphere); if (!hit_rec && !hit_sphere) return 0; /* pick the fill of the object that was hit */ fill = hit_rec ? hit_rec->element.rectangular_fill : hit_sphere->element.sphere_fill; void *hit_obj = hit_rec ? (void *) hit_rec : (void *) hit_sphere; /* assume it is a shadow */ SET_COLOR(object_color, 0.0, 0.0, 0.0); for (light_node light = lights; light; light = light->next) { /* calculate the intersection vector pointing at the light */ subtract_vector(ip.point, light->element.position, l); multiply_vector(l, -1, _l); normalize(_l); /* check for intersection with an object. use ignore_me * because we don't care about this normal */ ray_hit_object(ip.point, _l, MIN_DISTANCE, length(l), rectangulars, &light_hit_rec, spheres, &light_hit_sphere); /* the light was not block by itself(lit object) */ if (light_hit_rec || light_hit_sphere) continue; compute_specular_diffuse(&diffuse, &specular, d, l, ip.normal, fill.phong_power); localColor(object_color, light->element.light_color, diffuse, specular, &fill); } reflection(r, d, ip.normal); double idx = idx_stack_top(stk).idx, idx_pass = fill.index_of_refraction; if (idx_stack_top(stk).obj == hit_obj) { idx_stack_pop(stk); idx_pass = idx_stack_top(stk).idx; } else { idx_stack_element e = { .obj = hit_obj, .idx = fill.index_of_refraction }; idx_stack_push(stk, e); } refraction(rr, d, ip.normal, idx, idx_pass); double R = (fill.T > 0.1) ? fresnel(d, rr, ip.normal, idx, idx_pass) : 1.0; /* totalColor = localColor + mix((1-fill.Kd) * fill.R * reflection, T * refraction, R) */ if (fill.R > 0) { /* if we hit something, add the color */ int old_top = stk->top; if (ray_color(ip.point, MIN_DISTANCE, r, stk, rectangulars, spheres, lights, reflection_part, bounces_left - 1)) { multiply_vector(reflection_part, R * (1.0 - fill.Kd) * fill.R, reflection_part); add_vector(object_color, reflection_part, object_color); } stk->top = old_top; } /* calculate refraction ray */ if ((length(rr) > 0.0) && (fill.T > 0.0) && (fill.index_of_refraction > 0.0)) { normalize(rr); if (ray_color(ip.point, MIN_DISTANCE, rr, stk,rectangulars, spheres, lights, refraction_part, bounces_left - 1)) { multiply_vector(refraction_part, (1 - R) * fill.T, refraction_part); add_vector(object_color, refraction_part, object_color); } } protect_color_overflow(object_color); return 1; } /* @param background_color this is not ambient light */ static void *parallel (void* para) { Threadinside *inside = (Threadinside *)para; point3 d; idx_stack stk; color object_color = { 0.0, 0.0, 0.0 }; for (int j = inside->h1; j < inside->h2; j++) { for (int i = 0; i < inside->p->width; i++) { double r = 0, g = 0, b = 0; /* MSAA */ for (int s = 0; s < SAMPLES; s++) { idx_stack_init(&stk); rayConstruction(d, inside->p->u, inside->p->v, inside->p->w, i * inside->p->factor + s / inside->p->factor, j * inside->p->factor + s % inside->p->factor, inside->p->view, inside->p->width * inside->p->factor, inside->p->height * inside->p->factor); if (ray_color(inside->p->view->vrp, 0.0, d, &(stk), inside->p->rectangulars, inside->p->spheres, inside->p->lights, object_color, MAX_REFLECTION_BOUNCES)) { r += object_color[0]; g += object_color[1]; b += object_color[2]; } else { r += inside->p->background_color[0]; g += inside->p->background_color[1]; b += inside->p->background_color[2]; } inside->p->pixels[((i + (j * inside->p->width)) * 3) + 0] = r * 255 / SAMPLES; inside->p->pixels[((i + (j * inside->p->width)) * 3) + 1] = g * 255 / SAMPLES; inside->p->pixels[((i + (j * inside->p->width)) * 3) + 2] = b * 255 / SAMPLES; } } } return NULL; }
static void callBack_rescaleGrayLevelMat(int, void*) { std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl; rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)(histogramClippingValue/100.0)); normalize(imageInputRescaled, imageInputRescaled, 0.0, 255.0, cv::NORM_MINMAX); }
float3 DiTracer::GetDi(World const& world, Light const& light, Sampler const& lightsampler, Sampler const& bsdfsampler, float3 const& wo, ShapeBundle::Hit& hit) const { float3 radiance; // TODO: fix that later with correct heuristic assert(lightsampler.num_samples() == bsdfsampler.num_samples()); // Sample light source first to apply MIS later { // Direction from the shading point to the light float3 lightdir; // PDF for BSDF sample float bsdfpdf = 0.f; // PDF for light sample float lightpdf = 0.f; // Sample numsamples times int numsamples = lightsampler.num_samples(); // Allocate samples std::vector<float2> lightsamples(numsamples); std::vector<float2> bsdfsamples(numsamples); // Generate samples for (int i = 0; i < numsamples; ++i) { lightsamples[i] = lightsampler.Sample2D(); bsdfsamples[i] = bsdfsampler.Sample2D(); } // Cache singularity flag to avoid virtual call in the loop below bool singularlight = light.Singular(); // Fetch the material Material const& mat = *world.materials_[hit.m]; // Start sampling for (int i=0; i<numsamples; ++i) { lightpdf = 0.f; bsdfpdf = 0.f; // This is needed to support normal mapping. // Original intersection needs to be kept around since bsdf might alter the normal ShapeBundle::Hit hitlocal = hit; // Sample light source float3 le = light.GetSample(hitlocal, lightsamples[i], lightdir, lightpdf); // Continue if intensity > 0 and there is non-zero probability of sampling the point if (lightpdf > MINPDF && le.sqnorm() > 0.f) { // Normalize direction to light float3 wi = normalize(lightdir); // Calculate distance for shadow testing float dist = sqrtf(lightdir.sqnorm()); // Spawn shadow ray ray shadowray; // From an intersection point shadowray.o = hitlocal.p; // Into evaluated direction shadowray.d = wi; // TODO: move ray epsilon into some global options object shadowray.t = float2(0.01f, dist - 0.01f); // Check for an occlusion float shadow = world.Intersect(shadowray) ? 0.f : 1.f; // If we are not in shadow if (shadow > 0.f) { // Evaluate BSDF float3 bsdf = mat.Evaluate(hitlocal, wi, wo); // We can't apply MIS for singular lights, so use simple estimator if (singularlight) { // Estimate with Monte-Carlo L(wo) = int{ Ld(wi, wo) * fabs(dot(n, wi)) * dwi } radiance += le * bsdf * fabs(dot(hitlocal.n, wi)) * (1.f / lightpdf); assert(!has_nans(radiance)); } else { // Apply MIS bsdfpdf = mat.GetPdf(hitlocal, wi, wo); // Evaluate weight float weight = PowerHeuristic(1, lightpdf, 1, bsdfpdf); // Estimate with Monte-Carlo L(wo) = int{ Ld(wi, wo) * fabs(dot(n, wi)) * dwi } radiance += le * bsdf * fabs(dot(hitlocal.n, wi)) * weight * (1.f / lightpdf); assert(!has_nans(radiance)); } } } // Sample BSDF if the light is not singular if (!singularlight) { int bsdftype = 0; float3 wi; // Sample material float3 bsdf = mat.Sample(hitlocal, bsdfsamples[i], wo, wi, bsdfpdf, bsdftype); //assert(!has_nans(bsdf)); //assert(!has_nans(bsdfpdf < 1000000.f)); // Normalize wi wi = normalize(wi); // If something would be reflected if (bsdf.sqnorm() > 0.f && bsdfpdf > MINPDF) { float weight = 1.f; // Apply MIS if BSDF is not specular if (! (bsdftype & Bsdf::SPECULAR)) { // Evaluate light PDF lightpdf = light.GetPdf(hitlocal, wi); // If light PDF is zero skip to next sample if (lightpdf < MINPDF) { continue; } // Apply heuristic weight = PowerHeuristic(1, bsdfpdf, 1, lightpdf); } // Spawn shadow ray ray shadowray; // From an intersection point shadowray.o = hitlocal.p; // Into evaluated direction shadowray.d = wi; // TODO: move ray epsilon into some global options object shadowray.t = float2(0.01f, 10000000.f); // Cast the ray into the scene ShapeBundle::Hit shadowhit; float3 le(0.f, 0.f, 0.f); // If the ray intersects the scene check if we have intersected this light // TODO: move that to area light class if (world.Intersect(shadowray, shadowhit)) { // Only sample if this is our light if ((Light const*)shadowhit.bundle->GetAreaLight() == &light) { Material const& lightmat = *world.materials_[shadowhit.m]; // Get material emission properties ShapeBundle::Sample sampledata(shadowhit); float3 d = sampledata.p - hitlocal.p; // If the object facing the light compute emission if (dot(sampledata.n, -wi) > 0.f) { // Emissive power with squared fallof float d2inv = 1.f / d.sqnorm(); // Return emission characteristic of the material le = lightmat.GetLe(sampledata, -wi) * d2inv; } } } else { // This is to give a chance for IBL to contribute le = light.GetLe(shadowray); } if (le.sqnorm() > 0.f) { // Estimate with Monte-Carlo L(wo) = int{ Ld(wi, wo) * fabs(dot(n, wi)) * dwi } radiance += le * bsdf * fabs(dot(hitlocal.n, wi)) * weight * (1.f / bsdfpdf); //assert(!has_nans(radiance)); } } } } return (1.f / numsamples) * radiance; } }
/* * objective : get the gray level map of the input image and rescale it to the range [0-255] */ static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit) { // adjust output matrix wrt the input size but single channel std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl; //std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl; //std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl; // rescale between 0-255, keeping floating point values cv::normalize(inputMat, outputMat, 0.0, 255.0, cv::NORM_MINMAX); // extract a 8bit image that will be used for histogram edge cut cv::Mat intGrayImage; if (inputMat.channels()==1) { outputMat.convertTo(intGrayImage, CV_8U); }else { cv::Mat rgbIntImg; outputMat.convertTo(rgbIntImg, CV_8UC3); cv::cvtColor(rgbIntImg, intGrayImage, cv::COLOR_BGR2GRAY); } // get histogram density probability in order to cut values under above edges limits (here 5-95%)... usefull for HDR pixel errors cancellation cv::Mat dst, hist; int histSize = 256; calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0); cv::Mat normalizedHist; normalize(hist, normalizedHist, 1, 0, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1 double min_val, max_val; minMaxLoc(normalizedHist, &min_val, &max_val); //std::cout<<"Hist max,min = "<<max_val<<", "<<min_val<<std::endl; // compute density probability cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F); denseProb.at<float>(0)=normalizedHist.at<float>(0); int histLowerLimit=0, histUpperLimit=0; for (int i=1;i<normalizedHist.size().height;++i) { denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i); //std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl; if ( denseProb.at<float>(i)<histogramClippingLimit) histLowerLimit=i; if ( denseProb.at<float>(i)<1-histogramClippingLimit) histUpperLimit=i; } // deduce min and max admitted gray levels float minInputValue = (float)histLowerLimit/histSize*255; float maxInputValue = (float)histUpperLimit/histSize*255; std::cout<<"=> Histogram limits " <<"\n\t"<<histogramClippingLimit*100<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue <<"\n\t"<<(1-histogramClippingLimit)*100<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue <<std::endl; //drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit); drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit); // rescale image range [minInputValue-maxInputValue] to [0-255] outputMat-=minInputValue; outputMat*=255.0/(maxInputValue-minInputValue); // cut original histogram and back project to original image cv::threshold( outputMat, outputMat, 255.0, 255.0, 2 ); //THRESH_TRUNC, clips values above 255 cv::threshold( outputMat, outputMat, 0.0, 0.0, 3 ); //THRESH_TOZERO, clips values under 0 }
void CEmoticon::OnRender() { if(!m_Active) { if(m_WasActive) { if (m_SelectedEmote != -1) Emote(m_SelectedEmote); else if (Client()->IsServerType("ddrace") && m_SelectedEyes != -1) Eyes(m_SelectedEyes); } m_WasActive = false; return; } if(m_pClient->m_Snap.m_SpecInfo.m_Active) { m_Active = false; m_WasActive = false; return; } m_WasActive = true; if (length(m_SelectorMouse) > 170.0f) m_SelectorMouse = normalize(m_SelectorMouse) * 170.0f; float SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24; if (SelectedAngle < 0) SelectedAngle += 2*pi; float mouselen = length(m_SelectorMouse); if (mouselen > 110.0f) { m_SelectedEyes = -1; m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS); } else if (Client()->IsServerType("ddrace") && mouselen > 50.0f && mouselen < 110.0f) // H-Client { m_SelectedEmote = -1; m_SelectedEyes = (int)(SelectedAngle / (2*pi) * NUM_EMOTES); } else { m_SelectedEyes = -1; m_SelectedEmote = -1; } CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); Graphics()->BlendNormal(); Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.3f); DrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64); Graphics()->QuadsEnd(); // H-Client if (Client()->IsServerType("ddrace")) { Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->SetColor(60,60,60,0.3f); DrawCircle(Screen.w/2, Screen.h/2, 110.0f, 64); Graphics()->QuadsEnd(); } // Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); for (int i = 0; i < NUM_EMOTICONS; i++) { float Angle = 2*pi*i/NUM_EMOTICONS; if (Angle > pi) Angle -= 2*pi; bool Selected = m_SelectedEmote == i; float Size = Selected ? 80.0f : 50.0f; float NudgeX = 150.0f * cosf(Angle); float NudgeY = 150.0f * sinf(Angle); RenderTools()->SelectSprite(SPRITE_OOP + i); IGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size); Graphics()->QuadsDraw(&QuadItem, 1); } Graphics()->QuadsEnd(); if (Client()->IsServerType("ddrace")) { for (int i = 0; i < NUM_EMOTES; i++) { float Angle = 2*pi*i/NUM_EMOTES; if (Angle > pi) Angle -= 2*pi; bool Selected = m_SelectedEyes == i; float Size = Selected ? 80.0f : 50.0f; float NudgeX = 80.0f * cosf(Angle); float NudgeY = 80.0f * sinf(Angle); CTeeRenderInfo teeRenderInfo = m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_RenderInfo; teeRenderInfo.m_Size = Size; Graphics()->TextureSet(teeRenderInfo.m_Texture); Graphics()->QuadsBegin(); Graphics()->SetColor(teeRenderInfo.m_ColorBody.r, teeRenderInfo.m_ColorBody.g, teeRenderInfo.m_ColorBody.b, teeRenderInfo.m_ColorBody.a); switch (i) { case EMOTE_PAIN: RenderTools()->SelectSprite(SPRITE_TEE_EYE_PAIN, 0, 0, 0); break; case EMOTE_HAPPY: RenderTools()->SelectSprite(SPRITE_TEE_EYE_HAPPY, 0, 0, 0); break; case EMOTE_SURPRISE: RenderTools()->SelectSprite(SPRITE_TEE_EYE_SURPRISE, 0, 0, 0); break; case EMOTE_ANGRY: RenderTools()->SelectSprite(SPRITE_TEE_EYE_ANGRY, 0, 0, 0); break; default: RenderTools()->SelectSprite(SPRITE_TEE_EYE_NORMAL, 0, 0, 0); break; } vec2 Direction = vec2(-1,0); float BaseSize = teeRenderInfo.m_Size; float EyeScale = BaseSize*0.40f; float h = i == EMOTE_BLINK ? BaseSize*0.15f : EyeScale; float EyeSeparation = (0.075f - 0.010f*absolute(Direction.x))*BaseSize; vec2 Offset = vec2(Direction.x*0.125f, -0.05f+Direction.y*0.10f)*BaseSize; vec2 BodyPos = vec2(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY); IGraphics::CQuadItem Array[2] = { IGraphics::CQuadItem(BodyPos.x-EyeSeparation+Offset.x, BodyPos.y+Offset.y, EyeScale, h), IGraphics::CQuadItem(BodyPos.x+EyeSeparation+Offset.x, BodyPos.y+Offset.y, -EyeScale, h)}; Graphics()->QuadsDraw(Array, 2); Graphics()->QuadsEnd(); } } //Graphics()->QuadsEnd(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Screen.w/2,m_SelectorMouse.y+Screen.h/2,24,24); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); }
void main(void)\n\ { \n\ float fTime0_X = parameters[0][0];\n\ vec4 coreSeed = parameters[1];\n\ \n\ vec3 rayDir = normalize(objectPosition * vec3(1.0, 0.6, 1.0));\n\ vec3 camPos = vec3(0.0, 0.0, -parameters[0][1]);\n\ \n\ // rotate camera around y axis\n\ float alpha = parameters[0][2] * 4.5f;\n\ camPos.xz = vec2(cos(alpha)*camPos.x - sin(alpha)*camPos.z,\n\ sin(alpha)*camPos.x + cos(alpha)*camPos.z);\n\ rayDir.xz = vec2(cos(alpha)*rayDir.x - sin(alpha)*rayDir.z,\n\ sin(alpha)*rayDir.x + cos(alpha)*rayDir.z);\n\ \n\ vec3 rayPos = camPos;\n\ float sceneSize = 8.0;\n\ vec3 totalColor = vec3(0.);\n\ float stepSize;\n\ float totalDensity = 0.0;\n\ float stepDepth = 0.0; // how far I went already.\n\ \n\ for(int step = 0; length(rayPos)<sceneSize && totalDensity < 0.9 && step < 50; step++)\n\ { \n\ float implicitVal;\n\ \n\ // This stuff is the transformation information from previous stuff\n\ float transer = parameters[0][3];\n\ vec4 prevQuaternion = vec4(cos(transer), sin(transer), sin(transer * 1.3), sin(transer * 2.7));\n\ prevQuaternion = normalize(prevQuaternion);\n\ float prevLength = 1.0;\n\ vec3 prevMover = vec3(0.0);\n\ vec3 prevColor = vec3(1.0, 0.4, 0.2);\n\ \n\ // Multiple boxes\n\ implicitVal = 1.0e10;\n\ \n\ for (int loop = 0; loop < 12; loop++)\n\ {\n\ vec4 newQuaternion;\n\ float newLength;\n\ vec3 newMover;\n\ vec3 newColor;\n\ \n\ mat3 prevRotationMatrix = quaternionToMatrix(prevQuaternion);\n\ \n\ // Loop for solid stuff\n\ vec4 seed = coreSeed;\n\ for (int k = 0; k < 4; k++)\n\ {\n\ seed = randomIteration(seed);\n\ vec4 quaternion = normalize(seed - vec4(0.5));\n\ mat3 rotationMatrix = quaternionToMatrix(quatMult(quaternion, prevQuaternion));\n\ vec3 lengthes = seed.xyz * seed.xyz * seed.xyz * seed.xyz * vec3(0.2) + vec3(0.05);\n\ lengthes *= prevLength;\n\ vec3 mover = 0.5*seed.wzx - vec3(0.25);\n\ mover = (mover * prevRotationMatrix * prevLength) + prevMover;\n\ float curImplicitVal = getDistance(rotationMatrix, lengthes, mover, rayPos);\n\ implicitVal = min(implicitVal, curImplicitVal);\n\ }\n\ \n\ // Non-solid:\n\ float nonSolidDist = 1.0e10;\n\ for (int k = 0; k < 2; k++)\n\ {\n\ seed = randomIteration(seed);\n\ vec4 quaternion = normalize(seed - vec4(0.5));\n\ quaternion = quatMult(quaternion, prevQuaternion);\n\ vec3 lengthes = seed.xyz * vec3(0.3) + vec3(0.25);\n\ lengthes *= prevLength;\n\ vec3 mover = 0.5*seed.wzx - vec3(0.25);\n\ mover = (mover * prevRotationMatrix * prevLength) + prevMover;\n\ float curImplicitVal = getSphereDistance(lengthes.x, mover, rayPos);\n\ if (curImplicitVal < nonSolidDist)\n\ {\n\ nonSolidDist = curImplicitVal;\n\ newQuaternion = quaternion;\n\ newLength = lengthes.x;\n\ newMover = mover;\n\ newColor = seed.xyz;\n\ }\n\ }\n\ \n\ if (nonSolidDist > implicitVal)\n\ {\n\ // I will not get closer than where I am now.\n\ break;\n\ }\n\ else\n\ {\n\ prevQuaternion = newQuaternion;\n\ prevLength = newLength;\n\ prevMover = newMover;\n\ prevColor = 0.5 * prevColor + 0.5 * newColor; \n\ }\n\ }\n\ \n\ // I need to do this distance related to for the DOF! \n\ totalColor += vec3(1./50., 1./70., 1./90.) *\n\ 1.7 / exp(abs(implicitVal*5.) + 0.0) * 1.8;\n\ totalDensity += 1./ 15. / exp(abs(implicitVal*10.0) + 0.5);\n\ // *(1.0 - cos(fTime0_X*3.)*0.5);\n\ //if (implicitVal < 0.0)\n\ stepDepth += abs(implicitVal) * 0.95; \n\ {\n\ // TODO: I could make this distance-related, with offset to get the size right?\n\ float localDensity = implicitVal < 0.0 ? 1.0 : 0.0;\n\ totalColor = totalColor + (1.-totalDensity) * prevColor * localDensity;\n\ totalDensity = totalDensity + (1.05-totalDensity) * localDensity;\n\ }\n\ \n\ stepSize = abs(implicitVal) * 0.99;\n\ stepSize = max(0.005 * stepDepth, stepSize);\n\ rayPos += rayDir * stepSize;\n\ }\n\ \n\ float grad = normalize(rayDir).y;\n\ totalColor += (1.-totalDensity) * (grad * vec3(0.0,-0.4,-0.3) + (1.-grad)*vec3(0.0,0.4,0.6));\n\ \n\ gl_FragColor = vec4(totalColor-vec3(0.0), 1.0);\n\ }\n\
static char* scxnum (const char *str, const struct numfmt* pnf, struct canform* pre, struct canform* pim) { char *ptr, *endrp, *ptr2; struct canform cform1, cform2; size_t slen = strlen (str); cform1.sgn = 0; cform1.ipart = stralloc (slen); cform1.dpart = stralloc (slen); cform1.expn = 0; endrp = ptr = snum (str, pnf, &cform1); #ifdef _SCXNUM_DEBUG_ fprintf (stderr, "%s -->\n sign = \'%c\'\n ip = \"%s\"\n dp = \"%s\"\n expn = %ld, tail = \"%s\n", str, cform1.sgn, cform1.ipart, cform1.dpart, cform1.expn, endrp); #endif if (ptr != str) { normalize (&cform1); #ifdef _SCXNUM_DEBUG_ fprintf (stderr, "After normalization:\n"); fprintf (stderr, "%s -->\n sign = \'%c\'\n ip = \"%s\"\n dp = \"%s\"\n expn = %ld, tail = \"%s\n", str, cform1.sgn, cform1.ipart, cform1.dpart, cform1.expn, endrp); #endif if (*ptr == pnf->iu) { /* We have read a pure imaginary number. */ *pre = null; *pim = cform1; return ptr + 1; } else { /* We have to check if we have read a pure real number or if we can read a full complex number. */ *pre = cform1; while (is_space (*ptr)) ptr++; if (*ptr == POS_SIGN || *ptr == NEG_SIGN) { cform2.sgn = 0; cform2.ipart = stralloc (slen); cform2.dpart = stralloc (slen); cform2.expn = 0; ptr2 = snum (ptr, pnf, &cform2); #ifdef _SCXNUM_DEBUG_ fprintf (stderr, "%s -->\n sign = \'%c\'\n ip = \"%s\"\n dp = \"%s\"\n expn = %ld, tail = \"%s\n", ptr, cform2.sgn, cform2.ipart, cform2.dpart, cform2.expn, ptr2); #endif if (*ptr2 == pnf->iu) { /* We have read a full complex number. */ normalize (&cform2); #ifdef _SCXNUM_DEBUG_ fprintf (stderr, "After normalization:\n"); fprintf (stderr, "%s -->\n sign = \'%c\'\n ip = \"%s\"\n dp = \"%s\"\n expn = %ld, tail = \"%s\n", ptr, cform2.sgn, cform2.ipart, cform2.dpart, cform2.expn, ptr2); #endif *pim = cform2; return ptr2 + 1; } else { /* We have read a pure real number. */ free ((void*) cform2.ipart); free ((void*) cform2.dpart); *pim = null; return endrp; } } else { /* We have read a pure real number. */ *pim = null; return endrp; } } } else { /* We have read no valid number, clean and return. */ free ((void*) cform1.ipart); free ((void*) cform1.dpart); *pre = *pim = null; return ptr; } }
void TimeSigMap::add(int tick, const SigEvent& ev) { (*this)[tick] = ev; normalize(); }
int mpf_a2num (Real* pr, const char *q, char** endptr, const struct numfmt* pnf) { struct canform cform; size_t slen = strlen (q); cform.sgn = 0; cform.ipart = stralloc (slen); cform.dpart = stralloc (slen); cform.expn = 0; *endptr = snum (q, pnf, &cform); if (*endptr != q) { char *ptr, *str; long e; size_t len, explen; #ifdef HAVE_LOCALECONV struct lconv *plconv = localeconv(); char* dec_point = plconv->decimal_point; #else /* not HAVE_LOCALECONV */ char* dec_point = "."; #endif /* not HAVE_LOCALECONV */ if (cform.ipart == NULL || cform.dpart == NULL) { /* The number contained in the string Q is zero */ mpf_set_ui (*pr, 0); return 0; } normalize (&cform); e = cform.expn >= 0 ? cform.expn : -cform.expn; for (len = 0; e != 0; len++, e /= 10); explen = len; if (cform.expn < 0) /* We need space for the minus sign in front of the exponent */ len++; if (cform.sgn == NEG_SIGN) /* We need space for the minus sign in front of the whole number */ len++; /* We need space also for the decimal point and the exponent letter */ len += strlen (cform.ipart) + strlen (cform.dpart) + strlen(dec_point) + 1; ptr = str = stralloc (len); if (cform.sgn == NEG_SIGN) { *ptr = NEG_SIGN; ptr++; } if (*cform.ipart != '\0') { *ptr = *cform.ipart; strcat (str, dec_point); strcat (str, cform.ipart+1); strcat (str, cform.dpart); } else { *ptr = *cform.dpart; strcat (str, dec_point); strcat (str, cform.dpart+1); } if (explen > 0) { for (ptr++; *ptr != '\0'; ptr++); *ptr = ECH; if (cform.expn < 0) { ptr++; *ptr = NEG_SIGN; } ptr += explen; for (e = cform.expn >= 0 ? cform.expn : -cform.expn; e != 0; ptr--, e /= 10) *ptr = CHAR_ZERO + e % 10; } if ( mpf_set_str (*pr, str, 10) == -1 ) { /* This should never happen. If mpf_set_str() returns -1, then */ /* there is something wrong with the code above. */ fprintf (stderr, _("The string \"%s\"\nis not a valid number, the execution of the program ends now\n"), str); free ((void*) cform.ipart); free ((void*) cform.dpart); free ((void*) str); exit (EXIT_TROUBLE); } else { free ((void*) cform.ipart); free ((void*) cform.dpart); free ((void*) str); return 0; } } /* *endptr != q */ else { /* We have read no valid number, then free the previously allocated memory, set the value pointed to by PR to zero and return -1 */ free ((void*) cform.ipart); free ((void*) cform.dpart); mpf_set_ui (*pr, 0); return -1; } /* *endptr == q */ }
void ProjectConfig::setProjectDir(const string &projectDir) { _projectDir = projectDir; normalize(); }
void check_raindrops() { if (random(100) < 50) { create_raindrop(ndrops); } // //move rain droplets Raindrop *node = ihead; while(node) { //force is toward the ground node->vel[1] += gravity; VecCopy(node->pos, node->lastpos); if (node->pos[1] > node->lower_boundry) { node->pos[0] += node->vel[0] * timeslice; node->pos[1] += node->vel[1] * timeslice; } if (fabs(node->vel[1]) > node->maxvel[1]) node->vel[1] *= 0.96; node->vel[0] *= 0.999; // node = node->next; } //} // //check rain droplets int n=0; node = ihead; while(node) { n++; #ifdef USE_SOUND if (node->pos[1] < 0.0f) { //raindrop hit ground if (!node->sound && play_sounds) { //small chance that a sound will play int r = random(50); if (r==1) fmod_playsound(0); //if (r==2) // fmod_playsound(1); //sound plays once per raindrop node->sound=1; } } #endif //USE_SOUND #ifdef USE_UMBRELLA //collision detection for raindrop on umbrella if (show_umbrella) { if (umbrella.shape == UMBRELLA_FLAT) { if (node->pos[0] >= (umbrella.pos[0] - umbrella.width2) && node->pos[0] <= (umbrella.pos[0] + umbrella.width2)) { if (node->lastpos[1] > umbrella.lastpos[1] || node->lastpos[1] > umbrella.pos[1]) { if (node->pos[1] <= umbrella.pos[1] || node->pos[1] <= umbrella.lastpos[1]) { if (node->linewidth > 1) { Raindrop *savenode = node->next; delete_rain(node); node = savenode; continue; } } } } } if (umbrella.shape == UMBRELLA_ROUND) { float d0 = node->pos[0] - umbrella.pos[0]; float d1 = node->pos[1] - umbrella.pos[1]; float distance = sqrt((d0*d0)+(d1*d1)); //Log("distance: %f umbrella.radius: %f\n", // distance,umbrella.radius); if (distance <= umbrella.radius && node->pos[1] > umbrella.pos[1]) { if (node->linewidth > 1) { if (deflection) { //deflect raindrop double dot; Vec v, up = {0,1,0}; VecSub(node->pos, umbrella.pos, v); normalize(v); node->pos[0] = umbrella.pos[0] + v[0] * umbrella.radius; node->pos[1] = umbrella.pos[1] + v[1] * umbrella.radius; dot = VecDot(v,up); dot += 1.0; node->vel[0] += v[0] * dot * 1.0; node->vel[1] += v[1] * dot * 1.0; } else { Raindrop *savenode = node->next; delete_rain(node); node = savenode; continue; } } } } //VecCopy(umbrella.pos, umbrella.lastpos); } #endif //USE_UMBRELLA if (node->pos[1] < -20.0f || node->pos[1] <= node->lower_boundry) { //rain drop is below the visible area Raindrop *savenode = node->next; delete_rain(node); node = savenode; continue; } //if (node->next == NULL) break; node = node->next; } if (maxrain < n) maxrain = n; //} }
void ProjectConfig::setWritablePath(const string &writablePath) { _writablePath = writablePath; normalize(); }
void CameraAnimator::initCameraMoveToLight( dp::sg::core::LightSourceSharedPtr const& targetLight ) { DP_ASSERT( m_viewState->getCamera().isPtrTo<dp::sg::core::FrustumCamera>() ); m_cameraMoveStart = m_viewState->getCamera().clone().staticCast<dp::sg::core::FrustumCamera>(); m_cameraMoveTarget = m_cameraMoveStart.clone(); dp::sg::core::LightSourceSharedPtr lsh( targetLight->getSharedPtr<dp::sg::core::LightSource>() ); { DP_ASSERT( lsh->getLightPipeline() ); dp::sg::core::PipelineDataSharedPtr const& lp = lsh->getLightPipeline(); const dp::fx::EffectSpecSharedPtr & es = lp->getEffectSpec(); for ( dp::fx::EffectSpec::iterator it = es->beginParameterGroupSpecs() ; it != es->endParameterGroupSpecs() ; ++it ) { const dp::sg::core::ParameterGroupDataSharedPtr & parameterGroupData = lp->getParameterGroupData( it ); if ( parameterGroupData ) { std::string name = (*it)->getName(); if ( ( name == "standardDirectedLightParameters" ) || ( name == "standardPointLightParameters" ) || ( name == "standardSpotLightParameters" ) ) { const dp::fx::ParameterGroupSpecSharedPtr & pgs = parameterGroupData->getParameterGroupSpec(); if ( name == "standardDirectedLightParameters" ) { m_cameraMoveTarget->setDirection( parameterGroupData->getParameter<dp::math::Vec3f>( pgs->findParameterSpec( "direction" ) ) ); } else if ( name == "standardPointLightParameters" ) { dp::math::Vec3f position = parameterGroupData->getParameter<dp::math::Vec3f>( pgs->findParameterSpec( "position" ) ); m_cameraMoveTarget->setPosition( position ); // point us in the direction of the scene center.. if ( m_viewState->getScene()->getRootNode() ) { dp::math::Vec3f forward = m_viewState->getScene()->getRootNode()->getBoundingSphere().getCenter() - position; dp::math::Vec3f worldup( 0.f, 1.f, 0.f ); //pc->getUpVector(); dp::math::Vec3f right = forward ^ worldup; dp::math::Vec3f up = right ^ forward; normalize( forward ); normalize( right ); normalize( up ); // X east, Y up, -Z north dp::math::Mat33f lookat( { right[0], right[1], right[2], up[0], up[1], up[2], -forward[0], -forward[1], -forward[2] } ); dp::math::Quatf ori( lookat ); m_cameraMoveTarget->setOrientation( ori ); } } else { m_cameraMoveTarget->setPosition( parameterGroupData->getParameter<dp::math::Vec3f>( pgs->findParameterSpec( "position" ) ) ); m_cameraMoveTarget->setDirection( parameterGroupData->getParameter<dp::math::Vec3f>( pgs->findParameterSpec( "direction" ) ) ); } break; } } } } cameraMoveDurationFactor( determineDurationFactor() ); }