Camera::Camera(const std::string& name, const int w, const int h) : name(name), width(w), height(h), n_points(0), color(std::array<float, 3>{0, 1, 0}) { glGenFramebuffers(fbo.size(), fbo.data()); glGenRenderbuffers(rbo.size(), rbo.data()); glBindRenderbuffer(GL_RENDERBUFFER, rbo[0]); glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB, width, height); glBindRenderbuffer(GL_RENDERBUFFER, rbo[1]); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, fbo[0]); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo[0]); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo[1]); glBindFramebuffer(GL_FRAMEBUFFER, 0); look_at(0, 2, -0.5, 0, 0.5, 0, 0, 1, 0); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(49.8, static_cast<double>(width) / height, 0.1, 100); glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix.data()); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glGenVertexArrays(vao.size(), vao.data()); glGenBuffers(vbo.size(), vbo.data()); }
/* Update Method */ void Camera::update() { // It makes the 360 rotation work if(this->angle < 360) { GLfloat x = this->direction.v[0]; GLfloat y = this->direction.v[2]; this->direction.v[0] = x * cosf(this->angle * ONE_DEG_IN_RAD) - y * sinf(this->angle * ONE_DEG_IN_RAD); this->direction.v[2] = x * sinf(this->angle * ONE_DEG_IN_RAD) + y * cosf(this->angle * ONE_DEG_IN_RAD); this->angle += this->rotation_speed; } else { this->angle = 360.0f; this->initial_rotation = GL_FALSE; } /* Setting my LookAt function properties */ // It gets the direction that the target is looking at and with this, the camera looks at the correct position camera_position = this->target - this->direction * this->back_offset + vec3(0.0f, this->camera_y, 0.0f); camera_target = this->target + this->direction * this->front_offset; vec3 v = camera_target - camera_position; vec3 u = vec3(0.0f, this->camera_y, 0.0f); vec3 cros_u_v = cross(v, u); camera_up = normalise(cross(cros_u_v, v)); *this->view_matrix = look_at(camera_position, camera_target, camera_up); }
//-------------------------------------------------------------------------------- // update for back-mode //-------------------------------------------------------------------------------- bool zz_camera_follow::update_backmode (void) { // apply yaw factor to target_dir apply_yaw(final_.camera_dir, current_.yaw, final_.target_dir); // camera_dir interpolation. *pitch* was not yet applied to the camera_dir. final_.camera_dir = last_.camera_dir + time_weight_*(final_.camera_dir - last_.camera_dir); final_.camera_dir.normalize(); // use not-pitched target direction only for backmode last_.camera_dir = final_.camera_dir; // apply pitch. // CAUTION: must call apply_pitch() after camera_dir interpolation apply_pitch(final_.camera_dir, current_.pitch); // apply distance final_.camera_pos = final_.target_pos - current_.distance * final_.camera_dir; // recalc camera & target position final_.camera_pos = last_.camera_pos + time_weight_*(final_.camera_pos - last_.camera_pos); final_.target_pos = last_.target_pos + time_weight_*(final_.target_pos - last_.target_pos); look_at(final_.camera_pos, final_.target_pos, vec3(0, 0, 1)); // save last_target_pos for look_mode last_.target_pos = final_.target_pos; last_.camera_pos = final_.camera_pos; return true; }
void Compositor::render_shadowmap(Viewer& viewer) { OpenGLState state; glViewport(0, 0, g_shadowmap->get_width(), g_shadowmap->get_height()); glClearColor(1.0, 0.0, 1.0, 1.0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glm::vec3 light_pos = glm::rotate(glm::vec3(10.0f, 10.0f, 10.0f), viewer.m_cfg.m_light_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::vec3 up = glm::rotate(glm::vec3(0.0f, 1.0f, 0.0f), viewer.m_cfg.m_light_up, glm::vec3(0.0f, 0.0f, 1.0f)); glm::vec3 look_at(0.0f, 0.0f, 0.0f); Camera camera; camera.perspective(viewer.m_cfg.m_shadowmap_fov, 1.0f, viewer.m_cfg.m_near_z, viewer.m_cfg.m_far_z); //camera.ortho(-25.0f, 25.0f, -25.0f, 25.0f, m_near_z, m_far_z); camera.look_at(light_pos, look_at, up); g_shadowmap_matrix = glm::mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0); g_shadowmap_matrix = g_shadowmap_matrix * camera.get_matrix(); viewer.m_scene_manager->render(camera, true); }
void zz_camera_follow::update_camera_collision() { // get adjusted distance value by camera to target ray. float adjusted_distance; bool contacted = false; get_target_pos(final_.target_pos); if (collision_level != ZZ_CL_NONE) { contacted = get_distance_by_contact_point(adjusted_distance); } if (contacted) { current_.distance = adjusted_distance; // re-adjust by changed follow_distance_current final_.camera_pos = last_.target_pos - current_.distance * final_.camera_dir; look_at(final_.camera_pos, last_.target_pos, vec3(0, 0, 1)); last_.camera_pos = final_.camera_pos; // for back-mode } // if we have almost done our job, then do not update anymore. if ((FABS(current_.distance - last_.distance) < EPSILON_DISTANCE) && (FABS(current_.pitch - last_.pitch) < EPSILON_PITCH) && (FABS(current_.yaw - last_.yaw) < EPSILON_YAW)) { // onli for look mode // we have almost done out job, take a rest. is_dirty_ = false; // not to updated again if(camera_effect_onoff) stop_camera_effect(); } }
void camera::view_all(aabb const& box, vec3 const& up) { float diagonal = length(box.size()); float r = diagonal * 0.5f; vec3 eye = box.center() + vec3(0, 0, r + r / std::atan(fovy_)); look_at(eye, box.center(), up); }
/* * Alternate view matrix generator: * Takes (X, Y, Z) rotation instead of a point to look at. * Generate rotational matrix by rotating a +Z-axis unit vector * around Y, then X and generating a view matrix for that target. * For now, Z rotation will be ignored. * Also generate an 'up' vector from a +Y-axis unit fector rotated by Y, then X. */ m4 look_at(v3 pos, v3 t_angles) { v4 unit_direction(0.0f, 0.0f, 1.0f, 1.0f); v4 up_direction(0.0f, 1.0f, 0.0f, 1.0f); m4 ry = rotate_y(t_angles.v[1]); unit_direction = ry * unit_direction; up_direction = ry * up_direction; m4 rx = rotate_x(t_angles.v[0]); unit_direction = rx * unit_direction; up_direction = rx * up_direction; v3 t_vec = pos + unit_direction; return look_at(pos, t_vec, up_direction); }
void computeMatricesFromInputs(){ if(cam_moved) { } // glfwGetTime is called only once, the first time this function is called // static double lastTime = timeGetTime(); // Compute time difference between current and last frame // double currentTime = timeGetTime(); // delta_time = float(currentTime - lastTime); // clamp rotation angle between 0 - 2*PI // if (horizontalAngle > 3.14f*2) horizontalAngle = 0; // if (horizontalAngle < 0) horizontalAngle = 3.14f*2; // clamp camera up/down values so we can't go upside down // if (verticalAngle >= 3.14f/2.0f) verticalAngle = 3.14f/2.0f; // if (verticalAngle <= -3.14f/2.0f) verticalAngle = -3.14f/2.0f; // Direction : Spherical coordinates to Cartesian coordinates conversion float FoV = initialFoV - 5 * SDL_MOUSEWHEEL; direction = vec3( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); // Right vector right = vec3( sin(horizontalAngle - 3.14f/2.0f), 0, cos(horizontalAngle - 3.14f/2.0f) ); // Up vector up = cross( right, direction ); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f); // Camera matrix ViewMatrix= look_at(position, // Camera is here position+direction, // and looks here : at the same position, plus "direction" up // Head is up (set to 0,-1,0 to look upside-down) ); cam_moved = false; // For the next frame, the "last time" will be "now" // lastTime = currentTime; }
void render_scene(void) { float angle = timer.GetElapsedSeconds() * 3.14f / 10.0f; location[0] = -8.0f * cos(angle / 2.0f); location[1] = -8.0f * sin(angle / 2.0f); location[2] = 5.0f; light_0.position[0] = 10.0f * cos(-angle); light_0.position[1] = 10.0f * sin(-angle); light_0.position[2] = 3.0f; look_at(camera_frame, location, target, up_dir); camera_frame.GetCameraMatrix(camera_matrix); p_stack.LoadMatrix(view_frustum.GetProjectionMatrix()); mv_stack.LoadMatrix(camera_matrix); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); //-- glUseProgram(shader_color); mv_stack.PushMatrix(); mv_stack.Translate(light_0.position[0], light_0.position[1], light_0.position[2]); mv_stack.Scale(0.25f, 0.25f, 0.25f); glUniformMatrix4fv(mvp_matrix_location_shader_color, 1, GL_FALSE, geometry_pipeline.GetModelViewProjectionMatrix()); draw_light(); mv_stack.PopMatrix(); //-- glUseProgram(shader_light); glUniformMatrix3fv(normal_matrix_location, 1, GL_FALSE, geometry_pipeline.GetNormalMatrix()); glUniformMatrix4fv(v_matrix_location, 1, GL_FALSE, camera_matrix); glUniform3fv(intensity_ambient_component_location, 1, intensity_ambient_component); glUniform3fv(light_0_position_location, 1, light_0.position); glUniform3fv(light_0_intensity_diffuse_location, 1, light_0.intensity_diffuse); glUniform3fv(light_0_intensity_specular_location, 1, light_0.intensity_specular); glUniform3fv(light_0_attenuation_location, 1, light_0.attenuation); glUniform1f(material_0_ka_location, material_0.ka); glUniform1f(material_0_kd_location, material_0.kd); glUniform1f(material_0_ks_location, material_0.ks); glUniform1f(material_0_alpha_location, material_0.alpha); //-- for(int i = -10; i <= 10; i += 3) for(int j = -10; j <= 10; j += 3) { mv_stack.PushMatrix(); mv_stack.Translate(i, j, 0.0f); glUniformMatrix4fv(mvp_matrix_location, 1, GL_FALSE, geometry_pipeline.GetModelViewProjectionMatrix()); glUniformMatrix4fv(mv_matrix_location, 1, GL_FALSE, geometry_pipeline.GetModelViewMatrix()); glDrawElements(GL_TRIANGLES, faces.size(), GL_UNSIGNED_INT, 0); mv_stack.PopMatrix(); } //-- glUseProgram(0); glutSwapBuffers(); glutPostRedisplay(); }
void CameraObject::focus_at (const Vector3 &to, const Vector3 &up, const DTfloat radius) { look_at (to, up); Vector3 diff; DTfloat dist; diff = to - translation(); dist = diff.abs(); _angle = RAD_TO_DEG * 2.0F * std::atan(radius / dist); // Keep from getting too small if (_angle < 0.1F) _angle = 0.1F; }
void update() { if (targetCamera) view = look_at(position, target, Vector3f(0.f, 1.f, 0.f)); else { Vector4f p = invert(view) * Vector4f(0.f, 0.f, 0.f, 1.f); p /= p.w; position = p.xyz(); } Matrix4x4f m = perspective(fov, 1.f, 0.1f, 100.f) * view; viewToClip = m; clipToView = viewToClip; clipToView.invert(); }
void TestScene3::runPanda(int argc, char** argv) { // initialize framework PandaFramework framework; framework.open_framework(argc, argv); // open window WindowProperties windowProp; framework.get_default_window_props(windowProp); windowProp.set_size(800, 600); auto window = framework.open_window(windowProp, GraphicsPipe::BF_require_window); // adjust camera auto camera = window->get_camera_group(); camera.set_pos(2000, -2000, 2000); camera.look_at(0, 0, 0); // loop framework.main_loop(); }
//-------------------------------------------------------------------------------- // attach target //-------------------------------------------------------------------------------- bool zz_camera_follow::attach_target (zz_model * target_vis) { if (!target_vis) { ZZ_LOG("camera_follow: attach_target() failed. target not found\n"); return false; } if (target_ == target_vis) return true; target_ = target_vis; get_target_pos(final_.target_pos); look_at(final_.target_pos + INITIAL_CAMERA_POS_AT_ATTACH, final_.target_pos, vec3(0, 0, 1)); newly_attached_ = true; final_.camera_pos = get_eye(); last_.camera_pos = final_.camera_pos; last_.target_pos = final_.target_pos; is_dirty_ = true; return true; }
void set_main_view(const void *data) { float eye[3] = {0.0, 10.0, -8.0}; float view[3] = {0.0, 2.8, 3.0}; const struct wam *wam; struct marfitude_pos pos; if(data) {} marfitude_get_pos(&pos); wam = marfitude_get_wam(); view_focus = (double)wam->num_cols / 2.0 - 0.5; view[2] = TIC_HEIGHT * pos.tic; eye[2] = view[2] - 12.0; glLoadIdentity(); look_at(eye[0] - view_focus * BLOCK_WIDTH, eye[1], eye[2], view[0] - view_focus * BLOCK_WIDTH, view[1], view[2], 0.0, 1.0, 0.0); }
void TestScene5::runPanda(int argc, char** argv) { // initialize framework PandaFramework framework; framework.open_framework(argc, argv); // open window WindowProperties windowProp; framework.get_default_window_props(windowProp); windowProp.set_size(800, 600); auto window = framework.open_window(windowProp, GraphicsPipe::BF_require_window); // adjust camera auto camera = window->get_camera_group(); camera.set_pos(2000, -2000, 2000); camera.look_at(LPoint3(0, 0, 0)); // load & integrate model auto model = window->load_model(framework.get_models(), "panda-model"); model.set_pos(-2000, 2000, -2000); model.reparent_to(window->get_render()); // loop framework.main_loop(); }
bool zz_camera_follow::apply_shake (zz_time diff_time) { if (shake_lifetime == 0) return false; if (shake_lifetime <= diff_time) { shake_lifetime = 0; // do not modify return true; } else { shake_lifetime -= diff_time; } vec3 shakeed_cam_pos, shakeed_target_pos; vec3 shake_min_shrinked(shake_min), shake_max_shrinked(shake_max); shakeed_cam_pos = random_number(final_.camera_pos + shake_min_shrinked, final_.camera_pos + shake_max_shrinked); shakeed_target_pos = random_number(last_.target_pos + shake_min_shrinked, last_.target_pos + shake_max_shrinked); look_at(shakeed_cam_pos, shakeed_target_pos, vec3(0, 0, 1)); return true; }
int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint cube_sp, knot_sp; GLuint vao; // // Start OpenGL using helper libraries // -------------------------------------------------------------------------- if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); */ glfwWindowHint (GLFW_SAMPLES, msaa); window = glfwCreateWindow (gl_width, gl_height, "{quadratic bezier}", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: opening OS window\n"); return 1; } glfwMakeContextCurrent (window); glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); int point_count = 0; // // Set up vertex buffers and vertex array object // -------------------------------------------------------------------------- { GLfloat* vp = NULL; // array of vertex points GLfloat* vn = NULL; // array of vertex normals (we haven't used these yet) GLfloat* vt = NULL; // array of texture coordinates (or these) assert (load_obj_file ("smcube.obj", vp, vt, vn, point_count)); GLuint points_vbo, texcoord_vbo, normal_vbo; glGenBuffers (1, &points_vbo); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 3 * point_count, vp, GL_STATIC_DRAW); glGenBuffers (1, &texcoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 2 * point_count, vt, GL_STATIC_DRAW); glGenBuffers (1, &normal_vbo); glBindBuffer (GL_ARRAY_BUFFER, normal_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 3 * point_count, vn, GL_STATIC_DRAW); glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (2); glBindBuffer (GL_ARRAY_BUFFER, normal_vbo); glVertexAttribPointer (2, 3, GL_FLOAT, GL_FALSE, 0, NULL); free (vp); free (vn); free (vt); } // // Load shaders from files // -------------------------------------------------------------------------- { char* vertex_shader_str; char* fragment_shader_str; // allocate some memory to store shader strings vertex_shader_str = (char*)malloc (81920); fragment_shader_str = (char*)malloc (81920); // load shader strings from text files assert (parse_file_into_str ("cube.vert", vertex_shader_str, 81920)); assert (parse_file_into_str ("cube.frag", fragment_shader_str, 81920)); GLuint vs, fs; vs = glCreateShader (GL_VERTEX_SHADER); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (vs, 1, (const char**)&vertex_shader_str, NULL); glShaderSource (fs, 1, (const char**)&fragment_shader_str, NULL); // free memory free (vertex_shader_str); free (fragment_shader_str); glCompileShader (vs); glCompileShader (fs); cube_sp = glCreateProgram (); glAttachShader (cube_sp, fs); glAttachShader (cube_sp, vs); glBindAttribLocation (cube_sp, 0, "vp"); glBindAttribLocation (cube_sp, 1, "vt"); glBindAttribLocation (cube_sp, 2, "vn"); glLinkProgram (cube_sp); } { char* vertex_shader_str; char* fragment_shader_str; // allocate some memory to store shader strings vertex_shader_str = (char*)malloc (81920); fragment_shader_str = (char*)malloc (81920); // load shader strings from text files assert (parse_file_into_str ("knot.vert", vertex_shader_str, 81920)); assert (parse_file_into_str ("knot.frag", fragment_shader_str, 81920)); GLuint vs, fs; vs = glCreateShader (GL_VERTEX_SHADER); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (vs, 1, (const char**)&vertex_shader_str, NULL); glShaderSource (fs, 1, (const char**)&fragment_shader_str, NULL); // free memory free (vertex_shader_str); free (fragment_shader_str); glCompileShader (vs); glCompileShader (fs); knot_sp = glCreateProgram (); glAttachShader (knot_sp, fs); glAttachShader (knot_sp, vs); glLinkProgram (knot_sp); } // // Create some matrices // -------------------------------------------------------------------------- mat4 M, V, P; M = identity_mat4 ();//scale (identity_mat4 (), vec3 (0.05, 0.05, 0.05)); vec3 cam_pos (0.0, 0.0, 15.0); vec3 targ_pos (0.0, 0.0, 0.0); vec3 up = normalise (vec3 (0.0, 1.0, 0.0)); V = look_at (cam_pos, targ_pos, up); P = perspective (67.0f, (float)gl_width / (float)gl_height, 0.1, 1000.0); int M_loc = glGetUniformLocation (cube_sp, "M"); int V_loc = glGetUniformLocation (cube_sp, "V"); int P_loc = glGetUniformLocation (cube_sp, "P"); int A_loc = glGetUniformLocation (cube_sp, "A"); int B_loc = glGetUniformLocation (cube_sp, "B"); int C_loc = glGetUniformLocation (cube_sp, "C"); int t_loc = glGetUniformLocation (cube_sp, "t"); // send matrix values to shader immediately glUseProgram (cube_sp); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glUniformMatrix4fv (V_loc, 1, GL_FALSE, V.m); glUniformMatrix4fv (P_loc, 1, GL_FALSE, P.m); // // specific knots for bezier here A, C are start, end, B is control point // vec3 A = vec3 (-7.0f, -5.0f, 0.0f); vec3 B = vec3 (0.0f, 8.0f, 0.0f); vec3 C = vec3 (7.0f, -5.0f, 0.0f); glUniform3fv (A_loc, 1, A.v); glUniform3fv (B_loc, 1, B.v); glUniform3fv (C_loc, 1, C.v); int knot_loc = glGetUniformLocation (knot_sp, "pos"); int knotP_loc = glGetUniformLocation (knot_sp, "P"); int knotV_loc = glGetUniformLocation (knot_sp, "V"); glUseProgram (knot_sp); glUniformMatrix4fv (knotV_loc, 1, GL_FALSE, V.m); glUniformMatrix4fv (knotP_loc, 1, GL_FALSE, P.m); // // Start rendering // -------------------------------------------------------------------------- // tell GL to only draw onto a pixel if the fragment is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" glDepthFunc (GL_LESS); // depth-testing is to use a "less than" function glEnable (GL_CULL_FACE); // enable culling of faces glCullFace (GL_BACK); glFrontFace (GL_CCW); glClearColor (0.04, 0.04, 0.75, 1.0); /* Render Points, allow resize in vertex shader */ glEnable (GL_PROGRAM_POINT_SIZE); glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT); float t = 0.0f; float speed = 0.5f; double prev = glfwGetTime (); while (!glfwWindowShouldClose (window)) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // just the default viewport, covering the whole render area glViewport (0, 0, gl_width, gl_height); double curr = glfwGetTime (); double elapsed = curr - prev; prev = curr; // // move along spline if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_LEFT)) { t -= elapsed * speed; if (t < 0.0f) { t = 0.0f; } } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_RIGHT)) { t += elapsed * speed; if (t > 1.0f) { t = 1.0f; } } // // render 3 knots glEnable (GL_PROGRAM_POINT_SIZE); glUseProgram (knot_sp); glUniform3fv (knot_loc, 1, A.v); glDrawArrays (GL_POINTS, 0, 1); glUseProgram (knot_sp); glUniform3fv (knot_loc, 1, B.v); glDrawArrays (GL_POINTS, 0, 1); glUseProgram (knot_sp); glUniform3fv (knot_loc, 1, C.v); glDrawArrays (GL_POINTS, 0, 1); glDisable (GL_PROGRAM_POINT_SIZE); glUseProgram (cube_sp); glBindVertexArray (vao); M = identity_mat4 ();//rotate_y_deg (identity_mat4 (), a); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glUniform1f (t_loc, t); glDrawArrays (GL_TRIANGLES, 0, point_count); /* this just updates window events and keyboard input events (not used yet) */ glfwPollEvents (); glfwSwapBuffers (window); } return 0; }
int main () { assert (restart_gl_log ()); assert (start_gl ()); /* set up framebuffer with texture attachment */ assert (init_fb ()); init_ss_quad (); /* load the post-processing effect shaders */ GLuint post_sp = create_programme_from_files (POST_VS, POST_FS); /* load a mesh to draw in the main scene */ load_sphere (); GLuint sphere_sp = create_programme_from_files (SPHERE_VS, SPHERE_FS); GLint sphere_P_loc = glGetUniformLocation (sphere_sp, "P"); GLint sphere_V_loc = glGetUniformLocation (sphere_sp, "V"); assert (sphere_P_loc > -1); assert (sphere_V_loc > -1); /* set up view and projection matrices for sphere shader */ mat4 P = perspective ( 67.0f, (float)g_gl_width / (float)g_gl_height, 0.1f, 100.0f); mat4 V = look_at ( vec3 (0.0f, 0.0f, 5.0f), vec3 (0.0f, 0.0f, 0.0f), vec3 (0.0f, 1.0f, 0.0f)); glUseProgram (sphere_sp); glUniformMatrix4fv (sphere_P_loc, 1, GL_FALSE, P.m); glUniformMatrix4fv (sphere_V_loc, 1, GL_FALSE, V.m); glViewport (0, 0, g_gl_width, g_gl_height); while (!glfwWindowShouldClose (g_window)) { _update_fps_counter (g_window); /* bind the 'render to a texture' framebuffer for main scene */ glFlush (); glFinish (); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, 0); glBindFramebuffer (GL_FRAMEBUFFER, g_fb); /* clear the framebuffer's colour and depth buffers */ glClearColor (0.2, 0.2, 0.2, 1.0); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render an obj or something glUseProgram (sphere_sp); glBindVertexArray (g_sphere_vao); glDrawArrays (GL_TRIANGLES, 0, g_sphere_point_count); /* bind default framebuffer for post-processing effects. sample texture from previous pass */ glFlush (); glFinish (); glBindFramebuffer (GL_FRAMEBUFFER, 0); // clear the framebuffer's colour and depth buffers // glClearColor (0.0, 0.0, 0.0, 1.0); // glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // use our post-processing shader for the screen-space quad glUseProgram (post_sp); // bind the quad's VAO glBindVertexArray (g_ss_quad_vao); // activate the first texture slot and put texture from previous pass in it glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, g_fb_tex); // draw the quad that covers the screen area glDrawArrays (GL_TRIANGLES, 0, 6); // flip drawn framebuffer onto the display glfwSwapBuffers (g_window); glfwPollEvents (); if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (g_window, 1); } } return 0; }
int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint shader_programme; GLuint vao; // // Start OpenGL using helper libraries // -------------------------------------------------------------------------- if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); */ window = glfwCreateWindow (gl_width, gl_height, "Spinning Cube", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: opening OS window\n"); return 1; } glfwMakeContextCurrent (window); glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); int point_count = 0; // // Set up vertex buffers and vertex array object // -------------------------------------------------------------------------- { GLfloat* vp = NULL; // array of vertex points GLfloat* vn = NULL; // array of vertex normals (we haven't used these yet) GLfloat* vt = NULL; // array of texture coordinates (or these) assert (load_obj_file ("cube.obj", vp, vt, vn, point_count)); GLuint points_vbo, texcoord_vbo; glGenBuffers (1, &points_vbo); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); // copy our points from the header file into our VBO on graphics hardware glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 3 * point_count, vp, GL_STATIC_DRAW); // and grab the normals glGenBuffers (1, &texcoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 2 * point_count, vt, GL_STATIC_DRAW); glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); free (vp); free (vn); free (vt); } // // Load shaders from files // -------------------------------------------------------------------------- { char* vertex_shader_str; char* fragment_shader_str; // allocate some memory to store shader strings vertex_shader_str = (char*)malloc (81920); fragment_shader_str = (char*)malloc (81920); // load shader strings from text files assert (parse_file_into_str ("teapot.vert", vertex_shader_str, 81920)); assert (parse_file_into_str ("teapot.frag", fragment_shader_str, 81920)); GLuint vs, fs; vs = glCreateShader (GL_VERTEX_SHADER); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (vs, 1, (const char**)&vertex_shader_str, NULL); glShaderSource (fs, 1, (const char**)&fragment_shader_str, NULL); // free memory free (vertex_shader_str); free (fragment_shader_str); glCompileShader (vs); glCompileShader (fs); shader_programme = glCreateProgram (); glAttachShader (shader_programme, fs); glAttachShader (shader_programme, vs); glLinkProgram (shader_programme); /* TODO NOTE: you should check for errors and print logs after compiling and also linking shaders */ } // // Create some matrices // -------------------------------------------------------------------------- mat4 M, V, P; M = identity_mat4 ();//scale (identity_mat4 (), vec3 (0.05, 0.05, 0.05)); vec3 cam_pos (0.0, 0.0, 5.0); vec3 targ_pos (0.0, 0.0, 0.0); vec3 up (0.0, 1.0, 0.0); V = look_at (cam_pos, targ_pos, up); P = perspective (67.0f, (float)gl_width / (float)gl_height, 0.1, 1000.0); int M_loc = glGetUniformLocation (shader_programme, "M"); int V_loc = glGetUniformLocation (shader_programme, "V"); int P_loc = glGetUniformLocation (shader_programme, "P"); // send matrix values to shader immediately glUseProgram (shader_programme); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glUniformMatrix4fv (V_loc, 1, GL_FALSE, V.m); glUniformMatrix4fv (P_loc, 1, GL_FALSE, P.m); int dt_pixel_c = 16 * 16; char* dt_data = (char*)malloc (4 * dt_pixel_c); if (!dt_data) { fprintf (stderr, "ERROR: out of memory. malloc default texture\n"); return 1; } for (int i = 0; i < dt_pixel_c * 4; i += 4) { int sq_ac = i / 16; if ((sq_ac / 2) * 2 == sq_ac) { dt_data[i] = 0; dt_data[i + 1] = 0; dt_data[i + 2] = 0; dt_data[i + 3] = (char)255; } else { dt_data[i] = (char)255; dt_data[i + 1] = 0; dt_data[i + 2] = (char)255; dt_data[i + 3] = (char)255; } int sq_dn = i / (16 * 16); if ((sq_dn / 2) * 2 == sq_dn) { dt_data[i] = (char)255 - dt_data[i]; dt_data[i + 2] = (char)255 - dt_data[i + 2]; } } GLuint tex; glGenTextures (1, &tex); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, tex); int x,y,n; unsigned char *data = stbi_load ("move_me.png", &x, &y, &n, 4); if (!data) { fprintf (stderr, "ERROR: could not load image 'move_me.png'. using default texture\n"); glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, dt_data ); } else { glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); stbi_image_free(data); data = NULL; printf ("loaded image with [%i,%i] res and %i chans\n", x, y, n); } glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); free (dt_data); dt_data = NULL; // */ // // Start rendering // -------------------------------------------------------------------------- // tell GL to only draw onto a pixel if the fragment is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" glClearColor (0.01, 0.01, 0.25, 1.0); float a = 0.0f; double prev = glfwGetTime (); while (!glfwWindowShouldClose (window)) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // just the default viewport, covering the whole render area glViewport (0, 0, gl_width, gl_height); double curr = glfwGetTime (); double elapsed = curr - prev; prev = curr; glUseProgram (shader_programme); glBindVertexArray (vao); a += sinf (elapsed * 50.0f); M = rotate_y_deg (identity_mat4 (), a); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glDrawArrays (GL_TRIANGLES, 0, point_count); /* this just updates window events and keyboard input events (not used yet) */ glfwPollEvents (); glfwSwapBuffers (window); } return 0; }
//----------------------------------------------------------------------------- void MyGlDraw(void) { clearScreen(); //************************************************************************* // Chame aqui as funções do mygl.h //************************************************************************* objData = new objLoader(); // cria o objeto que carrega o modelo objData->load("models/monkey_head2.obj"); // a carga do modelo é indicada atraves do nome do arquivo. // Neste caso, deve ser sempre do tipo OBJ. /**************creating the list of all vertexs**********************/ std::vector<glm::vec4> vertex_list; std::vector<Vertex> my_list; obj_vector* vector; obj_face* faces; //std::cout<<"object vertex list"<<std::endl; for (int i = 0; i < objData->vertexCount; ++i) { vector = objData->vertexList[i]; glm::vec4 aux(vector->e[0], vector->e[1], vector->e[2], 1.0); //PrintVec4(aux); vertex_list.push_back(aux); } /******OBJECT SPACE TO UNIVERSE SPACE******/ glm::mat4 Scale = glm::mat4(2.0); Scale[3].w = 1.0; glm::mat4 Trans = glm::mat4(1.0); glm::vec4 v(1.0,1.0, 1.0, 1.0); Trans[3] = v; glm::mat4 Rotate = glm::mat4(1.0); Rotate[0].x = cos(angle +=1 * PI/180.0); Rotate[2].x = sin(angle +=1 * PI/180.0); Rotate[0].z = - sin(angle +=1 * PI/180.0); Rotate[2].z = cos(angle +=1 * PI/180.0); Rotate[3].w = 1.0; glm::mat4 M_Model = Rotate * Scale; /******OBJECT SPACE TO UNIVERSE SPACE******/ /******UNIVERSE SPACE TO CAMERA SPACE******/ glm::vec3 camera_pos(0.0,0.0,5.0); glm::vec3 look_at(0.0,0.0,0.0); glm::vec3 camera_up(0.0,1.0,0.0); glm::vec3 camera_dir = look_at - camera_pos; glm::vec3 z_camera = -normalize(camera_dir); glm::vec3 x_camera = normalize(cross(camera_up, z_camera)); glm::vec3 y_camera = normalize(cross(z_camera, x_camera)); glm::vec4 homog(0.0,0.0,0.0,1.0); glm::mat4 B = glm::mat4(1.0); B[0]= glm::vec4 (x_camera,0.0); B[1]= glm::vec4 (y_camera,0.0); B[2]= glm::vec4 (z_camera,0.0); B[3]=homog; glm::mat4 trans = glm::mat4(1.0); trans[3] = glm::vec4 (-camera_pos, 1.0); glm::mat4 M_View = transpose(B) * trans; glm::mat4 Model_View = M_View * M_Model; /******UNIVERSE SPACE TO CAMERA SPACE******/ /******CAMERA SPACE TO PROJECTION SPACE (CLIPPING)******/ double d=1.0; glm::mat4 M_Projection = glm::mat4(1.0); M_Projection[2] = glm::vec4(0.0, 0.0, 1.0, -1.0/d); M_Projection[3] = glm::vec4(0.0, 0.0, d, 0.0); glm::mat4 M_ModelViewProjection = M_Projection * Model_View; /******CAMERA SPACE TO PROJECTION SPACE (CLIPPING)******/ /******PROJECTION SPACE (CLIPPING) TO CANONICAL SPACE******/ //std::cout<<"PRINTING"<<std::endl; for (int i = 0; i < objData->vertexCount; ++i) { vertex_list[i]=M_ModelViewProjection*vertex_list[i]; vertex_list[i].x=vertex_list[i].x/vertex_list[i].w; vertex_list[i].y=vertex_list[i].y/vertex_list[i].w; vertex_list[i].z=vertex_list[i].z/vertex_list[i].w; vertex_list[i].w=vertex_list[i].w/vertex_list[i].w; } /******PROJECTION SPACE (CLIPPING) TO CANONICAL SPACE******/ /******CANONICAL SPACE TO SCREEN SPACE******/ glm::mat4 Translation_Screen = glm::mat4(1.0); Translation_Screen[3] = glm::vec4((IMAGE_WIDTH -1)/2, (IMAGE_HEIGHT -1)/2, 0.0, 1.0); glm::mat4 Scale_Screen = glm::mat4(1.0); Scale_Screen[0].x = IMAGE_WIDTH/2; Scale_Screen[1].y = IMAGE_HEIGHT/2; glm::mat4 InvertY_Screen = glm::mat4(1.0); InvertY_Screen[1].y = -1.0; glm::mat4 Final_Matrix = glm::mat4(1.0); //Final_Matrix = InvertY_Screen * Scale_Screen * Translation_Screen; Final_Matrix = Translation_Screen * Scale_Screen * InvertY_Screen; //PrintMatrix(Final_Matrix); for (int i = 0; i < objData->vertexCount; ++i) { vertex_list[i] = Final_Matrix * vertex_list[i]; //PrintVec4(vertex_list[i]); } /******CANONICAL SPACE TO SCREEN SPACE******/ //std::cout<<"object vertex list"<<std::endl; for (int i = 0; i < objData->vertexCount; ++i) { Vertex tmp; tmp.setX(round(vertex_list[i].x)); tmp.setY(round(vertex_list[i].y)); tmp.setZ(round(vertex_list[i].z)); tmp.setW(round(vertex_list[i].w)); my_list.push_back(tmp); } for (int i = 0; i < objData->faceCount; ++i) { faces = objData->faceList[i]; my_list[faces->vertex_index[0]].DrawTriangle(my_list[faces->vertex_index[1]], my_list[faces->vertex_index[2]]); } }
//------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, g_winSz[0], g_winSz[1]); //SwapBuffers( g_hDC ); //return; // // setup the block1 with base matrices // // g_transfBlock1.m4_Proj already done vec3 up(0,1,0); look_at(g_transfBlock1.m4_View, g_camera.curEyePos, g_camera.curFocusPos, up); //g_transfBlock1.m4_ViewIT = ...todo g_transfBlock1.m4_ViewProj = g_transfBlock1.m4_Proj * g_transfBlock1.m4_View; g_transfBlock1.eyePos = g_camera.curEyePos; // copy the block to OGL if(fx_transfBlock1) { void* p; fx_transfBlock1->mapBuffer(&p); memcpy(p, &g_transfBlock1, sizeof(transfBlock1)); fx_transfBlock1->unmapBuffer(); } //----------------------------------------------------------------- // // Render a basic floor // //glBeginQuery(GL_TIME_ELAPSED, timerQueries[tqOffset]); #define U 1.0f #define DU 0.1f struct Grid { Grid() { Elts = 0; for(float i=-U; i<=(U+DU); i+=DU) { vtx[Elts++] = vec3(-U, 0, i); vtx[Elts++] = vec3( U, 0, i); vtx[Elts++] = vec3(i, 0,-U); vtx[Elts++] = vec3(i, 0, U); } glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*(10*10+2), vtx[0].vec_array, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } int Elts; GLuint vbo; vec3 vtx[10*10+2]; }; static Grid sgrid; if(fx_TechFloor) { fx_pass = fx_TechFloor->getPass(0); fx_pass->execute(); } glEnableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); glDisableVertexAttribArray(4); glBindBuffer(GL_ARRAY_BUFFER, sgrid.vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glDrawArrays(GL_LINES, 0, sgrid.Elts); glDisableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); if(fx_pass) fx_pass->unbindProgram(); fx_pass = NULL; //glEndQuery(GL_TIME_ELAPSED); // // Mesh rendering // //glBeginQuery(GL_TIME_ELAPSED, timerQueries[tqOffset+1]); if(!meshFile) { #ifdef NOGLUT SwapBuffers( g_hDC ); #else glutSwapBuffers(); #endif return; } // // default values for second block made of World... // mat4 m4_world1; g_transfBlock2.m4_World.identity(); g_transfBlock2.m4_WorldView = g_transfBlock1.m4_View * g_transfBlock2.m4_World; g_transfBlock2.m4_WorldViewProj = g_transfBlock1.m4_Proj * g_transfBlock2.m4_WorldView; mat4 WI; invert(WI, g_transfBlock2.m4_World); transpose(g_transfBlock2.m4_WorldIT, WI); if(fx_transfBlock2) { #ifdef USECSTBUFUNIFORMS // we use setXXX() for constant buffer's uniforms fx_m4_World->setMatrix4f(g_transfBlock2.m4_World.mat_array); fx_m4_WorldIT->setMatrix4f(g_transfBlock2.m4_WorldIT.mat_array); fx_m4_WorldView->setMatrix4f(g_transfBlock2.m4_WorldView.mat_array); fx_m4_WorldViewProj->setMatrix4f(g_transfBlock2.m4_WorldViewProj.mat_array); // we dont need this update call: the Pass::execute() will take care of it if not done //fx_transfBlock2->update(); no need #else void* p; fx_transfBlock2->mapBuffer(&p); memcpy(p, &g_transfBlock2, sizeof(transfBlock2)); fx_transfBlock2->unmapBuffer(); #endif } nvFX::PassInfo passInfo; // structure in which many things are returned by execute() if(fx_Tech) { fx_pass = fx_Tech->getPass(0); fx_pass->execute(&passInfo); } else { glClearColor(1.0,0,0,0.0); } for(int i=0; i< meshFile->pMeshes->n; i++) { bk3d::Mesh *pMesh = meshFile->pMeshes->p[i]; // case where the mesh references a transformation // the absolute value must be available by default // if more than one transf, skip it : this might be a list of skeleton transformations if(pMesh->pTransforms && pMesh->pTransforms->n == 1) { g_transfBlock2.m4_World = mat4(pMesh->pTransforms->p[0]->MatrixAbs()); g_transfBlock2.m4_WorldView = g_transfBlock1.m4_View * g_transfBlock2.m4_World; g_transfBlock2.m4_WorldViewProj = g_transfBlock1.m4_Proj * g_transfBlock2.m4_WorldView; mat4 WI; invert(WI, g_transfBlock2.m4_World); transpose(g_transfBlock2.m4_WorldIT, WI); if(fx_transfBlock2) { #ifdef USECSTBUFUNIFORMS fx_m4_World->setMatrix4f(g_transfBlock2.m4_World.mat_array); fx_m4_WorldIT->setMatrix4f(g_transfBlock2.m4_WorldIT.mat_array); fx_m4_WorldView->setMatrix4f(g_transfBlock2.m4_WorldView.mat_array); fx_m4_WorldViewProj->setMatrix4f(g_transfBlock2.m4_WorldViewProj.mat_array); // Because we are AFTER the Pass::execute(), we must make sure that the constant buffer // gets updated as soon as we changed all the uniforms we wanted to change fx_transfBlock2->update(); #else void* p; fx_transfBlock2->mapBuffer(&p); memcpy(p, &g_transfBlock2, sizeof(transfBlock2)); fx_transfBlock2->unmapBuffer(); #endif } } // // let's make it very simple : each mesh attribute is *supposed* to match // the attribute Id of the effect. In real, meshes might not always match // but this is totally arbitrary... // we assume the mesh got baked as follow: // 0: would be pos; 1: normal; 2: TC; 3 and 4: Tan Binorm // int j = 0; for(int k=0; k<pMesh->pSlots->n;k++) { bk3d::Slot* pSlot = pMesh->pSlots->p[k]; glBindBuffer(GL_ARRAY_BUFFER, pSlot->userData); // assign buffers for(int l=0; l<pSlot->pAttributes->n; l++) { glEnableVertexAttribArray(j); glVertexAttribPointer(j, pSlot->pAttributes->p[l].p->numComp, pSlot->pAttributes->p[l].p->formatGL, GL_FALSE, pSlot->pAttributes->p[l].p->strideBytes, (void*)pSlot->pAttributes->p[l].p->dataOffsetBytes); j++; } } glBindBuffer(GL_ARRAY_BUFFER, 0); int MaxAttr = 16; //glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &MaxAttr); for(; j<MaxAttr;j++) glDisableVertexAttribArray(j); for(int pg=0; pg<pMesh->pPrimGroups->n; pg++) { bk3d::PrimGroup* pPG = pMesh->pPrimGroups->p[pg]; //if( ( (pPG->topologyGL == GL_LINES) // ||(pPG->topologyGL == GL_LINE_LOOP) // ||(pPG->topologyGL == GL_LINE_STRIP))) //{ } // case where the Primitive group references a transformation // the absolute value must be available by default if(pPG->pTransforms && pPG->pTransforms->n > 0) { g_transfBlock2.m4_World = mat4(pPG->pTransforms->p[0]->MatrixAbs()); g_transfBlock2.m4_WorldView = g_transfBlock1.m4_View * g_transfBlock2.m4_World; g_transfBlock2.m4_WorldViewProj = g_transfBlock1.m4_Proj * g_transfBlock2.m4_WorldView; //g_transfBlock2.m4_WorldIT = ... todo; if(fx_transfBlock2) { #ifdef USECSTBUFUNIFORMS fx_m4_World->setMatrix4f(g_transfBlock2.m4_World.mat_array); fx_m4_WorldView->setMatrix4f(g_transfBlock2.m4_WorldView.mat_array); fx_m4_WorldViewProj->setMatrix4f(g_transfBlock2.m4_WorldViewProj.mat_array); // Because we are AFTER the Pass::execute(), we must make sure that the constant buffer // gets updated as soon as we changed all the uniforms we wanted to change fx_transfBlock2->update(); #else void* p; fx_transfBlock2->mapBuffer(&p); memcpy(p, &g_transfBlock2, sizeof(transfBlock2)); fx_transfBlock2->unmapBuffer(); #endif } } bk3d::Material *pMat = pPG->pMaterial; if(pMat && g_bUseMaterial && fx_materialBlock) { MaterialBlock* p; fx_materialBlock->mapBuffer((void**)&p); // small issue with original modell (has a black material by default...) if(pMat->Diffuse()[0]==0.0==pMat->Diffuse()[1]==pMat->Diffuse()[2]) pMat->Diffuse()[0]=pMat->Diffuse()[1]=pMat->Diffuse()[2]= 0.7f; // simply copy of the data as they are in the original model memory int sz = sizeof(MaterialBlock); memcpy(p, pMat->Diffuse(), sz); fx_materialBlock->unmapBuffer(); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, (long)pPG->userPtr); // arbitrarily stating that (passInfo.renderingGroup == 3) means we need to feed // the GPU with patches, instead of regular primitives // assuming here that we are dealing only with triangles if(pPG->topologyGL == GL_TRIANGLES) { if(passInfo.renderingGroup == 3) glPatchParameteri(GL_PATCH_VERTICES, 3); glDrawElements( (passInfo.renderingGroup == 3) ? GL_PATCHES : GL_TRIANGLES, pPG->indexCount, pPG->indexFormatGL, (void*)pPG->indexArrayByteOffset);// pIndexBufferData); } } } if(fx_pass) fx_pass->unbindProgram(); fx_pass = NULL; //glEndQuery(GL_TIME_ELAPSED); #ifdef NOGLUT SwapBuffers( g_hDC ); #else glutSwapBuffers(); #endif // // Timer Query results // //tqOffset = tqOffset ? 0 : 2; // alternate between 2 groups //if(tqStart) // special case of the first render // tqStart = false; //else //{ // int available = 0; // while (!available) // { // glGetQueryObjectiv(timerQueries[tqOffset+1], GL_QUERY_RESULT_AVAILABLE, &available); // } // GLuint64 timeElapsed; // for (int i = 0; i < 2; i++) // { // // See how much time the rendering of object i took in nanoseconds. // glGetQueryObjectui64v(timerQueries[tqOffset+i], GL_QUERY_RESULT, &timeElapsed); // } //} }
//-------------------------------------------------------------------------------- // follow the target as near as possible //-------------------------------------------------------------------------------- bool zz_camera_follow::update_lookmode (float follow_yaw_last) { bool move_camera; // distance between last_target and current target position float target_diff = last_.target_pos.distance(final_.target_pos); // distance between camera and current target float target_dist = (target_) ? distance(target_) : get_position().distance(vec3_null); // update by camera-target difference // 1. we start moving camera position if the target_diff reaches a certain amount. // 2. we stop moving camera position if the target_diff is too small. if (now_following_) { // if we started moving camera position. if (target_diff > MIN_DISTANCE_THRESHOLD) { // now moving move_camera = true; // should move } else { // we are already very close to each other now_following_ = false; // quit following mode move_camera = true; // but keep in camera moving state for now } } else if (target_diff > MAX_DISTANCE_THRESHOLD) { // we should start moving the camera position now. now_following_ = true; move_camera = true; } else { // we do not need to move the camera position move_camera = false; } // force moving the camera for test if (!znzin->get_use_time_weight()) move_camera = true; if (move_camera) { // if we should move camera and target vec3 displacement; float damp = (target_diff / MAX_DISTANCE_THRESHOLD); // get target displacement by last and current displacement = .5f*time_weight_*(final_.target_pos - last_.target_pos); // .5f to make slower than 1.0f // update last_target_pos last_.target_pos += displacement; move(displacement); } //camera_dir = target_->get_position() - this->get_eye(); // update camera_dir for later use in update() final_.camera_dir = last_.target_pos - get_eye(); // recalc yaw, because eye position was changed in update_lookmode() // and, we need the difference between yaw and yaw_last float yaw_diff = final_.yaw - last_.yaw; current_.yaw = calc_yaw(); final_.yaw = current_.yaw + yaw_diff; // and apply new_value current_.yaw += time_weight_*(final_.yaw - current_.yaw); apply_yaw(final_.camera_dir, current_.yaw, final_.target_dir); // save last_camera_dir(non-pitched) for back-mode last_.camera_dir = final_.camera_dir; // apply pitch apply_pitch(final_.camera_dir, current_.pitch); final_.camera_pos = last_.target_pos - current_.distance * final_.camera_dir; look_at(final_.camera_pos, last_.target_pos, vec3(0, 0, 1)); last_.camera_pos = final_.camera_pos; // for back-mode return move_camera; }
camera::camera(camera_properties properties) : properties_(properties) { set_position(properties.eye[0], properties.eye[1], properties.eye[2]); look_at(properties.look_at[0], properties.look_at[1], properties.look_at[2]); }
int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint shader_programme; GLuint vao; // // Start OpenGL using helper libraries // -------------------------------------------------------------------------- if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } // change to 3.2 if on Apple OS X glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint (GLFW_SAMPLES, msaa); window = glfwCreateWindow (gl_width, gl_height, "Textured Mesh", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: opening OS window\n"); return 1; } glfwMakeContextCurrent (window); glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); int point_count = 0; // // Set up vertex buffers and vertex array object // -------------------------------------------------------------------------- { GLfloat* vp = NULL; // array of vertex points GLfloat* vn = NULL; // array of vertex normals (we haven't used these yet) GLfloat* vt = NULL; // array of texture coordinates (or these) //assert (load_obj_file ("cube.obj", vp, vt, vn, point_count)); assert (load_obj_file ("monkey.obj", vp, vt, vn, point_count)); GLuint points_vbo, texcoord_vbo, normal_vbo; glGenBuffers (1, &points_vbo); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 3 * point_count, vp, GL_STATIC_DRAW); glGenBuffers (1, &texcoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 2 * point_count, vt, GL_STATIC_DRAW); glGenBuffers (1, &normal_vbo); glBindBuffer (GL_ARRAY_BUFFER, normal_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (float) * 3 * point_count, vn, GL_STATIC_DRAW); glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); glBindBuffer (GL_ARRAY_BUFFER, texcoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (2); glBindBuffer (GL_ARRAY_BUFFER, normal_vbo); glVertexAttribPointer (2, 3, GL_FLOAT, GL_FALSE, 0, NULL); free (vp); free (vn); free (vt); } // // Load shaders from files // -------------------------------------------------------------------------- { char* vertex_shader_str; char* fragment_shader_str; // allocate some memory to store shader strings vertex_shader_str = (char*)malloc (81920); fragment_shader_str = (char*)malloc (81920); // load shader strings from text files assert (parse_file_into_str ("teapot.vert", vertex_shader_str, 81920)); assert (parse_file_into_str ("teapot.frag", fragment_shader_str, 81920)); GLuint vs, fs; vs = glCreateShader (GL_VERTEX_SHADER); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (vs, 1, (const char**)&vertex_shader_str, NULL); glShaderSource (fs, 1, (const char**)&fragment_shader_str, NULL); // free memory free (vertex_shader_str); free (fragment_shader_str); int params = -1; glCompileShader (vs); glGetShaderiv (vs, GL_COMPILE_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: GL shader index %i (teapot.vert) did not compile\n", vs); int max_length = 2048; int actual_length = 0; char log[2048]; glGetShaderInfoLog (vs, max_length, &actual_length, log); printf ("shader info log for GL index %u\n%s\n", vs, log); } glCompileShader (fs); glGetShaderiv (fs, GL_COMPILE_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: GL shader index %i (teapot.frag) did not compile\n", fs); int max_length = 2048; int actual_length = 0; char log[2048]; glGetShaderInfoLog (fs, max_length, &actual_length, log); printf ("shader info log for GL index %u\n%s\n", vs, log); } shader_programme = glCreateProgram (); glAttachShader (shader_programme, fs); glAttachShader (shader_programme, vs); glBindAttribLocation (shader_programme, 0, "vp"); glBindAttribLocation (shader_programme, 1, "vt"); glBindAttribLocation (shader_programme, 2, "vn"); glLinkProgram (shader_programme); glGetProgramiv (shader_programme, GL_LINK_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: could not link shader programme GL index %u\n", shader_programme); int max_length = 2048; int actual_length = 0; char log[2048]; glGetProgramInfoLog (shader_programme, max_length, &actual_length, log); printf ("program info log for GL index %u\n%s\n", shader_programme, log); } /* TODO NOTE: you should check for errors and print logs after compiling and also linking shaders */ } // // Create some matrices // -------------------------------------------------------------------------- mat4 M, V, P; M = identity_mat4 ();//scale (identity_mat4 (), vec3 (0.05, 0.05, 0.05)); vec3 cam_pos (0.0, 5.0, 5.0); vec3 targ_pos (0.0, 0.0, 0.0); vec3 up = normalise (vec3 (0.0, 1.0, -1.0)); V = look_at (cam_pos, targ_pos, up); P = perspective (67.0f, (float)gl_width / (float)gl_height, 0.1, 10.0); int M_loc = glGetUniformLocation (shader_programme, "M"); int V_loc = glGetUniformLocation (shader_programme, "V"); int P_loc = glGetUniformLocation (shader_programme, "P"); int ol_loc = glGetUniformLocation (shader_programme, "ol_mode"); int sm_loc = glGetUniformLocation (shader_programme, "sm_shaded"); // send matrix values to shader immediately glUseProgram (shader_programme); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glUniformMatrix4fv (V_loc, 1, GL_FALSE, V.m); glUniformMatrix4fv (P_loc, 1, GL_FALSE, P.m); glUniform1f (ol_loc, 0.0f); glUniform1f (sm_loc, 0.0f); // // Start rendering // -------------------------------------------------------------------------- // tell GL to only draw onto a pixel if the fragment is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" glDepthFunc (GL_LESS); // depth-testing is to use a "less than" function glEnable (GL_CULL_FACE); // enable culling of faces glCullFace (GL_BACK); glFrontFace (GL_CCW); glClearColor (0.04, 0.04, 0.75, 1.0); bool multi_pass = true; GLuint fb, c_tex, d_tex;; { // fb glGenFramebuffers (1, &fb); glBindFramebuffer (GL_FRAMEBUFFER, fb); glGenTextures (1, &c_tex); glGenTextures (1, &d_tex); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, c_tex); glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, c_tex, 0); glBindTexture (GL_TEXTURE_2D, d_tex); glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, gl_width, gl_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, d_tex, 0); glBindFramebuffer (GL_FRAMEBUFFER, 0); } GLuint quad_vao; { float quad_pts[] = {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0}; GLuint quad_vbo; glGenBuffers (1, &quad_vbo); glGenVertexArrays (1, &quad_vao); glBindVertexArray (quad_vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, quad_vbo); glBufferData (GL_ARRAY_BUFFER, 8 * sizeof (float), quad_pts, GL_STATIC_DRAW); glVertexAttribPointer (0, 2, GL_FLOAT, GL_FALSE, 0, NULL); } GLuint post_sp; { char* vertex_shader_str; char* fragment_shader_str; // allocate some memory to store shader strings vertex_shader_str = (char*)malloc (81920); fragment_shader_str = (char*)malloc (81920); // load shader strings from text files assert (parse_file_into_str ("post.vert", vertex_shader_str, 81920)); assert (parse_file_into_str ("post.frag", fragment_shader_str, 81920)); GLuint vs, fs; vs = glCreateShader (GL_VERTEX_SHADER); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (vs, 1, (const char**)&vertex_shader_str, NULL); glShaderSource (fs, 1, (const char**)&fragment_shader_str, NULL); // free memory free (vertex_shader_str); free (fragment_shader_str); int params = -1; glCompileShader (vs); glGetShaderiv (vs, GL_COMPILE_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: GL shader index %i (post.vert) did not compile\n", vs); int max_length = 2048; int actual_length = 0; char log[2048]; glGetShaderInfoLog (vs, max_length, &actual_length, log); printf ("shader info log for GL index %u\n%s\n", vs, log); } glCompileShader (fs); glGetShaderiv (fs, GL_COMPILE_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: GL shader index %i (post.frag) did not compile\n", fs); int max_length = 2048; int actual_length = 0; char log[2048]; glGetShaderInfoLog (fs, max_length, &actual_length, log); printf ("shader info log for GL index %u\n%s\n", vs, log); } post_sp = glCreateProgram (); glAttachShader (post_sp, fs); glAttachShader (post_sp, vs); glBindAttribLocation (post_sp, 0, "vp"); glLinkProgram (post_sp); glGetProgramiv (post_sp, GL_LINK_STATUS, ¶ms); if (GL_TRUE != params) { printf ("ERROR: could not link shader programme GL index %u\n", post_sp); int max_length = 2048; int actual_length = 0; char log[2048]; glGetProgramInfoLog (post_sp, max_length, &actual_length, log); printf ("program info log for GL index %u\n%s\n", post_sp, log); } } double a = 0.0f; double prev = glfwGetTime (); while (!glfwWindowShouldClose (window)) { if (multi_pass) { glBindFramebuffer (GL_FRAMEBUFFER, fb); } glViewport (0, 0, gl_width, gl_height); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, 0); double curr = glfwGetTime (); double elapsed = curr - prev; prev = curr; glUseProgram (shader_programme); glBindVertexArray (vao); a += elapsed * 50.0f; //float ang = (float)sin (a); M = rotate_y_deg (identity_mat4 (), a); glUniformMatrix4fv (M_loc, 1, GL_FALSE, M.m); glUniform1f (sm_loc, 1.0f); // smooth shaded or not (exception is flat-shaded, they might not be great // if non-cube anyway due to scaling) if (!multi_pass) { glFrontFace (GL_CW); glUniform1f (ol_loc, 1.0f); glDrawArrays (GL_TRIANGLES, 0, point_count); } glFrontFace (GL_CCW); glUniform1f (ol_loc, 0.0f); glDrawArrays (GL_TRIANGLES, 0, point_count); /* this just updates window events and keyboard input events (not used yet) */ if (multi_pass) { glFlush (); glFinish (); glBindFramebuffer (GL_FRAMEBUFFER, 0); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport (0, 0, gl_width, gl_height); glUseProgram (post_sp); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, d_tex); glBindVertexArray (quad_vao); glDrawArrays (GL_TRIANGLE_STRIP, 0, 4); } glfwPollEvents (); glfwSwapBuffers (window); } return 0; }
void PlayerLocomotion::FaceTowards(const Vector& vec) { Vector look_at(vec.x, vec.y, this->GetBot()->GetEntity()->EyePosition().z); this->GetBot()->GetBodyInterface()->AimHeadTowards(look_at, IBody::LookAtPriorityType::BORING, 0.1f, nullptr, "Body facing"); }
camera_callable::camera_callable(const variant& node) : fov_(45.0f), horizontal_angle_(float(M_PI)), vertical_angle_(0.0f), speed_(0.1f), mouse_speed_(0.005f), near_clip_(0.1f), far_clip_(300.0f), mode_(MODE_AUTO), type_(PERSPECTIVE_CAMERA), ortho_left_(0), ortho_bottom_(0), ortho_top_(preferences::actual_screen_height()), ortho_right_(preferences::actual_screen_width()) { position_ = glm::vec3(0.0f, 0.0f, 10.0f); if(node.has_key("fov")) { fov_ = std::min(90.0f, std::max(15.0f, float(node["fov"].as_decimal().as_float()))); } if(node.has_key("horizontal_angle")) { horizontal_angle_ = float(node["horizontal_angle"].as_decimal().as_float()); } if(node.has_key("vertical_angle")) { vertical_angle_ = float(node["vertical_angle"].as_decimal().as_float()); } if(node.has_key("speed")) { speed_ = float(node["speed"].as_decimal().as_float()); } if(node.has_key("mouse_speed")) { mouse_speed_ = float(node["mouse_speed"].as_decimal().as_float()); } if(node.has_key("aspect")) { aspect_ = float(node["aspect"].as_decimal().as_float()); } else { aspect_ = float(preferences::actual_screen_width())/float(preferences::actual_screen_height()); } if(node.has_key("position")) { ASSERT_LOG(node["position"].is_list() && node["position"].num_elements() == 3, "position must be a list of 3 decimals."); position_ = glm::vec3(float(node["position"][0].as_decimal().as_float()), float(node["position"][1].as_decimal().as_float()), float(node["position"][2].as_decimal().as_float())); } if(node.has_key("type")) { if(node["type"].as_string() == "orthogonal") { type_ = ORTHOGONAL_CAMERA; } } if(node.has_key("ortho_window")) { ASSERT_LOG(node["ortho_window"].is_list() && node["ortho_window"].num_elements() == 4, "Attribute 'ortho_window' must be a 4 element list. left,right,top,bottom"); ortho_left_ = node["ortho_window"][0].as_int(); ortho_right_ = node["ortho_window"][1].as_int(); ortho_top_ = node["ortho_window"][2].as_int(); ortho_bottom_ = node["ortho_window"][3].as_int(); } // If lookat key is specified it overrides the normal compute. if(node.has_key("lookat")) { const variant& la = node["lookat"]; ASSERT_LOG(la.has_key("position") && la.has_key("target") && la.has_key("up"), "lookat must be a map having 'position', 'target' and 'up' as tuples"); glm::vec3 position(la["position"][0].as_decimal().as_float(), la["position"][1].as_decimal().as_float(), la["position"][2].as_decimal().as_float()); glm::vec3 target(la["target"][0].as_decimal().as_float(), la["target"][1].as_decimal().as_float(), la["target"][2].as_decimal().as_float()); glm::vec3 up(la["up"][0].as_decimal().as_float(), la["up"][1].as_decimal().as_float(), la["up"][2].as_decimal().as_float()); look_at(position, target, up); mode_ = MODE_MANUAL; } else { compute_view(); } compute_projection(); }
Camera::Camera(YAML::Node& c, BaseElement* p) : core::BaseElement(c, p) { look_at((Vector3f() << 0,1,1).finished(), (Vector3f() << 0,1,0).finished(), Vector3f::UnitY()); }
//------------------------------------------------------------------------------ void initGL() { //-------------------------------------------------------------------------- #ifdef USESVCUI LOGI("adding more UI controls...\n"); class ControlsEvents : public IEventsWnd { void ScalarChanged(IControlScalar *pWin, float &v, float prev) { g_renderCnt++; }; void Button(IWindow *pWin, int pressed) { size_t tag; pWin->GetUserData(&tag); keyboard((unsigned char)tag, 0,0); }; void ToolbarChanged(IControlToolbar *pWin, int selecteditem, int prev) { int states; size_t tag; int ddsidx; pWin->GetItemInfos(selecteditem, states, tag, NULL, 0, NULL, 0, ddsidx); keyboard((unsigned char)tag, 0,0); } void CheckBoxChanged(IControlScalar *pWin, bool &value, bool prev) { g_renderCnt++; } void ComboSelectionChanged(IControlCombo *pWin, unsigned int selectedidx) { if(!strcmp(pWin->GetID(), "SCTECH")) { fx_TechScene = fx_EffectScene->findTechnique(selectedidx); } else if(!strcmp(pWin->GetID(), "MTECH")) { // ... } g_renderCnt++; }; }; static ControlsEvents controlsEvents; //--------------------------------------------------------------------------- if(g_pWinHandler) { g_pControls = g_pWinHandler->CreateWindowFolding("CTRLS", "Controls"); g_pComboTech = g_pWinHandler->CreateCtrlCombo("SCTECH", "Scene Tech", g_pControls); g_pWinHandler->CreateCtrlButton("LM", "Reload Materials", g_pControls)->SetUserData(NULL, 'm'); g_pWinHandler->CreateCtrlButton("LS", "Reload Scene Effect", g_pControls)->SetUserData(NULL, 's'); g_pWinHandler->VariableBind(g_pWinHandler->CreateCtrlCheck("RT", "Render Realtime", g_pControls), &g_realtime.bNonStopRendering); g_pControls->SetVisible(1)->SetLocation(g_winSz[0]+16,0)->SetSize(250,g_winSz[1]); // simplest solution: register the whole to one event manager g_pWinHandler->Register(&controlsEvents); } #endif //--------------------------------------------------------------------------- glewInit(); glClearColor(0.1f, 0.1f, 0.2f, 1.0f); // Bind only one vao glGenVertexArrays(1, &g_vao); glBindVertexArray(g_vao); // // Effects // nvFX::setErrorCallback(errorCallbackFunc); nvFX::setMessageCallback(errorCallbackFunc); nvFX::setIncludeCallback(includeCallbackFunc); loadSceneEffect(); loadModel(); LOGI("Pg Up/Down : zoom\n"); LOGI("Arrows: rotate the camera\n"); #ifdef NOGLUT LOGI("Ctrl + Arrows: pan the camera taget\n"); #endif LOGI("Mouse + left button: rotate the camera\n"); LOGI("Mouse + middle button: Pan the camera target\n"); LOGI("Mouse + right button: rotate Horizontally and change camera distance\n"); LOGI("space: toggle redraw on every frame\n"); LOGI("1,2,3 : switch between scene techniques\n"); LOGI("m/s : reload material/scene effect\n"); // // Timer Query // glGenQueries(4, timerQueries); // // Light... nothing special: it's a static light for this sample // perspective(g_lightProjection, 35.0f, 1.0f, 0.01f, 10.0f); look_at(g_lightView, g_lightPos, g_lightTarget, up); g_lightViewProj = g_lightProjection * g_lightView; mat4 offsetMat = mat4( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f); g_lightViewProjScaleBias = offsetMat * g_lightViewProj; }
//------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // // SCENE-LEVEL TEST // nvFX::PassInfo pr; int np = fx_TechScene->getNumPasses(); for(int i=0; i<np; i++) { nvFX::IPass* scenePass = fx_TechScene->getPass(i); // FIXME: viewport size depends on the render-target that was defined in nvFX // but I don't remember how to setup the size from nvFX when the target depends on the window of the sample // so, setting it by default to this window size is a temporary fix glViewport(0, 0, g_winSz[0], g_winSz[1]); scenePass->execute(&pr); switch(pr.renderingMode) { case nvFX::RENDER_SCENEGRAPH_SHADED: look_at(g_transfBlock1.m4_View, g_camera.curEyePos, g_camera.curFocusPos, up); g_transfBlock1.m4_Proj = g_cameraProj; g_transfBlock1.m4_ViewProj = g_transfBlock1.m4_Proj * g_transfBlock1.m4_View; g_transfBlock1.eyePos = g_camera.curEyePos; g_transfBlock1.m4_shadowMatrix = g_lightViewProjScaleBias; // needed here to find where we are in the shadowmap // copy the block to OGL if(fx_transfBlock1) { void* p; fx_transfBlock1->mapBuffer(&p); memcpy(p, &g_transfBlock1, sizeof(transfBlock1)); fx_transfBlock1->unmapBuffer(); } displayScene(pr); break; // NOTE: Let's assume for now that we do use RENDER_SCENEGRAPH_NOSHADING for the shadowmap view case nvFX::RENDER_SHADOWMAP: g_transfBlock1.m4_Proj = g_lightProjection; g_transfBlock1.m4_View = g_lightView; g_transfBlock1.m4_ViewProj = g_lightViewProj; g_transfBlock1.eyePos = g_lightPos; // useless for lightview rendering // copy the block to OGL if(fx_transfBlock1) { void* p; fx_transfBlock1->mapBuffer(&p); memcpy(p, &g_transfBlock1, sizeof(transfBlock1)); fx_transfBlock1->unmapBuffer(); } displayScene(pr); break; default: break; } } #ifdef NOGLUT SwapBuffers( g_hDC ); #else glutSwapBuffers(); #endif }
int main () { assert (restart_gl_log ()); assert (start_gl ()); /* set up framebuffer with texture attachment */ assert (init_fb ()); /* load the picking shaders */ g_pick_sp = create_programme_from_files (PICK_VS, PICK_FS); g_pick_unique_id_loc = glGetUniformLocation (g_pick_sp, "unique_id"); g_pick_P_loc = glGetUniformLocation (g_pick_sp, "P"); g_pick_V_loc = glGetUniformLocation (g_pick_sp, "V"); g_pick_M_loc = glGetUniformLocation (g_pick_sp, "M"); assert (g_pick_P_loc > -1); assert (g_pick_V_loc > -1); assert (g_pick_M_loc > -1); /* load a mesh to draw in the main scene */ load_sphere (); GLuint sphere_sp = create_programme_from_files (SPHERE_VS, SPHERE_FS); GLint sphere_P_loc = glGetUniformLocation (sphere_sp, "P"); GLint sphere_V_loc = glGetUniformLocation (sphere_sp, "V"); GLint sphere_M_loc = glGetUniformLocation (sphere_sp, "M"); assert (sphere_P_loc > -1); assert (sphere_V_loc > -1); assert (sphere_M_loc > -1); /* set up view and projection matrices for sphere shader */ mat4 P = perspective ( 67.0f, (float)g_gl_width / (float)g_gl_height, 0.1f, 100.0f); mat4 V = look_at ( vec3 (0.0f, 0.0f, 5.0f), vec3 (0.0f, 0.0f, 0.0f), vec3 (0.0f, 1.0f, 0.0f)); glUseProgram (sphere_sp); glUniformMatrix4fv (sphere_P_loc, 1, GL_FALSE, P.m); glUniformMatrix4fv (sphere_V_loc, 1, GL_FALSE, V.m); glViewport (0, 0, g_gl_width, g_gl_height); while (!glfwWindowShouldClose (g_window)) { _update_fps_counter (g_window); /* bind the 'render to a texture' framebuffer for main scene */ glBindFramebuffer (GL_FRAMEBUFFER, 0); /* clear the framebuffer's colour and depth buffers */ glClearColor (0.2, 0.2, 0.2, 1.0); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render an obj or something glUseProgram (sphere_sp); glBindVertexArray (g_sphere_vao); // model matrices for all 3 spheres mat4 Ms[3]; // first sphere Ms[0] = identity_mat4 (); glUniformMatrix4fv (sphere_M_loc, 1, GL_FALSE, Ms[0].m); glDrawArrays (GL_TRIANGLES, 0, g_sphere_point_count); // 2nd sphere Ms[1] = translate (identity_mat4 (), vec3 (1.0, -1.0, -4.0)); glUniformMatrix4fv (sphere_M_loc, 1, GL_FALSE, Ms[1].m); glDrawArrays (GL_TRIANGLES, 0, g_sphere_point_count); // 3rd sphere Ms[2] = translate (identity_mat4 (), vec3 (-0.50, 2.0, -2.0)); glUniformMatrix4fv (sphere_M_loc, 1, GL_FALSE, Ms[2].m); glDrawArrays (GL_TRIANGLES, 0, g_sphere_point_count); /* bind framebuffer for pick */ draw_picker_colours (P, V, Ms); // flip drawn framebuffer onto the display glfwSwapBuffers (g_window); glfwPollEvents (); if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (g_window, 1); } debug_colours = glfwGetKey (g_window, GLFW_KEY_SPACE); if (glfwGetMouseButton (g_window, 0)) { glBindFramebuffer (GL_FRAMEBUFFER, g_fb); double xpos, ypos; glfwGetCursorPos (g_window, &xpos, &ypos); int mx = (int)xpos; int my = (int)ypos; unsigned char data[4] = {0, 0, 0, 0}; glReadPixels ( mx, g_gl_height - my, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &data); int id = decode_id ((int)data[0], (int)data[1], (int)data[2]); int mid = -1; if (id == 255) { mid = 0; } if (id == 65280) { mid = 1; } if (id == 16711680) { mid = 2; } printf ("%i,%i,%i means -> id was %i, and monkey number is %i\n", data[0], data[1], data[2], id, mid); glBindFramebuffer (GL_FRAMEBUFFER, 0); } } return 0; }