void display(void) { // Buffer clearen glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // View Matrix erstellen glLoadIdentity(); float x = distance * sin(theta) * cos(phi); float y = distance * cos(theta); float z = distance * sin(theta) * sin(phi); gluLookAt(x, y, z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // Teekanne rendern. glutSolidTeapot(1); // Den Matrix-Stack sichern. glPushMatrix(); // Zeichnen der Kugelkreisbahn. drawCircle(10.0f, 50); // Zeichnen der Kugel. // Wenden Sie eine Translation und eine Rotation an, bevor sie die Kugel zeichnen. Sie können die Variable 'angle' für die Rotation verwenden. // Bedenken Sie dabei die richtige Reihenfolge der beiden Transformationen. glRotated(angle, 0, 1.0f, 0); glTranslatef(10.0f, 0, 0); glutSolidSphere(1.0f, 32, 32); // Zeichnen der Würfelkreisbahn. // Hinweis: Der Ursprung des Koordinatensystems befindet sich nun im Zentrum des Würfels. // Drehen Sie das Koordinatensystem um 90° entlang der Achse, die für die Verschiebung des Würfels genutzt wurde. // Danach steht die Würfelkreisbahn senkrecht zur Tangentialrichtung der Kugelkreisbahn. glRotated(90.0f, 1.0f, 0, 0); drawCircle(5.0f, 50); // Zeichnen des Würfels. // Wenden Sie die entsprechende Translation und Rotation an, bevor sie den Würfel zeichnen. glRotated(angle, 0, 1.0f, 0); glTranslatef(5.0f, 0, 0); glutSolidCube(1.0f); // Zeichnen einer Linie von Würfel zu Kegel. glDisable(GL_LIGHTING); glTranslatef(3.0f, 0, 0); glBegin(GL_LINE_STRIP); glVertex3f(0, 0, 0); glVertex3f(-3.0f, 0, 0); glEnd(); glEnable(GL_LIGHTING); // Drehung anwenden, sodass Koordinatensystem in Richtung Ursprung orientiert ist. (Hinweis: Implementieren Sie dies zuletzt.) GLfloat height = 8*cos(toRad(angle-90)); GLfloat d = 8*sin(toRad(angle-90)); GLfloat e = 10 - d; GLfloat l = pow(pow(height,2) + pow(e,2), 0.5f); GLfloat alpha = toDeg(acos(e/l)) - 90; if(static_cast<int>(angle)%360 > 180) alpha = -alpha; glRotated(alpha, 0, 1.0f, 0); if(static_cast<int>(angle)%360 > 180) { glRotated(180 - angle, 0, 1.0f, 0); std::cout << alpha + 180 - (int)angle%360 << std::endl; } else { glRotated(-angle, 0, 1.0f, 0); std::cout << alpha - (int)angle%360 << std::endl; } // Zeichnen der Linie von Kegel zu Urpsrung. glDisable(GL_LIGHTING); glBegin(GL_LINE_STRIP); glVertex3f(0, 0, 0); glVertex3f(0, 0, l); glEnd(); glEnable(GL_LIGHTING); // Zeichnen des Kegels. glutSolidCone(0.5f, 1.0f, 32, 4); // Den Matrix-Stack wiederherstellen. glPopMatrix(); glutSwapBuffers(); angle += 5.0f / 60.0f; }
void RCamera::Animate(int deltaTime) { const float UP_AMT = 1; const float BACK_AMT = 2.2; const float LOOK_AHEAD = 6; glLoadIdentity(); RPlayer *player = m_engine->GetPlayer(m_playerId); Vector4 desiredUp = Normalize3(player->GetUp()); Vector4 playAhead = player->GetAhead(); Vector4 dirNormal = CrossProduct(playAhead,desiredUp); playAhead = Normalize3(CrossProduct(desiredUp,dirNormal)); Vector4 desiredPos = player->GetPosition()+desiredUp*UP_AMT-playAhead*BACK_AMT; Vector4 desiredAhead = Normalize3(player->GetPosition()+playAhead*LOOK_AHEAD-desiredPos); float distance = Length3(desiredPos - m_pos); m_pos = desiredPos; m_ahead = desiredAhead; m_up = CrossProduct(CrossProduct(m_ahead,desiredUp),m_ahead); Vector4 aa = m_pos+m_ahead; if(!freeCameraEnabled) gluLookAt(m_pos[0],m_pos[1],m_pos[2],aa[0],aa[1],aa[2],m_up[0],m_up[1],m_up[2]); //m_ahead = playAhead; // NOTE: // m_ahead and m_up must be normal to each other // AND correspond exactly to depth and height. // View Frustum culling finds the the vertices // of the view frustum by moving in these directions, // so if they are not exactly straight ahead and straight up // there will be a problem. //m_ahead = Normalize3(player->GetAhead()); //m_ahead = Normalize3(desiredAhead); //m_up = desiredUp; //m_up = Normalize3(player->GetUp()); //Vector4 pointAhead = desiredPos+desiredAhead; //Vector4 pointAhead = m_pos+m_ahead; //gluLookAt(m_pos[0],m_pos[1],m_pos[2],pointAhead[0],pointAhead[1],pointAhead[2],m_up[0],m_up[1],m_up[2]); //glLoadIdentity(); timeSinceLastMove +=deltaTime; //if(timeSinceLastMove>100) { timeSinceLastMove = 0; viewPos[0]+=-speed*sin(viewAngle*PI/180);; viewPos[2]+=speed*cos(viewAngle*PI/180); if (freeCameraEnabled) { if(onTrack) m_engine->GetWorld()->getTrack()->Viewpoint(trackDistance,12); else { glRotatef(viewAngle,0,1,0); glTranslatef(viewPos[0],viewPos[1],viewPos[2]); } } /* Vector4 pos = player->GetPosition()+.2*desiredUp; Vector4 a = pos+playAhead; m_ahead = Normalize3(playAhead); Vector4 upNormalizer = CrossProduct(m_ahead,desiredUp); m_up = Normalize3(CrossProduct(upNormalizer,m_ahead)); if (!freeCameraEnabled) gluLookAt(pos[0],pos[1],pos[2],a[0],a[1],a[2],m_up[0],m_up[1],m_up[2]); m_pos = pos; */ // cout << "Position: "; PrintVector(m_pos); cout << endl; // cout << "Ahead: "; PrintVector(m_ahead); cout << endl; // cout << "Up: "; PrintVector(m_up); cout << endl; }
void lookAt(Point3D *position, Point3D *target) { gluLookAt(position->x, position->y, position->z, target->x, target->y, target->z, 0, 1, 0); }
void gl_renderiza_escena(void) { static float grados=0; /* Auxiliar de cálculo */ unsigned int aux,j; float aux2; float viewport[4]; GLboolean visible; /* Reseteamos los buffers y la matriz de modelado */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Dibujamos el fondo */ /* Primero preparamos el estado de OpenGL */ glMatrixMode(GL_PROJECTION); glLoadMatrixd(&matriz_proyeccion_B[0][0]); gluLookAt( camara[3][0],camara[3][1],camara[3][2], // Posición camara[3][0]+camara[2][0],camara[3][1]+camara[2][1],camara[3][2]+camara[2][2], // Punto al que miramos camara[1][0],camara[1][1],camara[1][2]); // Orientación Y glMatrixMode(GL_MODELVIEW); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glLoadIdentity(); glDisable(GL_LIGHTING); for (aux=0;aux<n_estrellas;aux+=4) { glPointSize(estrellas[aux+3]); glBegin(GL_POINTS); glVertex3f(estrellas[aux],estrellas[aux+1],estrellas[aux+2]); glEnd(); } glPointSize(4.0f); glEnable(GL_TEXTURE_2D); for (aux=0;aux<n_sprites_spc;aux++) { glLoadMatrixf(&sprites_spc[aux].matriz); glBindTexture(GL_TEXTURE_2D, sprites_spc[aux].textura); aux2=sprites_spc[aux].tam_x; glBegin(GL_QUADS); glTexCoord2f(1.0f, 1.0f); glVertex2f( aux2, aux2); glTexCoord2f(1.0f, 0.0f); glVertex2f( aux2, -aux2); glTexCoord2f(0.0f, 0.0f); glVertex2f(-aux2, -aux2); glTexCoord2f(0.0f, 1.0f); glVertex2f(-aux2, aux2); glEnd(); } glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); glLoadIdentity(); /* Dibujamos el laser */ if (disparo_laser.ttl>0) { //glDisable(GL_TEXTURE_2D); memcpy(auxiliar_objeto,camara,sizeof(float)*16); auxiliar_objeto[3][0]=disparo_laser.posicion[0]; auxiliar_objeto[3][1]=disparo_laser.posicion[1]; auxiliar_objeto[3][2]=disparo_laser.posicion[2]; glLoadMatrixf(&auxiliar_objeto); glBindTexture(GL_TEXTURE_2D, textura[5]); aux2=0.5f; glBegin(GL_QUADS); glTexCoord2f(1.0f, 1.0f); glVertex2f( aux2, aux2); glTexCoord2f(1.0f, 0.0f); glVertex2f( aux2, -aux2); glTexCoord2f(0.0f, 0.0f); glVertex2f(-aux2, -aux2); glTexCoord2f(0.0f, 1.0f); glVertex2f(-aux2, aux2); glEnd(); glLoadIdentity(); if ( audio_on == 1){ // Actualizamos posicion de la fuente de laser ActualizarSource ( 0, auxiliar_objeto[3]); } } /* Luces */ glEnable(GL_LIGHTING); LightPosition1[0]=-camara[2][0]; LightPosition1[1]=-camara[2][1]; LightPosition1[2]=-camara[2][2]; LightPosition1[3]=0; glLightfv(GL_LIGHT1, GL_POSITION, LightPosition1); /* Comenzamos a dibujar la nave de marras */ glEnable(GL_TEXTURE_2D); auxiliar_objeto[0][0]=nave1->base[0].x; auxiliar_objeto[0][1]=nave1->base[0].y; auxiliar_objeto[0][2]=nave1->base[0].z; auxiliar_objeto[0][3]=0; auxiliar_objeto[1][0]=nave1->base[1].x; auxiliar_objeto[1][1]=nave1->base[1].y; auxiliar_objeto[1][2]=nave1->base[1].z; auxiliar_objeto[1][3]=0; auxiliar_objeto[2][0]=nave1->base[2].x; auxiliar_objeto[2][1]=nave1->base[2].y; auxiliar_objeto[2][2]=nave1->base[2].z; auxiliar_objeto[2][3]=0; auxiliar_objeto[3][0]=nave1->x; auxiliar_objeto[3][1]=nave1->y; auxiliar_objeto[3][2]=nave1->z; auxiliar_objeto[3][3]=1; glLoadMatrixf(&auxiliar_objeto); glBindTexture(GL_TEXTURE_2D, nave1->n_textura); for (j = 0; j < nave1->n_caras; j++) { glBegin(GL_TRIANGLES); glTexCoord2f(nave1->triangulos[j].vertices[0].u, nave1->triangulos[j].vertices[0].v); glNormal3f(nave1->triangulos[j].vertices[0].Nx, nave1->triangulos[j].vertices[0].Ny, nave1->triangulos[j].vertices[0].Nz); glVertex3f(nave1->triangulos[j].vertices[0].x,nave1->triangulos[j].vertices[0].y,nave1->triangulos[j].vertices[0].z); glTexCoord2f(nave1->triangulos[j].vertices[1].u, nave1->triangulos[j].vertices[1].v); glNormal3f(nave1->triangulos[j].vertices[1].Nx, nave1->triangulos[j].vertices[1].Ny, nave1->triangulos[j].vertices[1].Nz); glVertex3f(nave1->triangulos[j].vertices[1].x,nave1->triangulos[j].vertices[1].y,nave1->triangulos[j].vertices[1].z); glTexCoord2f(nave1->triangulos[j].vertices[2].u, nave1->triangulos[j].vertices[2].v); glNormal3f(nave1->triangulos[j].vertices[2].Nx, nave1->triangulos[j].vertices[2].Ny, nave1->triangulos[j].vertices[2].Nz); glVertex3f(nave1->triangulos[j].vertices[2].x,nave1->triangulos[j].vertices[2].y,nave1->triangulos[j].vertices[2].z); glEnd(); } glLoadIdentity(); glDisable(GL_LIGHTING); glRasterPos3f(nave1->x,nave1->y,nave1->z); glGetBooleanv( GL_CURRENT_RASTER_POSITION_VALID,&visible); glGetFloatv( GL_CURRENT_RASTER_POSITION,&viewport); glLoadIdentity(); if ( audio_on == 1){ PosSonidoNave1[0] = nave1->x; PosSonidoNave1[1] = nave1->y; PosSonidoNave1[2] = nave1->z; ActualizarSource ( 2, PosSonidoNave1 ); // Actualizamos posicion de la fuente de la nave enemiga } /* Dibujado de las fuentes */ glDisable(GL_DEPTH_TEST); /* Las fuentes se dibujan en primer plano y utilizando el canal ALPHA */ glMatrixMode(GL_PROJECTION); glLoadMatrixd(&matriz_proyeccion_C[0][0]); glClear(GL_DEPTH_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, textura[3]); /* CrossHair */ /* Con la funcion glTexCoord2f mapeamos las coordenadas de la textura*/ glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex2f(config.SCREEN_SIZE_X/2-16.0f,config.SCREEN_SIZE_Y/2+16.0f); glTexCoord2f(0.0f, 0.0f); glVertex2f(config.SCREEN_SIZE_X/2-16.0f,config.SCREEN_SIZE_Y/2-16.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(config.SCREEN_SIZE_X/2+16.0f,config.SCREEN_SIZE_Y/2-16.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(config.SCREEN_SIZE_X/2+16.0f,config.SCREEN_SIZE_Y/2+16.0f); glEnd(); /* Localizador */ if (visible) { glBindTexture(GL_TEXTURE_2D, textura[4]); glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex2f(viewport[0]-16.0f,viewport[1]+16.0f); glTexCoord2f(0.0f, 0.0f); glVertex2f(viewport[0]-16.0f,viewport[1]-16.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(viewport[0]+16.0f,viewport[1]-16.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(viewport[0]+16.0f,viewport[1]+16.0f); glEnd(); } /* Actualizamos posicion del listener */ if (audio_on == 1){ ActualizarListener (1,camara[3][0],camara[3][1],camara[3][2],0.0f,0.0f,0.0f,camara[1][0],camara[1][1],camara[1][2], camara[3][0]+camara[2][0],camara[3][1]+camara[2][1],camara[3][2]+camara[2][2]); } /* Calculamos e imprimimos los frames por segundo */ print(fuentes[1],0.0f,config.SCREEN_SIZE_Y,.5f,"Velocidad %f",velocidad); /* Incrementamos el número de frames visualizados */ FPS++; /* Llamamos a la función de intercambio de buffers*/ sys_swapbuffers(); }
int main(int argc, char **argv) { int i; glutInitWindowSize(400, 200); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); glutInit(&argc, argv); for (i = 1; i < argc; i++) { if (!strcmp("-sb", argv[i])) { glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_MULTISAMPLE); singleBuffer = 1; } } glutCreateWindow("multilight"); glClearColor(0.0, 0.0, 0.0, 0.0); glMatrixMode(GL_PROJECTION); gluPerspective(50.0, 2.0, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); gluLookAt( 0.0, 1.0, -16.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.); numActiveLights = MIN_VALUE(MAX_LIGHTS, 8); for (i = 0; i < numActiveLights; i++) { initLight(i); } glLightModelfv(GL_LIGHT_MODEL_AMBIENT, modelAmb); glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glMaterialfv(GL_FRONT, GL_AMBIENT, matAmb); glMaterialfv(GL_FRONT, GL_DIFFUSE, matDiff); glMaterialfv(GL_FRONT, GL_SPECULAR, matSpec); glMaterialfv(GL_FRONT, GL_EMISSION, matEmission); glMaterialf(GL_FRONT, GL_SHININESS, 10.0); glNewList(DL_LIGHT_SPHERE, GL_COMPILE); glutSolidSphere(0.2, 4, 4); glEndList(); glNewList(DL_BIG_SPHERE, GL_COMPILE); glutSolidSphere(1.5, 20, 20); glEndList(); glNewList(DL_ICO, GL_COMPILE); glutSolidIcosahedron(); glEndList(); glutDisplayFunc(display); glutVisibilityFunc(visible); glutKeyboardFunc(key); glutMouseFunc(mouse); glutMotionFunc(motion); glutCreateMenu(menu); glutAddMenuEntry("Sphere", M_SPHERE); glutAddMenuEntry("Icosahedron", M_ICO); glutAddMenuEntry("Linear attenuation", M_LINEAR); glutAddMenuEntry("Quadratic attenuation", M_QUAD); glutAddMenuEntry("Toggle Light Number Labels", M_LABELS); glutAddMenuEntry("Report Light Significance", M_REPORT_SIG); glutAddMenuEntry("Lambertian-based Significance", M_LAMBERTIAN); glutAddMenuEntry("Distance-based Significance", M_DISTANCE); glutAddMenuEntry("Time Frames", M_TIME); glutAddMenuEntry("Quit", 666); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); return 0; /* ANSI C requires main to return int. */ }
void vsx_widget_desktop::draw() { if (!init_run) return; // this is designed to be root, so set up things // Deal with movement around the desktop #define SGN(N) (N >= 0 ? 1 : -1) #define MAX(N, M) ((N) >= (M) ? (N) : (M)) #define MIN(N, M) ((N) <= (M) ? (N) : (M)) #define CLAMP(N, L, U) (MAX(MIN((N), (U)), (L))) //if (logo_time > animlen) { if (!interpolating) { double acc = 4, dec = 3, spd = global_key_speed; // interpolation falloff control float tt = dtime*interpolation_speed*global_interpolation_speed; if (tt > 1) { tt = 1; } if(zpd != 0.0) { double sgn = SGN(zpd); zps += dtime * acc * sgn * global_interpolation_speed; zps = CLAMP(zps, -1.2f, 1.2f); } if(zpd == 0.0) { double sgn = SGN(zps); zps -= dtime * dec * sgn * global_interpolation_speed; zps = MAX(zps * sgn, 0) * sgn; } zp += zps * fabs(zp - 1.1)* spd * dtime + zpp*(zp - 1.0f); zpp = zpp*(1-tt); if (zp > 100) {zp = 100; zps = 0;} if (zp < 1.2) {zp = 1.2; zps = 0;} if(xpd != 0.0) { double sgn = SGN(xpd); xps += dtime * acc * sgn * global_interpolation_speed; xps = CLAMP(xps, -1, 1); } if(xpd == 0.0) { double sgn = SGN(xps); xps -= dtime * dec * sgn * global_interpolation_speed; xps = MAX(xps * sgn, 0) * sgn; } xp += xps * fabs(zp - 1.1)* spd * dtime*0.6 + xpp*(zp-1.0f); xpp = xpp*(1-tt); if (xp > 10) {xp = 10; xps = 0;} if (xp < -10) {xp = -10; xps = 0;} if(ypd != 0.0) { double sgn = SGN(ypd); yps += dtime * acc * sgn * global_interpolation_speed; yps = CLAMP(yps, -1, 1); } if(ypd == 0.0) { double sgn = SGN(yps); yps -= dtime * dec * sgn * global_interpolation_speed; yps = MAX(yps * sgn, 0) * sgn; } yp += yps * fabs(zp - 1.1)* spd * dtime*0.6 + ypp*(zp-1.0f); ypp = ypp*(1-tt); if (yp > 10) {yp = 10; yps = 0;} if (yp < -10) {yp = -10; yps = 0;} // printf("xp: %f xps: %f xpd %f dt %f::",xp,xps,xpd,tt); } else { float tt = dtime*10.0f*global_interpolation_speed; if (tt > 1) { tt = 1; interpolating = false;} xp = xp*(1-tt)+camera_target.x*tt; yp = yp*(1-tt)+camera_target.y*tt; zp = zp*(1-tt)+camera_target.z*tt; if ( (round(xp*2000) == round(camera_target.x*2000)) && (round(yp*2000) == round(camera_target.y*2000)) && (round(zp*2000) == round(camera_target.z*2000)) ) interpolating = false; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45,screen_x/screen_y,0.001,120.0); gluLookAt(xp,yp,zp-1.1f,xp,yp,-1.1f,0.0,1.0,0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // PERFORMANCE_MODE_CHANGE // if (performance_mode) // glBlendFunc(GL_SRC_ALPHA, GL_ONE); //else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // //return; glEnable(GL_BLEND); //glClear(GL_COLOR_BUFFER_BIT); if (!performance_mode) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //glEnable(GL_LINE_SMOOTH); if (!performance_mode) { glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); glColor4f(1,1,1,1); #ifndef VSXU_PLAYER if (!mtex.bind()) #endif glColor4f(skin_color[13].r,skin_color[13].g,skin_color[13].b,skin_color[13].a); //else glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(pos.x-size.x/2,pos.y-size.y/2,-10.0f); glTexCoord2f(0, 1); glVertex3f(pos.x-size.x/2,pos.y+size.y/2,-10.0f); glTexCoord2f(1, 1); glVertex3f(pos.x+size.x/2,pos.y+size.y/2,-10.0f); glTexCoord2f(1, 0); glVertex3f(pos.x+size.x/2,pos.y-size.y/2,-10.0f); glEnd(); #ifndef VSXU_PLAYER mtex._bind(); #endif } draw_children(); }
void draw() { // Clear Screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Place Camera glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eyeX, eyeY, eyeZ, 0, 0, 0, upX, upY, upZ); // Set Perspective glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, 1.33, 1.6, 10); glMatrixMode(GL_MODELVIEW); // Draw Faces Far and Near glBegin(GL_QUADS); glColor3f(1.0, 0.0, 0.0); glVertex3f(0.8, 0.8, -0.8); glVertex3f(0.8, -0.8, -0.8); glVertex3f(-0.8, -0.8, -0.8); glVertex3f(-0.8, 0.8, -0.8); glColor3f(0.0, 1.0, 0.0); glVertex3f(0.8, 0.8, 0.8); glVertex3f(0.8, -0.8, 0.8); glVertex3f(-0.8, -0.8, 0.8); glVertex3f(-0.8, 0.8, 0.8); glEnd(); // Draw Faces Right and Left glBegin(GL_QUADS); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.8, -0.8, -0.8); glVertex3f(0.8, 0.8, -0.8); glVertex3f(0.8, 0.8, 0.8); glVertex3f(0.8, -0.8, 0.8); glColor3f(1.0, 1.0, 0.0); glVertex3f(-0.8, -0.8, -0.8); glVertex3f(-0.8, 0.8, -0.8); glVertex3f(-0.8, 0.8, 0.8); glVertex3f(-0.8, -0.8, 0.8); glEnd(); // Draw Faces Top and Bottom glBegin(GL_QUADS); glColor3f(0.0, 1.0, 1.0); glVertex3f(-0.8, 0.8, -0.8); glVertex3f(-0.8, 0.8, 0.8); glVertex3f(0.8, 0.8, 0.8); glVertex3f(0.8, 0.8, -0.8); glColor3f(1.0, 0.0, 1.0); glVertex3f(-0.8, -0.8, -0.8); glVertex3f(-0.8, -0.8, 0.8); glVertex3f(0.8, -0.8, 0.8); glVertex3f(0.8, -0.8, -0.8); glEnd(); glfwSwapBuffers(); }
void GLCanvas::renderSkeleton() { Vector3 lookAt = _cameraPosition + _cameraFront; gluLookAt(_cameraPosition.x(), _cameraPosition.y(), _cameraPosition.z(), lookAt.x() , lookAt.y() , lookAt.z(), _cameraUp.x() , _cameraUp.y() , _cameraUp.z()); if (_style & DRAW_GRID) { drawGrid(); } if (_skeleton == nullptr) { return; } for (auto it = _skeleton->beginBones(); it != _skeleton->endBones(); ++it) { glPushMatrix(); Bone bone = *(it->second); int boneId = bone.getId(); // don't draw any bone without valid id if (boneId < 0) { continue; } // get the bone id as color for SELECTION_MODE GLubyte boneIdColor[4] = {GLubyte((boneId >> 8) & 255), GLubyte((boneId >> 8) & 255), GLubyte(boneId & 255), 255}; const GLubyte* boneColor1 = boneStandardColor1; const GLubyte* boneColor2 = boneStandardColor2; if (_style & SELECTION_MODE) { boneColor1 = boneIdColor; boneColor2 = boneIdColor; } else if (_style & HIGHLIGHT_SELECTED_BONE && bone.getId() == _skeleton->getSelectedBoneId()) { boneColor1 = boneHighlightedColor1; boneColor2 = boneHighlightedColor2; } Vector3 startPos = bone.getStartPos(); glTranslatef(startPos.x(), startPos.y(), startPos.z()); float length = bone.getLength(); Vector3 dir = bone.getDirection(); Vector3 up = bone.getUpDirection(); Vector3 right = bone.getRightDirection(); Vector3 endPos = dir*length; startPos = Vector3(0, 0, 0); float length_10 = length * 0.1f; Vector3 endPos_10 = endPos * 0.1f; Vector3 upPoint = up*length_10 + endPos_10; Vector3 downPoint = - up*length_10 + endPos_10; Vector3 rightPoint = right*length_10 + endPos_10; Vector3 leftPoint = - right*length_10 + endPos_10; if (!(_style & SELECTION_MODE)) { //set point size to 10 pixels glPointSize(10.0f); glColor4ubv(pointColor); // TODO(JK#9#): maybe don't draw points for bones (or add render style flag) glBegin(GL_POINTS); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glEnd(); } // set line width glLineWidth(_lineWidth); // draw local coordinate system if (_style & DRAW_LOCAL_COORDINATE_SYSTEM) { glBegin(GL_LINES); glColor4ubv(red); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glVertex3f(endPos.x() + dir.x()*0.1f, endPos.y() + dir.y()*0.1f, endPos.z() + dir.z()*0.1f); glColor4ubv(green); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glVertex3f(endPos.x() + up.x()*0.1f, endPos.y() + up.y()*0.1f, endPos.z() + up.z()*0.1f); glColor4ubv(blue); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glVertex3f(endPos.x() + right.x()*0.1f, endPos.y() + right.y()*0.1f, endPos.z() + right.z()*0.1f); glEnd(); } if (_style & DRAW_ROTATION_AXIS) { Vector3 rotAxis = bone.getRelOrientation().getRotationAxis(); glBegin(GL_LINES); glColor4ubv(yellow); glVertex3f(-rotAxis.x()*0.2f, -rotAxis.y()*0.2f, -rotAxis.z()*0.2f); glVertex3f(rotAxis.x()*0.2f, rotAxis.y()*0.2f, rotAxis.z()*0.2f); glEnd(); } // draw bone glPolygonMode(GL_FRONT, GL_FILL); glColor4ubv(boneColor1); glBegin(GL_TRIANGLE_FAN); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glVertex3f(leftPoint.x(), leftPoint.y(), leftPoint.z()); glVertex3f(downPoint.x(), downPoint.y(), downPoint.z()); glVertex3f(rightPoint.x(), rightPoint.y(), rightPoint.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glEnd(); glColor4ubv(boneColor2); glBegin(GL_TRIANGLE_FAN); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glVertex3f(rightPoint.x(), rightPoint.y(), rightPoint.z()); glVertex3f(downPoint.x(), downPoint.y(), downPoint.z()); glVertex3f(leftPoint.x(), leftPoint.y(), leftPoint.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glEnd(); if (!(_style & SELECTION_MODE)) { // draw black mesh lines around bones glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4ubv(black); glBegin(GL_TRIANGLE_FAN); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glVertex3f(leftPoint.x(), leftPoint.y(), leftPoint.z()); glVertex3f(downPoint.x(), downPoint.y(), downPoint.z()); glVertex3f(rightPoint.x(), rightPoint.y(), rightPoint.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glEnd(); glBegin(GL_TRIANGLE_FAN); glVertex3f(endPos.x(), endPos.y(), endPos.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glVertex3f(rightPoint.x(), rightPoint.y(), rightPoint.z()); glVertex3f(downPoint.x(), downPoint.y(), downPoint.z()); glVertex3f(leftPoint.x(), leftPoint.y(), leftPoint.z()); glVertex3f(upPoint.x(), upPoint.y(), upPoint.z()); glEnd(); // draw labels if (_style & DRAW_LABEL) { // glDisable(GL_DEPTH_TEST); GLImage* image = _labels.find(boneId)->second; image->setPosition(0.5f * bone.getLength() * dir - 0.06f * bone.getLength() * _cameraFront); image->render(); // glEnable(GL_DEPTH_TEST); } } // reset line width glLineWidth(1.0f); if (_style & DRAW_SPIN_ARROWS && bone.getId() == _skeleton->getSelectedBoneId()) { drawSpinArrows(endPos - 0.2 * bone.getLength() * dir, dir, up, right); } glPopMatrix(); // append trace point and draw trace if (_traceLength > 0) { Vector3 globalEndPos = bone.getEndPos(); std::map<int, std::vector<Vector3> >::iterator traceIt = _boneIdsWithTracePoints.find(boneId); if (traceIt != _boneIdsWithTracePoints.end()) { if (traceIt->second.size() < _traceLength) { traceIt->second.push_back(globalEndPos); } else { traceIt->second[_tracePos] = globalEndPos; } glBegin(GL_LINES); glColor4ubv(yellow); for (size_t i = 0; i < traceIt->second.size() - 1; ++i) { if (i != _tracePos) { glVertex3f(traceIt->second[i].x(), traceIt->second[i].y(), traceIt->second[i].z()); glVertex3f(traceIt->second[i+1].x(), traceIt->second[i+1].y(), traceIt->second[i+1].z()); } } // draw gab between end and beginning of the vector data if (traceIt->second.size() > 1 && _tracePos != traceIt->second.size() - 1) { glVertex3f(traceIt->second.back().x(), traceIt->second.back().y(), traceIt->second.back().z()); glVertex3f(traceIt->second[0].x(), traceIt->second[0].y(), traceIt->second[0].z()); } glEnd(); } } } // draw joints (after everything else, as they are transparent and need everything else be rendered) if (_style & DRAW_JOINT_CONSTRAINTS) { for (auto it = _skeleton->beginBones(); it != _skeleton->endBones(); ++it) { glPushMatrix(); Bone bone = *(it->second); Vector3 startPos = bone.getStartPos(); glTranslatef(startPos.x(), startPos.y(), startPos.z()); JointConstraint constraint = bone.getJointConstraint(); drawJoint(constraint); glPopMatrix(); } } // update trace position if (++_tracePos >= _traceLength) { _tracePos = 0; } if (!(_style & SELECTION_MODE) && _style & DRAW_AABB) { drawAABB(_skeleton->getAABB()); } } void GLCanvas::drawSpinArrows(Vector3 pos, Vector3 dir, Vector3 up, Vector3 right) const { float length = 0.03f; float offset = 0.05f; GLubyte red[4] = {255, 0, 0, 255}; GLubyte green[4] = {0, 255, 0, 255}; GLubyte blue[4] = {0, 0, 255, 255}; GLubyte black[4] = {0, 0, 0, 255}; // set arroe ids to next available free ids int idArrowDir = _skeleton->getNextFreeId(); int idArrowUp = _skeleton->getNextFreeId() + 1; int idArrowRight = _skeleton->getNextFreeId() + 2; GLubyte idArrowDirColor[4] = {GLubyte((idArrowDir >> 8) & 255), GLubyte((idArrowDir >> 8) & 255), GLubyte(idArrowDir & 255), 255}; GLubyte idArrowUpColor[4] = {GLubyte((idArrowUp >> 8) & 255), GLubyte((idArrowUp >> 8) & 255), GLubyte(idArrowUp & 255), 255}; GLubyte idArrowRightColor[4] = {GLubyte((idArrowRight >> 8) & 255), GLubyte((idArrowRight >> 8) & 255), GLubyte(idArrowRight & 255), 255}; const GLubyte* arrowDirColor = red; const GLubyte* arrowUpColor = green; const GLubyte* arrowRightColor = blue; // base points of the arrow pyramids Vector3 basePointUp = pos + up * offset; Vector3 basePointRight = pos + right * offset; Vector3 basePointDown = pos - up * offset; Vector3 basePointLeft = pos - right * offset; dir *= length; up *= length; right *= length; Vector3 dirHalf = dir * 0.5; Vector3 rightHalf = right * 0.5; // base vertices of the circle like arrow Vector3 upperCircle[4]; upperCircle[0] = basePointDown; upperCircle[1] = basePointDown - right; upperCircle[2] = basePointLeft - up; upperCircle[3] = basePointLeft; Vector3 lowerCircle[4]; lowerCircle[0] = basePointDown - up; lowerCircle[1] = basePointDown - right*1.4 - up; lowerCircle[2] = basePointLeft - right - up*1.4; lowerCircle[3] = basePointLeft - right; // the arrow rendering is done twice, one iteration for filling color, one for having black corner lines int numIterations = 2; if (_style & SELECTION_MODE) { // do not draw the corner lines in selection mode numIterations = 1; // draw the arrows with their id color arrowDirColor = idArrowDirColor; arrowUpColor = idArrowUpColor; arrowRightColor = idArrowRightColor; } // draw vertices twice, one run with filling and one with black lines for (int j = 0; j < numIterations; ++j) { if (j == 0) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0, 0.0, 0.0, 1.0); arrowDirColor = arrowUpColor = arrowRightColor = black; } if (j == 0) { glColor4ubv(arrowUpColor); } glColor4ubv(arrowUpColor); // arrow pointing upwards glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointUp.x() + up.x()*2.0, basePointUp.y() + up.y()*2.0, basePointUp.z() + up.z()*2.0); glVertex3f(basePointUp.x() + dir.x(), basePointUp.y() + dir.y(), basePointUp.z() + dir.z()); glVertex3f(basePointUp.x() + right.x(), basePointUp.y() + right.y(), basePointUp.z() + right.z()); glVertex3f(basePointUp.x() - dir.x(), basePointUp.y() - dir.y(), basePointUp.z() - dir.z()); glVertex3f(basePointUp.x() - right.x(), basePointUp.y() - right.y(), basePointUp.z() - right.z()); glVertex3f(basePointUp.x() + dir.x(), basePointUp.y() + dir.y(), basePointUp.z() + dir.z()); glEnd(); // arrow pointing downwards /* glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointDown.x() - up.x(), basePointDown.y() - up.y(), basePointDown.z() - up.z()); glVertex3f(basePointDown.x() + dir.x(), basePointDown.y() + dir.y(), basePointDown.z() + dir.z()); glVertex3f(basePointDown.x() + right.x(), basePointDown.y() + right.y(), basePointDown.z() + right.z()); glVertex3f(basePointDown.x() - dir.x(), basePointDown.y() - dir.y(), basePointDown.z() - dir.z()); glVertex3f(basePointDown.x() - right.x(), basePointDown.y() - right.y(), basePointDown.z() - right.z()); glVertex3f(basePointDown.x() + dir.x(), basePointDown.y() + dir.y(), basePointDown.z() + dir.z()); glEnd(); */ if (j == 0) { glColor4f(0.0, 0.0, 1.0, 1.0); } glColor4ubv(arrowRightColor); // arrow pointing to the right glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointRight.x() + right.x()*2.0, basePointRight.y() + right.y()*2.0, basePointRight.z() + right.z()*2.0); glVertex3f(basePointRight.x() + dir.x(), basePointRight.y() + dir.y(), basePointRight.z() + dir.z()); glVertex3f(basePointRight.x() - up.x(), basePointRight.y() - up.y(), basePointRight.z() - up.z()); glVertex3f(basePointRight.x() - dir.x(), basePointRight.y() - dir.y(), basePointRight.z() - dir.z()); glVertex3f(basePointRight.x() + up.x(), basePointRight.y() + up.y(), basePointRight.z() + up.z()); glVertex3f(basePointRight.x() + dir.x(), basePointRight.y() + dir.y(), basePointRight.z() + dir.z()); glEnd(); // arrow pointing to the left /* glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointLeft.x() - right.x(), basePointLeft.y() - right.y(), basePointLeft.z() - right.z()); glVertex3f(basePointLeft.x() + dir.x(), basePointLeft.y() + dir.y(), basePointLeft.z() + dir.z()); glVertex3f(basePointLeft.x() - up.x(), basePointLeft.y() - up.y(), basePointLeft.z() - up.z()); glVertex3f(basePointLeft.x() - dir.x(), basePointLeft.y() - dir.y(), basePointLeft.z() - dir.z()); glVertex3f(basePointLeft.x() + up.x(), basePointLeft.y() + up.y(), basePointLeft.z() + up.z()); glVertex3f(basePointLeft.x() + dir.x(), basePointLeft.y() + dir.y(), basePointLeft.z() + dir.z()); glEnd(); */ if (j == 0) { glColor4f(1.0, 0.0, 0.0, 1.0); } glColor4ubv(arrowDirColor); glBegin(GL_TRIANGLE_FAN); // top of arrow glVertex3f(basePointLeft.x() - rightHalf.x() + up.x()*2.0, basePointLeft.y() - rightHalf.y() + up.y()*2.0, basePointLeft.z() - rightHalf.z() + up.z()*2.0); glVertex3f(basePointLeft.x() + rightHalf.x(), basePointLeft.y() + rightHalf.y(), basePointLeft.z() + rightHalf.z()); glVertex3f(basePointLeft.x() - rightHalf.x() + dir.x(), basePointLeft.y() - rightHalf.y() + dir.y(), basePointLeft.z() - rightHalf.z() + dir.z()); glVertex3f(basePointLeft.x() - right.x() - rightHalf.x(), basePointLeft.y() - right.y() - rightHalf.y(), basePointLeft.z() - right.z() - rightHalf.z()); glVertex3f(basePointLeft.x() - rightHalf.x() - dir.x(), basePointLeft.y() - rightHalf.y() - dir.y(), basePointLeft.z() - rightHalf.z() - dir.z()); glVertex3f(basePointLeft.x() + rightHalf.x(), basePointLeft.y() + rightHalf.y(), basePointLeft.z() + rightHalf.z()); glEnd(); // draw arrows base glBegin(GL_QUAD_STRIP); for (int i = 0; i < 4; ++i) { glVertex3f(upperCircle[i].x() + dirHalf.x(), upperCircle[i].y() + dirHalf.y(), upperCircle[i].z() + dirHalf.z()); glVertex3f(upperCircle[i].x() - dirHalf.x(), upperCircle[i].y() - dirHalf.y(), upperCircle[i].z() - dirHalf.z()); } for (int i = 3; i >= 0; --i) { glVertex3f(lowerCircle[i].x() + dirHalf.x(), lowerCircle[i].y() + dirHalf.y(), lowerCircle[i].z() + dirHalf.z()); glVertex3f(lowerCircle[i].x() - dirHalf.x(), lowerCircle[i].y() - dirHalf.y(), lowerCircle[i].z() - dirHalf.z()); } glVertex3f(upperCircle[0].x() + dirHalf.x(), upperCircle[0].y() + dirHalf.y(), upperCircle[0].z() + dirHalf.z()); glVertex3f(upperCircle[0].x() - dirHalf.x(), upperCircle[0].y() - dirHalf.y(), upperCircle[0].z() - dirHalf.z()); glEnd(); glBegin(GL_QUAD_STRIP); for (int i = 0; i < 4; ++i) { glVertex3f(lowerCircle[i].x() + dirHalf.x(), lowerCircle[i].y() + dirHalf.y(), lowerCircle[i].z() + dirHalf.z()); glVertex3f(upperCircle[i].x() + dirHalf.x(), upperCircle[i].y() + dirHalf.y(), upperCircle[i].z() + dirHalf.z()); } for (int i = 3; i >= 0; --i) { glVertex3f(lowerCircle[i].x() - dirHalf.x(), lowerCircle[i].y() - dirHalf.y(), lowerCircle[i].z() - dirHalf.z()); glVertex3f(upperCircle[i].x() - dirHalf.x(), upperCircle[i].y() - dirHalf.y(), upperCircle[i].z() - dirHalf.z()); } glEnd(); } /* glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor4f(0.0, 0.0, 0.0, 1.0); // arrow pointing upwards glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointUp.x() + up.x()*2.0, basePointUp.y() + up.y()*2.0, basePointUp.z() + up.z()*2.0); glVertex3f(basePointUp.x() + dir.x(), basePointUp.y() + dir.y(), basePointUp.z() + dir.z()); glVertex3f(basePointUp.x() + right.x(), basePointUp.y() + right.y(), basePointUp.z() + right.z()); glVertex3f(basePointUp.x() - dir.x(), basePointUp.y() - dir.y(), basePointUp.z() - dir.z()); glVertex3f(basePointUp.x() - right.x(), basePointUp.y() - right.y(), basePointUp.z() - right.z()); glVertex3f(basePointUp.x() + dir.x(), basePointUp.y() + dir.y(), basePointUp.z() + dir.z()); glEnd(); // arrow pointing to the right glBegin(GL_TRIANGLE_FAN); glVertex3f(basePointRight.x() + right.x()*2.0, basePointRight.y() + right.y()*2.0, basePointRight.z() + right.z()*2.0); glVertex3f(basePointRight.x() + dir.x(), basePointRight.y() + dir.y(), basePointRight.z() + dir.z()); glVertex3f(basePointRight.x() - up.x(), basePointRight.y() - up.y(), basePointRight.z() - up.z()); glVertex3f(basePointRight.x() - dir.x(), basePointRight.y() - dir.y(), basePointRight.z() - dir.z()); glVertex3f(basePointRight.x() + up.x(), basePointRight.y() + up.y(), basePointRight.z() + up.z()); glVertex3f(basePointRight.x() + dir.x(), basePointRight.y() + dir.y(), basePointRight.z() + dir.z()); glEnd();*/ } void GLCanvas::renderSingleSensor() const { // Vector3 lookAt = Vector3(0.0f, 0.0f, 0.0f); // Vector3 lookAt = _cameraPosition + _cameraFront; // gluLookAt(_cameraPosition.x(), _cameraPosition.y(), _cameraPosition.z(), // lookAt.x() , lookAt.y() , lookAt.z(), // _cameraUp.x() , _cameraUp.y() , _cameraUp.z()); gluLookAt(0.0f, 0.0f, _cameraPosition.z(), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); Vector3 dir = _sensorOrientation.rotate(Vector3(1.0f, 0.0f, 0.0f)); Vector3 up = 0.25 * _sensorOrientation.rotate(Vector3(0.0f, 1.0f, 0.0f)); Vector3 right = 0.5 * _sensorOrientation.rotate(Vector3(0.0f, 0.0f, 1.0f)); Vector3 frontUpRight = dir + up + right; Vector3 frontDownRight = dir - up + right; Vector3 frontUpLeft = dir + up - right; Vector3 frontDownLeft = dir - up - right; Vector3 backUpRight = -dir + up + right; Vector3 backDownRight = -dir - up + right; Vector3 backUpLeft = -dir + up - right; Vector3 backDownLeft = -dir - up - right; glBegin(GL_QUADS); glColor3f(0.8, 0.5, 0.5); glVertex3f(frontUpLeft.x(), frontUpLeft.y(), frontUpLeft.z()); glVertex3f(frontUpRight.x(), frontUpRight.y(), frontUpRight.z()); glVertex3f(frontDownRight.x(), frontDownRight.y(), frontDownRight.z()); glVertex3f(frontDownLeft.x(), frontDownLeft.y(), frontDownLeft.z()); glColor3f(0.5, 0.7, 0.5); glVertex3f(backUpRight.x(), backUpRight.y(), backUpRight.z()); glVertex3f(frontUpRight.x(), frontUpRight.y(), frontUpRight.z()); glVertex3f(frontUpLeft.x(), frontUpLeft.y(), frontUpLeft.z()); glVertex3f(backUpLeft.x(), backUpLeft.y(), backUpLeft.z()); glColor3f(0.5, 0.5, 0.7); glVertex3f(backDownRight.x(), backDownRight.y(), backDownRight.z()); glVertex3f(frontDownRight.x(), frontDownRight.y(), frontDownRight.z()); glVertex3f(frontUpRight.x(), frontUpRight.y(), frontUpRight.z()); glVertex3f(backUpRight.x(), backUpRight.y(), backUpRight.z()); glColor3f(0.7, 0.7, 0.7); glVertex3f(backUpRight.x(), backUpRight.y(), backUpRight.z()); glVertex3f(backUpLeft.x(), backUpLeft.y(), backUpLeft.z()); glVertex3f(backDownLeft.x(), backDownLeft.y(), backDownLeft.z()); glVertex3f(backDownRight.x(), backDownRight.y(), backDownRight.z()); glVertex3f(backDownLeft.x(), backDownLeft.y(), backDownLeft.z()); glVertex3f(frontDownLeft.x(), frontDownLeft.y(), frontDownLeft.z()); glVertex3f(frontDownRight.x(), frontDownRight.y(), frontDownRight.z()); glVertex3f(backDownRight.x(), backDownRight.y(), backDownRight.z()); glVertex3f(backUpLeft.x(), backUpLeft.y(), backUpLeft.z()); glVertex3f(frontUpLeft.x(), frontUpLeft.y(), frontUpLeft.z()); glVertex3f(frontDownLeft.x(), frontDownLeft.y(), frontDownLeft.z()); glVertex3f(backDownLeft.x(), backDownLeft.y(), backDownLeft.z()); glEnd(); // scale slightly to ensure the lines are visible glScalef(1.001f, 1.001f, 1.001f); glLineWidth(1.0f); glColor3f(0.0, 0.0, 0.0); glBegin(GL_LINE_STRIP); glVertex3f(backUpRight.x(), backUpRight.y(), backUpRight.z()); glVertex3f(backUpLeft.x(), backUpLeft.y(), backUpLeft.z()); glVertex3f(backDownLeft.x(), backDownLeft.y(), backDownLeft.z()); glVertex3f(backDownRight.x(), backDownRight.y(), backDownRight.z()); glVertex3f(backUpRight.x(), backUpRight.y(), backUpRight.z()); glVertex3f(frontUpRight.x(), frontUpRight.y(), frontUpRight.z()); glVertex3f(frontUpLeft.x(), frontUpLeft.y(), frontUpLeft.z()); glVertex3f(frontDownLeft.x(), frontDownLeft.y(), frontDownLeft.z()); glVertex3f(frontDownRight.x(), frontDownRight.y(), frontDownRight.z()); glVertex3f(frontUpRight.x(), frontUpRight.y(), frontUpRight.z()); glEnd(); glBegin(GL_LINES); glVertex3f(backUpLeft.x(), backUpLeft.y(), backUpLeft.z()); glVertex3f(frontUpLeft.x(), frontUpLeft.y(), frontUpLeft.z()); glVertex3f(backDownLeft.x(), backDownLeft.y(), backDownLeft.z()); glVertex3f(frontDownLeft.x(), frontDownLeft.y(), frontDownLeft.z()); glVertex3f(backDownRight.x(), backDownRight.y(), backDownRight.z()); glVertex3f(frontDownRight.x(), frontDownRight.y(), frontDownRight.z()); glEnd(); glLineWidth(2.0f); // draw global coordinate system glBegin(GL_LINES); glColor3f(1.0, 0.0, 0.0); glVertex3f(-1.5, -1.0, -1.0); glVertex3f(1.0, -1.0, -1.0); glColor3f(0.0, 1.0, 0.0); glVertex3f(-1.5, -1.0, -1.0); glVertex3f(-1.5, 1.0, -1.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(-1.5, -1.0, -1.0); glVertex3f(-1.5, -1.0, 1.0); glEnd(); // draw global coordinate system // glBegin(GL_LINES); // glColor3f(1.0, 0.0, 0.0); // glVertex3f(0.0, 0.0, 0.0); // glVertex3f(1.5, 00.0, 0.0); // // glColor3f(0.0, 1.0, 0.0); // glVertex3f(0.0, 0.0, 0.0); // glVertex3f(0.0, 1.5, 0.0); // // glColor3f(0.0, 0.0, 1.0); // glVertex3f(0.0, 0.0, 0.0); // glVertex3f(0.0, 0.0, 1.5); // glEnd(); glLineWidth(1.0f); } void GLCanvas::renderSingleJoint() const { Vector3 lookAt = _cameraPosition + _cameraFront; gluLookAt(_cameraPosition.x(), _cameraPosition.y(), _cameraPosition.z(), lookAt.x() , lookAt.y() , lookAt.z(), _cameraUp.x() , _cameraUp.y() , _cameraUp.z()); glBegin(GL_LINES); glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glColor4f(0.0f, 0.0f, 1.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); glEnd(); if (_constraint != nullptr) { drawJoint(*_constraint, 1.0f); } } // Initialization of all OpenGL specific parameters. void GLCanvas::InitGL() { SetCurrent(*_GLRC); glClearColor(0.0, 0.0, 0.0, 0.0); //glClearColor(1.0, 1.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glEnable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_SMOOTH); }
void View::initialize(){ glViewport(0,0,screenWidth,screenHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70,screenWidth/screenHeight,1,20); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(2.5,2.5,2.5, 0,0,0 , 0,1,0); glEnable(GL_DEPTH_TEST); glEnable(GL_STENCIL_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_LIGHT2); glEnable(GL_LIGHT3); glEnable(GL_NORMALIZE); glEnable( GL_TEXTURE_2D ); glShadeModel(GL_SMOOTH); //when all light is off----> Pitch Black..!!! GLfloat ambientColor[] = {0.0f, 0.0f, 0.0f, 1.0f}; //Color (0.2, 0.2, 0.2) glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor); //point source GLfloat diffuseLightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat specularLightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f}; glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLightColor0); glLightfv(GL_LIGHT0, GL_SPECULAR, specularLightColor0); //directed light GLfloat lightColor1[] = {1.0f, 0.27f, 0.0f, 1.0f}; //Color (0.5, 0.2, 0.2) glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1); GLfloat lightPos2[] = {2.5f,2.5f,2.5f, 1.0f }; GLfloat specular2[] = { 1.0f, 0.0f, 0.0f, 1.0f}; GLfloat ambientLight2[] = { 1.0f, 0.0f, 0.0f, 1.0f}; glLightfv(GL_LIGHT2,GL_DIFFUSE,ambientLight2); glLightfv(GL_LIGHT2,GL_SPECULAR,specular2); glLightfv(GL_LIGHT2,GL_POSITION,lightPos2); glLightf(GL_LIGHT2,GL_SPOT_CUTOFF,10.0f); glLightf(GL_LIGHT2,GL_SPOT_EXPONENT,5.0f); GLfloat lightPos3[] = {0.0,2.5f,0.0f, 1.0f }; GLfloat specular3[] = { 0.0f, 0.0f, 1.0f, 1.0f}; GLfloat ambientLight3[] = { 0.0f, 0.0f, 1.0f, 1.0f}; glLightfv(GL_LIGHT3,GL_DIFFUSE,ambientLight3); glLightfv(GL_LIGHT3,GL_SPECULAR,specular3); //controlls the cone -- more value more wider glLightf(GL_LIGHT3,GL_SPOT_CUTOFF,30.0f); //controlls the spread -- less the value more the spread glLightf(GL_LIGHT3,GL_SPOT_EXPONENT,45.0f); }
void display(void){ glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glDepthMask(GL_TRUE); glClearColor(1.0,1.0,1.0,1.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); /* A variável gouraud, utilizando a função display, decide o modelo de sombreamento (shading) para os objetos. Caso a variável gouraud sja setada o sombreamento que será utilizado será o Gouraund(GL_SMOOTH) e flat_shading caso contrário. */ if(gouraud){ glShadeModel(GL_SMOOTH); } else{ glShadeModel(GL_FLAT); } glPushMatrix(); /* calcula a posicao do observador */ obs[0]=raioxz*cos(2*PI*tetaxz/360); obs[2]=raioxz*sin(2*PI*tetaxz/360); gluLookAt(obs[0],obs[1],obs[2],olho[0],olho[1],olho[2],0.0,1.0,0.0); /* propriedades do material do plano A função glMaterialfv() define as propriedades da reflexão difusa, especular e brilho do mateiral que irá compor o objeto, neste caso é um plano*/ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, plano_difusa); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, plano_especular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, plano_brilho); /* desenha o plano */ /* A função glNormal3f() define a orientação da normal do desenho. Por padrão a normal encontra-se na direção (x,y,z) = (0,0,1), assim para que a mesma esteja orientada junto ao plano, a função glNormal3f() orienta a normal no eixo y*/ glNormal3f(0,1,0); glBegin(GL_QUADS); glVertex3f(-10,0,10); glVertex3f(10,0,10); glVertex3f(10,0,-10); glVertex3f(-10,0,-10); glEnd(); /*No OpenGL as fontes de luz não são visíveis, sendo assim, uma espfera foi definida para representar a fonte a luz. Na chamada da função glMaterialfv() o parâmetro GL_EMISSION define a intensidade emitida pelo material como sendo a própria fonte de luz, dando a aparência de que a esfera brilha, como uma lâmpada.*/ glPushMatrix(); glTranslatef(posicao_luz0[0],posicao_luz0[1],posicao_luz0[2]); glMaterialfv(GL_FRONT, GL_EMISSION, cor_luz0); glutSolidSphere(0.3,5,5); glPopMatrix(); glMaterialfv(GL_FRONT, GL_EMISSION, cor_p); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_a_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_a_especular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_a_brilho); glPushMatrix(); glTranslatef(0.0,3.0,-3.0); glutSolidSphere(raioEsfera,fatias,pilhas); glPopMatrix(); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_b_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_b_especular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_b_brilho); glTranslatef(0.0,+3.0,+3.0); glutSolidSphere(raioEsfera,fatias,pilhas); glPopMatrix(); glutSwapBuffers(); }
void GLFW_test2::run_thread(){ float ratio; int width, height; glfwMakeContextCurrent(window); //これで描画するウィンドウを設定するのかもしれない glfwSwapInterval(1); /* OpenGLの初期化 */ glEnable(GL_DEPTH_TEST);// デプスバッファの有効化。 glEnable(GL_CULL_FACE);// カリングの有効化。 glEnable(GL_LIGHTING);// ライティングの有効化。 glEnable(GL_LIGHT0);// 光源0 を有効化。 glEnable(GL_LIGHT1);// 光源1 を有効化。 glCullFace(GL_FRONT);// カリング。 glLightfv(GL_LIGHT1, GL_DIFFUSE, aLightColor);// 光源1の色を設定。 glLightfv(GL_LIGHT1, GL_SPECULAR, aLightColor);// 光源1の色を設定。 glClearColor(1, 1, 1, 1);// glClear() で使用する色(RGBA) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); while (!glfwWindowShouldClose(window)){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glfwGetFramebufferSize(window, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); // 透視投影。 gluPerspective(30.0, ratio, 0.1, 500.0); // 視点設定前の行列をすべて平行移動(視界に収める)。 glTranslated(0.0, 0.0, 0.0); // 視点の設定。 gluLookAt(3.0 * 4, 4.0 * 4, 5.0 * 4, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); drawGround(); // 光源の位置設定 (*重要 視点の位置を設定した後に行う) glLightfv(GL_LIGHT0, GL_POSITION, aLight0pos); glLightfv(GL_LIGHT1, GL_POSITION, aLight1pos); /* 描画 */ //drawCube(); Drawer_test1::Cuboid(1, 2, 3); glfwSwapBuffers(window); glfwPollEvents(); } glfwMakeContextCurrent(NULL); //破壊すると、JOINがこまるのでHIDEして閉じたように見せる //Window自体は破壊されるがコンテクストは破壊されない glfwHideWindow(window); }
// 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 RenderEngine::renderWorld( ICamera& camera ) { World& world = *mClientWorld; glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 45.0f , mAspect , 0.01 , 1000.0 ); Vec3f camPos = camera.getPos(); Vec3f viewPos = camPos + camera.getViewDir(); Vec3f upDir = camera.getUpDir(); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( camPos.x , camPos.y , camPos.z , viewPos.x , viewPos.y , viewPos.z , 0 , 0 , 1.0 ); { glPushMatrix(); glTranslatef( 0 , 10 , 0 ); float len = 10; drawCroodAxis(len); glPopMatrix(); } #if 0 glColor3f (1.0, 1.0, 0.0);// glBegin ( GL_TRIANGLES );// glVertex3f( 0 , 0 , 0 );// glVertex3f(0 ,0.5 , 0 ); glVertex3f(0 ,0.5 , 0.5 ); glEnd (); mMesh.clearBuffer(); mMesh.setVertexOffset( Vec3f(0,0,0) ); mMesh.setColor( 0 , 255 , 0 ); mMesh.addVertex( 0 , 0 , 0 ); mMesh.addVertex( 0 ,0.5 , 0 ); mMesh.addVertex( 0 ,0.5 , 0.5 ); mMesh.addTriangle( 0 , 1 , 2 ); mMesh.render(); for( int i = 0 ; i < 1 ; ++i ) { //glTranslatef( 0 , 1 , 0 ); mBlockRenderer->drawUnknown( 0xffffffff ); } mMesh.render(); #endif int bx = Math::floor( camPos.x ); int by = Math::floor( camPos.y ); ChunkPos cPos; cPos.setBlockPos( bx , by ); int len = 1; glPolygonMode(GL_FRONT, GL_LINE); for( int i = -len ; i <= len ; ++i ) { for( int j = -len ; j <= len ; ++j ) { ChunkPos curPos; curPos.x = cPos.x + i; curPos.y = cPos.y + j; WDMap::iterator iter = mWDMap.find( curPos.hash_value() ); WorldData* data = NULL; if ( iter == mWDMap.end() ) { Chunk* chunk = world.getChunk( curPos ); if ( !chunk ) continue; data = new WorldData; data->needUpdate = true; data->drawList[0] = glGenLists( WorldData::NumPass ); for( int i = 1 ; i < WorldData::NumPass ; ++i ) { data->drawList[i] = data->drawList[0] + i; } mWDMap.insert( std::make_pair( curPos.hash_value() , data ) ); } else { data = iter->second; } if ( data->needUpdate ) { Chunk* chunk = world.getChunk( curPos ); assert( chunk ); glPushMatrix(); glLoadIdentity(); for( int i = 0 ; i < WorldData::NumPass ; ++i ) { mMesh.clearBuffer(); chunk->render( *mBlockRenderer ); glNewList( data->drawList[i] , GL_COMPILE ); mMesh.render(); glEndList(); } glPopMatrix(); data->needUpdate = false; } else { glPushMatrix(); int bx = ChunkSize * curPos.x; int by = ChunkSize * curPos.y; glTranslatef( bx , by , 0 ); glCallLists( WorldData::NumPass , GL_UNSIGNED_INT , data->drawList ); glPopMatrix(); } } } BlockPosInfo info; BlockId id = world.rayBlockTest( camPos , camera.getViewDir() , 100 , &info ); if ( id ) { glPushMatrix(); glTranslatef( info.x , info.y , info.z ); glColor3f ( 1 , 1 , 1 ); glBegin( GL_LINE_LOOP ); switch( info.face ) { case FACE_X: glVertex3f( 1 , 0 , 0 ); glVertex3f( 1 , 1 , 0 ); glVertex3f( 1 , 1 , 1 ); glVertex3f( 1 , 0 , 1 ); break; case FACE_NX: glVertex3f( 0 , 0 , 0 ); glVertex3f( 0 , 1 , 0 ); glVertex3f( 0 , 1 , 1 ); glVertex3f( 0 , 0 , 1 ); break; case FACE_Y: glVertex3f( 0 , 1 , 0 ); glVertex3f( 1 , 1 , 0 ); glVertex3f( 1 , 1 , 1 ); glVertex3f( 0 , 1 , 1 ); break; case FACE_NY: glVertex3f( 0 , 0 , 0 ); glVertex3f( 1 , 0 , 0 ); glVertex3f( 1 , 0 , 1 ); glVertex3f( 0 , 0 , 1 ); break; case FACE_Z: glVertex3f( 0 , 0 , 1 ); glVertex3f( 1 , 0 , 1 ); glVertex3f( 1 , 1 , 1 ); glVertex3f( 0 , 1 , 1 ); break; case FACE_NZ: glVertex3f( 0 , 0 , 0 ); glVertex3f( 1 , 0 , 0 ); glVertex3f( 1 , 1 , 0 ); glVertex3f( 0 , 1 , 0 ); break; } glEnd(); glPopMatrix(); } }
// The display function. It is called whenever the window needs // redrawing (ie: overlapping window moves, resize, maximize) // You should redraw your polygons here void display(void) { // Clear the background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (PERSPECTIVE) { // Perpective Projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60, (GLdouble)window_width / window_height, 0.01, 10000); glutSetWindowTitle("Assignment 2 Template (perspective)"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set the camera position, orientation and target eyeX = rho * cos(theta)*sin(phi); eyeY = rho * sin(theta)*sin(phi); eyeZ = rho * cos(phi); gluLookAt(eyeX, eyeY, eyeZ, 0, 0, 0, 0, 1, 0); } else { // Orthogonal Projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-0.25*rho, 0.25*rho, -0.25*rho, 0.25*rho, -10000, 10000); glutSetWindowTitle("Assignment 2 Template (orthogonal)"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glPushMatrix(); glRotatef(degrees, 0.0, 0.0, 1); if (OBJECT_ON) { glColor3f(1, 0, 0); glBegin(GL_TRIANGLES); for (int i = 0; i < faces; i++) { glNormal3f(normList[(faceList[i].v1)].x, normList[(faceList[i].v1)].y, normList[(faceList[i].v1)].z); // normals glVertex3f(vertList[(faceList[i].v1)].x, vertList[(faceList[i].v1)].y, vertList[(faceList[i].v1)].z); glNormal3f(normList[(faceList[i].v2)].x, normList[(faceList[i].v2)].y, normList[(faceList[i].v2)].z); // normals glVertex3f(vertList[(faceList[i].v2)].x, vertList[(faceList[i].v2)].y, vertList[(faceList[i].v2)].z); glNormal3f(normList[(faceList[i].v3)].x, normList[(faceList[i].v3)].y, normList[(faceList[i].v3)].z); // normals glVertex3f(vertList[(faceList[i].v3)].x, vertList[(faceList[i].v3)].y, vertList[(faceList[i].v3)].z); } glEnd(); } point p = { 200, 200, 0 }; drawMapBase(mb, &p); // //draw a red rectangle // glColor3f(1,0,0); //glBegin(GL_POLYGON); // glVertex3f(0.8,0.8,-0.8); // glVertex3f(0.8,-0.8,-0.8); // glVertex3f(-0.8,-0.8,-0.0); // glVertex3f(-0.8,0.8,-0.0); // glEnd(); // Draw a blue tetraheadron /* glColor3f(0, 0, 1); glBegin(GL_TRIANGLES); glVertex3f(0.0, 1.6, 0.0); glVertex3f(0.8, -0.4, 0.8); glVertex3f(-0.8, -0.4, 0.8); glVertex3f(0.0, 1.6, 0.0); glVertex3f(0.8, -0.4, 0.8); glVertex3f(0.0, -0.4, -0.8); glVertex3f(0.0, 1.6, 0.0); glVertex3f(0.0, -0.4, -0.8); glVertex3f(-0.8, -0.4, 0.8); glVertex3f(-0.8, -0.4, 0.8); glVertex3f(0.8, -0.4, 0.8); glVertex3f(0.0, -0.4, -0.8); glEnd(); */ if (AXIS_ON) { // Draw a green line glColor3f(0, 1, 0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(4, 0, 0); glEnd(); // Draw a green line glColor3f(0, 0, 1); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0, 4, 0); glEnd(); // Draw a green line glColor3f(1, 0, 0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0, 0, 4); glEnd(); } glPopMatrix(); // (Note that the origin is lower left corner) // (Note also that the window spans (0,1) ) // Finish drawing, update the frame buffer, and swap buffers glutSwapBuffers(); }
void DrawParabolicMapWithSphere() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-width, width, -height, height, -100000, 100000); gluLookAt(0, 0, 1, 0, 0, 0, 0, -1, 0); glViewport(0, 0, width * 2, height * 2); glScissor(0, 0, width * 2, height * 2); glClearColor(1,1,1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); double showMapPoints[LOD+1][LOD+1][2]; double showMapTexCoords[LOD+1][LOD+1][2]; for (int i = 0; i <= LOD; i++) { float x = i * 1.0 / LOD; for (int j = 0; j <= LOD; j++) { float y = j * 1.0 / LOD; showMapPoints[i][j][0] = x * width; showMapPoints[i][j][1] = y * height; float parabolic_x, parabolic_y, parabolic_z; // float parabolic_x = ((mapped.x / (2 * (1 + mapped.z))) + 0.5) / 2; // float parabolic_y = (-mapped.y / (2 * (1 + mapped.z))) + 0.5; // float parabolic_z = (1 - parabolic_x * parabolic_x + parabolic_y * parabolic_y) / 2; if (i < LOD / 2) { parabolic_x = (2 * x - 0.5) * 2; parabolic_y = -(2 * y - 1); parabolic_z = (1 - (parabolic_x * parabolic_x + parabolic_y * parabolic_y)) / 2; } else { parabolic_x = (2 * (x - 0.5) - 0.5) * 2; parabolic_y = -(2 * y - 1); parabolic_z = -(1 - (parabolic_x * parabolic_x + parabolic_y * parabolic_y)) / 2; } // printf("para : %f, %f, %f\n",parabolic_x, parabolic_y, parabolic_z); Vector3d mapped = Vector3d(parabolic_x, parabolic_y, parabolic_z); mapped.normalize(); double sum = sqrt(mapped.x*mapped.x + mapped.y*mapped.y + pow(mapped.z+1,2)); showMapTexCoords[i][j][0] = (mapped.x/sum + 1) / 2; showMapTexCoords[i][j][1] = (-mapped.y/sum + 1) / 2; // showMapTexCoords[i][j][0] = x; // showMapTexCoords[i][j][1] = y; } } glEnable(GL_TEXTURE_2D); for (int i = 0; i < LOD; i++) { glBegin(GL_QUAD_STRIP); for (int j = 0; j < LOD; j++) { glTexCoord2dv(showMapTexCoords[i][j]); glVertex2dv(showMapPoints[i][j]); glTexCoord2dv(showMapTexCoords[i + 1][j]); glVertex2dv(showMapPoints[i + 1][j]); } glEnd(); } glDisable(GL_TEXTURE_2D); return; }
void display(void) { if(dipMode==1) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); }else{ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } curF++; // put your OpenGL display commands here glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // reset OpenGL transformation matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // reset transformation matrix to identity // setup look at transformation so that // eye is at : (0,0,3) // look at center is at : (0,0,0) // up direction is +y axis gluLookAt(0.f,0.f,3.f,0.f,0.f,0.f,0.f,1.f,0.f); glRotatef(fRotateAngle,.3f,1.f,.3f); //rand() * 2 - 1; // Test drawing a solid teapot /* else{ glLineWidth(2.5); //glColor3f(1. , 0. , 0.); } */ glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange //glutSolidTeapot(1.f); // call glut utility to draw a solid teapot glBegin(GL_TRIANGLE_FAN); glVertex2f(-.6 + sin(change - 10) / 20, 1. + cos(change - 10) / 20); glVertex2f(-.6 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3 glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10 glVertex2f(.6 + sin(change - 10) / 20, .6 + sin(change - 10) / 20); glVertex2f(.6 + cos(change - 10) / 20, 1. + sin(change - 10) / 20); glEnd(); glBegin(GL_TRIANGLE_FAN); /* if (colorflag) { glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange } else { glColor3f(changecolor + 1., changecolor + .5, changecolor); }*/ glVertex2f(0. + sin(change - 10) / 20, -1. + sin(change - 10) / 20); glVertex2f(-.6 + sin(change - 10) / 20, -1. + sin(change - 10) / 20); glVertex2f(-.6 + cos(change - 10) / 20, -.6 + cos(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20); glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3 glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10 glVertex2f(.2 + sin(change - 10) / 20, -.6 + cos(change - 10) / 20); glVertex2f(.6 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20); glVertex2f(.6 + sin(change - 10) / 20, -1. + cos(change - 10) / 20); glEnd(); //glFlush(); glutSwapBuffers(); // swap front/back framebuffer to avoid flickering curClock=clock(); float elapsed=(curClock-startClock)/(float)CLOCKS_PER_SEC; if(elapsed>1.0f){ float fps=(float)(curF-prevF)/elapsed; printf("fps:%f\n",fps); prevF=curF; startClock=curClock; } }
/* Focntion de dessin */ void DrawGLScene() { // Effacement du buffer de couleur et de profondeur glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(0.0,15.0,20.0,0.0,8.0,0.0,0.0,1.0,0.0); // 1er Partie du TD /* // Objet par extrusion : segement/pince glPushMatrix(); glColor3f(0.6,0.6,0.6); glRotatef(45,1.0,0.0,0.0); glTranslatef(0,0,0); glScalef(0.5,0.5,0.5); extrude(9, Segment_2d, extrusion_vector); glPopMatrix(); */ /* // Objet par révolution : base/lampadaire glPushMatrix(); glColor3f(0.6,0.6,0.6); glTranslatef(-0,0.0,0); glRotatef(0,1.0,0.0,0.0); glScalef(0.3,0.3,0.3); revolution(7, pied_2d, 360, 16); glPopMatrix(); */ /* // Chargement d'un objet : articluation DessinModele(); */ // Objets par listes d'affichage /* Make_CallListes(); glCallList(OBJET_1); glCallList(OBJET_2); glCallList(OBJET_3); glCallList(OBJET_4); glCallList(OBJET_5); */ //2eme Partie du TD // Terain glBegin(GL_POLYGON); glNormal3f(0,1,0); glVertex3f(-10.0f,0.0f,-10.0f); glVertex3f(10.0f,0.0f,-10.0f); glVertex3f(10.0f,0.0f,10.0f); glVertex3f(-10.0f,0.0f,10.0f); glEnd(); // Compilation des listes Make_CallListes(); //pied 1 glPushMatrix(); glTranslatef(5.0f,0.0f,-8.0f); glCallList(OBJET_4); glPopMatrix(); //pied 2 glPushMatrix(); glTranslatef(-5.0f,0.0f,-8.0f); glCallList(OBJET_4); glPopMatrix(); //pied 3 glPushMatrix(); glTranslatef(5.0f,0.0f,0.0f); glCallList(OBJET_4); glPopMatrix(); //pied 4 glPushMatrix(); glTranslatef(-5.0f,0.0f,0.0f); glCallList(OBJET_4); glPopMatrix(); //etablie glPushMatrix(); glTranslatef(0.0f,7.0f,-5.0f); glScalef(15.0,0.2,15.0); glutSolidCube(1.0); glPopMatrix(); //base robot glPushMatrix(); glTranslatef(5.0f,7.0f,-9.0f); glCallList(OBJET_3); glPopMatrix(); //segement 1 glPushMatrix(); glTranslatef(-6.0f,7.5f,-10.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(-15.0,0.0,0.0,1.0); glCallList(OBJET_1); glPopMatrix(); //segement 2 glPushMatrix(); glTranslatef(-3.0f,7.5f,-10.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(-15.0,0.0,0.0,1.0); glCallList(OBJET_1); glPopMatrix(); //segement 1 glPushMatrix(); glTranslatef(0.0f,7.5f,-10.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(-15.0,0.0,0.0,1.0); glCallList(OBJET_1); glPopMatrix(); //pince 1 glPushMatrix(); glTranslatef(-5.0f,7.2f,-2.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(45.0,0.0,0.0,1.0); glCallList(OBJET_2); glPopMatrix(); //pince 2 glPushMatrix(); glTranslatef(-3.0f,7.2f,-2.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(45.0,0.0,0.0,1.0); glCallList(OBJET_2); glPopMatrix(); //pince 3 glPushMatrix(); glTranslatef(-1.0f,7.2f,-2.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(45.0,0.0,0.0,1.0); glCallList(OBJET_2); glPopMatrix(); //pince 4 glPushMatrix(); glTranslatef(1.0f,7.2f,-2.0f); glRotatef(90.0,1.0,0.0,0.0); glRotatef(45.0,0.0,0.0,1.0); glCallList(OBJET_2); glPopMatrix(); //articulation 1 glPushMatrix(); glTranslatef(6.0f,8.0f,-2.0f); glCallList(OBJET_5); glPopMatrix(); //articulation 2 glPushMatrix(); glTranslatef(3.0f,8.0f,-2.0f); glCallList(OBJET_5); glPopMatrix(); //articulation 3 glPushMatrix(); glTranslatef(4.5f,8.0f,0.0f); glCallList(OBJET_5); glPopMatrix(); // Permutation des buffers glutSwapBuffers(); //Raffrechissement de l'image glutPostRedisplay(); }
void display(){ glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); /* Set up transformation */ sceneTransformation(); /* GLdouble V[3],U[3]= {0,1,0},R[3]; V[0] = -current_view[0]; V[1] = -current_view[1]; V[2] = -current_view[2]; Scross_product(&R[0],&R[1],&R[2],U[0],U[1],U[2],V[0],V[1],V[2]); Snormalize(&R[0],&R[1],&R[2]); GLdouble mx,my; mx = startX-prevx; my = startY-prevy; GLdouble newViewPoint[3] = {current_view[0] + (mx*distanceX *R[0]) + (my*distanceY*U[0]), current_view[1] + (mx*distanceX *R[1]) + (my*distanceY*U[1]), current_view[2] + (mx*distanceX *R[2]) + (my*distanceY*U[2])}; GLdouble length_nvp = sqrt((newViewPoint[0]*newViewPoint[0])+ (newViewPoint[1]*newViewPoint[1])+(newViewPoint[2]*newViewPoint[2])); current_view[0] = newViewPoint[0]*distanceX/length_nvp; current_view[1] = newViewPoint[1]*distanceY/length_nvp; current_view[2] = newViewPoint[2]*distanceZ/length_nvp; Scross_product(&U[0],&U[1],&U[2],R[0],R[1],R[2],V[0],V[1],V[2]); Snormalize(&U[0],&U[1],&U[2]); gluLookAt(-V[0],-V[1],-V[2],0,0,0,U[0],U[1],U[2]); prevx = startX; prevy = startY; */ /* Draw the scene into the back buffer */ //draw rotator (larger cube) glPushMatrix(); glLoadIdentity(); glScalef(0.5f,0.5f,0.5f); gluLookAt(-1.0, -6.0, -2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glTranslatef(0.0f, 0.0f, 0.0f); glRotated(anglex,1,0,0); drawScene(); glPopMatrix(); //draw spinner (smaller cube) glPushMatrix(); glRotated(angley,0,1,0); glTranslatef(-0.0f, 4.5f, -0.0f); glScalef(0.25f, 0.25f, 0.25f); drawScene(); glPopMatrix(); /* glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0,20.0,1.0,100.0); glMatrixMode(GL_MODELVIEW); */ /* Swap the front buffer with the back buffer - assumes double buffering */ glutSwapBuffers(); }
void display(void) { curTime = timeGetTime(); float dt = (float)(curTime - lastTime) * 0.001;//secに変換 elapseTime1 += dt; elapseTime2 += dt; fps ++; if(elapseTime1 >= 1.0) { printf("frame per sec = %d \n", fps); elapseTime1 = 0.0; fps = 0; } lastTime = curTime; //カラーバッファ,デプスバッファのクリア glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity();//視点を変えるときはこの位置に必要 if(cos(M_PI * view.theta /180.0) >= 0.0)//カメラ仰角90度でビューアップベクトル切替 gluLookAt(view.pos[0], view.pos[1], view.pos[2], view.cnt[0], view.cnt[1], view.cnt[2], 0.0, 1.0, 0.0); else gluLookAt(view.pos[0], view.pos[1], view.pos[2], view.cnt[0], view.cnt[1], view.cnt[2], 0.0, -1.0, 0.0); //光源設定//'l'を押した後光源位置可変 glLightfv(GL_LIGHT0, GL_POSITION, lightPos); if(flagWireframe)//'w'でwireframeとsolid model切り替え { glPolygonMode(GL_FRONT,GL_LINE); glPolygonMode(GL_BACK,GL_POINT); } else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //描画 // シェーダプログラムの適用 glUseProgram(shaderProg); //テクスチャユニットをシェーダ側のサンプラに関連付け,レンダリング //fragment shaderのユニフォーム変数texのインデックスを取得 GLint texLoc = glGetUniformLocation(shaderProg, "tex"); glUniform1i(texLoc, 0);//GL_TEXTURE0を適用 drawTerrain(); // シェーダプログラムの適用を解除 glUseProgram(0); drawParticle(dt); drawParticle2(dt); //テクスチャ、半透明物体があるとき glDepthMask(GL_FALSE); //デプスバッファを書き込み禁止 glEnable(GL_BLEND);//アルファブレンディングを有効にする glBlendFunc(GL_DST_ALPHA,GL_ONE_MINUS_SRC_ALPHA);//色混合係数を決める //半透明描画 makeRiver(elapseTime2); drawRiver(); //テクスチャ、半透明物体があるとき glDepthMask(GL_TRUE); //デプスバッファの書き込みを許可 glDisable(GL_BLEND); if(flagHelp) { printf("矢印キーによるアフィン変換/光源移動 \n"); printf(" →,←:x軸 \n"); printf(" ↑,↓:y軸 \n"); printf(" [Shift]+↑,↓:z軸 \n"); printf(" 'r'を押した後:回転 \n"); printf(" 't'を押した後:平行移動 \n"); printf(" 's'を押した後:スケーリング \n"); printf(" 'l'を押した後、光源位置の移動可 \n"); printf("'w'でワイヤーフレームとソリッドモデル切り替え \n"); printf("マウス操作で視点変更可 \n"); printf(" dolly:中央付近を左ボタンクリックで近づき,右ボタンクリックで遠ざかる \n"); printf(" pan:左横および右横を右ボタンクリックで注視点が左右に変化する \n"); printf(" tilt:真上および真下を右ボタンクリックで注視点が上下に変化する \n"); printf(" tumble:左右にドラッグすると視点が左右に変化する \n"); printf(" crane:上下にドラッグすると視点が上下に変化する \n"); printf(" zoom:左下を右ボタンクリックでズームイン \n"); printf(" 右下を右ボタンクリックでズームアウト \n"); printf("[Shift]+'r'でリセット \n"); printf("[F1]キー:βの調整 \n"); printf("[F2]キー:σの調整 \n"); printf("[F3]キー:seedの変更 \n"); printf("[F4]キー:x方向の風力変更 \n"); flagHelp = false; } //終了 glutSwapBuffers(); }
void glutDisplay(void) { static DWORD frames = 0; DWORD elapsed = 0; static bool bInit = false; static LARGE_INTEGER tSetposStart,tSetposEnd; if(!g_pVideoMixer) return; if(!bInit) { bInit = true; QueryPerformanceFrequency(&coutFreq); QueryPerformanceCounter (&tSetposStart); } QueryPerformanceCounter (&tSetposEnd); elapsed= 1000*(tSetposEnd.QuadPart - tSetposStart.QuadPart)/coutFreq.QuadPart ; static char prtinfo[MAX_PATH] = {0}; if(elapsed >2000) { sprintf(prtinfo, "fps:%d \n", frames*1000/(elapsed)); DP(prtinfo); frames = 0; QueryPerformanceCounter (&tSetposStart); } frames++; QueryPerformanceCounter (&st); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); static GLfloat rotate = 0.0f; rotate += 0.03f; if(rotate > 360) rotate = 0; for(int i=0;i<4;i++) { switch(i) { case 0: glViewport( 0, g_wndHeight/2, g_wndWidth/2, g_wndHeight/2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-0.5,0.5, -0.5, 0.5, 0.0,100.0); break; case 1: glViewport( g_wndWidth/2, g_wndHeight/2, g_wndWidth/2, g_wndHeight/2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0); gluLookAt(0.0f,0.0f,1.0f, 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f ); break; case 2: glViewport( 0, 0, g_wndWidth/2, g_wndHeight/2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0); gluLookAt(0.0f + 10*cos(rotate),0.0f,10*sin(rotate), 0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f ); break; case 3: glViewport( g_wndWidth/2, 0, g_wndWidth/2, g_wndHeight/2); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0); gluLookAt(0.0f,4.0f,4.0f, 0.0f,0.0f,-4.0f, 0.0f,0.0f,-1.0f ); break; default: break; } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); g_pVideoMixer->Display(); } glutDispMsg(prtinfo); glutSwapBuffers(); QueryPerformanceCounter (&ed); //DP("c:%d \n", 1000*(ed.QuadPart - st.QuadPart)/coutFreq.QuadPart ); }
/* * Configure view mode */ void View::setView() { gluLookAt( ex,ey,ez, vx,vy,vz, 0,Cos(elevationAngle),0); }
void AlignPairWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.beginNativePainting(); makeCurrent(); if(!isValid() )return; glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(freeMesh==0 || gluedTree==0) return; for(int i=0;i<2;++i) { if(i==0) glViewport (0, 0, (GLsizei) QTLogicalToDevice(this,width()/2), (GLsizei) QTLogicalToDevice(this,height())); else glViewport (QTLogicalToDevice(this,width()/2), 0, (GLsizei) QTLogicalToDevice(this,width()/2), (GLsizei) QTLogicalToDevice(this,height())); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30, (AlignPairWidget::width()/2)/(float)AlignPairWidget::height(), 0.1, 100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0,0,6, 0,0,0, 0,1,0); tt[i]->center=vcg::Point3f(0, 0, 0); tt[i]->radius= 1; tt[i]->GetView(); tt[i]->Apply(); vcg::Box3f bb; if(i==0) bb=freeMesh->bbox(); else bb=gluedTree->gluedBBox(); vcg::GLW::DrawMode localDM=vcg::GLW::DMFlat; vcg::GLW::ColorMode localCM = vcg::GLW::CMPerMesh; if((freeMesh->m->hasDataMask(MeshModel::MM_VERTCOLOR))&&(isUsingVertexColor)) localCM = vcg::GLW::CMPerVert; if((freeMesh->m->cm.fn==0)||(usePointRendering)) localDM=vcg::GLW::DMPoints; glPushMatrix(); bool allowScaling = qobject_cast<AlignPairDialog *>(parent())->allowScalingCB->isChecked(); if(allowScaling) vcg::glScale(3.0f/bb.Diag()); else vcg::glScale(3.0f/gluedTree->gluedBBox().Diag()); vcg::glTranslate(-bb.Center()); if(i==0) { freeMesh->m->render(localDM,localCM,vcg::GLW::TMNone); drawPickedPoints(&painter, freePickedPointVec,vcg::Color4b(vcg::Color4b::Red)); } else { foreach(MeshNode *mn, gluedTree->nodeList) if(mn->glued && mn != freeMesh && mn->m->visible) mn->m->render(localDM,localCM,vcg::GLW::TMNone); drawPickedPoints(&painter, gluedPickedPointVec,vcg::Color4b(vcg::Color4b::Blue)); } int pickSide= ( pointToPick[0] < QTLogicalToDevice(this,(width()/2)) )? 0 : 1; if(hasToPick && pickSide==i) { vcg::Point3f pp; hasToPick=false; if(vcg::Pick<vcg::Point3f>(pointToPick[0],pointToPick[1],pp)) { std::vector<vcg::Point3f> &curVec = pickSide?gluedPickedPointVec:freePickedPointVec; qDebug("Picked point %i %i -> %f %f %f",pointToPick[0],pointToPick[1],pp[0],pp[1],pp[2]); if(hasToDelete) { int bestInd = -1; double bestDist =10e100; for(int i=0;i<curVec.size();++i) if(Distance(pp,curVec[i])<bestDist) { bestDist = Distance(pp,curVec[i]); bestInd=i; } hasToDelete=false; if(bestInd>=0) curVec.erase(curVec.begin()+bestInd); } else curVec.push_back(pp); hasToPick=false; update(); } } glPopMatrix(); tt[i]->DrawPostApply(); } doneCurrent(); painter.endNativePainting(); }
/** * realiza a renderização de um frame do jogo */ void RobotWindow::display() { // ajusta para a matriz de modelo e zera as transformações glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // obtém a posição do robô e ajusta câmera para apontar para essa direção robot.configureLookAt(lookAt); setCameraPosition(cameraLongitude, cameraLatitude); gluLookAt(eye.x, eye.y, eye.z, lookAt.x, lookAt.y, lookAt.z, 0.0, 1.0, 0.0); // limpa o atual buffer de renderização glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // verifica se o jogo terminou (o robo tem vidas?) if (robot.getLives() == 0) { // desenha o Game Over e paralisa a aplicação textGameOver.draw2D(); glutSwapBuffers(); disableEvents(); return; } else // senão existem vidas // verifica se o robot deve ser revivido if (!robot.isAlive()) { robot.revive(); newEvent(EVENT_RESET, interval); } // verifica se deve desenhar o limite espacial do jogo if (drawCage) { //glPushMatrix(); borderland.draw(); //glPopMatrix(); } // desenha a plataforma //glPushMatrix(); glColor4dv(platformColor.getVect()); platform.draw(); //glPopMatrix(); /*/ Desenha uma pequena esfera na posição lookAt para referência visual glPushMatrix(); glTranslated(lookAt.x, lookAt.y, lookAt.z); glColor3dv(laranja.getVect()); glutSolidSphere(0.1, 20, 20); glPopMatrix(); /*/ // desenha o robô //glPushMatrix(); robot.draw(); //glPopMatrix(); // desenha o número de vidas textLives.setText("Vidas: %d", robot.getLives()); textLives.draw2D(); // desenha o número de Frames Per Second textFps.setText("FPS: %d", getFps()); textFps.draw2D(); // solicita a saída em vídeo do quadro renderizado glutSwapBuffers(); }
void Scene::render(){ for(int t = 0; t < timeStep; t++){ //for every timestep glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the color buffer glMatrixMode(GL_MODELVIEW); // indicate we are specifying camera transformations glLoadIdentity(); gluLookAt(0.0, 1.0, -0.25, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0 ); // if(t % 5 == 0) { // init(); // } //Draw the boundaries drawBoundaries(); vector<vector<Particle * > > neighbors; //density calculations #pragma omp for for(int i = 0; i < particles->size(); i++){ //for every particle Particle *particle = particles->at(i); double density = MASS; vector<Particle *> findNeighs; for(int j = 0; j < particles->size(); j++){ //comparison to all other particles to see if they're close enough to effect the density Particle *tempParticle = particles->at(j); double dist = particle->getDistance(*tempParticle); if (dist <= H && i != j){ //if the particle is close enough, add its mass * kernel to the density double kern = particle->getKernel(dist); density += tempParticle->getMass() * kern; findNeighs.push_back(tempParticle); } } neighbors.push_back(findNeighs); particle->setDensity(density); } //second iteration of particles and only their neighbors #pragma omp for for(int i = 0; i < particles->size(); i++){ Particle *particle = particles->at(i); Vector3f position = particle->getPosition(); Vector3f velocity = particle->getVelocity(); //http://stackoverflow.com/questions/17565664/gluproject-and-2d-display //Render particle GLdouble posX, posY, posZ;//3D point posX=convert(position.x(), WIDTH); posY=convert(position.y(), HEIGHT); posZ=convert(position.z(), LENGTH); glPushMatrix(); glTranslated(posX, posY, posZ); glutSolidSphere(SRADIUS, 10, 10); glPopMatrix(); //Force calculations Vector3f viscosityForce = Vector3f::Zero(); Vector3f pressureForce = Vector3f::Zero(); Vector3f surfaceNormal = Vector3f::Zero(); double colorField = 0; double pressureJ = particle->calcPressure(); vector<Particle * > curNeighs = neighbors[i]; for(int j = 0; j < curNeighs.size(); j++){//currNeighs.size(); j++){ Particle *tempParticle = curNeighs[j];// currNeighs[j]->p; double tempMass = tempParticle->getMass(); double tempDens = tempParticle->getDensity(); Vector3f tempVel = tempParticle->getVelocity(); double dist = particle->getDistance(*tempParticle); double kern = particle->getKernel(dist); colorField += tempMass / tempDens * kern; //Pressure and surfaceNormal Vector3f rij = tempParticle->getPosition() - position; Vector3f kernDerive = particle->getKernDerive(dist, rij); double pressureK = tempParticle->calcPressure(); pressureForce += tempMass * (pressureJ + pressureK) / (2 * tempDens) * kernDerive; surfaceNormal += tempMass / tempDens * kernDerive; //Viscosity double kernSecond = particle->getKernSecond(dist); viscosityForce += (tempVel - velocity) * tempMass / tempDens * kernSecond; } pressureForce *= -1; viscosityForce *= VISC; Vector3f surfaceTension = Vector3f::Zero(); Vector3f gravityForce(0, particle->getDensity() * GRAVITY, 0); // cout << "pForce: " << pressureForce << endl; // //cout << "dens: " << particle->getDensity() << endl; // cout << "glForce: " << gravityForce << endl; // cout << "vForce: " << viscosityForce << endl; //Update next position Vector3f totalForce = gravityForce + pressureForce + viscosityForce; //cout << "totalForce: " << totalForce << endl; Vector3f acceleration = totalForce/particle->getDensity(); //cout << "1. " << particle->getVelocity() << endl; velocity = velocity + DELTAT * acceleration; //maybe implement some kind of terminal velocity? //cout << "2. " << velocity << endl; Vector3f newPosition = position + DELTAT * velocity; //Boundary check next position bool bounce = false; while((newPosition.x() - RADIUS <= LEFT) || (newPosition.y() - RADIUS <= BOTTOM) || (newPosition.x() + RADIUS >= RIGHT) || (newPosition.y() + RADIUS >= TOP) || (newPosition.z() + RADIUS <= BACK) || (newPosition.z() - RADIUS >= FRONT)){ bounce = true; velocity *= 0.9; newPosition = position + DELTAT * velocity; } if(bounce) velocity *= -1; // if(newPosition.y() - RADIUS <= BOTTOM){ // int boundTime = (BOTTOM - position.y()) / velocity; // Vector3f collision = position + boundTime * velocity; // Vector3f collNorm(collision.x(), 1, collision.z()).normalized(); // double penDist = newPosition.dist(collision); // newPosition = newPosition + penDist * collNorm; // velocity = velocity - 0.3 * (velocity.dot(collNorm)) * collNorm; // } particle->setPosition(newPosition); particle->setVelocity(velocity); } saveImage(t); glFlush(); glutSwapBuffers(); glPopMatrix(); } }
void display() { x_pos = R * cos(phi) * cos(theta); y_pos = R * sin(theta); z_pos = R * sin(phi) * cos(theta); glClearColor(0.0f, 1.0f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (cos(theta) >= 0) gluLookAt(x_pos, y_pos, z_pos, 0, 0, 0, 0, 1, 0); else gluLookAt(x_pos, y_pos, z_pos, 0, 0, 0, 0, -1, 0); // the base plane (square) glColor3f(0.0, 0.0, 0.6); glTranslatef(0, -4, 0); glBegin(GL_POLYGON); glVertex3f(-G.baseEdge / 2, 0, -G.baseEdge / 2); glVertex3f(G.baseEdge / 2, 0, -G.baseEdge / 2); glVertex3f(G.baseEdge / 2, 0, G.baseEdge / 2); glVertex3f(-G.baseEdge / 2, 0, G.baseEdge / 2); glEnd(); C = G.cuboids[j]; C.setTranslation(C.getXT(), C.getYT() - y, C.getZT()); float x, z, xa, xb, za, zb; if (j > 0) { float x = C.getXT(); float z = C.getZT(); float xa = G.cuboids[j - 1].getXT() - (G.cuboids[j - 1].getXS() / 2); float xb = G.cuboids[j - 1].getXT() + (G.cuboids[j - 1].getXS() / 2); float za = G.cuboids[j - 1].getZT() - (G.cuboids[j - 1].getZS() / 2); float zb = G.cuboids[j - 1].getZT() + (G.cuboids[j - 1].getZS() / 2); if (x >= xa && x <= xb && z >= za && z <= zb) { C.setColor(0.7, 0.0, 0.0); rightZone = true; } else rightZone = false; } bool GameOver = GameLose || GameWin; if (!GameOver) C.generateCuboid(); if (!Pause) y += speed; else print_text((char*) "PAUSED", 3, 10, GLUT_BITMAP_TIMES_ROMAN_24, 1.0, 1.0, 0.0); if (y >= newHeight && !GameOver) { y = 0.0; speed = 0.02; C.setColor(0.0, 0.8, 0.0); G.cuboids[j] = C; newHeight -= G.cuboids[j].getYS() / 2 + G.cuboids[j + 1.2].getYS() / 2; if (newHeight < C.getYS()) { GameWin = true; std::cout << "YOU WIN! Game over!" << std::endl; } else if (j > 0 && rightZone == false) { GameLose = true; std::cout << "YOU LOSE! Game over!" << std::endl; } j++; } if (GameWin) print_text((char*) "YOU WIN! Game over!", 3, 10, GLUT_BITMAP_TIMES_ROMAN_24, 1.0, 0.0, 1.0); if (GameLose) print_text((char*) "YOU LOOSE! Game over!", 3, 10, GLUT_BITMAP_TIMES_ROMAN_24, 1.0, 0.0, 1.0); if (j > 0) { C.setColor(0.8, 0.0, 0.0); for (int i = 0; i < j; i++) { G.cuboids[i].generateCuboid(); } } glutSwapBuffers(); }
main(int argc, char *argv[]) { GLuint *tex; int texwid, texht, texcomps; GLUquadricObj *quadric; glutInitWindowSize(winWidth, winHeight); glutInit(&argc, argv); if(argc > 1) { char *args = argv[1]; int done = FALSE; while(!done) { switch(*args) { case 's': /* single buffer */ printf("Single Buffered\n"); dblbuf = FALSE; break; case '-': /* do nothing */ break; case 0: done = TRUE; break; } args++; } } if(dblbuf) glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE); else glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH); (void)glutCreateWindow("example program"); glutDisplayFunc(redraw_original); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(key); /* draw a perspective scene */ glMatrixMode(GL_PROJECTION); glFrustum(-100., 100., -100., 100., 300., 600.); glMatrixMode(GL_MODELVIEW); /* look at scene from (0, 0, 450) */ gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.); /* turn on features */ glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glMateriali(GL_FRONT, GL_SHININESS, 128); /* cosine power */ /* remove back faces to speed things up */ glCullFace(GL_BACK); glBlendFunc(GL_ONE, GL_ONE); lightchanged[UPDATE_TEX] = GL_TRUE; lightchanged[UPDATE_OGL] = GL_TRUE; /* load pattern for current 2d texture */ tex = read_texture("../data/wood.rgb", &texwid, &texht, &texcomps); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, texwid, texht, GL_RGBA, GL_UNSIGNED_BYTE, tex); free(tex); CHECK_ERROR("end of main"); lighttex = (GLfloat *)malloc(texdim * texdim * sizeof(GL_FLOAT) * 3); /* XXX TODO use display list to avoid retesselating */ glNewList(1, GL_COMPILE); glutSolidSphere((GLdouble)texdim/2., 50, 50); glEndList(); glNewList(2, GL_COMPILE); glutSolidTeapot(70.); glEndList(); quadric = gluNewQuadric(); gluQuadricTexture(quadric, GL_TRUE); glNewList(3, GL_COMPILE); gluSphere(quadric, 70., 20, 20); glEndList(); gluDeleteQuadric(quadric); maxobject = 3; glutMainLoop(); return 0; }
void display(int d) { int i; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if(lock) { if(eye[0] < -23.0 - 28.0*tan(M_PI/6)) eye[0] = -23.0 - 28.0*tan(M_PI/6); if(eye[0] > 33.0) eye[0] = 33.0; if(eye[1] < -28.0 - 26.5*tan(M_PI/6)) eye[1] = -28.0 - 26.5*tan(M_PI/6); if(eye[1] > 25.0) eye[1] = 25.0; if(eye[2] < -25.0) eye[2] = -25.0; if(eye[2] > 51.0 + 65.0*tan(M_PI/6)) eye[2] = 51.0 + 65.0*tan(M_PI/6); } if(!helmet) { for(i=0; i < 3; i++) view[i] = (2 * negview * eye[i]); up[0] = 0; up[1] = negup * 1.0; up[2] = 0; } if(d==D_LEFT) { glTranslatef(-2.5, 0.0, 0.0); } else if(d==D_RIGHT) { glTranslatef(2.5, 0.0, 0.0); } gluLookAt(eye[0], eye[1], eye[2], view[0], view[1], view[2], up[0], up[1], up[2]); glTranslatef(global_translate[0], global_translate[1], global_translate[2]); glPushAttrib(GL_ALL_ATTRIB_BITS); glPushMatrix(); /* glRotatef(theta, 0.0, 1.0, 0.0); glRotatef(phi, 1.0, 0.0, 0.0);*/ glColor3f(1.0, 1.0, 1.0); if(wireframe) { glPolygonMode(GL_FRONT, GL_LINE); glDisable(GL_CULL_FACE); } else { glPolygonMode(GL_FRONT, GL_FILL); glEnable(GL_CULL_FACE); } /* Draw coordinate axes */ glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); if(axes) { glPushMatrix(); glTranslatef(-global_translate[0], -global_translate[1], -global_translate[2]); glBegin(GL_LINES); glVertex3f(-100.0, 0.0, 0.0); glVertex3f(100.0, 0.0, 0.0); glVertex3f(0.0, -100.0, 0.0); glVertex3f(0.0, 100.0, 0.0); glVertex3f(0.0, 0.0, -100.0); glVertex3f(0.0, 0.0, 100.0); glEnd(); glPopMatrix(); } if(texture) glEnable(GL_TEXTURE_2D); if(lighting) glEnable(GL_LIGHTING); if(!smooth) {glDisable(GL_SMOOTH); glShadeModel(GL_FLAT); glEnable(GL_FLAT);} else {glDisable(GL_FLAT); glShadeModel(GL_SMOOTH); glEnable(GL_SMOOTH);} if(filtering) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } draw_scene(); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); if(terrain) draw_terrain(); /* Draw w/o lighting */ if(stars) draw_stars(); glPopMatrix(); glPopAttrib(); /* And swap buffers to display the image */ glutSwapBuffers(); /* if(helmet) child(1);*/ }
void DrawParabolicMapWithCube() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-width, width, -height, height, -100000, 100000); gluLookAt(0, 0, 1, 0, 0, 0, 0, -1, 0); glViewport(0, 0, width * 2, height * 2); glScissor(0, 0, width * 2, height * 2); glClearColor(1,1,1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); double showMapPoints[LOD+1][LOD+1][2]; double showMapTexCoords[LOD+1][LOD+1][2]; for (int i = 0; i <= LOD; i++) { float x = i * 1.0 / LOD; for (int j = 0; j <= LOD; j++) { float y = j * 1.0 / LOD; showMapPoints[i][j][0] = x * width; showMapPoints[i][j][1] = y * height; float parabolic_x, parabolic_y, parabolic_z; // float parabolic_x = ((mapped.x / (2 * (1 + mapped.z))) + 0.5) / 2; // float parabolic_y = (-mapped.y / (2 * (1 + mapped.z))) + 0.5; // float parabolic_z = (1 - parabolic_x * parabolic_x + parabolic_y * parabolic_y) / 2; if (i < LOD / 2) { parabolic_x = (2 * x - 0.5) * 2; parabolic_y = -(2 * y - 1); parabolic_z = (1 - (parabolic_x * parabolic_x + parabolic_y * parabolic_y)) / 2; } else { parabolic_x = (2 * (x - 0.5) - 0.5) * 2; parabolic_y = -(2 * y - 1); parabolic_z = -(1 - (parabolic_x * parabolic_x + parabolic_y * parabolic_y)) / 2; } // printf("para : %f, %f, %f\n",parabolic_x, parabolic_y, parabolic_z); Vector3d mapped = Vector3d(parabolic_x, parabolic_y, parabolic_z); mapped.normalize(); float padding_y = 1/3.0; float padding_x = 1/4.0; if (mapped.x >= std::abs(mapped.y) && mapped.x >= std::abs(mapped.z)) { // right showMapTexCoords[i][j][0] = (-mapped.z / mapped.x + 1) / 2 / 4 + padding_x * 2; showMapTexCoords[i][j][1] = (-mapped.y / mapped.x + 1) / 2 / 3 + padding_y; } else if (mapped.y >= std::abs(mapped.x) && mapped.y >= std::abs(mapped.z)) { // top showMapTexCoords[i][j][0] = (mapped.x / mapped.y + 1) / 2 / 4 + padding_x; showMapTexCoords[i][j][1] = (mapped.z / mapped.y + 1) / 2 / 3; } else if (mapped.z >= std::abs(mapped.x) && mapped.z >= std::abs(mapped.y)) { // front showMapTexCoords[i][j][0] = (mapped.x / mapped.z + 1) / 2 / 4 + padding_x; showMapTexCoords[i][j][1] = (-mapped.y / mapped.z + 1) / 2 / 3 + padding_y; } else if (mapped.x <= -std::abs(mapped.y) && mapped.x <= -std::abs(mapped.z)) { // left showMapTexCoords[i][j][0] = (-mapped.z / mapped.x + 1) / 2 / 4; showMapTexCoords[i][j][1] = (mapped.y / mapped.x + 1) / 2 / 3 + padding_y; } else if (mapped.y <= -std::abs(mapped.x) && mapped.y <= -std::abs(mapped.z)) { // bottom showMapTexCoords[i][j][0] = (-mapped.x / mapped.y + 1) / 2 / 4 + padding_x; showMapTexCoords[i][j][1] = (mapped.z / mapped.y + 1) / 2 / 3 + padding_y * 2; } else if (mapped.z <= -std::abs(mapped.x) && mapped.z <= -std::abs(mapped.y)) { // back showMapTexCoords[i][j][0] = (mapped.x / mapped.z + 1) / 2 / 4 + padding_x * 3; showMapTexCoords[i][j][1] = (mapped.y / mapped.z + 1) / 2 / 3 + padding_y; } // showMapTexCoords[i][j][0] = x; // showMapTexCoords[i][j][1] = y; } } glEnable(GL_TEXTURE_2D); for (int i = 0; i < LOD; i++) { glBegin(GL_QUAD_STRIP); for (int j = 0; j < LOD; j++) { glTexCoord2dv(showMapTexCoords[i][j]); glVertex2dv(showMapPoints[i][j]); glTexCoord2dv(showMapTexCoords[i + 1][j]); glVertex2dv(showMapPoints[i + 1][j]); } glEnd(); } glDisable(GL_TEXTURE_2D); return; }
//setting a camera position and what does camera look at will change depends on it's position0 void SetCamera(void) { gluLookAt(camX, camY, camZ, camX + focX, camY + focY, camZ + focZ + 0.5, 0.0,1.0,0.0); }
//---------------------------------------------------------- void ofGLRenderer::setupScreenPerspective(float width, float height, int orientation, bool vFlip, float fov, float nearDist, float farDist) { if(width == 0) width = ofGetWidth(); if(height == 0) height = ofGetHeight(); if( orientation == 0 ) orientation = ofGetOrientation(); float w = width; float h = height; //we do this because ofGetWidth and ofGetHeight return orientated widths and height //for the camera we need width and height of the actual screen if( orientation == OF_ORIENTATION_90_LEFT || orientation == OF_ORIENTATION_90_RIGHT ){ h = width; w = height; } float eyeX = w / 2; float eyeY = h / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float aspect = (float) w / h; if(nearDist == 0) nearDist = dist / 10.0f; if(farDist == 0) farDist = dist * 10.0f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, aspect, nearDist, farDist); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0); //note - theo checked this on iPhone and Desktop for both vFlip = false and true switch(orientation) { case OF_ORIENTATION_180: glRotatef(-180, 0, 0, 1); if(vFlip){ glScalef(1, -1, 1); glTranslatef(-width, 0, 0); }else{ glTranslatef(-width, -height, 0); } break; case OF_ORIENTATION_90_RIGHT: glRotatef(-90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); }else{ glScalef(-1, -1, 1); glTranslatef(0, -height, 0); } break; case OF_ORIENTATION_90_LEFT: glRotatef(90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); glTranslatef(-width, -height, 0); }else{ glScalef(-1, -1, 1); glTranslatef(-width, 0, 0); } break; case OF_ORIENTATION_DEFAULT: default: if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } break; } }